Beispiel #1
0
def updateSharedMemory():
    global sharedMem
    sharedmem = sharedMem.getsharedmem()
    sharedmem.numVehicles = ac.getCarsCount()
    sharedmem.focusVehicle = ac.getFocusedCar()

    #now we'll build the slots, so we later know every single (possible) car
    carIds = range(0, ac.getCarsCount(), 1)
    for carId in carIds:
        #first we'll check wether there is a car for this id; as soon it returns -1
        #it's over
        if str(ac.getCarName(carId)) == '-1':
            break
        else:
            sharedmem.vehicleInfo[carId].carId = carId
            sharedmem.vehicleInfo[carId].driverName = ac.getDriverName(carId).encode('utf-8')
            sharedmem.vehicleInfo[carId].carModel = ac.getCarName(carId).encode('utf-8')
            sharedmem.vehicleInfo[carId].speedMS = ac.getCarState(carId, acsys.CS.SpeedMS)
            sharedmem.vehicleInfo[carId].bestLapMS = ac.getCarState(carId, acsys.CS.BestLap)
            sharedmem.vehicleInfo[carId].lapCount = ac.getCarState(carId, acsys.CS.LapCount)
            sharedmem.vehicleInfo[carId].currentLapInvalid = ac.getCarState(carId, acsys.CS.LapInvalidated)
            sharedmem.vehicleInfo[carId].currentLapTimeMS = ac.getCarState(carId, acsys.CS.LapTime)
            sharedmem.vehicleInfo[carId].lastLapTimeMS = ac.getCarState(carId, acsys.CS.LastLap)
            sharedmem.vehicleInfo[carId].worldPosition = ac.getCarState(carId, acsys.CS.WorldPosition)
            sharedmem.vehicleInfo[carId].isCarInPitline = ac.isCarInPitline(carId)
            sharedmem.vehicleInfo[carId].isCarInPit = ac.isCarInPit(carId)
            sharedmem.vehicleInfo[carId].carLeaderboardPosition = ac.getCarLeaderboardPosition(carId)
            sharedmem.vehicleInfo[carId].carRealTimeLeaderboardPosition = ac.getCarRealTimeLeaderboardPosition(carId)
            sharedmem.vehicleInfo[carId].spLineLength=  ac.getCarState(carId, acsys.CS.NormalizedSplinePosition) 
            sharedmem.vehicleInfo[carId].isConnected = ac.isConnected(carId)
def acUpdate(delta_t):
    global last_calculated, last_posted
    global spinner_calculation_interval, spinner_posting_interval
    global label_names, label_track_progress, label_penalties, label_last_message
    global turn_gen, penalties

    CALCULATION_INTERVAL = ac.getValue(spinner_calculation_interval) / 1000
    POSTING_INTERVAL = ac.getValue(spinner_posting_interval) / 1000

    if (time.clock() - last_calculated) > CALCULATION_INTERVAL:
        last_calculated = time.clock()

        progresses = get_progresses()
        penalties = calculate_penalties(progresses)

        ac.setText(
            label_track_progress, "Track progresses: {}".format(
                [round(float(i), 2) for i in progresses]))
        ac.setText(
            label_penalties, "Penalty percentages: {}".format(
                [round(float(i), 2) for i in penalties]))

    if (time.clock() - last_posted) > POSTING_INTERVAL:
        p_type, target = next(turn_gen)

        if ac.isConnected(target):
            last_posted = time.clock()
            msg = create_msg(p_type, target, penalties)

            ac.sendChatMessage(msg)
            ac.setText(label_last_message,
                       "Last message posted: {}".format(msg))
Beispiel #3
0
    def __get_next_car(self, data, car_id, pitline_validation=False):
        try:
            self.nsp = ac.getCarState(car_id, acsys.CS.NormalizedSplinePosition)
            self.next_car = [car_id, 1]
            for self.iteration in range(32): #max cars
                if ac.isConnected(self.iteration) == 1 and self.iteration != car_id:
                    self.pitline_condition = True
                    if pitline_validation:
                        if data.is_car_in_pitline(self.iteration) == data.is_car_in_pitline(car_id):
                            self.pitline_condition = True
                        else:
                            self.pitline_condition = False

                    if self.pitline_condition:
                        if self.nsp <  ac.getCarState(self.iteration, acsys.CS.NormalizedSplinePosition):
                            self.distance = abs(self.nsp - ac.getCarState(self.iteration, acsys.CS.NormalizedSplinePosition))
                        else:
                            self.distance = 1 - abs(self.nsp - ac.getCarState(self.iteration, acsys.CS.NormalizedSplinePosition))

                        if self.distance < self.next_car[1]:
                            self.next_car = [self.iteration, self.distance]

            return self.next_car[0]
        except Exception as e:
            debug(e)
def get_progresses():
    progs = []
    for i in range(NCARS):
        if ac.isConnected(i):
            lap = ac.getCarState(i, acsys.CS.LapCount)
            spline = ac.getCarState(i, acsys.CS.NormalizedSplinePosition)
            prg = lap + spline
            progs.append(prg)
    return progs
Beispiel #5
0
    def get_tracked_car(self, car=0):
        if car == 0:
            self.car_id = self.__tracked_car_a
        else:
            self.car_id = self.__tracked_car_b

        if ac.isConnected(self.car_id) == 1:
            return self.car_id
        else:
            return 0
Beispiel #6
0
 def getStandingsPosition(self,vehicule):
     #mainly for replay
     standings = []
     for i in range(self.carsCount): 
         bl=ac.getCarState(i,acsys.CS.BestLap)
         if bl > 0  and bool(ac.isConnected(vehicule)):
             standings.append((i,bl))  
     standings = sorted(standings, key=lambda student: student[1]) 
     p=[i for i, v in enumerate(standings) if v[0] == vehicule] 
     if len(p) > 0:
         return p[0]+1
     return 0
 def updateTiming(self):
     """
     Рядовое обновление данных
     """
     for car in self.carList:
         if car is not None:
             postLogMessage('ac.isConnected(' + str(car.carId) + ') : ' +
                            str(ac.isConnected(car.carId)))
             car.connected = ac.isConnected(car.carId) == 1
             if not car.connected:  # отключённые машины не обновляем
                 continue
             # Если количество кругов, пройденных пилотом, в игре больше, чем в структуре car, обновляем данные по кругам
             newLapsCompleted = ac.getCarState(car.carId, acsys.CS.LapCount)
             if car.lapsCompleted < newLapsCompleted:
                 postLogMessage('car' + str(car.carId) +
                                ' per-lap timing update')
                 # Покруговые обновления
                 car.lapsCompleted = newLapsCompleted
                 car.lastLap = ac.getCarState(car.carId, acsys.CS.LastLap)
                 car.bestLap = ac.getCarState(car.carId, acsys.CS.BestLap)
                 car.totalTime += car.lastLap
                 car.lapPostTime = self.session_time
                 car.isFinished = ac.getCarState(car.carId,
                                                 acsys.CS.RaceFinished)
                 # postLogMessage('Per-lap update OK')
             # Постоянные обновления
             # postLogMessage('Per-iterval update')
             car.totalDistance = car.lapsCompleted + ac.getCarState(
                 car.carId, acsys.CS.NormalizedSplinePosition)
             car.isInPitlane = ac.isCarInPitlane(car.carId)
             car.isInPit = ac.isCarInPit(car.carId)
             car.leaderboardPosition = ac.getCarLeaderboardPosition(
                 car.carId)
             car.realTimeLeaderboardPosition = ac.getCarRealTimeLeaderboardPosition(
                 car.carId)
             car.isFinished = ac.getCarState(car.carId,
                                             acsys.CS.RaceFinished)
