Пример #1
0
    def updateFastCarPosition(self, car, idx, meetPoint, dt):
        xCar = -car.xPos
        sDiff = car.currentSpeed - self.staticSpeed  # speed diff between next slow car and participant
        d = meetPoint - xCar  # distance from participant to meetpoint
        xFast = self.fastCars[idx].x

        fDiff = xFast - xCar

        if not self.fastCars[idx].speedingAway:
            if self.fastCars[
                    idx].kind == 'none' and fDiff > FAST_OVERTAKE_DISTANCE:  # fast car is passing, ride off into the sunset!
                self.fastCars[idx].speedingAway = True
            elif self.fastCars[
                    idx].kind == 'tailer' and fDiff > -2.0:  # change speed
                self.fastCars[idx].speed *= 1 - (dt * 0.2)
            elif self.fastCars[idx].kind == 'tailer' and d < 5.0:  # change lane
                transSpeed = 2.5
                if self.fastCars[idx].zOff < 4.0:
                    self.fastCars[idx].zOff += transSpeed * dt
                self.fastCars[idx].speed *= 1 - (dt * 0.2)
            elif d > 10.0:  # recompute fast car speed for accuracy until its close enough to the participant

                ttx = d / sDiff  # time to the meetpoint
                ep = xCar + (ttx * car.currentSpeed
                             )  # expected road position of the meetpoint

                dFast = ep - xFast  # distance between the meetpoint and the fast car
                sf = dFast / ttx  # fast car speed required to hit the meetpoint at the right moment
                #print 'car speed: '+str(globals.mpsToKph(sf))
                self.fastCars[idx].speed = sf
                #print 'ep: '+str(ep)+' ttx: '+str(ttx)+' dFast: '+str(dFast)+' sf: '+str(sf)

            #print 'mp: '+str(meetPoint)+' car.x: '+str(tc)+' fast.x: '+str(tf)+' dist: '+str(d)
            if self.fastCars[idx].inProxTime < 0.0:
                if fDiff > -8.0:
                    self.fastCars[idx].inProxTime = helpers.currentTime(
                    )  # set the tailgaiting timer
                    if globals.debug: print '[starting tailgaiting timer]'
            else:
                if helpers.currentTime() - self.fastCars[idx].inProxTime > 5.0:
                    self.fastCars[idx].speedingAway = True
                    if globals.debug: print '[tailgaiting timer exceeded]'
        else:
            self.fastCars[idx].speed *= 1 + (dt * 0.1)

        #self.fastCars[idx].speed = min(globals.kphToMps(140.0), self.fastCars[idx].speed)
        xnew = xFast + self.fastCars[idx].speed * dt
        if car.inSafeZone:  # fastcar can't collide with participant
            #print 'xnew: '+str(xnew)+' xcar: '+str(xCar)
            xnew = min(xCar - 20.0, xnew)

        (xl, zl, heading, hx,
         hz) = self.road.getLanePosition(xnew, globals.LEFT_LANE)
        self.fastCars[idx].update(xnew, zl + self.fastCars[idx].zOff, heading,
                                  hx, hz)
        self.tFastCars[idx] = xnew
Пример #2
0
    def updateFastCarPosition(self, car, idx, meetPoint, dt):
        xCar = -car.xPos
        sDiff = car.currentSpeed - self.staticSpeed # speed diff between next slow car and participant
        d = meetPoint - xCar # distance from participant to meetpoint
        xFast = self.fastCars[idx].x

        fDiff = xFast - xCar

        if not self.fastCars[idx].speedingAway:
            if self.fastCars[idx].kind == 'none' and fDiff > FAST_OVERTAKE_DISTANCE: # fast car is passing, ride off into the sunset!
                self.fastCars[idx].speedingAway = True
            elif self.fastCars[idx].kind == 'tailer' and fDiff > -2.0: # change speed
                self.fastCars[idx].speed *= 1 - (dt*0.2)
            elif self.fastCars[idx].kind == 'tailer' and d < 5.0: # change lane
                transSpeed = 2.5
                if self.fastCars[idx].zOff < 4.0:
                    self.fastCars[idx].zOff += transSpeed*dt
                self.fastCars[idx].speed *= 1 - (dt*0.2)
            elif d > 10.0: # recompute fast car speed for accuracy until its close enough to the participant

                ttx = d / sDiff # time to the meetpoint
                ep = xCar + (ttx * car.currentSpeed) # expected road position of the meetpoint

                dFast = ep - xFast # distance between the meetpoint and the fast car
                sf = dFast / ttx # fast car speed required to hit the meetpoint at the right moment
                #print 'car speed: '+str(globals.mpsToKph(sf))
                self.fastCars[idx].speed = sf
                #print 'ep: '+str(ep)+' ttx: '+str(ttx)+' dFast: '+str(dFast)+' sf: '+str(sf)

            #print 'mp: '+str(meetPoint)+' car.x: '+str(tc)+' fast.x: '+str(tf)+' dist: '+str(d)
            if self.fastCars[idx].inProxTime < 0.0:
                if fDiff > -8.0:
                    self.fastCars[idx].inProxTime = helpers.currentTime() # set the tailgaiting timer
                    if globals.debug: print '[starting tailgaiting timer]'
            else:
                if helpers.currentTime() - self.fastCars[idx].inProxTime > 5.0:
                    self.fastCars[idx].speedingAway = True
                    if globals.debug: print '[tailgaiting timer exceeded]'
        else:
            self.fastCars[idx].speed *= 1 + (dt*0.1)

        #self.fastCars[idx].speed = min(globals.kphToMps(140.0), self.fastCars[idx].speed)
        xnew = xFast + self.fastCars[idx].speed*dt
        if car.inSafeZone: # fastcar can't collide with participant
            #print 'xnew: '+str(xnew)+' xcar: '+str(xCar)
            xnew = min(xCar - 20.0, xnew)

        (xl, zl, heading, hx, hz) = self.road.getLanePosition(xnew, globals.LEFT_LANE)
        self.fastCars[idx].update(xnew, zl+self.fastCars[idx].zOff, heading, hx, hz)
        self.tFastCars[idx] = xnew
