forked from mmp/vice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsim.go
1431 lines (1248 loc) · 39.2 KB
/
sim.go
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
// sim.go
// Copyright(c) 2022 Matt Pharr, licensed under the GNU Public License, Version 3.
// SPDX: GPL-3.0-only
package main
import (
"errors"
"fmt"
"sort"
"strings"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/mmp/imgui-go/v4"
)
const initialSimSeconds = 45
var (
ErrArrivalAirportUnknown = errors.New("Arrival airport unknown")
ErrUnknownApproach = errors.New("Unknown approach")
ErrClearedForUnexpectedApproach = errors.New("Cleared for unexpected approach")
ErrNoAircraftForCallsign = errors.New("No aircraft exists with specified callsign")
ErrNoFlightPlan = errors.New("No flight plan has been filed for aircraft")
ErrOtherControllerHasTrack = errors.New("Another controller is already tracking the aircraft")
ErrNotBeingHandedOffToMe = errors.New("Aircraft not being handed off to current controller")
ErrNoController = errors.New("No controller with that callsign")
ErrUnknownAircraftType = errors.New("Unknown aircraft type")
ErrUnableCommand = errors.New("Unable")
)
type SimConnectionConfiguration struct {
numAircraft int32
departureChallenge float32
goAroundRate float32
scenario *Scenario
controller *Controller
validControllers map[string]*Controller
}
func (ssc *SimConnectionConfiguration) Initialize() {
ssc.numAircraft = 30
ssc.departureChallenge = 0.25
ssc.goAroundRate = 0.10
ssc.ResetScenarioGroup()
}
func (ssc *SimConnectionConfiguration) ResetScenarioGroup() {
ssc.scenario = scenarioGroup.Scenarios[scenarioGroup.DefaultScenarioGroup]
ssc.validControllers = make(map[string]*Controller)
for _, sc := range scenarioGroup.Scenarios {
ssc.validControllers[sc.Callsign] = scenarioGroup.ControlPositions[sc.Callsign]
}
ssc.controller = scenarioGroup.ControlPositions[scenarioGroup.DefaultController]
globalConfig.DisplayRoot.VisitPanes(func(p Pane) {
if stars, ok := p.(*STARSPane); ok {
stars.ResetScenarioGroup()
stars.ResetScenario(ssc.scenario)
}
})
}
func (ssc *SimConnectionConfiguration) SetScenario(name string) {
var ok bool
ssc.scenario, ok = scenarioGroup.Scenarios[name]
if !ok {
lg.Errorf("%s: called SetScenario with an unknown scenario name???", name)
return
}
globalConfig.DisplayRoot.VisitPanes(func(p Pane) {
if stars, ok := p.(*STARSPane); ok {
stars.ResetScenario(ssc.scenario)
}
})
}
func (ssc *SimConnectionConfiguration) DrawUI() bool {
if imgui.BeginComboV("Scenario Group", scenarioGroup.Name, imgui.ComboFlagsHeightLarge) {
for _, name := range SortedMapKeys(scenarioGroups) {
if imgui.SelectableV(name, name == scenarioGroup.Name, 0, imgui.Vec2{}) {
scenarioGroup = scenarioGroups[name]
globalConfig.LastScenarioGroup = name
ssc.ResetScenarioGroup()
}
}
imgui.EndCombo()
}
if imgui.BeginComboV("Control Position", ssc.controller.Callsign, imgui.ComboFlagsHeightLarge) {
for _, controllerName := range SortedMapKeys(ssc.validControllers) {
if imgui.SelectableV(controllerName, controllerName == ssc.controller.Callsign, 0, imgui.Vec2{}) {
ssc.controller = ssc.validControllers[controllerName]
// Set the current scenario to the first one alphabetically
// with the selected controller.
for _, scenarioName := range SortedMapKeys(scenarioGroup.Scenarios) {
if scenarioGroup.Scenarios[scenarioName].Callsign == controllerName {
ssc.SetScenario(scenarioName)
break
}
}
}
}
imgui.EndCombo()
}
scenario := ssc.scenario
if imgui.BeginComboV("Config", scenario.Name(), imgui.ComboFlagsHeightLarge) {
for _, name := range SortedMapKeys(scenarioGroup.Scenarios) {
if scenarioGroup.Scenarios[name].Callsign != ssc.controller.Callsign {
continue
}
if imgui.SelectableV(name, name == scenario.Name(), 0, imgui.Vec2{}) {
ssc.SetScenario(name)
}
}
imgui.EndCombo()
}
imgui.InputIntV("Total Aircraft", &ssc.numAircraft, 1, 100, 0)
if imgui.BeginTableV("scenario", 2, 0, imgui.Vec2{500, 0}, 0.) {
imgui.TableNextRow()
imgui.TableNextColumn()
if len(scenario.DepartureRunways) > 0 {
imgui.TableNextRow()
imgui.TableNextColumn()
imgui.Text("Departing:")
imgui.TableNextColumn()
d := SortedMapKeys(scenario.nextDepartureSpawn)
// Only list ones that are actually active.
d = FilterSlice(d, func(rwy string) bool {
return scenario.runwayDepartureRate(rwy) > 0
})
imgui.Text(strings.Join(d, ", "))
}
if len(scenario.ArrivalRunways) > 0 {
imgui.TableNextRow()
imgui.TableNextColumn()
imgui.Text("Landing:")
imgui.TableNextColumn()
var a []string
for _, rwy := range scenario.ArrivalRunways {
a = append(a, rwy.Airport+"/"+rwy.Runway)
}
sort.Strings(a)
imgui.Text(strings.Join(a, ", "))
}
imgui.TableNextRow()
imgui.TableNextColumn()
imgui.Text("Wind:")
imgui.TableNextColumn()
if scenario.Wind.Gust > scenario.Wind.Speed {
imgui.Text(fmt.Sprintf("%d at %d gust %d", scenario.Wind.Direction, scenario.Wind.Speed, scenario.Wind.Gust))
} else {
imgui.Text(fmt.Sprintf("%d at %d", scenario.Wind.Direction, scenario.Wind.Speed))
}
imgui.EndTable()
}
if len(scenario.DepartureRunways) > 0 {
imgui.Separator()
imgui.Text("Departures")
imgui.SliderFloatV("Sequencing challenge", &ssc.departureChallenge, 0, 1, "%.02f", 0)
flags := imgui.TableFlagsBordersV | imgui.TableFlagsBordersOuterH | imgui.TableFlagsRowBg | imgui.TableFlagsSizingStretchProp
if imgui.BeginTableV("departureRunways", 4, flags, imgui.Vec2{500, 0}, 0.) {
imgui.TableSetupColumn("Airport")
imgui.TableSetupColumn("Runway")
imgui.TableSetupColumn("Category")
imgui.TableSetupColumn("ADR")
imgui.TableHeadersRow()
for i, rwy := range scenario.DepartureRunways {
imgui.PushID(rwy.Airport + rwy.Runway + rwy.Category)
imgui.TableNextRow()
imgui.TableNextColumn()
imgui.Text(rwy.Airport)
imgui.TableNextColumn()
imgui.Text(rwy.Runway)
imgui.TableNextColumn()
if rwy.Category == "" {
imgui.Text("(All)")
} else {
imgui.Text(rwy.Category)
}
imgui.TableNextColumn()
imgui.InputIntV("##adr", &scenario.DepartureRunways[i].Rate, 0, 120, 0)
imgui.PopID()
}
imgui.EndTable()
}
}
if len(scenario.ArrivalGroupRates) > 0 {
// Figure out how many unique airports we've got for AAR columns in the table...
allAirports := make(map[string]interface{})
for _, agr := range scenario.ArrivalGroupRates {
for ap := range agr {
allAirports[ap] = nil
}
}
nAirports := len(allAirports)
imgui.Separator()
imgui.Text("Arrivals")
imgui.SliderFloatV("Go around probability", &ssc.goAroundRate, 0, 1, "%.02f", 0)
flags := imgui.TableFlagsBordersV | imgui.TableFlagsBordersOuterH | imgui.TableFlagsRowBg | imgui.TableFlagsSizingStretchProp
if imgui.BeginTableV("arrivalgroups", 1+nAirports, flags, imgui.Vec2{500, 0}, 0.) {
imgui.TableSetupColumn("Arrival")
sortedAirports := SortedMapKeys(allAirports)
for _, ap := range sortedAirports {
imgui.TableSetupColumn(ap + " AAR")
}
imgui.TableHeadersRow()
for _, group := range SortedMapKeys(scenario.ArrivalGroupRates) {
imgui.PushID(group)
imgui.TableNextRow()
imgui.TableNextColumn()
imgui.Text(group)
for ap, rate := range scenario.ArrivalGroupRates[group] {
idx := Find(sortedAirports, ap)
if idx == -1 {
lg.Errorf("%s: airport not found in sorted all airports? %+v", ap, sortedAirports)
} else {
imgui.TableSetColumnIndex(1 + idx)
imgui.InputIntV("##aar-"+ap, rate, 0, 120, 0)
}
}
imgui.PopID()
}
imgui.EndTable()
}
}
return false
}
func (ssc *SimConnectionConfiguration) Valid() bool {
return true
}
func (ssc *SimConnectionConfiguration) Connect() error {
// Send out events to remove any existing aircraft (necessary for when
// we restart...)
for _, ac := range sim.GetAllAircraft() {
eventStream.Post(&RemovedAircraftEvent{ac: ac})
}
sim.Disconnect()
sim = NewSim(*ssc)
sim.Prespawn()
return nil
}
///////////////////////////////////////////////////////////////////////////
// Sim
type Sim struct {
scenario *Scenario
aircraft map[string]*Aircraft
handoffs map[string]time.Time
metar map[string]*METAR
currentTime time.Time // this is our fake time--accounting for pauses & simRate..
lastUpdateTime time.Time // this is w.r.t. true wallclock time
simRate float32
paused bool
remainingLaunches int
eventsId EventSubscriberId
departureChallenge float32
goAroundRate float32
willGoAround map[*Aircraft]interface{}
lastTrackUpdate time.Time
lastSimUpdate time.Time
showSettings bool
}
func NewSim(ssc SimConnectionConfiguration) *Sim {
rand.Seed(time.Now().UnixNano())
sim := &Sim{
scenario: ssc.scenario,
aircraft: make(map[string]*Aircraft),
handoffs: make(map[string]time.Time),
metar: make(map[string]*METAR),
currentTime: time.Now(),
lastUpdateTime: time.Now(),
remainingLaunches: int(ssc.numAircraft),
eventsId: eventStream.Subscribe(),
simRate: 1,
departureChallenge: ssc.departureChallenge,
goAroundRate: ssc.goAroundRate,
willGoAround: make(map[*Aircraft]interface{}),
}
// Make some fake METARs; slightly different for all airports.
alt := 2980 + rand.Intn(40)
for _, ap := range sim.scenario.AllAirports() {
spd := sim.scenario.Wind.Speed - 3 + rand.Int31n(6)
var wind string
if spd < 0 {
wind = "00000KT"
} else if spd < 4 {
wind = fmt.Sprintf("VRB%02dKT", spd)
} else {
dir := 10 * ((sim.scenario.Wind.Direction + 5) / 10)
dir += [3]int32{-10, 0, 10}[rand.Intn(3)]
wind = fmt.Sprintf("%03d%02d", dir, spd)
gst := sim.scenario.Wind.Gust - 3 + rand.Int31n(6)
if gst-sim.scenario.Wind.Speed > 5 {
wind += fmt.Sprintf("G%02d", gst)
}
wind += "KT"
}
// Just provide the stuff that the STARS display shows
sim.metar[ap] = &METAR{
AirportICAO: ap,
Wind: wind,
Altimeter: fmt.Sprintf("A%d", alt-2+rand.Intn(4)),
}
}
// Randomize next spawn time for departures and arrivals; may be before
// or after the current time.
randomSpawn := func(rate int) time.Time {
if rate == 0 {
return time.Now().Add(365 * 24 * time.Hour)
}
avgWait := 3600 / rate
delta := rand.Intn(avgWait) - avgWait/2 - initialSimSeconds
return time.Now().Add(time.Duration(delta) * time.Second)
}
for group, rates := range sim.scenario.ArrivalGroupRates {
rateSum := 0
for _, rate := range rates {
rateSum += int(*rate)
}
sim.scenario.nextArrivalSpawn[group] = randomSpawn(rateSum)
}
for rwy := range sim.scenario.nextDepartureSpawn {
sim.scenario.nextDepartureSpawn[rwy] = randomSpawn(sim.scenario.runwayDepartureRate(rwy))
}
return sim
}
func (sim *Sim) Prespawn() {
// Prime the pump before the user gets involved
t := time.Now().Add(-(initialSimSeconds + 1) * time.Second)
for i := 0; i < initialSimSeconds; i++ {
sim.currentTime = t
sim.lastUpdateTime = t
t = t.Add(1 * time.Second)
sim.updateState()
}
sim.currentTime = time.Now()
sim.lastUpdateTime = time.Now()
}
func (sim *Sim) SetSquawk(callsign string, squawk Squawk) error {
return nil // UNIMPLEMENTED
}
func (sim *Sim) SetSquawkAutomatic(callsign string) error {
return nil // UNIMPLEMENTED
}
func (sim *Sim) SetScratchpad(callsign string, scratchpad string) error {
if ac, ok := sim.aircraft[callsign]; !ok {
return ErrNoAircraftForCallsign
} else if ac.TrackingController != sim.scenario.Callsign {
return ErrOtherControllerHasTrack
} else {
ac.Scratchpad = scratchpad
eventStream.Post(&ModifiedAircraftEvent{ac: ac})
return nil
}
}
func (sim *Sim) SetTemporaryAltitude(callsign string, alt int) error {
return nil // UNIMPLEMENTED
}
func (sim *Sim) AmendFlightPlan(callsign string, fp FlightPlan) error {
return nil // UNIMPLEMENTED
}
func (sim *Sim) PushFlightStrip(callsign string, controller string) error {
return nil // UNIMPLEMENTED
}
func (sim *Sim) InitiateTrack(callsign string) error {
if ac, ok := sim.aircraft[callsign]; !ok {
return ErrNoAircraftForCallsign
} else if ac.TrackingController != "" {
return ErrOtherControllerHasTrack
} else {
ac.TrackingController = sim.scenario.Callsign
eventStream.Post(&ModifiedAircraftEvent{ac: ac})
eventStream.Post(&InitiatedTrackEvent{ac: ac})
return nil
}
}
func (sim *Sim) DropTrack(callsign string) error {
if ac, ok := sim.aircraft[callsign]; !ok {
return ErrNoAircraftForCallsign
} else if ac.TrackingController != sim.scenario.Callsign {
return ErrOtherControllerHasTrack
} else {
ac.TrackingController = ""
eventStream.Post(&ModifiedAircraftEvent{ac: ac})
eventStream.Post(&DroppedTrackEvent{ac: ac})
return nil
}
}
func (sim *Sim) Handoff(callsign string, controller string) error {
if ac, ok := sim.aircraft[callsign]; !ok {
return ErrNoAircraftForCallsign
} else if ac.TrackingController != sim.scenario.Callsign {
return ErrOtherControllerHasTrack
} else if ctrl := sim.GetController(controller); ctrl == nil {
return ErrNoController
} else {
ac.OutboundHandoffController = ctrl.Callsign
eventStream.Post(&ModifiedAircraftEvent{ac: ac})
acceptDelay := 2 + rand.Intn(10)
sim.handoffs[callsign] = sim.CurrentTime().Add(time.Duration(acceptDelay) * time.Second)
return nil
}
}
func (sim *Sim) AcceptHandoff(callsign string) error {
if ac, ok := sim.aircraft[callsign]; !ok {
return ErrNoAircraftForCallsign
} else if ac.InboundHandoffController != sim.scenario.Callsign {
return ErrNotBeingHandedOffToMe
} else {
ac.InboundHandoffController = ""
ac.TrackingController = sim.scenario.Callsign
eventStream.Post(&AcceptedHandoffEvent{controller: sim.scenario.Callsign, ac: ac})
eventStream.Post(&ModifiedAircraftEvent{ac: ac}) // FIXME...
return nil
}
}
func (sim *Sim) RejectHandoff(callsign string) error {
return nil // UNIMPLEMENTED
}
func (sim *Sim) CancelHandoff(callsign string) error {
if ac, ok := sim.aircraft[callsign]; !ok {
return ErrNoAircraftForCallsign
} else if ac.TrackingController != sim.scenario.Callsign {
return ErrOtherControllerHasTrack
} else {
ac.OutboundHandoffController = ""
// TODO: we are inconsistent in other control backends about events
// when user does things like this; sometimes no event, sometimes
// modified a/c event...
eventStream.Post(&ModifiedAircraftEvent{ac: ac})
return nil
}
}
func (sim *Sim) PointOut(callsign string, controller string) error {
return nil // UNIMPLEMENTED
}
func (sim *Sim) RequestControllerATIS(controller string) error {
return nil // UNIMPLEMENTED
}
func (sim *Sim) SetRadarCenters(primary Point2LL, secondary [3]Point2LL, rangeNm int) error {
return nil // UNIMPLEMENTED
}
func (sim *Sim) Disconnect() {
for _, ac := range sim.aircraft {
eventStream.Post(&RemovedAircraftEvent{ac: ac})
}
if sim.eventsId != InvalidEventSubscriberId {
eventStream.Unsubscribe(sim.eventsId)
sim.eventsId = InvalidEventSubscriberId
}
}
func (sim *Sim) GetAircraft(callsign string) *Aircraft {
if ac, ok := sim.aircraft[callsign]; ok {
return ac
}
return nil
}
func (sim *Sim) GetFilteredAircraft(filter func(*Aircraft) bool) []*Aircraft {
var filtered []*Aircraft
for _, ac := range sim.aircraft {
if filter(ac) {
filtered = append(filtered, ac)
}
}
return filtered
}
func (sim *Sim) GetAllAircraft() []*Aircraft {
return sim.GetFilteredAircraft(func(*Aircraft) bool { return true })
}
func (sim *Sim) GetFlightStrip(callsign string) *FlightStrip {
if ac, ok := sim.aircraft[callsign]; ok {
return &ac.Strip
}
return nil
}
func (sim *Sim) AddAirportForWeather(airport string) {
// UNIMPLEMENTED
}
func (sim *Sim) GetMETAR(location string) *METAR {
return sim.metar[location]
}
func (sim *Sim) GetAirportATIS(airport string) []ATIS {
// UNIMPLEMENTED
return nil
}
func (s *Sim) GetController(callsign string) *Controller {
if s.scenario == nil {
return nil
}
ctrl, ok := scenarioGroup.ControlPositions[callsign]
if ok {
return ctrl
}
for _, c := range scenarioGroup.ControlPositions {
// Make sure that the controller is active in the scenarioGroup...
if c.SectorId == callsign && Find(s.scenario.Controllers, c.Callsign) != -1 {
return c
}
}
return ctrl
}
func (s *Sim) GetAllControllers() []*Controller {
if s.scenario == nil {
return nil
}
_, ctrl := FlattenMap(scenarioGroup.ControlPositions)
return FilterSlice(ctrl,
func(ctrl *Controller) bool { return Find(s.scenario.Controllers, ctrl.Callsign) != -1 })
}
func (sim *Sim) SetPrimaryFrequency(f Frequency) {
// UNIMPLEMENTED
}
func (sim *Sim) GetUpdates() {
if sim.paused || sim.scenario == nil {
return
}
// Process events
if sim.eventsId != InvalidEventSubscriberId {
for _, ev := range eventStream.Get(sim.eventsId) {
if rem, ok := ev.(*RemovedAircraftEvent); ok {
delete(sim.aircraft, rem.ac.Callsign)
}
}
}
// Update the current time
elapsed := time.Since(sim.lastUpdateTime)
elapsed = time.Duration(sim.simRate * float32(elapsed))
sim.currentTime = sim.currentTime.Add(elapsed)
sim.lastUpdateTime = time.Now()
sim.updateState()
}
// FIXME: this is poorly named...
func (sim *Sim) updateState() {
// Accept any handoffs whose time has time...
now := sim.CurrentTime()
for callsign, t := range sim.handoffs {
if now.After(t) {
if ac, ok := sim.aircraft[callsign]; ok {
ac.TrackingController = ac.OutboundHandoffController
ac.OutboundHandoffController = ""
eventStream.Post(&AcceptedHandoffEvent{controller: ac.TrackingController, ac: ac})
globalConfig.Audio.PlaySound(AudioEventHandoffAccepted)
}
delete(sim.handoffs, callsign)
}
}
// Update the simulation state once a second.
if now.Sub(sim.lastSimUpdate) >= time.Second {
sim.lastSimUpdate = now
for _, ac := range sim.aircraft {
ac.Update()
if _, ok := sim.willGoAround[ac]; !ok {
continue
}
if !ac.OnFinal || len(ac.Waypoints) != 1 {
continue
}
dist := nmdistance2ll(ac.Position, ac.Waypoints[0].Location)
if dist < 0.25 {
delete(sim.willGoAround, ac)
ac.GoAround()
pilotResponse(ac.Callsign, "Going around")
}
}
}
// Add a new radar track every 5 seconds.
if now.Sub(sim.lastTrackUpdate) >= 5*time.Second {
sim.lastTrackUpdate = now
for _, ac := range sim.aircraft {
ac.AddTrack(RadarTrack{
Position: ac.Position,
Altitude: int(ac.Altitude),
Groundspeed: int(ac.GS),
Heading: ac.Heading - scenarioGroup.MagneticVariation,
Time: now,
})
eventStream.Post(&ModifiedAircraftEvent{ac: ac})
}
}
sim.SpawnAircraft()
}
func (sim *Sim) Connected() bool {
return true
}
func (sim *Sim) Callsign() string {
if sim.scenario != nil {
return sim.scenario.Callsign
} else {
return "(disconnected)"
}
}
func (sim *Sim) CurrentTime() time.Time {
return sim.currentTime
}
func (sim *Sim) GetWindowTitle() string {
if sim.scenario == nil {
return "(disconnected)"
}
remaining := fmt.Sprintf("[%d aircraft remaining]", sim.remainingLaunches)
return sim.scenario.Callsign + ": " + sim.scenario.Name() + " " + remaining
}
func pilotResponse(callsign string, fm string, args ...interface{}) {
lg.Printf("%s: %s", callsign, fmt.Sprintf(fm, args...))
eventStream.Post(&RadioTransmissionEvent{callsign: callsign, message: fmt.Sprintf(fm, args...)})
}
func (sim *Sim) AssignAltitude(callsign string, altitude int) error {
if ac, ok := sim.aircraft[callsign]; !ok {
return ErrNoAircraftForCallsign
} else {
if float32(altitude) > ac.Altitude {
pilotResponse(callsign, "climb and maintain %d", altitude)
} else if float32(altitude) == ac.Altitude {
pilotResponse(callsign, "maintain %d", altitude)
} else {
pilotResponse(callsign, "descend and maintain %d", altitude)
}
if ac.AssignedSpeed != 0 {
ac.AssignedAltitudeAfterSpeed = altitude
} else {
ac.AssignedAltitude = altitude
}
ac.CrossingAltitude = 0
return nil
}
}
func (sim *Sim) AssignHeading(callsign string, heading int, turn int) error {
if ac, ok := sim.aircraft[callsign]; !ok {
return ErrNoAircraftForCallsign
} else {
if turn > 0 {
pilotResponse(callsign, "turn right heading %d", heading)
} else if turn == 0 {
pilotResponse(callsign, "fly heading %d", heading)
} else {
pilotResponse(callsign, "turn left heading %d", heading)
}
// A 0 heading shouldn't be specified, but at least cause the
// aircraft to do what is intended, since 0 represents an
// unassigned heading.
if heading == 0 {
heading = 360
}
ac.AssignedHeading = heading
ac.TurnDirection = turn
ac.ClearedApproach = false // if cleared, giving a heading cancels clearance
return nil
}
}
func (sim *Sim) TurnLeft(callsign string, deg int) error {
if ac, ok := sim.aircraft[callsign]; !ok {
return ErrNoAircraftForCallsign
} else {
pilotResponse(callsign, "turn left %d degrees", deg)
if ac.AssignedHeading == 0 {
ac.AssignedHeading = int(ac.Heading) - deg
} else {
ac.AssignedHeading -= deg
}
if ac.AssignedHeading <= 0 {
ac.AssignedHeading += 360
}
ac.TurnDirection = 0
ac.ClearedApproach = false // if cleared, giving a heading cancels clearance
return nil
}
}
func (sim *Sim) TurnRight(callsign string, deg int) error {
if ac, ok := sim.aircraft[callsign]; !ok {
return ErrNoAircraftForCallsign
} else {
pilotResponse(callsign, "turn right %d degrees", deg)
if ac.AssignedHeading == 0 {
ac.AssignedHeading = int(ac.Heading) + deg
} else {
ac.AssignedHeading += deg
}
if ac.AssignedHeading > 360 {
ac.AssignedHeading -= 360
}
ac.TurnDirection = 0
ac.ClearedApproach = false // if cleared, giving a heading cancels clearance
return nil
}
}
func (sim *Sim) AssignSpeed(callsign string, speed int) error {
if ac, ok := sim.aircraft[callsign]; !ok {
return ErrNoAircraftForCallsign
} else {
if speed == 0 {
pilotResponse(callsign, "cancel speed restrictions")
} else if speed < ac.Performance.Speed.Landing {
pilotResponse(callsign, "unable--our minimum speed is %d knots", ac.Performance.Speed.Landing)
return ErrUnableCommand
} else if speed > ac.Performance.Speed.Max {
pilotResponse(callsign, "unable--our maximum speed is %d knots", ac.Performance.Speed.Max)
return ErrUnableCommand
} else if ac.ClearedApproach {
pilotResponse(callsign, "%d knots until 5 mile final", speed)
} else if speed == ac.AssignedSpeed {
pilotResponse(callsign, "we'll maintain %d knots", speed)
} else {
pilotResponse(callsign, "maintain %d knots", speed)
}
if ac.AssignedAltitude != 0 {
ac.AssignedSpeedAfterAltitude = speed
} else {
ac.AssignedSpeed = speed
}
ac.CrossingSpeed = 0
return nil
}
}
func (sim *Sim) DirectFix(callsign string, fix string) error {
if ac, ok := sim.aircraft[callsign]; !ok {
return ErrNoAircraftForCallsign
} else {
fix = strings.ToUpper(fix)
// Look for the fix in the waypoints in the flight plan.
for i, wp := range ac.Waypoints {
if fix == wp.Fix {
ac.Waypoints = ac.Waypoints[i:]
if len(ac.Waypoints) > 0 {
ac.WaypointUpdate(wp)
}
pilotResponse(callsign, "direct %s", fix)
return nil
}
}
if ac.Approach != nil {
for _, route := range ac.Approach.Waypoints {
for _, wp := range route {
if wp.Fix == fix {
ac.Waypoints = []Waypoint{wp}
if len(ac.Waypoints) > 0 {
ac.WaypointUpdate(wp)
}
pilotResponse(callsign, "direct %s", fix)
return nil
}
}
}
}
return fmt.Errorf("%s: fix not found in route", fix)
}
}
func (sim *Sim) getApproach(callsign string, approach string) (*Approach, *Aircraft, error) {
ac, ok := sim.aircraft[callsign]
if !ok {
return nil, nil, ErrNoAircraftForCallsign
}
fp := ac.FlightPlan
if fp == nil {
return nil, nil, ErrNoFlightPlan
}
ap, ok := scenarioGroup.Airports[fp.ArrivalAirport]
if !ok {
lg.Errorf("Can't find TRACON airport %s for %s approach for %s", fp.ArrivalAirport, approach, callsign)
return nil, nil, ErrArrivalAirportUnknown
}
for name, appr := range ap.Approaches {
if name == approach {
return &appr, ac, nil
}
}
return nil, nil, ErrUnknownApproach
}
func (sim *Sim) ExpectApproach(callsign string, approach string) error {
ap, ac, err := sim.getApproach(callsign, approach)
if err != nil {
return err
}
ac.Approach = ap
pilotResponse(callsign, "we'll expect the "+ap.FullName+" approach")
return nil
}
func (sim *Sim) ClearedApproach(callsign string, approach string) error {
ap, ac, err := sim.getApproach(callsign, approach)
if err != nil {
return err
}
response := ""
if ac.Approach == nil {
// allow it anyway...
response = "you never told us to expect an approach, but ok, cleared " + ap.FullName
ac.Approach = ap
}
if ac.Approach.FullName != ap.FullName {
pilotResponse(callsign, "but you cleared us for the "+ac.Approach.FullName+" approach...")
return ErrClearedForUnexpectedApproach
}
if ac.ClearedApproach {
pilotResponse(callsign, "you already cleared us for the "+ap.FullName+" approach...")
return nil
}
directApproachFix := false
var remainingApproachWaypoints []Waypoint
if ac.AssignedHeading == 0 && len(ac.Waypoints) > 0 {
// Is the aircraft cleared direct to a waypoint on the approach?
for _, approach := range ap.Waypoints {
for i, wp := range approach {
if wp.Fix == ac.Waypoints[0].Fix {
directApproachFix = true
if i+1 < len(approach) {
remainingApproachWaypoints = approach[i+1:]
}
break
}
}
}
}
if ac.Approach.Type == ILSApproach {
if ac.AssignedHeading == 0 {
if !directApproachFix {
pilotResponse(callsign, "we need either direct or a heading to intercept")
return nil
} else {
if remainingApproachWaypoints != nil {
ac.Waypoints = append(ac.Waypoints, remainingApproachWaypoints...)
}
}
}
// If the aircraft is on a heading, there's nothing more to do for
// now; keep flying the heading and after we intercept we'll add
// the rest of the waypoints to the aircraft's waypoints array.
} else {
// RNAV
if !directApproachFix {
pilotResponse(callsign, "we need direct to a fix on the approach...")
return nil
}
if remainingApproachWaypoints != nil {
ac.Waypoints = append(ac.Waypoints, remainingApproachWaypoints...)
}
}
// cleared approach cancels speed restrictions, but let's assume that
// aircraft will just maintain their present speed and not immediately
// accelerate up to 250...
ac.AssignedSpeed = 0
ac.CrossingSpeed = int(ac.IAS)
ac.ClearedApproach = true
pilotResponse(callsign, response+"cleared "+ap.FullName+" approach")
return nil
}
func (sim *Sim) PrintInfo(callsign string) error {
if ac, ok := sim.aircraft[callsign]; !ok {
return ErrNoAircraftForCallsign
} else {
lg.Errorf("%s", spew.Sdump(ac))
s := fmt.Sprintf("%s: current alt %f, assigned alt %d crossing alt %d",
ac.Callsign, ac.Altitude, ac.AssignedAltitude, ac.CrossingAltitude)
if ac.AssignedHeading != 0 {
s += fmt.Sprintf(" heading %d", ac.AssignedHeading)
if ac.TurnDirection != 0 {
s += fmt.Sprintf(" turn direction %d", ac.TurnDirection)
}
}
s += fmt.Sprintf(", IAS %f GS %.1f speed %d crossing speed %d",
ac.IAS, ac.GS, ac.AssignedSpeed, ac.CrossingSpeed)
if ac.ClearedApproach {
s += ", cleared approach"
}
if ac.OnFinal {
s += ", on final"
}
lg.Errorf("%s", s)
}
return nil
}
func (sim *Sim) DeleteAircraft(callsign string) error {
if ac, ok := sim.aircraft[callsign]; !ok {
return ErrNoAircraftForCallsign
} else {
eventStream.Post(&RemovedAircraftEvent{ac: ac})
delete(sim.aircraft, callsign)
return nil
}
}
func (sim *Sim) Paused() bool {