-
Notifications
You must be signed in to change notification settings - Fork 0
/
scenario.ls
2169 lines (1793 loc) · 55.4 KB
/
scenario.ls
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
P = require 'bluebird'
Co = P.coroutine
$ = require 'jquery'
seqr = require './seqr.ls'
{addGround, Scene} = require './scene.ls'
{addVehicle} = require './vehicle.ls'
{NonSteeringControl} = require './controls.ls'
{DefaultEngineSound, BellPlayer, NoisePlayer} = require './sounds.ls'
assets = require './assets.ls'
prelude = require 'prelude-ls'
ui = require './ui.ls'
exportScenario = (name, impl) ->
scn = seqr.bind impl
scn.scenarioName = name
module.exports[name] = scn
return scn
DummyScene = ->
beforePhysics: Signal!
afterPhysics: Signal!
beforeRender: Signal!
onRender: Signal!
onStart: Signal!
onExit: Signal!
onTickHandled: Signal!
#camera: new THREE.PerspectiveCamera!
camera:
updateProjectionMatrix: ->
add: ->
#visual: new THREE.Scene!
visual:
add: ->
traverse: ->
addEventListener: ->
physics:
add: ->
addEventListener: ->
removeBody: ->
preroll: ->
tick: ->
bindPhys: ->
#Scene = DummyScene
export baseScene = seqr.bind (env) ->*
{controls, audioContext, L} = env
scene = new Scene
yield P.resolve addGround scene
sky = yield P.resolve assets.addSky scene
scene.playerControls = controls
player = yield addVehicle scene, controls, objectName: 'player'
player.eye.add scene.camera
player.physical.position.x = -1.75
scene.player = player
scene.player.speedometer = ui.gauge env,
name: L "Speed"
unit: L "km/h"
value: ->
speed = scene.player.getSpeed()*3.6
Math.round speed
engineSounds = yield DefaultEngineSound audioContext
gainNode = audioContext.createGain()
gainNode.connect audioContext.destination
engineSounds.connect gainNode
scene.afterPhysics.add ->
rev = Math.abs(player.getSpeed())/(200/3.6)
rev = Math.max 0.1, rev
rev = (rev + 0.1)/1.1
gain = scene.playerControls.throttle
gain = (gain + 0.5)/1.5
gainNode.gain.value = gain
engineSounds.setPitch rev*2000
scene.onStart.add engineSounds.start
scene.onExit.add engineSounds.stop
scene.preroll = ->
# Tick a couple of frames for the physics to settle
scene.tick 1/60
n = 100
t = Date.now()
for [0 to n]
scene.tick 1/60
console.log "Prewarming FPS", (n/(Date.now() - t)*1000)
return scene
export minimalScenario = seqr.bind (env) ->*
scene = new Scene
addGround scene
scene.preroll = ->
@let \scene, scene
yield @get \done
exportScenario \freeDriving, (env) ->*
# Load the base scene
scene = yield baseScene env
# The scene would be customized here
# "Return" the scene to the caller, so they know
# we are ready
@let \scene, scene
# Run until somebody says "done".
yield @get \done
export basePedalScene = (env) ->
env = env with
controls: NonSteeringControl env.controls
return baseScene env
catchthething = require './catchthething.ls'
addReactionTest = seqr.bind (scene, env) ->*
react = yield catchthething.React()
screen = yield assets.SceneDisplay()
screen.object.position.z = -0.3
screen.object.scale.set 0.12, 0.12, 0.12
screen.object.visible = false
#screen.object.position.y = 2
#screen.object.rotation.y = Math.PI
scene.camera.add screen.object
env.controls.change (btn, isOn) !->
if btn == "catch" and isOn and screen.object.visible
react.catch()
else if btn == "blinder"
screen.object.visible = isOn
react.event (type) ->
env.logger.write reactionGameEvent: type
scene.onRender.add (dt) ->
react.tick dt
env.renderer.render react.scene, react.camera, screen.renderTarget, true
#env.renderer.render react.scene, react.camera
return react
addBlinder = (scene, env) ->
mask = new THREE.Mesh do
new THREE.PlaneGeometry 0.1*16/9, 0.1
new THREE.MeshBasicMaterial color: 0x000000
mask.position.z = -0.3
mask.position.x = 0.03
mask.position.y = -0.03
scene.camera.add mask
self =
change: Signal!
glances: 0
self._showMask = showMask = ->
return if mask.visible
mask.visible = true
self.change.dispatch true
env.logger.write blinder: true
self._showMask()
self._liftMask = ->
mask.visible = false
self.glances += 1
self.change.dispatch false
env.logger.write blinder: false
setTimeout showMask, 300
return self
addBlinderTask = (scene, env) ->
self = addBlinder(scene, env)
ui.gauge env,
name: env.L "Glances"
unit: ""
value: ->
self.glances
env.controls.change (btn, isOn) ->
return if btn != 'blinder'
return if isOn != true
self._liftMask()
return self
addForcedBlinderTask = (scene, env, {interval=2}={}) ->
self = addBlinder(scene, env)
id = setInterval self~_liftMask, interval*1000
env.finally ->
clearInterval id
return self
exportScenario \runTheLight, (env) ->*
@let \intro,
title: env.L "Run the light"
subtitle: env.L "(Just this once)"
content: $ env.L "%runTheLight.intro"
scene = yield basePedalScene env
startLight = yield assets.TrafficLight()
startLight.position.x = -4
startLight.position.z = 6
startLight.addTo scene
@let \scene, scene
yield @get \run
scene.player.onCollision (e) ~>
@let \done, passed: true, outro:
title: env.L "Passed"
content: env.L '%runTheLight.outro'
return yield @get \done
collisionReason = ({L}, e) ->
switch (e.body.objectClass)
| 'traffic-light' => L "You ran the red light!"
| 'stop-sign' => L "You ran the stop sign!"
| otherwise => L "You crashed!"
failOnCollision = (env, scn, scene) ->
scene.player.onCollision (e) ->
reason = collisionReason env, e
scn.let \done, passed: false, outro:
title: env.L "Oops!"
content: reason
env.logger.write playerVehicleCollision:
collisionTarget: e.body.objectClass
return false
exportScenario \closeTheGap, (env) ->*
@let \intro,
title: env.L "Close the gap"
content: env.L '%closeTheGap.intro'
scene = yield basePedalScene env
leader = yield addVehicle scene
leader.physical.position.x = scene.player.physical.position.x
leader.physical.position.z = 100
failOnCollision env, @, scene
@let \scene, scene
yield @get \run
distanceToLeader = ->
rawDist = scene.player.physical.position.distanceTo leader.physical.position
return rawDist - scene.player.physical.boundingRadius - leader.physical.boundingRadius
env.controls.change (btn, isOn) !~>
return unless btn == 'catch' and isOn
distance = distanceToLeader!
distance += 1.47 # HACK!
@let \done, passed: true, outro:
title: env.L "Passed"
content: env.L "%closeTheGap.outro", distance: distance
return false
return yield @get \done
exportScenario \throttleAndBrake, (env) ->*
L = env.L
@let \intro,
title: L "Throttle and brake"
content: L '%throttleAndBrake.intro'
scene = yield basePedalScene env
goalDistance = 200
startLight = yield assets.TrafficLight()
startLight.position.x = -4
startLight.position.z = 6
startLight.addTo scene
stopSign = yield assets.StopSign!
..position.x = -4
..position.z = goalDistance + 10
..addTo scene
failOnCollision env, @, scene
finishSign = yield assets.FinishSign!
finishSign.position.z = goalDistance
finishSign.addTo scene
ui.gauge env,
name: L "Time"
unit: L "s"
value: ->
if not startTime?
return 0.toFixed 2
(scene.time - startTime).toFixed 2
@let \scene, scene
yield @get \run
yield P.delay 2000
yield startLight.switchToGreen()
startTime = scene.time
finishSign.bodyPassed(scene.player.physical).then ~> scene.onTickHandled ~>
return if Math.abs(scene.player.getSpeed()) > 0.1
time = scene.time - startTime
@let \done, passed: true, outro:
title: L "Passed"
content: L '%throttleAndBrake.outro', time: time
return false
return yield @get \done
speedControl = exportScenario \speedControl, (env) ->*
L = env.L
@let \intro,
title: L "Speed control"
content: L "%speedControl.intro"
scene = yield basePedalScene env
limits = [
[-Infinity, 50]
[20, 50]
[200, 30]
[250, 80]
[500, 60]
]
goalDistance = 700
for [dist, limit] in limits
sign = yield assets.SpeedSign limit
sign.position.z = dist
sign.position.x = -4
scene.visual.add sign
limits.reverse()
currentLimit = ->
mypos = scene.player.physical.position.z
for [distance, limit] in limits
break if distance < mypos
return limit
limitSign = ui.gauge env,
name: L "Speed limit"
unit: L "km/h"
value: currentLimit
illGainsMultiplier = 10
illGains = 0
timePenalty = 0
scene.afterPhysics (dt) ->
return if not startTime?
limit = currentLimit!
speed = Math.abs scene.player.getSpeed()*3.6
if speed <= limit
limitSign.normal()
return
limitSign.warning()
traveled = (speed/3.6)*dt
legalMinTime = traveled/(limit/3.6)
timeGained = legalMinTime - dt
illGains += timeGained
timePenalty := illGains*illGainsMultiplier
ui.gauge env,
name: L "Penalty"
unit: "s"
value: ->
timePenalty.toFixed 2
startLight = yield assets.TrafficLight()
startLight.position.x = -4
startLight.position.z = 6
startLight.addTo scene
stopSign = yield assets.StopSign!
..position.x = -4
..position.z = goalDistance + 10
..addTo scene
failOnCollision env, @, scene
scene.player.onCollision (e) ~>
@let \done, passed: false, outro:
title: L "Oops!"
content: L "You ran the red light!"
return false
finishSign = yield assets.FinishSign!
finishSign.position.z = goalDistance
finishSign.addTo scene
@let \scene, scene
yield @get \run
yield P.delay 1000
yield startLight.switchToGreen()
startTime = scene.time
finishSign.bodyPassed(scene.player.physical).then ~> scene.onTickHandled ~>
return if Math.abs(scene.player.getSpeed()) > 0.1
time = scene.time - startTime
@let \done, passed: true, outro:
title: L "Passed"
content: L '%speedControl.outro', time: time, timePenalty: timePenalty
return false
return yield @get \done
exportScenario \blindSpeedControl, (env) ->*
L = env.L
base = speedControl env
intro = yield base.get \intro
@let \intro,
title: L "Anticipatory speed control"
content: L '%blindSpeedControl.intro'
scene = yield base.get \scene
addBlinderTask scene, env
@let \scene, scene
yield @get \run
base.let \run
result = yield base.get \done
@let \done, result
return result
{IdmVehicle, LoopMicrosim} = require './microsim.ls'
class MicrosimWrapper
(@phys) ->
position:~->
@phys.position.z
velocity:~->
@phys.velocity.z
acceleration:~-> null
step: ->
{knuthShuffle: shuffleArray} = require 'knuth-shuffle'
{TargetSpeedController2, linearTargetSpeedController} = require './controls.ls'
inTraffic = exportScenario \inTraffic, (env) ->*
L = env.L
@let \intro,
title: L "Driving in traffic"
content: $ L "%inTraffic.intro"
scene = yield basePedalScene env
scene.player.onCollision (e) ~>
reason = L "You crashed!"
@let \done, passed: false, outro:
title: L "Oops!"
content: reason
return false
scene.afterPhysics.add (dt) !->
return if not startTime?
leaderControls = new TargetSpeedController2
leader = yield addVehicle scene, leaderControls
leader.physical.position.x = -1.75
leader.physical.position.z = 10
speeds = [10,0,30,0,50,0,80,0]
speeds = [s/3.6 for s in speeds]
stayOnSpeedTarget = 15
stayOnZeroTarget = 8
stayOnTarget = stayOnSpeedTarget
timeOnTarget = 0
scene.afterPhysics.add (dt) !~>
#console.log 'speed diff' (Math.abs(speeds[0] - leader.physical.velocity.z))
#console.log 'tot' timeOnTarget, speeds.length
if (Math.abs(speeds[0] - leader.physical.velocity.z)) < 1.0
timeOnTarget += dt
if timeOnTarget >= stayOnTarget and speeds.length >= 1
speeds := speeds.slice(1)
timeOnTarget := 0
if speeds[0] == 0
stayOnTarget := stayOnZeroTarget
else
stayOnTarget := stayOnSpeedTarget
env.logger.write changeLimit: speeds[0]
if speeds.length == 0
@let \done, passed: true, outro:
title: L "Passed!"
content: L '%inTraffic.outro'
return false
leaderControls.target = speeds[0]
leaderControls.tick leader.getSpeed(), dt
headway =
cumulative: 0
time: 0
average: ->
@cumulative/@time
cumHeadway = 0
averageHeadway = 0
scene.afterPhysics (dt) ->
return if not startTime?
headway.cumulative += dt*distanceToLeader!
headway.time += dt
distanceToLeader = ->
rawDist = scene.player.physical.position.distanceTo leader.physical.position
return rawDist - scene.player.physical.boundingRadius - leader.physical.boundingRadius
@let \scene, scene
yield @get \run
yield P.delay 1000
startTime = scene.time
return yield @get \done
{rnorm} = require 'randgen'
easyRider = exportScenario \easyRider, (env, {sequence, acceleration, currentSegment, segmentNro}={}) ->*
L = env.L
@let \intro,
title: L "Easy Rider"
content: $ L "%easyRider.intro", currentSegment: currentSegment+1, segmentNro: segmentNro
scene = yield basePedalScene env
scene.player.onCollision (e) ~>
reason = L "You crashed!"
@let \done, passed: false, outro:
title: L "Oops!"
content: reason
return false
scene.afterPhysics.add (dt) !->
return if not startTime?
leaderControls = new linearTargetSpeedController
leader = yield addVehicle scene, leaderControls
leader.physical.position.x = -1.75
leader.physical.position.z = 100 #10
blockinfo =
blockSequence: sequence
currentSegment: currentSegment
blockAccelerationParams: acceleration
env.logger.write blockinfo
speeds = [s/3.6 for s in sequence]
stayOnSpeedTarget = 20
stayOnZeroTarget = 5
speedTargetSigma = 10
zeroTargetSigma = 4
smoothTarget = 0
stayOnTarget = stayOnSpeedTarget
timeOnTarget = 0
freeToGo = false
approach = true
env.logger.write changeLimit: speeds[0]
scene.afterPhysics.add (dt) !~>
if speeds[0] == 0
if scene.player.physical.velocity.z <= 0
freeToGo := true
timeOnTarget += dt
else
freeToGo := false
else if (Math.abs(speeds[0] - leader.physical.velocity.z)) < 1.0
timeOnTarget += dt
freeToGo := true
else
freeToGo := true
if timeOnTarget >= stayOnTarget and sequence.length >= 1 and freeToGo
speeds := speeds.slice(1)
acceleration := acceleration.slice(1)
timeOnTarget := 0
if speeds[0] == 0
error = zeroTargetSigma * Math.random! - (zeroTargetSigma/2)
stayOnTarget := stayOnZeroTarget + error
#stayOnTarget := zeroTargetSigma * rnorm(0, 0.5) + stayOnZeroTarget
else
error = speedTargetSigma * Math.random! - (speedTargetSigma/2)
stayOnTarget := stayOnSpeedTarget + error
#stayOnTarget := speedTargetSigma * rnorm(0, 0.5) + stayOnSpeedTarget
speedinfo =
changeLimit: speeds[0]
changeAccel: acceleration[0]
stayOnLimit: stayOnTarget
env.logger.write speedinfo
#console.log 'go' , freeToGo
#console.log 'time target', stayOnTarget
if speeds.length == 0
@let \done, passed: true, outro:
title: L "Passed!"
content: L '%easyRider.outro'
return false
dist = scene.player.physical.position.distanceTo leader.physical.position
dist = dist - scene.player.physical.boundingRadius - leader.physical.boundingRadius
if approach and (dist > 30)
leaderControls.target = 0
else
leaderControls.target = speeds[0]
approach := false
#leaderControls.accelParams = acceleration[0]
leaderControls.targetAccelMs = acceleration[0]
leaderControls.environment = env
leaderControls.tick leader.getSpeed(), dt
headway =
cumulative: 0
time: 0
average: ->
@cumulative/@time
cumHeadway = 0
averageHeadway = 0
scene.afterPhysics (dt) ->
return if not startTime?
headway.cumulative += dt*distanceToLeader!
headway.time += dt
distanceToLeader = ->
rawDist = scene.player.physical.position.distanceTo leader.physical.position
return rawDist - scene.player.physical.boundingRadius - leader.physical.boundingRadius
scene.player.speedometer.el.hide()
@let \scene, scene
yield @get \run
yield P.delay 1000
startTime = scene.time
return yield @get \done
{TargetSpeedController} = require './controls.ls'
followInTraffic = exportScenario \followInTraffic, (env, {distance=2000}={}) ->*
L = env.L
@let \intro,
title: L "Supermiler"
content: $ L "%followInTraffic.intro"
scene = yield basePedalScene env
#addReactionTest scene, env
#addBlinderTask scene, env
startLight = yield assets.TrafficLight()
startLight.position.x = -4
startLight.position.z = 6
startLight.addTo scene
goalDistance = distance
finishSign = yield assets.FinishSign!
finishSign.position.z = goalDistance
finishSign.addTo scene
finishSign.visual.visible = false
scene.player.onCollision (e) ~>
reason = L "You crashed!"
if e.body.objectClass == "traffic-light"
reason = L "You ran the red light!"
@let \done, passed: false, outro:
title: L "Oops!"
content: reason
return false
maximumFuelFlow = 200/60/1000
constantConsumption = maximumFuelFlow*0.1
draftingCoeff = (d) ->
# Estimated from Mythbusters!
Math.exp(0) - Math.exp(-(d + 5.6)*0.1)
consumption =
time: 0
distance: 0
instant: 0
total: 0
noDraftTotal: 0
avgLitersPer100km: (consumption=@total) ->
metersPerLiter = @distance/consumption
1.0/metersPerLiter*1000*100
instLitersPer100km: ->
metersPerLiter = Math.abs(scene.player.getSpeed())/@instant
1.0/metersPerLiter*1000*100
scene.afterPhysics.add (dt) !->
return if not startTime?
consumption.time += dt
consumption.distance += dt*Math.abs(scene.player.getSpeed())
instant = env.controls.throttle*maximumFuelFlow + constantConsumption
consumption.instant = instant * draftingCoeff(distanceToLeader!)
consumption.total += consumption.instant*dt
consumption.noDraftTotal += instant*dt
ui.gauge env,
name: L "Current consumption"
unit: "l/100km"
range: [0, 30]
format: (v) ->
if Math.abs(scene.player.getSpeed()) < 1.0
return null
return v.toFixed 2
value: ->
c = consumption.instLitersPer100km!
return c
ui.gauge env,
name: L "Average consumption"
unit: "l/100km"
range: [0, 30]
format: (v) ->
return null if consumption.distance < 1
return v.toFixed 2
value: ->
return consumption.avgLitersPer100km!
/*nVehicles = 20
spacePerVehicle = 20
traffic = new LoopMicrosim nVehicles*spacePerVehicle
for i in [1 til nVehicles]
v = new IdmVehicle do
a: 4.0
b: 10.0
timeHeadway: 1.0
v.position = i*spacePerVehicle
traffic.addVehicle v
scene.beforePhysics.add traffic~step
scene.traffic = traffic
playerSim = new MicrosimWrapper scene.player.physical
traffic.addVehicle playerSim
leader = yield addVehicle scene
leader.physical.position.z = playerSim.leader.position
leader.physical.position.x = -1.75
scene.beforeRender.add (dt) ->
leader.forceModelSync()
leader.physical.position.z = playerSim.leader.position
leader.forceModelSync()*/
leaderControls = new TargetSpeedController
leader = yield addVehicle scene, leaderControls
leader.physical.position.x = -1.75
leader.physical.position.z = 10
speeds = [0, 30, 40, 50, 60, 70, 80]*2
shuffleArray speeds
while speeds[*-1] == 0
shuffleArray speeds
speedDuration = 10
sequence = for speed, i in speeds
[(i+1)*speedDuration, speed/3.6]
scene.afterPhysics.add (dt) ->
if scene.time > sequence[0][0] and sequence.length > 1
sequence := sequence.slice(1)
leaderControls.target = sequence[0][1]
leaderControls.tick leader.getSpeed(), dt
headway =
cumulative: 0
time: 0
average: ->
@cumulative/@time
cumHeadway = 0
averageHeadway = 0
scene.afterPhysics (dt) ->
return if not startTime?
headway.cumulative += dt*distanceToLeader!
headway.time += dt
distanceToLeader = ->
rawDist = scene.player.physical.position.distanceTo leader.physical.position
return rawDist - scene.player.physical.boundingRadius - leader.physical.boundingRadius
scene.draftIndicator = ui.gauge env,
name: L "Draft saving"
unit: "%"
#range: [0, 30]
#format: (v) ->
# return null if consumption.distance < 1
# return v.toFixed 2
value: ->
c = draftingCoeff distanceToLeader!
((1 - c)*100).toFixed 1
# Wait for the traffic to queue up
#while not traffic.isInStandstill()
# traffic.step 1/60
finishSign.bodyPassed(scene.player.physical).then ~>
@let \done, passed: true, outro:
title: L "Passed!"
content: L '%followInTraffic.outro', consumption: consumption
@let \scene, scene
yield @get \run
yield P.delay 1000
yield startLight.switchToGreen()
startTime = scene.time
return yield @get \done
exportScenario \blindFollowInTraffic, (env) ->*
L = env.L
base = followInTraffic env
intro = yield base.get \intro
@let \intro,
title: L "Anticipating supermiler"
content: L '%blindFollowInTraffic.intro'
scene = yield base.get \scene
scene.draftIndicator.el.hide()
addBlinderTask scene, env
@let \scene, scene
yield @get \run
base.let \run
@get \done .then (result) ->
base.let \done, result
result = yield base.get \done
@let \done, result
return result
exportScenario \forcedBlindFollowInTraffic, (env, opts) ->*
L = env.L
base = followInTraffic env, distance: 1000
intro = yield base.get \intro
@let \intro,
title: L "Distracted supermiler"
content: L '%forcedBlindFollowInTraffic.intro'
scene = yield base.get \scene
scene.draftIndicator.el.hide()
addForcedBlinderTask scene, env, opts
@let \scene, scene
yield @get \run
base.let \run
@get \done .then (result) ->
base.let \done, result
result = yield base.get \done
@let \done, result
return result
exportScenario \participantInformation, (env) ->*
L = env.L
currentYear = (new Date).getFullYear()
radioSelect = (name, ...options) ->
for {value, label} in options
$ """
<div class="radio">
<label>
<input type="radio" name="#name" value="#value">
#label
</label>
</div>
"""
dialogs =
->
@ \title .text L "Welcome to the experiment"
@ \text .append L "%intro.introduction"
@ \accept .text L "Next"
@ \cancel-button .hide!
->
@ \title .text L "Participation is voluntary"
@ \text .append L "%intro.participantRights"
@ \cancel .text L "Previous"
@ \accept .text L "I wish to participate"
->
@ \title .text L "Collection and use of data"
@ \text .append L "%intro.dataUse"
@ \cancel .text L "Previous"
@ \accept .text L "I accept the usage of my data"
->
@ \title .text L "Background information"
@ \text .append L "%intro.backgroundInfo"
@ \accept .text L "Next"
@ \cancel .text L "Previous"
->
@ \title .text L "E-mail address"
@ \text .append L "%intro.email"
@ \accept .text L "Next"
@ \cancel .text L "Previous"
input = $('<input name="email" type="email" style="color: black">')
.prop "placeholder", L "E-mail address"
.appendTo @ \inputs
setTimeout input~focus, 0
->
@ \title .text L "Birth year"
@ \accept .text L "Next"
@ \cancel .text L "Previous"
input = $("""<input name="birthyear" type="number" min="1900" max="#currentYear" style="color: black">""")
.appendTo @ \inputs
setTimeout input~focus, 0
->
@ \title .text L "Gender"
@ \accept .text L "Next"
@ \cancel .text L "Previous"
@ \inputs .append radioSelect "gender",
* value: 'female', label: L "Female"
* value: 'male', label: L "Male"
->
@ \title .text L "Driving license"
@ \text .append L "What class is your driver's licence?"
@ \accept .text L "Next"
@ \cancel .text L "Previous"
input = $("""<input name="drivinglicenseclass" type="string" style="color: black">""")
.appendTo @ \inputs
setTimeout input~focus, 0
->
@ \title .text L "Driving license year"
@ \text .append L "%intro.license"
@ \accept .text L "Next"
@ \cancel .text L "Previous"
input = $("""<input name="drivinglicenseyear" type="number" min="1900" max="#currentYear" style="color: black">""")
.appendTo @ \inputs
setTimeout input~focus, 0
->
#@ \title .text L "Past year driving"
#@ \text .append L "On average, how frequently have you driven during the <strong>past year</strong>."
#@ \accept .text L "Next"
#@ \cancel .text L "Previous"
#@ \inputs .append radioSelect "drivingFreqPastYear",
# * value: 'daily', label: L "Most days"
# * value: 'weekly', label: L "Most weeks"
# * value: 'monthly', label: L "Most months"
# * value: 'yearly', label: L "Few times a year"
# * value: 'none', label: L "Not at all"
#->
#@ \title .text L "Lifetime driving"
#@ \text .append L "On average, how frequently have you driven <strong>since you got your driver's license</strong>."
#@ \accept .text L "Next"
#@ \cancel .text L "Previous"
#@ \inputs .append radioSelect "drivingFreqTotal",
# * value: 'daily', label: L "Most days"
# * value: 'weekly', label: L "Most weeks"
# * value: 'monthly', label: L "Most months"
# * value: 'yearly', label: L "Few times a year"
# * value: 'none', label: L "Not at all"
#->
@ \title .text L "Past 12 month kilometrage"
@ \text .append L "Give out an estimate on how many kilometres have you driven during the past 12 months."
@ \accept .text L "Next"
@ \cancel .text L "Previous"
@ \inputs .append radioSelect "drivingDist",
* value: 'None', label: L "not driven"
* value: '0', label: "<1000"
* value: '1000', label: "1000 - 5000"
* value: '5000', label: "5001 - 10 000"
* value: '100000', label: "10 001 - 15 000"
* value: '150000', label: "15 001 - 20 000"
* value: '200000', label: "20 001 - 30 000"
* value: '300000', label: "30 001 - 50 000"
* value: '500000', label: "> 50 000"
->
@ \title .text L "Lifetime kilometrage"