Пример #3
0
    def setBlinker(self, direction):
        global db

        self.activeBlinker = direction
        d = 'L'
        if (direction == globals.RIGHT_BLINKER):
            d = 'R'
        self.blinkerCooldown = 1.0

        self.lastBlinkerDir = d
        self.lastBlinkerTime = helpers.currentTime()

        blinkSound = pyglet.resource.media('blinker.wav')
        blinkSound.play()

        globals.db['blinker'].addData(['pp', globals.participant, 'condition', globals.flow.getCondition(), 'direction', d, 'condtime', r3(helpers.conditionTime()),  'block', block,
                               'time', r3(helpers.currentTime())], True)
Пример #4
0
    def checkBlinkerUse(self, cardir):
        curtime = helpers.currentTime()
        if curtime - self.lastBlinkerTime > globals.MAX_TRANSITION_LAG_TIME:
            if globals.debug:
                print 'No blinker was used during a lane transition'
            if doPractice and block < 2:
                self.blinkerPracWarning = 1.5

            globals.bonusCounter = max(
                0.0, globals.bonusCounter - globals.BLINKER_PENALTY)
            globals.db['lanetransition'].addData([
                'pp', globals.participant, 'condition',
                globals.flow.getCondition(), 'blinkerused', '0', 'blinkdir',
                '?', 'block', globals.flow.block, 'cardir', cardir,
                'congruent', '0', 'condtime',
                r3(helpers.conditionTime()), 'time',
                r3(helpers.currentTime())
            ], True)
        else:
            if (cardir == 'L' and self.lastBlinkerDir
                    == 'L') or (cardir == 'R' and self.lastBlinkerDir == 'R'):
                globals.db['lanetransition'].addData([
                    'pp', globals.participant, 'condition',
                    globals.flow.getCondition(), 'blinkerused', '1',
                    'blinkdir', self.lastBlinkerDir, 'block',
                    globals.flow.block, 'cardir', cardir, 'congruent', '1',
                    'condtime',
                    r3(helpers.conditionTime()), 'time',
                    r3(helpers.currentTime())
                ], True)
                if globals.debug:
                    print 'Correct use of blinker during lane transition'
            else:
                globals.db['lanetransition'].addData([
                    'pp', globals.participant, 'condition',
                    globals.flow.getCondition(), 'blinkerused', '1',
                    'blinkdir', self.lastBlinkerDir, 'block',
                    globals.flow.block, 'cardir', cardir, 'congruent', '0',
                    'condtime',
                    r3(helpers.conditionTime()), 'time',
                    r3(helpers.currentTime())
                ], True)
                if globals.debug:
                    print 'Incorrect use of blinker during lane transition'
                globals.bonusCounter -= BLINKER_PENALTY
Пример #5
0
    def setBlinker(self, direction):
        global db

        self.activeBlinker = direction
        d = 'L'
        if (direction == globals.RIGHT_BLINKER):
            d = 'R'
        self.blinkerCooldown = 1.0

        self.lastBlinkerDir = d
        self.lastBlinkerTime = helpers.currentTime()

        blinkSound = pyglet.resource.media('blinker.wav')
        blinkSound.play()

        globals.db['blinker'].addData([
            'pp', globals.participant, 'condition',
            globals.flow.getCondition(), 'direction', d, 'condtime',
            r3(helpers.conditionTime()), 'block', block, 'time',
            r3(helpers.currentTime())
        ], True)
Пример #6
0
    def reportNearbyStaticCars(self, car):
        iMin = bisect.bisect(self.tStaticCars, -car.xPos - 25.0)
        iMax = bisect.bisect(self.tStaticCars, -car.xPos + 25.0)

        speed = (self.staticSpeed * 3600) * 0.001
        for i in xrange(iMin, iMax):
            s = self.staticCars[i]

            globals.db['slowcars'].addData([
                'pp', globals.participant, 'condition',
                globals.flow.getCondition(), 'id', s.id, 'type', 'slow',
                'speed',
                r3(speed), 'xposition',
                r3(s.x), 'distance',
                r3(s.x - (-car.xPos)), 'block', globals.flow.block, 'condtime',
                r3(helpers.conditionTime()), 'time',
                r3(helpers.currentTime())
            ], True)
Пример #7
0
    def reportNearbyFastCars(self, car):
        iMin = bisect.bisect(self.tFastCars,
                             -car.xPos - 25.0)  # get plants close to the car
        iMax = bisect.bisect(self.tFastCars, -car.xPos + 25.0)

        for i in xrange(iMin, iMax):
            f = self.fastCars[i]

            speed = (f.speed * 3600) * 0.001
            globals.db['fastcars'].addData([
                'pp', globals.participant, 'condition',
                globals.flow.getCondition(), 'id', f.id, 'type', 'fast',
                'speed',
                r3(speed), 'xposition',
                r3(f.x), 'distance',
                r3(f.x - (-car.xPos)), 'block', globals.flow.block, 'condtime',
                r3(helpers.conditionTime()), 'time',
                r3(helpers.currentTime())
            ], True)
Пример #8
0
    def checkBlinkerUse(self, cardir):
        curtime = helpers.currentTime()
        if curtime - self.lastBlinkerTime > globals.MAX_TRANSITION_LAG_TIME:
            if globals.debug: print 'No blinker was used during a lane transition'
            if doPractice and block < 2:
                self.blinkerPracWarning = 1.5

            globals.bonusCounter = max(0.0, globals.bonusCounter - globals.BLINKER_PENALTY)
            globals.db['lanetransition'].addData(['pp', globals.participant, 'condition', globals.flow.getCondition(), 'blinkerused', '0', 'blinkdir', '?', 'block', globals.flow.block,
                                'cardir', cardir, 'congruent', '0', 'condtime', r3(helpers.conditionTime()), 'time', r3(helpers.currentTime())], True)
        else:
            if (cardir == 'L' and self.lastBlinkerDir == 'L') or (cardir == 'R' and self.lastBlinkerDir == 'R'):
                globals.db['lanetransition'].addData(['pp', globals.participant, 'condition', globals.flow.getCondition(), 'blinkerused', '1', 'blinkdir', self.lastBlinkerDir, 'block', globals.flow.block,
                                'cardir', cardir, 'congruent', '1', 'condtime', r3(helpers.conditionTime()), 'time', r3(helpers.currentTime())], True)
                if globals.debug: print 'Correct use of blinker during lane transition'
            else:
                globals.db['lanetransition'].addData(['pp', globals.participant, 'condition', globals.flow.getCondition(), 'blinkerused', '1', 'blinkdir', self.lastBlinkerDir, 'block', globals.flow.block,
                                'cardir', cardir, 'congruent', '0', 'condtime', r3(helpers.conditionTime()), 'time', r3(helpers.currentTime())], True)
                if globals.debug: print 'Incorrect use of blinker during lane transition'
                globals.bonusCounter -= BLINKER_PENALTY
