webXRAbstractMotionController.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. import { IDisposable, Scene } from '../../scene';
  2. import { WebXRControllerComponent } from './webXRControllerComponent';
  3. import { Observable } from '../../Misc/observable';
  4. import { Logger } from '../../Misc/logger';
  5. import { SceneLoader } from '../../Loading/sceneLoader';
  6. import { AbstractMesh } from '../../Meshes/abstractMesh';
  7. import { Nullable } from '../../types';
  8. import { Quaternion, Vector3 } from '../../Maths/math.vector';
  9. import { Mesh } from '../../Meshes/mesh';
  10. /**
  11. * Handness type in xrInput profiles. These can be used to define layouts in the Layout Map.
  12. */
  13. export type MotionControllerHandness = "none" | "left" | "right";
  14. /**
  15. * The type of components available in motion controllers.
  16. * This is not the name of the component.
  17. */
  18. export type MotionControllerComponentType = "trigger" | "squeeze" | "touchpad" | "thumbstick" | "button";
  19. /**
  20. * The state of a controller component
  21. */
  22. export type MotionControllerComponentStateType = "default" | "touched" | "pressed";
  23. /**
  24. * The schema of motion controller layout.
  25. * No object will be initialized using this interface
  26. * This is used just to define the profile.
  27. */
  28. export interface IMotionControllerLayout {
  29. /**
  30. * Defines the main button component id
  31. */
  32. selectComponentId: string;
  33. /**
  34. * Available components (unsorted)
  35. */
  36. components: {
  37. /**
  38. * A map of component Ids
  39. */
  40. [componentId: string]: {
  41. /**
  42. * The type of input the component outputs
  43. */
  44. type: MotionControllerComponentType;
  45. /**
  46. * The indices of this component in the gamepad object
  47. */
  48. gamepadIndices: {
  49. /**
  50. * Index of button
  51. */
  52. button?: number;
  53. /**
  54. * If available, index of x-axis
  55. */
  56. xAxis?: number;
  57. /**
  58. * If available, index of y-axis
  59. */
  60. yAxis?: number;
  61. };
  62. /**
  63. * The mesh's root node name
  64. */
  65. rootNodeName: string;
  66. /**
  67. * Animation definitions for this model
  68. */
  69. visualResponses: {
  70. [stateKey: string]: {
  71. /**
  72. * What property will be animated
  73. */
  74. componentProperty: "xAxis" | "yAxis" | "button" | "state";
  75. /**
  76. * What states influence this visual reponse
  77. */
  78. states: MotionControllerComponentStateType[];
  79. /**
  80. * Type of animation - movement or visibility
  81. */
  82. valueNodeProperty: "transform" | "visibility";
  83. /**
  84. * Base node name to move. Its position will be calculated according to the min and max nodes
  85. */
  86. valueNodeName?: string;
  87. /**
  88. * Minimum movement node
  89. */
  90. minNodeName?: string;
  91. /**
  92. * Max movement node
  93. */
  94. maxNodeName?: string;
  95. }
  96. }
  97. /**
  98. * If touch enabled, what is the name of node to display user feedback
  99. */
  100. touchPointNodeName?: string;
  101. }
  102. };
  103. /**
  104. * Is it xr standard mapping or not
  105. */
  106. gamepadMapping: "" | "xr-standard";
  107. /**
  108. * Base root node of this entire model
  109. */
  110. rootNodeName: string;
  111. /**
  112. * Path to load the assets. Usually relative to the base path
  113. */
  114. assetPath: string;
  115. }
  116. /**
  117. * A definition for the layout map in the input profile
  118. */
  119. export interface IMotionControllerLayoutMap {
  120. /**
  121. * Layouts with handness type as a key
  122. */
  123. [handness: string /* handness */]: IMotionControllerLayout;
  124. }
  125. /**
  126. * The XR Input profile schema
  127. * Profiles can be found here:
  128. * https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/registry/profiles
  129. */
  130. export interface IMotionControllerProfile {
  131. /**
  132. * The id of this profile
  133. * correlates to the profile(s) in the xrInput.profiles array
  134. */
  135. profileId: string;
  136. /**
  137. * fallback profiles for this profileId
  138. */
  139. fallbackProfileIds: string[];
  140. /**
  141. * The layout map, with handness as key
  142. */
  143. layouts: IMotionControllerLayoutMap;
  144. }
  145. /**
  146. * A helper-interface for the 3 meshes needed for controller button animation
  147. * The meshes are provided to the _lerpButtonTransform function to calculate the current position of the value mesh
  148. */
  149. export interface IMotionControllerButtonMeshMap {
  150. /**
  151. * The mesh that will be changed when value changes
  152. */
  153. valueMesh: AbstractMesh;
  154. /**
  155. * the mesh that defines the pressed value mesh position.
  156. * This is used to find the max-position of this button
  157. */
  158. pressedMesh: AbstractMesh;
  159. /**
  160. * the mesh that defines the unpressed value mesh position.
  161. * This is used to find the min (or initial) position of this button
  162. */
  163. unpressedMesh: AbstractMesh;
  164. }
  165. /**
  166. * A helper-interface for the 3 meshes needed for controller axis animation.
  167. * This will be expanded when touchpad animations are fully supported
  168. * The meshes are provided to the _lerpAxisTransform function to calculate the current position of the value mesh
  169. */
  170. export interface IMotionControllerMeshMap {
  171. /**
  172. * The mesh that will be changed when axis value changes
  173. */
  174. valueMesh: AbstractMesh;
  175. /**
  176. * the mesh that defines the minimum value mesh position.
  177. */
  178. minMesh?: AbstractMesh;
  179. /**
  180. * the mesh that defines the maximum value mesh position.
  181. */
  182. maxMesh?: AbstractMesh;
  183. }
  184. /**
  185. * The elements needed for change-detection of the gamepad objects in motion controllers
  186. */
  187. export interface IMinimalMotionControllerObject {
  188. /**
  189. * An array of available buttons
  190. */
  191. buttons: Array<{
  192. /**
  193. * Value of the button/trigger
  194. */
  195. value: number;
  196. /**
  197. * If the button/trigger is currently touched
  198. */
  199. touched: boolean;
  200. /**
  201. * If the button/trigger is currently pressed
  202. */
  203. pressed: boolean;
  204. }>;
  205. /**
  206. * Available axes of this controller
  207. */
  208. axes: number[];
  209. }
  210. /**
  211. * An Abstract Motion controller
  212. * This class receives an xrInput and a profile layout and uses those to initialize the components
  213. * Each component has an observable to check for changes in value and state
  214. */
  215. export abstract class WebXRAbstractMotionController implements IDisposable {
  216. /**
  217. * The profile id of this motion controller
  218. */
  219. public abstract profileId: string;
  220. /**
  221. * A map of components (WebXRControllerComponent) in this motion controller
  222. * Components have a ComponentType and can also have both button and axis definitions
  223. */
  224. public readonly components: {
  225. [id: string]: WebXRControllerComponent
  226. } = {};
  227. /**
  228. * Observers registered here will be triggered when the model of this controller is done loading
  229. */
  230. public onModelLoadedObservable: Observable<WebXRAbstractMotionController> = new Observable();
  231. /**
  232. * The root mesh of the model. It is null if the model was not yet initialized
  233. */
  234. public rootMesh: Nullable<AbstractMesh>;
  235. /**
  236. * Disable the model's animation. Can be set at any time.
  237. */
  238. public disableAnimation: boolean = false;
  239. private _modelReady: boolean = false;
  240. /**
  241. * constructs a new abstract motion controller
  242. * @param scene the scene to which the model of the controller will be added
  243. * @param layout The profile layout to load
  244. * @param gamepadObject The gamepad object correlating to this controller
  245. * @param handness handness (left/right/none) of this controller
  246. * @param _doNotLoadControllerMesh set this flag to ignore the mesh loading
  247. */
  248. constructor(protected scene: Scene, protected layout: IMotionControllerLayout,
  249. /**
  250. * The gamepad object correlating to this controller
  251. */
  252. public gamepadObject: IMinimalMotionControllerObject,
  253. /**
  254. * handness (left/right/none) of this controller
  255. */
  256. public handness: MotionControllerHandness,
  257. _doNotLoadControllerMesh: boolean = false) {
  258. // initialize the components
  259. if (layout.components) {
  260. Object.keys(layout.components).forEach(this._initComponent);
  261. }
  262. // Model is loaded in WebXRInput
  263. }
  264. private _initComponent = (id: string) => {
  265. if (!id) { return; }
  266. const componentDef = this.layout.components[id];
  267. const type = componentDef.type;
  268. const buttonIndex = componentDef.gamepadIndices.button;
  269. // search for axes
  270. let axes: number[] = [];
  271. if (componentDef.gamepadIndices.xAxis !== undefined && componentDef.gamepadIndices.yAxis !== undefined) {
  272. axes.push(componentDef.gamepadIndices.xAxis, componentDef.gamepadIndices.yAxis);
  273. }
  274. this.components[id] = new WebXRControllerComponent(id, type, buttonIndex, axes);
  275. }
  276. /**
  277. * Update this model using the current XRFrame
  278. * @param xrFrame the current xr frame to use and update the model
  279. */
  280. public updateFromXRFrame(xrFrame: XRFrame): void {
  281. this.getComponentIds().forEach((id) => this.getComponent(id).update(this.gamepadObject));
  282. this.updateModel(xrFrame);
  283. }
  284. /**
  285. * Get the list of components available in this motion controller
  286. * @returns an array of strings correlating to available components
  287. */
  288. public getComponentIds(): string[] {
  289. return Object.keys(this.components);
  290. }
  291. /**
  292. * Get the main (Select) component of this controller as defined in the layout
  293. * @returns the main component of this controller
  294. */
  295. public getMainComponent(): WebXRControllerComponent {
  296. return this.getComponent(this.layout.selectComponentId);
  297. }
  298. /**
  299. * get a component based an its component id as defined in layout.components
  300. * @param id the id of the component
  301. * @returns the component correlates to the id or undefined if not found
  302. */
  303. public getComponent(id: string): WebXRControllerComponent {
  304. return this.components[id];
  305. }
  306. /**
  307. * Get the first component of specific type
  308. * @param type type of component to find
  309. * @return a controller component or null if not found
  310. */
  311. public getComponentOfType(type: MotionControllerComponentType): Nullable<WebXRControllerComponent> {
  312. return this.getAllComponentsOfType(type)[0] || null;
  313. }
  314. /**
  315. * Returns all components of specific type
  316. * @param type the type to search for
  317. * @return an array of components with this type
  318. */
  319. public getAllComponentsOfType(type: MotionControllerComponentType): WebXRControllerComponent[] {
  320. return this.getComponentIds().map((id) => this.components[id]).filter((component) => component.type === type);
  321. }
  322. /**
  323. * Loads the model correlating to this controller
  324. * When the mesh is loaded, the onModelLoadedObservable will be triggered
  325. * @returns A promise fulfilled with the result of the model loading
  326. */
  327. public async loadModel(): Promise<boolean> {
  328. let useGeneric = !this._getModelLoadingConstraints();
  329. let loadingParams = this._getGenericFilenameAndPath();
  330. // Checking if GLB loader is present
  331. if (useGeneric) {
  332. Logger.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  333. } else {
  334. loadingParams = this._getFilenameAndPath();
  335. }
  336. return new Promise((resolve, reject) => {
  337. SceneLoader.ImportMesh("", loadingParams.path, loadingParams.filename, this.scene, (meshes: AbstractMesh[]) => {
  338. if (useGeneric) {
  339. this._getGenericParentMesh(meshes);
  340. } else {
  341. this._setRootMesh(meshes);
  342. }
  343. this._processLoadedModel(meshes);
  344. this._modelReady = true;
  345. this.onModelLoadedObservable.notifyObservers(this);
  346. resolve(true);
  347. }, null, (_scene: Scene, message: string) => {
  348. Logger.Log(message);
  349. Logger.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${loadingParams.path}${loadingParams.filename}`);
  350. reject(message);
  351. });
  352. });
  353. }
  354. /**
  355. * Update the model itself with the current frame data
  356. * @param xrFrame the frame to use for updating the model mesh
  357. */
  358. protected updateModel(xrFrame: XRFrame): void {
  359. if (!this._modelReady) {
  360. return;
  361. }
  362. this._updateModel(xrFrame);
  363. }
  364. /**
  365. * Moves the axis on the controller mesh based on its current state
  366. * @param axis the index of the axis
  367. * @param axisValue the value of the axis which determines the meshes new position
  368. * @hidden
  369. */
  370. protected _lerpTransform(axisMap: IMotionControllerMeshMap, axisValue: number, fixValueCoordinates?: boolean): void {
  371. if (!axisMap.minMesh || !axisMap.maxMesh) {
  372. return;
  373. }
  374. if (!axisMap.minMesh.rotationQuaternion || !axisMap.maxMesh.rotationQuaternion || !axisMap.valueMesh.rotationQuaternion) {
  375. return;
  376. }
  377. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  378. let lerpValue = fixValueCoordinates ? axisValue * 0.5 + 0.5 : axisValue;
  379. Quaternion.SlerpToRef(
  380. axisMap.minMesh.rotationQuaternion,
  381. axisMap.maxMesh.rotationQuaternion,
  382. lerpValue,
  383. axisMap.valueMesh.rotationQuaternion);
  384. Vector3.LerpToRef(
  385. axisMap.minMesh.position,
  386. axisMap.maxMesh.position,
  387. lerpValue,
  388. axisMap.valueMesh.position);
  389. }
  390. // Look through all children recursively. This will return null if no mesh exists with the given name.
  391. protected _getChildByName(node: AbstractMesh, name: string): AbstractMesh {
  392. return <AbstractMesh>node.getChildren((n) => n.name === name, false)[0];
  393. }
  394. // Look through only immediate children. This will return null if no mesh exists with the given name.
  395. protected _getImmediateChildByName(node: AbstractMesh, name: string): AbstractMesh {
  396. return <AbstractMesh>node.getChildren((n) => n.name == name, true)[0];
  397. }
  398. private _getGenericFilenameAndPath(): { filename: string, path: string } {
  399. return {
  400. filename: "generic.babylon",
  401. path: "https://controllers.babylonjs.com/generic/"
  402. };
  403. }
  404. private _getGenericParentMesh(meshes: AbstractMesh[]): void {
  405. this.rootMesh = new Mesh(this.profileId + " " + this.handness, this.scene);
  406. meshes.forEach((mesh) => {
  407. if (!mesh.parent) {
  408. mesh.isPickable = false;
  409. mesh.setParent(this.rootMesh);
  410. }
  411. });
  412. this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0);
  413. }
  414. /**
  415. * Get the filename and path for this controller's model
  416. * @returns a map of filename and path
  417. */
  418. protected abstract _getFilenameAndPath(): { filename: string, path: string };
  419. /**
  420. * This function will be called after the model was successfully loaded and can be used
  421. * for mesh transformations before it is available for the user
  422. * @param meshes the loaded meshes
  423. */
  424. protected abstract _processLoadedModel(meshes: AbstractMesh[]): void;
  425. /**
  426. * Set the root mesh for this controller. Important for the WebXR controller class
  427. * @param meshes the loaded meshes
  428. */
  429. protected abstract _setRootMesh(meshes: AbstractMesh[]): void;
  430. /**
  431. * A function executed each frame that updates the mesh (if needed)
  432. * @param xrFrame the current xrFrame
  433. */
  434. protected abstract _updateModel(xrFrame: XRFrame): void;
  435. /**
  436. * This function is called before the mesh is loaded. It checks for loading constraints.
  437. * For example, this function can check if the GLB loader is available
  438. * If this function returns false, the generic controller will be loaded instead
  439. * @returns Is the client ready to load the mesh
  440. */
  441. protected abstract _getModelLoadingConstraints(): boolean;
  442. /**
  443. * Dispose this controller, the model mesh and all its components
  444. */
  445. public dispose(): void {
  446. this.getComponentIds().forEach((id) => this.getComponent(id).dispose());
  447. if (this.rootMesh) {
  448. this.rootMesh.dispose();
  449. }
  450. }
  451. }