Debian Codegraph @

3rdparty/osgXR/src/XRState.h

raw symbols SCIP
1 // SPDX-License-Identifier: LGPL-2.1-only
2 // Copyright (C) 2021 James Hogan <[email protected]>
3
4 #ifndef OSGXR_XRSTATE
5 #define OSGXR_XRSTATE 1
6
7 #include "OpenXR/ActionSet.h"
8 #include "OpenXR/EventHandler.h"
9 #include "OpenXR/Instance.h"
10 #include "OpenXR/InteractionProfile.h"
11 #include "OpenXR/System.h"
12 #include "OpenXR/Session.h"
13 #include "OpenXR/SwapchainGroup.h"
14 #include "OpenXR/SwapchainGroupSubImage.h"
15 #include "OpenXR/Compositor.h"
16 #include "OpenXR/DepthInfo.h"
17
18 #include "XRFramebuffer.h"
19 #include "FrameStampedVector.h"
20 #include "FrameStore.h"
21
22 #include <osg/DisplaySettings>
23 #include <osg/Referenced>
24 #include <osg/observer_ptr>
25 #include <osg/ref_ptr>
26
27 #include <osgXR/ActionSet>
28 #include <osgXR/CompositionLayer>
29 #include <osgXR/InteractionProfile>
30 #include <osgXR/Settings>
31 #include <osgXR/Subaction>
32 #include <osgXR/View>
33
34 #include <list>
35 #include <memory>
36 #include <vector>
37
38 namespace osg {
39 class FrameStamp;
40 }
41
42 namespace osgViewer {
43 class ViewerBase;
44 }
45
46 namespace osgXR {
47
48 class Manager;
49
50 class XRState : public OpenXR::EventHandler
51 {
52 public:
53 typedef Settings::VRMode VRMode;
54 typedef Settings::SwapchainMode SwapchainMode;
55
56 XRState(Settings *settings, Manager *manager = nullptr);
57
58 /// Represents a swapchain group
59 class XRSwapchain : public OpenXR::SwapchainGroup
60 {
61 public:
62
63 XRSwapchain(XRState *state,
64 osg::ref_ptr<OpenXR::Session> session,
65 const OpenXR::System::ViewConfiguration::View &view,
66 int64_t chosenRGBAFormat,
67 int64_t chosenDepthFormat,
68 GLenum fallbackDepthFormat);
69
70 // GL context must be current (for XRFramebuffer)
71 virtual ~XRSwapchain();
72
73 void setForcedAlpha(float alpha = -1.0f)
74 {
75 _forcedAlpha = alpha;
76 }
77
78 void incNumDrawPasses(unsigned int num = 1)
79 {
80 _numDrawPasses += num;
81 }
82
83 void decNumDrawPasses(unsigned int num = 1)
84 {
85 _numDrawPasses -= num;
86 }
87
88 unsigned int getNumDrawPasses()
89 {
90 return _numDrawPasses;
91 }
92
93 void setupImage(const osg::FrameStamp *stamp);
94
95 void preDrawCallback(osg::RenderInfo &renderInfo);
96 void postDrawCallback(osg::RenderInfo &renderInfo);
97 void endFrame();
98
99 osg::ref_ptr<osg::Texture2D> getOsgTexture(const osg::FrameStamp *stamp);
100
101 protected:
102
103 XRState *_state;
104 FrameStampedVector<osg::ref_ptr<XRFramebuffer> > _imageFramebuffers;
105
106 float _forcedAlpha;
107
108 /// Number of expected draw passes.
109 unsigned int _numDrawPasses;
110 unsigned int _drawPassesDone;
111 bool _imagesReady;
112 };
113
114 /// Represents an OpenXR view
115 class XRView : public osg::Referenced
116 {
117 public:
118
119 XRView(XRState *state,
120 uint32_t viewIndex,
121 osg::ref_ptr<XRSwapchain> swapchain);
122 XRView(XRState *state,
123 uint32_t viewIndex,
124 osg::ref_ptr<XRSwapchain> swapchain,
125 const OpenXR::System::ViewConfiguration::View::Viewport &viewport);
126
127 // GL context must be current (for XRFramebuffer)
128 virtual ~XRView();
129
130 bool valid() const
131 {
132 return _swapchainSubImage.valid();
133 }
134
135 osg::ref_ptr<XRSwapchain> getSwapchain()
136 {
137 return static_cast<XRSwapchain *>(_swapchainSubImage.getSwapchainGroup().get());
138 }
139
140 const XRSwapchain::SubImage &getSubImage() const
141 {
142 return _swapchainSubImage;
143 }
144
145 void setupCamera(osg::ref_ptr<osg::Camera> camera);
146
147 void endFrame(OpenXR::Session::Frame *frame);
148
149 protected:
150
151 XRState *_state;
152 XRSwapchain::SubImage _swapchainSubImage;
153
154 uint32_t _viewIndex;
155 };
156
157 /** Represents a generic app level view.
158 * This may handle multiple OpenXR views.
159 */
160 class AppView : public View
161 {
162 public:
163
164 AppView(XRState *state,
165 osgViewer::GraphicsWindow *window,
166 osgViewer::View *osgView);
167 virtual ~AppView();
168
169 void destroy();
170
171 void init();
172
173 protected:
174
175 bool _valid;
176
177 XRState *_state;
178 };
179
180 /// Represents an app level view in slave cams mode
181 class SlaveCamsAppView : public AppView
182 {
183 public:
184
185 SlaveCamsAppView(XRState *state,
186 uint32_t viewIndex,
187 osgViewer::GraphicsWindow *window,
188 osgViewer::View *osgView);
189
190 void addSlave(osg::Camera *slaveCamera) override;
191 void removeSlave(osg::Camera *slaveCamera) override;
192
193 protected:
194
195 uint32_t _viewIndex;
196 };
197
198 /// Represents an app level view in scene view mode
199 class SceneViewAppView : public AppView
200 {
201 public:
202
203 SceneViewAppView(XRState *state,
204 osgViewer::GraphicsWindow *window,
205 osgViewer::View *osgView);
206
207 void addSlave(osg::Camera *slaveCamera) override;
208 void removeSlave(osg::Camera *slaveCamera) override;
209 };
210
211 bool hasValidationLayer() const;
212 bool hasDepthInfoExtension() const;
213 bool hasVisibilityMaskExtension() const;
214
215 inline const char *getRuntimeName() const
216 {
217 if (_currentState < VRSTATE_INSTANCE)
218 return "";
219 return _instance->getRuntimeName();
220 }
221
222 inline const char *getSystemName() const
223 {
224 if (_currentState < VRSTATE_SYSTEM)
225 return "";
226 return _system->getSystemName();
227 }
228
229 inline bool getPresent() const
230 {
231 return _instance.valid() && _instance->valid();
232 }
233
234 inline bool valid() const
235 {
236 return _currentState >= VRSTATE_SESSION;
237 }
238
239 typedef enum {
240 /// No OpenXR instance.
241 VRSTATE_DISABLED = 0,
242 /// OpenXR instance created.
243 VRSTATE_INSTANCE,
244 /// Valid OpenXR system found.
245 VRSTATE_SYSTEM,
246 /// Session created
247 VRSTATE_SESSION,
248 /// Actions configured
249 VRSTATE_ACTIONS,
250
251 VRSTATE_MAX,
252 } VRState;
253
254 /// Set the init state to drop down to before returning to prior level.
255 void setDownState(VRState downState)
256 {
257 if (downState < _downState && downState < _currentState)
258 {
259 _downState = downState;
260 _stateChanged = true;
261 }
262 }
263 /// Get the current init state to rise up to.
264 VRState getUpState() const
265 {
266 return _upState;
267 }
268 /// Get the current init state to rise up to.
269 VRState getCurrentState() const
270 {
271 return _currentState;
272 }
273 /// Set the init state to rise up to.
274 void setUpState(VRState upState)
275 {
276 if (upState != _upState)
277 {
278 _upState = upState;
279 _stateChanged = true;
280 }
281 }
282 /// Set the minimum init state to rise up to.
283 void setMinUpState(VRState minUpState)
284 {
285 if (minUpState > _upState)
286 {
287 _upState = minUpState;
288 _stateChanged = true;
289 }
290 }
291 /// Set destination state, both up and down.
292 void setDestState(VRState destState)
293 {
294 setDownState(destState);
295 setUpState(destState);
296 }
297 /// Find if updates are needed for state changes.
298 bool isStateUpdateNeeded() const
299 {
300 return _currentState > _downState || _currentState < _upState;
301 }
302
303 /// Find if a VR session is running.
304 bool isRunning() const
305 {
306 if (_currentState < VRSTATE_SESSION)
307 return false;
308 return _session->isRunning() && !_session->isLost();
309 }
310
311 /// Set whether probing should be active.
312 void setProbing(bool probing)
313 {
314 if (_probing == probing)
315 return;
316 _probing = probing;
317 if (probing)
318 {
319 // Init at least up to system
320 setMinUpState(VRSTATE_SYSTEM);
321 }
322 else
323 {
324 // If only initing to system, shutdown
325 if (_upState <= VRSTATE_SYSTEM)
326 setDestState(VRSTATE_DISABLED);
327 }
328 }
329
330 VRState getProbingState() const
331 {
332 if (_instance.valid() && _instance->getQuirk(OpenXR::QUIRK_AVOID_DESTROY_INSTANCE))
333 return _probing ? VRSTATE_SYSTEM : VRSTATE_DISABLED;
334 return VRSTATE_DISABLED;
335 }
336
337 void setViewer(osgViewer::ViewerBase *viewer)
338 {
339 _viewer = viewer;
340 }
341
342 /// Set the NodeMasks to use for visibility masks.
343 void setVisibilityMaskNodeMasks(osg::Node::NodeMask left,
344 osg::Node::NodeMask right)
345 {
346 _visibilityMaskLeft = left;
347 _visibilityMaskRight = right;
348 }
349
350 /// Get the subaction object for a subaction path string.
351 std::shared_ptr<Subaction::Private> getSubaction(const std::string &path);
352
353 /// Add an action set
354 void addActionSet(ActionSet::Private *actionSet)
355 {
356 _actionSets.insert(actionSet);
357 _actionsUpdated = true;
358 }
359
360 /// Remove an action set
361 void removeActionSet(ActionSet::Private *actionSet)
362 {
363 _actionSets.erase(actionSet);
364 _actionsUpdated = true;
365 }
366
367 /// Add an interaction profile
368 void addInteractionProfile(InteractionProfile::Private *interactionProfile)
369 {
370 _interactionProfiles.insert(interactionProfile);
371 _actionsUpdated = true;
372 }
373
374 /// Remove an interaction profile
375 void removeInteractionProfile(InteractionProfile::Private *interactionProfile)
376 {
377 _interactionProfiles.erase(interactionProfile);
378 _actionsUpdated = true;
379 }
380
381 /// Get the current interaction profile for the given subaction path.
382 InteractionProfile *getCurrentInteractionProfile(const OpenXR::Path &subactionPath) const;
383
384 /// Get a string describing the state (for user consumption).
385 const char *getStateString() const;
386
387 // Initialize information required for setting up VR
388 void init(osgViewer::GraphicsWindow *window,
389 osgViewer::View *view = nullptr)
390 {
391 _window = window;
392 _view = view;
393 }
394
395 /// Update down state depending on any changed settings.
396 void syncSettings();
397
398 /// Find whether actions have been updated.
399 bool getActionsUpdated() const;
400
401 /// Arrange reinit as needed of action setup.
402 void syncActionSetup();
403
404 /// Add a composition layer
405 void addCompositionLayer(CompositionLayer::Private *layer);
406
407 /// Remove a composition layer
408 void removeCompositionLayer(CompositionLayer::Private *layer);
409
410 /// Find whether state has changed since last call, and reset.
411 bool checkAndResetStateChanged();
412
413 /// Perform a regular update.
414 void update();
415
416 // Extending OpenXR::EventManager
417 void onInstanceLossPending(OpenXR::Instance *instance,
418 const XrEventDataInstanceLossPending *event) override;
419 void onInteractionProfileChanged(OpenXR::Session *session,
420 const XrEventDataInteractionProfileChanged *event) override;
421 void onSessionStateChanged(OpenXR::Session *session,
422 const XrEventDataSessionStateChanged *event) override;
423 void onSessionStateStart(OpenXR::Session *session) override;
424 void onSessionStateEnd(OpenXR::Session *session, bool retry) override;
425 void onSessionStateReady(OpenXR::Session *session) override;
426 void onSessionStateStopping(OpenXR::Session *session, bool loss) override;
427 void onSessionStateFocus(OpenXR::Session *session) override;
428 void onSessionStateUnfocus(OpenXR::Session *session) override;
429
430 osg::ref_ptr<OpenXR::Session::Frame> getFrame(osg::FrameStamp *stamp);
431 void startRendering(osg::FrameStamp *stamp);
432 void endFrame(osg::FrameStamp *stamp);
433
434 void updateSlave(uint32_t viewIndex, osg::View& view,
435 osg::View::Slave& slave);
436 void updateVisibilityMaskTransform(osg::Camera *camera,
437 osg::MatrixTransform *transform);
438
439 osg::Matrixd getEyeProjection(osg::FrameStamp *stamp,
440 uint32_t viewIndex,
441 const osg::Matrixd& projection);
442 osg::Matrixd getEyeView(osg::FrameStamp *stamp, uint32_t viewIndex,
443 const osg::Matrixd& view);
444
445 void initialDrawCallback(osg::RenderInfo &renderInfo);
446 void releaseGLObjects(osg::State *state);
447 void swapBuffersImplementation(osg::GraphicsContext* gc);
448
449 inline osg::ref_ptr<OpenXR::CompositionLayerProjection> getProjectionLayer()
450 {
451 return _projectionLayer;
452 }
453
454 class TextureRect
455 {
456 public:
457
458 float x, y;
459 float width, height;
460
461 TextureRect(const OpenXR::SwapchainGroup::SubImage &subImage)
462 {
463 float w = subImage.getSwapchainGroup()->getWidth();
464 float h = subImage.getSwapchainGroup()->getHeight();
465 x = (float)subImage.getX() / w;
466 y = (float)subImage.getY() / h;
467 width = (float)subImage.getWidth() / w;
468 height = (float)subImage.getHeight() / h;
469 }
470 };
471
472 unsigned int getViewCount() const
473 {
474 return _xrViews.size();
475 }
476
477 TextureRect getViewTextureRect(unsigned int viewIndex) const
478 {
479 return TextureRect(_xrViews[viewIndex]->getSubImage());
480 }
481
482 // Caller must validate viewIndex using getViewCount()
483 osg::ref_ptr<osg::Texture2D> getViewTexture(unsigned int viewIndex,
484 const osg::FrameStamp *stamp) const
485 {
486 return _xrViews[viewIndex]->getSwapchain()->getOsgTexture(stamp);
487 }
488
489 /**
490 * Choose an RGBA swapchain format.
491 * @param bestRGBBits Desired number of combined RGB bits.
492 * @param bestAlphaBits Desired number of alpha bits.
493 * @param preferredRGBEncodingMask Mask of preferred RGB encodings (see
494 * Settings::Encoding).
495 * @param allowedRGBEncodingMask Mask of allowed RGB encodings (see
496 * Settings::Encoding).
497 * @return The chosen OpenGL swapchain format.
498 */
499 int64_t chooseRGBAFormat(unsigned int bestRGBBits,
500 unsigned int bestAlphaBits,
501 uint32_t preferredRGBEncodingMask,
502 uint32_t allowedRGBEncodingMask) const;
503 /**
504 * Choose a fallback depth / stencil format for use if the OpenXR
505 * runtime doesn't support depth swapchains.
506 * @param bestDepthBits Desired number of depth bits.
507 * @param bestStencilBits Desired number of stencil bits.
508 * @param preferredDepthEncodingMask Mask of preferred depth encodings
509 * (see Settings::Encoding).
510 * @param allowedDepthEncodingMask Mask of allowed depth encodings
511 * (see Settings::Encoding).
512 * @return The chosen fallback OpenGL depth / stencil format.
513 */
514 GLenum chooseFallbackDepthFormat(unsigned int bestDepthBits,
515 unsigned int bestStencilBits,
516 uint32_t preferredDepthEncodingMask,
517 uint32_t allowedDepthEncodingMask) const;
518 /**
519 * Choose a depth / stencil swapchain format for submission to OpenXR.
520 * @param bestDepthBits Desired number of depth bits.
521 * @param bestStencilBits Desired number of stencil bits.
522 * @param preferredDepthEncodingMask Mask of preferred depth encodings
523 * (see Settings::Encoding).
524 * @param allowedDepthEncodingMask Mask of allowed depth encodings
525 * (see Settings::Encoding).
526 * @return The chosen OpenGL depth / stencil swapchain format.
527 */
528 int64_t chooseDepthFormat(unsigned int bestDepthBits,
529 unsigned int bestStencilBits,
530 uint32_t preferredDepthEncodingMask,
531 uint32_t allowedDepthEncodingMask) const;
532
533 protected:
534
535 typedef enum {
536 /// Successfully completed operation.
537 UP_SUCCESS,
538 /// Operation not possible at the moment, try again soon.
539 UP_SOON,
540 /// Operation not possible at the moment, try again later.
541 UP_LATER,
542 /// Operation permanently failed, disable VR.
543 UP_ABORT,
544 } UpResult;
545
546 typedef enum {
547 /// Successfully completed operation.
548 DOWN_SUCCESS,
549 /// Operation not possible at the moment, try again soon.
550 DOWN_SOON,
551 } DownResult;
552
553 // Pre-instance probing
554 void probe() const;
555 void unprobe() const;
556
557 // These are called during update to raise or lower VR state level
558 UpResult upInstance();
559 DownResult downInstance();
560 UpResult upSystem();
561 DownResult downSystem();
562 UpResult upSession();
563 DownResult downSession();
564 UpResult upActions();
565 DownResult downActions();
566
567 // Drop the _session and check it gets cleaned up
568 bool dropSessionCheck();
569
570 // Set up a single swapchain containing multiple viewports
571 bool setupSingleSwapchain(int64_t format, int64_t depthFormat = 0,
572 GLenum fallbackDepthFormat = 0);
573 // Set up a swapchain for each view
574 bool setupMultipleSwapchains(int64_t format, int64_t depthFormat = 0,
575 GLenum fallbackDepthFormat = 0);
576 // Set up slave cameras
577 void setupSlaveCameras();
578 // Set up SceneView VR mode cameras
579 void setupSceneViewCameras();
580 void setupSceneViewCamera(osg::Camera *camera);
581 // Visibility mask setup
582 inline bool needsVisibilityMask(osg::Camera *camera)
583 {
584 return _useVisibilityMask &&
585 (camera->getClearMask() & GL_DEPTH_BUFFER_BIT);
586 }
587 void setupSceneViewVisibilityMasks(osg::Camera *camera,
588 osg::ref_ptr<osg::MatrixTransform> &transform);
589 osg::ref_ptr<osg::Geode> setupVisibilityMask(osg::Camera *camera,
590 uint32_t viewIndex,
591 osg::ref_ptr<osg::MatrixTransform> &transform);
592
593 osg::ref_ptr<Settings> _settings;
594 Settings _settingsCopy;
595 osg::observer_ptr<Manager> _manager;
596
597 // app configuration
598 osg::Node::NodeMask _visibilityMaskLeft;
599 osg::Node::NodeMask _visibilityMaskRight;
600
601 // Actions
602 bool _actionsUpdated;
603 std::set<ActionSet::Private *> _actionSets;
604 std::set<InteractionProfile::Private *> _interactionProfiles;
605 std::map<std::string, std::weak_ptr<Subaction::Private>> _subactions;
606
607 // Composition layers
608 bool _compositionLayersUpdated;
609 std::list<CompositionLayer::Private *> _compositionLayers;
610
611 /// Current state of OpenXR initialization.
612 VRState _currentState;
613 /// State of OpenXR initialisation to drop down to.
614 VRState _downState;
615 /// State of OpenXR initialisation to rise up to.
616 VRState _upState;
617 /// Number of attempts made to rise VR state.
618 unsigned int _upDelay;
619 /// Whether probing should be kept active.
620 bool _probing;
621 /// Last read state as a user readable string.
622 mutable std::string _stateString;
623 /// Whether state has changed since the last update.
624 bool _stateChanged;
625
626 // Session setup
627 osg::observer_ptr<osgViewer::ViewerBase> _viewer;
628 osg::observer_ptr<osgViewer::GraphicsWindow> _window;
629 osg::observer_ptr<osgViewer::View> _view;
630
631 // Pre-Instance related
632 mutable bool _probed;
633 mutable bool _hasValidationLayer;
634 mutable bool _hasDepthInfoExtension;
635 mutable bool _hasVisibilityMaskExtension;
636
637 // Instance related
638 osg::ref_ptr<OpenXR::Instance> _instance;
639 bool _useDepthInfo;
640 bool _useVisibilityMask;
641 OpenXR::Instance::Result _lastError;
642 OpenXR::Instance::Result _lastRunError;
643
644 // System related
645 XrFormFactor _formFactor;
646 OpenXR::System *_system;
647 const OpenXR::System::ViewConfiguration *_chosenViewConfig;
648 XrEnvironmentBlendMode _chosenEnvBlendMode;
649
650 // Session related
651 VRMode _vrMode;
652 SwapchainMode _swapchainMode;
653 osg::ref_ptr<OpenXR::Session> _session;
654 std::vector<osg::ref_ptr<XRView> > _xrViews;
655 std::vector<osg::ref_ptr<AppView> > _appViews;
656 FrameStore _frames;
657 osg::ref_ptr<OpenXR::CompositionLayerProjection> _projectionLayer;
658 OpenXR::DepthInfo _depthInfo;
659 osg::ref_ptr<osg::DisplaySettings> _stereoDisplaySettings;
660 };
661
662 } // osgXR
663
664 #endif