Пример #9
0
    def calcPassingStates(self, car):
        iMin = bisect.bisect(self.tStaticCars, -car.xPos - 20.0)
        iMax = bisect.bisect(self.tStaticCars, -car.xPos + 20.0)

        for i in xrange(iMin, iMax):

            if self.waitingForLaneTransition:  # don't generate new cars until the particpant is back on the right lane
                if car.getRoadPosition() < 0.0 or helpers.conditionTime(
                ) - self.waitingForLaneTransTime > 10.0:
                    if car.getRoadPosition() < 0.0:
                        if globals.debug:
                            print 'Participant returned to right lane after overtaking a car'
                    else:
                        if globals.debug:
                            print 'Participant is sticking left too long, generating cars anyway'
                    self.waitingForLaneTransition = False

                    oldNews = [
                        j for j, v in enumerate(self.beingOvertaken)
                        if v > self.staticCars[i].id
                    ]
                    if len(
                            oldNews
                    ) == 0:  # participant has not started overtaking another car yet
                        #rand = random.random()
                        #if rand < 1.0 - NO_OVERTAKES_CHANCE:
                        if self.recentPassedCar + 1 < len(self.staticCars):
                            try:
                                approxDist = self.staticCars[
                                    self.recentPassedCar + 1].x - (-car.xPos)
                            except IndexError:
                                approxDist = -1
                            if globals.debug:
                                print 'Distance to next car: ' + str(
                                    approxDist)

                            #critRand = random.random()
                            #secRand = random.random()
                            #if secRand <= 0.50:
                            ad = approxDist
                            if approxDist > -1:
                                #if random.random() >= 0.5:
                                for dynCar in self.dynamicCarTypes:
                                    if random.random(
                                    ) <= dynCar.genChance and approxDist > dynCar.minRoom:
                                        self.genDynamicCar(
                                            dynCar.distanceFactor * approxDist
                                            + random.uniform(
                                                -dynCar.jitterFactor * ad,
                                                dynCar.jitterFactor * ad),
                                            dynCar.generateDistance)

                                # if self.recentPassedCar < len(self.fastCars3):
                                #     if self.fastCars3[self.recentPassedCar]:
                                #         self.genDynamicCar(0.9*ad + random.uniform(-0.05*ad, 0.05*ad), random.uniform(40.0, 41.0))
                                #
                                # #if random.random() >= 0.5:
                                # if self.recentPassedCar < len(self.fastCars4) and approxDist > 75.0:
                                #     if self.fastCars4[self.recentPassedCar]:
                                #         self.genDynamicCar(0.7*ad + random.uniform(-0.05*ad, 0.05*ad), random.uniform(60.0, 61.0))
                                #
                                #
                                # secLoc = 0.5*approxDist + random.uniform(-0.05*approxDist, 0.05*approxDist)
                                # if self.recentPassedCar < len(self.fastCars1):
                                #     if self.fastCars1[self.recentPassedCar]:
                                #         if approxDist > 20.0:
                                #             #print 'Non-critical fast car generated after overtaking ' + str(self.recentPassedCar)+' at '+str(secLoc)
                                #             self.genDynamicCar(secLoc, random.uniform(71.0, 85.0))
                                #
                                #if random.random() > 0.001 and approxDist > 80.0:
                                #self.genDynamicCar(0.3*ad + random.uniform(-0.05*ad, 0.05*ad), random.uniform(100.0, 101.0))

                                #if random.random() >= 0.5 and overtakePoint * 3 < 0.3*ad:
                                # overtakePoint = car.getAvgOvertakePoint()
                                #
                                # if self.recentPassedCar < len(self.fastCars5) and approxDist > 75.0:
                                #     if self.fastCars5[self.recentPassedCar]:
                                #         self.genDynamicCar(overtakePoint*3, random.uniform(110.0, 111.0))
                                #
                                # if self.recentPassedCar < len(self.fastCars2):
                                #     if self.fastCars2[self.recentPassedCar]:
                                #         critLoc = overtakePoint
                                #         self.genDynamicCar(critLoc, random.uniform(135.0, 145.0))
                                #         if globals.debug: print 'Critical fast car generated after overtaking ' + str(self.recentPassedCar) + ', will overtake at distance '+str(critLoc)
                                #     #else:
                                #         #print 'Not generating any fast cars after overtaking ' + str(self.staticCars[i].id)
                                #
                                # # tailer
                                # #if random.random() >= 0.5:
                                # if self.recentPassedCar < len(self.fastCars6):
                                #     if self.fastCars6[self.recentPassedCar]:
                                #     #if 1:
                                #         if self.genDynamicCar(0.0, random.uniform(155.0, 161.0)):
                                #             if len(self.fastCars) > 0:
                                #                 self.fastCars[-1].kind = 'tailer'
                                #
            #print 'car '+str(i)
            oldState = self.staticCars[i].passState
            (state, dist) = self.determinePassingState(car, self.staticCars[i])
            if oldState < globals.PASS_COMPLETE:
                self.staticCars[i].passState = state

                if not self.staticCars[i].beingOvertaken:
                    if state == globals.PASS_ALONG_CAR and oldState == globals.PASS_BEHIND_CAR:
                        if globals.debug:
                            print 'Starting overtake [slow car ID: ' + str(
                                self.staticCars[i].id) + ']'

                        self.staticCars[i].beingOvertaken = True
                        self.beingOvertaken.append(self.staticCars[i].id)
                        globals.db['overtake'].addData([
                            'pp', globals.participant, 'condition',
                            globals.flow.getCondition(), 'state', 'start',
                            'carNum', self.staticCars[i].id, 'carDist',
                            car.laneCrossDist, 'block', globals.flow.block,
                            'condtime',
                            r3(helpers.conditionTime()), 'time',
                            r3(helpers.currentTime())
                        ], True)

                else:
                    if state == globals.PASS_INFRONT_CAR and dist > 2.0:
                        if globals.debug:
                            print 'Finished overtake [slow car ID: ' + str(
                                self.staticCars[i].id) + ']'
                        globals.db['overtake'].addData([
                            'pp', globals.participant, 'condition',
                            globals.flow.getCondition(), 'state', 'complete',
                            'carNum', self.staticCars[i].id, 'carDist',
                            car.laneCrossDist, 'block', globals.flow.block,
                            'condtime',
                            r3(helpers.conditionTime()), 'time',
                            r3(helpers.currentTime())
                        ], True)

                        self.staticCars[i].passState = globals.PASS_COMPLETE
                        self.beingOvertaken.remove(self.staticCars[i].id)
                        self.beenOvertaken.append(self.staticCars[i].id)
                        self.recentPassedCar = i
                        car.saveOvertakePoint()

                        self.fastCars = []
                        self.tFastCars = []

                        self.waitingForLaneTransition = True
                        self.waitingForLaneTransTime = helpers.conditionTime()

                    elif state == globals.PASS_BEHIND_CAR and dist < -9.0:

                        self.staticCars[i].beingOvertaken = False
                        globals.db['overtake'].addData([
                            'pp', globals.participant, 'condition',
                            globals.flow.getCondition(), 'state', 'failed',
                            'carNum', self.staticCars[i].id, 'carDist',
                            car.laneCrossDist, 'block', globals.flow.block,
                            'condtime',
                            r3(helpers.conditionTime()), 'time',
                            r3(helpers.currentTime())
                        ], True)
                        if globals.debug:
                            print 'Overtake incomplete [slow car ID: ' + str(
                                self.staticCars[i].id) + ']'