Beispiel #8
0
    def update(self, delta: float):
        for c in range(0, self._server.cars):
            if ac.isCarInPit(c) or not ac.isConnected(c):
                continue

            lap = ac.getCarState(c, acsys.CS.LapCount)
            pos = ac.getCarState(c, acsys.CS.NormalizedSplinePosition)
            invalid = ac.getCarState(
                c, acsys.CS.LapInvalidated) and self._valid[c]
            sec = int(pos * 3)
            #msec = int(pos * 12)

            if lap != self._lap_index[c]:
                self._valid[c] = True
                self._start_lap_time[c] = time() * 1000
                best_lap = ac.getCarState(c, acsys.CS.BestLap)
                if not invalid and best_lap > 0:
                    if best_lap < self._gb_lap_time:
                        self._gb_lap_time = best_lap
                        self._pb_lap_time[c] = best_lap
                    elif best_lap < self._pb_lap_time[c]:
                        self._pb_lap_time[c] = best_lap

                self._lap_index[c] = lap

            self._current_lap_time[c] = time() * 1000 - self._start_lap_time[c]

            if sec > 0:
                self._current_sector_time[c][sec] = self._current_lap_time[
                    c] - sum(self._current_sector_time[c][:sec])
            else:
                self._current_sector_time[c][sec] = self._current_lap_time[c]

            if sec != self._sector_index[c]:
                last_sec = self._sector_index[c]

                if not invalid and self._current_sector_time[c][last_sec] > 0:
                    if self._current_sector_time[c][
                            last_sec] < self._gb_sector_time[last_sec]:
                        self._gb_sector_time[
                            last_sec] = self._current_sector_time[c][last_sec]
                        self._pb_sector_time[c][
                            last_sec] = self._current_sector_time[c][last_sec]
                    elif self._current_sector_time[c][
                            last_sec] < self._pb_sector_time[c][last_sec]:
                        self._pb_sector_time[c][
                            last_sec] = self._current_sector_time[c][last_sec]

                self._sector_index[c] = sec
Beispiel #9
0
    def get_closest_opponent(self, car_id, interpolation, x, data):
        self.max_cars = 32
        self.nsp = ac.getCarState(car_id, acsys.CS.NormalizedSplinePosition)
        self.next_car = vec(car_id, 1)
        for self.i in range(32): #max cars
            if ac.isConnected(self.i) == 1 and self.i != car_id:
                if data.is_car_in_pitline(car_id) == data.is_car_in_pitline(self.i):
                    self.distance_a = abs(self.nsp - ac.getCarState(self.i, acsys.CS.NormalizedSplinePosition))
                    self.distance_b = 1 - abs(self.nsp - ac.getCarState(self.i, acsys.CS.NormalizedSplinePosition))
                    self.distance = min(self.distance_a, self.distance_b)

                    if self.distance < self.next_car.y:
                        self.next_car = vec(self.i, self.distance)

        return self.next_car.x
Beispiel #10
0
    def calc(self, player):
        if self == player or not ac.isConnected(self.id) or ac.isCarInPitline(
                self.id):
            self.isVisible = False
            return

        # we are visible, so it's worth calculating the car's properties
        self.isVisible = True
        x, y, z = self.calcCar()

        # and add the stuff relative to the driver
        self.relativePositionMeters = euclid.Point2(
            x - player.currentWorldPosition.x,
            z - player.currentWorldPosition.y)
        self.playerDistance = player.currentWorldPosition.distance(
            euclid.Point2(x, z))
Beispiel #11
0
 def get_race_standings_position_in_class(self, identifier):
     if len(self.standings):
         #filter
         standings = []
         for s in self.standings:
             if s[2] == self.current_car_class.value and ac.isConnected(
                     s[0]) > 0:
                 standings.append((s[0], s[1]))
         p = [i for i, v in enumerate(standings) if v[0] == identifier]
         if len(p) > 0:
             if p[0] + 1 > len(standings):
                 return (len(standings), len(standings))
             return (p[0] + 1, len(standings))
     if self.session.value != 2:
         return (ac.getCarLeaderboardPosition(identifier), self.numCars)
     return (ac.getCarRealTimeLeaderboardPosition(identifier) + 1,
             self.numCars)
Beispiel #12
0
def updateSharedMemory():
    global sharedMem
    sharedmem = sharedMem.getsharedmem()
    sharedmem.numVehicles = ac.getCarsCount()
    sharedmem.focusVehicle = ac.getFocusedCar()
    #now we'll build the slots, so we later know every single (possible) car
    carIds = range(0, ac.getCarsCount(), 1)
    for carId in carIds:
        #first we'll check wether there is a car for this id; as soon it returns -1
        #it's over
        if str(ac.getCarName(carId)) == '-1':
            break
        else:
            sharedmem.vehicleInfo[carId].carId = carId
            sharedmem.vehicleInfo[carId].driverName = ac.getDriverName(
                carId).encode('utf-8')
            sharedmem.vehicleInfo[carId].carModel = ac.getCarName(
                carId).encode('utf-8')
            sharedmem.vehicleInfo[carId].speedMS = ac.getCarState(
                carId, acsys.CS.SpeedMS)
            sharedmem.vehicleInfo[carId].bestLapMS = ac.getCarState(
                carId, acsys.CS.BestLap)
            sharedmem.vehicleInfo[carId].lapCount = ac.getCarState(
                carId, acsys.CS.LapCount)
            sharedmem.vehicleInfo[carId].currentLapInvalid = ac.getCarState(
                carId, acsys.CS.LapInvalidated)
            sharedmem.vehicleInfo[carId].currentLapTimeMS = ac.getCarState(
                carId, acsys.CS.LapTime)
            sharedmem.vehicleInfo[carId].lastLapTimeMS = ac.getCarState(
                carId, acsys.CS.LastLap)
            sharedmem.vehicleInfo[carId].worldPosition = ac.getCarState(
                carId, acsys.CS.WorldPosition)
            sharedmem.vehicleInfo[carId].isCarInPitline = ac.isCarInPitline(
                carId)
            sharedmem.vehicleInfo[carId].isCarInPit = ac.isCarInPit(carId)
            sharedmem.vehicleInfo[
                carId].carLeaderboardPosition = ac.getCarLeaderboardPosition(
                    carId)
            sharedmem.vehicleInfo[
                carId].carRealTimeLeaderboardPosition = ac.getCarRealTimeLeaderboardPosition(
                    carId)
            sharedmem.vehicleInfo[carId].spLineLength = ac.getCarState(
                carId, acsys.CS.NormalizedSplinePosition)
            sharedmem.vehicleInfo[carId].isConnected = ac.isConnected(carId)
            sharedmem.vehicleInfo[carId].finishStatus = ac.getCarState(
                carId, acsys.CS.RaceFinished)
