/
GeospatialController.cs
1510 lines (1316 loc) · 56.9 KB
/
GeospatialController.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
// <copyright file="GeospatialController.cs" company="Google LLC">
//
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
#if UNITY_2022_3_OR_NEWER && !ARCORE_USE_ARF_5
// For AR Foundation 5.X compatibility, define the ARCORE_USE_ARF_5
// symbol, see https://docs.unity3d.com/Manual/CustomScriptingSymbols.html
// You can define ARCORE_USE_ARF_5 for Unity 2021.x or higher but you have
// to define it after 2022.x
#warning For AR Foundation 5.X compatibility, define the ARCORE_USE_ARF_5 symbol
#endif
#if !ENABLE_LEGACY_INPUT_MANAGER
// Input.location will not work at runtime with out the old input system.
// Given that sample has not been ported to support new input
// Check that Project Settings > Player > Other Settings > Active Input Handling
// is set to Both or Input Manager (Old)
#error Input.location API requires Active Input Handling to be set to Input Manager (Old) or Both
#endif
#if !ENABLE_INPUT_SYSTEM && ARCORE_USE_ARF_5
// The camera's pose driver in ARF5 needs Input System (New) but given we need Input Manager
// (Old) for Input.location (see above) ARF5 needs both.
// Check that Project Settings > Player > Other Settings > Active Input Handling
// is set to Both
#error The camera's pose driver needs Input System (New) so set Active Input Handling to Both
#endif
namespace Google.XR.ARCoreExtensions.Samples.Geospatial
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#if ARCORE_USE_ARF_5 // use ARF 5
using Unity.XR.CoreUtils;
#endif
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
#if UNITY_ANDROID
using UnityEngine.Android;
#endif
/// <summary>
/// Controller for Geospatial sample.
/// </summary>
[SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1118:ParameterMustNotSpanMultipleLines",
Justification = "Bypass source check.")]
public class GeospatialController : MonoBehaviour
{
[Header("AR Components")]
#if ARCORE_USE_ARF_5 // use ARF 5
/// <summary>
/// The XROrigin used in the sample.
/// </summary>
public XROrigin Origin;
#else // use ARF 4
/// <summary>
/// The ARSessionOrigin used in the sample.
/// </summary>
public ARSessionOrigin SessionOrigin;
#endif
/// <summary>
/// The ARSession used in the sample.
/// </summary>
public ARSession Session;
/// <summary>
/// The ARAnchorManager used in the sample.
/// </summary>
public ARAnchorManager AnchorManager;
/// <summary>
/// The ARRaycastManager used in the sample.
/// </summary>
public ARRaycastManager RaycastManager;
/// <summary>
/// The AREarthManager used in the sample.
/// </summary>
public AREarthManager EarthManager;
/// <summary>
/// The ARStreetscapeGeometryManager used in the sample.
/// </summary>
public ARStreetscapeGeometryManager StreetscapeGeometryManager;
/// <summary>
/// The ARCoreExtensions used in the sample.
/// </summary>
public ARCoreExtensions ARCoreExtensions;
/// <summary>
/// The StreetscapeGeometry materials for rendering geometry building meshes.
/// </summary>
public List<Material> StreetscapeGeometryMaterialBuilding;
/// <summary>
/// The StreetscapeGeometry material for rendering geometry terrain meshes.
/// </summary>
public Material StreetscapeGeometryMaterialTerrain;
[Header("UI Elements")]
/// <summary>
/// A 3D object that presents a Geospatial Anchor.
/// </summary>
public GameObject GeospatialPrefab;
/// <summary>
/// A 3D object that presents a Geospatial Terrain anchor.
/// </summary>
public GameObject TerrainPrefab;
/// <summary>
/// UI element showing privacy prompt.
/// </summary>
public GameObject PrivacyPromptCanvas;
/// <summary>
/// UI element showing VPS availability notification.
/// </summary>
public GameObject VPSCheckCanvas;
/// <summary>
/// UI element containing all AR view contents.
/// </summary>
public GameObject ARViewCanvas;
/// <summary>
/// UI element for clearing all anchors, including history.
/// </summary>
public Button ClearAllButton;
/// <summary>
/// UI element that enables streetscape geometry visibility.
/// </summary>
public Toggle GeometryToggle;
/// <summary>
/// UI element to display or hide the Anchor Settings panel.
/// </summary>
public Button AnchorSettingButton;
/// <summary>
/// UI element for the Anchor Settings panel.
/// </summary>
public GameObject AnchorSettingPanel;
/// <summary>
/// UI element that toggles anchor type to Geometry.
/// </summary>
public Toggle GeospatialAnchorToggle;
/// <summary>
/// UI element that toggles anchor type to Terrain.
/// </summary>
public Toggle TerrainAnchorToggle;
/// <summary>
/// UI element that toggles anchor type to Rooftop.
/// </summary>
public Toggle RooftopAnchorToggle;
/// <summary>
/// UI element to display information at runtime.
/// </summary>
public GameObject InfoPanel;
/// <summary>
/// Text displaying <see cref="GeospatialPose"/> information at runtime.
/// </summary>
public Text InfoText;
/// <summary>
/// Text displaying in a snack bar at the bottom of the screen.
/// </summary>
public Text SnackBarText;
/// <summary>
/// Text displaying debug information, only activated in debug build.
/// </summary>
public Text DebugText;
/// <summary>
/// Help message shown while localizing.
/// </summary>
private const string _localizingMessage = "Localizing your device to set anchor.";
/// <summary>
/// Help message shown while initializing Geospatial functionalities.
/// </summary>
private const string _localizationInitializingMessage =
"Initializing Geospatial functionalities.";
/// <summary>
/// Help message shown when <see cref="AREarthManager.EarthTrackingState"/> is not tracking
/// or the pose accuracies are beyond thresholds.
/// </summary>
private const string _localizationInstructionMessage =
"Point your camera at buildings, stores, and signs near you.";
/// <summary>
/// Help message shown when location fails or hits timeout.
/// </summary>
private const string _localizationFailureMessage =
"Localization not possible.\n" +
"Close and open the app to restart the session.";
/// <summary>
/// Help message shown when localization is completed.
/// </summary>
private const string _localizationSuccessMessage = "Localization completed.";
/// <summary>
/// The timeout period waiting for localization to be completed.
/// </summary>
private const float _timeoutSeconds = 180;
/// <summary>
/// Indicates how long a information text will display on the screen before terminating.
/// </summary>
private const float _errorDisplaySeconds = 3;
/// <summary>
/// The key name used in PlayerPrefs which indicates whether the privacy prompt has
/// displayed at least one time.
/// </summary>
private const string _hasDisplayedPrivacyPromptKey = "HasDisplayedGeospatialPrivacyPrompt";
/// <summary>
/// The key name used in PlayerPrefs which stores geospatial anchor history data.
/// The earliest one will be deleted once it hits storage limit.
/// </summary>
private const string _persistentGeospatialAnchorsStorageKey = "PersistentGeospatialAnchors";
/// <summary>
/// The limitation of how many Geospatial Anchors can be stored in local storage.
/// </summary>
private const int _storageLimit = 20;
/// <summary>
/// Accuracy threshold for orientation yaw accuracy in degrees that can be treated as
/// localization completed.
/// </summary>
private const double _orientationYawAccuracyThreshold = 25;
/// <summary>
/// Accuracy threshold for heading degree that can be treated as localization completed.
/// </summary>
private const double _headingAccuracyThreshold = 25;
/// <summary>
/// Accuracy threshold for altitude and longitude that can be treated as localization
/// completed.
/// </summary>
private const double _horizontalAccuracyThreshold = 20;
/// <summary>
/// Determines if the anchor settings panel is visible in the UI.
/// </summary>
private bool _showAnchorSettingsPanel = false;
/// <summary>
/// Represents the current anchor type of the anchor being placed in the scene.
/// </summary>
private AnchorType _anchorType = AnchorType.Geospatial;
/// <summary>
/// Determines if streetscape geometry is rendered in the scene.
/// </summary>
private bool _streetscapeGeometryVisibility = false;
/// <summary>
/// Determines which building material will be used for the current building mesh.
/// </summary>
private int _buildingMatIndex = 0;
/// <summary>
/// Dictionary of streetscapegeometry handles to render objects for rendering
/// streetscapegeometry meshes.
/// </summary>
private Dictionary<TrackableId, GameObject> _streetscapegeometryGOs =
new Dictionary<TrackableId, GameObject>();
/// <summary>
/// ARStreetscapeGeometries added in the last Unity Update.
/// </summary>
List<ARStreetscapeGeometry> _addedStreetscapeGeometries =
new List<ARStreetscapeGeometry>();
/// <summary>
/// ARStreetscapeGeometries updated in the last Unity Update.
/// </summary>
List<ARStreetscapeGeometry> _updatedStreetscapeGeometries =
new List<ARStreetscapeGeometry>();
/// <summary>
/// ARStreetscapeGeometries removed in the last Unity Update.
/// </summary>
List<ARStreetscapeGeometry> _removedStreetscapeGeometries =
new List<ARStreetscapeGeometry>();
/// <summary>
/// Determines if streetscape geometry should be removed from the scene.
/// </summary>
private bool _clearStreetscapeGeometryRenderObjects = false;
private bool _waitingForLocationService = false;
private bool _isInARView = false;
private bool _isReturning = false;
private bool _isLocalizing = false;
private bool _enablingGeospatial = false;
private bool _shouldResolvingHistory = false;
private float _localizationPassedTime = 0f;
private float _configurePrepareTime = 3f;
private GeospatialAnchorHistoryCollection _historyCollection = null;
private List<GameObject> _anchorObjects = new List<GameObject>();
private IEnumerator _startLocationService = null;
private IEnumerator _asyncCheck = null;
/// <summary>
/// Callback handling "Get Started" button click event in Privacy Prompt.
/// </summary>
public void OnGetStartedClicked()
{
PlayerPrefs.SetInt(_hasDisplayedPrivacyPromptKey, 1);
PlayerPrefs.Save();
SwitchToARView(true);
}
/// <summary>
/// Callback handling "Learn More" Button click event in Privacy Prompt.
/// </summary>
public void OnLearnMoreClicked()
{
Application.OpenURL(
"https://developers.google.com/ar/data-privacy");
}
/// <summary>
/// Callback handling "Clear All" button click event in AR View.
/// </summary>
public void OnClearAllClicked()
{
foreach (var anchor in _anchorObjects)
{
Destroy(anchor);
}
_anchorObjects.Clear();
_historyCollection.Collection.Clear();
SnackBarText.text = "Anchor(s) cleared!";
ClearAllButton.gameObject.SetActive(false);
SaveGeospatialAnchorHistory();
}
/// <summary>
/// Callback handling "Continue" button click event in AR View.
/// </summary>
public void OnContinueClicked()
{
VPSCheckCanvas.SetActive(false);
}
/// <summary>
/// Callback handling "Geometry" toggle event in AR View.
/// </summary>
/// <param name="enabled">Whether to enable Streetscape Geometry visibility.</param>
public void OnGeometryToggled(bool enabled)
{
_streetscapeGeometryVisibility = enabled;
if (!_streetscapeGeometryVisibility)
{
_clearStreetscapeGeometryRenderObjects = true;
}
}
/// <summary>
/// Callback handling the "Anchor Setting" panel display or hide event in AR View.
/// </summary>
public void OnAnchorSettingButtonClicked()
{
_showAnchorSettingsPanel = !_showAnchorSettingsPanel;
if (_showAnchorSettingsPanel)
{
SetAnchorPanelState(true);
}
else
{
SetAnchorPanelState(false);
}
}
/// <summary>
/// Callback handling Geospatial anchor toggle event in AR View.
/// </summary>
/// <param name="enabled">Whether to enable Geospatial anchors.</param>
public void OnGeospatialAnchorToggled(bool enabled)
{
// GeospatialAnchorToggle.GetComponent<Toggle>().isOn = true;;
_anchorType = AnchorType.Geospatial;
SetAnchorPanelState(false);
}
/// <summary>
/// Callback handling Terrain anchor toggle event in AR View.
/// </summary>
/// <param name="enabled">Whether to enable Terrain anchors.</param>
public void OnTerrainAnchorToggled(bool enabled)
{
// TerrainAnchorToggle.GetComponent<Toggle>().isOn = true;
_anchorType = AnchorType.Terrain;
SetAnchorPanelState(false);
}
/// <summary>
/// Callback handling Rooftop anchor toggle event in AR View.
/// </summary>
/// <param name="enabled">Whether to enable Rooftop anchors.</param>
public void OnRooftopAnchorToggled(bool enabled)
{
// RooftopAnchorToggle.GetComponent<Toggle>().isOn = true;
_anchorType = AnchorType.Rooftop;
SetAnchorPanelState(false);
}
/// <summary>
/// Unity's Awake() method.
/// </summary>
public void Awake()
{
// Lock screen to portrait.
Screen.autorotateToLandscapeLeft = false;
Screen.autorotateToLandscapeRight = false;
Screen.autorotateToPortraitUpsideDown = false;
Screen.orientation = ScreenOrientation.Portrait;
// Enable geospatial sample to target 60fps camera capture frame rate
// on supported devices.
// Note, Application.targetFrameRate is ignored when QualitySettings.vSyncCount != 0.
Application.targetFrameRate = 60;
#if ARCORE_USE_ARF_5 // use ARF 5
if (Origin == null)
{
Debug.LogError("Cannot find XROrigin.");
}
#else // use ARF 4
if (SessionOrigin == null)
{
Debug.LogError("Cannot find ARSessionOrigin.");
}
#endif
if (Session == null)
{
Debug.LogError("Cannot find ARSession.");
}
if (ARCoreExtensions == null)
{
Debug.LogError("Cannot find ARCoreExtensions.");
}
}
/// <summary>
/// Unity's OnEnable() method.
/// </summary>
public void OnEnable()
{
_startLocationService = StartLocationService();
StartCoroutine(_startLocationService);
_isReturning = false;
_enablingGeospatial = false;
InfoPanel.SetActive(false);
GeometryToggle.gameObject.SetActive(false);
AnchorSettingButton.gameObject.SetActive(false);
AnchorSettingPanel.gameObject.SetActive(false);
GeospatialAnchorToggle.gameObject.SetActive(false);
TerrainAnchorToggle.gameObject.SetActive(false);
RooftopAnchorToggle.gameObject.SetActive(false);
ClearAllButton.gameObject.SetActive(false);
DebugText.gameObject.SetActive(Debug.isDebugBuild && EarthManager != null);
GeometryToggle.onValueChanged.AddListener(OnGeometryToggled);
AnchorSettingButton.onClick.AddListener(OnAnchorSettingButtonClicked);
GeospatialAnchorToggle.onValueChanged.AddListener(OnGeospatialAnchorToggled);
TerrainAnchorToggle.onValueChanged.AddListener(OnTerrainAnchorToggled);
RooftopAnchorToggle.onValueChanged.AddListener(OnRooftopAnchorToggled);
_localizationPassedTime = 0f;
_isLocalizing = true;
SnackBarText.text = _localizingMessage;
LoadGeospatialAnchorHistory();
_shouldResolvingHistory = _historyCollection.Collection.Count > 0;
SwitchToARView(PlayerPrefs.HasKey(_hasDisplayedPrivacyPromptKey));
if (StreetscapeGeometryManager == null)
{
Debug.LogWarning("StreetscapeGeometryManager must be set in the " +
"GeospatialController Inspector to render StreetscapeGeometry.");
}
if (StreetscapeGeometryMaterialBuilding.Count == 0)
{
Debug.LogWarning("StreetscapeGeometryMaterialBuilding in the " +
"GeospatialController Inspector must contain at least one material " +
"to render StreetscapeGeometry.");
return;
}
if (StreetscapeGeometryMaterialTerrain == null)
{
Debug.LogWarning("StreetscapeGeometryMaterialTerrain must be set in the " +
"GeospatialController Inspector to render StreetscapeGeometry.");
return;
}
// get access to ARstreetscapeGeometries in ARStreetscapeGeometryManager
if (StreetscapeGeometryManager)
{
StreetscapeGeometryManager.StreetscapeGeometriesChanged += GetStreetscapeGeometry;
}
}
/// <summary>
/// Unity's OnDisable() method.
/// </summary>
public void OnDisable()
{
StopCoroutine(_asyncCheck);
_asyncCheck = null;
StopCoroutine(_startLocationService);
_startLocationService = null;
Debug.Log("Stop location services.");
Input.location.Stop();
foreach (var anchor in _anchorObjects)
{
Destroy(anchor);
}
_anchorObjects.Clear();
SaveGeospatialAnchorHistory();
if (StreetscapeGeometryManager)
{
StreetscapeGeometryManager.StreetscapeGeometriesChanged -=
GetStreetscapeGeometry;
}
}
/// <summary>
/// Unity's Update() method.
/// </summary>
public void Update()
{
if (!_isInARView)
{
return;
}
UpdateDebugInfo();
// Check session error status.
LifecycleUpdate();
if (_isReturning)
{
return;
}
if (ARSession.state != ARSessionState.SessionInitializing &&
ARSession.state != ARSessionState.SessionTracking)
{
return;
}
// Check feature support and enable Geospatial API when it's supported.
var featureSupport = EarthManager.IsGeospatialModeSupported(GeospatialMode.Enabled);
switch (featureSupport)
{
case FeatureSupported.Unknown:
return;
case FeatureSupported.Unsupported:
ReturnWithReason("The Geospatial API is not supported by this device.");
return;
case FeatureSupported.Supported:
if (ARCoreExtensions.ARCoreExtensionsConfig.GeospatialMode ==
GeospatialMode.Disabled)
{
Debug.Log("Geospatial sample switched to GeospatialMode.Enabled.");
ARCoreExtensions.ARCoreExtensionsConfig.GeospatialMode =
GeospatialMode.Enabled;
ARCoreExtensions.ARCoreExtensionsConfig.StreetscapeGeometryMode =
StreetscapeGeometryMode.Enabled;
_configurePrepareTime = 3.0f;
_enablingGeospatial = true;
return;
}
break;
}
// Waiting for new configuration to take effect.
if (_enablingGeospatial)
{
_configurePrepareTime -= Time.deltaTime;
if (_configurePrepareTime < 0)
{
_enablingGeospatial = false;
}
else
{
return;
}
}
// Check earth state.
var earthState = EarthManager.EarthState;
if (earthState == EarthState.ErrorEarthNotReady)
{
SnackBarText.text = _localizationInitializingMessage;
return;
}
else if (earthState != EarthState.Enabled)
{
string errorMessage =
"Geospatial sample encountered an EarthState error: " + earthState;
Debug.LogWarning(errorMessage);
SnackBarText.text = errorMessage;
return;
}
// Check earth localization.
bool isSessionReady = ARSession.state == ARSessionState.SessionTracking &&
Input.location.status == LocationServiceStatus.Running;
var earthTrackingState = EarthManager.EarthTrackingState;
var pose = earthTrackingState == TrackingState.Tracking ?
EarthManager.CameraGeospatialPose : new GeospatialPose();
if (!isSessionReady || earthTrackingState != TrackingState.Tracking ||
pose.OrientationYawAccuracy > _orientationYawAccuracyThreshold ||
pose.HorizontalAccuracy > _horizontalAccuracyThreshold)
{
// Lost localization during the session.
if (!_isLocalizing)
{
_isLocalizing = true;
_localizationPassedTime = 0f;
GeometryToggle.gameObject.SetActive(false);
AnchorSettingButton.gameObject.SetActive(false);
AnchorSettingPanel.gameObject.SetActive(false);
GeospatialAnchorToggle.gameObject.SetActive(false);
TerrainAnchorToggle.gameObject.SetActive(false);
RooftopAnchorToggle.gameObject.SetActive(false);
ClearAllButton.gameObject.SetActive(false);
foreach (var go in _anchorObjects)
{
go.SetActive(false);
}
}
if (_localizationPassedTime > _timeoutSeconds)
{
Debug.LogError("Geospatial sample localization timed out.");
ReturnWithReason(_localizationFailureMessage);
}
else
{
_localizationPassedTime += Time.deltaTime;
SnackBarText.text = _localizationInstructionMessage;
}
}
else if (_isLocalizing)
{
// Finished localization.
_isLocalizing = false;
_localizationPassedTime = 0f;
GeometryToggle.gameObject.SetActive(true);
AnchorSettingButton.gameObject.SetActive(true);
ClearAllButton.gameObject.SetActive(_anchorObjects.Count > 0);
SnackBarText.text = _localizationSuccessMessage;
foreach (var go in _anchorObjects)
{
go.SetActive(true);
}
ResolveHistory();
}
else
{
if (_streetscapeGeometryVisibility)
{
foreach (
ARStreetscapeGeometry streetscapegeometry in _addedStreetscapeGeometries)
{
InstantiateRenderObject(streetscapegeometry);
}
foreach (
ARStreetscapeGeometry streetscapegeometry in _updatedStreetscapeGeometries)
{
// This second call to instantiate is required if geometry is toggled on
// or off after the app has started.
InstantiateRenderObject(streetscapegeometry);
UpdateRenderObject(streetscapegeometry);
}
foreach (
ARStreetscapeGeometry streetscapegeometry in _removedStreetscapeGeometries)
{
DestroyRenderObject(streetscapegeometry);
}
}
else if (_clearStreetscapeGeometryRenderObjects)
{
DestroyAllRenderObjects();
_clearStreetscapeGeometryRenderObjects = false;
}
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began
&& !EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)
&& _anchorObjects.Count < _storageLimit)
{
// Set anchor on screen tap.
PlaceAnchorByScreenTap(Input.GetTouch(0).position);
}
// Hide anchor settings and toggles if the storage limit has been reached.
if (_anchorObjects.Count >= _storageLimit)
{
AnchorSettingButton.gameObject.SetActive(false);
AnchorSettingPanel.gameObject.SetActive(false);
GeospatialAnchorToggle.gameObject.SetActive(false);
TerrainAnchorToggle.gameObject.SetActive(false);
RooftopAnchorToggle.gameObject.SetActive(false);
}
else
{
AnchorSettingButton.gameObject.SetActive(true);
}
}
InfoPanel.SetActive(true);
if (earthTrackingState == TrackingState.Tracking)
{
InfoText.text = string.Format(
"Latitude/Longitude: {1}°, {2}°{0}" +
"Horizontal Accuracy: {3}m{0}" +
"Altitude: {4}m{0}" +
"Vertical Accuracy: {5}m{0}" +
"Eun Rotation: {6}{0}" +
"Orientation Yaw Accuracy: {7}°",
Environment.NewLine,
pose.Latitude.ToString("F6"),
pose.Longitude.ToString("F6"),
pose.HorizontalAccuracy.ToString("F6"),
pose.Altitude.ToString("F2"),
pose.VerticalAccuracy.ToString("F2"),
pose.EunRotation.ToString("F1"),
pose.OrientationYawAccuracy.ToString("F1"));
}
else
{
InfoText.text = "GEOSPATIAL POSE: not tracking";
}
}
/// <summary>
/// Connects the <c>ARStreetscapeGeometry</c> to the specified lists for access.
/// </summary>
/// <param name="eventArgs">The
/// <c><see cref="ARStreetscapeGeometriesChangedEventArgs"/></c> containing the
/// <c>ARStreetscapeGeometry</c>.
/// </param>
private void GetStreetscapeGeometry(ARStreetscapeGeometriesChangedEventArgs eventArgs)
{
_addedStreetscapeGeometries = eventArgs.Added;
_updatedStreetscapeGeometries = eventArgs.Updated;
_removedStreetscapeGeometries = eventArgs.Removed;
}
/// <summary>
/// Sets up a render object for this <c>ARStreetscapeGeometry</c>.
/// </summary>
/// <param name="streetscapegeometry">The
/// <c><see cref="ARStreetscapeGeometry"/></c> object containing the mesh
/// to be rendered.</param>
private void InstantiateRenderObject(ARStreetscapeGeometry streetscapegeometry)
{
if (streetscapegeometry.mesh == null)
{
return;
}
// Check if a render object already exists for this streetscapegeometry and
// create one if not.
if (_streetscapegeometryGOs.ContainsKey(streetscapegeometry.trackableId))
{
return;
}
GameObject renderObject = new GameObject(
"StreetscapeGeometryMesh", typeof(MeshFilter), typeof(MeshRenderer));
if (renderObject)
{
renderObject.transform.position = new Vector3(0, 0.5f, 0);
renderObject.GetComponent<MeshFilter>().mesh = streetscapegeometry.mesh;
// Add a material with transparent diffuse shader.
if (streetscapegeometry.streetscapeGeometryType ==
StreetscapeGeometryType.Building)
{
renderObject.GetComponent<MeshRenderer>().material =
StreetscapeGeometryMaterialBuilding[_buildingMatIndex];
_buildingMatIndex =
(_buildingMatIndex + 1) % StreetscapeGeometryMaterialBuilding.Count;
}
else
{
renderObject.GetComponent<MeshRenderer>().material =
StreetscapeGeometryMaterialTerrain;
}
renderObject.transform.position = streetscapegeometry.pose.position;
renderObject.transform.rotation = streetscapegeometry.pose.rotation;
_streetscapegeometryGOs.Add(streetscapegeometry.trackableId, renderObject);
}
}
/// <summary>
/// Updates the render object transform based on this StreetscapeGeometries pose.
/// It must be called every frame to update the mesh.
/// </summary>
/// <param name="streetscapegeometry">The <c><see cref="ARStreetscapeGeometry"/></c>
/// object containing the mesh to be rendered.</param>
private void UpdateRenderObject(ARStreetscapeGeometry streetscapegeometry)
{
if (_streetscapegeometryGOs.ContainsKey(streetscapegeometry.trackableId))
{
GameObject renderObject = _streetscapegeometryGOs[streetscapegeometry.trackableId];
renderObject.transform.position = streetscapegeometry.pose.position;
renderObject.transform.rotation = streetscapegeometry.pose.rotation;
}
}
/// <summary>
/// Destroys the render object associated with the
/// <c><see cref="ARStreetscapeGeometry"/></c>.
/// </summary>
/// <param name="streetscapegeometry">The <c><see cref="ARStreetscapeGeometry"/></c>
/// containing the render object to be destroyed.</param>
private void DestroyRenderObject(ARStreetscapeGeometry streetscapegeometry)
{
if (_streetscapegeometryGOs.ContainsKey(streetscapegeometry.trackableId))
{
var geometry = _streetscapegeometryGOs[streetscapegeometry.trackableId];
_streetscapegeometryGOs.Remove(streetscapegeometry.trackableId);
Destroy(geometry);
}
}
/// <summary>
/// Destroys all stored <c><see cref="ARStreetscapeGeometry"/></c> render objects.
/// </summary>
private void DestroyAllRenderObjects()
{
var keys = _streetscapegeometryGOs.Keys;
foreach (var key in keys)
{
var renderObject = _streetscapegeometryGOs[key];
Destroy(renderObject);
}
_streetscapegeometryGOs.Clear();
}
/// <summary>
/// Activate or deactivate all UI elements on the anchor setting Panel.
/// </summary>
/// <param name="state">A bool value to determine if the anchor settings panel is visible.
private void SetAnchorPanelState(bool state)
{
AnchorSettingPanel.gameObject.SetActive(state);
GeospatialAnchorToggle.gameObject.SetActive(state);
TerrainAnchorToggle.gameObject.SetActive(state);
RooftopAnchorToggle.gameObject.SetActive(state);
}
private IEnumerator CheckRooftopPromise(ResolveAnchorOnRooftopPromise promise,
GeospatialAnchorHistory history)
{
yield return promise;
var result = promise.Result;
if (result.RooftopAnchorState == RooftopAnchorState.Success &&
result.Anchor != null)
{
// Adjust the scale of the prefab anchor object to maintain visibility when it is
// far away.
result.Anchor.gameObject.transform.localScale *= GetRooftopAnchorScale(
result.Anchor.gameObject.transform.position,
Camera.main.transform.position);
GameObject anchorGO = Instantiate(TerrainPrefab,
result.Anchor.gameObject.transform);
anchorGO.transform.parent = result.Anchor.gameObject.transform;
_anchorObjects.Add(result.Anchor.gameObject);
_historyCollection.Collection.Add(history);
SnackBarText.text = GetDisplayStringForAnchorPlacedSuccess();
ClearAllButton.gameObject.SetActive(_anchorObjects.Count > 0);
SaveGeospatialAnchorHistory();
}
else
{
SnackBarText.text = GetDisplayStringForAnchorPlacedFailure();
}
yield break;
}
private IEnumerator CheckTerrainPromise(ResolveAnchorOnTerrainPromise promise,
GeospatialAnchorHistory history)
{
yield return promise;
var result = promise.Result;
if (result.TerrainAnchorState == TerrainAnchorState.Success &&
result.Anchor != null)
{
GameObject anchorGO = Instantiate(TerrainPrefab,
result.Anchor.gameObject.transform);
anchorGO.transform.parent = result.Anchor.gameObject.transform;
_anchorObjects.Add(result.Anchor.gameObject);
_historyCollection.Collection.Add(history);
SnackBarText.text = GetDisplayStringForAnchorPlacedSuccess();
ClearAllButton.gameObject.SetActive(_anchorObjects.Count > 0);
SaveGeospatialAnchorHistory();
}
else
{
SnackBarText.text = GetDisplayStringForAnchorPlacedFailure();
}
yield break;
}
private float GetRooftopAnchorScale(Vector3 anchor, Vector3 camera)
{
// Return the scale in range [1, 2] after mapping a distance between camera and anchor
// to [2, 20].
float distance =
Mathf.Sqrt(
Mathf.Pow(anchor.x - camera.x, 2.0f)
+ Mathf.Pow(anchor.y - camera.y, 2.0f)
+ Mathf.Pow(anchor.z - camera.z, 2.0f));
float mapDistance = Mathf.Min(Mathf.Max(2.0f, distance), 20.0f);
return (mapDistance - 2.0f) / (20.0f - 2.0f) + 1.0f;
}
private void PlaceAnchorByScreenTap(Vector2 position)
{
if (_streetscapeGeometryVisibility)
{
// Raycast against streetscapeGeometry.
List<XRRaycastHit> hitResults = new List<XRRaycastHit>();
if (RaycastManager.RaycastStreetscapeGeometry(position, ref hitResults))
{