Пример #10
0
    def reportNearbyFastCars(self, car):
        iMin = bisect.bisect(self.tFastCars, -car.xPos - 25.0) # get plants close to the car
        iMax = bisect.bisect(self.tFastCars, -car.xPos + 25.0)

        for i in xrange(iMin, iMax):
            f = self.fastCars[i]

            speed = (f.speed * 3600) * 0.001
            globals.db['fastcars'].addData(['pp', globals.participant, 'condition', globals.flow.getCondition(), 'id', f.id, 'type', 'fast',
                                    'speed', r3(speed), 'xposition', r3(f.x), 'distance', r3(f.x-(-car.xPos)), 'block', globals.flow.block,
                                    'condtime', r3(helpers.conditionTime()), 'time', r3(helpers.currentTime())], True)
Пример #11
0
    def calcPassingStates(self, car):
        iMin = bisect.bisect(self.tStaticCars, -car.xPos - 20.0)
        iMax = bisect.bisect(self.tStaticCars, -car.xPos + 20.0)

        for i in xrange(iMin, iMax):

            if self.waitingForLaneTransition: # don't generate new cars until the particpant is back on the right lane
                if car.getRoadPosition() < 0.0 or helpers.conditionTime() -  self.waitingForLaneTransTime > 10.0:
                    if car.getRoadPosition() < 0.0:
                        if globals.debug: print 'Participant returned to right lane after overtaking a car'
                    else:
                        if globals.debug: print 'Participant is sticking left too long, generating cars anyway'
                    self.waitingForLaneTransition = False

                    oldNews = [j for j,v in enumerate(self.beingOvertaken) if v > self.staticCars[i].id]
                    if len(oldNews) == 0: # participant has not started overtaking another car yet
                        #rand = random.random()
                        #if rand < 1.0 - NO_OVERTAKES_CHANCE:
                        if self.recentPassedCar+1 < len(self.staticCars):
                            try:
                                approxDist = self.staticCars[self.recentPassedCar+1].x - (-car.xPos)
                            except IndexError:
                                approxDist = -1
                            if globals.debug: print 'Distance to next car: '+str(approxDist)

                            #critRand = random.random()
                            #secRand = random.random()
                            #if secRand <= 0.50:
                            ad = approxDist
                            if approxDist > -1:
                                #if random.random() >= 0.5:
                                for dynCar in self.dynamicCarTypes:
                                    if random.random() <= dynCar.genChance and approxDist > dynCar.minRoom:
                                        self.genDynamicCar(dynCar.distanceFactor*approxDist + random.uniform(-dynCar.jitterFactor*ad, dynCar.jitterFactor*ad), dynCar.generateDistance)

                                # if self.recentPassedCar < len(self.fastCars3):
                                #     if self.fastCars3[self.recentPassedCar]:
                                #         self.genDynamicCar(0.9*ad + random.uniform(-0.05*ad, 0.05*ad), random.uniform(40.0, 41.0))
                                #
                                # #if random.random() >= 0.5:
                                # if self.recentPassedCar < len(self.fastCars4) and approxDist > 75.0:
                                #     if self.fastCars4[self.recentPassedCar]:
                                #         self.genDynamicCar(0.7*ad + random.uniform(-0.05*ad, 0.05*ad), random.uniform(60.0, 61.0))
                                #
                                #
                                # secLoc = 0.5*approxDist + random.uniform(-0.05*approxDist, 0.05*approxDist)
                                # if self.recentPassedCar < len(self.fastCars1):
                                #     if self.fastCars1[self.recentPassedCar]:
                                #         if approxDist > 20.0:
                                #             #print 'Non-critical fast car generated after overtaking ' + str(self.recentPassedCar)+' at '+str(secLoc)
                                #             self.genDynamicCar(secLoc, random.uniform(71.0, 85.0))
                                #
                                #if random.random() > 0.001 and approxDist > 80.0:
                                    #self.genDynamicCar(0.3*ad + random.uniform(-0.05*ad, 0.05*ad), random.uniform(100.0, 101.0))

                                #if random.random() >= 0.5 and overtakePoint * 3 < 0.3*ad:
                                # overtakePoint = car.getAvgOvertakePoint()
                                #
                                # if self.recentPassedCar < len(self.fastCars5) and approxDist > 75.0:
                                #     if self.fastCars5[self.recentPassedCar]:
                                #         self.genDynamicCar(overtakePoint*3, random.uniform(110.0, 111.0))
                                #
                                # if self.recentPassedCar < len(self.fastCars2):
                                #     if self.fastCars2[self.recentPassedCar]:
                                #         critLoc = overtakePoint
                                #         self.genDynamicCar(critLoc, random.uniform(135.0, 145.0))
                                #         if globals.debug: print 'Critical fast car generated after overtaking ' + str(self.recentPassedCar) + ', will overtake at distance '+str(critLoc)
                                #     #else:
                                #         #print 'Not generating any fast cars after overtaking ' + str(self.staticCars[i].id)
                                #
                                # # tailer
                                # #if random.random() >= 0.5:
                                # if self.recentPassedCar < len(self.fastCars6):
                                #     if self.fastCars6[self.recentPassedCar]:
                                #     #if 1:
                                #         if self.genDynamicCar(0.0, random.uniform(155.0, 161.0)):
                                #             if len(self.fastCars) > 0:
                                #                 self.fastCars[-1].kind = 'tailer'
                                #
            #print 'car '+str(i)
            oldState = self.staticCars[i].passState
            (state, dist) = self.determinePassingState(car,self.staticCars[i])
            if oldState < globals.PASS_COMPLETE:
                self.staticCars[i].passState = state

                if not self.staticCars[i].beingOvertaken:
                    if state == globals.PASS_ALONG_CAR and oldState == globals.PASS_BEHIND_CAR:
                        if globals.debug: print 'Starting overtake [slow car ID: ' + str(self.staticCars[i].id) +']'

                        self.staticCars[i].beingOvertaken = True
                        self.beingOvertaken.append(self.staticCars[i].id)
                        globals.db['overtake'].addData(['pp', globals.participant, 'condition', globals.flow.getCondition(), 'state', 'start',
                                                'carNum', self.staticCars[i].id, 'carDist', car.laneCrossDist, 'block', globals.flow.block,
                                                'condtime', r3(helpers.conditionTime()), 'time', r3(helpers.currentTime())], True)

                else:
                    if state == globals.PASS_INFRONT_CAR and dist > 2.0:
                        if globals.debug: print 'Finished overtake [slow car ID: ' + str(self.staticCars[i].id) +']'
                        globals.db['overtake'].addData(['pp', globals.participant, 'condition', globals.flow.getCondition(), 'state', 'complete',
                                                'carNum', self.staticCars[i].id, 'carDist', car.laneCrossDist, 'block', globals.flow.block,
                                                'condtime', r3(helpers.conditionTime()), 'time', r3(helpers.currentTime())], True)

                        self.staticCars[i].passState = globals.PASS_COMPLETE
                        self.beingOvertaken.remove(self.staticCars[i].id)
                        self.beenOvertaken.append(self.staticCars[i].id)
                        self.recentPassedCar = i
                        car.saveOvertakePoint()

                        self.fastCars = []
                        self.tFastCars = []

                        self.waitingForLaneTransition = True
                        self.waitingForLaneTransTime = helpers.conditionTime()

                    elif state == globals.PASS_BEHIND_CAR and dist < -9.0:

                        self.staticCars[i].beingOvertaken = False
                        globals.db['overtake'].addData(['pp', globals.participant, 'condition', globals.flow.getCondition(), 'state', 'failed',
                                                'carNum', self.staticCars[i].id, 'carDist', car.laneCrossDist, 'block', globals.flow.block,
                                                'condtime', r3(helpers.conditionTime()), 'time', r3(helpers.currentTime())], True)
                        if globals.debug: print 'Overtake incomplete [slow car ID: ' + str(self.staticCars[i].id) +']'