Beispiel #13
0
    def get_prev_car(self, car_id):
        try:
            self.max_cars = 32
            self.nsp = ac.getCarState(car_id, acsys.CS.NormalizedSplinePosition)
            self.prev_car = vec(car_id, 1)
            for self.i in range(32): #max cars
                if ac.isConnected(self.i) == 1 and self.i != car_id:
                    if self.nsp > ac.getCarState(self.i, acsys.CS.NormalizedSplinePosition):
                        self.distance = abs(self.nsp - ac.getCarState(self.i, acsys.CS.NormalizedSplinePosition))
                    else:
                        self.distance = 1 - abs(self.nsp - ac.getCarState(self.i, acsys.CS.NormalizedSplinePosition))

                    if self.distance < self.prev_car.y:
                        self.prev_car = vec(self.i, self.distance)

            return self.prev_car.x
        except Exception as e:
            debug(e)
Beispiel #14
0
def build_driver_list():
    """Builds list of cars that drove through joker"""
    global driver_list, polygon

    # Get number of cars
    car_amount = ac.getCarsCount()

    # Iterate through cars
    for i in range(0, car_amount):
        driver_name = ac.getDriverName(i)
        if driver_name not in driver_list:
            inpitbox = ac.isCarInPit(i)
            isconnected = ac.isConnected(i)
            if not inpitbox and isconnected:
                crds = ac.getCarState(i, acsys.CS.WorldPosition)
                inside_joker = inside_polygon(crds[0], crds[2], polygon)
                if inside_joker:
                    driver_list.append(driver_name)
                    lap = ac.getCarState(i, acsys.CS.LapCount)
                    send_chat_message(driver_name, lap)
Beispiel #15
0
    def refresh(self, x, dt, interpolation, main_file):
        try:
            if not self.init:
                self.init = True
                try:
                    self.load(main_file, "init")
                except Exception:
                    pass

            for self.i in range(32): #max_cars
                if ac.isConnected(self.i) == 1:
                    self.update_custom_car_info(interpolation, dt, self.i)

            self.prev_active_cam = self.active_cam
            for self.i in range( self.get_n_cameras() ):
                if not self.mode[self.active_mode][self.i].camera_pit:
                    if x * ac.getTrackLength() < self.get_camera_in(self.i):
                        self.active_cam = self.get_prev_camera(self.i)
                        break
                    else:
                        self.active_cam = self.get_last_camera()

            #pit cameras
            if self.car_is_in_pitline[ac.getFocusedCar()]:
                for self.i in range( self.get_n_cameras() ):
                    if self.mode[self.active_mode][self.i].camera_pit:
                        if x * ac.getTrackLength() < self.get_camera_in(self.i):
                            self.active_cam = self.get_prev_camera(self.i, "pit")
                            break
                        else:
                            self.active_cam = self.get_last_camera("pit")


        except Exception as e:
            debug(e)
            self.active_cam = 0
