-
Notifications
You must be signed in to change notification settings - Fork 1
/
Application.cs
2212 lines (1801 loc) · 86.5 KB
/
Application.cs
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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Http;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Windows.Data.Json;
using Windows.Networking;
using Windows.Networking.Connectivity;
using Microsoft.MixedReality.QR;
using SimpleJSON;
using StereoKit;
namespace DutchSkies
{
using URLFetchRequest = Tuple<string, string, bool, object>;
using TileFetchRequest = Tuple<int, int, int, int, int, string[], OSMMap>;
using PostMessageRequest = Tuple<string>;
using Update = Tuple<string, object, object>;
class Application
{
enum DetailLevel { NONE, CALLSIGN, FULL };
const float PLANE_SIZE_METERS = 0.015f;
// Some often used transforms
static Matrix ROT_90_X = Matrix.R(-90f, 0f, 0f);
static Matrix ROT_MIN90_X = Matrix.R(-90f, 0f, 0f);
static Matrix ROT_180_Y = Matrix.R(0f, 180f, 0f);
// Log
List<string> log_lines;
string log_text;
LogLevel log_level = LogLevel.Info;
string our_ip;
float fps;
bool show_origin;
string discord_webhook_url;
// Configurations
List<string> stored_map_sets;
List<string> stored_landmark_sets;
List<string> stored_observer_sets;
Dictionary<string, MapSet> map_sets;
MapSet current_map_set;
string current_map_set_name;
Dictionary<string, LandmarkSet> landmark_sets;
LandmarkSet current_landmark_set;
string current_landmark_set_name;
Dictionary<string, ObserverSet> observer_sets;
ObserverSet current_observer_set;
string current_observer_set_name;
Observer map_center_observer;
// XXX need to use a different value to show in the UI
string current_configuration_name;
// UI
Pose main_window_pose, log_window_pose, configuration_window_pose;
bool show_log_window;
bool show_trim_window;
bool show_configuration_window;
// Plane data
ConcurrentQueue<Vec4> query_extent_update_queue;
Dictionary<string, PlaneData> plane_data;
int num_planes_on_map;
int num_planes_late, num_planes_missing;
int num_planes_on_ground;
DetailLevel map_detail_level;
bool map_visible;
bool map_show_plane_model, sky_show_plane_models;
bool map_show_vlines, sky_show_vlines;
bool map_show_track_lines, sky_show_trail_lines;
bool map_show_observer;
bool sky_show_landmarks;
bool use_flight_units;
int sky_d_trim; // In 0.1 degree increments
int sky_v_trim; // In centimeters
double draw_time;
Vec3 head_pos;
Quat head_orientation;
// Map geometry
const float REALWORLD_MAP_WIDTH = 1.5f; // meters
const float MAP_WINDROSE_SIZE = 0.1f; // meters
float realworld_map_height;
Dictionary<string, OSMMap> maps_in_current_set;
string current_map_name;
OSMMap current_map;
Material map_material;
float map_scale_km_to_scene;
Mesh map_quad;
Tex map_texture;
// Sky mode
Dictionary<string, Landmark> landmarks_in_current_set;
List<string> sorted_landmark_names;
Dictionary<string, Observer> observers_in_current_set;
string current_observer_name;
Observer current_observer;
const float OBSERVER_WINDROSE_SIZE = 1f; // meters
AlignmentSolver alignment_solver;
string current_alignment_landmark;
bool alignment_mode;
Pose alignment_window_pose;
Vec3 alignment_offset;
float alignment_rotation;
bool use_alignment_transform;
// Query
const int OPENSKY_QUERY_INTERVAL = 8;
// XXX rename payload to marker or something
// Thread event queue (type, data, payload)
ConcurrentQueue<Update> updates_queue;
// URL requests queue (url, type, binary, payload)
BlockingCollection<URLFetchRequest> url_requests_queue;
// Tile fetch queue (mini/j, maxi/j, zoom, payload)
BlockingCollection<TileFetchRequest> tile_requests_queue;
BlockingCollection<PostMessageRequest> message_send_queue;
bool discord_messages_enabled;
// QR code scanning
bool scanning_for_qrcodes;
QRCodeWatcher qrcode_watcher;
DateTime qrcode_watcher_start;
//Dictionary<Guid, QRData> poses = new Dictionary<Guid, QRData>();
System.Guid last_qrcode_id;
static void Main(string[] args)
{
// To get , as thousand separator
CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
// Initialize StereoKit
SKSettings settings = new SKSettings
{
appName = "DutchSkies",
assetsFolder = "Assets",
//displayPreference = DisplayMode.Flatscreen,
//noFlatscreenFallback = true,
};
if (!SK.Initialize(settings))
Environment.Exit(1);
Application app = new Application();
app.Run();
SK.Shutdown();
}
void OnLog(LogLevel level, string text)
{
string time = DateTime.Now.ToString("HH:mm:ss.fff");
if (log_lines.Count > 20)
log_lines.RemoveAt(0);
text = $"{time} {text}";
//log_lines.Add(text.Length < 120 ? text : text.Substring(0, 120) + "...\n");
log_lines.Add(text);
log_text = "";
for (int i = 0; i < log_lines.Count; i++)
log_text += log_lines[i];
}
public void Run()
{
// Set up logging
log_lines = new List<string>();
log_level = LogLevel.Info;
Log.Subscribe(OnLog);
discord_messages_enabled = false;
if (ConfigurationStore.LoadOption("discord_webhook", out discord_webhook_url))
Log.Info($"Have Discord webhook {discord_webhook_url}");
// Tweak renderer
Renderer.SetClip(0.08f, 10000f);
Renderer.EnableSky = false;
// Determine IP address (useful in debugging)
our_ip = "<unknown>";
foreach (HostName localHostName in NetworkInformation.GetHostNames())
{
if (localHostName.IPInformation != null)
{
if (localHostName.Type == HostNameType.Ipv4)
{
our_ip = localHostName.ToString();
break;
}
}
}
// Gamepad
XboxController xbox_controller = new XboxController();
//
// Start some background threads
// XXX can probably take more advantage of async/await, but let's use threads for now
//
// Queue for receiving updates from threads
updates_queue = new ConcurrentQueue<Update>();
// Launch data update thread
// Queue for sending updated query range to thread
query_extent_update_queue = new ConcurrentQueue<Vec4>();
var plane_update_thread = new Thread(FetchPlaneUpdates);
plane_update_thread.IsBackground = true;
plane_update_thread.Start(query_extent_update_queue);
Log.Info("Plane update thread started");
// Launch config fetch thread
// Queue for fetching different types of data by URL
url_requests_queue = new BlockingCollection<URLFetchRequest>(new ConcurrentQueue<URLFetchRequest>());
var url_fetch_thread = new Thread(FetchURLThread);
url_fetch_thread.IsBackground = true;
url_fetch_thread.Start();
Log.Info("URL fetch thread started");
// Tile fetch thread
// input: lat/lon range, zoomlevel, tile servers
tile_requests_queue = new BlockingCollection<TileFetchRequest>(new ConcurrentQueue<TileFetchRequest>());
var tiles_fetch_thread = new Thread(OSMTiles.FetchMapTiles);
tiles_fetch_thread.IsBackground = true;
tiles_fetch_thread.Start(new Tuple<object, object>(tile_requests_queue, updates_queue));
Log.Info("Tile fetch thread started");
message_send_queue = new BlockingCollection<PostMessageRequest>(new ConcurrentQueue<PostMessageRequest>());
var post_messages_thread = new Thread(PostMessagesThread);
post_messages_thread.IsBackground = true;
post_messages_thread.Start();
Log.Info("Message post thread started");
// Configurations
current_configuration_name = "<builtin>";
current_map_set_name = "";
current_landmark_set_name = "";
current_observer_set_name = "";
stored_map_sets = new List<string>();
stored_landmark_sets = new List<string>();
stored_observer_sets = new List<string>();
UpdateConfigurationLists();
Log.Info("--- Available stored configurations ---");
foreach (string s in stored_map_sets)
Log.Info($"[MAP_SET] '{s}'");
foreach (string s in stored_map_sets)
Log.Info($"[LANDMARK_SET] '{s}'");
foreach (string s in stored_observer_sets)
Log.Info($"[OBSERVER_SET] '{s}'");
Log.Info("--- Available stored configurations ---");
// Planes
plane_data = new Dictionary<string, PlaneData>();
// Observer
Mesh observer_cylinder_marker = Mesh.GenerateCylinder(0.002f, 0.02f, Vec3.UnitY, 8);
Mesh observer_sphere_marker = Mesh.GenerateSphere(0.006f, 8);
Material observer_marker_material = Default.Material.Copy();
observer_marker_material[MatParamName.ColorTint] = new Color(1f, 0.5f, 0f);
current_observer = null;
observers_in_current_set = null;
landmarks_in_current_set = new Dictionary<string, Landmark>();
sorted_landmark_names = landmarks_in_current_set.Keys.ToList();
sorted_landmark_names.Sort();
alignment_solver = new AlignmentSolver();
Mesh windrose_mesh = Mesh.GeneratePlane(new Vec2(1f, 1f), -Vec3.Forward, Vec3.Up);
Material windrose_material = Material.Default.Copy();
windrose_material[MatParamName.DiffuseTex] = Tex.FromFile("Windrose.png");
windrose_material.Transparency = Transparency.Blend;
windrose_material.DepthWrite = false;
//
// Maps
//
Matrix MAP_PLACEMENT_XFORM = Matrix.T(1f * Vec3.Forward - 0.7f * Vec3.Up);
map_material = Default.Material.Copy();
// Disable backface culling on the map for now, for debugging
map_material.FaceCull = Cull.None;
map_scale_km_to_scene = 0.001f;
map_sets = new Dictionary<string, MapSet>();
// Prepare built-in maps and select default
PrepareBuiltinMaps();
landmark_sets = new Dictionary<string, LandmarkSet>();
observer_sets = new Dictionary<string, ObserverSet>();
ObserverSet map_center_observer_set = new ObserverSet("<default>");
// Observer position will be updated when switching maps
map_center_observer = new Observer("<map center>", 0f, 0f, 0f);
current_observer = map_center_observer;
map_center_observer_set.Add("<map center>", current_observer);
observer_sets.Add("<default>", map_center_observer_set);
SelectMapSet("<default>");
SelectObserverSet("<default>"); // Assumes current map is set
//
// Some models
//
// Plane 3D model
Model plane_model = Model.FromFile("Airplane-cleaned.rotated.glb");
if (plane_model == null)
Log.Err("Could not load plane model");
Matrix MAP_SCALE_PLANE_SIZE = Matrix.S(PLANE_SIZE_METERS);
// XXX need to figure out why the marker needs to be much smaller compared to the plane model, doesn't make sense
Mesh plane_ground_marker = Mesh.GenerateCylinder(0.001f, 0.002f, Vec3.UnitY, 8);
if (plane_ground_marker == null)
{
Log.Err("Could not generate plane ground marker, something is really screwed! I'm giving up...");
SK.Quit();
}
Material plane_marker_material = Default.Material.Copy();
plane_marker_material[MatParamName.ColorTint] = new Color(0f, 0f, 1f);
// Floor (for non-seethrough devices)
//Matrix floorTransform = Matrix.TS(0, -1.5f, 0, new Vec3(30, 0.1f, 30));
//Material floorMaterial = new Material(Shader.FromFile("floor.hlsl"));
//floorMaterial.Transparency = Transparency.Blend;
// Initial config (for debugging)
// XXX
string initial_config = "";
//initial_config = "http://192.168.178.32:8000/config-netherlands-and-schiphol-image.json";
//initial_config = "http://192.168.178.32:8000/config-netherlands-and-schiphol-osmtiles.json";
//initial_config = "http://192.168.178.32:8000/config-newyork-image.json";
//initial_config = "http://192.168.178.32:8000/config-alps-image.json";
//initial_config = "http://192.168.178.32:8000/sanfrancisco-osmtiles.json";
//initial_config = "http://192.168.178.32:8000/observer-and-landmarks-home-backroom.json";
//initial_config = "http://192.168.178.32:8000/config-alps-surfdriveimage.json2";
//initial_config = "http://192.168.178.32:8000/sanfrancisco-image-surfdrive.json2";
//initial_config = "http://192.168.178.32:8000/config-netherlands-park-osm.json2";
if (initial_config != "")
ScheduleURLFetch(initial_config, "config_data", false, initial_config);
// Prepare for QR scanning
// Ask for permission to use the QR code tracking system
var status = QRCodeWatcher.RequestAccessAsync().Result;
if (status == QRCodeWatcherAccessStatus.Allowed)
{
// Create watcher and set up callbacks
qrcode_watcher = new QRCodeWatcher();
qrcode_watcher.Added += (o, qr) =>
{
//Log.Info($"(QR code Added handler) Found QR code: {qr.Code.Id} '{qr.Code.Data}'");
updates_queue.Enqueue(new Update("qrcode", qr.Code, ""));
};
qrcode_watcher.Updated += (o, qr) =>
{
//Log.Info($"(QR code Updated handler) QR code: {qr.Code.Id} '{qr.Code.Data}'");
updates_queue.Enqueue(new Update("qrcode", qr.Code, ""));
};
//watcher.Removed += (o, qr) => poses.Remove(qr.Code.Id);
}
else
Log.Info("Cannot perform QR code scanning, no permission given");
scanning_for_qrcodes = false;
// Alignment
alignment_mode = false;
alignment_offset = new Vec3();
alignment_rotation = 0f;
use_alignment_transform = false;
current_alignment_landmark = "";
// Main settings
main_window_pose = new Pose(0.5f, -0.2f, -0.5f, Quat.LookDir(-1, 0, 1));
log_window_pose = new Pose(0.9f, -0.2f, 0f, Quat.LookDir(-1, 0, 1));
configuration_window_pose = new Pose(-0.5f, -0.2f, 0f, Quat.LookDir(1, 0, 1));
alignment_window_pose = new Pose(-0.9f, -0.2f, 0f, Quat.LookDir(1, 0, 1));
map_detail_level = DetailLevel.FULL;
show_log_window = true;
show_trim_window = false;
show_configuration_window = true;
map_visible = true;
map_show_plane_model = true;
sky_show_plane_models = true;
map_show_vlines = true;
sky_show_vlines = false;
map_show_track_lines = true;
sky_show_trail_lines = true;
map_show_observer = false;
sky_show_landmarks = true;
use_flight_units = false;
show_origin = false;
sky_d_trim = 0;
sky_v_trim = 0;
num_planes_on_map = 0;
num_planes_late = 0;
num_planes_missing = 0;
num_planes_on_ground = 0;
const float TRACK_LINE_THICKNESS = 0.001f;
Color MAP_BASE_COLOR = new Color(0.8f, 0f, 0.8f);
Color32 MAP_TRACK_LINE_COLOR = new Color32(0, 0, 255, 255);
Color SKY_BASE_COLOR = new Color(1f, 0f, 0f);
Color SKY_TRAIL_LINE_COLOR = new Color(0.4f, 1f, 0.4f);
Color LANDMARK_VLINE_COLOR = new Color(1f, 0f, 1f);
Color LANDMARK_VLINE_COLOR_HIGHLIGHTED = new Color(0f, 1f, 0f);
Color ALIGNMENT_TEXT_COLOR = new Color(0f, 1f, 0f);
Color32 ALIGNMENT_LINE_COLOR = new Color32(0, 255, 0, 255);
const float ALIGNMENT_LINE_THICKNESS = 0.1f;
const float SKY_SCALING_THRESHOLD = 3f;
Matrix SKY_FAR_MODEL_SCALE = Matrix.S(30f);
Matrix SKY_CLOSE_MODEL_SCALE = Matrix.S(60f);
// XXX style uses gamma-space color, leading to slight difference with vline color
TextStyle MAP_TEXT_STYLE = Text.MakeStyle(Default.Font, 0.7f * U.cm, MAP_BASE_COLOR);
TextStyle SKY_TEXT_STYLE = Text.MakeStyle(Default.Font, 15f * U.m, SKY_BASE_COLOR);
TextStyle LANDMARK_TEXT_STYLE = Text.MakeStyle(Default.Font, 2f * U.m, LANDMARK_VLINE_COLOR);
TextStyle LANDMARK_TEXT_STYLE_HIGHLIGHTED = Text.MakeStyle(Default.Font, 2f * U.m, LANDMARK_VLINE_COLOR_HIGHLIGHTED);
TextStyle MAP_DIMENSION_TEXT_STYLE = Text.MakeStyle(Default.Font, 0.01f * U.m, Color.White);
TextStyle ALIGNMENT_TEXT_STYLE = Text.MakeStyle(Default.Font, 0.35f * U.m, ALIGNMENT_TEXT_COLOR);
Update update;
string update_type;
JSONNode root_node;
int fps_num_frames = 0;
float fps_start_time = Time.Totalf;
fps = 0f;
SchedulePostMessage("Entering main loop");
// Core application loop
while (SK.Step(() =>
{
draw_time = DateTimeOffset.Now.ToUnixTimeMilliseconds() * 0.001;
head_pos = Input.Head.position;
head_orientation = Input.Head.orientation;
//if (SK.System.displayType == Display.Opaque)
// Default.MeshCube.Draw(floorMaterial, floorTransform);
// World origin (for debugging)
if (show_origin)
Lines.AddAxis(Pose.Identity, 0.1f);
//
// Process received plane data, if any
//
while (!updates_queue.IsEmpty)
{
// XXX handle error
updates_queue.TryDequeue(out update);
update_type = update.Item1;
//Log.Info($"Update type '{update_type}'");
if (update_type == "map_image")
{
byte[] map_image_file = update.Item2 as byte[];
OSMMap map_to_update = update.Item3 as OSMMap;
Log.Info($"Got updated map image ({map_image_file.Length} bytes), for map '{map_to_update.id}'");
Tex texture = Tex.FromMemory(map_image_file);
if (texture != null)
{
map_to_update.texture = texture;
if (current_map_name == map_to_update.id)
map_material[MatParamName.DiffuseTex] = maps_in_current_set[map_to_update.id].texture;
}
else
Log.Err($"Could not load map image file!");
}
else if (update_type == "plane_data")
{
root_node = update.Item2 as JSONNode;
JSONNode states = root_node["states"];
Log.Info($"Got {states.Count} state updates");
float update_time = Time.Totalf;
for (int i = 0; i < states.Count; i++)
{
JSONNode plane = states[i];
// 24-bit ICAO address as string
string id = plane[0];
if (!plane_data.ContainsKey(id))
plane_data[id] = new PlaneData(id);
plane_data[id].ProcessDataUpdate(update_time, plane, current_map, current_observer);
}
}
else if (update_type == "qrcode")
{
QRCode qrcode = update.Item2 as QRCode;
if (qrcode.LastDetectedTime <= qrcode_watcher_start || qrcode.Id == last_qrcode_id)
return;
// As soon as we find a QR code stop scanning for more and apply the data in the code
qrcode_watcher.Stop();
scanning_for_qrcodes = false;
last_qrcode_id = qrcode.Id;
// Make a noise to indicate QR code was recognized
Pose pose;
World.FromSpatialNode(qrcode.SpatialGraphNodeId, out pose);
Default.SoundUnclick.Play(pose.position);
string data = qrcode.Data;
Log.Info($"Got QR code {qrcode.Id} dtime {qrcode.LastDetectedTime}, starttime {qrcode_watcher_start}");
Log.Info($"qr data: '{data}'");
Log.Info($"Disabled further QR code scanning");
if (data.StartsWith("http://") || data.StartsWith("https://"))
{
Log.Info($"Scheduling config fetch from {data}");
ScheduleURLFetch(data, "config_data", false, data);
}
else
{
Log.Info("Parsing QR code that doesn't look like URL as JSON");
try
{
JSON.Parse(data);
ProcessConfigurationData(data, "");
}
catch (Exception e)
{
Log.Warn($"Discarding QR code data, neither a URL or parseable JSON");
}
}
}
else if (update_type == "config_data")
{
ProcessConfigurationData(update.Item2 as string, update.Item3 as string);
}
else if (update_type == "map_tilefetch_progress")
{
// XXX do something with it :)
}
else
Log.Warn($"Unhandled update type '{update_type}!");
}
// Gamepad
if (alignment_mode && xbox_controller.QueryState())
{
if (xbox_controller.LeftThumbstickX < -0.2f)
sky_d_trim--;
else if (xbox_controller.LeftThumbstickX > 0.2f)
sky_d_trim++;
if (xbox_controller.Pressed(XboxController.DPAD_LEFT))
sky_d_trim -= 10;
else if (xbox_controller.Pressed(XboxController.DPAD_RIGHT))
sky_d_trim += 10;
if (xbox_controller.Pressed(XboxController.DPAD_UP))
{
int idx = sorted_landmark_names.IndexOf(current_alignment_landmark);
idx = Math.Max(idx - 1, 0);
current_alignment_landmark = sorted_landmark_names[idx];
}
else if (xbox_controller.Pressed(XboxController.DPAD_DOWN))
{
int idx = sorted_landmark_names.IndexOf(current_alignment_landmark);
idx = Math.Min(sorted_landmark_names.Count - 1, idx + 1);
current_alignment_landmark = sorted_landmark_names[idx];
}
if (xbox_controller.Pressed(XboxController.A))
{
if (!use_alignment_transform)
{
var hp = Input.Head.position;
var ho = Input.Head.orientation.Rotate(new Vec3(0f, 0f, -1f));
JsonObject jo = new JsonObject();
jo["lm"] = JsonValue.CreateStringValue(current_alignment_landmark);
jo["head_pos"] = JsonValue.CreateStringValue($"[{hp.x:F6}, {hp.y:F6}, {hp.z:F6}]");
jo["head_ori"] = JsonValue.CreateStringValue($"[{ho.x:F6}, {ho.y:F6}, {ho.z:F6}]");
SchedulePostMessage(jo.ToString());
alignment_solver.AddObservation(current_alignment_landmark, hp, ho);
}
else
Log.Warn("Not adding observation, as alignment transform is active");
}
else if (xbox_controller.Pressed(XboxController.X))
{
if (!use_alignment_transform)
{
SchedulePostMessage($"Remove observations, lm {current_alignment_landmark}, ");
alignment_solver.RemoveObservations(current_alignment_landmark);
}
else
Log.Warn("Not removing observations, as alignment transform is active");
}
else if (xbox_controller.Pressed(XboxController.B))
{
// The found solution transform the observations onto the world coordinate system
UpdateAlignmentSolution();
}
else if (xbox_controller.Pressed(XboxController.Y))
{
// Toggle use of alignment
use_alignment_transform = !use_alignment_transform;
}
}
//
// Draw map and planes
//
Hierarchy.Push(MAP_PLACEMENT_XFORM);
// Map
if (map_visible)
{
const float ABOVE = 0.003f;
map_quad.Draw(map_material, ROT_MIN90_X);
// XXX can be precomputed, only changes when map changes
windrose_mesh.Draw(windrose_material,
ROT_MIN90_X *
Matrix.S(MAP_WINDROSE_SIZE) *
Matrix.T(-REALWORLD_MAP_WIDTH * 0.5f + 0.52f * MAP_WINDROSE_SIZE, ABOVE, realworld_map_height * 0.5f - 0.52f * MAP_WINDROSE_SIZE));
// Dimensions
Text.Add($"{current_map.width:F0} km", ROT_180_Y * ROT_MIN90_X * Matrix.T(0f, 0f, 0.5f * realworld_map_height + 0.01f), MAP_DIMENSION_TEXT_STYLE,
TextAlign.TopCenter);
Text.Add($"{current_map.height:F0} km", ROT_180_Y * ROT_MIN90_X * Matrix.R(0f, -90f, 0f) * Matrix.T(0.5f * REALWORLD_MAP_WIDTH + 0.01f, 0f, 0f), MAP_DIMENSION_TEXT_STYLE,
TextAlign.CenterLeft);
}
// Planes
num_planes_on_map = 0;
num_planes_on_ground = 0;
num_planes_late = 0;
num_planes_missing = 0;
foreach (var plane in plane_data.Values)
{
string callsign = $"{plane.callsign}";
if (plane.update_state == PlaneData.UpdateState.MISSING)
{
// Don't bother until it comes back alive again
num_planes_missing++;
continue;
}
else if (plane.update_state == PlaneData.UpdateState.LATE)
{
callsign = $"({callsign})";
num_planes_late++;
}
plane.Update(draw_time);
var map_pos = plane.computed_map_position;
var pos = ROT_MIN90_X * map_pos * map_scale_km_to_scene;
// XXX should use interpolated map-space position
if (!current_map.OnMapLatLon(plane.last_lat, plane.last_lon))
continue;
num_planes_on_map++;
if (plane.on_ground)
{
// XXX could set y to 0, as there seem to be cases where a plane is marked on-ground, but has an incorrect altitude value
plane_ground_marker.Draw(plane_marker_material, ROT_MIN90_X * Matrix.R(0f, -plane.last_heading, 0f) * Matrix.T(pos));
num_planes_on_ground++;
continue;
}
if (map_show_plane_model)
{
//Lines.AddAxis(new Pose(plane.computed_position * map_scale_km_to_scene, Quat.FromAngles(0f, 0f, -plane.last_heading)));
plane_model.Draw(MAP_SCALE_PLANE_SIZE * ROT_MIN90_X * Matrix.R(-plane.computed_climb_angle * 2f, 0f, 0f)
* Matrix.R(0f, -plane.last_heading, 0f) * Matrix.T(pos));
}
// Plane information
Vec3 dir = head_pos - MAP_PLACEMENT_XFORM.Transform(pos);
dir.y = 0f;
Quat textquat = Quat.LookDir(dir);
Vec3 text_pos = pos;
TextAlign pos_align = TextAlign.XLeft | TextAlign.YTop;
if (pos.y < 0.05f)
{
pos_align = TextAlign.XLeft | TextAlign.YBottom;
text_pos.y = 0.01f;
}
if (map_detail_level == DetailLevel.CALLSIGN)
{
Text.Add(
$"{callsign}",
Matrix.TR(pos, textquat),
MAP_TEXT_STYLE,
pos_align,
TextAlign.XLeft | TextAlign.YTop,
-0.01f, 0.00f);
}
else if (map_detail_level == DetailLevel.FULL)
{
float vrate = plane.last_vertical_rate;
string vstring = " ";
string astring = "";
string sstring = "";
if (use_flight_units)
{
sstring = $"{plane.last_velocity * 1.94384449f:N0} kn";
int fl = (int)MathF.Round(plane.computed_barometric_altitude / 30.48f);
astring = $"FL {fl:D3}";
vrate = vrate / 0.3048f * 60f;
if (vrate > 1f)
vstring = $"▲ {vrate:F0} ft/min";
else if (vrate < -1f)
vstring = $"▼ {-vrate:F0} ft/min";
}
else
{
sstring = $"{plane.last_velocity * 3.6f:N0} km / h";
astring = $"{plane.computed_barometric_altitude:N0} m";
if (vrate > 1f)
vstring = $"▲ {vrate:F0} m/s";
else if (vrate < -1f)
vstring = $"▼ {-vrate:F0} m/s";
}
Text.Add(
$"{callsign}\n{plane.last_heading:F0}°\n{sstring}\n{astring}\n{vstring}",
Matrix.TR(pos, textquat),
MAP_TEXT_STYLE,
pos_align,
TextAlign.XLeft | TextAlign.YTop,
-0.006f, 0f);
}
// Plane lines vertically to the ground position
if (map_show_vlines)
Lines.Add(pos, new Vec3(pos.x, 0f, pos.z), MAP_BASE_COLOR, 0.001f);
// Historical track
if (map_show_track_lines && plane.map_track_points.Count >= 2)
{
LinePoint[] lp = new LinePoint[plane.map_track_points.Count];
int idx = 0;
foreach (Vec3 p in plane.map_track_points)
lp[idx++] = new LinePoint(ROT_MIN90_X * p * map_scale_km_to_scene, MAP_TRACK_LINE_COLOR, TRACK_LINE_THICKNESS);
Lines.Add(lp);
}
}
// Observer location on map
if (map_show_observer && current_observer.on_map)
{
Vec3 observer_pos = ROT_MIN90_X.Transform(current_observer.map_position) * map_scale_km_to_scene;
observer_cylinder_marker.Draw(observer_marker_material, Matrix.T(0f, 0.005f, 0f) * Matrix.T(observer_pos));
observer_sphere_marker.Draw(observer_marker_material, Matrix.T(0f, 0.015f, 0f) * Matrix.T(observer_pos));
}
Hierarchy.Pop();
//
// Draw planes in sky
// Assumes Forward (-Z) is pointing North, although a manual trim is applied on top of that
//
if (use_alignment_transform)
{
Hierarchy.Push(
Matrix.R(0f, alignment_rotation - sky_d_trim * 0.1f, 0f)
*
Matrix.T(alignment_offset + new Vec3(0f, sky_v_trim * 0.1f, 0f))
);
}
else
Hierarchy.Push(Matrix.R(0f, -sky_d_trim * 0.1f, 0f) * Matrix.T(0f, sky_v_trim * 0.1f, 0f));
bool scaled;
foreach (var plane in plane_data.Values)
{
if (plane.on_ground)
continue;
if (plane.update_state == PlaneData.UpdateState.MISSING)
continue;
string callsign = plane.callsign;
if (plane.update_state == PlaneData.UpdateState.LATE)
callsign = $"({callsign})";
var pos = ROT_MIN90_X.Transform(plane.computed_sky_position);
var prev_pos = ROT_MIN90_X.Transform(plane.previous_sky_position);
// Don't bother with planes below the horizon
if (pos.y < 0f)
continue;
// XXX should use inrterpolation map-space position
if (!current_map.OnMapLatLon(plane.last_lat, plane.last_lon))
continue;
if (plane.observer_distance > SKY_SCALING_THRESHOLD)
{
// To avoid large clipping distances move plane along the line from plane to viewer,
// with a smaller plane model to avoid a weird scaling visual issues
// Vector from head to plane
Vec3 v = pos - Input.Head.position;
v.Normalize();
pos *= SKY_SCALING_THRESHOLD / plane.observer_distance;
prev_pos *= SKY_SCALING_THRESHOLD / plane.observer_distance;
//Log.Info($"[{plane.callsign}] position scaled to {pos}");
scaled = true;
}
else
scaled = false;
if (sky_show_plane_models)
{
// Plane
if (scaled)
{
// Plane far away, draw closer but smaller
plane_model.Draw(SKY_FAR_MODEL_SCALE * ROT_MIN90_X * Matrix.R(0f, -plane.last_heading, 0f) * Matrix.T(pos));
}
else
{
// Plane is close, use model with "realistic" scale
plane_model.Draw(SKY_CLOSE_MODEL_SCALE * ROT_MIN90_X * Matrix.R(0f, -plane.last_heading, 0f) * Matrix.T(pos));
}
}
if (sky_show_vlines)
{
// Vertical line, start slightly below plane to make room for text
Lines.Add(new Vec3(pos.x, pos.y - 120f, pos.z), new Vec3(pos.x, 0f, pos.z), SKY_BASE_COLOR, 3f);
}
if (sky_show_trail_lines)
{
// Trail line
Lines.Add(prev_pos, pos, SKY_TRAIL_LINE_COLOR, 3f);
}
// Text labels
Quat textquat = Quat.LookAt(pos, head_pos, Vec3.UnitY);
string astring = "";
string sstring = "";
if (use_flight_units)
{
sstring = $"{plane.last_velocity * 1.94384449f:N0} kn";
int fl = (int)MathF.Round(plane.computed_geometric_altitude / 30.48f);
astring = $"FL {fl:D3} (G)";
}
else
{
sstring = $"{plane.last_velocity * 3.6f:N0} km / h";
astring = $"{plane.computed_geometric_altitude:N0} m (G)";
}
Text.Add(
$"({plane.observer_distance:F0} km)",
Matrix.R(textquat) * Matrix.T(pos),
SKY_TEXT_STYLE,
TextAlign.XCenter | TextAlign.YTop,
TextAlign.XCenter | TextAlign.YTop,
0f, 30f);
Text.Add(
$"{callsign}\n{astring}\n{sstring}",
Matrix.R(textquat) * Matrix.T(pos),
SKY_TEXT_STYLE,
TextAlign.XCenter | TextAlign.YTop,
TextAlign.XCenter | TextAlign.YTop,
0f, -25f);
}
// Landmarks
if (sky_show_landmarks)
{
Color color;
TextStyle style;
foreach (KeyValuePair<string, Landmark> item in landmarks_in_current_set)
{
Landmark landmark = item.Value;
Vec3 pos = ROT_MIN90_X.Transform(landmark.sky_position);
color = LANDMARK_VLINE_COLOR;
style = LANDMARK_TEXT_STYLE;
if (alignment_mode && item.Key == current_alignment_landmark)
{
color = LANDMARK_VLINE_COLOR_HIGHLIGHTED;
style = LANDMARK_TEXT_STYLE_HIGHLIGHTED;
}
Lines.Add(pos, new Vec3(pos.x, pos.y - landmark.height, pos.z), color, 2f);
Quat textquat = Quat.LookAt(pos, head_pos, Vec3.UnitY);
Text.Add(
$"{item.Key}",
Matrix.R(textquat) * Matrix.T(pos),
style,
TextAlign.XCenter | TextAlign.YTop,
TextAlign.XCenter | TextAlign.YTop,
0f, 2f);
}
}
// Observer origin and orientation
// XXX as we don't have an exact distance to the floor use a good guess
windrose_mesh.Draw(windrose_material, ROT_MIN90_X * Matrix.S(OBSERVER_WINDROSE_SIZE) * Matrix.T(0f, -1.5f, 0f));
Hierarchy.Pop();
// Alignment (head coordinate space)
if (alignment_mode && current_alignment_landmark != "")
{
Vec2 size = new Vec2(1 * U.cm, 0);
Hierarchy.Push(Input.Head.ToMatrix());
Lines.Add(new Vec3(0f, -1.5f, -20f), new Vec3(0f, 1.5f, -20f), ALIGNMENT_LINE_COLOR, ALIGNMENT_LINE_THICKNESS);
Lines.Add(new Vec3(-0.2f, 0f, -20f), new Vec3(0.2f, 0f, -20f), ALIGNMENT_LINE_COLOR, ALIGNMENT_LINE_THICKNESS);
Text.Add($"[{alignment_solver.ObservationCount(current_alignment_landmark)}] {current_alignment_landmark}",
Matrix.R(0f, 180f, 0f) * Matrix.T(0f, -2f, -20f), ALIGNMENT_TEXT_STYLE);