Пример #12
0
    def reportNearbyStaticCars(self, car):
        iMin = bisect.bisect(self.tStaticCars, -car.xPos - 25.0)
        iMax = bisect.bisect(self.tStaticCars, -car.xPos + 25.0)

        speed = (self.staticSpeed * 3600) * 0.001
        for i in xrange(iMin, iMax):
            s = self.staticCars[i]

            globals.db['slowcars'].addData(['pp', globals.participant, 'condition', globals.flow.getCondition(), 'id', s.id, 'type', 'slow',
                                    'speed', r3(speed), 'xposition', r3(s.x), 'distance', r3(s.x-(-car.xPos)), 'block', globals.flow.block,
                                    'condtime', r3(helpers.conditionTime()), 'time', r3(helpers.currentTime())], True)
Пример #13
0
    def updatePosition(self, dt):

        if self.autoPilot:
            x = self.xPos
            xnew = x - globals.kphToMps(90.0) * dt
            (xl, zl, heading, hx,
             hz) = self.road.getLanePosition(xnew, globals.LEFT_LANE)
            self.xPos = xnew
            self.zPos = zl
            self.xHeading = hx
            self.zHeading = hz
        else:
            self.prevRoadPos = self.getRoadPosition()  #self.zPos
            roadPos = self.prevRoadPos

            self.updateAcceleration()
            self.updateBreaking()

            self.collisionCooldown = max(0.0, self.collisionCooldown - dt)
            self.blinkerCooldown = max(0.0, self.blinkerCooldown - dt)
            self.blinkerPracWarning = max(0.0, self.blinkerPracWarning - dt)

            self.traffic.calcPassingStates(self)

            # Hit a fast moving car (left lane)
            (idx, collisionId,
             collisionZone) = self.traffic.foundFastCollisions(self)
            if collisionId >= 0:

                if self.collisionCooldown < 0.001:
                    self.collisionCooldown = 1.0

                    self.traffic.removeFastCar(idx)

                    self.incrementDamage()
                    globals.db['collision'].addData([
                        'pp', globals.participant, 'condition',
                        globals.flow.getCondition(), 'zone', collisionZone,
                        'carType', 'fast', 'block', block, 'carNum',
                        collisionId, 'condtime',
                        r3(helpers.conditionTime()), 'time',
                        r3(helpers.currentTime())
                    ], True)

                    if globals.debug:
                        print 'Collision detected with fast car [' + str(
                            idx) + ', zone: ' + str(collisionZone) + ']'

            # hit a slow moving car (right lane)
            (idx, collisionId,
             collisionZone) = self.traffic.foundSlowCollisions(self)
            if collisionId >= 0:

                if collisionZone == FRONT:

                    mul = 0.9
                    self.xVelocity = min(self.xVelocity * mul,
                                         self.traffic.staticSpeed * mul)
                    self.zVelocity = min(self.zVelocity * mul,
                                         self.traffic.staticSpeed * mul)

                else:  # BACK
                    bumpspeed = self.traffic.staticSpeed
                    ratio = bumpspeed / self.currentSpeed
                    self.xVelocity *= ratio * 1.2
                    self.zVelocity *= ratio * 1.2

                    self.currentSpeed = self.lenVector(self.xVelocity,
                                                       self.zVelocity)
                    self.xPos -= self.xVelocity * dt
                    self.zPos -= self.zVelocity * dt

                if self.collisionCooldown < 0.001:
                    #print 'boem! '+str(collisionZone)
                    self.collisionCooldown = 1.0
                    self.incrementDamage()
                    globals.db['collision'].addData([
                        'pp', globals.participant, 'condition',
                        globals.flow.getCondition(), 'zone', collisionZone,
                        'carType', 'slow', 'block', block, 'carNum',
                        collisionId, 'condtime',
                        r3(helpers.conditionTime()), 'time',
                        r3(helpers.currentTime())
                    ], True)

                    if globals.debug:
                        print 'Collision detected with slow car [' + str(
                            idx) + ', zone: ' + str(collisionZone) + ']'

                roadPos = self.getRoadPosition()

            else:
                dotProd = sum(
                    map(operator.mul, (self.xHeading, self.zHeading),
                        (self.xVelocity, self.zVelocity)))
                #print dotProd
                xLatVel = self.xHeading * dotProd
                zLatVel = self.zHeading * dotProd

                xLatFric = 0  #-xLatVel*self.latFricFactor
                zLatFric = 0  #-zLatVel*self.latFricFactor
                xBackFric = -self.xVelocity * self.backFricFactor
                zBackFric = -self.zVelocity * self.backFricFactor

                #print xLatFric
                self.xVelocity += (xBackFric + xLatFric) * dt
                self.zVelocity += (zBackFric + zLatFric) * dt

                #print self.xVelocity

                dm = self.currentSpeed * dt
                self.currentSpeed = self.lenVector(self.xVelocity,
                                                   self.zVelocity)
                if self.currentSpeed < globals.MAX_SPEED:
                    self.xVelocity += self.xAccel * dt
                    self.zVelocity += self.zAccel * dt
                    self.xVelocity *= self.breakPower
                    self.zVelocity *= self.breakPower
                    #self.xVelocity = max(0.0001*self.xVelocity, self.xVelocity - self.xBreak * dt)
                    #self.zVelocity = max(0.0001*self.zVelocity, self.zVelocity - self.zBreak * dt)

                self.xPos -= self.xVelocity * dt
                self.zPos -= self.zVelocity * dt
                #self.xPos -= self.xHeading*dm
                #self.zPos -= self.zHeading*dm

                vHx = self.currentSpeed * self.xHeading
                vHz = self.currentSpeed * self.zHeading

                latFactor = 0.2
                (x, z) = self.lerpVectors(vHx, vHz, self.xVelocity,
                                          self.zVelocity, latFactor)
                self.xVelocity = x
                self.zVelocity = z

                self.angleHeading = (atan2(self.xVelocity, self.zVelocity) -
                                     atan2(1.0, 0.0)) * globals.RAD2DEG

                roadPos = self.getRoadPosition()

            if self.prevRoadPos <= 0.0 and roadPos > 0.0:  # left lane transition
                if globals.flow.drivingCondition == 'complex':
                    (cid, x) = self.traffic.findNextStaticCar(self)
                    dist = x - (-self.xPos)

                    self.laneCrossDist = dist

                    if globals.debug:
                        print 'Lane transition to left lane at ' + str(
                            -self.xPos
                        ) + '. Distance to next static car (' + str(
                            cid) + '): ' + str(dist)
                else:
                    if globals.debug:
                        print 'Lane transition to left lane at ' + str(
                            -self.xPos)

                self.checkBlinkerUse('L')

            elif self.prevRoadPos >= 0.0 and roadPos < 0.0:  #right lane transition
                if globals.debug:
                    print 'Lane transition to right lane at ' + str(-self.xPos)

                self.checkBlinkerUse('R')

        self.testRumbleStrip()

        if self.isOffRoad():
            self.offroadTime += dt

        if self.offroadTime >= 1.0:
            globals.bonusCounter = max(
                0.0, globals.bonusCounter - globals.OFFROAD_PENALTY)
            self.offroadTime = 0.0

        # See if we're next to a car we're overtaking
        self.inSafeZone = False
        if self.traffic.recentPassedCar + 1 < len(self.traffic.staticCars):
            try:
                nextx = self.traffic.staticCars[self.traffic.recentPassedCar +
                                                1].x
            except IndexError:
                nextx = -1

            if nextx > 0.0:
                #print 'next: '+str(nextx)+' car: '+str(self.xPos)
                d = abs(nextx - -self.xPos)
                #print 'distance to next car: '+str(d)
                if (d < 6.0 and self.prevRoadPos > 0.1) or d < -1.0:
                    #print 'safe!'
                    self.inSafeZone = True