def acUpdate(deltaT):
    # TIMERS
    global timer0, timer1, timer2

    # VARIABLES
    global totalDrivers
    global drivers
    global fastest_lap

    global race_started, replay_started, quali_started

    global qualify_session_time

    global replay_file
    global replay_data

    # Widgets
    global leaderboardWindow, driverWidget, driverComparisonWidget

    # LABELS
    global leaderboard
    global lapCountTimerLabel, leaderboardBaseLabel, leaderboardInfoBackgroundLabel, leaderboardBackgroundLabel
    global flagLabel

    # ============================
    # UPDATE TIMERS
    timer0 += deltaT
    timer1 += deltaT
    timer2 += deltaT
    # ============================

    # ================================================================
    #                            RACES
    # ================================================================
    if info.graphics.session == 2:

        # 10 times per second
        if timer2 > 0.1:
            timer2 = 0

            # =============================
            # SAVE SPLIT TIMES
            for d in drivers:
                if ac.isConnected(d.id) == 0: continue
                current_split = d.get_split_id(ac.getCarState(d.id, acsys.CS.NormalizedSplinePosition))
                if d.current_split != current_split: # save split time at each split of the track
                    d.split_times[current_split-1] = time.time()
                    d.current_split = current_split

        # 3 times per second
        if timer1 > 0.3:
            # CHECK RACE RESTART
            if race_started and info.graphics.completedLaps == 0 and info.graphics.iCurrentTime == 0:
                race_started = False

            # CHECK RACE START
            if not race_started and info.graphics.iCurrentTime > 0:
                # RESET THINGS
                fastest_lap = MAX_LAP_TIME
                LeaderboardRow.FASTEST_LAP_ID = -1
                for row in leaderboard: # clean the fastest lap marker
                    row.mark_fastest_lap()
                # in case we are coming from a qualify
                ac.setFontColor(lapCountTimerLabel, 0.86, 0.86, 0.86, 1)
                ac.setBackgroundTexture(leaderboardBaseLabel, FC.LEADERBOARD_BASE_RACE)
                ac.setVisible(lapCountTimerLabel, 1)

                race_started = True
                quali_started = False
                for d in drivers:
                    d.starting_position = ac.getCarLeaderboardPosition(d.id)
                    d.tyre = ac.getCarTyreCompound(d.id)
                    d.pits = 0
                replay_file = setup_replay_file(drivers, info.graphics.numberOfLaps) # save starting info on the drivers

            # ============================
            # POSITION UPDATE
            for i in range(totalDrivers):
                pos = ac.getCarRealTimeLeaderboardPosition(i)
                connected = ac.isConnected(i)
                if connected == 0: # mark unconnected drivers
                    leaderboard[pos].mark_out()
                    drivers[i].out = True
                else:
                    leaderboard[pos].mark_in()
                    drivers[i].out = False
                leaderboard[pos].update_name(i)

                # OVERTAKE
                if pos != drivers[i].position: # there was an overtake
                    drivers[i].timer = FC.OVERTAKE_POSITION_LABEL_TIMER # set timer
                    if pos < drivers[i].position:
                        leaderboard[pos].mark_green_position()
                    elif pos > drivers[i].position:
                        leaderboard[pos].mark_red_position()
                elif drivers[i].timer <= 0:
                    leaderboard[pos].mark_white_position()
                else:
                    drivers[i].timer -= timer1
                drivers[i].position = pos
                # END OVERTAKE

            # ============================
            # FASTEST LAP BANNER TIMER
            if fastest_lap_banner.timer > 0:
                fastest_lap_banner.timer -= timer1
                fastest_lap_banner.hide()

            # ============================
            # FLAGS
            if info.graphics.flag == 1:
                ac.setBackgroundTexture(flagLabel, FC.BLUE_FLAG)
                ac.setVisible(flagLabel, 1)
            elif info.graphics.flag == 2:
                ac.setBackgroundTexture(flagLabel, FC.YELLOW_FLAG)
                ac.setVisible(flagLabel, 1)
            elif info.graphics.flag == 5:
                ac.setBackgroundTexture(flagLabel, FC.CHECKERED_FLAG)
                ac.setVisible(flagLabel, 1)
            elif info.graphics.flag == 0:
                ac.setVisible(flagLabel, 0)

            timer1 = 0

        # Once per second
        if timer0 > 1:
            timer0 = 0
            ac.setBackgroundOpacity(leaderboardWindow, 0)
            ac.setBackgroundOpacity(driverWidget.window, 0)
            ac.setBackgroundOpacity(driverComparisonWidget.window, 0)
            ac.setBackgroundOpacity(fastest_lap_banner.window, 0)

            # ============================
            # SERVER LAP
            for i in range(totalDrivers):
                drivers[i].current_lap = ac.getCarState(i, acsys.CS.LapCount)
            lc = max((drivers[i].current_lap for i in range(totalDrivers))) + 1
            if lc >= info.graphics.numberOfLaps:
                ac.setVisible(lapCountTimerLabel, 0)
                ac.setBackgroundTexture(leaderboardBaseLabel, FC.LEADERBOARD_FINAL_LAP)
            else:
                ac.setText(lapCountTimerLabel, "%d / %d" % (lc, info.graphics.numberOfLaps))

            # ===========================
            # CALCULATE TIME DIFERENCES
            dPosition = sorted(drivers, key=lambda x: x.position)
            if LeaderboardRow.update_type == INFO_TYPE.GAPS:
                for i in range(1, len(dPosition)):
                    driver_ahead, driver = dPosition[i-1], dPosition[i]
                    timeDiff = driver.split_times[driver.current_split - 1] - driver_ahead.split_times[driver.current_split - 1]
                    if timeDiff < 0: continue # ignore these times, happens on overtakes
                    if driver.position > totalDrivers: continue # might try to update before it is possible
                    driver.timeDiff = timeDiff
                    if timeDiff > 60:
                        leaderboard[driver.position].update_time("+1 MIN")
                    else:
                        leaderboard[driver.position].update_time("+" + time_to_string(timeDiff*1000))
                leaderboard[0].update_time("Interval") # Force it
            elif LeaderboardRow.update_type == INFO_TYPE.POSITIONS:
                for d in dPosition:
                    posDiff = d.starting_position - d.position - 1
                    leaderboard[d.position].update_positions(posDiff)

            # ============================
            # MARK FASTEST LAP
            if lc > FC.FASTEST_LAP_STARTING_LAP:
                for d in drivers:
                    lap = ac.getCarState(d.id, acsys.CS.BestLap)
                    if lap != 0 and lap < fastest_lap:
                        fastest_lap = lap
                        fastest_lap_banner.show(lap, ac.getDriverName(d.id))
                        LeaderboardRow.FASTEST_LAP_ID = d.id
                        if replay_file:
                            write_fastest_lap(replay_file, info.graphics.completedLaps, info.graphics.iCurrentTime, d, fastest_lap)
                for row in leaderboard:
                    row.mark_fastest_lap()

            # ============================
            # PITS MARKER
            for row in leaderboard:
                if ac.isCarInPitline(row.driverId) == 1:
                    row.mark_enter_pits()
                    drivers[row.driverId].tyre = ac.getCarTyreCompound(row.driverId) # maybe will change tyre
                else:
                    row.mark_left_pits()
                if time.time() - drivers[row.driverId].pit_time > 20 and ac.isCarInPit(row.driverId):
                    drivers[row.driverId].pits += 1
                    drivers[row.driverId].pit_time = time.time()

            # ============================
            # CHANGE CAR FOCUS AND DRIVER WIDGET
            if race_started:
                id = ac.getFocusedCar()
                if drivers[id].position <= totalDrivers: # in case it wasnt updated yet
                    driverWidget.show(id, drivers[id].position, drivers[id].starting_position, drivers[id].tyre, drivers[id].pits)
                    if drivers[id].position == 0:
                        driverComparisonWidget.hide()
                    else:
                        for d in drivers: # find driver ahead
                            if d.position == drivers[id].position - 1:
                                driverComparisonWidget.show(d.id, d.position, id, drivers[id].position, drivers[id].timeDiff*1000)
                                break
            else:
                driverWidget.hide()
                driverComparisonWidget.hide()

            # ========================================================
            # SAVE DRIVER STATUS IN A FILE TO LOAD ON REPLAY
            if replay_file:
                write_driver_info(replay_file, info.graphics.completedLaps, info.graphics.iCurrentTime, drivers)
            # ========================================================


    # ================================================================
    #                        QUALIFY / PRACTICE
    # ================================================================
    elif info.graphics.session == 1 or (info.graphics.session == 0 and info.graphics.status != 1):

        # 3 times per second
        if timer1 > 0.3:
            # =============================================
            # QUALIFY RESTART
            if quali_started and qualify_session_time - info.graphics.sessionTimeLeft < 1:
                quali_started = False

            # =============================================
            # QUALIFY START
            if not quali_started:
                ac.setBackgroundTexture(leaderboardBaseLabel, FC.LEADERBOARD_BASE_QUALI)
                if (info.graphics.session == 0 and info.graphics.status != 0):
                    ac.setBackgroundTexture(leaderboardBaseLabel, FC.LEADERBOARD_BASE_PRACTICE)
                ac.setFontColor(lapCountTimerLabel, 0.86, 0.86, 0.86, 1)
                qualify_session_time = info.graphics.sessionTimeLeft
                fastest_lap = MAX_LAP_TIME
                LeaderboardRow.FASTEST_LAP_ID = -1
                quali_started = True
                race_started = False

            # =============================================
            # SAVE BEST LAPS FOR EACH DRIVER
            for i in range(totalDrivers):
                lap = ac.getCarState(i, acsys.CS.BestLap)
                if lap != 0:
                    drivers[i].best_lap = lap
                if lap != 0 and lap < fastest_lap:
                    fastest_lap = lap
                    fastest_lap_banner.show(lap, ac.getDriverName(i))

                # MARK IN/OUT DRIVERS
                connected = ac.isConnected(i)
                if connected == 0: # mark unconnected drivers
                    drivers[i].out = True
                else:
                    drivers[i].out = False
                
            # =============================================
            # MANAGE LEADERBOARD

            # Sorting: sort drivers by this order 1. in or out drivers, 2. best lap, 3. driver id
            dPosition = sorted(drivers, key=lambda d: (d.out, d.best_lap, d.id))

            for i in range(totalDrivers):
                if dPosition[i].out:
                    leaderboard[i].mark_out()
                else:
                    leaderboard[i].mark_in()

                leaderboard[i].update_name(dPosition[i].id)
                if dPosition[i].best_lap == MAX_LAP_TIME:
                    leaderboard[i].update_time("NO TIME")
                elif i == 0:
                    leaderboard[i].update_time(time_to_string(dPosition[i].best_lap))
                else:
                    timeDiff = dPosition[i].best_lap - dPosition[0].best_lap
                    if timeDiff > 60000:
                        leaderboard[i].update_time("+1 MIN")
                    else:
                        leaderboard[i].update_time("+" + time_to_string(timeDiff))

                # OVERTAKES
                if i != dPosition[i].position: # there was an overtake on this driver
                    dPosition[i].timer = FC.OVERTAKE_POSITION_LABEL_TIMER
                    if i < dPosition[i].position:
                        leaderboard[i].mark_green_position()
                    elif i > dPosition[i].position:
                        leaderboard[i].mark_red_position()
                elif dPosition[i].timer <= 0:
                    leaderboard[i].mark_white_position()
                else:
                    dPosition[i].timer -= timer1
                dPosition[i].position = i
                # END OVERTAKE

            # ============================
            # FASTEST LAP BANNER TIMER
            if fastest_lap_banner.timer > 0:
                fastest_lap_banner.timer -= timer1
                fastest_lap_banner.hide()

            timer1 = 0

        # Once per second
        if timer0 > 1:
            timer0 = 0
            ac.setBackgroundOpacity(leaderboardWindow, 0)
            ac.setBackgroundOpacity(driverWidget.window, 0)
            ac.setBackgroundOpacity(driverComparisonWidget.window, 0)
            ac.setBackgroundOpacity(fastest_lap_banner.window, 0)

            if quali_started:
                if info.graphics.sessionTimeLeft < 0:
                    ac.setText(lapCountTimerLabel, "0:00")
                else:
                    timeText = time_to_string(info.graphics.sessionTimeLeft)[:-4]
                    ac.setText(lapCountTimerLabel, "0:00"[:-len(timeText)] + timeText)
                if info.graphics.sessionTimeLeft < qualify_session_time / 5:
                    ac.setFontColor(lapCountTimerLabel, 1,0,0,1)

            driverWidget.hide()
            driverComparisonWidget.hide()


    # ================================================================
    #                            REPLAYS
    # ================================================================
    elif info.graphics.status == 1:

        # three times per second
        if timer1 > 0.3:
            if not replay_started:
                if info.graphics.iCurrentTime > 0:
                    replay_data = load_replay_file(drivers)
                    replay_started = True

            # ============================
            # FASTEST LAP BANNER TIMER
            if fastest_lap_banner.timer > 0:
                fastest_lap_banner.timer -= timer1
                fastest_lap_banner.hide()

            # ============================
            # GET DATA FOR THIS UPDATE
            if replay_data:
                new_positions = lookup_data(info.graphics.completedLaps, info.graphics.iCurrentTime, replay_data, drivers)

                # ============================
                # POSITION UPDATE
                for i in range(totalDrivers):
                    pos = new_positions[i]
                    if drivers[i].out: # mark unconnected drivers
                        leaderboard[pos].mark_out()
                    else:
                        leaderboard[pos].mark_in()
                    leaderboard[pos].update_name(i)

                    # OVERTAKE
                    if pos != drivers[i].position: # there was an overtake
                        drivers[i].timer = FC.OVERTAKE_POSITION_LABEL_TIMER # set timer
                        if pos < drivers[i].position:
                            leaderboard[pos].mark_green_position()
                        elif pos > drivers[i].position:
                            leaderboard[pos].mark_red_position()
                    elif drivers[i].timer <= 0:
                        leaderboard[pos].mark_white_position()
                    else:
                        drivers[i].timer -= timer1
                    drivers[i].position = pos
                    # END OVERTAKE

            timer1 = 0

        # Once per second
        if timer0 > 1:
            timer0 = 0
            ac.setBackgroundOpacity(leaderboardWindow, 0)
            ac.setBackgroundOpacity(driverWidget.window, 0)
            ac.setBackgroundOpacity(driverComparisonWidget.window, 0)
            ac.setBackgroundOpacity(fastest_lap_banner.window, 0)

            # ============================
            # GET FASTEST LAP UPDATE
            if replay_data:
                fl_data = lookup_fastest_lap(info.graphics.completedLaps, info.graphics.iCurrentTime, replay_data)
                if fl_data:
                    display_time = FC.FASTEST_LAP_DISPLAY_TIME - (info.graphics.iCurrentTime - fl_data[0]) / 1000
                    fastest_lap_banner.show(fl_data[2], ac.getDriverName(fl_data[1]), timer=display_time) # display only for the time left

            # ============================
            # SERVER LAP
            if replay_data:
                lc = max((drivers[i].current_lap for i in range(totalDrivers))) + 1
                if lc >= replay_data['nLaps']:
                    ac.setVisible(lapCountTimerLabel, 0)
                    ac.setBackgroundTexture(leaderboardBaseLabel, FC.LEADERBOARD_FINAL_LAP)
                else:
                    ac.setText(lapCountTimerLabel, "%d / %d" % (lc, replay_data['nLaps']))
                    ac.setVisible(lapCountTimerLabel, 1)
                    ac.setBackgroundTexture(leaderboardBaseLabel, FC.LEADERBOARD_BASE_RACE)

            # ============================
            # PITS MARKER
            for row in leaderboard:
                if ac.isCarInPitline(row.driverId) == 1:
                    row.mark_enter_pits()
                else:
                    row.mark_left_pits()

            # ============================
            # DRIVER WIDGET UPDATE
            if replay_started:
                id = ac.getFocusedCar()
                if drivers[id].position <= totalDrivers: # in case it wasnt updated yet
                    driverWidget.show(id, drivers[id].position, drivers[id].starting_position, drivers[id].tyre, drivers[id].pits)
                    if drivers[id].position == 0:
                        driverComparisonWidget.hide()
                    else:
                        for d in drivers: # find driver ahead
                            if d.position == drivers[id].position - 1:
                                driverComparisonWidget.show(d.id, d.position, id, drivers[id].position, drivers[id].timeDiff*1000)
                                break
            else:
                driverWidget.hide()
                driverComparisonWidget.hide()

            # ============================
            # UPDATE TIMES
            if replay_data:
                for row in leaderboard:
                    if LeaderboardRow.update_type == INFO_TYPE.GAPS:
                        row.update_time("+" + time_to_string(drivers[row.driverId].timeDiff*1000))
                        if row.row == 0:
                            row.update_time("Interval") # Force it
                    elif LeaderboardRow.update_type == INFO_TYPE.POSITIONS:
                        posDiff = drivers[row.driverId].starting_position - drivers[row.driverId].position - 1
                        row.update_positions(posDiff)
