babylon.windowsMotionController.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. module BABYLON {
  2. class LoadedMeshInfo {
  3. public rootNode: AbstractMesh;
  4. public pointingPoseNode: AbstractMesh;
  5. public buttonMeshes: { [id: string] : IButtonMeshInfo; } = {};
  6. public axisMeshes: { [id: number] : IAxisMeshInfo; } = {};
  7. }
  8. interface IMeshInfo {
  9. index: number;
  10. value: AbstractMesh;
  11. }
  12. interface IButtonMeshInfo extends IMeshInfo {
  13. pressed: AbstractMesh;
  14. unpressed: AbstractMesh;
  15. }
  16. interface IAxisMeshInfo extends IMeshInfo {
  17. min: AbstractMesh;
  18. max: AbstractMesh;
  19. }
  20. export class WindowsMotionController extends WebVRController {
  21. private static readonly MODEL_BASE_URL:string = 'https://controllers.babylonjs.com/microsoft/';
  22. private static readonly MODEL_LEFT_FILENAME:string = 'left.glb';
  23. private static readonly MODEL_RIGHT_FILENAME:string = 'right.glb';
  24. public static readonly GAMEPAD_ID_PREFIX:string = 'Spatial Controller (Spatial Interaction Source) ';
  25. private static readonly GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  26. private _loadedMeshInfo: LoadedMeshInfo;
  27. private readonly _mapping = {
  28. // Semantic button names
  29. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  30. // A mapping of the button name to glTF model node name
  31. // that should be transformed by button value.
  32. buttonMeshNames: {
  33. 'trigger': 'SELECT',
  34. 'menu': 'MENU',
  35. 'grip': 'GRASP',
  36. 'thumbstick': 'THUMBSTICK_PRESS',
  37. 'trackpad': 'TOUCHPAD_PRESS'
  38. },
  39. // This mapping is used to translate from the Motion Controller to Babylon semantics
  40. buttonObservableNames: {
  41. 'trigger': 'onTriggerStateChangedObservable',
  42. 'menu': 'onSecondaryButtonStateChangedObservable',
  43. 'grip': 'onMainButtonStateChangedObservable',
  44. 'thumbstick': 'onPadStateChangedObservable',
  45. 'trackpad': 'onTrackpadChangedObservable'
  46. },
  47. // A mapping of the axis name to glTF model node name
  48. // that should be transformed by axis value.
  49. // This array mirrors the browserGamepad.axes array, such that
  50. // the mesh corresponding to axis 0 is in this array index 0.
  51. axisMeshNames: [
  52. 'THUMBSTICK_X',
  53. 'THUMBSTICK_Y',
  54. 'TOUCHPAD_TOUCH_X',
  55. 'TOUCHPAD_TOUCH_Y'
  56. ],
  57. pointingPoseMeshName: 'POINTING_POSE'
  58. };
  59. public onTrackpadChangedObservable = new Observable<ExtendedGamepadButton>();
  60. constructor(vrGamepad) {
  61. super(vrGamepad);
  62. this.controllerType = PoseEnabledControllerType.WINDOWS;
  63. this._loadedMeshInfo = null;
  64. }
  65. public get onTriggerButtonStateChangedObservable(): Observable<ExtendedGamepadButton> {
  66. return this.onTriggerStateChangedObservable;
  67. }
  68. public get onMenuButtonStateChangedObservable(): Observable<ExtendedGamepadButton> {
  69. return this.onSecondaryButtonStateChangedObservable;
  70. }
  71. public get onGripButtonStateChangedObservable(): Observable<ExtendedGamepadButton> {
  72. return this.onMainButtonStateChangedObservable;
  73. }
  74. public get onThumbstickButtonStateChangedObservable(): Observable<ExtendedGamepadButton> {
  75. return this.onPadStateChangedObservable;
  76. }
  77. public get onTouchpadButtonStateChangedObservable(): Observable<ExtendedGamepadButton> {
  78. return this.onTrackpadChangedObservable;
  79. }
  80. /**
  81. * Called once per frame by the engine.
  82. */
  83. public update() {
  84. super.update();
  85. // Only need to animate axes if there is a loaded mesh
  86. if (this._loadedMeshInfo) {
  87. if (this.browserGamepad.axes) {
  88. for (let axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  89. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  90. }
  91. }
  92. }
  93. }
  94. /**
  95. * Called once for each button that changed state since the last frame
  96. * @param buttonIdx Which button index changed
  97. * @param state New state of the button
  98. * @param changes Which properties on the state changed since last frame
  99. */
  100. protected handleButtonChange(buttonIdx: number, state: ExtendedGamepadButton, changes: GamepadButtonChanges) {
  101. let buttonName = this._mapping.buttons[buttonIdx];
  102. if (!buttonName) {
  103. return;
  104. }
  105. // Only emit events for buttons that we know how to map from index to name
  106. let observable = this[this._mapping.buttonObservableNames[buttonName]];
  107. if (observable) {
  108. observable.notifyObservers(state);
  109. }
  110. this.lerpButtonTransform(buttonName, state.value);
  111. }
  112. protected lerpButtonTransform(buttonName: string, buttonValue: number) {
  113. // If there is no loaded mesh, there is nothing to transform.
  114. if (!this._loadedMeshInfo) {
  115. return;
  116. }
  117. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  118. BABYLON.Quaternion.SlerpToRef(
  119. meshInfo.unpressed.rotationQuaternion,
  120. meshInfo.pressed.rotationQuaternion,
  121. buttonValue,
  122. meshInfo.value.rotationQuaternion);
  123. BABYLON.Vector3.LerpToRef(
  124. meshInfo.unpressed.position,
  125. meshInfo.pressed.position,
  126. buttonValue,
  127. meshInfo.value.position);
  128. }
  129. protected lerpAxisTransform(axis:number, axisValue: number) {
  130. let meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  131. if (!meshInfo) {
  132. return;
  133. }
  134. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  135. let lerpValue = axisValue * 0.5 + 0.5;
  136. BABYLON.Quaternion.SlerpToRef(
  137. meshInfo.min.rotationQuaternion,
  138. meshInfo.max.rotationQuaternion,
  139. lerpValue,
  140. meshInfo.value.rotationQuaternion);
  141. BABYLON.Vector3.LerpToRef(
  142. meshInfo.min.position,
  143. meshInfo.max.position,
  144. lerpValue,
  145. meshInfo.value.position);
  146. }
  147. /**
  148. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  149. * @param scene scene in which to add meshes
  150. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  151. */
  152. public initControllerMesh(scene: Scene, meshLoaded?: (mesh: AbstractMesh) => void, forceDefault = false) {
  153. let path: string;
  154. let filename: string;
  155. // Checking if GLB loader is present
  156. if (SceneLoader.GetPluginForExtension("glb")) {
  157. // Determine the device specific folder based on the ID suffix
  158. let device = 'default';
  159. if (this.id && !forceDefault) {
  160. let match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  161. device = ((match && match[0]) || device);
  162. }
  163. // Hand
  164. if (this.hand === 'left') {
  165. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  166. }
  167. else { // Right is the default if no hand is specified
  168. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  169. }
  170. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  171. } else {
  172. Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  173. path = GenericController.MODEL_BASE_URL;
  174. filename = GenericController.MODEL_FILENAME;
  175. }
  176. SceneLoader.ImportMesh("", path, filename, scene, (meshes: AbstractMesh[]) => {
  177. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  178. this._loadedMeshInfo = this.processModel(scene, meshes);
  179. if (!this._loadedMeshInfo) {
  180. return;
  181. }
  182. this._defaultModel = this._loadedMeshInfo.rootNode;
  183. this.attachToMesh(this._defaultModel);
  184. if (meshLoaded) {
  185. meshLoaded(this._defaultModel);
  186. }
  187. }, null, (scene: Scene, message: string) => {
  188. Tools.Log(message);
  189. Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  190. if (!forceDefault) {
  191. this.initControllerMesh(scene, meshLoaded, true);
  192. }
  193. });
  194. }
  195. /**
  196. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  197. * can be transformed by button presses and axes values, based on this._mapping.
  198. *
  199. * @param scene scene in which the meshes exist
  200. * @param meshes list of meshes that make up the controller model to process
  201. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  202. */
  203. private processModel(scene: Scene, meshes: AbstractMesh[]) : LoadedMeshInfo {
  204. let loadedMeshInfo = null;
  205. // Create a new mesh to contain the glTF hierarchy
  206. let parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  207. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  208. let childMesh : AbstractMesh = null;
  209. for (let i = 0; i < meshes.length; i++) {
  210. let mesh = meshes[i];
  211. if (!mesh.parent) {
  212. // Exclude controller meshes from picking results
  213. mesh.isPickable = false;
  214. // Handle root node, attach to the new parentMesh
  215. childMesh = mesh;
  216. break;
  217. }
  218. }
  219. if (childMesh) {
  220. childMesh.setParent(parentMesh);
  221. // Create our mesh info. Note that this method will always return non-null.
  222. loadedMeshInfo = this.createMeshInfo(parentMesh);
  223. } else {
  224. Tools.Warn('Could not find root node in model file.');
  225. }
  226. return loadedMeshInfo;
  227. }
  228. private createMeshInfo(rootNode: AbstractMesh) : LoadedMeshInfo {
  229. let loadedMeshInfo = new LoadedMeshInfo();
  230. var i;
  231. loadedMeshInfo.rootNode = rootNode;
  232. // Reset the caches
  233. loadedMeshInfo.buttonMeshes = {};
  234. loadedMeshInfo.axisMeshes = {};
  235. // Button Meshes
  236. for (i = 0; i < this._mapping.buttons.length; i++) {
  237. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  238. if (!buttonMeshName) {
  239. Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  240. continue;
  241. }
  242. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  243. if (!buttonMesh) {
  244. Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  245. continue;
  246. }
  247. var buttonMeshInfo = {
  248. index: i,
  249. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  250. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  251. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  252. };
  253. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  254. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  255. } else {
  256. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  257. Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  258. '(VALUE: ' + !!buttonMeshInfo.value +
  259. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  260. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  261. ')');
  262. }
  263. }
  264. // Axis Meshes
  265. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  266. var axisMeshName = this._mapping.axisMeshNames[i];
  267. if (!axisMeshName) {
  268. Tools.Log('Skipping unknown axis at index: ' + i);
  269. continue;
  270. }
  271. var axisMesh = getChildByName(rootNode, axisMeshName);
  272. if (!axisMesh) {
  273. Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  274. continue;
  275. }
  276. var axisMeshInfo = {
  277. index: i,
  278. value: getImmediateChildByName(axisMesh, 'VALUE'),
  279. min: getImmediateChildByName(axisMesh, 'MIN'),
  280. max: getImmediateChildByName(axisMesh, 'MAX')
  281. };
  282. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  283. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  284. } else {
  285. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  286. Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  287. '(VALUE: ' + !!axisMeshInfo.value +
  288. ', MIN: ' + !!axisMeshInfo.min +
  289. ', MAX:' + !!axisMeshInfo.max +
  290. ')');
  291. }
  292. }
  293. // Pointing Ray
  294. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  295. if (!loadedMeshInfo.pointingPoseNode) {
  296. Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  297. }
  298. return loadedMeshInfo;
  299. // Look through all children recursively. This will return null if no mesh exists with the given name.
  300. function getChildByName(node, name) {
  301. return node.getChildMeshes(false, n => n.name === name)[0];
  302. }
  303. // Look through only immediate children. This will return null if no mesh exists with the given name.
  304. function getImmediateChildByName (node, name) : AbstractMesh {
  305. return node.getChildMeshes(true, n => n.name == name)[0];
  306. }
  307. }
  308. public getForwardRay(length = 100): Ray {
  309. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  310. return super.getForwardRay(length);
  311. }
  312. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  313. var origin = m.getTranslation();
  314. var forward = new BABYLON.Vector3(0, 0, -1);
  315. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  316. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  317. return new Ray(origin, direction, length);
  318. }
  319. public dispose(): void {
  320. super.dispose();
  321. this.onTrackpadChangedObservable.clear();
  322. }
  323. }
  324. }