Пример #14
0
    def measureData(self, car, traffic, dt):

        if self.flowIdx < len(self.flow) and self.flow[self.flowIdx].type == 'drive':
            # get all the car measurements
            laneDeviation = car.getLaneDeviation()
            roadPos = car.getRoadPosition()
            wheelAngle = car.currentWheelAngle
            speed = (car.currentSpeed * 3600) * 0.001
            acceleration = car.accelerationInput
            breaking = car.breakInput
            xpos = car.xPos

            globals.db['car'].addData(['pp', globals.participant, 'condition', self.getCondition(), 'deviation', r3(laneDeviation), 'yposition', r3(roadPos),
                            'speed', r3(speed), 'wheelangle', r3(wheelAngle), 'accel', r3(acceleration), 'break', r3(breaking),
                            'xposition', r3(xpos), 'block', self.block, 'condtime', r3(helpers.conditionTime()), 'time', r3(helpers.currentTime())], True)

            traffic.reportNearbyStaticCars(car)
            traffic.reportNearbyFastCars(car)
Пример #15
0
    def startNextState(self, car, traffic, renderer):

        state = self.flow[self.flowIdx]

        if state.type == 'screen':
            renderer.textScreens[self.flow[self.flowIdx].id].start()

        elif state.type == 'drive':
            self.block += 1
            self.blockDuration = state.duration

            # reset damage counter after practice
            if self.doPractice and self.block == 2:
                globals.bonusCounter = globals.STARTING_BONUS
                self.radioTask.doPractice = False
                self.tabletTask.doPractice = False

            print '\n########\nSTARTING BLOCK '+str(self.block-1)+'\n########\n'+state.id+' & '+state.secondary+', length: '+str(self.blockDuration)
            print 'Current bonus: '+str(globals.bonusCounter/10.0)

            # set up databases for driving
            globals.db['blinker'] = DataCollector('Blinker DB', 'data/'+globals.participant+'_'+self.getCondition()+'_blinker.dat',
                                            ['pp', 'condition', 'direction', 'block', 'condtime', 'time'])
            globals.db['lanetransition'] = DataCollector('Lane Transitions DB', 'data/'+globals.participant+'_'+self.getCondition()+'_transition.dat',
                                            ['pp', 'condition', 'blinkerused', 'blinkdir', 'cardir', 'congruent', 'block', 'condtime', 'time'])
            globals.db['overtake'] = DataCollector('Overtaken Slow Traffic DB', 'data/'+globals.participant+'_'+self.getCondition()+'_overtake.dat',
                                            ['pp', 'condition', 'state', 'carNum', 'carDist', 'block', 'condtime', 'time'])
            globals.db['collision'] = DataCollector('Collision DB', 'data/'+globals.participant+'_'+self.getCondition()+'_collision.dat',
                                            ['pp', 'condition', 'zone', 'carType', 'carNum', 'block', 'condtime', 'time'])
            globals.db['car'] = DataCollector('Car DB', 'data/'+globals.participant+'_'+self.getCondition()+'_car.dat', ['pp', 'condition',
                                        'speed', 'wheelangle', 'yposition', 'deviation', 'accel', 'break', 'xposition', 'block', 'condtime', 'time'])
            globals.db['slowcars'] = DataCollector('Slow Car DB', 'data/'+globals.participant+'_'+self.getCondition()+'_slowcars.dat', ['pp', 'condition',
                                        'id', 'speed', 'xposition', 'distance', 'block', 'condtime', 'time'])
            globals.db['fastcars'] = DataCollector('Fast Car DB', 'data/'+globals.participant+'_'+self.getCondition()+'_fastcars.dat', ['pp', 'condition',
                                        'id', 'speed', 'xposition', 'distance', 'block', 'condtime', 'time'])
            globals.db['blinker'].open()
            globals.db['lanetransition'].open()
            globals.db['car'].open()
            globals.db['overtake'].open()
            globals.db['collision'].open()
            globals.db['slowcars'].open()
            globals.db['fastcars'].open()

            # traffic.road = self.roads[self.block]
            # car.bindRoad(self.roads[self.block])

            traffic.reset(self.roads[self.block])
            car.reset(self.roads[self.block])

            # populate road with traffic
            if state.id == 'complex':
                sDiff = abs(globals.EXPECTED_SPEED - globals.SLOW_SPEED)
                dist = sDiff * globals.DRIVE_DURATION
                overtakes = globals.COMPLEX_OVERTAKES
                duration = globals.DRIVE_DURATION

                if doPractice and block < 2: # practice blocks
                    duration = globals.PRACTICE_DURATION
                    overtakes = globals.PRACTICE_OVERTAKES

                interval = dist / overtakes
                #print interval
                #interval = 20.0
                print 'Generating complex traffic'
                traffic.genStaticCars(overtakes, globals.EXPECTED_SPEED, globals.SLOW_SPEED, duration, globals.RIGHT_LANE)
            else:
                sDiff = abs(globals.EXPECTED_SPEED - globals.FAST_SPEED)
                dist = sDiff * globals.DRIVE_DURATION
                interval = dist / globals.SIMPLE_OVERTAKERS
                #print interval
                print 'Generating simple traffic'
                traffic.genStaticCars(globals.SIMPLE_OVERTAKERS, globals.EXPECTED_SPEED, globals.FAST_SPEED, globals.DRIVE_DURATION, globals.LEFT_LANE)

            if state.secondary != 'none':
                print 'Starting secondary task'
                if state.secondary == 'tablet':
                    print 'Tablet task selected'
                    self.secondary = self.tabletTask
                else:
                    print 'Radio task selected'
                    self.secondary = self.radioTask

                if (not self.doPractice or (self.block > 1)) and state.secondary != 'easy':
                    print 'Loading hard task conditions (quiz or tablet)'

                    curShow = 0

                    if self.fixedOrder:
                        print 'Quiz show order fixed on participant ID'
                        ppid = globals.participant.split('D') # names have the form SDXX or CDXX with XX between 01 and 24

                        even = False
                        if len(ppid) > 1:
                            ppidx = int(ppid[1])
                            if (ppidx % 2) == 0:
                                even = True

                        if even:
                            if state.secondary == 'tablet':
                                curShow = 0
                            else:
                                curShow = 1
                        else: # odd
                            if state.secondary == 'tablet':
                                curShow = 1
                            else:
                                curShow = 0

                    else:
                        print 'Picking quiz show randomly'
                        # pick a show
                        idx = random.sample(range(0,len(self.shows)), 1)[0]
                        curShow = self.shows[idx]

                        del self.shows[idx]

                    print 'Playing show '+str(curShow)
                    self.secondary.setConversation(curShow)

                self.secondary.startTask(state.secondary, state.id)

            print 'Beginning driving section'

            globals.conditionStartTime = helpers.currentTime()