def acUpdate(delta_t):
    global timer, isPatch, app, rolesLONG
    global debug, mirrorrole, mirrorindex, toggleMonButton, fovValue, arDown, arUp, prevButton, nextButton
    global btnVirtSizePlus, btnVirtSizeMinus
    timer += delta_t
    if timer > 0.1 and ac.isConnected(0):
        timer = 0.0
        if not isPatch:
            ac.setText(debug, 'Shaders Patch not active.')
        else:
            try:
                cammode = ac.getCameraMode()
                if cammode == acsys.CM.Cockpit:
                    params = ac.ext_mirrorParams()
                    if params[3] == 0:
                        ac.setText(debug, '')  #  + str(ac.ext_mirrorDebug()) )
                        HideControls()
                        ShowVirtControls()
                        ac.setText(mirrorrole, 'F11 VirtMirror')
                        ac.setText(fovValue, '')
                        ac.setSize(app, 144, 213)
                    else:
                        index = int(params[4])
                        HideVirtControls()
                        if bool(int(params[0])) == True:
                            HideControls()
                            ac.setText(debug, 'set to Monitor\n'
                                       )  #  + str(ac.ext_mirrorDebug()) )
                            ac.setText(toggleMonButton, "M")
                        else:
                            ShowControls()
                            ac.setText(debug,
                                       '\n')  #  + str(ac.ext_mirrorDebug()) )
                            ac.setText(toggleMonButton, "m")
                        if index > 0:
                            ac.setText(mirrorindex, str(index))
                        else:
                            ac.setText(mirrorindex, "")
                        if virt:
                            ac.setText(fovValue, '')
                        else:
                            ac.setText(fovValue, str(int(params[1])))
                        # ac.setText(mirrorrole, roles[int(params[3])])
                        ac.setText(
                            arDown, '  -   ' +
                            str(round(float(params[2]), 1)) + '\n       AR')
                        ac.setText(mirrorrole, rolesLONG[int(params[3])])
                        ac.setVisible(toggleMonButton, 1)
                        ac.setVisible(mirrorrole, 1)
                        ac.setVisible(prevButton, 1)
                        ac.setVisible(nextButton, 1)
                        ac.setSize(app, 144, 213)
                else:
                    ac.setText(
                        mirrorrole,
                        'Not in Cockpit\n')  #  + str(ac.ext_mirrorDebug()) )
                    ac.setText(debug, '')
                    HideVirtControls()
                    HideControls()
                    ac.setSize(app, 144, 85)
            except:
                isPatch = False
                ac.log("AccExtMirror error: " + traceback.format_exc())
