-
-
Notifications
You must be signed in to change notification settings - Fork 82
/
SimpleWebXR.cs
1290 lines (1084 loc) · 51.9 KB
/
SimpleWebXR.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
// SimpleWebXR - Unity
// .*#%@@@@@@&.
// .. , .,(%&@@@@@@@@@@@@@@@@#
// //////, ./(((((/ %@@@@@@@@@@@@@@@@@@@@@@@@*
// *//////////, .*((((((((((, *@@@@@@@@&#/,. #@@@@@@@@@@&.
// /////////////*,*/(((((((((((/ .#@@@@@@@#/,. ,&@@@@@*(@@@@@#
// ////////*,,,,,,,,,,,*/((((((, /@@@@@@@&. (@@@@@% %@@@@@*
// //*,,,,,,,,,,,,,,,,,,,,,,,// .%@@@@@@@( ,&@@@@@* ,@@@@@&.
// ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, (@@@@@@@%. (@@@@@%. /@@@@@%
// .,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,&@@@@@@@/ .&@@@@@/ #@@@@&.
// ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,. #@@@@@@@@#((((((((((((((((((%@@@@@%. .&@@(
// ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@/ *&.
// ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,%@@@@@@@@&%%%%%%%%%%%%%%%%%%&@@@@@# &@@*
// ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, /@@@@@@@&, *@@@@@@, (@@@@%.
// ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,. .%@@@@@@@# %@@@@@# *@@@@@%
// ,,,,,,,,,,,,,,,,,,,,,,,,,,,,. *&@@@@@@&, *@@@@@@, .&@@@@@,
// ,,,,,,,,,,,,,,,,,,,,,,,,,,. #@@@@@@@# %@@@@@# %@@@@@/
// ,,,,,,,,,,. .,,,,,,,,,,. ,&@@@@@@&/,. *@@@@@@,/@@@@@%
// ,.,,,,, ,,,,,,,. /@@@@@@@%#/,. %@@@@@@@@@@@.
// .... .,,,. .&@@@@@@@@@@@@@@@@@@@@@@@@*
// .*(%@@@@@@@@@@@@@@@@@@#
// ,/#&@@@@@@@&.
// .*,
//
// ███████╗██╗███╗ ███╗██████╗ ██╗ ███████╗██╗ ██╗███████╗██████╗ ██╗ ██╗██████╗
// ██╔════╝██║████╗ ████║██╔══██╗██║ ██╔════╝██║ ██║██╔════╝██╔══██╗╚██╗██╔╝██╔══██╗
// ███████╗██║██╔████╔██║██████╔╝██║ █████╗ ██║ █╗ ██║█████╗ ██████╔╝ ╚███╔╝ ██████╔╝
// ╚════██║██║██║╚██╔╝██║██╔═══╝ ██║ ██╔══╝ ██║███╗██║██╔══╝ ██╔══██╗ ██╔██╗ ██╔══██╗
// ███████║██║██║ ╚═╝ ██║██║ ███████╗███████╗╚███╔███╔╝███████╗██████╔╝██╔╝ ██╗██║ ██║
// ╚══════╝╚═╝╚═╝ ╚═╝╚═╝ ╚══════╝╚══════╝ ╚══╝╚══╝ ╚══════╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝
//
//
// -----------------------------------------------------------------------------
//
// https://github.com/Rufus31415/Simple-WebXR-Unity
//
// -----------------------------------------------------------------------------
//
// MIT License
//
// Copyright(c) 2020 Florent GIRAUD (Rufus31415)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// -----------------------------------------------------------------------------
using System;
using System.Text;
using UnityEngine;
using UnityEngine.Events;
#if UNITY_WEBGL && !UNITY_EDITOR
using System.Runtime.InteropServices;
#endif
namespace Rufus31415.WebXR
{
/// <summary>
/// This class can be used as a Behavior to make your application instantly compatible with WebXR.
/// It will display a "Enter AR" or "Enter VR" GUI button that will launch the WebXR session and the main camera pose is automatically updated.
/// However, for more advanced applications, this class contains static functions to expose the WebXR javascript API in the Unity C# code.
/// </summary>
/// <remarks>
/// The data (projection matrix, position and rotation) are shared with javascript via arrays.
/// See also files SimpleWebXR.jslib and SimpleWebXR.jspre
/// </remarks>
public class SimpleWebXR : MonoBehaviour
{
#region MonoBehaviour
/// <summary>
/// Hide the GUI button "Start AR" or "Start VR".
/// </summary>
public bool HideStartButton;
/// <summary>
/// XR Space in which positions are returned
/// </summary>
public WebXRReferenceSpaces ReferenceSpace = WebXRReferenceSpaces.Viewer;
/// <summary>
/// Y axis offset to apply when local floor XR space is not supported
/// </summary>
public float FallbackUserHeight = 1.8f;
/// Update cameras poses and trigger events
private void LateUpdate()
{
_referenceSpace = ReferenceSpace;
_fallbackUserHeight = FallbackUserHeight;
UpdateWebXR();
}
/// <summary>
/// A human-readable presentation of the WebXR session and capabilities
/// </summary>
public override string ToString() => Stringify();
#if UNITY_WEBGL
// Display "Enter AR" or "Enter VR" button if WebXR immersive AR is supported
private void OnGUI()
{
if (HideStartButton) return;
if (!InternalInSession)
{
var width = 120;
var height = 60;
if ((IsArSupported() || IsVrSupported()))
{
if (GUI.Button(new Rect((Screen.width - width) / 2, Screen.height - height, width, height), "Enter " + (IsArSupported() ? "AR" : "VR")))
{
StartSession();
}
}
else
{
GUI.Button(new Rect((Screen.width - width) / 2, Screen.height - height, width, height), "WebXR\r\nNot supported");
}
}
}
#endif
#endregion
#region Static WebXR library
/// <summary>
/// Indicates if a WebXR session is running
/// </summary>
public static bool InSession { get; private set; }
/// <summary>
/// User height in meter (startup distance from floor to device)
/// </summary>
public static float UserHeight => _dataArray[100];
/// <summary>
/// Event triggered when a session has started
/// </summary>
public static readonly UnityEvent SessionStart = new UnityEvent();
/// <summary>
/// Event triggered when a session has ended
/// </summary>
public static readonly UnityEvent SessionEnd = new UnityEvent();
/// <summary>
/// Left input controller data
/// </summary>
public static readonly WebXRInputSource LeftInput = new WebXRInputSource(WebXRHandedness.Left);
/// <summary>
/// Right input controller data
/// </summary>
public static readonly WebXRInputSource RightInput = new WebXRInputSource(WebXRHandedness.Right);
/// <summary>
/// Event triggered when the browser triggers a XRSession.selectend event, which means the input source has fully completed its primary action.
/// </summary>
/// <remarks>
/// On Oculus Quest : Back trigger button was pressed
/// On Hololens 2 : A air tap has been was performed
/// On smartphones : The screen was touched
/// </remarks>
public static readonly WebXRInputEvent InputSourceSelect = new WebXRInputEvent();
/// <summary>
/// Event triggered when the browser triggers a XRSession.selectstart event, which means the input source begins its primary action.
/// </summary>
public static readonly WebXRInputEvent InputSourceSelectStart = new WebXRInputEvent();
/// <summary>
/// Event triggered when the browser triggers a XRSession.selectend event, which means the input source ends its primary action.
/// </summary>
public static readonly WebXRInputEvent InputSourceSelectEnd = new WebXRInputEvent();
/// <summary>
/// Event triggered when the browser triggers a XRSession.selectend event, which means the input source has fully completed its primary squeeze action.
/// </summary>
/// <remarks>
/// On Oculus Quest : Side grip button was pressed
/// </remarks>
public static readonly WebXRInputEvent InputSourceSqueeze = new WebXRInputEvent();
/// <summary>
/// Event triggered when the browser triggers a XRSession.selectstart event, which means the input source begins its primary squeeze action.
/// </summary>
public static readonly WebXRInputEvent InputSourceSqueezeStart = new WebXRInputEvent();
/// <summary>
/// Event triggered when the browser triggers a XRSession.selectend event, which means the input source ends its primary squeeze action.
/// </summary>
public static readonly WebXRInputEvent InputSourceSqueezeEnd = new WebXRInputEvent();
/// <summary>
/// Event triggered when the browser triggers a XRSession.inputsourceschange event, which means a input sources has been added or removed.
/// </summary>
public static readonly UnityEvent InputSourcesChange = new UnityEvent();
/// <summary>
/// Camera that renders Left eye (Camera.main)
/// </summary>
public static Camera LeftEye => _cameras[0];
/// <summary>
/// Camera that renders Right eye
/// </summary>
public static Camera RightEye => _cameras[1];
/// <summary>
/// Indicates that a hit test is available in HitTestPosition and HitTestRotation
/// </summary>
public static bool HitTestInProgress => _byteArray[48] != 0;
/// <summary>
/// Indicates hit test is supported
/// The immersive session should be started to estimate this capability
/// </summary>
public static bool HitTestSupported => _byteArray[49] != 0;
/// <summary>
/// Position of the hit test between head ray and the real world
/// </summary>
public static Vector3 HitTestPosition;
/// <summary>
/// Orientation of the hit test normal between head ray and the real world
/// </summary>
public static Quaternion HitTestRotation;
/// <summary>
/// Initialize the binding with the WebXR API, via shared arrays
/// </summary>
public static void Initialize()
{
if (_initialized) return;
InitWebXR(_dataArray, _dataArray.Length, _byteArray, _byteArray.Length, _handData, _handData.Length);
_initialized = true;
}
/// <summary>
/// Returns SimpleWebXR.LeftInput or SimpleWebXR.RightInput according to the argument
/// </summary>
/// <param name="handedness">The handedness of the desired input source</param>
/// <returns>Input source controller</returns>
public static WebXRInputSource GetInput(WebXRHandedness handedness)
{
return handedness == WebXRHandedness.Left ? LeftInput : RightInput;
}
/// <summary>
/// Returns the instance of the GameObject SimpleWebXR in current scene.
/// </summary>
/// <remarks>Return null is no GameObject was found</remarks>
public static SimpleWebXR GetInstance()
{
return FindObjectOfType<SimpleWebXR>();
}
/// <summary>
/// Ensures that a SimpleWebXR instance is available in the current scene.
/// If no instance was found, a "WebXR" GameObject is created as a root GameObject with a SimpleWebXR component.
/// </summary>
/// <returns>The existing or newly created SimpleWebXR instance</returns>
public static SimpleWebXR EnsureInstance()
{
var xr = GetInstance();
if (xr) return xr;
var newGameObject = new GameObject("WebXR");
return newGameObject.AddComponent<SimpleWebXR>();
}
/// <summary>
/// Check if Augmented Reality (AR) is supported
/// </summary>
/// <remarks>It returns the result of navigator.xr.isSessionSupported('immersive-ar')</remarks>
/// <returns>True if AR is supported</returns>
public static bool IsArSupported()
{
Initialize();
return InternalIsArSupported();
}
/// <summary>
/// Check if Virtual Reality (VR) is supported
/// </summary>
/// <remarks>It returns the result of navigator.xr.isSessionSupported('immersive-vr')</remarks>
/// <returns>True if VR is supported</returns>
public static bool IsVrSupported()
{
Initialize();
return InternalIsVrSupported();
}
/// <summary>
/// Check if OVR Multiview2 extension is supported.
/// </summary>
/// <returns>True, if multiview2 is supported.</returns>
public static bool IsMultiview2Supported()
{
Initialize();
return InternalIsOVRMultiview2Supported();
}
/// <summary>
/// Check if Oculus Multiview with sampling is supported.
/// </summary>
/// <returns>True, if Oculus multiview with sampling is supported.</returns>
public static bool IsOculusMultiviewSampledSupported()
{
Initialize();
return InternalIsOculusMultiviewSupported();
}
/// <summary>
/// Triggers the start of a WebXR immersive session
/// </summary>
public static void StartSession()
{
Initialize();
if (InternalInSession) return;
InternalStartSession();
}
/// <summary>
/// Ends the current WebXR immersive session
/// </summary>
public static void EndSession()
{
if (!InternalInSession) return;
InternalHitTestCancel();
InternalEndSession();
}
/// <summary>
/// Starts hit test
/// </summary>
public static void HitTestStart()
{
Initialize();
InternalHitTestStart();
}
/// <summary>
/// Ends hit test
/// </summary>
public static void HitTestCancel()
{
Initialize();
InternalHitTestCancel();
}
/// <summary>
/// Update cameras (eyes), input sources and propagates WebXR events to Unity. This function should be called once per frame.
/// </summary>
public static void UpdateWebXR()
{
UpdateCamera(WebXRViewEyes.Left);
UpdateCamera(WebXRViewEyes.Right);
UpdateInput(LeftInput);
UpdateInput(RightInput);
LeftInput.Available = _byteArray[44] != 0;
RightInput.Available = _byteArray[45] != 0;
// Input source change event
if (_byteArray[3] != 0)
{
InputSourcesChange.Invoke();
_byteArray[3] = 0;
}
UpdateHitTest();
// Session state changed invoked when all gamepads and cameras are updated
if (InternalInSession && !InSession) //New session detected
{
InSession = true;
SessionStart.Invoke();
}
else if (InSession && !InternalInSession) // End of session detected
{
InSession = false;
SessionEnd.Invoke();
}
}
/// <summary>
/// Applies haptic pulse feedback to a controller
/// </summary>
/// <param name="hand">Controller to apply feedback</param>
/// <param name="intensity">Feedback strength between 0 and 1</param>
/// <param name="duration">Feedback duration in milliseconds</param>
public static void HapticPulse(WebXRHandedness hand, float intensity, float duration)
{
_dataArray[101 + (int)hand] = intensity;
_dataArray[103 + (int)hand] = duration;
}
/// <summary>
/// A human-readable presentation of the WebXR session and capabilities
/// </summary>
public static string Stringify()
{
var sb = new StringBuilder();
sb.Append("In session : ");
sb.AppendLine(InSession ? "Yes" : "No");
sb.Append("AR supported : ");
sb.AppendLine(IsArSupported() ? "Yes" : "No");
sb.Append("VR supported : ");
sb.AppendLine(IsVrSupported() ? "Yes" : "No");
sb.Append("User height : ");
sb.AppendLine(UserHeight.ToString("0.0"));
sb.AppendLine(Stringify(LeftEye, "left"));
sb.AppendLine(Stringify(RightEye, "right"));
sb.Append(LeftInput.ToString());
sb.Append(RightInput.ToString());
return sb.ToString();
}
// Indicate that InitWebXR() has been called
private static bool _initialized = false;
// Shared float array with javascript.
// [0] -> [15] : projection matrix of view 1
// [16], [17], [18] : X, Y, Z position in m of view 1
// [19], [20], [21], [22] : RX, RY, RZ, RW rotation (quaternion) of view 1
// [23] -> [26] : Viewport X, Y, width, height of view 1
// [27] -> [42] : projection matrix of view 2
// [43], [44], [45] : X, Y, Z position in m of view 2
// [46], [47], [48], [49] : RX, RY, RZ, RW rotation (quaternion) of view 2
// [50] -> [53] : Viewport X, Y, width, height of view 2
// [54] -> [60] : Left input x, y, z, rx, ry, rz, rw
// [61] -> [68] : left input axes
// [69] -> [76] : left gamepad value
// [77] -> [83] : right input x, y, z, rx, ry, rz, rw
// [84] -> [91] : right input axes
// [92] -> [99] : right gamepad value
// [100] : user height
// [101] : left input haptic pulse value
// [102] : right input haptic pulse value
// [103] : left input haptic pulse duration
// [104] : right input haptic pulse duration
// [105] -> [111] : hit test x, y, z, rx, ry, rz, rw
private static readonly float[] _dataArray = new float[112];
// Shared float array with javascript.
// [0] : number of views (0 : session is stopped)
// [1] : left controller events
// [2] : right controller events
// [3] : input change event
// [4] : left input has position info
// [5] : left input target ray mode
// [6] : left input gamepad axes count
// [7] : left input gamepad buttons count
// [8] -> [15] : left inputs touched
// [16] -> [23] : left inputs pressed
// [24] : right input has position info
// [25] : right input target ray mode
// [26] : right input gamepad axes count
// [27] : right input gamepad buttons count
// [28] -> [35] : right inputs touched
// [36] -> [43] : right inputs pressed
// [44] : Left controller active
// [45] : Right controller active
// [46] : Left hand active
// [47] : Right hand active
// [48] : Hit test in progress
// [49] : Hit test supported
private static readonly byte[] _byteArray = new byte[50];
// Hand data
// [0] -> [7] : Left Wrist x, y, z, rx, ry, rz, zw, radius
// [8] -> [199] : Left other fingers ...
// [200] -> [399] : right wrist and fingers
private static readonly float[] _handData = new float[8 * 25 * 2];
// static cache value of ReferenceSpace
private static WebXRReferenceSpaces _referenceSpace;
// static cache value of FallbackUserHeight
private static float _fallbackUserHeight;
// Number of views (i.e. cameras)
private static WebXRViewEyes ViewEye => (WebXRViewEyes)_byteArray[0];
// A session is running
private static bool InternalInSession => _byteArray[0] != 0;
// Cameras created for each eyes ([0]:left, [1]:right)
private static readonly Camera[] _cameras = new Camera[2];
// Indicates that main camera properties should be restored after sessions ends
private static bool _shouldRestoreMainCameraProperties;
// Remember main camera background color to restore value after sessions ends
private static Color _mainCameraBackgroundColor;
// Remember main camera clear flags to restore value after sessions ends
private static CameraClearFlags _mainCameraClearFlags;
private static Matrix4x4 _mainCameraProjectionMatrix;
private static Rect _mainCameraRect;
// Create and update camera pose
private static void UpdateCamera(WebXRViewEyes eye)
{
var id = (eye == WebXRViewEyes.Left) ? 0 : 1;
// If the camera for this id should not exist
if ((ViewEye & eye) != eye)
{
if (_cameras[id])
{
if (eye == WebXRViewEyes.Left) // don't destroy main camera
{
if (_shouldRestoreMainCameraProperties)
{
Camera.main.backgroundColor = _mainCameraBackgroundColor;
Camera.main.clearFlags = _mainCameraClearFlags;
Camera.main.projectionMatrix = _mainCameraProjectionMatrix;
Camera.main.rect = _mainCameraRect;
}
}
else
{
Destroy(_cameras[id].gameObject);
}
_cameras[id] = null;
}
return;
}
// Create camera
if (!_cameras[id])
{
if (id > 0)
{
// clone main camera
_cameras[id] = Instantiate(Camera.main, Camera.main.gameObject.transform.parent);
_cameras[id].name = "WebXRCamera_" + id;
_cameras[id].depth = Camera.main.depth - 1;
}
else
{
_shouldRestoreMainCameraProperties = false;
if (Camera.main)
{
_cameras[0] = Camera.main;
_shouldRestoreMainCameraProperties = true;
_mainCameraBackgroundColor = Camera.main.backgroundColor;
_mainCameraClearFlags = Camera.main.clearFlags;
_mainCameraProjectionMatrix = Camera.main.projectionMatrix;
_mainCameraRect = Camera.main.rect;
}
else
{
var go = new GameObject("WebXRCamera_0");
_cameras[0] = go.AddComponent<Camera>();
}
}
if (IsArSupported())
{
_cameras[id].clearFlags = CameraClearFlags.SolidColor;
_cameras[id].backgroundColor = new Color(0, 0, 0, 0);
}
}
var floatStartId = id * 27;
var rect = new Rect(_dataArray[floatStartId + 23], _dataArray[floatStartId + 24], _dataArray[floatStartId + 25], _dataArray[floatStartId + 26]);
if (id > 0)
{
if (_cameras[0] && _cameras[0].rect == rect)
{
_cameras[id].gameObject.SetActive(false);
return;
}
else
{
_cameras[id].gameObject.SetActive(true);
}
}
_cameras[id].rect = rect;
// Get and transpose projection matrix
var pm = new Matrix4x4();
pm.m00 = _dataArray[floatStartId + 0];
pm.m01 = _dataArray[floatStartId + 4];
pm.m02 = _dataArray[floatStartId + 8];
pm.m03 = _dataArray[floatStartId + 12];
pm.m10 = _dataArray[floatStartId + 1];
pm.m11 = _dataArray[floatStartId + 5];
pm.m12 = _dataArray[floatStartId + 9];
pm.m13 = _dataArray[floatStartId + 13];
pm.m20 = _dataArray[floatStartId + 2];
pm.m21 = _dataArray[floatStartId + 6];
pm.m22 = _dataArray[floatStartId + 10];
pm.m23 = _dataArray[floatStartId + 14];
pm.m30 = _dataArray[floatStartId + 3];
pm.m31 = _dataArray[floatStartId + 7];
pm.m32 = _dataArray[floatStartId + 11];
pm.m33 = _dataArray[floatStartId + 15];
_cameras[id].projectionMatrix = pm;
// Get position and rotation Z, RX and RY are inverted
_cameras[id].transform.localPosition = ToUnityPosition(_dataArray[floatStartId + 16], _dataArray[floatStartId + 17], _dataArray[floatStartId + 18]);
_cameras[id].transform.localRotation = ToUnityRotation(_dataArray[floatStartId + 19], _dataArray[floatStartId + 20], _dataArray[floatStartId + 21], _dataArray[floatStartId + 22]);
}
// Update input source pose
private static void UpdateInput(WebXRInputSource inputSource)
{
var floatStartId = (int)inputSource.Handedness * 23 + 54;
var byteStartId = (int)inputSource.Handedness * 20 + 4;
inputSource.Position = ToUnityPosition(_dataArray[floatStartId + 0], _dataArray[floatStartId + 1], _dataArray[floatStartId + 2]);
inputSource.Rotation = ToUnityRotation(_dataArray[floatStartId + 3], _dataArray[floatStartId + 4], _dataArray[floatStartId + 5], _dataArray[floatStartId + 6]);
inputSource.IsPositionTracked = (_byteArray[byteStartId + 0] != 0);
var eventId = (int)inputSource.Handedness + 1;
var mask = _byteArray[eventId];
if (mask != 0)
{
RaiseInputSourceEvent(mask, WebXRInputSourceEventTypes.Select, InputSourceSelect, inputSource.Select, inputSource);
RaiseInputSourceEvent(mask, WebXRInputSourceEventTypes.SelectEnd, InputSourceSelectEnd, inputSource.SelectEnd, inputSource);
RaiseInputSourceEvent(mask, WebXRInputSourceEventTypes.SelectStart, InputSourceSelectStart, inputSource.SelectStart, inputSource);
RaiseInputSourceEvent(mask, WebXRInputSourceEventTypes.Squeeze, InputSourceSqueeze, inputSource.Squeeze, inputSource);
RaiseInputSourceEvent(mask, WebXRInputSourceEventTypes.SqueezeEnd, InputSourceSqueezeEnd, inputSource.SqueezeEnd, inputSource);
RaiseInputSourceEvent(mask, WebXRInputSourceEventTypes.SqueezeStart, InputSourceSqueezeStart, inputSource.SqueezeStart, inputSource);
_byteArray[eventId] = 0;
}
inputSource.TargetRayMode = (WebXRTargetRayModes)_byteArray[byteStartId + 1];
inputSource.AxesCount = _byteArray[byteStartId + 2];
for (int i = 0; i < WebXRInputSource.AXES_BUTTON_COUNT; i++)
{
inputSource.Axes[i] = _dataArray[floatStartId + 7 + i];
}
inputSource.ButtonsCount = _byteArray[byteStartId + 3];
for (int i = 0; i < WebXRInputSource.AXES_BUTTON_COUNT; i++)
{
var button = inputSource.Buttons[i];
button.Value = _dataArray[floatStartId + 15 + i];
button.Touched = _byteArray[byteStartId + 4 + i] != 0;
button.Pressed = _byteArray[byteStartId + 12 + i] != 0;
}
var handAvailable = 0 != _byteArray[46 + (int)inputSource.Handedness];
inputSource.Hand.Available = handAvailable;
if (handAvailable)
{
for (int j = 0; j < 25; j++)
{
var i = (int)inputSource.Handedness * 200 + j * 8;
var joint = inputSource.Hand.Joints[j];
joint.Position = ToUnityPosition(_handData[i], _handData[i + 1], _handData[i + 2]);
joint.Rotation = ToUnityRotation(_handData[i + 3], _handData[i + 4], _handData[i + 5], _handData[i + 6]);
joint.Radius = _handData[i + 7];
}
}
}
// Raise input sources select and squeeze events
private static void RaiseInputSourceEvent(byte mask, WebXRInputSourceEventTypes type, WebXRInputEvent webxrInputEvent, UnityEvent unityEvent, WebXRInputSource inputSource)
{
if (((WebXRInputSourceEventTypes)mask & type) == type)
{
switch (type)
{
case WebXRInputSourceEventTypes.SelectStart:
inputSource.Selected = true;
break;
case WebXRInputSourceEventTypes.SelectEnd:
inputSource.Selected = false;
break;
case WebXRInputSourceEventTypes.SqueezeStart:
inputSource.Squeezed = true;
break;
case WebXRInputSourceEventTypes.SqueezeEnd:
inputSource.Squeezed = false;
break;
}
unityEvent.Invoke();
webxrInputEvent.Invoke(inputSource);
Debug.Log($"{inputSource.Handedness} : {type}");
}
}
// Update the hit test infos
private static void UpdateHitTest()
{
if (HitTestInProgress)
{
HitTestPosition = ToUnityPosition(_dataArray[105], _dataArray[106], _dataArray[107]);
HitTestRotation = ToUnityRotation(_dataArray[108], _dataArray[109], _dataArray[110], _dataArray[111]);
}
}
// Converts a WebGL position coordinate to a Unity position coordinate
private static Vector3 ToUnityPosition(float x, float y, float z)
{
float yOffset = 0;
if (_referenceSpace == WebXRReferenceSpaces.LocalFloor)
{
yOffset = UserHeight <= 0 ? _fallbackUserHeight : UserHeight;
}
return new Vector3(x, y + yOffset, -z);
}
// Converts a WebGL rotation to a Unity rotation
private static Quaternion ToUnityRotation(float x, float y, float z, float w)
{
return new Quaternion(-x, -y, z, w);
}
#if UNITY_WEBGL && !UNITY_EDITOR // If executed in browser
[DllImport("__Internal")]
private static extern void InternalStartSession();
[DllImport("__Internal")]
private static extern void InternalEndSession();
[DllImport("__Internal")]
private static extern void InitWebXR(float[] dataArray, int length, byte[] byteArray, int _byteArrayLength, float[] handDataArray, int handDataArrayLength);
[DllImport("__Internal")]
private static extern bool InternalIsArSupported();
[DllImport("__Internal")]
private static extern bool InternalIsVrSupported();
[DllImport("__Internal")]
private static extern bool InternalIsOVRMultiview2Supported();
[DllImport("__Internal")]
private static extern bool InternalIsOculusMultiviewSupported();
[DllImport("__Internal")]
private static extern void InternalHitTestStart();
[DllImport("__Internal")]
private static extern void InternalHitTestCancel();
[DllImport("__Internal")]
private static extern void InternalGetDeviceOrientation(float[] orientationArray, byte[] orientationInfo);
#else // if executed with Unity editor
private static void InternalEndSession() { }
private static void InternalStartSession() { }
private static void InitWebXR(float[] dataArray, int length, byte[] _byteArray, int _byteArrayLength, float[] handDataArray, int handDataArrayLength) { }
private static bool InternalIsArSupported() => false;
private static bool InternalIsVrSupported() => false;
private static bool InternalIsOVRMultiview2Supported() => false;
private static bool InternalIsOculusMultiviewSupported() => false;
private static void InternalGetDeviceOrientation(float[] orientationArray, byte[] orientationInfo) { }
private static void InternalHitTestStart() { }
private static void InternalHitTestCancel() { }
#endif
[System.Flags]
private enum WebXRViewEyes
{
None = 0,
Left = 1,
Right = 2,
Both = Left | Right
}
[System.Flags]
private enum WebXRInputSourceEventTypes
{
None = 0,
SqueezeStart = 1,
Squeeze = 2,
SqueezeEnd = 4,
SelectStart = 8,
Select = 16,
SelectEnd = 32
}
private static string Stringify(Camera camera, string name)
{
if (camera)
{
var sb = new StringBuilder();
sb.Append(name);
sb.AppendLine("eye : ");
sb.Append(" Position :");
sb.AppendLine(camera.transform.position.ToString());
sb.Append(" Rotation :");
sb.AppendLine(camera.transform.rotation.eulerAngles.ToString());
return sb.ToString();
}
else return $"No {name} eye";
}
#endregion
#region Device orientation sensor
// Orientation float data (shared array with javascript)
// [0] : alpha
// [1] : beta
// [2] : gamma
private static readonly float[] _orientationArray = new float[3];
// Orientation byte data (shared array with javascript)
// [0] : 1=valid angle values, 0=angles not available yet
private static readonly byte[] _orientationInfo = new byte[1];
// Indicates that InternalGetDeviceOrientation was already called
private static bool _orientationDeviceStarted = false;
/// <summary>
/// Get the orientation of the device. This feature is independent of WebXR and can be used as a fallback if WebXR is not supported.
/// </summary>
/// <remarks>
/// Values come from the javascript event "deviceorientation" obtained by : window.addEventListener("deviceorientation", _onDeviceOrientation);
/// The x axis is in the plane of the screen and is positive toward the right and negative toward the left.
/// The y axis is in the plane of the screen and is positive toward the top and negative toward the bottom.
/// The z axis is perpendicular to the screen or keyboard, and is positive extending outward from the screen.
/// </remarks>
/// <see href="https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Orientation_and_motion_data_explained#About_rotation"/>
/// <param name="alpha">Rotation around the z axis -- that is, twisting the device -- causes the alpha rotation angle to change. The alpha angle is 0° when top of the device is pointed directly toward the Earth's north pole, and increases as the device is rotated toward the left</param>
/// <param name="beta">Rotation around the x axis -- that is, tipping the device away from or toward the user -- causes the beta rotation angle to change. The beta angle is 0° when the device's top and bottom are the same distance from the Earth's surface; it increases toward 180° as the device is tipped forward toward the user, and it decreases toward -180° as the device is tipped backward away from the user.</param>
/// <param name="gamma">Rotation around the y axis -- that is, tilting the device toward the left or right -- causes the gamma rotation angle to change.The gamma angle is 0° when the device's left and right sides are the same distance from the surface of the Earth, and increases toward 90° as the device is tipped toward the right, and toward -90° as the device is tipped toward the left.</param>
/// <returns>True if valid angles are returned</returns>
public static bool GetDeviceOrientation(out float alpha, out float beta, out float gamma)
{
if (!_orientationDeviceStarted)
{
InternalGetDeviceOrientation(_orientationArray, _orientationInfo);
_orientationDeviceStarted = true;
}
alpha = _orientationArray[0];
beta = _orientationArray[1];
gamma = _orientationArray[2];
return _orientationInfo[0] != 0;
}
#endregion
#region Simulation
public static float[] SimulatedDataArray => _dataArray;
public static byte[] SimulatedByteArray => _byteArray;
public static Quaternion SimulatedToUnityRotation(Quaternion q)
{
return ToUnityRotation(q.x, q.y, q.z, q.w);
}
#endregion Simulation
}
/// <summary>
/// Handedness of a controller
/// </summary>
public enum WebXRHandedness { Left = 0, Right = 1 }
/// <summary>
/// Contains WebXR input source controller state and events
/// </summary>
[Serializable]
public class WebXRInputSource
{
#region Events
/// <summary>
/// Event triggered when the browser triggers a XRSession.selectend event, which means the input source has fully completed its primary action.
/// </summary>
/// <remarks>
/// On Oculus Quest : Back trigger button was pressed
/// On Hololens 2 : A air tap has been was performed
/// On smartphones : The screen was touched
/// </remarks>
public readonly UnityEvent Select = new UnityEvent();
/// <summary>
/// Event triggered when the browser triggers a XRSession.selectstart event, which means the input source begins its primary action.
/// </summary>
public readonly UnityEvent SelectStart = new UnityEvent();
/// <summary>
/// Event triggered when the browser triggers a XRSession.selectend event, which means the input source ends its primary action.
/// </summary>
public readonly UnityEvent SelectEnd = new UnityEvent();
/// <summary>
/// Event triggered when the browser triggers a XRSession.selectend event, which means the input source has fully completed its primary squeeze action.
/// </summary>
/// <remarks>
/// On Oculus Quest : Side grip button was pressed
/// </remarks>
public readonly UnityEvent Squeeze = new UnityEvent();
/// <summary>
/// Event triggered when the browser triggers a XRSession.selectstart event, which means the input source begins its primary squeeze action.
/// </summary>
public readonly UnityEvent SqueezeStart = new UnityEvent();
/// <summary>
/// Event triggered when the browser triggers a XRSession.selectend event, which means the input source ends its primary squeeze action.
/// </summary>
public readonly UnityEvent SqueezeEnd = new UnityEvent();
#endregion
#region Constant
public const int AXES_BUTTON_COUNT = 8;
#endregion
#region State
/// <summary>
/// Indicates if the input source exists
/// </summary>
public bool Available;
/// <summary>
/// Handedness of the input source
/// </summary>
public readonly WebXRHandedness Handedness;
/// <summary>
/// Indicates that the input source is detected and its position is tracked
/// </summary>
public bool IsPositionTracked = false;
/// <summary>
/// Current position of the input source if the position is tracked
/// </summary>
public Vector3 Position;
/// <summary>
/// Current rotation of the input source if the position is tracked
/// </summary>
public Quaternion Rotation;
/// <summary>
/// Number of axes available for this input source
/// </summary>
public int AxesCount = 0;