Пример #16
0
    def updatePosition(self, dt):

        if self.autoPilot:
            x = self.xPos
            xnew = x-globals.kphToMps(90.0)*dt
            (xl, zl, heading, hx, hz) = self.road.getLanePosition(xnew, globals.LEFT_LANE)
            self.xPos = xnew
            self.zPos = zl
            self.xHeading = hx
            self.zHeading = hz
        else:
            self.prevRoadPos = self.getRoadPosition() #self.zPos
            roadPos = self.prevRoadPos

            self.updateAcceleration()
            self.updateBreaking()

            self.collisionCooldown = max(0.0, self.collisionCooldown - dt)
            self.blinkerCooldown = max(0.0, self.blinkerCooldown - dt)
            self.blinkerPracWarning = max(0.0, self.blinkerPracWarning - dt)

            self.traffic.calcPassingStates(self)

            # Hit a fast moving car (left lane)
            (idx, collisionId, collisionZone) = self.traffic.foundFastCollisions(self)
            if collisionId >= 0:

                if self.collisionCooldown < 0.001:
                    self.collisionCooldown = 1.0

                    self.traffic.removeFastCar(idx)

                    self.incrementDamage()
                    globals.db['collision'].addData(['pp', globals.participant, 'condition', globals.flow.getCondition(), 'zone', collisionZone, 'carType', 'fast',  'block', block,
                                        'carNum', collisionId ,'condtime', r3(helpers.conditionTime()), 'time', r3(helpers.currentTime())], True)

                    if globals.debug: print 'Collision detected with fast car ['+str(idx)+', zone: '+str(collisionZone)+']'

            # hit a slow moving car (right lane)
            (idx, collisionId, collisionZone) = self.traffic.foundSlowCollisions(self)
            if collisionId >= 0:

                if collisionZone == FRONT:

                    mul = 0.9
                    self.xVelocity = min(self.xVelocity*mul, self.traffic.staticSpeed*mul)
                    self.zVelocity = min(self.zVelocity*mul, self.traffic.staticSpeed*mul)

                else: # BACK
                    bumpspeed = self.traffic.staticSpeed
                    ratio = bumpspeed / self.currentSpeed
                    self.xVelocity *= ratio*1.2
                    self.zVelocity *= ratio*1.2

                    self.currentSpeed = self.lenVector(self.xVelocity, self.zVelocity)
                    self.xPos -= self.xVelocity*dt
                    self.zPos -= self.zVelocity*dt

                if self.collisionCooldown < 0.001:
                    #print 'boem! '+str(collisionZone)
                    self.collisionCooldown = 1.0
                    self.incrementDamage()
                    globals.db['collision'].addData(['pp', globals.participant, 'condition', globals.flow.getCondition(), 'zone', collisionZone, 'carType', 'slow',  'block', block,
                                        'carNum', collisionId ,'condtime', r3(helpers.conditionTime()), 'time', r3(helpers.currentTime())], True)

                    if globals.debug: print 'Collision detected with slow car ['+str(idx)+', zone: '+str(collisionZone)+']'

                roadPos = self.getRoadPosition()

            else:
                dotProd = sum(map( operator.mul, (self.xHeading, self.zHeading), (self.xVelocity, self.zVelocity)))
                #print dotProd
                xLatVel = self.xHeading * dotProd
                zLatVel = self.zHeading * dotProd

                xLatFric = 0#-xLatVel*self.latFricFactor
                zLatFric = 0#-zLatVel*self.latFricFactor
                xBackFric = -self.xVelocity*self.backFricFactor
                zBackFric = -self.zVelocity*self.backFricFactor

                #print xLatFric
                self.xVelocity += (xBackFric + xLatFric) * dt
                self.zVelocity += (zBackFric + zLatFric) * dt

                #print self.xVelocity

                dm = self.currentSpeed*dt
                self.currentSpeed = self.lenVector(self.xVelocity, self.zVelocity)
                if self.currentSpeed < globals.MAX_SPEED:
                    self.xVelocity += self.xAccel * dt
                    self.zVelocity += self.zAccel * dt
                    self.xVelocity *= self.breakPower
                    self.zVelocity *= self.breakPower
                    #self.xVelocity = max(0.0001*self.xVelocity, self.xVelocity - self.xBreak * dt)
                    #self.zVelocity = max(0.0001*self.zVelocity, self.zVelocity - self.zBreak * dt)

                self.xPos -= self.xVelocity*dt
                self.zPos -= self.zVelocity*dt
                #self.xPos -= self.xHeading*dm
                #self.zPos -= self.zHeading*dm

                vHx = self.currentSpeed*self.xHeading
                vHz = self.currentSpeed*self.zHeading

                latFactor = 0.2
                (x,z) = self.lerpVectors(vHx, vHz, self.xVelocity, self.zVelocity, latFactor)
                self.xVelocity = x
                self.zVelocity  = z

                self.angleHeading = (atan2(self.xVelocity, self.zVelocity) - atan2(1.0, 0.0))*globals.RAD2DEG

                roadPos = self.getRoadPosition()

            if self.prevRoadPos <= 0.0 and roadPos > 0.0: # left lane transition
                if globals.flow.drivingCondition == 'complex':
                    (cid, x) = self.traffic.findNextStaticCar(self)
                    dist = x - (-self.xPos)

                    self.laneCrossDist = dist

                    if globals.debug: print 'Lane transition to left lane at ' + str(-self.xPos) + '. Distance to next static car ('+str(cid)+'): '+str(dist)
                else:
                    if globals.debug: print 'Lane transition to left lane at ' + str(-self.xPos)

                self.checkBlinkerUse('L')

            elif self.prevRoadPos >= 0.0 and roadPos < 0.0: #right lane transition
                if globals.debug: print 'Lane transition to right lane at ' + str(-self.xPos)

                self.checkBlinkerUse('R')

        self.testRumbleStrip()

        if self.isOffRoad():
            self.offroadTime += dt

        if self.offroadTime >= 1.0:
            globals.bonusCounter = max(0.0, globals.bonusCounter - globals.OFFROAD_PENALTY)
            self.offroadTime = 0.0

        # See if we're next to a car we're overtaking
        self.inSafeZone = False
        if self.traffic.recentPassedCar+1 < len(self.traffic.staticCars):
            try:
                nextx = self.traffic.staticCars[self.traffic.recentPassedCar+1].x
            except IndexError:
                nextx = -1

            if nextx > 0.0:
                #print 'next: '+str(nextx)+' car: '+str(self.xPos)
                d = abs(nextx - -self.xPos)
                #print 'distance to next car: '+str(d)
                if (d < 6.0 and self.prevRoadPos > 0.1) or d < -1.0:
                    #print 'safe!'
                    self.inSafeZone = True