Beispiel #18
0
    def update_smart_tracking_values(self, ctt, data, interpolation, info, the_x, dt):
        try:
            self.camera_in = data.mode[data.active_mode][data.active_cam].camera_in
            self.camera_out = data.get_camera_out()
            self.car_id = ac.getFocusedCar()
            self.opponent = self.get_closest_opponent(self.car_id, interpolation, x, data)

            #-------------------------------------------------------------------
            #VERIFY SECOND CAR
            #change opponent only if is the closest one for x amount of time
            if self.opponent != self.__prev_smart_tracked_car_2:
                self.__t_smart_tracking_2 += (dt * info.graphics.replayTimeMultiplier / 2)

                if self.__t_smart_tracking_2 > 1 and self.__t_smart_tracking == 0:
                    self.__t_smart_tracking_2 = 0
                    self.__prev_smart_tracked_car_2 = self.opponent
                else:
                    self.opponent = self.__prev_smart_tracked_car_2
            else:
                self.__t_smart_tracking_2 = 0
                self.__prev_smart_tracked_car_2 = self.opponent


            #dark magic - prevent jumping between opponents during transition
            if self.__prev_smart_tracked_car != self.opponent or self.__t_smart_tracking > 0:
                if self.__locked_smart_tracked_car == None:
                    self.__locked_smart_tracked_car = self.opponent
                else:
                    self.opponent = self.__locked_smart_tracked_car

                self.__t_smart_tracking += (dt * info.graphics.replayTimeMultiplier / self.transition)

                if self.__t_smart_tracking > 1:
                    self.__prev_smart_tracked_car = self.__locked_smart_tracked_car
                    self.__locked_smart_tracked_car = None
                    self.__t_smart_tracking = 0


            #-------------------------------------------------------------------
            #FIND AND VERIFY LAST CAR OUT IN CAMERA SECTOR
            self.last_car_out = {"id": None, "duration": None, "pos_expected": None}
            for self.i in range(32): #max_cars
                if ac.isConnected(self.i) == 1:
                    if data.get_car_is_out(self.i)["status"] == True:
                        if self.last_car_out["id"] == None:
                            self.last_car_out["id"] = self.i
                            self.last_car_out["duration"] = data.get_car_is_out(self.i)["duration"]
                            self.last_car_out["pos_expected"] = data.get_car_is_out(self.i)["pos_expected"]
                        else:
                            if self.last_car_out["duration"] > data.get_car_is_out(self.i)["duration"] and data.get_car_is_out(self.i)["duration"] > 1:
                                self.last_car_out["id"] = self.i
                                self.last_car_out["duration"] = data.get_car_is_out(self.i)["duration"]
                                self.last_car_out["pos_expected"] = data.get_car_is_out(self.i)["pos_expected"]


            #-------------------------------------------------------------------
            #CAR IS CLOSE
            #if self.last_car_out["id"] == None:
                #if self.car_id =


                #CAR OUT
                #self.__car_out = self.last_car_out["id"]
                # self.__smart_tracking_fov_mix = 1
                # self.__smart_tracking_cam_rot_to_track = self.calculate_cam_rot_to_point(ctt, self.last_car_out["pos_expected"])
                # self.__smart_tracking_cam_rot_to_car_out = self.calculate_cam_rot_to_tracking_car(ctt, data, info, self.__car_out) * vec3(0.5, 0.5, 0.5) + self.__smart_tracking_cam_rot_to_track * vec3(0.5, 0.5, 0.5)
                # self.__smart_tracking_fov = self.calculate_fov(ctt, self.cam_pos_2d, self.car_pos_2d, vec(self.last_car_out["pos_expected"].x, self.last_car_out["pos_expected"].y))


            self.__smart_tracking_x = the_x
            self.__smart_tracking_cam_rot = self.calculate_cam_rot_to_tracking_car(ctt, data, info, ac.getFocusedCar(), dt)
            self.__smart_tracking_fov = ctt.get_fov()

        except Exception as e:
            debug(e)
Beispiel #19
0
 def connected(self):
     return ac.isConnected(self._player)
Beispiel #20
0
def updateSharedMemory():
    global sharedMem
    global packetID

    sharedmem = sharedMem.getsharedmem()
    sharedmem.packetID = -1
    sharedmem.numVehicles = ac.getCarsCount()
    sharedmem.focusVehicle = ac.getFocusedCar()

    carIds = range(0, ac.getCarsCount(), 1)

    for carId in carIds:
        if str(ac.getCarName(carId)) == '-1':
            break
        else:
            sharedmem.vehicleInfo[carId].carId = carId
            sharedmem.vehicleInfo[carId].driverName = ac.getDriverName(
                carId).encode('utf-8')
            sharedmem.vehicleInfo[carId].carModel = ac.getCarName(
                carId).encode('utf-8')
            sharedmem.vehicleInfo[carId].speedMS = ac.getCarState(
                carId, acsys.CS.SpeedMS)
            sharedmem.vehicleInfo[carId].bestLapMS = ac.getCarState(
                carId, acsys.CS.BestLap)
            sharedmem.vehicleInfo[carId].lapCount = ac.getCarState(
                carId, acsys.CS.LapCount)
            sharedmem.vehicleInfo[carId].currentLapInvalid = ac.getCarState(
                carId, acsys.CS.LapInvalidated)
            sharedmem.vehicleInfo[carId].currentLapTimeMS = ac.getCarState(
                carId, acsys.CS.LapTime)
            sharedmem.vehicleInfo[carId].lastLapTimeMS = ac.getCarState(
                carId, acsys.CS.LastLap)
            sharedmem.vehicleInfo[carId].worldPosition = ac.getCarState(
                carId, acsys.CS.WorldPosition)
            sharedmem.vehicleInfo[carId].isCarInPitline = ac.isCarInPitline(
                carId)
            sharedmem.vehicleInfo[carId].isCarInPit = ac.isCarInPit(carId)
            sharedmem.vehicleInfo[
                carId].carLeaderboardPosition = ac.getCarLeaderboardPosition(
                    carId)
            sharedmem.vehicleInfo[
                carId].carRealTimeLeaderboardPosition = ac.getCarRealTimeLeaderboardPosition(
                    carId)
            sharedmem.vehicleInfo[carId].splinePosition = ac.getCarState(
                carId, acsys.CS.NormalizedSplinePosition)
            sharedmem.vehicleInfo[carId].isConnected = ac.isConnected(carId)

            if libInit == 1 and carId == 0:
                sharedmem.vehicleInfo[carId].suspensionDamage[
                    0] = funcGetSuspensionDamage(carId, 0)
                sharedmem.vehicleInfo[carId].suspensionDamage[
                    1] = funcGetSuspensionDamage(carId, 1)
                sharedmem.vehicleInfo[carId].suspensionDamage[
                    2] = funcGetSuspensionDamage(carId, 2)
                sharedmem.vehicleInfo[carId].suspensionDamage[
                    3] = funcGetSuspensionDamage(carId, 3)
                sharedmem.vehicleInfo[
                    carId].engineLifeLeft = funcGetEngineLifeLeft(carId)
                sharedmem.vehicleInfo[carId].tyreInflation[
                    0] = funcGetTyreInflation(carId, 0)
                sharedmem.vehicleInfo[carId].tyreInflation[
                    1] = funcGetTyreInflation(carId, 1)
                sharedmem.vehicleInfo[carId].tyreInflation[
                    2] = funcGetTyreInflation(carId, 2)
                sharedmem.vehicleInfo[carId].tyreInflation[
                    3] = funcGetTyreInflation(carId, 3)

    packetID = packetID + 1
    sharedmem.packetID = packetID
