/
Playspace.cs
executable file
·1336 lines (1161 loc) · 50.5 KB
/
Playspace.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 (c) 2018-present, Magic Leap, Inc. All Rights Reserved.
// Use of this file is governed by the Creator Agreement, located
// here: https://id.magicleap.com/terms/developer
//
// ---------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System;
using UnityEngine;
using UnityEngine.XR.MagicLeap;
#if PLATFORM_LUMIN
using UnityEngine.XR.MagicLeap.Native;
#endif
using UnityEngine.Events;
namespace MagicLeapTools
{
[RequireComponent(typeof(SpatialMapperThrottle))]
public class Playspace : MonoBehaviour
{
#if PLATFORM_LUMIN
//Private Classes:
private class VirtualWall
{
//Public Variables:
public Vector3 cornerA;
public Vector3 cornerB;
public Vector3 normal;
public MLPlanes.Plane plane;
public MLPlanes.QueryParams query;
public bool physical = true;
//Public Properties:
public Vector3 Center
{
get
{
return Vector3.Lerp(cornerA, cornerB, .5f);
}
}
public Vector3 Vector
{
get
{
return cornerB - cornerA;
}
}
//Constructors:
public VirtualWall(Vector3 cornerA, Vector3 cornerB)
{
this.cornerA = cornerA;
this.cornerB = cornerB;
}
}
#endif
//Public Variables:
public bool runAtStart = true;
[Tooltip("The gui to display when a user needs to find the floor.")]
public GameObject findFloorGUI;
[Tooltip("The gui to display when a user needs to find the ceiling.")]
public GameObject findCeilingGUI;
[Tooltip("The gui to display when a user needs to plot the corners of their room.")]
public GameObject drawPerimeterGUI;
[Tooltip("The gui to display when confirming the perimeter of the playspace.")]
public GameObject confirmAreaGUI;
[Tooltip("The gui to be displayed when a user needs to select the primary wall.")]
public GameObject selectPrimaryWallGUI;
[Tooltip("The gui to be shown on the wall when the primary wall is known.")]
public GameObject primaryWallPlaque;
public Material cornerMaterial;
[Tooltip("The material used when the outline of the playspace is shown for confirmation.")]
public Material perimeterOutlineMaterial;
public Material wallMaterial;
public Material floorMaterial;
public Material ceilingMaterial;
[Tooltip("How far behind a plotted wall should we look to find a physical wall.")]
public float maxPlaneDepthTest = 1.524f;
[HideInInspector] public MLPersistentCoordinateFrames.PCF pcfAnchor;
//Events:
/// <summary>
/// Thrown when the user completes building a playspace.
/// </summary>
public UnityEvent OnCompleted;
/// <summary>
/// Thrown if something has caused the playspace to update sucha as a PCF relocating.
/// </summary>
public UnityEvent OnUpdated;
/// <summary>
/// Thrown when the user declines the solved playspace so they can try again. Useful for clearing anything that was using the playspace.
/// </summary>
public UnityEvent OnCleared;
//Enums:
public enum State { Idle, Restore, FindPCF, FindFloor, FindCeiling, DrawPerimeter, FindWalls, ConfirmArea, ConfirmAreaReload, ConfirmPrimaryWall, Complete };
//Public Properties:
public static Playspace Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<Playspace>();
}
if (_instance == null)
{
Debug.LogError("No instance of Playspace found in scene.");
}
return _instance;
}
}
public bool Ready
{
get;
private set;
}
public State CurrentState
{
get;
private set;
}
public GameObject FloorGeometry
{
get;
private set;
}
public GameObject WallGeometry
{
get;
private set;
}
public GameObject CeilingGeometry
{
get;
private set;
}
public PlayspaceWall[] Walls
{
get;
private set;
}
public Vector3 Center
{
get
{
#if PLATFORM_LUMIN
//we make this relative to the pcf so relocalization keeps this value accurate:
return TransformUtilities.WorldPosition(pcfAnchor.Position, pcfAnchor.Rotation, _playspaceCenter);
#else
return Vector3.zero;
#endif
}
}
public Vector3 CeilingCenter
{
get
{
Vector3 location = Center;
location.y += Height * .5f;
return location;
}
}
public Vector3 FloorCenter
{
get
{
Vector3 location = Center;
location.y -= Height * .5f;
return location;
}
}
public float Height
{
get;
private set;
}
/// <summary>
/// The index in the Walls array of the wall a user has defined as primary.
/// </summary>
public int PrimaryWall
{
get;
private set;
}
/// <summary>
/// The index in the Walls array of the largest rear wall.
/// </summary>
public int RearWall
{
get;
private set;
}
/// <summary>
/// The index in the Walls array of the largest left wall.
/// </summary>
public int LeftWall
{
get;
private set;
}
/// <summary>
/// The index in the Walls array of the largest right wall.
/// </summary>
public int RightWall
{
get;
private set;
}
//Private Variables:
private static Playspace _instance;
#if PLATFORM_LUMIN
private Transform _camera;
private List<Transform> _plottedCorners = new List<Transform>();
private List<VirtualWall> _virtualWalls = new List<VirtualWall>();
private float _loopClosureDistance = 0.3048f;
private int _queryCount;
private float _ceilingHuntMaxDuration = 5;
private Bounds _plottedBounds;
private List<Vector3> _playspaceCorners;
private GameObject _currentGUI;
private SurfaceDetails _surfaceDetails;
private float _roomVerticalCenter;
private float _roomCeilingHeight;
private float _roomFloorHeight;
private string _sessionDataKey = "playspace_data";
private string _sessionMeshKey = "playspace_mesh";
private string _serializedMeshes;
private int _restoreAttempt;
private int _maxRestoreAttempts = 3;
private float _restoreRetryDelay = 1;
private Vector3 _playspaceCenter;
private Vector3 _cachedPrimaryWallGUIScale;
//Init:
private IEnumerator Start()
{
HideGUI();
//refs:
_camera = Camera.main.transform;
//sets:
_cachedPrimaryWallGUIScale = selectPrimaryWallGUI.transform.localScale;
//features:
MLPersistentCoordinateFrames.Start();
MLPlanes.Start();
MLInput.Start();
//wait for service startup:
Debug.Log("Waiting for PersistentCoordinateFrames service to localize...");
while (!MLPersistentCoordinateFrames.IsLocalized)
{
yield return null;
}
Debug.Log("PersistentCoordinateFrames service localized!");
//hooks:
MLPersistentCoordinateFrames.OnLocalized += HandleOnLocalized;
MLPersistentCoordinateFrames.PCF.OnStatusChange += HandlePCFChanged;
//requirements:
_surfaceDetails = FindObjectOfType<SurfaceDetails>();
if (_surfaceDetails == null)
{
_surfaceDetails = gameObject.AddComponent<SurfaceDetails>();
}
if (runAtStart)
{
Create();
}
}
//Deinit:
private void OnDestroy()
{
if (MLPersistentCoordinateFrames.IsStarted)
{
MLPersistentCoordinateFrames.Stop();
}
if (MLPlanes.IsStarted)
{
MLPlanes.Stop();
}
if (MLInput.IsStarted)
{
MLInput.Stop();
}
}
//Public Methods:
/// <summary>
/// Forces a new Playspace creation from scratch.
/// </summary>
public void Rebuild()
{
PlayerPrefs.DeleteKey(_sessionDataKey);
PlayerPrefs.DeleteKey(_sessionMeshKey);
Create();
}
/// <summary>
/// Initiates the guided system for generating a Playspace.
/// </summary>
public void Create()
{
Ready = false;
OnCleared?.Invoke();
//clean up:
HideGUI();
RemovePlottedBounds();
RemoveDebugLines();
//remove previous geometry:
if (WallGeometry != null)
{
Destroy(WallGeometry);
}
if (CeilingGeometry != null)
{
Destroy(CeilingGeometry);
}
if (FloorGeometry != null)
{
Destroy(FloorGeometry);
}
//reload or create new:
if (PlayerPrefs.HasKey(_sessionDataKey) && PlayerPrefs.HasKey(_sessionMeshKey))
{
ChangeState(State.Restore);
}
else
{
ChangeState(State.FindPCF);
}
}
/// <summary>
/// Returns true if the position is inside the playspace.
/// </summary>
public bool Inside(Vector3 position)
{
//can't operate without walls:
if (Walls.Length == 0)
{
return false;
}
float angle = 0;
for (int i = 0; i < Walls.Length; i++)
{
//add up angles:
Vector3 to = Walls[i].LeftEdge - position;
Vector3 toNext = Walls[i].RightEdge - position;
angle += Vector3.SignedAngle(to, toNext, Vector3.down);
}
//set inside status - if we ended up at about 0 we are outside if we ended up at about 360 we are inside:
return angle > 180;
}
/// <summary>
/// Given a position and rotation the index of the facing wall will be returned.
/// </summary>
public int FacingWall(Vector3 position, Vector3 forward, ref Vector3 intersection)
{
//can't operate without walls:
if (Walls.Length == 0)
{
return -1;
}
int facingWallID = -1;
float furthestFacingWallDistance = float.MinValue;
for (int i = 0; i < Walls.Length; i++)
{
//find facing wall
Vector3 stretchedForward = position + forward * 100;
if (MathUtilities.LineSegmentsIntersecting(position, stretchedForward, Walls[i].LeftEdge, Walls[i].RightEdge, true))
{
Vector3 _intersection = Vector3.zero;
MathUtilities.RayIntersection(new Ray(position, forward), new Ray(Walls[i].LeftEdge, Walls[i].Right), ref _intersection);
float distance = Vector3.Distance(position, _intersection);
if (distance > furthestFacingWallDistance)
{
intersection = _intersection;
furthestFacingWallDistance = distance;
facingWallID = i;
}
}
};
return facingWallID;
}
//Private Methods:
private void FireOnUpdated()
{
//only fire this if we aren't in the middle of building a playspace:
if (Ready)
{
OnUpdated?.Invoke();
}
}
private void PreviewArea()
{
//visualize:
Vector3[] playspacePerimeterOnFloor = new Vector3[_playspaceCorners.Count];
Vector3[] playspacePerimeterOnCeiling = new Vector3[_playspaceCorners.Count];
//populate floor and ceiling corner loops:
for (int i = 0; i < _playspaceCorners.Count; i++)
{
//cache floor and ceiling locations:
Vector3 floor = TransformUtilities.WorldPosition(pcfAnchor.Position, pcfAnchor.Rotation, _playspaceCorners[i]);
Vector3 ceiling = floor + new Vector3(0, Height);
playspacePerimeterOnFloor[i] = floor;
playspacePerimeterOnCeiling[i] = ceiling;
//draw corner supports:
LineRenderer cornerSupportsOutline = Lines.DrawLine($"PlayspaceCornerSupport{i}", Color.green, Color.green, .005f, floor, ceiling);
cornerSupportsOutline.material = perimeterOutlineMaterial;
}
//draw ceiling and floor perimeter:
LineRenderer ceilingOutline = Lines.DrawLine($"PlayspaceCeilingOutline", Color.green, Color.green, .005f, playspacePerimeterOnCeiling);
LineRenderer floorOutline = Lines.DrawLine($"PlayspaceFloorOutline", Color.green, Color.green, .005f, playspacePerimeterOnFloor);
ceilingOutline.material = perimeterOutlineMaterial;
floorOutline.material = perimeterOutlineMaterial;
}
private void AnchorToPCF()
{
//if we don't have anything to anchor then exit:
if (WallGeometry == null || FloorGeometry == null || CeilingGeometry == null)
{
return;
}
//anchor to PCF and correct any tilt:
Vector3 correctedForward = Vector3.ProjectOnPlane(pcfAnchor.Rotation * Vector3.forward, Vector3.up).normalized;
Quaternion correctedRotation = Quaternion.LookRotation(correctedForward);
WallGeometry.transform.SetPositionAndRotation(pcfAnchor.Position, correctedRotation);
FloorGeometry.transform.SetPositionAndRotation(pcfAnchor.Position, correctedRotation);
CeilingGeometry.transform.SetPositionAndRotation(pcfAnchor.Position, correctedRotation);
}
private void BuildGeometry(Vector3[] wallVerticies, int[] wallTriangles, Vector3[] floorVerticies, int[] floorTriangles, Vector3[] ceilingVerticies)
{
//setup geometry:
WallGeometry = new GameObject("(PlayspaceWalls)", typeof(MeshFilter), typeof(MeshRenderer));
FloorGeometry = new GameObject("(PlayspaceFloor)", typeof(MeshFilter), typeof(MeshRenderer));
CeilingGeometry = new GameObject("(PlayspaceCeiling)", typeof(MeshFilter), typeof(MeshRenderer));
AnchorToPCF();
//setup renderers:
MeshRenderer wallsRenderer = WallGeometry.GetComponent<MeshRenderer>();
if (wallMaterial != null)
{
wallsRenderer.material = wallMaterial;
}
else
{
wallsRenderer.enabled = false;
}
MeshRenderer floorRenderer = FloorGeometry.GetComponent<MeshRenderer>();
if (floorMaterial != null)
{
floorRenderer.material = floorMaterial;
}
else
{
floorRenderer.enabled = false;
}
MeshRenderer ceilingRenderer = CeilingGeometry.GetComponent<MeshRenderer>();
if (ceilingMaterial != null)
{
ceilingRenderer.material = ceilingMaterial;
}
else
{
ceilingRenderer.enabled = false;
}
//apply mesh:
Mesh wallMesh = new Mesh();
wallMesh.vertices = wallVerticies;
wallMesh.triangles = wallTriangles;
WallGeometry.GetComponent<MeshFilter>().mesh = wallMesh;
Mesh floorMesh = new Mesh();
floorMesh.vertices = floorVerticies;
floorMesh.triangles = floorTriangles;
FloorGeometry.GetComponent<MeshFilter>().mesh = floorMesh;
Mesh ceilingMesh = new Mesh();
ceilingMesh.vertices = ceilingVerticies;
ceilingMesh.triangles = floorTriangles.Reverse().ToArray();
CeilingGeometry.GetComponent<MeshFilter>().mesh = ceilingMesh;
//apply colliders:
WallGeometry.AddComponent<MeshCollider>();
FloorGeometry.AddComponent<MeshCollider>();
CeilingGeometry.AddComponent<MeshCollider>();
//serialize mesh:
string wallVertsSerialized = SerializationUtilities.Serialize(wallMesh.vertices);
string wallTrisSerialized = SerializationUtilities.Serialize(wallMesh.triangles);
string floorVertsSerialized = SerializationUtilities.Serialize(floorMesh.vertices);
string floorTrisSerialized = SerializationUtilities.Serialize(floorMesh.triangles);
string ceilingVertsSerialized = SerializationUtilities.Serialize(ceilingMesh.vertices);
_serializedMeshes = wallVertsSerialized + "|" + wallTrisSerialized + "|" + floorVertsSerialized + "|" + floorTrisSerialized + "|" + ceilingVertsSerialized;
}
private void ShowGUI(GameObject next)
{
if (_currentGUI != null)
{
_currentGUI.SetActive(false);
}
_currentGUI = next;
next.SetActive(true);
}
private void HideGUI()
{
findFloorGUI.SetActive(false);
findCeilingGUI.SetActive(false);
drawPerimeterGUI.SetActive(false);
confirmAreaGUI.SetActive(false);
selectPrimaryWallGUI.SetActive(false);
primaryWallPlaque.SetActive(false);
}
private void RemoveDebugLines()
{
Lines.DestroyAllLines();
}
private void RemovePlottedBounds()
{
//clean up previous items:
foreach (var item in _plottedCorners)
{
Destroy(item.gameObject);
}
_plottedCorners.Clear();
//remove lines:
Lines.DestroyAllLines();
}
private void ChangeState(State nextState)
{
StopAllCoroutines();
//find and run current state's exit:
GetType().GetMethod(CurrentState + "_Exit", BindingFlags.Instance | BindingFlags.NonPublic)?.Invoke(this, null);
//update current state:
CurrentState = nextState;
string currentStateName = nextState.ToString();
//find and run state's enter:
GetType().GetMethod(currentStateName + "_Enter", BindingFlags.Instance | BindingFlags.NonPublic)?.Invoke(this, null);
//find and run state's update:
if (GetType().GetMethod(currentStateName + "_Update", BindingFlags.Instance | BindingFlags.NonPublic) != null)
{
StartCoroutine(currentStateName + "_Update");
}
}
//Event Handlers:
private void HandlePCFChanged(MLPersistentCoordinateFrames.PCF.Status pcfStatus, MLPersistentCoordinateFrames.PCF pcf)
{
if (pcfAnchor != null && pcf.CFUID == pcfAnchor.CFUID)
{
//adjust to pcf:
pcfAnchor.Update();
AnchorToPCF();
FireOnUpdated();
}
}
private void HandleOnLocalized(bool localized)
{
if (localized)
{
Debug.Log("Playspace has been realigned to the world.");
//adjust to pcf:
pcfAnchor.Update();
AnchorToPCF();
FireOnUpdated();
}
else
{
Debug.Log("Tracking lost - look around some to localize so Playspace can realign to the world.");
}
}
//State Methods:
private void Restore_Enter()
{
//deserialize previous session:
string[] sessionData = PlayerPrefs.GetString(_sessionDataKey).Split('|');
Walls = SerializationUtilities.Deserialize<PlayspaceWall[]>(sessionData[1]);
_playspaceCenter = JsonUtility.FromJson<Vector3>(sessionData[2]);
PrimaryWall = int.Parse(sessionData[3]);
RightWall = int.Parse(sessionData[4]);
RearWall = int.Parse(sessionData[5]);
LeftWall = int.Parse(sessionData[6]);
_playspaceCorners = SerializationUtilities.Deserialize<Vector3[]>(sessionData[7]).ToList<Vector3>();
Height = float.Parse(sessionData[8]);
//determine restore success:
if (PrimaryWall == -1 || RightWall == -1 || RearWall == -1 || LeftWall == -1)
{
//something is not right with this room so let's force a reset:
PlayerPrefs.DeleteKey(_sessionMeshKey);
PlayerPrefs.DeleteKey(_sessionDataKey);
Create();
}
else
{
//locate pcf:
StartCoroutine("Restore_Relocalize", sessionData[0]);
}
}
private IEnumerator Restore_Relocalize(string pcfCFUID)
{
MagicLeapNativeBindings.MLCoordinateFrameUID cfuid = SerializationUtilities.StringToCFUID(pcfCFUID);
while (true)
{
MLPersistentCoordinateFrames.FindPCFByCFUID(cfuid, out pcfAnchor);
if (pcfAnchor == null)
{
//we didn't find the pcf we needed this time:
_restoreAttempt++;
if (_restoreAttempt < _maxRestoreAttempts)
{
//retry:
Debug.Log($"Previous PCF not located. Trying again. Attempt: {_restoreAttempt}/{_maxRestoreAttempts}");
yield return new WaitForSeconds(_restoreRetryDelay);
}
else
{
//failed:
Debug.Log($"Failed to locate PCF attempt: {_restoreAttempt}/{_maxRestoreAttempts}. Creating new Playspace.");
ChangeState(State.FindPCF);
yield break;
}
yield return null;
}
else
{
//deserialize meshes:
string[] meshData = PlayerPrefs.GetString(_sessionMeshKey).Split('|');
Vector3[] wallVerts = SerializationUtilities.Deserialize<Vector3[]>(meshData[0]);
int[] wallTris = SerializationUtilities.Deserialize<int[]>(meshData[1]);
Vector3[] floorVerts = SerializationUtilities.Deserialize<Vector3[]>(meshData[2]);
int[] floorTris = SerializationUtilities.Deserialize<int[]>(meshData[3]);
Vector3[] ceilingVerts = SerializationUtilities.Deserialize<Vector3[]>(meshData[4]);
BuildGeometry(wallVerts, wallTris, floorVerts, floorTris, ceilingVerts);
ChangeState(State.ConfirmAreaReload);
yield break;
}
}
}
private void FindPCF_Enter()
{
MLPersistentCoordinateFrames.FindClosestPCF(_camera.position, out pcfAnchor);
ChangeState(State.FindFloor);
}
private void FindFloor_Enter()
{
ShowGUI(findFloorGUI);
}
private IEnumerator FindFloor_Update()
{
while (true)
{
if (SurfaceDetails.FloorFound)
{
ChangeState(State.FindCeiling);
}
yield return null;
}
}
private void FindCeiling_Enter()
{
ShowGUI(findCeilingGUI);
}
private IEnumerator FindCeiling_Update()
{
float startedTime = Time.realtimeSinceStartup;
while (true)
{
if (SurfaceDetails.CeilingFound)
{
ChangeState(State.DrawPerimeter);
}
if (startedTime - Time.realtimeSinceStartup > _ceilingHuntMaxDuration)
{
Debug.Log("Timed out locating ceiling.");
ChangeState(State.DrawPerimeter);
}
yield return null;
}
}
private void DrawPerimeter_Enter()
{
ShowGUI(drawPerimeterGUI);
//reset:
_plottedCorners.Clear();
//hook:
MLInput.OnTriggerDown += DrawPerimeter_HandleTriggerDown;
}
private void DrawPerimeter_HandleTriggerDown(byte controllerId, float triggerValue)
{
//cache room details (to avoid tilt if room analyzation updates):
if (_plottedCorners.Count == 0)
{
_roomVerticalCenter = SurfaceDetails.VerticalCenter;
_roomCeilingHeight = SurfaceDetails.CeilingHeight;
_roomFloorHeight = SurfaceDetails.FloorHeight;
Height = SurfaceDetails.RoomHeight;
}
//corner details:
Vector3 controlPosition = MLInput.GetController(controllerId).Position;
Vector3 cornerLocation = new Vector3(controlPosition.x, _roomVerticalCenter, controlPosition.z);
//invalid placement if this proposed segment would overlap any previous ones:
if (_plottedCorners.Count >= 3)
{
//proposed line segment:
Vector2 proposedStart = new Vector2(_plottedCorners[_plottedCorners.Count - 1].position.x, _plottedCorners[_plottedCorners.Count - 1].position.z);
Vector2 proposedEnd = new Vector2(cornerLocation.x, cornerLocation.z);
//look for any intersections (in 2d):
for (int i = 1; i < _plottedCorners.Count; i++)
{
//get a pervious segment:
Vector2 startA = new Vector2(_plottedCorners[i - 1].position.x, _plottedCorners[i - 1].position.z);
Vector2 endA = new Vector2(_plottedCorners[i].position.x, _plottedCorners[i].position.z);
//is there an intersection with something previous?
Vector2 previousIntersection = Vector2.zero;
if (MathUtilities.LineSegmentsIntersecting(startA, endA, proposedStart, proposedEnd, false))
{
//ignore this proposed corner since it would create an overlapped wall:
return;
}
}
}
//bounds:
if (_plottedCorners.Count == 0)
{
_plottedBounds = new Bounds(cornerLocation, Vector3.zero);
}
else
{
_plottedBounds.Encapsulate(cornerLocation);
}
//loop complete?
bool loopComplete = false;
if (_plottedCorners.Count > 3)
{
//close to first? close to last? close the loop:
if (Vector3.Distance(cornerLocation, _plottedCorners[0].position) <= _loopClosureDistance || Vector3.Distance(cornerLocation, _plottedCorners[_plottedCorners.Count - 1].position) <= _loopClosureDistance)
{
_plottedCorners.Add(_plottedCorners[0]);
loopComplete = true;
}
}
if (!loopComplete)
{
//visualize corner:
GameObject corner = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
corner.GetComponent<Renderer>().material = cornerMaterial;
corner.name = $"(Corner{_plottedCorners.Count})";
corner.transform.position = cornerLocation;
corner.transform.localScale = new Vector3(0.0508f, Height * .5f, 0.0508f);
_plottedCorners.Add(corner.transform);
//visualize boundry:
Lines.DrawLine("Boundry", Color.white, Color.white, .01f, _plottedCorners.ToArray());
}
else
{
//visualize boundry:
Lines.DrawLine("Boundry", Color.white, Color.white, .01f, _plottedCorners.ToArray());
ChangeState(State.FindWalls);
}
}
private void DrawPerimeter_Exit()
{
//unhook:
MLInput.OnTriggerDown -= DrawPerimeter_HandleTriggerDown;
}
private void FindWalls_Enter()
{
//generate virtual walls:
_virtualWalls.Clear();
for (int i = 1; i < _plottedCorners.Count; i++)
{
_virtualWalls.Add(new VirtualWall(_plottedCorners[i - 1].position, _plottedCorners[i].position));
}
//discover winding direction:
float angleCount = 0;
for (int i = 1; i < _plottedCorners.Count; i++)
{
Vector3 centerToPrevious = Vector3.Normalize(_plottedCorners[i - 1].position - _plottedBounds.center);
Vector3 centerToCurrent = Vector3.Normalize(_plottedCorners[i].position - _plottedBounds.center);
angleCount += Vector3.SignedAngle(centerToPrevious, centerToCurrent, Vector3.up);
}
float windingDirection = Mathf.Sign(angleCount); //1 = clockwise, -1 = counterclockwise
//set normals:
for (int i = 0; i < _virtualWalls.Count; i++)
{
_virtualWalls[i].normal = Vector3.Normalize(Quaternion.AngleAxis(90 * windingDirection, Vector3.up) * _virtualWalls[i].Vector);
}
//generate world plane queries:
for (int i = 0; i < _virtualWalls.Count; i++)
{
//establish and cache query:
MLPlanes.QueryParams query = new MLPlanes.QueryParams();
query.MaxResults = 10;
query.Flags = MLPlanes.QueryFlags.Vertical | MLPlanes.QueryFlags.OrientToGravity | MLPlanes.QueryFlags.Inner;
query.BoundsCenter = _virtualWalls[i].Center - _virtualWalls[i].normal * (maxPlaneDepthTest * .5f);
query.BoundsRotation = Quaternion.LookRotation(_virtualWalls[i].normal);
query.BoundsExtents = new Vector3(_virtualWalls[i].Vector.magnitude, _plottedCorners[i].localScale.y, maxPlaneDepthTest);
_virtualWalls[i].query = query;
}
//execute world planes queries:
_queryCount = -1;
FindWalls_ResolveToPhysicalWalls();
}
private void FindWalls_ResolveToPhysicalWalls()
{
_queryCount++;
MLPlanes.GetPlanes(_virtualWalls[_queryCount].query, FindWalls_HandleLocatePhysicalWallPlaneQuery);
}
private void FindWalls_HandleLocatePhysicalWallPlaneQuery(MLResult result, MLPlanes.Plane[] planes, MLPlanes.Boundaries[] boundaries)
{
//resets:
Vector3 sourceWallCenter = Vector3.Lerp(_plottedCorners[_queryCount].position, _plottedCorners[_queryCount + 1].position, .5f);
//find furthest:
int primeID = -1;
float largest = 0;
for (int i = 0; i < planes.Length; i++)
{
//check to make sure this plane is close to the same orientation as the virtual one:
float dot = Vector3.Dot(planes[i].Rotation * Vector3.back, _virtualWalls[_queryCount].normal);
//candidate - test for largest plane:
if (dot > .9f)
{
float size = planes[i].Width + planes[i].Height;
if (size > largest)
{
largest = size;
primeID = i;
}
}
}
//use found wall or just use boundry from virtual wall:
if (primeID != -1)
{
MLPlanes.Plane foundPlane = planes[primeID];
foundPlane.Center.y = _roomVerticalCenter;
foundPlane.Width = _virtualWalls[_queryCount].Vector.magnitude;
foundPlane.Height = Height;
_virtualWalls[_queryCount].plane = foundPlane;
}
else
{
//if we didn't find a physical wall let's just make the virtual wall a boundary plane as is:
MLPlanes.Plane plane = new MLPlanes.Plane();
Vector3 center = _virtualWalls[_queryCount].Center;
center.y = _roomVerticalCenter;
plane.Center = center;
plane.Rotation = Quaternion.LookRotation(_virtualWalls[_queryCount].normal);
plane.Width = _virtualWalls[_queryCount].Vector.magnitude;
plane.Height = Height;
_virtualWalls[_queryCount].plane = plane;
_virtualWalls[_queryCount].physical = false;
}
//continue additional queries:
if (_queryCount < _virtualWalls.Count - 1)
{
FindWalls_ResolveToPhysicalWalls();
}
else
{
FindWalls_LocateBoundry();
}
}
private void FindWalls_LocateBoundry()
{
//remove initial guides:
RemovePlottedBounds();
//sort by angles from a base vector to find clockwise order:
Vector3 baseVector = Vector3.Normalize(_virtualWalls[0].plane.Center - _plottedBounds.center);
SortedDictionary<float, int> sortedDirection = new SortedDictionary<float, int>();
for (int i = 0; i < _virtualWalls.Count; i++)
{
Vector3 toNext = Vector3.Normalize(_virtualWalls[i].plane.Center - _plottedBounds.center);
float angle = Vector3.SignedAngle(baseVector, toNext, Vector3.up) + 180;
if (sortedDirection.ContainsKey(angle))
{
//we have a bad set of locations so it is best to just everything:
Create();
break;
}
else
{
sortedDirection.Add(angle, i);
}
}
int[] clockwiseOrder = sortedDirection.Values.ToArray<int>();
//find and connect 'betweens' which end up being final walls of playspace
List<bool> physicalStatus = new List<bool>();