/
LKAirspace.cpp
executable file
·3132 lines (2689 loc) · 118 KB
/
LKAirspace.cpp
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
/*
LK8000 Tactical Flight Computer - WWW.LK8000.IT
Released under GNU/GPL License v.2
See CREDITS.TXT file for authors and copyrights
*/
#include "externs.h"
#include "LKAirspace.h"
#include "RasterTerrain.h"
#include "LKProfiles.h"
#include "Dialogs.h"
#include <ctype.h>
#include <utility>
#include <Point2D.h>
#include "md5.h"
#include "LKObjects.h"
#include "utils/2dpclip.h"
#include "utils/stringext.h"
#include "utils/openzip.h"
#include "Draw/ScreenProjection.h"
#if TESTBENCH
//#define DEBUG_NEAR_POINTS 1
#define DEBUG_AIRSPACE
#endif
extern double ExtractFrequency(TCHAR*);
static const int k_nAreaCount = 15;
static const TCHAR* k_strAreaStart[k_nAreaCount] = {
_T("R"),
_T("Q"),
_T("P"),
_T("A"),
_T("B"),
_T("C"),
_T("D"),
_T("GP"),
_T("W"),
_T("E"),
_T("F"),
_T("G"),
_T("CTR"),
_T("TMZ"),
_T("RMZ")
};
static const int k_nAreaType[k_nAreaCount] = {
RESTRICT,
DANGER,
PROHIBITED,
CLASSA,
CLASSB,
CLASSC,
CLASSD,
NOGLIDER,
WAVE,
CLASSE,
CLASSF,
CLASSG,
CTR,
CLASSTMZ,
CLASSRMZ
};
// CAirspaceManager class attributes
CAirspaceManager CAirspaceManager::_instance = CAirspaceManager(CAirspaceManager::_instance);
// CAirspace class attributes
#ifndef LKAIRSP_INFOBOX_USE_SELECTED
int CAirspace::_nearesthdistance = 0; // for infobox
int CAirspace::_nearestvdistance = 0; // for infobox
TCHAR* CAirspace::_nearesthname = NULL; // for infobox
TCHAR* CAirspace::_nearestvname = NULL; // for infobox
#endif
bool CAirspaceBase::_pos_in_flyzone = false; // for refine warnings in flyzones
bool CAirspaceBase::_pred_in_flyzone = false; // for refine warnings in flyzones
bool CAirspaceBase::_pos_in_acked_nonfly_zone = false; // for refine warnings in flyzones
bool CAirspaceBase::_pred_in_acked_nonfly_zone = false; // for refine warnings in flyzones
int CAirspaceBase::_now = 0; // gps time saved
int CAirspaceBase::_hdistancemargin = 0; // calculated horizontal distance margin to use
CPoint2D CAirspaceBase::_lastknownpos(0, 0); // last known position saved for calculations
int CAirspaceBase::_lastknownalt = 0; // last known alt saved for calculations
int CAirspaceBase::_lastknownagl = 0; // last known agl saved for calculations
int CAirspaceBase::_lastknownheading = 0; // last known heading saved for calculations
int CAirspaceBase::_lastknowntrackbearing = 0; // last known track bearing saved for calculations
bool CAirspaceBase::_pred_blindtime = true; // disable predicted position based warnings near takeoff, and other conditions
CAirspace* CAirspace::_sideview_nearest_instance = NULL; // collect nearest airspace instance for sideview during warning calculations
//
// CAIRSPACE CLASS
//
// Dumps object instance to Runtime.log
void CAirspace::Dump() const {
//StartupStore(TEXT("CAirspace Dump%s"),NEWLINE);
StartupStore(TEXT(" Name:%s%s"), _name, NEWLINE);
StartupStore(TEXT(" Type:%d (%s)%s"), _type, k_strAreaStart[_type], NEWLINE);
StartupStore(TEXT(" Base.Altitude:%f%s"), _base.Altitude, NEWLINE);
StartupStore(TEXT(" Base.FL:%f%s"), _base.FL, NEWLINE);
StartupStore(TEXT(" Base.AGL:%f%s"), _base.AGL, NEWLINE);
StartupStore(TEXT(" Base.Base:%d%s"), _base.Base, NEWLINE);
StartupStore(TEXT(" Top.Altitude:%f%s"), _top.Altitude, NEWLINE);
StartupStore(TEXT(" Top.FL:%f%s"), _top.FL, NEWLINE);
StartupStore(TEXT(" Top.AGL:%f%s"), _top.AGL, NEWLINE);
StartupStore(TEXT(" Top.Base:%d%s"), _top.Base, NEWLINE);
StartupStore(TEXT(" bounds.minx,miny:%f,%f%s"), _bounds.minx, _bounds.miny, NEWLINE);
StartupStore(TEXT(" bounds.maxx,maxy:%f,%f%s"), _bounds.maxx, _bounds.maxy, NEWLINE);
}
const TCHAR* CAirspaceBase::TypeName(void) const {
return (CAirspaceManager::Instance().GetAirspaceTypeText(_type));
};
const LKColor& CAirspaceBase::TypeColor(void) const {
return MapWindow::GetAirspaceColourByClass(_type);
}
const LKBrush& CAirspaceBase::TypeBrush(void) const {
#ifdef HAVE_HATCHED_BRUSH
return MapWindow::GetAirspaceBrushByClass(_type);
#else
return MapWindow::GetAirSpaceSldBrushByClass(_type);
#endif
}
void CAirspaceBase::AirspaceAGLLookup(double av_lat, double av_lon, double *basealt_out, double *topalt_out) const {
double base_out = _base.Altitude;
double top_out = _top.Altitude;
if (((_base.Base == abAGL) || (_top.Base == abAGL))) {
RasterTerrain::Lock();
// want most accurate rounding here
RasterTerrain::SetTerrainRounding(0, 0);
double th = RasterTerrain::GetTerrainHeight(av_lat, av_lon);
if (th == TERRAIN_INVALID) th = 0; //@ 101027 FIX
// 101027 We still use 0 altitude for no terrain, what else can we do..
RasterTerrain::Unlock();
if (_base.Base == abAGL) {
base_out = th;
if (_base.AGL >= 0) base_out += _base.AGL;
}
if (_top.Base == abAGL) {
top_out = th;
if (_top.AGL >= 0) top_out += _top.AGL;
}
}
if (basealt_out) *basealt_out = base_out;
if (topalt_out) *topalt_out = top_out;
}
// Called when QNH changed
void CAirspaceBase::QnhChangeNotify() {
if (_top.Base == abFL) _top.Altitude = AltitudeToQNHAltitude((_top.FL * 100) / TOFEET);
if (_base.Base == abFL) _base.Altitude = AltitudeToQNHAltitude((_base.FL * 100) / TOFEET);
}
inline bool CheckInsideLongitude(const double &longitude, const double &lon_min, const double &lon_max) {
if (lon_min <= lon_max) {
// normal case
return ((longitude > lon_min) && (longitude < lon_max));
} else {
// area goes across 180 degree boundary, so lon_min is +ve, lon_max is -ve (flipped)
return ((longitude > lon_min) || (longitude < lon_max));
}
}
// returns true if the given altitude inside this airspace + alt extension
bool CAirspaceBase::IsAltitudeInside(int alt, int agl, int extension) const {
return (
((((_base.Base != abAGL) && (alt >= (_base.Altitude - extension)))
|| ((_base.Base == abAGL) && (agl >= (_base.AGL - extension)))))
&& ((((_top.Base != abAGL) && (alt < (_top.Altitude + extension))))
|| ((_top.Base == abAGL) && (agl < (_top.AGL + extension))))
);
}
// Step1:
// warning calculation, set initial states, etc.
void CAirspace::StartWarningCalculation(NMEA_INFO *Basic, DERIVED_INFO *Calculated) {
_pos_in_flyzone = false;
_pred_in_flyzone = false;
_pos_in_acked_nonfly_zone = false;
_pred_in_acked_nonfly_zone = false;
#ifndef LKAIRSP_INFOBOX_USE_SELECTED
_nearesthname = NULL;
_nearestvname = NULL;
_nearesthdistance = 100000;
_nearestvdistance = 100000;
#endif
_sideview_nearest_instance = NULL; // Init nearest instance for sideview
// 110518 PENDING_QUESTION
// From Paolo to Kalman: casting a double to a signed int won't create problems
// if for any reason it overflows the positive sign, going negative?
// Kalman: overflow occurs after 24855days (68years) runtime, i think it will not cause problems.
_now = (int) Basic->Time;
//Save position for further calculations made by gui threads
if (Basic->BaroAltitudeAvailable && EnableNavBaroAltitude) {
_lastknownalt = (int) Basic->BaroAltitude;
} else {
_lastknownalt = (int) Basic->Altitude;
}
_lastknownagl = (int) Calculated->AltitudeAGL;
if (_lastknownagl < 0) _lastknownagl = 0; // Limit agl to zero
CPoint2D position_now(Basic->Latitude, Basic->Longitude);
_lastknownpos = position_now;
// Horizontal distance margin
_hdistancemargin = (int) (Basic->Speed * WarningTime); // 110518 casting forced
// Heading
_lastknownheading = (int) Calculated->Heading;
// Track bearing
_lastknowntrackbearing = (int) Basic->TrackBearing;
// Predicted position blind time near takeoff
_pred_blindtime = false;
if ((!Calculated->Flying) || ((!SIMMODE)&&((Basic->Time - Calculated->TakeOffTime) < 60))) _pred_blindtime = true;
// When we are inside dlgConfiguration, NO AIRSPACE WARNINGS!
if (MenuActive) _pred_blindtime = true;
}
// Step2: first pass on all airspace instances
// Calculate warnlevel based on last/now/next position
void CAirspace::CalculateWarning(NMEA_INFO *Basic, DERIVED_INFO *Calculated) {
_warnevent = aweNone;
int alt;
int agl;
//Check actual position
_pos_inside_now = false;
if (Basic->BaroAltitudeAvailable && EnableNavBaroAltitude) {
alt = (int) Basic->BaroAltitude;
} else {
alt = (int) Basic->Altitude;
}
agl = (int) Calculated->AltitudeAGL;
if (agl < 0) agl = 0; // Limit actual altitude to surface to not get warnings if close to ground
// Calculate distances
CalculateDistance(NULL, NULL, NULL);
if (_hdistance <= 0) {
_pos_inside_now = true;
}
// Check for altitude
bool pos_altitude = IsAltitudeInside(alt, agl);
if (!pos_altitude) _pos_inside_now = false;
#ifndef LKAIRSP_INFOBOX_USE_SELECTED
if (_flyzone && _pos_inside_now) {
// If in flyzone, nearest warning point given (nearest distance to leaving the fly zone)
if (abs(_hdistance) < abs(_nearesthdistance)) {
_nearesthname = _name;
_nearesthdistance = abs(_hdistance);
}
if (abs(_vdistance) < abs(_nearestvdistance)) {
_nearestvname = _name;
_nearestvdistance = _vdistance;
}
}
if (!_flyzone) {
if (_pos_inside_now) {
// Inside a non fly zone, distance is zero
_nearesthname = _name;
_nearesthdistance = 0;
_nearestvname = _name;
_nearestvdistance = 0;
} else {
// If outside nofly zone, then nearest distance selected
// Do not count it, if directly above or below (_hdistance<=0), or give zero horiz distance?
if ((abs(_hdistance) < abs(_nearesthdistance)) && (_hdistance > 0) && IsAltitudeInside(alt, agl, AirspaceWarningVerticalMargin / 10)) {
_nearesthname = _name;
_nearesthdistance = abs(_hdistance);
}
// Just directly above or below distances counts
if ((abs(_vdistance) < abs(_nearestvdistance)) && (_hdistance < 0)) {
_nearestvname = _name;
_nearestvdistance = _vdistance;
}
}
}
#endif
if (_sideview_nearest_instance == NULL) {
_sideview_nearest_instance = this;
} else {
if (_3ddistance > 0) {
if (_3ddistance < _sideview_nearest_instance->_3ddistance) {
_sideview_nearest_instance = this;
}
}
}
// We have to calculate with the predicted position
bool pred_inside_now = false;
alt = (int) Calculated->NextAltitude;
agl = (int) Calculated->NextAltitudeAGL;
if (agl < 0) agl = 0; // Limit predicted agl to surface
// Check for altitude
pos_altitude = IsAltitudeInside(alt, agl);
if (pos_altitude) pred_inside_now = IsHorizontalInside(Calculated->NextLongitude, Calculated->NextLatitude);
if (_flyzone) {
// FLY-ZONE
if (pred_inside_now) _pred_in_flyzone = true;
if (_pos_inside_now) {
_pos_in_flyzone = true;
if (_pos_inside_last) {
if (pred_inside_now) {
// FLY-ZONE _pos_inside_last = true, _pos_inside_now = true, _pred_inside_now = true
// moving inside -> normal, no warning event
_warnevent = aweMovingInsideFly;
} else {
// FLY-ZONE _pos_inside_last = true, _pos_inside_now = true, _pred_inside_now = false
// predicted leaving, yellow warning
_warnevent = awePredictedLeavingFly;
}
} else {
// FLY-ZONE _pos_inside_last = false, _pos_inside_now = true, _pred_inside_now = X
// Entering, generate info msg
_warnevent = aweEnteringFly;
}
} else {
if (_pos_inside_last) {
// FLY-ZONE _pos_inside_last = true, _pos_inside_now = false, _pred_inside_now = X
// leaving, red warning
_warnevent = aweLeavingFly;
} else {
if (pred_inside_now) {
// FLY-ZONE _pos_inside_last = false, _pos_inside_now = false, _pred_inside_now = true
// predicted enter
_warnevent = awePredictedEnteringFly;
} else {
// FLY-ZONE _pos_inside_last = false, _pos_inside_now = false, _pred_inside_now = true
// moving outside
_warnevent = aweMovingOutsideFly;
}
}
}
} else {
// Default NON-FLY ZONE
if (pred_inside_now && (_warningacklevel > awNone)) _pred_in_acked_nonfly_zone = true;
if (_pos_inside_now) {
if (_warningacklevel > awNone) _pos_in_acked_nonfly_zone = true;
if (_pos_inside_last) {
// NON-FLY ZONE _pos_inside_last = true, _pos_inside_now = true, _pred_inside_now = X
// Moving indside or predicted leaving, nothing to do
_warnevent = aweMovingInsideNonfly;
} else {
// NON-FLY ZONE _pos_inside_last = false, _pos_inside_now = true, _pred_inside_now = X
// Entering, set warnlevel
_warnevent = aweEnteringNonfly;
}
} else {
if (_pos_inside_last) {
// NON-FLY ZONE _pos_inside_last = true, _pos_inside_now = false, _pred_inside_now = X
// leaving, or leaving and then predicted entry? -> nothing to do
_warnevent = aweLeavingNonFly;
} else {
if (pred_inside_now) {
// NON-FLY ZONE _pos_inside_last = false, _pos_inside_now = false, _pred_inside_now = true
// predicted enter
_warnevent = awePredictedEnteringNonfly;
} else {
// NON-FLY ZONE _pos_inside_last = false, _pos_inside_now = false, _pred_inside_now = false
// moving outside
_warnevent = aweMovingOutsideNonfly;
}
}
}
}//if else flyzone
_pos_inside_last = _pos_inside_now;
}
// Step3: second pass on all airspace instances
// returns true if a warning message has to be printed
bool CAirspace::FinishWarning() {
bool res = false;
int abs_hdistance = abs(_hdistance);
int abs_vdistance = abs(_vdistance);
int hdistance_histeresis = 500; // Horizontal distance histeresis to step back awNone
int vdistance_histeresis = 20; // Vertical distance histeresis to step back awNone
int hdistance_lookout = 200; // Horizontal distance to lookout from a flyzone to check what is outside
int vdistance_lookout = 20; // Vertical distance to lookout from a flyzone to check what is outside
int abs_beardiff = abs((int) AngleLimit180(_lastknownheading - _bearing));
//Calculate warning state based on airspace warning events
switch (_warnevent) {
default:
break;
// Events for FLY zones
case aweMovingInsideFly:
// If far away from border, set warnlevel to none
// If base is sfc, we skip near warnings to base, to not get disturbing messages on landing.
if ((abs_hdistance > (_hdistancemargin + hdistance_histeresis)) &&
(abs_vdistance > ((AirspaceWarningVerticalMargin / 10) + vdistance_histeresis))
) {
// Far away horizontally _and_ vertically
_warninglevel = awNone;
_hwarninglabel_hide = false;
_vwarninglabel_hide = false;
break;
}
_hwarninglabel_hide = true;
if (abs_hdistance < _hdistancemargin) {
// Check what is outside this flyzone. If another flyzone or acked nonfly zone, then we don't have to increase the warn state
double lon = 0;
double lat = 0;
double dist = abs(_hdistance) + hdistance_lookout;
FindLatitudeLongitude(_lastknownpos.Latitude(), _lastknownpos.Longitude(), _bearing, dist, &lat, &lon);
if (!CAirspaceManager::Instance().AirspaceWarningIsGoodPosition(lon, lat, _lastknownalt, _lastknownagl)) {
// Near to outside, modify warnevent to inform user
_warninglevel = awYellow;
_warnevent = aweNearOutsideFly;
_hwarninglabel_hide = false;
}
}
_vwarninglabel_hide = true;
if (abs_vdistance < (AirspaceWarningVerticalMargin / 10)) {
// Check what is outside vertically this flyzone. If another flyzone or acked nonfly zone, then we don't have to increase the warn state
int alt = _lastknownalt;
int agl = _lastknownagl;
if (_vdistance < 0) {
// adjacent airspace will be above this one
alt += abs_vdistance + vdistance_lookout;
agl += abs_vdistance + vdistance_lookout;
} else {
// adjacent airspace will be below this one
alt -= abs_vdistance + vdistance_lookout;
agl -= abs_vdistance + vdistance_lookout;
}
if (agl < 0) agl = 0;
if (!CAirspaceManager::Instance().AirspaceWarningIsGoodPosition(_lastknownpos.Longitude(), _lastknownpos.Latitude(), alt, agl)) {
// Near to outside, modify warnevent to inform user
_warninglevel = awYellow;
_warnevent = aweNearOutsideFly;
_vwarninglabel_hide = false;
}
}
break;
case awePredictedLeavingFly:
if (_pred_blindtime) break; //Do not count predicted events near takeoff, filters not settled yet
if (!(_pred_in_flyzone || _pred_in_acked_nonfly_zone)) {
// if predicted position not in other fly or acked nonfly zone, then leaving this one should be wrong
_warninglevel = awYellow;
}
break;
case aweLeavingFly:
if (_pred_blindtime) break; //Do not count predicted events near takeoff, filters not settled yet
if (!(_pos_in_flyzone || _pos_in_acked_nonfly_zone)) {
// if current position not in other fly or acked nonfly zone, then leaving this one should be wrong
_warninglevel = awRed;
}
break;
case awePredictedEnteringFly:
break;
case aweEnteringFly:
if (_pred_blindtime) break; //Do not count predicted events near takeoff, filters not settled yet
// Also preset warnlevel to awYellow, because we entering yellow zone.
// but we don't need to generate a warning message right now - force no change in warnlevel
_hwarninglabel_hide = true;
if (abs_hdistance < _hdistancemargin) {
// Check what is outside this flyzone. If another flyzone or acked nonfly zone, then we don't have to increase the warn state
double lon = 0;
double lat = 0;
double dist = abs(_hdistance) + hdistance_lookout;
FindLatitudeLongitude(_lastknownpos.Latitude(), _lastknownpos.Longitude(), _bearing, dist, &lat, &lon);
if (!CAirspaceManager::Instance().AirspaceWarningIsGoodPosition(lon, lat, _lastknownalt, _lastknownagl)) {
_warninglevelold = _warninglevel = awYellow;
_hwarninglabel_hide = false;
}
}
_vwarninglabel_hide = true;
if (abs_vdistance < (AirspaceWarningVerticalMargin / 10)) {
// Check what is outside vertically this flyzone. If another flyzone or acked nonfly zone, then we don't have to increase the warn state
int alt = _lastknownalt;
int agl = _lastknownagl;
if (_vdistance < 0) {
// adjacent airspace will be above this one
alt += abs_vdistance + vdistance_lookout;
agl += abs_vdistance + vdistance_lookout;
} else {
// adjacent airspace will be below this one
alt -= abs_vdistance + vdistance_lookout;
agl -= abs_vdistance + vdistance_lookout;
}
if (agl < 0) agl = 0;
if (!CAirspaceManager::Instance().AirspaceWarningIsGoodPosition(_lastknownpos.Longitude(), _lastknownpos.Latitude(), alt, agl)) {
_warninglevelold = _warninglevel = awYellow;
_vwarninglabel_hide = false;
}
}
// Do info message on entering a fly zone
res = true;
break;
case aweMovingOutsideFly:
// if outside, but in good zone, then this one is good as well
if ((_pos_in_flyzone || _pos_in_acked_nonfly_zone)) _warninglevel = awNone;
break;
// Events for NON-FLY zones
case aweMovingOutsideNonfly:
if (_pred_blindtime) break; //Do not count predicted events near takeoff, filters not settled yet
if ((_hdistance > (_hdistancemargin + hdistance_histeresis)) ||
(!IsAltitudeInside(_lastknownalt, _lastknownagl, (AirspaceWarningVerticalMargin / 10) + vdistance_histeresis))
) {
// Far away horizontally _or_ vertically
_warninglevel = awNone;
}
if ((_hdistance < _hdistancemargin) && (abs_beardiff <= 90)) {
if (IsAltitudeInside(_lastknownalt, _lastknownagl, (AirspaceWarningVerticalMargin / 10))) {
// Near to inside and moving closer, modify warnevent to inform user
_warninglevel = awYellow;
_warnevent = aweNearInsideNonfly;
}
}
break;
case awePredictedEnteringNonfly:
if (_pred_blindtime) break; //Do not count predicted events near takeoff, filters not settled yet
_warninglevel = awYellow;
break;
case aweEnteringNonfly:
if (_pred_blindtime) break; //Do not count predicted events near takeoff, filters not settled yet
_warninglevel = awRed;
break;
case aweMovingInsideNonfly:
if (_pred_blindtime) break; //Do not count predicted events near takeoff, filters not settled yet
_warninglevel = awRed;
break;
case aweLeavingNonFly:
if (_pred_blindtime) break; //Do not count predicted events near takeoff, filters not settled yet
_warninglevel = awYellow;
// Do info message on leaving a nonfly zone
res = true;
break;
}//sw warnevent
_warneventold = _warnevent;
// Warnstate increased above ack state -> generate message
if ((_warninglevel > _warninglevelold) && (_warninglevel > _warningacklevel)) {
_warn_repeat_time = _now + AirspaceWarningRepeatTime;
res = true;
}
// Unacknowledged warning repeated after some time
if ((_warninglevel > _warningacklevel) && (_now > _warn_repeat_time)) {
_warn_repeat_time = _now + AirspaceWarningRepeatTime;
res = true;
}
//ACK Step back, if ack time ellapsed and warningstate below ack state
if ((_warningacklevel > _warninglevel) && (_now > _warnacktimeout)) _warningacklevel = _warninglevel;
_warninglevelold = _warninglevel;
return res;
}
// Set ack timeout to configured value
void CAirspaceBase::SetAckTimeout() {
_warnacktimeout = _now + AcknowledgementTime;
}
// Gets calculated distances, returns true if distances valid
bool CAirspaceBase::GetDistanceInfo(bool &inside, int &hDistance, int &Bearing, int &vDistance) const {
if (_distances_ready) {
Bearing = _bearing;
hDistance = _hdistance;
vDistance = _vdistance;
inside = _pos_inside_now;
return true;
}
return false;
}
// Get warning point coordinates, returns true if distances valid
bool CAirspaceBase::GetWarningPoint(double &longitude, double &latitude, AirspaceWarningDrawStyle_t &hdrawstyle, int &vDistance, AirspaceWarningDrawStyle_t &vdrawstyle) const {
if (_distances_ready && _enabled) {
if (_flyzone && !_pos_inside_now) return false; // no warning labels if outside a flyzone
double dist = abs(_hdistance);
double basealt, topalt;
FindLatitudeLongitude(_lastknownpos.Latitude(), _lastknownpos.Longitude(), _bearing, dist, &latitude, &longitude);
AirspaceAGLLookup(latitude, longitude, &basealt, &topalt);
vdrawstyle = awsBlack;
if ((_lastknownalt >= basealt) && (_lastknownalt < topalt)) {
if (!_flyzone) vdrawstyle = awsRed;
} else {
if (_flyzone) vdrawstyle = awsAmber;
}
hdrawstyle = vdrawstyle;
vDistance = _vdistance;
//if (abs(_vdistance) > (AirspaceWarningVerticalMargin/10)) vdrawstyle = awsHidden;
// Nofly zones
if (!_flyzone && (_hdistance < 0)) hdrawstyle = awsHidden; // No horizontal warning label if directly below or above
if (!_flyzone && (_hdistance > 0)) vdrawstyle = awsHidden; // No vertical warning label if outside horizontally
//In flyzones if adjacent flyzone exists, we do not display labels
if (_hwarninglabel_hide) hdrawstyle = awsHidden;
if (_vwarninglabel_hide) vdrawstyle = awsHidden;
return true;
}
return false;
}
/******************************************************
* compare name and type for gruping airspaces
******************************************************/
bool CAirspaceBase::IsSame(CAirspaceBase &as2) {
bool ret = false;
if (_type == as2.Type())
if (_tcscmp((_name), (as2.Name())) == 0)
ret = true;
return ret;
}
// Calculates nearest horizontal, vertical and 3d distance to airspace based on last known position
// Returns true if inside, false if outside
bool CAirspace::CalculateDistance(int *hDistance, int *Bearing, int *vDistance, double Longitude, double Latitude, int Altitude) {
bool inside = true;
int vDistanceBase;
int vDistanceTop;
double fbearing;
double distance;
distance = Range(Longitude, Latitude, fbearing);
if (distance > 0) {
inside = false;
// if outside we need the terrain height at the intersection point
double intersect_lat, intersect_lon;
FindLatitudeLongitude(Latitude, Longitude, fbearing, distance, &intersect_lat, &intersect_lon);
AirspaceAGLLookup(intersect_lat, intersect_lon, &_base.Altitude, &_top.Altitude);
} else {
// if inside we need the terrain height at the current position
AirspaceAGLLookup(Latitude, Longitude, &_base.Altitude, &_top.Altitude);
}
vDistanceBase = Altitude - (int) (_base.Altitude);
vDistanceTop = Altitude - (int) (_top.Altitude);
if (vDistanceBase < 0 || vDistanceTop > 0) inside = false;
_bearing = (int) fbearing;
_hdistance = (int) distance;
if ((-vDistanceBase > vDistanceTop) && ((_base.Base != abAGL) || (_base.AGL > 0)))
_vdistance = vDistanceBase;
else
_vdistance = vDistanceTop;
// 3d distance calculation
if (_hdistance > 0) {
//outside horizontally
if (vDistanceBase < 0 || vDistanceTop > 0) {
//outside vertically
_3ddistance = (int) sqrt(distance * distance + (double) _vdistance * (double) _vdistance);
} else {
//inside vertically
_3ddistance = _hdistance;
}
} else {
//inside horizontally
if (vDistanceBase < 0 || vDistanceTop > 0) {
//outside vertically
_3ddistance = abs(_vdistance);
} else {
//inside vertically
if (abs(_vdistance) < abs(_hdistance)) _3ddistance = -abs(_vdistance);
else _3ddistance = _hdistance;
}
}
if (Bearing) *Bearing = _bearing;
if (hDistance) *hDistance = _hdistance;
if (vDistance) *vDistance = _vdistance;
_distances_ready = true;
return inside;
}
// Reset warnings, if airspace outside calculation scope
void CAirspaceBase::ResetWarnings() {
_warninglevel = awNone;
_warninglevelold = awNone;
_distances_ready = false;
}
// Initialize instance attributes
void CAirspaceBase::Init(const TCHAR *name, const int type, const AIRSPACE_ALT &base, const AIRSPACE_ALT &top, bool flyzone) {
LK_tcsncpy(_name, name, NAME_SIZE);
_type = type;
memcpy(&_base, &base, sizeof (_base));
memcpy(&_top, &top, sizeof (_top));
_flyzone = flyzone;
}
//
// CAIRSPACE_CIRCLE CLASS
//
CAirspace_Circle::CAirspace_Circle(const double &Center_Latitude, const double &Center_Longitude, const double &Airspace_Radius) :
CAirspace(),
_latcenter(Center_Latitude),
_loncenter(Center_Longitude),
_radius(Airspace_Radius) {
_screenpoints.reserve(65);
CalcBounds();
AirspaceAGLLookup(Center_Latitude, Center_Longitude, &_base.Altitude, &_top.Altitude);
}
// Dumps object instance to Runtime.log
void CAirspace_Circle::Dump() const {
StartupStore(TEXT("CAirspace_Circle Dump, CenterLat:%f, CenterLon:%f, Radius:%f%s"), _latcenter, _loncenter, _radius, NEWLINE);
CAirspace::Dump();
}
// Calculate unique hash code for this airspace
void CAirspace_Circle::Hash(char *hashout, int maxbufsize) const {
MD5 md5;
md5.Update((const unsigned char*) &_type, sizeof (_type));
md5.Update((const unsigned char*) _name, _tcslen(_name) * sizeof (TCHAR));
if (_base.Base == abFL) md5.Update((const unsigned char*) &_base.FL, sizeof (_base.FL));
if (_base.Base == abAGL) md5.Update((const unsigned char*) &_base.AGL, sizeof (_base.AGL));
if (_base.Base == abMSL) md5.Update((const unsigned char*) &_base.Altitude, sizeof (_base.Altitude));
if (_top.Base == abFL) md5.Update((const unsigned char*) &_top.FL, sizeof (_top.FL));
if (_top.Base == abAGL) md5.Update((const unsigned char*) &_top.AGL, sizeof (_top.AGL));
if (_top.Base == abMSL) md5.Update((const unsigned char*) &_top.Altitude, sizeof (_top.Altitude));
md5.Update((const unsigned char*) &_latcenter, sizeof (_latcenter));
md5.Update((const unsigned char*) &_loncenter, sizeof (_loncenter));
md5.Update((const unsigned char*) &_radius, sizeof (_radius));
md5.Final();
memcpy(hashout, md5.digestChars, min(maxbufsize, 33));
}
// Check if the given coordinate is inside the airspace
bool CAirspace_Circle::IsHorizontalInside(const double &longitude, const double &latitude) const {
double bearing;
if ((latitude > _bounds.miny) &&
(latitude < _bounds.maxy) &&
CheckInsideLongitude(longitude, _bounds.minx, _bounds.maxx)
) {
if (Range(longitude, latitude, bearing) < 0) {
return true;
}
}
return false;
}
// Calculate horizontal distance from a given point
double CAirspace_Circle::Range(const double &longitude, const double &latitude, double &bearing) const {
double distance;
DistanceBearing(latitude, longitude,
_latcenter,
_loncenter,
&distance, &bearing);
distance -= _radius;
if (distance < 0) bearing += 180;
if (bearing > 360) bearing -= 360;
return distance;
}
// Helper function to calculate circle bounds
void CAirspace_Circle::ScanCircleBounds(double bearing) {
double lat, lon;
FindLatitudeLongitude(_latcenter, _loncenter,
bearing, _radius,
&lat, &lon);
_bounds.minx = min(lon, _bounds.minx);
_bounds.maxx = max(lon, _bounds.maxx);
_bounds.miny = min(lat, _bounds.miny);
_bounds.maxy = max(lat, _bounds.maxy);
}
// Calculate airspace bounds
void CAirspace_Circle::CalcBounds() {
_bounds.minx = _loncenter;
_bounds.maxx = _loncenter;
_bounds.miny = _latcenter;
_bounds.maxy = _latcenter;
ScanCircleBounds(0);
ScanCircleBounds(90);
ScanCircleBounds(180);
ScanCircleBounds(270);
// JMW detect airspace that wraps across 180
if ((_bounds.minx< -90) && (_bounds.maxx > 90)) {
double tmp = _bounds.minx;
_bounds.minx = _bounds.maxx;
_bounds.maxx = tmp;
}
}
// Calculate screen coordinates for drawing
void CAirspace_Circle::CalculateScreenPosition(const rectObj &screenbounds_latlon, const int iAirspaceMode[], const int iAirspaceBrush[], const RECT& rcDraw, const ScreenProjection& _Proj, const double &ResMapScaleOverDistanceModify) {
_drawstyle = adsHidden;
// if (!_enabled) return;
if (iAirspaceMode[_type] % 2 == 1) {
if (CAirspaceManager::Instance().CheckAirspaceAltitude(_base, _top)) {
/* if (msRectOverlap(&_bounds, &screenbounds_latlon) // Ulli: this caused problems with Multiselect for Multimaps, no drawback by removing found
// || msRectContained(&screenbounds_latlon, &_bounds) is redundant here, msRectOverlap also returns true on containing!
) */
{
if ((!(iAirspaceBrush[_type] == NUMAIRSPACEBRUSHES - 1)) && ((_warninglevel == awNone) || (_warninglevel > _warningacklevel))) {
_drawstyle = adsFilled;
} else {
_drawstyle = adsOutline;
// _drawstyle = adsFilled;
}
if (!_enabled)
_drawstyle = adsDisabled;
_screencenter = _Proj.LonLat2Screen(_loncenter, _latcenter);
_screenradius = iround(_radius * ResMapScaleOverDistanceModify);
LKSurface::buildCircle(_screencenter, _screenradius, _screenpoints);
}
}
}
}
// Draw airspace
void CAirspace::Draw(LKSurface& Surface, const RECT &rc, bool param1) const {
size_t outLength = _screenpoints.size();
const POINT * clip_ptout = &(*_screenpoints.begin());
if (param1) {
if (outLength > 2) {
Surface.Polygon(clip_ptout, outLength, rc);
}
} else {
if (outLength > 1) {
Surface.Polyline(clip_ptout, outLength, rc);
}
}
}
//
// CAIRSPACE AREA CLASS
//
CAirspace_Area::CAirspace_Area(CPoint2DArray &&Area_Points) : CAirspace(), _geopoints(std::move(Area_Points)) {
CalcBounds();
AirspaceAGLLookup((_bounds.miny + _bounds.maxy) / 2.0, (_bounds.minx + _bounds.maxx) / 2.0, &_base.Altitude, &_top.Altitude);
}
// Dumps object instance to Runtime.log
void CAirspace_Area::Dump() const {
StartupStore(TEXT("CAirspace_Area Dump%s"), NEWLINE);
CAirspace::Dump();
for (CPoint2DArray::const_iterator i = _geopoints.begin(); i != _geopoints.end(); ++i) {
StartupStore(TEXT(" Point lat:%f, lon:%f%s"), i->Latitude(), i->Longitude(), NEWLINE);
}
}
// Calculate unique hash code for this airspace
void CAirspace_Area::Hash(char *hashout, int maxbufsize) const {
MD5 md5;
double dtemp;
md5.Update((const unsigned char*) &_type, sizeof (_type));
md5.Update((const unsigned char*) _name, _tcslen(_name) * sizeof (TCHAR));
if (_base.Base == abFL) md5.Update((const unsigned char*) &_base.FL, sizeof (_base.FL));
if (_base.Base == abAGL) md5.Update((const unsigned char*) &_base.AGL, sizeof (_base.AGL));
if (_base.Base == abMSL) md5.Update((const unsigned char*) &_base.Altitude, sizeof (_base.Altitude));
if (_top.Base == abFL) md5.Update((const unsigned char*) &_top.FL, sizeof (_top.FL));
if (_top.Base == abAGL) md5.Update((const unsigned char*) &_top.AGL, sizeof (_top.AGL));
if (_top.Base == abMSL) md5.Update((const unsigned char*) &_top.Altitude, sizeof (_top.Altitude));
for (CPoint2DArray::const_iterator it = _geopoints.begin(); it != _geopoints.end(); ++it) {
dtemp = it->Latitude();
md5.Update((unsigned char*) &dtemp, sizeof (dtemp));
dtemp = it->Longitude();
md5.Update((unsigned char*) &dtemp, sizeof (dtemp));
}
md5.Final();
memcpy(hashout, md5.digestChars, min(maxbufsize, 33));
}
///////////////////////////////////////////////////
// Copyright 2001, softSurfer (www.softsurfer.com)
// This code may be freely used and modified for any purpose
// providing that this copyright notice is included with it.
// SoftSurfer makes no warranty for this code, and cannot be held
// liable for any real or imagined damage resulting from its use.
// Users of this code must verify correctness for their application.
// a Point is defined by its coordinates {int x, y;}
//===================================================================
// isLeft(): tests if a point is Left|On|Right of an infinite line.
// Input: three points P0, P1, and P2
// Return: >0 for P2 left of the line through P0 and P1
// =0 for P2 on the line
// <0 for P2 right of the line
// See: the January 2001 Algorithm "Area of 2D and 3D Triangles and Polygons"
inline static float
isLeft(const CPoint2D &P0, const CPoint2D &P1, const double &longitude, const double &latitude) {
return ( (P1.Longitude() - P0.Longitude()) * (latitude - P0.Latitude())
- (longitude - P0.Longitude()) * (P1.Latitude() - P0.Latitude()));
}
// wn_PnPoly(): winding number test for a point in a polygon
// Input: P = a point,
// V[] = vertex points of a polygon V[n+1] with V[n]=V[0]
// Return: wn = the winding number (=0 only if P is outside V[])
int CAirspace_Area::wn_PnPoly(const double &longitude, const double &latitude) const {
int wn = 0; // the winding number counter
// loop through all edges of the polygon
CPoint2DArray::const_iterator it = _geopoints.begin();
CPoint2DArray::const_iterator itnext = it;
++itnext;
for (int i = 0; i < ((int) _geopoints.size() - 1); ++i, ++it, ++itnext) {
if (it->Latitude() <= latitude) { // start y <= P.Latitude
if (itnext->Latitude() > latitude) // an upward crossing
if (isLeft(*it, *itnext, longitude, latitude) > 0) // P left of edge
++wn; // have a valid up intersect
} else { // start y > P.Latitude (no test needed)
if (itnext->Latitude() <= latitude) // a downward crossing
if (isLeft(*it, *itnext, longitude, latitude) < 0) // P right of edge
--wn; // have a valid down intersect
}
}
return wn;
}
// Check if the given coordinate is inside the airspace
bool CAirspace_Area::IsHorizontalInside(const double &longitude, const double &latitude) const {
if (_geopoints.size() < 3) return false;
// first check if point is within bounding box
if (
(latitude > _bounds.miny)&&
(latitude < _bounds.maxy) &&
CheckInsideLongitude(longitude, _bounds.minx, _bounds.maxx)
) {
// it is within, so now do detailed polygon test