-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaviation.go
2295 lines (2003 loc) · 60.2 KB
/
aviation.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
// aviation.go
// Copyright(c) 2022 Matt Pharr, licensed under the GNU Public License, Version 3.
// SPDX: GPL-3.0-only
package main
import (
"archive/zip"
"bufio"
"bytes"
"encoding/csv"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"io/fs"
"log/slog"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/davecgh/go-spew/spew"
)
type FAAAirport struct {
Id string
Name string
Elevation int
Location Point2LL
Runways []Runway
Approaches map[string][]WaypointArray
STARs map[string]STAR
}
type TRACON struct {
Name string
ARTCC string
}
type ARTCC struct {
Name string
}
type ReportingPoint struct {
Fix string
Location Point2LL
}
type Arrival struct {
Waypoints WaypointArray `json:"waypoints"`
RunwayWaypoints map[string]map[string]WaypointArray `json:"runway_waypoints"` // Airport -> runway -> waypoints
SpawnWaypoint string `json:"spawn"` // if "waypoints" aren't specified
CruiseAltitude float32 `json:"cruise_altitude"`
Route string `json:"route"`
STAR string `json:"star"`
InitialController string `json:"initial_controller"`
InitialAltitude float32 `json:"initial_altitude"`
AssignedAltitude float32 `json:"assigned_altitude"`
InitialSpeed float32 `json:"initial_speed"`
SpeedRestriction float32 `json:"speed_restriction"`
ExpectApproach string `json:"expect_approach"`
Scratchpad string `json:"scratchpad"`
SecondaryScratchpad string `json:"secondary_scratchpad"`
Description string `json:"description"`
// Airport -> arrival airlines
Airlines map[string][]ArrivalAirline `json:"airlines"`
}
type ArrivalAirline struct {
ICAO string `json:"icao"`
Airport string `json:"airport"`
Fleet string `json:"fleet,omitempty"`
}
type STAR struct {
Transitions map[string]WaypointArray
RunwayWaypoints map[string]WaypointArray
}
func (s STAR) Check(e *ErrorLogger) {
check := func(wps WaypointArray) {
for _, wp := range wps {
_, okn := database.Navaids[wp.Fix]
_, okf := database.Fixes[wp.Fix]
if !okn && !okf {
e.ErrorString("fix %s not found in navaid database", wp.Fix)
}
}
}
for _, wps := range s.Transitions {
check(wps)
}
for _, wps := range s.RunwayWaypoints {
check(wps)
}
}
func (s STAR) HasWaypoint(wp string) bool {
for _, wps := range s.Transitions {
if slices.ContainsFunc(wps, func(w Waypoint) bool { return w.Fix == wp }) {
return true
}
}
for _, wps := range s.RunwayWaypoints {
if slices.ContainsFunc(wps, func(w Waypoint) bool { return w.Fix == wp }) {
return true
}
}
return false
}
func (s STAR) GetWaypointsFrom(fix string) WaypointArray {
for _, tr := range SortedMapKeys(s.Transitions) {
wps := s.Transitions[tr]
if idx := slices.IndexFunc(wps, func(w Waypoint) bool { return w.Fix == fix }); idx != -1 {
return wps[idx:]
}
}
for _, tr := range SortedMapKeys(s.RunwayWaypoints) {
wps := s.RunwayWaypoints[tr]
if idx := slices.IndexFunc(wps, func(w Waypoint) bool { return w.Fix == fix }); idx != -1 {
return wps[idx:]
}
}
return nil
}
func MakeSTAR() *STAR {
return &STAR{
Transitions: make(map[string]WaypointArray),
RunwayWaypoints: make(map[string]WaypointArray),
}
}
func (s STAR) Print(name string) {
for tr, wps := range s.Transitions {
fmt.Printf("%-12s: %s\n", name+"."+tr, wps.Encode())
}
for rwy, wps := range s.RunwayWaypoints {
fmt.Printf("%-12s: %s\n", name+".RWY"+rwy, wps.Encode())
}
}
type Runway struct {
Id string
Heading float32
Threshold Point2LL
Elevation int
}
type METAR struct {
AirportICAO string
Time string
Auto bool
Wind string
Weather string
Altimeter string
Rmk string
}
func (m METAR) String() string {
auto := ""
if m.Auto {
auto = "AUTO"
}
return strings.Join([]string{m.AirportICAO, m.Time, auto, m.Wind, m.Weather, m.Altimeter, m.Rmk}, " ")
}
func ParseMETAR(str string) (*METAR, error) {
fields := strings.Fields(str)
if len(fields) < 3 {
return nil, fmt.Errorf("Expected >= 3 fields in METAR text")
}
i := 0
next := func() string {
if i == len(fields) {
return ""
}
s := fields[i]
i++
return s
}
m := &METAR{AirportICAO: next(), Time: next(), Wind: next()}
if m.Wind == "AUTO" {
m.Auto = true
m.Wind = next()
}
for {
s := next()
if s == "" {
break
}
if s[0] == 'A' || s[0] == 'Q' {
m.Altimeter = s
break
}
m.Weather += s + " "
}
m.Weather = strings.TrimRight(m.Weather, " ")
if s := next(); s != "RMK" {
// TODO: improve the METAR parser...
lg.Warnf("Expecting RMK where %s is in METAR \"%s\"", s, str)
} else {
for s != "" {
s = next()
m.Rmk += s + " "
}
m.Rmk = strings.TrimRight(m.Rmk, " ")
}
return m, nil
}
type ATIS struct {
Airport string
AppDep string
Code string
Contents string
}
// Frequencies are scaled by 1000 and then stored in integers.
type Frequency int
func NewFrequency(f float32) Frequency {
// 0.5 is key for handling rounding!
return Frequency(f*1000 + 0.5)
}
func (f Frequency) String() string {
s := fmt.Sprintf("%03d.%03d", f/1000, f%1000)
for len(s) < 7 {
s += "0"
}
return s
}
type Controller struct {
Callsign string // Not provided in scenario JSON
FullName string `json:"full_name"`
Frequency Frequency `json:"frequency"`
SectorId string `json:"sector_id"` // e.g. N56, 2J, ...
Scope string `json:"scope_char"` // For tracked a/c on the scope--e.g., T
IsHuman bool // Not provided in scenario JSON
FacilityIdentifier string `json:"facility_id"` // For example the "N" in "N4P" showing the N90 TRACON
ERAMFacility bool `json:"eram_facility"` // To weed out N56 and N4P being the same fac
DefaultAirport string `json:"default_airport"` // only required if CRDA is a thing
}
type FlightRules int
const (
UNKNOWN = iota
IFR
VFR
DVFR
SVFR
)
func (f FlightRules) String() string {
return [...]string{"Unknown", "IFR", "VFR", "DVFR", "SVFR"}[f]
}
type FlightPlan struct {
Rules FlightRules
AircraftType string
CruiseSpeed int
DepartureAirport string
DepartTimeEst int
DepartTimeActual int
Altitude int
ArrivalAirport string
Hours, Minutes int
FuelHours, FuelMinutes int
AlternateAirport string
Route string
Remarks string
}
type FlightStrip struct {
Callsign string
Annotations [9]string
}
type Squawk int
func (s Squawk) String() string { return fmt.Sprintf("%04o", s) }
func ParseSquawk(s string) (Squawk, error) {
if s == "" {
return Squawk(0), nil
}
sq, err := strconv.ParseInt(s, 8, 32) // base 8!!!
if err != nil {
return Squawk(0), fmt.Errorf("%s: invalid squawk code", s)
} else if sq < 0 || sq > 0o7777 {
return Squawk(0), fmt.Errorf("%s: out of range squawk code", s)
}
return Squawk(sq), nil
}
// Special purpose code: beacon codes are squawked in various unusual situations.
type SPC struct {
Squawk Squawk
Code string
}
var spcs = []SPC{
{Squawk: Squawk(0o7400), Code: "LL"}, // lost link
{Squawk: Squawk(0o7500), Code: "HJ"}, // hijack
{Squawk: Squawk(0o7600), Code: "RF"}, // radio failure
{Squawk: Squawk(0o7700), Code: "EM"}, // emergency condigion
{Squawk: Squawk(0o7777), Code: "MI"}, // military intercept
}
// SquawkIsSPC returns true if the given beacon code is a SPC. The second
// return value is a string giving the two-letter abbreviated SPC it
// corresponds to.
func SquawkIsSPC(squawk Squawk) (bool, string) {
for _, spc := range spcs {
if spc.Squawk == squawk {
return true, spc.Code
}
}
return false, ""
}
func StringIsSPC(code string) bool {
return slices.ContainsFunc(spcs, func(spc SPC) bool { return spc.Code == code })
}
type RadarTrack struct {
Position Point2LL
Altitude int
Groundspeed int
Time time.Time
}
func FormatAltitude(falt float32) string {
alt := int(falt)
if alt >= 18000 {
return "FL" + strconv.Itoa(alt/100)
} else if alt < 1000 {
return strconv.Itoa(alt)
} else {
th := alt / 1000
hu := (alt % 1000) / 100 * 100
if th == 0 {
return strconv.Itoa(hu)
} else if hu == 0 {
return strconv.Itoa(th) + ",000"
} else {
return fmt.Sprintf("%d,%03d", th, hu)
}
}
}
type TransponderMode int
const (
Standby = iota
Charlie
)
func (t TransponderMode) String() string {
return [...]string{"Standby", "C"}[t]
}
type Navaid struct {
Id string
Type string
Name string
Location Point2LL
}
type Fix struct {
Id string
Location Point2LL
}
func NewFlightPlan(r FlightRules, ac, dep, arr string) *FlightPlan {
return &FlightPlan{
Rules: r,
AircraftType: ac,
DepartureAirport: dep,
ArrivalAirport: arr,
}
}
func (fp FlightPlan) BaseType() string {
s := strings.TrimPrefix(fp.TypeWithoutSuffix(), "H/")
s = strings.TrimPrefix(s, "S/")
s = strings.TrimPrefix(s, "J/")
return s
}
func (fp FlightPlan) TypeWithoutSuffix() string {
// try to chop off equipment suffix
actypeFields := strings.Split(fp.AircraftType, "/")
switch len(actypeFields) {
case 3:
// Heavy (presumably), with suffix
return actypeFields[0] + "/" + actypeFields[1]
case 2:
if actypeFields[0] == "H" || actypeFields[0] == "S" || actypeFields[0] == "J" {
// Heavy or super, no suffix
return actypeFields[0] + "/" + actypeFields[1]
} else {
// No heavy, with suffix
return actypeFields[0]
}
default:
// Who knows, so leave it alone
return fp.AircraftType
}
}
func PlausibleFinalAltitude(w *World, fp *FlightPlan, perf AircraftPerformance) (altitude int) {
// try to figure out direction of flight
dep, dok := database.Airports[fp.DepartureAirport]
arr, aok := database.Airports[fp.ArrivalAirport]
if !dok || !aok {
return 34000
}
pDep, pArr := dep.Location, arr.Location
if nmdistance2ll(pDep, pArr) < 100 {
altitude = 7000
if dep.Elevation > 3000 || arr.Elevation > 3000 {
altitude += 1000
}
} else if nmdistance2ll(pDep, pArr) < 200 {
altitude = 11000
if dep.Elevation > 3000 || arr.Elevation > 3000 {
altitude += 1000
}
} else if nmdistance2ll(pDep, pArr) < 300 {
altitude = 21000
} else {
altitude = 37000
}
altitude = min(altitude, int(perf.Ceiling))
if headingp2ll(pDep, pArr, w.NmPerLongitude, w.MagneticVariation) > 180 {
altitude += 1000
}
return
}
///////////////////////////////////////////////////////////////////////////
type RadioTransmissionType int
const (
RadioTransmissionContact = iota // Messages initiated by the pilot
RadioTransmissionReadback // Reading back an instruction
RadioTransmissionUnexpected // Something urgent or unusual
)
func (r RadioTransmissionType) String() string {
switch r {
case RadioTransmissionContact:
return "contact"
case RadioTransmissionReadback:
return "readback"
case RadioTransmissionUnexpected:
return "urgent"
default:
return "(unhandled type)"
}
}
type RadioTransmission struct {
Controller string
Message string
Type RadioTransmissionType
}
func PostRadioEvents(from string, transmissions []RadioTransmission, ep EventPoster) {
for _, rt := range transmissions {
ep.PostEvent(Event{
Type: RadioTransmissionEvent,
Callsign: from,
ToController: rt.Controller,
Message: rt.Message,
RadioTransmissionType: rt.Type,
})
}
}
///////////////////////////////////////////////////////////////////////////
type TurnMethod int
const (
TurnClosest = iota // default
TurnLeft
TurnRight
)
func (t TurnMethod) String() string {
return []string{"closest", "left", "right"}[t]
}
const StandardTurnRate = 3
func TurnAngle(from, to float32, turn TurnMethod) float32 {
switch turn {
case TurnLeft:
return NormalizeHeading(from - to)
case TurnRight:
return NormalizeHeading(to - from)
case TurnClosest:
return abs(headingDifference(from, to))
default:
panic("unhandled TurnMethod")
}
}
///////////////////////////////////////////////////////////////////////////
// HILPT
type PTType int
const (
PTUndefined = iota
PTRacetrack
PTStandard45
)
func (pt PTType) String() string {
return []string{"undefined", "racetrack", "standard 45"}[pt]
}
type ProcedureTurn struct {
Type PTType
RightTurns bool
ExitAltitude int `json:",omitempty"`
MinuteLimit float32 `json:",omitempty"`
NmLimit float32 `json:",omitempty"`
Entry180NoPT bool `json:",omitempty"`
}
type RacetrackPTEntry int
const (
DirectEntryShortTurn = iota
DirectEntryLongTurn
ParallelEntry
TeardropEntry
)
func (e RacetrackPTEntry) String() string {
return []string{"direct short", "direct long", "parallel", "teardrop"}[int(e)]
}
func (e RacetrackPTEntry) MarshalJSON() ([]byte, error) {
s := "\"" + e.String() + "\""
return []byte(s), nil
}
func (e *RacetrackPTEntry) UnmarshalJSON(b []byte) error {
if len(b) < 2 {
return fmt.Errorf("invalid HILPT")
}
switch string(b[1 : len(b)-1]) {
case "direct short":
*e = DirectEntryShortTurn
case "direct long":
*e = DirectEntryLongTurn
case "parallel":
*e = ParallelEntry
case "teardrop":
*e = TeardropEntry
default:
return fmt.Errorf("%s: malformed HILPT JSON", string(b))
}
return nil
}
func (pt *ProcedureTurn) SelectRacetrackEntry(inboundHeading float32, aircraftFixHeading float32) RacetrackPTEntry {
// Rotate so we can treat inboundHeading as 0.
hdg := aircraftFixHeading - inboundHeading
if hdg < 0 {
hdg += 360
}
if pt.RightTurns {
if hdg > 290 {
return DirectEntryLongTurn
} else if hdg < 110 {
return DirectEntryShortTurn
} else if hdg > 180 {
return ParallelEntry
} else {
return TeardropEntry
}
} else {
if hdg > 250 {
return DirectEntryShortTurn
} else if hdg < 70 {
return DirectEntryLongTurn
} else if hdg < 180 {
return ParallelEntry
} else {
return TeardropEntry
}
}
}
///////////////////////////////////////////////////////////////////////////
// Wind
type Wind struct {
Direction int32 `json:"direction"`
Speed int32 `json:"speed"`
Gust int32 `json:"gust"`
}
type WindModel interface {
GetWindVector(p Point2LL, alt float32) Point2LL
AverageWindVector() [2]float32
}
///////////////////////////////////////////////////////////////////////////
// AltitudeRestriction
type AltitudeRestriction struct {
// We treat 0 as "unset", which works naturally for the bottom but
// requires occasional care at the top.
Range [2]float32
}
func (a *AltitudeRestriction) UnmarshalJSON(b []byte) error {
// For backwards compatibility with saved scenarios, we allow
// unmarshaling from the single-valued altitude restrictions we had
// before.
if alt, err := strconv.Atoi(string(b)); err == nil {
a.Range = [2]float32{float32(alt), float32(alt)}
return nil
} else {
// Otherwise declare a temporary variable with matching structure
// but a different type to avoid an infinite loop when
// json.Unmarshal is called.
ar := struct{ Range [2]float32 }{}
if err := json.Unmarshal(b, &ar); err == nil {
a.Range = ar.Range
return nil
} else {
return err
}
}
}
func (a AltitudeRestriction) TargetAltitude(alt float32) float32 {
if a.Range[1] != 0 {
return clamp(alt, a.Range[0], a.Range[1])
} else {
return max(alt, a.Range[0])
}
}
// ClampRange limits a range of altitudes to satisfy the altitude
// restriction; the returned Boolean indicates whether the ranges
// overlapped.
func (a AltitudeRestriction) ClampRange(r [2]float32) ([2]float32, bool) {
a0, a1 := a.Range[0], a.Range[1]
if a1 == 0 {
a1 = 1000000
}
ok := r[0] <= a1 || r[1] >= a0
return [2]float32{clamp(r[0], a0, a1), clamp(r[1], a0, a1)}, ok
}
// Summary returns a human-readable summary of the altitude
// restriction.
func (a AltitudeRestriction) Summary() string {
if a.Range[0] != 0 {
if a.Range[1] == a.Range[0] {
return fmt.Sprintf("at %s", FormatAltitude(a.Range[0]))
} else if a.Range[1] != 0 {
return fmt.Sprintf("between %s-%s", FormatAltitude(a.Range[0]), FormatAltitude(a.Range[1]))
} else {
return fmt.Sprintf("at or above %s", FormatAltitude(a.Range[0]))
}
} else if a.Range[1] != 0 {
return fmt.Sprintf("at or below %s", FormatAltitude(a.Range[1]))
} else {
return ""
}
}
// Encoded returns the restriction in the encoded form in which it is
// specified in scenario configuration files, e.g. "5000+" for "at or above
// 5000".
func (a AltitudeRestriction) Encoded() string {
if a.Range[0] != 0 {
if a.Range[0] == a.Range[1] {
return fmt.Sprintf("%.0f", a.Range[0])
} else if a.Range[1] != 0 {
return fmt.Sprintf("%.0f-%.0f", a.Range[0], a.Range[1])
} else {
return fmt.Sprintf("%.0f+", a.Range[0])
}
} else if a.Range[1] != 0 {
return fmt.Sprintf("%.0f-", a.Range[1])
} else {
return ""
}
}
// ParseAltitudeRestriction parses an altitude restriction in the compact
// text format used in scenario definition files.
func ParseAltitudeRestriction(s string) (*AltitudeRestriction, error) {
n := len(s)
if n == 0 {
return nil, fmt.Errorf("%s: no altitude provided for crossing restriction", s)
}
if s[n-1] == '-' {
// At or below
alt, err := strconv.Atoi(s[:n-1])
if err != nil {
return nil, fmt.Errorf("%s: error parsing altitude restriction: %v", s, err)
}
return &AltitudeRestriction{Range: [2]float32{0, float32(alt)}}, nil
} else if s[n-1] == '+' {
// At or above
alt, err := strconv.Atoi(s[:n-1])
if err != nil {
return nil, fmt.Errorf("%s: error parsing altitude restriction: %v", s, err)
}
return &AltitudeRestriction{Range: [2]float32{float32(alt), 0}}, nil
} else if alts := strings.Split(s, "-"); len(alts) == 2 {
// Between
if low, err := strconv.Atoi(alts[0]); err != nil {
return nil, fmt.Errorf("%s: error parsing altitude restriction: %v", s, err)
} else if high, err := strconv.Atoi(alts[1]); err != nil {
return nil, fmt.Errorf("%s: error parsing altitude restriction: %v", s, err)
} else if low > high {
return nil, fmt.Errorf("%s: low altitude %d is above high altitude %d", s, low, high)
} else {
return &AltitudeRestriction{Range: [2]float32{float32(low), float32(high)}}, nil
}
} else {
// At
if alt, err := strconv.Atoi(s); err != nil {
return nil, fmt.Errorf("%s: error parsing altitude restriction: %v", s, err)
} else {
return &AltitudeRestriction{Range: [2]float32{float32(alt), float32(alt)}}, nil
}
}
}
///////////////////////////////////////////////////////////////////////////
// DMEArc
// Can either be specified with (Fix,Radius), or (Length,Clockwise); the
// remaining fields are then derived from those.
type DMEArc struct {
Fix string
Center Point2LL
Radius float32
Length float32
InitialHeading float32
Clockwise bool
}
///////////////////////////////////////////////////////////////////////////
// Waypoint
type Waypoint struct {
Fix string `json:"fix"`
Location Point2LL // not provided in scenario JSON; derived from fix
AltitudeRestriction *AltitudeRestriction `json:"altitude_restriction,omitempty"`
Speed int `json:"speed,omitempty"`
Heading int `json:"heading,omitempty"` // outbound heading after waypoint
ProcedureTurn *ProcedureTurn `json:"pt,omitempty"`
NoPT bool `json:"nopt,omitempty"`
Handoff bool `json:"handoff,omitempty"`
FlyOver bool `json:"flyover,omitempty"`
Delete bool `json:"delete,omitempty"`
Arc *DMEArc `json:"arc,omitempty"`
IAF, IF, FAF bool // not provided in scenario JSON; derived from fix
}
func (wp Waypoint) LogValue() slog.Value {
attrs := []slog.Attr{slog.String("fix", wp.Fix)}
if wp.AltitudeRestriction != nil {
attrs = append(attrs, slog.Any("altitude_restriction", wp.AltitudeRestriction))
}
if wp.Speed != 0 {
attrs = append(attrs, slog.Int("speed", wp.Speed))
}
if wp.Heading != 0 {
attrs = append(attrs, slog.Int("heading", wp.Heading))
}
if wp.ProcedureTurn != nil {
attrs = append(attrs, slog.Any("procedure_turn", wp.ProcedureTurn))
}
if wp.IAF {
attrs = append(attrs, slog.Bool("IAF", wp.IAF))
}
if wp.IF {
attrs = append(attrs, slog.Bool("IF", wp.IF))
}
if wp.FAF {
attrs = append(attrs, slog.Bool("FAF", wp.FAF))
}
if wp.NoPT {
attrs = append(attrs, slog.Bool("no_pt", wp.NoPT))
}
if wp.Handoff {
attrs = append(attrs, slog.Bool("handoff", wp.Handoff))
}
if wp.FlyOver {
attrs = append(attrs, slog.Bool("fly_over", wp.FlyOver))
}
if wp.Delete {
attrs = append(attrs, slog.Bool("delete", wp.Delete))
}
if wp.Arc != nil {
attrs = append(attrs, slog.Any("arc", wp.Arc))
}
return slog.GroupValue(attrs...)
}
func (wp *Waypoint) ETA(p Point2LL, gs float32) time.Duration {
dist := nmdistance2ll(p, wp.Location)
eta := dist / gs
return time.Duration(eta * float32(time.Hour))
}
type WaypointArray []Waypoint
func (wslice WaypointArray) Encode() string {
var entries []string
for _, w := range wslice {
s := w.Fix
if w.AltitudeRestriction != nil {
s += "/a" + w.AltitudeRestriction.Encoded()
}
if w.Speed != 0 {
s += fmt.Sprintf("/s%d", w.Speed)
}
if pt := w.ProcedureTurn; pt != nil {
if pt.Type == PTStandard45 {
if !pt.RightTurns {
s += "/lpt45"
} else {
s += "/pt45"
}
} else {
if !pt.RightTurns {
s += "/lhilpt"
} else {
s += "/hilpt"
}
}
if pt.MinuteLimit != 0 {
s += fmt.Sprintf("%.1fmin", pt.MinuteLimit)
} else {
s += fmt.Sprintf("%.1fnm", pt.NmLimit)
}
if pt.Entry180NoPT {
s += "/nopt180"
}
if pt.ExitAltitude != 0 {
s += fmt.Sprintf("/pta%d", pt.ExitAltitude)
}
}
if w.IAF {
s += "/iaf"
}
if w.IF {
s += "/if"
}
if w.FAF {
s += "/faf"
}
if w.NoPT {
s += "/nopt"
}
if w.Handoff {
s += "/ho"
}
if w.FlyOver {
s += "/flyover"
}
if w.Delete {
s += "/delete"
}
if w.Heading != 0 {
s += fmt.Sprintf("/h%d", w.Heading)
}
if w.Arc != nil {
if w.Arc.Fix != "" {
s += fmt.Sprintf("/arc%.1f%s", w.Arc.Radius, w.Arc.Fix)
} else {
s += fmt.Sprintf("/arc%.1f", w.Arc.Length)
}
}
entries = append(entries, s)
}
return strings.Join(entries, " ")
}
func (w *WaypointArray) UnmarshalJSON(b []byte) error {
if len(b) >= 2 && b[0] == '"' && b[len(b)-1] == '"' {
// Handle the string encoding used in scenario JSON files
wp, err := parseWaypoints(string(b[1 : len(b)-1]))
if err == nil {
*w = wp
}
return err
} else {
// Otherwise unmarshal it normally
var wp []Waypoint
err := json.Unmarshal(b, &wp)
if err == nil {
*w = wp
}
return err
}
}
func (w WaypointArray) CheckDeparture(e *ErrorLogger) {
w.checkBasics(e)
var lastMin float32 // previous minimum altitude restriction
var minFix string
for _, wp := range w {
e.Push(wp.Fix)
if wp.IAF || wp.IF || wp.FAF {
e.ErrorString("Unexpected IAF/IF/FAF specification in departure")
}
if war := wp.AltitudeRestriction; war != nil {
// Make sure it's generally reasonable
if war.Range[0] < 0 || war.Range[0] >= 50000 || war.Range[1] < 0 || war.Range[1] >= 50000 {
e.ErrorString("Invalid altitude range: should be between 0 and FL500: %s-%s",
FormatAltitude(war.Range[0]), FormatAltitude(war.Range[1]))
}
if war.Range[0] != 0 {
if lastMin != 0 && war.Range[0] < lastMin {
// our minimum must be >= the previous minimum
e.ErrorString("Minimum altitude %s is lower than previous fix %s's minimum %s",
FormatAltitude(war.Range[0]), minFix, FormatAltitude(lastMin))
}
lastMin = war.Range[0]
minFix = wp.Fix
}
}
e.Pop()
}
}
func (w WaypointArray) checkBasics(e *ErrorLogger) {
for _, wp := range w {
e.Push(wp.Fix)
if wp.Speed < 0 || wp.Speed > 300 {
e.ErrorString("invalid speed restriction %d", wp.Speed)
}
e.Pop()
}
}
func (w WaypointArray) CheckApproach(e *ErrorLogger) {
w.checkBasics(e)
w.checkDescending(e)
if len(w) < 2 {
e.ErrorString("must have at least two waypoints in an approach")
}
/*
// Disable for now...
foundFAF := false
for _, wp := range w {
if wp.FAF {
foundFAF = true
break