Beispiel #21
0
    def on_update(self, sim_info, standings, game_data):
        session_time_left = game_data.sessionTimeLeft
        sim_info_status = game_data.status
        self.standings = standings
        if self.is_multiplayer:
            self.numCars = 0
        for i in range(self.cars_count):
            if ac.isConnected(i) > 0:
                if self.is_multiplayer:
                    self.numCars += 1
                self.drivers_lap_count[i].setValue(
                    ac.getCarState(i, acsys.CS.LapCount))
                if self.last_lap_start[i] == -1 and session_time_left != 0:
                    self.last_lap_start[i] = session_time_left
                if self.drivers_lap_count[i].hasChanged(
                ) and session_time_left != 0:
                    self.last_lap_start[i] = session_time_left
                    # if PB save delta
                    if ac.getCarState(i, acsys.CS.LastLap) <= ac.getCarState(
                            i, acsys.CS.BestLap):
                        self.reference_lap_time_others[i] = list(
                            self.current_lap_others[i])
                        if len(self.reference_lap_time_others[i]
                               ) > 2000:  # 2laps in
                            how_much = math.floor(
                                len(self.reference_lap_time_others[i]) / 1000)
                            del self.reference_lap_time_others[i][0:math.floor(
                                len(self.reference_lap_time_others[i]) /
                                how_much)]
                    # reset
                    self.current_lap_others[i] = []
                # Deltas
                self.spline_others[i].setValue(
                    round(ac.getCarState(i, acsys.CS.NormalizedSplinePosition),
                          3))
                if self.is_touristenfahrten and self.spline_others[
                        i].value == 0.953:
                    self.last_lap_start[i] = session_time_left
                    self.current_lap_others[i] = []
                if ac.isCarInPit(i) or ac.isCarInPitline(i):
                    self.current_lap_others[i] = []
                if self.spline_others[i].hasChanged(
                ) and session_time_left != 0:
                    self.current_lap_others[i].append(
                        raceGaps(self.spline_others[i].value,
                                 self.last_lap_start[i] - session_time_left))

        if not self.deltaLoaded and Configuration.save_delta:
            thread_load = threading.Thread(target=self.load_delta)
            thread_load.daemon = True
            thread_load.start()
        if self.__class__.resetPressed:
            self.referenceLapTime.setValue(0)
            self.referenceLap = []
            self.lastLapTime.setValue(0)
            self.spline.setValue(0)
            self.__class__.resetPressed = False
        if self.__class__.importPressed:
            self.referenceLap = self.reference_lap_time_others[
                self.currentVehicle.value]
            self.referenceLapTime.setValue(
                ac.getCarState(self.currentVehicle.value, acsys.CS.BestLap))
            '''
            self.lastLapTime.setValue(0)
            self.spline.setValue(0)
            '''
            self.__class__.importPressed = False
        self.session.setValue(game_data.session)
        self.manage_window(game_data)
        self.animate()
        self.currentVehicle.setValue(game_data.focusedCar)
        self.current_car_class.setValue(
            self.get_class_id(self.currentVehicle.value))
        if self.currentVehicle.hasChanged(
        ) or self.current_car_class.hasChanged():
            # number, curtime...
            if Configuration.names == 1:
                self.lbl_name_text.setText(
                    self.format_name_tlc2(
                        ac.getDriverName(self.currentVehicle.value)))
            else:
                self.lbl_name_text.setText(
                    self.format_name_tlc(
                        ac.getDriverName(self.currentVehicle.value)))
            self.lbl_number_text.setText(self.get_driver_number())
            #car_name=ac.getCarName(self.currentVehicle.value)
            self.lbl_number_bg.set(background=Colors.color_for_car_class(
                self.current_car_class.value),
                                   init=True)
            self.lbl_number_text.set(color=Colors.txt_color_for_car_class(
                self.current_car_class.value),
                                     init=True)
            self.performance_display = 0
        completed_laps = ac.getCarState(self.currentVehicle.value,
                                        acsys.CS.LapCount)
        self.lbl_laps_completed_text.setText(str(completed_laps))
        self.lbl_laps_completed_text_shadow.setText(str(completed_laps))
        if completed_laps > 1:
            self.lbl_laps_text.setText("LAPS")
            self.lbl_laps_text_shadow.setText("LAPS")
        else:
            self.lbl_laps_text.setText("LAP")
            self.lbl_laps_text_shadow.setText("LAP")

        if sim_info_status == 2:  # LIVE
            if session_time_left == 0 or game_data.beforeRaceStart:
                self.reset_data()
                self.reset_others()
                if not Configuration.save_delta:
                    self.referenceLapTime.setValue(0)
                    self.referenceLap = []
                    self.lastLapTime.setValue(0)
                    self.spline.setValue(0)
            elif self.currentVehicle.value == 0 and bool(
                    ac.isCarInPitline(0)) or bool(ac.isCarInPit(0)):
                self.reset_data()
            self.spline.setValue(
                round(
                    ac.getCarState(self.currentVehicle.value,
                                   acsys.CS.NormalizedSplinePosition), 3))
            #Current lap time
            if self.currentVehicle.value != 0 and self.last_lap_start[
                    self.currentVehicle.
                    value] != -1 and session_time_left != 0:
                self.lbl_current_time_text.setText(
                    self.time_splitting_full(
                        self.last_lap_start[self.currentVehicle.value] -
                        session_time_left))
            else:
                self.lbl_current_time_text.setText(
                    self.time_splitting_full(
                        ac.getCarState(self.currentVehicle.value,
                                       acsys.CS.LapTime)))
            if self.currentVehicle.value == 0 and not self.lastLapIsValid:
                self.lbl_current_time_text.set(color=Colors.red(),
                                               animated=True)
            else:
                self.lbl_current_time_text.set(color=Colors.white(),
                                               animated=True)

            if self.currentVehicle.value == 0 and self.lastLapIsValid and sim_info.physics.numberOfTyresOut >= 4:
                self.lastLapIsValid = False

            if self.spline.hasChanged():
                if self.currentVehicle.value == 0:
                    self.laptime.setValue(
                        round(
                            ac.getCarState(self.currentVehicle.value,
                                           acsys.CS.LapTime), 3))
                    self.lastLapTime.setValue(
                        ac.getCarState(self.currentVehicle.value,
                                       acsys.CS.LastLap))
                    gap = self.get_performance_gap(self.spline.value,
                                                   self.laptime.value)
                    if gap != False:
                        self.performance.setValue(gap)
                    if self.lastLapTime.value > 0:
                        self.lbl_last_time_text.setText(
                            self.time_splitting(self.lastLapTime.value, "yes"))
                    else:
                        self.lbl_last_time_text.setText("--:--.---")
                    # new lap
                    if self.lastLapTime.hasChanged():
                        if (
                                self.referenceLapTime.value == 0
                                or self.lastLapTime.value <
                                self.referenceLapTime.value
                        ) and self.lastLapIsValid and self.lastLapTime.value > 0 and self.lapCount < ac.getCarState(
                                0, acsys.CS.LapCount):
                            #if self.lastLapTime.value > 0:
                            #    self.lbl_last_time_text.setText(self.time_splitting(self.lastLapTime.value, "yes"))
                            #else:
                            #    self.lbl_last_time_text.setText("--:--.---")
                            self.referenceLapTime.setValue(
                                self.lastLapTime.value)
                            self.referenceLap = list(self.currentLap)
                            if len(self.referenceLap) > 2000:  # 2laps in
                                ac.console("too many laps in reference----")
                                ac.log("too many laps in reference----")
                                how_much = math.floor(
                                    len(self.referenceLap) / 1000)
                                del self.referenceLap[0:math.floor(
                                    len(self.referenceLap) / how_much)]
                            if self.currentVehicle.value == 0 and Configuration.save_delta and len(
                                    self.referenceLap) > 20:
                                thread_save = threading.Thread(
                                    target=self.save_delta)
                                thread_save.daemon = True
                                thread_save.start()

                        self.currentLap = []
                        self.lapCount = ac.getCarState(
                            self.currentVehicle.value, acsys.CS.LapCount)
                        self.lastLapIsValid = True

                    self.currentLap.append(
                        raceGaps(self.spline.value, self.laptime.value))

                    self.best_lap_time = self.referenceLapTime.value
                    self.performance_display = self.performance.value
                else:
                    gap = self.get_performance_gap(
                        self.spline.value,
                        self.last_lap_start[self.currentVehicle.value] -
                        session_time_left)
                    if gap != False:
                        self.performance_display = gap
                    #else:
                    #    self.performance_display = ac.getCarState(self.currentVehicle.value, acsys.CS.PerformanceMeter)
                    self.best_lap_time = ac.getCarState(
                        self.currentVehicle.value, acsys.CS.BestLap)
                    last_lap = ac.getCarState(self.currentVehicle.value,
                                              acsys.CS.LastLap)
                    if last_lap > 0:
                        self.lbl_last_time_text.setText(
                            self.time_splitting(last_lap, "yes"))
                    else:
                        self.lbl_last_time_text.setText("--:--.---")

            #update rate
            self.TimeLeftUpdate.setValue(int(session_time_left / 500))
            if self.TimeLeftUpdate.hasChanged():
                # update graphics

                # position
                if self.session.value != 2:
                    pos = self.get_standings_position(
                        self.currentVehicle.value)
                else:
                    pos = self.get_race_standings_position(
                        self.currentVehicle.value)
                if pos > self.numCars:
                    pos = self.numCars

                if Colors.multiCarsClasses:
                    # Position in class
                    pos_class = self.get_race_standings_position_in_class(
                        self.currentVehicle.value)
                    self.lbl_position_text.setText(str(pos_class[0]))
                    self.lbl_position_text_shadow.setText(str(pos_class[0]))
                    self.lbl_position_total_text.setText("/{0}".format(
                        pos_class[1]))
                    self.lbl_position_total_text_shadow.setText("/{0}".format(
                        pos_class[1]))
                    # Position in overall
                    self.lbl_position_text_multi.setText(str(pos)).show()
                    self.lbl_position_text_multi_shadow.setText(
                        str(pos)).show()
                    self.lbl_position_total_text_multi.setText("/{0}".format(
                        self.numCars)).show()
                    self.lbl_position_total_text_multi_shadow.setText(
                        "/{0}".format(self.numCars)).show()
                else:
                    # Position in overall
                    self.lbl_position_text.setText(str(pos))
                    self.lbl_position_text_shadow.setText(str(pos))
                    self.lbl_position_total_text.setText("/{0}".format(
                        self.numCars))
                    self.lbl_position_total_text_shadow.setText("/{0}".format(
                        self.numCars))
                    self.lbl_position_text_multi.hide()
                    self.lbl_position_text_multi_shadow.hide()
                    self.lbl_position_total_text_multi.hide()
                    self.lbl_position_total_text_multi_shadow.hide()

                # flags
                flag = game_data.flag
                if flag == 1:
                    # AC_BLUE_FLAG Flag
                    self.lbl_flag.set(background=Colors.blue_flag()).show()
                elif flag == 2:
                    # AC_YELLOW_FLAG Flag
                    self.lbl_flag.set(background=Colors.
                                      timer_border_yellow_flag_bg()).show()
                    self.last_yellow_flag_end = session_time_left
                elif flag == 3 or flag == 6:
                    # AC_BLACK_FLAG,AC_PENALTY_FLAG
                    self.lbl_flag.set(background=Colors.black()).show()
                elif flag == 4:
                    # AC_WHITE_FLAG
                    self.lbl_flag.set(background=Colors.white(bg=True)).show()
                elif ac.getCarState(self.currentVehicle.value,
                                    acsys.CS.RaceFinished) == 1:  #flag == 5
                    # AC_CHECKERED_FLAG
                    self.lbl_flag.set(background=Colors.flag_finish()).show()
                elif self.last_yellow_flag_end != False and self.last_yellow_flag_end - 4000 <= session_time_left:
                    # Green flag
                    self.lbl_flag.set(
                        background=Colors.timer_border_bg()).show()
                else:
                    self.lbl_flag.hide()

                if self.best_lap_time > 0:
                    self.lbl_best_time_text.setText(
                        self.time_splitting(self.best_lap_time, "yes"))
                else:
                    self.lbl_best_time_text.setText("--:--.---")
                if self.best_lap_time > 0:  # and self.currentVehicle.value == 0
                    time_prefix = "+"
                    color = Colors.delta_neutral()
                    if self.performance_display >= 10:
                        time_prefix = "+"
                        color = Colors.delta_positive()
                    elif self.performance_display <= -10:
                        time_prefix = "-"
                        color = Colors.delta_negative()
                    self.lbl_delta_bg.set(background=color, animated=True)
                    txt_delta = time_prefix + self.time_splitting_delta(
                        abs(self.performance_display))
                    self.lbl_delta_text.set(
                        font_size=self.font_size +
                        self.rowHeight.value * 3 / 38 -
                        ((len(txt_delta) - 5) * self.rowHeight.value * 4 / 38),
                        animated=True).setText(txt_delta)
                    if self.performance_display < self.best_lap_time:
                        self.lbl_prediction_time_text.setText(
                            self.time_splitting(
                                self.best_lap_time + self.performance_display,
                                "yes"))
                    else:
                        self.lbl_prediction_time_text.setText("--:--.---")
                else:
                    self.lbl_delta_bg.set(background=Colors.delta_neutral(),
                                          animated=True)
                    self.lbl_delta_text.set(font_size=self.font_size +
                                            self.rowHeight.value * 4 / 38,
                                            animated=True).setText("-.--")
                    self.lbl_prediction_time_text.setText("--:--.---")