-
Notifications
You must be signed in to change notification settings - Fork 215
/
BrowserWorld.cpp
1663 lines (1460 loc) · 51.6 KB
/
BrowserWorld.cpp
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
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "BrowserWorld.h"
#include "Controller.h"
#include "ControllerContainer.h"
#include "FadeAnimation.h"
#include "Device.h"
#include "DeviceDelegate.h"
#include "ExternalBlitter.h"
#include "ExternalVR.h"
#include "GeckoSurfaceTexture.h"
#include "LoadingAnimation.h"
#include "Skybox.h"
#include "SplashAnimation.h"
#include "Pointer.h"
#include "Widget.h"
#include "WidgetMover.h"
#include "WidgetResizer.h"
#include "WidgetPlacement.h"
#include "Cylinder.h"
#include "Quad.h"
#include "VRBrowser.h"
#include "VRVideo.h"
#include "VRLayer.h"
#include "vrb/CameraSimple.h"
#include "vrb/Color.h"
#include "vrb/ConcreteClass.h"
#include "vrb/CreationContext.h"
#include "vrb/CullVisitor.h"
#include "vrb/DataCache.h"
#include "vrb/DrawableList.h"
#include "vrb/Geometry.h"
#include "vrb/GLError.h"
#include "vrb/Group.h"
#include "vrb/Light.h"
#include "vrb/Logger.h"
#include "vrb/Matrix.h"
#include "vrb/ModelLoaderAndroid.h"
#include "vrb/NodeFactoryObj.h"
#include "vrb/ParserObj.h"
#include "vrb/PerformanceMonitor.h"
#include "vrb/RenderContext.h"
#include "vrb/RenderState.h"
#include "vrb/SurfaceTextureFactory.h"
#include "vrb/TextureCache.h"
#include "vrb/TextureSurface.h"
#include "vrb/TextureCubeMap.h"
#include "vrb/ThreadUtils.h"
#include "vrb/Toggle.h"
#include "vrb/Transform.h"
#include "vrb/VertexArray.h"
#include "vrb/Vector.h"
#include <array>
#include <functional>
#include <fstream>
#include <unordered_map>
#define ASSERT_ON_RENDER_THREAD(X) \
if (m.context && !m.context->IsOnRenderThread()) { \
VRB_ERROR("Function: '%s' not called on render thread.", __FUNCTION__); \
return X; \
}
#define INJECT_SKYBOX_PATH "skybox"
using namespace vrb;
namespace {
const int GestureSwipeLeft = 0;
const int GestureSwipeRight = 1;
const float kScrollFactor = 20.0f; // Just picked what fell right.
const double kHoverRate = 1.0 / 10.0;
class SurfaceObserver;
typedef std::shared_ptr<SurfaceObserver> SurfaceObserverPtr;
class SurfaceObserver : public SurfaceTextureObserver {
public:
explicit SurfaceObserver(crow::BrowserWorldWeakPtr& aWorld);
~SurfaceObserver() override = default;
void SurfaceTextureCreated(const std::string& aName, GLuint aHandle, jobject aSurfaceTexture) override;
void SurfaceTextureHandleUpdated(const std::string aName, GLuint aHandle) override;
void SurfaceTextureDestroyed(const std::string& aName) override;
void SurfaceTextureCreationError(const std::string& aName, const std::string& aReason) override;
protected:
crow::BrowserWorldWeakPtr mWorld;
};
SurfaceObserver::SurfaceObserver(crow::BrowserWorldWeakPtr& aWorld) : mWorld(aWorld) {}
void
SurfaceObserver::SurfaceTextureCreated(const std::string& aName, GLuint, jobject aSurfaceTexture) {
crow::BrowserWorldPtr world = mWorld.lock();
if (world) {
world->SetSurfaceTexture(aName, aSurfaceTexture);
}
}
void
SurfaceObserver::SurfaceTextureHandleUpdated(const std::string, GLuint) {}
void
SurfaceObserver::SurfaceTextureDestroyed(const std::string& aName) {
crow::BrowserWorldPtr world = mWorld.lock();
if (world) {
jobject nullObject = nullptr;
world->SetSurfaceTexture(aName, nullObject);
}
}
void
SurfaceObserver::SurfaceTextureCreationError(const std::string& aName, const std::string& aReason) {
}
class PerformanceObserver;
typedef std::shared_ptr<PerformanceObserver> PerformanceObserverPtr;
class PerformanceObserver : public PerformanceMonitorObserver {
public:
void PoorPerformanceDetected(const double& aTargetFrameRate, const double& aAverageFrameRate) override;
void PerformanceRestored(const double& aTargetFrameRate, const double& aAverageFrameRate) override;
};
void
PerformanceObserver::PoorPerformanceDetected(const double& aTargetFrameRate, const double& aAverageFrameRate) {
crow::VRBrowser::HandlePoorPerformance();
}
void
PerformanceObserver::PerformanceRestored(const double& aTargetFrameRate, const double& aAverageFrameRate) {
}
} // namespace
namespace crow {
struct BrowserWorld::State {
BrowserWorldWeakPtr self;
std::vector<WidgetPtr> widgets;
SurfaceObserverPtr surfaceObserver;
DeviceDelegatePtr device;
bool paused;
bool glInitialized;
bool modelsLoaded;
RenderContextPtr context;
CreationContextPtr create;
ModelLoaderAndroidPtr loader;
GroupPtr rootOpaqueParent;
TransformPtr rootOpaque;
TransformPtr rootTransparent;
GroupPtr rootController;
LightPtr light;
ControllerContainerPtr controllers;
CullVisitorPtr cullVisitor;
DrawableListPtr drawList;
CameraPtr leftCamera;
CameraPtr rightCamera;
float cylinderDensity;
float nearClip;
float farClip;
JNIEnv* env;
jobject activity;
GestureDelegateConstPtr gestures;
ExternalVRPtr externalVR;
ExternalBlitterPtr blitter;
bool windowsInitialized;
SkyboxPtr skybox;
FadeAnimationPtr fadeAnimation;
uint32_t loaderDelay;
bool exitImmersiveRequested;
WidgetPtr resizingWidget;
LoadingAnimationPtr loadingAnimation;
SplashAnimationPtr splashAnimation;
VRVideoPtr vrVideo;
PerformanceMonitorPtr monitor;
WidgetMoverPtr movingWidget;
WidgetResizerPtr widgetResizer;
std::unordered_map<vrb::Node*, std::pair<Widget*, float>> depthSorting;
State() : paused(true), glInitialized(false), modelsLoaded(false), env(nullptr), cylinderDensity(0.0f), nearClip(0.1f),
farClip(300.0f), activity(nullptr), windowsInitialized(false), exitImmersiveRequested(false), loaderDelay(0) {
context = RenderContext::Create();
create = context->GetRenderThreadCreationContext();
loader = ModelLoaderAndroid::Create(context);
rootOpaque = Transform::Create(create);
rootTransparent = Transform::Create(create);
rootController = Group::Create(create);
light = Light::Create(create);
rootOpaqueParent = Group::Create(create);
rootOpaqueParent->AddNode(rootOpaque);
//rootOpaque->AddLight(light);
//rootTransparent->AddLight(light);
rootController->AddLight(light);
cullVisitor = CullVisitor::Create(create);
drawList = DrawableList::Create(create);
controllers = ControllerContainer::Create(create, rootTransparent);
externalVR = ExternalVR::Create();
blitter = ExternalBlitter::Create(create);
fadeAnimation = FadeAnimation::Create(create);
loadingAnimation = LoadingAnimation::Create(create);
splashAnimation = SplashAnimation::Create(create);
monitor = PerformanceMonitor::Create(create);
monitor->AddPerformanceMonitorObserver(std::make_shared<PerformanceObserver>());
#if defined(WAVEVR)
monitor->SetPerformanceDelta(15.0);
#endif
}
void CheckBackButton();
bool CheckExitImmersive();
void EnsureControllerFocused();
void ChangeControllerFocus(const Controller& aController);
void UpdateControllers(bool& aRelayoutWidgets);
WidgetPtr GetWidget(int32_t aHandle) const;
WidgetPtr FindWidget(const std::function<bool(const WidgetPtr&)>& aCondition) const;
bool IsParent(const Widget& aChild, const Widget& aParent) const;
int ParentCount(const WidgetPtr& aWidget) const;
float ComputeNormalizedZ(const Widget& aWidget) const;
void SortWidgets();
};
void
BrowserWorld::State::CheckBackButton() {
for (Controller& controller: controllers->GetControllers()) {
if (!controller.enabled || (controller.index < 0)) {
continue;
}
if (!(controller.lastButtonState & ControllerDelegate::BUTTON_APP) &&
(controller.buttonState & ControllerDelegate::BUTTON_APP)) {
controller.lastButtonState = controller.buttonState;
VRBrowser::HandleBack();
}
}
}
bool
BrowserWorld::State::CheckExitImmersive() {
if (exitImmersiveRequested && externalVR->IsPresenting()) {
externalVR->StopPresenting();
blitter->StopPresenting();
exitImmersiveRequested = false;
return true;
}
return false;
}
static bool
OutOfDeadZone(Controller& aController, const float aX, const float aY) {
if (!aController.inDeadZone) {
return true;
}
const float kDeadZone = 20.0f;
const float xDistance = aX - aController.pointerX;
const float yDistance = aY - aController.pointerY;
aController.inDeadZone = sqrtf((xDistance * xDistance) + (yDistance * yDistance)) < kDeadZone;
// VRB_ERROR("Out of DEAD ZONE[%f]: %s", sqrtf((xDistance * xDistance) + (yDistance * yDistance)), (!aController.inDeadZone ? "TRUE" : "FALSE"));
return !aController.inDeadZone;
}
static bool
ThrottleHoverEvent(Controller& aController, const double aTimestamp, const bool aIsPressed, const bool aWasPressed) {
if (aIsPressed || aWasPressed) {
return false;
}
if ((aTimestamp - aController.lastHoverEvent) < kHoverRate) {
return true;
}
aController.lastHoverEvent = aTimestamp;
return false;
}
void
BrowserWorld::State::EnsureControllerFocused() {
Controller* right = nullptr;
Controller* first = nullptr;
bool focused = false;
for (Controller& controller: controllers->GetControllers()) {
focused = controller.focused;
if (focused) {
break;
}
if (!controller.leftHanded && controller.enabled) {
right = &controller;
}
if (!first && controller.enabled) {
first = &controller;
}
}
if (!focused) {
if (right) {
ChangeControllerFocus(*right);
} else if (first) {
ChangeControllerFocus(*first);
}
}
}
void
BrowserWorld::State::ChangeControllerFocus(const Controller& aController) {
for (Controller& controller: controllers->GetControllers()) {
controller.focused = (&controller == &aController);
if (controller.pointer) {
controller.pointer->SetVisible(controller.focused);
}
if (controller.beamToggle) {
controller.beamToggle->ToggleAll(controller.focused);
}
}
}
static inline float
ScaleScrollDelta(const float aValue, const double aStartTime, const double aCurrentTime) {
const float kMaxDelta = 2.0f; // in seconds
const float kMinScale = 0.15f;
const double deltaTime = aCurrentTime - aStartTime;
auto scale = float(deltaTime / kMaxDelta);
if (deltaTime > kMaxDelta) {
scale = 1.0f;
} else if (scale < kMinScale) {
scale = kMinScale;
}
return aValue * scale;
}
void
BrowserWorld::State::UpdateControllers(bool& aRelayoutWidgets) {
EnsureControllerFocused();
for (Controller& controller: controllers->GetControllers()) {
if (!controller.enabled || (controller.index < 0)) {
continue;
}
if (controller.pointer && !controller.pointer->IsLoaded()) {
controller.pointer->Load(device);
}
if (!(controller.lastButtonState & ControllerDelegate::BUTTON_APP) && (controller.buttonState & ControllerDelegate::BUTTON_APP)) {
VRBrowser::HandleBack();
}
if (!controller.focused) {
const bool focusRequested =
((controller.buttonState & ControllerDelegate::BUTTON_TRIGGER) && (controller.lastButtonState & ControllerDelegate::BUTTON_TRIGGER) == 0) ||
((controller.buttonState & ControllerDelegate::BUTTON_A) && (controller.lastButtonState & ControllerDelegate::BUTTON_A) == 0) ||
((controller.buttonState & ControllerDelegate::BUTTON_B) && (controller.lastButtonState & ControllerDelegate::BUTTON_B) == 0) ||
((controller.buttonState & ControllerDelegate::BUTTON_X) && (controller.lastButtonState & ControllerDelegate::BUTTON_X) == 0) ||
((controller.buttonState & ControllerDelegate::BUTTON_Y) && (controller.lastButtonState & ControllerDelegate::BUTTON_Y) == 0);
if (focusRequested) {
ChangeControllerFocus(controller);
}
controller.lastButtonState = controller.buttonState;
continue;
}
const vrb::Vector start = controller.StartPoint();
const vrb::Vector direction = controller.Direction();
WidgetPtr hitWidget;
float hitDistance = farClip;
vrb::Vector hitPoint;
vrb::Vector hitNormal;
for (const WidgetPtr& widget: widgets) {
if (resizingWidget && resizingWidget->IsResizingActive() && resizingWidget != widget) {
// Don't interact with other widgets when resizing gesture is active.
continue;
}
if (movingWidget && movingWidget->GetWidget() != widget) {
// Don't interact with other widgets when moving gesture is active.
continue;
}
vrb::Vector result;
vrb::Vector normal;
float distance = 0.0f;
bool isInWidget = false;
const bool clamp = !widget->IsResizing() && !movingWidget;
if (widget->TestControllerIntersection(start, direction, result, normal, clamp, isInWidget, distance)) {
if (isInWidget && (distance < hitDistance)) {
hitWidget = widget;
hitDistance = distance;
hitPoint = result;
hitNormal = normal;
}
}
}
if ((!hitWidget || !hitWidget->IsResizing()) && resizingWidget) {
resizingWidget->HoverExitResize();
resizingWidget.reset();
}
if (controller.pointer) {
controller.pointer->SetVisible(hitWidget.get() != nullptr);
controller.pointer->SetHitWidget(hitWidget);
if (hitWidget) {
vrb::Matrix translation = vrb::Matrix::Translation(hitPoint);
vrb::Matrix localRotation = vrb::Matrix::Rotation(hitNormal);
vrb::Matrix reorient = device->GetReorientTransform();
controller.pointer->SetTransform(reorient.AfineInverse().PostMultiply(translation).PostMultiply(localRotation));
controller.pointer->SetScale(hitPoint, device->GetHeadTransform());
}
}
const bool pressed = controller.buttonState & ControllerDelegate::BUTTON_TRIGGER ||
controller.buttonState & ControllerDelegate::BUTTON_TOUCHPAD;
const bool wasPressed = controller.lastButtonState & ControllerDelegate::BUTTON_TRIGGER ||
controller.lastButtonState & ControllerDelegate::BUTTON_TOUCHPAD;
if (movingWidget && movingWidget->IsMoving(controller.index)) {
if (!pressed && wasPressed) {
movingWidget->EndMoving();
} else {
WidgetPlacementPtr updatedPlacement = movingWidget->HandleMove(start, direction);
if (updatedPlacement) {
movingWidget->GetWidget()->SetPlacement(updatedPlacement);
aRelayoutWidgets = true;
}
}
} else if (hitWidget && hitWidget->IsResizing()) {
bool aResized = false, aResizeEnded = false;
hitWidget->HandleResize(hitPoint, pressed, aResized, aResizeEnded);
resizingWidget = hitWidget;
if (aResized) {
aRelayoutWidgets = true;
std::shared_ptr<BrowserWorld> world = self.lock();
if (world) {
world->LayoutWidget(hitWidget->GetHandle());
}
}
if (aResizeEnded) {
float width, height;
hitWidget->GetWorldSize(width, height);
VRBrowser::HandleResize(hitWidget->GetHandle(), width, height);
}
} else if (hitWidget) {
float theX = 0.0f, theY = 0.0f;
hitWidget->ConvertToWidgetCoordinates(hitPoint, theX, theY);
const uint32_t handle = hitWidget->GetHandle();
if (!pressed && wasPressed) {
controller.inDeadZone = true;
}
controller.pointerWorldPoint = hitPoint;
const bool moved = pressed ? OutOfDeadZone(controller, theX, theY)
: (controller.pointerX != theX) || (controller.pointerY != theY);
const bool throttled = ThrottleHoverEvent(controller, context->GetTimestamp(), pressed, wasPressed);
if ((!throttled && moved) || (controller.widget != handle) || (pressed != wasPressed)) {
controller.widget = handle;
controller.pointerX = theX;
controller.pointerY = theY;
VRBrowser::HandleMotionEvent(handle, controller.index, jboolean(pressed),
controller.pointerX, controller.pointerY);
}
if ((controller.scrollDeltaX != 0.0f) || controller.scrollDeltaY != 0.0f) {
if (controller.scrollStart < 0.0) {
controller.scrollStart = context->GetTimestamp();
}
const double ctime = context->GetTimestamp();
VRBrowser::HandleScrollEvent(controller.widget, controller.index,
ScaleScrollDelta(controller.scrollDeltaX, controller.scrollStart, ctime),
ScaleScrollDelta(controller.scrollDeltaY, controller.scrollStart, ctime));
controller.scrollDeltaX = 0.0f;
controller.scrollDeltaY = 0.0f;
} else {
controller.scrollStart = -1.0;
}
if (!pressed) {
if (controller.touched) {
if (!controller.wasTouched) {
controller.wasTouched = controller.touched;
} else {
VRBrowser::HandleScrollEvent(controller.widget,
controller.index,
(controller.touchX - controller.lastTouchX) * kScrollFactor,
(controller.touchY - controller.lastTouchY) * kScrollFactor);
}
controller.lastTouchX = controller.touchX;
controller.lastTouchY = controller.touchY;
} else {
controller.wasTouched = false;
controller.lastTouchX = controller.lastTouchY = 0.0f;
}
}
} else if (controller.widget) {
VRBrowser::HandleMotionEvent(0, controller.index, (jboolean) pressed, 0.0f, 0.0f);
controller.widget = 0;
} else if (wasPressed != pressed) {
VRBrowser::HandleMotionEvent(0, controller.index, (jboolean) pressed, 0.0f, 0.0f);
} else if (vrVideo != nullptr) {
const bool togglePressed = controller.buttonState & ControllerDelegate::BUTTON_X ||
controller.buttonState & ControllerDelegate::BUTTON_A;
const bool toggleWasPressed = controller.lastButtonState & ControllerDelegate::BUTTON_X ||
controller.lastButtonState & ControllerDelegate::BUTTON_A;
if (togglePressed != toggleWasPressed) {
VRBrowser::HandleMotionEvent(0, controller.index, (jboolean) togglePressed, 0.0f, 0.0f);
}
}
controller.lastButtonState = controller.buttonState;
}
if (gestures) {
const int32_t gestureCount = gestures->GetGestureCount();
for (int32_t count = 0; count < gestureCount; count++) {
const GestureType type = gestures->GetGestureType(count);
jint javaType = -1;
if (type == GestureType::SwipeLeft) {
javaType = GestureSwipeLeft;
} else if (type == GestureType::SwipeRight) {
javaType = GestureSwipeRight;
}
if (javaType >= 0) {
VRBrowser::HandleGesture(javaType);
}
}
}
}
WidgetPtr
BrowserWorld::State::GetWidget(int32_t aHandle) const {
return FindWidget([=](const WidgetPtr& aWidget){
return aWidget->GetHandle() == aHandle;
});
}
WidgetPtr
BrowserWorld::State::FindWidget(const std::function<bool(const WidgetPtr&)>& aCondition) const {
for (const WidgetPtr & widget: widgets) {
if (aCondition(widget)) {
return widget;
}
}
return {};
}
bool
BrowserWorld::State::IsParent(const Widget& aChild, const Widget& aParent) const {
if (aChild.GetPlacement()->parentHandle == aParent.GetHandle()) {
return true;
}
if (aChild.GetPlacement()->parentHandle > 0) {
WidgetPtr next = GetWidget(aChild.GetPlacement()->parentHandle);
if (next) {
return IsParent(*next, aParent);
}
}
return false;
}
int
BrowserWorld::State::ParentCount(const WidgetPtr& aWidget) const {
int result = 0;
WidgetPtr current = aWidget;
while (current && current->GetPlacement()->parentHandle > 0) {
current = GetWidget(current->GetPlacement()->parentHandle);
if (current) {
result++;
}
}
return result;
}
float
BrowserWorld::State::ComputeNormalizedZ(const Widget& aWidget) const {
const vrb::Vector headPosition = device->GetHeadTransform().GetTranslation();
const vrb::Vector headDirection = device->GetHeadTransform().MultiplyDirection(vrb::Vector(0.0f, 0.0f, -1.0f));
vrb::Vector hitPoint;
vrb::Vector normal;
bool inside = false;
float distance;
if (aWidget.GetQuad()) {
aWidget.GetQuad()->TestIntersection(headPosition, headDirection, hitPoint, normal, true, inside, distance);
} else if (aWidget.GetCylinder()) {
aWidget.GetCylinder()->TestIntersection(headPosition, headDirection, hitPoint, normal, true, inside, distance);
}
const vrb::Matrix& projection = device->GetCamera(device::Eye::Left)->GetPerspective();
const vrb::Matrix& view = device->GetCamera(device::Eye::Left)->GetView();
vrb::Matrix viewProjection = projection.PostMultiply(view);
vrb::Vector ndc = viewProjection.MultiplyPosition(hitPoint);
return ndc.z();
}
void
BrowserWorld::State::SortWidgets() {
depthSorting.clear();
// Compute normalized z for each widget
for (int i = 0; i < rootTransparent->GetNodeCount(); ++i) {
vrb::NodePtr node = rootTransparent->GetNode(i);
Widget * target = nullptr;
float zDelta = 0.0f;
for (const auto & widget: widgets) {
if (widget->GetRoot() == node) {
target = widget.get();
break;
}
}
if (!target) {
for (Controller& controller: controllers->GetControllers()) {
if (controller.pointer && controller.pointer->GetRoot() == node) {
target = controller.pointer->GetHitWidget().get();
zDelta = 0.02f;
break;
}
}
}
if (!target && widgetResizer && widgetResizer->GetRoot() == node) {
target = widgetResizer->GetWidget();
zDelta = 0.01f;
}
if (!target || !target->IsVisible()) {
depthSorting.emplace(node.get(), std::make_pair(target, 1.0f));
continue;
}
const float z = ComputeNormalizedZ(*target) - zDelta;
depthSorting.emplace(node.get(), std::make_pair(target, z));
}
// Sort nodes based on cached depth values
rootTransparent->SortNodes([=](const NodePtr& a, const NodePtr& b) {
auto da = depthSorting.find(a.get());
auto db = depthSorting.find(b.get());
Widget* wa = da->second.first;
Widget* wb = db->second.first;
// Parenting sort
if (wa && wb && wa->IsVisible() && wb->IsVisible()) {
if (IsParent(*wa, *wb)) {
return true;
} else if (IsParent(*wb, *wa)) {
return false;
}
}
// Depth sort
return da->second.second < db->second.second;
});
}
static BrowserWorldPtr sWorldInstance;
BrowserWorld&
BrowserWorld::Instance() {
if (!sWorldInstance) {
sWorldInstance = Create();
}
return *sWorldInstance;
}
void
BrowserWorld::Destroy() {
sWorldInstance = nullptr;
}
vrb::RenderContextPtr&
BrowserWorld::GetRenderContext() {
return m.context;
}
void
BrowserWorld::RegisterDeviceDelegate(DeviceDelegatePtr aDelegate) {
ASSERT_ON_RENDER_THREAD();
DeviceDelegatePtr previousDevice = std::move(m.device);
m.device = std::move(aDelegate);
if (m.device) {
m.device->RegisterImmersiveDisplay(m.externalVR);
m.device->SetClearColor(vrb::Color(0.0f, 0.0f, 0.0f, 0.0f));
m.leftCamera = m.device->GetCamera(device::Eye::Left);
m.rightCamera = m.device->GetCamera(device::Eye::Right);
ControllerDelegatePtr delegate = m.controllers;
m.device->SetClipPlanes(m.nearClip, m.farClip);
m.device->SetControllerDelegate(delegate);
m.gestures = m.device->GetGestureDelegate();
} else if (previousDevice) {
m.leftCamera = m.rightCamera = nullptr;
m.controllers->Reset();
m.gestures = nullptr;
previousDevice->ReleaseControllerDelegate();
}
}
void
BrowserWorld::Pause() {
ASSERT_ON_RENDER_THREAD();
m.paused = true;
m.monitor->Pause();
}
void
BrowserWorld::Resume() {
ASSERT_ON_RENDER_THREAD();
m.paused = false;
m.monitor->Resume();
}
bool
BrowserWorld::IsPaused() const {
ASSERT_ON_RENDER_THREAD(m.paused);
return m.paused;
}
void
BrowserWorld::InitializeJava(JNIEnv* aEnv, jobject& aActivity, jobject& aAssetManager) {
ASSERT_ON_RENDER_THREAD();
VRB_LOG("BrowserWorld::InitializeJava");
if (m.context) {
m.context->InitializeJava(aEnv, aActivity, aAssetManager);
}
m.env = aEnv;
if (!m.env) {
return;
}
m.activity = m.env->NewGlobalRef(aActivity);
if (!m.activity) {
return;
}
jclass clazz = m.env->GetObjectClass(m.activity);
if (!clazz) {
return;
}
VRBrowser::InitializeJava(m.env, m.activity);
GeckoSurfaceTexture::InitializeJava(m.env, m.activity);
m.loader->InitializeJava(aEnv, aActivity, aAssetManager);
VRBrowser::RegisterExternalContext((jlong)m.externalVR->GetSharedData());
VRBrowser::SetDeviceType(m.device->GetDeviceType());
if (!m.modelsLoaded) {
const int32_t modelCount = m.device->GetControllerModelCount();
for (int32_t index = 0; index < modelCount; index++) {
const std::string fileName = m.device->GetControllerModelName(index);
if (!fileName.empty()) {
m.controllers->LoadControllerModel(index, m.loader, fileName);
}
}
m.controllers->InitializeBeam();
m.controllers->SetPointerColor(vrb::Color(VRBrowser::GetPointerColor()));
m.loadingAnimation->LoadModels(m.loader);
m.rootController->AddNode(m.controllers->GetRoot());
#if !defined(SNAPDRAGONVR)
UpdateEnvironment();
// Don't load the env model, we are going for skyboxes in v1.0
// CreateFloor();
#endif
m.fadeAnimation->SetFadeChangeCallback([=](const vrb::Color& aTintColor) {
if (m.skybox) {
m.skybox->SetTintColor(aTintColor);
}
});
m.modelsLoaded = true;
}
SetThreadName("VRB Render");
}
void
BrowserWorld::InitializeGL() {
ASSERT_ON_RENDER_THREAD();
VRB_LOG("BrowserWorld::InitializeGL");
if (m.context) {
if (!m.glInitialized) {
m.glInitialized = m.context->InitializeGL();
VRB_GL_CHECK(glEnable(GL_BLEND));
VRB_GL_CHECK(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
VRB_GL_CHECK(glEnable(GL_DEPTH_TEST));
VRB_GL_CHECK(glEnable(GL_CULL_FACE));
if (!m.glInitialized) {
return;
}
if (m.splashAnimation) {
m.splashAnimation->Load(m.context, m.device);
}
// delay the m.loader->InitializeGL() call to fix some issues with Daydream activities
m.loaderDelay = 3;
SurfaceTextureFactoryPtr factory = m.context->GetSurfaceTextureFactory();
for (WidgetPtr& widget: m.widgets) {
const std::string name = widget->GetSurfaceTextureName();
jobject surface = factory->LookupSurfaceTexture(name);
if (surface) {
SetSurfaceTexture(name, surface);
}
}
}
}
}
void
BrowserWorld::ShutdownJava() {
ASSERT_ON_RENDER_THREAD();
VRB_LOG("BrowserWorld::ShutdownJava");
GeckoSurfaceTexture::ShutdownJava();
VRBrowser::ShutdownJava();
if (m.env) {
m.env->DeleteGlobalRef(m.activity);
}
m.activity = nullptr;
m.env = nullptr;
}
void
BrowserWorld::ShutdownGL() {
ASSERT_ON_RENDER_THREAD();
VRB_LOG("BrowserWorld::ShutdownGL");
if (!m.glInitialized) {
return;
}
if (m.loader) {
m.loader->ShutdownGL();
}
if (m.context) {
m.context->ShutdownGL();
}
m.glInitialized = false;
}
void
BrowserWorld::Draw() {
ASSERT_ON_RENDER_THREAD();
if (!m.device) {
VRB_WARN("No device");
return;
}
if (m.paused) {
VRB_LOG("BrowserWorld Paused");
return;
}
if (!m.glInitialized) {
m.glInitialized = m.context->InitializeGL();
if (!m.glInitialized) {
VRB_LOG("Failed to initialize GL");
return;
}
}
if (m.loaderDelay > 0) {
m.loaderDelay--;
if (m.loaderDelay == 0) {
m.loader->InitializeGL();
}
}
m.device->ProcessEvents();
m.context->Update();
m.externalVR->PullBrowserState();
m.externalVR->SetHapticState(m.controllers);
m.CheckExitImmersive();
if (m.splashAnimation) {
DrawSplashAnimation();
} else if (m.externalVR->IsPresenting()) {
m.CheckBackButton();
DrawImmersive();
} else {
bool relayoutWidgets = false;
m.UpdateControllers(relayoutWidgets);
if (relayoutWidgets) {
UpdateVisibleWidgets();
}
DrawWorld();
m.externalVR->PushSystemState();
}
// Update the 3d audio engine with the most recent head rotation.
const vrb::Matrix &head = m.device->GetHeadTransform();
const vrb::Vector p = head.GetTranslation();
const vrb::Quaternion q(head);
VRBrowser::HandleAudioPose(q.x(), q.y(), q.z(), q.w(), p.x(), p.y(), p.z());
}
void
BrowserWorld::SetTemporaryFilePath(const std::string& aPath) {
ASSERT_ON_RENDER_THREAD();
VRB_LOG("Got temp path: %s", aPath.c_str());
m.context->GetDataCache()->SetCachePath(aPath);
}
void
BrowserWorld::UpdateEnvironment() {
ASSERT_ON_RENDER_THREAD();
std::string skyboxPath = VRBrowser::GetActiveEnvironment();
std::string extension;
if (VRBrowser::isOverrideEnvPathEnabled()) {
std::string storagePath = VRBrowser::GetStorageAbsolutePath(INJECT_SKYBOX_PATH);
if (std::ifstream(storagePath)) {
skyboxPath = storagePath;
extension = Skybox::ValidateCustomSkyboxAndFindFileExtension(storagePath);
if (!extension.empty()) {
skyboxPath = storagePath;
VRB_DEBUG("Found custom skybox file extension: %s", extension.c_str());
} else {
VRB_ERROR("Failed to find custom skybox files.");
}
} else {
VRB_ERROR("Failed to find override skybox storage path %s", storagePath.c_str());
}
}
VRB_LOG("Setting environment: %s", skyboxPath.c_str());
CreateSkyBox(skyboxPath, extension);
}
void
BrowserWorld::UpdateFoveatedLevel(const int aAppLevel) {
ASSERT_ON_RENDER_THREAD();
m.device->SetFoveatedLevel(aAppLevel);
}
void
BrowserWorld::UpdatePointerColor() {
ASSERT_ON_RENDER_THREAD();
int32_t color = VRBrowser::GetPointerColor();
VRB_LOG("Setting pointer color to: %d:", color);
if (m.controllers) {
m.controllers->SetPointerColor(vrb::Color(color));
}
}
void
BrowserWorld::SetSurfaceTexture(const std::string& aName, jobject& aSurface) {
ASSERT_ON_RENDER_THREAD();
VRB_LOG("SetSurfaceTexture: %s", aName.c_str());
WidgetPtr widget = m.FindWidget([=](const WidgetPtr& aWidget) -> bool {
return aName == aWidget->GetSurfaceTextureName();
});
if (widget) {
int32_t width = 0, height = 0;
widget->GetSurfaceTextureSize(width, height);
VRBrowser::DispatchCreateWidget(widget->GetHandle(), aSurface, width, height);
}
}
void
BrowserWorld::AddWidget(int32_t aHandle, const WidgetPlacementPtr& aPlacement) {
ASSERT_ON_RENDER_THREAD();
if (m.GetWidget(aHandle)) {
VRB_LOG("Widget with handle %d already added, updating it.", aHandle);
UpdateWidget(aHandle, aPlacement);
return;
}
float worldWidth = aPlacement->worldWidth;
if (worldWidth <= 0.0f) {
worldWidth = aPlacement->width * WidgetPlacement::kWorldDPIRatio;
}
const int32_t textureWidth = aPlacement->GetTextureWidth();
const int32_t textureHeight = aPlacement->GetTextureHeight();
const float aspect = (float)textureWidth / (float)textureHeight;
const float worldHeight = worldWidth / aspect;
WidgetPtr widget;
if (aPlacement->cylinder && m.cylinderDensity > 0) {
VRLayerCylinderPtr layer = m.device->CreateLayerCylinder(textureWidth, textureHeight, VRLayerQuad::SurfaceType::AndroidSurface);
CylinderPtr cylinder = Cylinder::Create(m.create, layer);
widget = Widget::Create(m.context, aHandle, aPlacement, textureWidth, textureHeight, (int32_t)worldWidth, (int32_t)worldHeight, cylinder);
}
if (!widget) {
VRLayerQuadPtr layer;
if (aPlacement->layer) {
layer = m.device->CreateLayerQuad(textureWidth, textureHeight, VRLayerQuad::SurfaceType::AndroidSurface);
}
QuadPtr quad = Quad::Create(m.create, worldWidth, worldHeight, layer);
widget = Widget::Create(m.context, aHandle, aPlacement, textureWidth, textureHeight, quad);
}
if (aPlacement->opaque) {
m.rootOpaque->AddNode(widget->GetRoot());
} else {