VRButton.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. /**
  2. * A utility class for creating a button that allows to initiate
  3. * immersive VR sessions based on WebXR. The button can be created
  4. * with a factory method and then appended ot the website's DOM.
  5. *
  6. * ```js
  7. * document.body.appendChild( VRButton.createButton( renderer ) );
  8. * ```
  9. *
  10. * @hideconstructor
  11. */
  12. class VRButton {
  13. /**
  14. * Constructs a new VR button.
  15. *
  16. * @param {WebGLRenderer|WebGPURenderer} renderer - The renderer.
  17. * @param {XRSessionInit} [sessionInit] - The a configuration object for the AR session.
  18. * @return {HTMLElement} The button or an error message if `immersive-ar` isn't supported.
  19. */
  20. static createButton( renderer, sessionInit = {} ) {
  21. const button = document.createElement( 'button' );
  22. function showEnterVR( /*device*/ ) {
  23. let currentSession = null;
  24. async function onSessionStarted( session ) {
  25. session.addEventListener( 'end', onSessionEnded );
  26. await renderer.xr.setSession( session );
  27. button.textContent = 'EXIT VR';
  28. currentSession = session;
  29. }
  30. function onSessionEnded( /*event*/ ) {
  31. currentSession.removeEventListener( 'end', onSessionEnded );
  32. button.textContent = 'ENTER VR';
  33. currentSession = null;
  34. }
  35. //
  36. button.style.display = '';
  37. button.style.cursor = 'pointer';
  38. button.style.left = 'calc(50% - 50px)';
  39. button.style.width = '100px';
  40. button.textContent = 'ENTER VR';
  41. // WebXR's requestReferenceSpace only works if the corresponding feature
  42. // was requested at session creation time. For simplicity, just ask for
  43. // the interesting ones as optional features, but be aware that the
  44. // requestReferenceSpace call will fail if it turns out to be unavailable.
  45. // ('local' is always available for immersive sessions and doesn't need to
  46. // be requested separately.)
  47. const sessionOptions = {
  48. ...sessionInit,
  49. optionalFeatures: [
  50. 'local-floor',
  51. 'bounded-floor',
  52. 'layers',
  53. ...( sessionInit.optionalFeatures || [] )
  54. ],
  55. };
  56. button.onmouseenter = function () {
  57. button.style.opacity = '1.0';
  58. };
  59. button.onmouseleave = function () {
  60. button.style.opacity = '0.5';
  61. };
  62. button.onclick = function () {
  63. if ( currentSession === null ) {
  64. navigator.xr.requestSession( 'immersive-vr', sessionOptions ).then( onSessionStarted );
  65. } else {
  66. currentSession.end();
  67. if ( navigator.xr.offerSession !== undefined ) {
  68. navigator.xr.offerSession( 'immersive-vr', sessionOptions )
  69. .then( onSessionStarted )
  70. .catch( ( err ) => {
  71. console.warn( err );
  72. } );
  73. }
  74. }
  75. };
  76. if ( navigator.xr.offerSession !== undefined ) {
  77. navigator.xr.offerSession( 'immersive-vr', sessionOptions )
  78. .then( onSessionStarted )
  79. .catch( ( err ) => {
  80. console.warn( err );
  81. } );
  82. }
  83. }
  84. function disableButton() {
  85. button.style.display = '';
  86. button.style.cursor = 'auto';
  87. button.style.left = 'calc(50% - 75px)';
  88. button.style.width = '150px';
  89. button.onmouseenter = null;
  90. button.onmouseleave = null;
  91. button.onclick = null;
  92. }
  93. function showWebXRNotFound() {
  94. disableButton();
  95. button.textContent = 'VR NOT SUPPORTED';
  96. }
  97. function showVRNotAllowed( exception ) {
  98. disableButton();
  99. console.warn( 'Exception when trying to call xr.isSessionSupported', exception );
  100. button.textContent = 'VR NOT ALLOWED';
  101. }
  102. function stylizeElement( element ) {
  103. element.style.position = 'absolute';
  104. element.style.bottom = '20px';
  105. element.style.padding = '12px 6px';
  106. element.style.border = '1px solid #fff';
  107. element.style.borderRadius = '4px';
  108. element.style.background = 'rgba(0,0,0,0.1)';
  109. element.style.color = '#fff';
  110. element.style.font = 'normal 13px sans-serif';
  111. element.style.textAlign = 'center';
  112. element.style.opacity = '0.5';
  113. element.style.outline = 'none';
  114. element.style.zIndex = '999';
  115. }
  116. if ( 'xr' in navigator ) {
  117. button.id = 'VRButton';
  118. button.style.display = 'none';
  119. stylizeElement( button );
  120. navigator.xr.isSessionSupported( 'immersive-vr' ).then( function ( supported ) {
  121. supported ? showEnterVR() : showWebXRNotFound();
  122. if ( supported && VRButton.xrSessionIsGranted ) {
  123. button.click();
  124. }
  125. } ).catch( showVRNotAllowed );
  126. return button;
  127. } else {
  128. const message = document.createElement( 'a' );
  129. if ( window.isSecureContext === false ) {
  130. message.href = document.location.href.replace( /^http:/, 'https:' );
  131. message.innerHTML = 'WEBXR NEEDS HTTPS'; // TODO Improve message
  132. } else {
  133. message.href = 'https://immersiveweb.dev/';
  134. message.innerHTML = 'WEBXR NOT AVAILABLE';
  135. }
  136. message.style.left = 'calc(50% - 90px)';
  137. message.style.width = '180px';
  138. message.style.textDecoration = 'none';
  139. stylizeElement( message );
  140. return message;
  141. }
  142. }
  143. /**
  144. * Registers a `sessiongranted` event listener. When a session is granted, the {@link VRButton#xrSessionIsGranted}
  145. * flag will evaluate to `true`. This method is automatically called by the module itself so there
  146. * should be no need to use it on app level.
  147. */
  148. static registerSessionGrantedListener() {
  149. if ( typeof navigator !== 'undefined' && 'xr' in navigator ) {
  150. // WebXRViewer (based on Firefox) has a bug where addEventListener
  151. // throws a silent exception and aborts execution entirely.
  152. if ( /WebXRViewer\//i.test( navigator.userAgent ) ) return;
  153. navigator.xr.addEventListener( 'sessiongranted', () => {
  154. VRButton.xrSessionIsGranted = true;
  155. } );
  156. }
  157. }
  158. }
  159. /**
  160. * Whether a XR session has been granted or not.
  161. *
  162. * @static
  163. * @type {boolean}
  164. * @default false
  165. */
  166. VRButton.xrSessionIsGranted = false;
  167. VRButton.registerSessionGrantedListener();
  168. export { VRButton };
粤ICP备19079148号