Viewport.VR.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import * as THREE from '../../build/three.module.js';
  2. import { HTMLMesh } from './libs/three.html.js';
  3. import { XRControllerModelFactory } from '../../examples/jsm/webxr/XRControllerModelFactory.js';
  4. class VR {
  5. constructor( editor ) {
  6. const signals = editor.signals;
  7. let group = null;
  8. let renderer = null;
  9. this.currentSession = null;
  10. const onSessionStarted = async ( session ) => {
  11. if ( group === null ) {
  12. group = new THREE.Group();
  13. editor.sceneHelpers.add( group );
  14. const mesh = new HTMLMesh( document.getElementById( 'sidebar' ) );
  15. mesh.position.set( 1, 1.5, 0 );
  16. mesh.rotation.y = - 0.5;
  17. group.add( mesh );
  18. //
  19. const controllerModelFactory = new XRControllerModelFactory();
  20. const controllerGrip1 = renderer.xr.getControllerGrip( 0 );
  21. controllerGrip1.add( controllerModelFactory.createControllerModel( controllerGrip1 ) );
  22. group.add( controllerGrip1 );
  23. const controllerGrip2 = renderer.xr.getControllerGrip( 1 );
  24. controllerGrip2.add( controllerModelFactory.createControllerModel( controllerGrip2 ) );
  25. group.add( controllerGrip2 );
  26. }
  27. group.visible = true;
  28. this.currentSession = session;
  29. this.currentSession.addEventListener( 'end', onSessionEnded );
  30. await renderer.xr.setSession( this.currentSession );
  31. }
  32. const onSessionEnded = async () => {
  33. group.visible = false;
  34. this.currentSession.removeEventListener( 'end', onSessionEnded );
  35. this.currentSession = null;
  36. await renderer.xr.setSession( null );
  37. signals.exitedVR.dispatch();
  38. };
  39. signals.toggleVR.add( () => {
  40. if ( this.currentSession === null ) {
  41. const sessionInit = { optionalFeatures: [ 'local-floor', 'bounded-floor' ] };
  42. navigator.xr.requestSession( 'immersive-vr', sessionInit ).then( onSessionStarted );
  43. } else {
  44. this.currentSession.end();
  45. }
  46. } );
  47. signals.rendererChanged.add( ( value ) => {
  48. renderer = value;
  49. renderer.xr.enabled = true;
  50. } );
  51. }
  52. }
  53. export { VR };