XRControllerModelFactory.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /**
  2. * @author Nell Waliczek / https://github.com/NellWaliczek
  3. * @author Brandon Jones / https://github.com/toji
  4. */
  5. import {
  6. Mesh,
  7. MeshBasicMaterial,
  8. Object3D,
  9. Quaternion,
  10. SphereGeometry,
  11. } from "../../../build/three.module.js";
  12. import { GLTFLoader } from '../loaders/GLTFLoader.js';
  13. import {
  14. Constants as MotionControllerConstants,
  15. fetchProfile,
  16. MotionController
  17. } from '../libs/motion-controllers.module.js';
  18. const DEFAULT_PROFILES_PATH = 'https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles';
  19. const DEFAULT_PROFILE = 'generic-trigger';
  20. function XRControllerModel( ) {
  21. Object3D.call( this );
  22. this.motionController = null;
  23. this.envMap = null;
  24. }
  25. XRControllerModel.prototype = Object.assign( Object.create( Object3D.prototype ), {
  26. constructor: XRControllerModel,
  27. setEnvironmentMap: function ( envMap ) {
  28. if ( this.envMap == envMap ) {
  29. return this;
  30. }
  31. this.envMap = envMap;
  32. this.traverse(( child ) => {
  33. if ( child.isMesh ) {
  34. child.material.envMap = this.envMap;
  35. child.material.needsUpdate = true;
  36. }
  37. });
  38. return this;
  39. },
  40. /**
  41. * Polls data from the XRInputSource and updates the model's components to match
  42. * the real world data
  43. */
  44. updateMatrixWorld: function ( force ) {
  45. Object3D.prototype.updateMatrixWorld.call( this, force );
  46. if ( !this.motionController ) return;
  47. // Cause the MotionController to poll the Gamepad for data
  48. this.motionController.updateFromGamepad();
  49. // Update the 3D model to reflect the button, thumbstick, and touchpad state
  50. Object.values( this.motionController.components ).forEach(( component ) => {
  51. // Update node data based on the visual responses' current states
  52. Object.values( component.visualResponses ).forEach(( visualResponse ) => {
  53. const { valueNode, minNode, maxNode, value, valueNodeProperty } = visualResponse;
  54. // Skip if the visual response node is not found. No error is needed,
  55. // because it will have been reported at load time.
  56. if ( !valueNode ) return;
  57. // Calculate the new properties based on the weight supplied
  58. if ( valueNodeProperty === MotionControllerConstants.VisualResponseProperty.VISIBILITY ) {
  59. valueNode.visible = value;
  60. } else if ( valueNodeProperty === MotionControllerConstants.VisualResponseProperty.TRANSFORM ) {
  61. Quaternion.slerp(
  62. minNode.quaternion,
  63. maxNode.quaternion,
  64. valueNode.quaternion,
  65. value
  66. );
  67. valueNode.position.lerpVectors(
  68. minNode.position,
  69. maxNode.position,
  70. value
  71. );
  72. }
  73. });
  74. });
  75. }
  76. } );
  77. /**
  78. * Walks the model's tree to find the nodes needed to animate the components and
  79. * saves them to the motionContoller components for use in the frame loop. When
  80. * touchpads are found, attaches a touch dot to them.
  81. */
  82. function findNodes( motionController, scene ) {
  83. // Loop through the components and find the nodes needed for each components' visual responses
  84. Object.values( motionController.components ).forEach(( component ) => {
  85. const { type, touchPointNodeName, visualResponses } = component;
  86. if (type === MotionControllerConstants.ComponentType.TOUCHPAD) {
  87. component.touchPointNode = scene.getObjectByName( touchPointNodeName );
  88. if ( component.touchPointNode ) {
  89. // Attach a touch dot to the touchpad.
  90. const sphereGeometry = new SphereGeometry( 0.001 );
  91. const material = new MeshBasicMaterial({ color: 0x0000FF });
  92. const sphere = new Mesh( sphereGeometry, material );
  93. component.touchPointNode.add( sphere );
  94. } else {
  95. console.warn(`Could not find touch dot, ${component.touchPointNodeName}, in touchpad component ${componentId}`);
  96. }
  97. }
  98. // Loop through all the visual responses to be applied to this component
  99. Object.values( visualResponses ).forEach(( visualResponse ) => {
  100. const { valueNodeName, minNodeName, maxNodeName, valueNodeProperty } = visualResponse;
  101. // If animating a transform, find the two nodes to be interpolated between.
  102. if ( valueNodeProperty === MotionControllerConstants.VisualResponseProperty.TRANSFORM ) {
  103. visualResponse.minNode = scene.getObjectByName(minNodeName);
  104. visualResponse.maxNode = scene.getObjectByName(maxNodeName);
  105. // If the extents cannot be found, skip this animation
  106. if ( !visualResponse.minNode ) {
  107. console.warn(`Could not find ${minNodeName} in the model`);
  108. return;
  109. }
  110. if ( !visualResponse.maxNode ) {
  111. console.warn(`Could not find ${maxNodeName} in the model`);
  112. return;
  113. }
  114. }
  115. // If the target node cannot be found, skip this animation
  116. visualResponse.valueNode = scene.getObjectByName(valueNodeName);
  117. if ( !visualResponse.valueNode ) {
  118. console.warn(`Could not find ${valueNodeName} in the model`);
  119. }
  120. });
  121. });
  122. }
  123. function addAssetSceneToControllerModel( controllerModel, scene ) {
  124. // Find the nodes needed for animation and cache them on the motionController.
  125. findNodes( controllerModel.motionController, scene );
  126. // Apply any environment map that the mesh already has set.
  127. if ( controllerModel.envMap ) {
  128. scene.traverse(( child ) => {
  129. if ( child.isMesh ) {
  130. child.material.envMap = controllerModel.envMap;
  131. child.material.needsUpdate = true;
  132. }
  133. });
  134. }
  135. // Add the glTF scene to the controllerModel.
  136. controllerModel.add( scene );
  137. }
  138. var XRControllerModelFactory = ( function () {
  139. function XRControllerModelFactory( gltfLoader = null ) {
  140. this.gltfLoader = gltfLoader;
  141. this.path = DEFAULT_PROFILES_PATH;
  142. this._assetCache = {};
  143. // If a GLTFLoader wasn't supplied to the constructor create a new one.
  144. if ( !this.gltfLoader ) {
  145. this.gltfLoader = new GLTFLoader();
  146. }
  147. }
  148. XRControllerModelFactory.prototype = {
  149. constructor: XRControllerModelFactory,
  150. createControllerModel: function ( controller ) {
  151. const controllerModel = new XRControllerModel();
  152. let scene = null;
  153. controller.addEventListener( 'connected', ( event ) => {
  154. const xrInputSource = event.data;
  155. if (xrInputSource.targetRayMode !== 'tracked-pointer' || !xrInputSource.gamepad ) return;
  156. fetchProfile( xrInputSource, this.path, DEFAULT_PROFILE ).then(({ profile, assetPath }) => {
  157. controllerModel.motionController = new MotionController(
  158. xrInputSource,
  159. profile,
  160. assetPath
  161. );
  162. let cachedAsset = this._assetCache[controllerModel.motionController.assetUrl];
  163. if (cachedAsset) {
  164. scene = cachedAsset.scene.clone();
  165. addAssetSceneToControllerModel(controllerModel, scene);
  166. } else {
  167. if ( !this.gltfLoader ) {
  168. throw new Error(`GLTFLoader not set.`);
  169. }
  170. this.gltfLoader.setPath('');
  171. this.gltfLoader.load( controllerModel.motionController.assetUrl, ( asset ) => {
  172. this._assetCache[controllerModel.motionController.assetUrl] = asset;
  173. scene = asset.scene.clone();
  174. addAssetSceneToControllerModel(controllerModel, scene);
  175. },
  176. null,
  177. () => {
  178. throw new Error(`Asset ${motionController.assetUrl} missing or malformed.`);
  179. });
  180. }
  181. }).catch((err) => {
  182. console.warn(err);
  183. });
  184. });
  185. controller.addEventListener( 'disconnected', () => {
  186. controllerModel.motionController = null;
  187. controllerModel.remove( scene );
  188. scene = null;
  189. });
  190. return controllerModel;
  191. }
  192. };
  193. return XRControllerModelFactory;
  194. } )();
  195. export { XRControllerModelFactory };