forked from microsoft/MixedRealityToolkit-Unity
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSharingWorldAnchorManager.cs
672 lines (575 loc) · 25.8 KB
/
SharingWorldAnchorManager.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using HoloToolkit.Unity;
#if UNITY_WSA
using System;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_2017_2_OR_NEWER
using UnityEngine.XR.WSA;
using UnityEngine.XR.WSA.Persistence;
using UnityEngine.XR.WSA.Sharing;
#else
using UnityEngine.VR.WSA;
using UnityEngine.VR.WSA.Persistence;
using UnityEngine.VR.WSA.Sharing;
#endif
#endif
namespace HoloToolkit.Sharing
{
/// <summary>
/// Wrapper around world anchor store to streamline some of the persistence API busy work.
/// </summary>
public class SharingWorldAnchorManager : WorldAnchorManager
{
#if UNITY_WSA
/// <summary>
/// Called once the anchor has fully uploaded.
/// </summary>
public event Action<bool> AnchorUploaded;
/// <summary>
/// Called when the anchor has been downloaded.
/// </summary>
public event Action<bool, GameObject> AnchorDownloaded;
/// <summary>
/// Sometimes we'll see a really small anchor blob get generated.
/// These tend to not work, so we have a minimum trustworthy size.
/// </summary>
private const uint MinTrustworthySerializedAnchorDataSize = 100000;
/// <summary>
/// WorldAnchorTransferBatch is the primary object in serializing/deserializing anchors.
/// <remarks>Only available on device.</remarks>
/// </summary>
private WorldAnchorTransferBatch currentAnchorTransferBatch;
private bool isExportingAnchors;
private bool shouldExportAnchors;
/// <summary>
/// The data blob of the anchor.
/// </summary>
private List<byte> rawAnchorUploadData = new List<byte>(0);
private bool canUpdate;
private bool isImportingAnchors;
private bool shouldImportAnchors;
/// <summary>
/// The current download anchor data blob.
/// </summary>
private byte[] rawAnchorDownloadData;
#region Unity Methods
protected override void Start()
{
base.Start();
if (SharingStage.Instance != null)
{
ShowDetailedLogs = SharingStage.Instance.ShowDetailedLogs;
// SharingStage should be valid at this point, but we may not be connected.
if (SharingStage.Instance.IsConnected)
{
Connected();
}
else
{
Disconnected();
}
}
else
{
Debug.LogError("SharingWorldAnchorManager requires the SharingStage.");
}
}
protected override void Update()
{
if (AnchorStore == null ||
SharingStage.Instance == null ||
SharingStage.Instance.CurrentRoom == null ||
!canUpdate)
{ return; }
if (LocalAnchorOperations.Count > 0)
{
if (!isExportingAnchors && !isImportingAnchors)
{
DoAnchorOperation(LocalAnchorOperations.Dequeue());
}
}
else
{
if (shouldImportAnchors && !isImportingAnchors && !isExportingAnchors)
{
if (AnchorDebugText != null)
{
AnchorDebugText.text += "\nStarting Anchor Download...";
}
isImportingAnchors = true;
shouldImportAnchors = false;
WorldAnchorTransferBatch.ImportAsync(rawAnchorDownloadData, ImportComplete);
}
if (shouldExportAnchors && !isExportingAnchors && !isImportingAnchors)
{
if (AnchorDebugText != null)
{
AnchorDebugText.text += "\nStarting Anchor Upload...";
}
isExportingAnchors = true;
shouldExportAnchors = false;
WorldAnchorTransferBatch.ExportAsync(currentAnchorTransferBatch, WriteBuffer, ExportComplete);
}
}
}
protected override void OnDestroy()
{
Disconnected();
base.OnDestroy();
}
#endregion // Unity Methods
#region Event Callbacks
/// <summary>
/// Callback function that contains the WorldAnchorStore object.
/// </summary>
/// <param name="anchorStore">The WorldAnchorStore to cache.</param>
protected override void AnchorStoreReady(WorldAnchorStore anchorStore)
{
AnchorStore = anchorStore;
if (!SharingStage.Instance.KeepRoomAlive || !PersistentAnchors)
{
if (AnchorDebugText != null)
{
AnchorDebugText.text += "\nClearing Anchor Store...";
}
anchorStore.Clear();
}
}
/// <summary>
/// Called when the sharing stage connects to a server.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Events Arguments.</param>
private void Connected(object sender = null, EventArgs e = null)
{
SharingStage.Instance.SharingManagerConnected -= Connected;
SharingStage.Instance.SharingManagerDisconnected += Disconnected;
SharingStage.Instance.RoomManagerAdapter.UserJoinedRoomEvent += RoomManagerListener_OnRoomJoined;
SharingStage.Instance.RoomManagerAdapter.UserLeftRoomEvent += RoomManagerListener_OnLeftRoom;
if (ShowDetailedLogs)
{
Debug.Log("[SharingWorldAnchorManager] Connected to server.");
}
if (AnchorDebugText != null)
{
AnchorDebugText.text += "\nConnected to Server.";
}
}
/// <summary>
/// Called when the sharing stage is disconnected from a server.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event Arguments.</param>
private void Disconnected(object sender = null, EventArgs e = null)
{
if (SharingStage.Instance != null)
{
SharingStage.Instance.SharingManagerConnected += Connected;
SharingStage.Instance.SharingManagerDisconnected -= Disconnected;
SharingStage.Instance.RoomManagerAdapter.UserJoinedRoomEvent -= RoomManagerListener_OnRoomJoined;
SharingStage.Instance.RoomManagerAdapter.UserLeftRoomEvent -= RoomManagerListener_OnLeftRoom;
}
if (ShowDetailedLogs)
{
Debug.Log("[SharingWorldAnchorManager] Disconnected from server.");
}
if (AnchorDebugText != null)
{
AnchorDebugText.text += "\nDisconnected from Server.";
}
canUpdate = false;
}
private void RoomManagerListener_OnRoomJoined(Room room, int userId)
{
if (SharingStage.Instance.Manager.GetLocalUser().GetID() == userId &&
SharingStage.Instance.CurrentRoom.GetID() == room.GetID())
{
SharingStage.Instance.RoomManagerAdapter.AnchorUploadedEvent += RoomManagerListener_AnchorUploaded;
SharingStage.Instance.RoomManagerAdapter.AnchorsChangedEvent += RoomManagerListener_AnchorsChanged;
SharingStage.Instance.RoomManagerAdapter.AnchorsDownloadedEvent += RoomManagerListener_AnchorDownloaded;
canUpdate = true;
if (ShowDetailedLogs)
{
Debug.LogFormat("[SharingWorldAnchorManager] In room {0} with {1} anchors.",
SharingStage.Instance.CurrentRoom.GetName().GetString(),
SharingStage.Instance.CurrentRoom.GetAnchorCount());
}
if (AnchorDebugText != null)
{
AnchorDebugText.text += string.Format("\nIn room {0} with {1} anchors.",
SharingStage.Instance.CurrentRoom.GetName().GetString(),
SharingStage.Instance.CurrentRoom.GetAnchorCount());
}
}
}
private void RoomManagerListener_OnLeftRoom(Room room, int userId)
{
if (SharingStage.Instance.Manager.GetLocalUser().GetID() == userId)
{
SharingStage.Instance.RoomManagerAdapter.AnchorUploadedEvent -= RoomManagerListener_AnchorUploaded;
SharingStage.Instance.RoomManagerAdapter.AnchorsChangedEvent -= RoomManagerListener_AnchorsChanged;
SharingStage.Instance.RoomManagerAdapter.AnchorsDownloadedEvent -= RoomManagerListener_AnchorDownloaded;
canUpdate = false;
if (ShowDetailedLogs)
{
Debug.LogFormat("\n[SharingWorldAnchorManager] Left room {0}", room.GetName().GetString());
}
if (AnchorDebugText != null)
{
AnchorDebugText.text += string.Format("\nLeft room {0}", room.GetName().GetString());
}
}
}
/// <summary>
/// Called when anchor upload operations complete.
/// </summary>
private void RoomManagerListener_AnchorUploaded(bool successful, XString failureReason)
{
if (successful)
{
string[] anchorIds = currentAnchorTransferBatch.GetAllIds();
for (int i = 0; i < anchorIds.Length; i++)
{
if (ShowDetailedLogs)
{
Debug.LogFormat("[SharingWorldAnchorManager] Successfully uploaded anchor \"{0}\".", anchorIds[i]);
}
if (AnchorDebugText != null)
{
AnchorDebugText.text += string.Format("\nSuccessfully uploaded anchor \"{0}\".", anchorIds[i]);
}
}
}
else
{
Debug.LogError("[SharingWorldAnchorManager] Upload failed: " + failureReason);
if (AnchorDebugText != null)
{
AnchorDebugText.text += string.Format("\nUpload failed: " + failureReason);
}
}
rawAnchorUploadData.Clear();
currentAnchorTransferBatch.Dispose();
currentAnchorTransferBatch = null;
isExportingAnchors = false;
if (AnchorUploaded != null)
{
AnchorUploaded(successful);
}
}
/// <summary>
/// Called when anchor download operations complete.
/// </summary>
private void RoomManagerListener_AnchorDownloaded(bool successful, AnchorDownloadRequest request, XString failureReason)
{
// If we downloaded anchor data successfully we should import the data.
if (successful)
{
int dataSize = request.GetDataSize();
if (ShowDetailedLogs)
{
Debug.LogFormat("[SharingWorldAnchorManager] Downloaded {0} bytes.", dataSize.ToString());
}
if (AnchorDebugText != null)
{
AnchorDebugText.text += string.Format("\nDownloaded {0} bytes.", dataSize.ToString());
}
rawAnchorDownloadData = new byte[dataSize];
request.GetData(rawAnchorDownloadData, dataSize);
shouldImportAnchors = true;
}
else
{
Debug.LogWarning("[SharingWorldAnchorManager] Anchor DL failed " + failureReason);
if (AnchorDebugText != null)
{
AnchorDebugText.text += string.Format("\nAnchor DL failed " + failureReason);
}
}
}
/// <summary>
/// Called when anchors are changed in the room.
/// </summary>
/// <param name="room">The room where the anchors were changed.</param>
private void RoomManagerListener_AnchorsChanged(Room room)
{
if (SharingStage.Instance.CurrentRoom.GetID() == room.GetID())
{
if (AnchorDebugText != null)
{
AnchorDebugText.text += "\nRoom Anchors Updated! Clearing the local Anchor Store and attempting to download the update...";
}
// Clear our local anchor store, and download all our shared anchors again.
// TODO: Only download the anchors that changed. Currently there's no way to know which anchor changed.
AnchorStore.Clear();
if (ShowDetailedLogs)
{
Debug.LogFormat("[SharingWorldAnchorManager] Anchors updated for room \"{0}\".\nClearing the local Anchor Store and attempting to download the update...", room.GetName().GetString());
}
if (AnchorDebugText != null)
{
AnchorDebugText.text += string.Format("\nAnchors updated for room \"{0}\".\nClearing the local Anchor Store and attempting to download the update...", room.GetName().GetString());
}
int roomAnchorCount = SharingStage.Instance.CurrentRoom.GetAnchorCount();
for (int i = 0; i < roomAnchorCount; i++)
{
GameObject anchoredObject;
string roomAnchorId = SharingStage.Instance.CurrentRoom.GetAnchorName(i).GetString();
if (AnchorGameObjectReferenceList.TryGetValue(roomAnchorId, out anchoredObject))
{
if (ShowDetailedLogs)
{
Debug.LogFormat("[SharingWorldAnchorManager] Found cached GameObject reference for \"{0}\".", roomAnchorId);
}
if (AnchorDebugText != null)
{
AnchorDebugText.text += string.Format("\nFound cached GameObject reference for \"{0}\".", roomAnchorId);
}
AttachAnchor(anchoredObject, roomAnchorId);
}
else
{
anchoredObject = GameObject.Find(roomAnchorId);
if (anchoredObject != null)
{
if (ShowDetailedLogs)
{
Debug.LogFormat("[SharingWorldAnchorManager] Found a GameObject reference form scene for \"{0}\".", roomAnchorId);
}
if (AnchorDebugText != null)
{
AnchorDebugText.text += string.Format("\nFound a GameObject reference form scene for \"{0}\".", roomAnchorId);
}
AttachAnchor(anchoredObject, roomAnchorId);
}
else
{
Debug.LogWarning("[SharingWorldAnchorManager] Unable to find a matching GameObject for anchor!");
if (AnchorDebugText != null)
{
AnchorDebugText.text += "\nUnable to find a matching GameObject for anchor!";
}
}
}
}
}
}
#endregion // Event Callbacks
/// <summary>
/// Called before creating anchor. Used to check if import required.
/// </summary>
/// <param name="anchorId">Name of the anchor to import.</param>
/// <param name="objectToAnchor">GameObject </param>
/// <returns>Success.</returns>
protected override bool ImportAnchor(string anchorId, GameObject objectToAnchor)
{
if (SharingStage.Instance == null ||
SharingStage.Instance.Manager == null ||
SharingStage.Instance.CurrentRoom == null)
{
Debug.LogErrorFormat("[SharingWorldAnchorManager] Failed to import anchor \"{0}\"! The sharing service was not ready.", anchorId);
if (AnchorDebugText != null)
{
AnchorDebugText.text += string.Format("\nFailed to import anchor \"{0}\"! The sharing service was not ready.", anchorId);
}
return false;
}
int roomAnchorCount = SharingStage.Instance.CurrentRoom.GetAnchorCount();
for (int i = 0; i < roomAnchorCount; i++)
{
XString roomAnchorId = SharingStage.Instance.CurrentRoom.GetAnchorName(i);
if (roomAnchorId.GetString().Equals(anchorId))
{
bool downloadStarted = SharingStage.Instance.CurrentRoomManager.DownloadAnchor(SharingStage.Instance.CurrentRoom, anchorId);
if (downloadStarted)
{
if (ShowDetailedLogs)
{
Debug.Log("[SharingWorldAnchorManager] Found a match! Attempting to download anchor...");
}
if (AnchorDebugText != null)
{
AnchorDebugText.text += "\nFound a match! Attempting to download anchor...";
}
}
else
{
Debug.LogWarning("[SharingWorldAnchorManager] Found a match, but we've failed to start download!");
if (AnchorDebugText != null)
{
AnchorDebugText.text += "\nFound a match, but we've failed to start download!";
}
}
return downloadStarted;
}
}
if (ShowDetailedLogs)
{
Debug.LogFormat("[SharingWorldAnchorManager] No matching anchor found for \"{0}\" in room {1}.", anchorId, SharingStage.Instance.CurrentRoom.GetName().GetString());
}
if (AnchorDebugText != null)
{
AnchorDebugText.text += string.Format("\nNo matching anchor found for \"{0}\" in room {1}.", anchorId, SharingStage.Instance.CurrentRoom.GetName().GetString());
}
return false;
}
/// <summary>
/// Exports and uploads the anchor to the sharing service.
/// </summary>
/// <param name="anchor">The anchor to export.</param>
/// <returns>Success</returns>
protected override void ExportAnchor(WorldAnchor anchor)
{
if (SharingStage.Instance == null ||
SharingStage.Instance.Manager == null ||
SharingStage.Instance.CurrentRoom == null)
{
Debug.LogErrorFormat("[SharingWorldAnchorManager] Failed to export anchor \"{0}\"! The sharing service was not ready.", anchor.name);
if (AnchorDebugText != null)
{
AnchorDebugText.text += string.Format("\nFailed to export anchor \"{0}\"! The sharing service was not ready.", anchor.name);
}
return;
}
if (!shouldExportAnchors)
{
if (ShowDetailedLogs)
{
Debug.LogWarningFormat("[SharingWorldAnchorManager] Attempting to export anchor \"{0}\".", anchor.name);
}
if (AnchorDebugText != null)
{
AnchorDebugText.text += string.Format("\nAttempting to export anchor \"{0}\".", anchor.name);
}
if (currentAnchorTransferBatch == null)
{
currentAnchorTransferBatch = new WorldAnchorTransferBatch();
if (AnchorDebugText != null)
{
AnchorDebugText.text += "\nCreating a new World Anchor Transfer Batch...";
}
}
else
{
Debug.LogWarning("[SharingWorldAnchorManager] We didn't properly cleanup our WorldAnchorTransferBatch!");
if (AnchorDebugText != null)
{
AnchorDebugText.text += "\nWe didn't properly cleanup our WorldAnchorTransferBatch!";
}
}
currentAnchorTransferBatch.AddWorldAnchor(anchor.name, anchor);
shouldExportAnchors = true;
}
}
/// <summary>
/// Called by the WorldAnchorTransferBatch when anchor exporting is complete.
/// </summary>
/// <param name="status">Serialization Status.</param>
private void ExportComplete(SerializationCompletionReason status)
{
if (status == SerializationCompletionReason.Succeeded &&
rawAnchorUploadData.Count > MinTrustworthySerializedAnchorDataSize)
{
if (ShowDetailedLogs)
{
Debug.LogFormat("[SharingWorldAnchorManager] Exporting {0} anchors with {1} bytes.", currentAnchorTransferBatch.anchorCount.ToString(), rawAnchorUploadData.ToArray().Length.ToString());
}
if (AnchorDebugText != null)
{
AnchorDebugText.text += string.Format("\nExporting {0} anchors with {1} bytes.",
currentAnchorTransferBatch.anchorCount.ToString(),
rawAnchorUploadData.ToArray().Length.ToString());
}
string[] anchorNames = currentAnchorTransferBatch.GetAllIds();
for (var i = 0; i < anchorNames.Length; i++)
{
SharingStage.Instance.Manager.GetRoomManager().UploadAnchor(
SharingStage.Instance.CurrentRoom,
new XString(anchorNames[i]),
rawAnchorUploadData.ToArray(),
rawAnchorUploadData.Count);
}
}
else
{
Debug.LogWarning("[SharingWorldAnchorManager] Failed to upload anchor!");
if (AnchorDebugText != null)
{
AnchorDebugText.text += "\nFailed to upload anchor!";
}
if (rawAnchorUploadData.Count < MinTrustworthySerializedAnchorDataSize)
{
Debug.LogWarning("[SharingWorldAnchorManager] Anchor data was not valid. Try creating the anchor again.");
if (AnchorDebugText != null)
{
AnchorDebugText.text += "\nAnchor data was not valid. Try creating the anchor again.";
}
}
}
}
/// <summary>
/// Called when a remote anchor has been deserialized.
/// </summary>
/// <param name="status"></param>
/// <param name="anchorBatch"></param>
private void ImportComplete(SerializationCompletionReason status, WorldAnchorTransferBatch anchorBatch)
{
bool successful = status == SerializationCompletionReason.Succeeded;
GameObject objectToAnchor = null;
if (successful)
{
if (ShowDetailedLogs)
{
Debug.LogFormat("[SharingWorldAnchorManager] Successfully imported \"{0}\" anchors.", anchorBatch.anchorCount.ToString());
}
if (AnchorDebugText != null)
{
AnchorDebugText.text += string.Format("\nSuccessfully imported \"{0}\" anchors.", anchorBatch.anchorCount.ToString());
}
string[] anchorNames = anchorBatch.GetAllIds();
for (var i = 0; i < anchorNames.Length; i++)
{
if (AnchorGameObjectReferenceList.TryGetValue(anchorNames[i], out objectToAnchor))
{
AnchorStore.Save(anchorNames[i], anchorBatch.LockObject(anchorNames[i], objectToAnchor));
}
else
{
//TODO: Figure out how to get the GameObject reference from across the network. For now it's best to use unique GameObject names.
Debug.LogWarning("[SharingWorldAnchorManager] Unable to import anchor! We don't know which GameObject to anchor!");
if (AnchorDebugText != null)
{
AnchorDebugText.text += "\nUnable to import anchor! We don\'t know which GameObject to anchor!";
}
}
}
}
else
{
Debug.LogError("[SharingWorldAnchorManager] Import failed!");
if (AnchorDebugText != null)
{
AnchorDebugText.text += "\nImport failed!";
}
}
if (AnchorDownloaded != null)
{
AnchorDownloaded(successful, objectToAnchor);
}
anchorBatch.Dispose();
rawAnchorDownloadData = null;
isImportingAnchors = false;
}
/// <summary>
/// Called by the WorldAnchorTransferBatch as anchor data is available.
/// </summary>
/// <param name="data"></param>
private void WriteBuffer(byte[] data)
{
rawAnchorUploadData.AddRange(data);
}
#endif
}
}