motion-controllers.module.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. /**
  2. * @webxr-input-profiles/motion-controllers 1.0.0 https://github.com/immersive-web/webxr-input-profiles
  3. */
  4. const Constants = {
  5. Handedness: Object.freeze({
  6. NONE: 'none',
  7. LEFT: 'left',
  8. RIGHT: 'right'
  9. }),
  10. ComponentState: Object.freeze({
  11. DEFAULT: 'default',
  12. TOUCHED: 'touched',
  13. PRESSED: 'pressed'
  14. }),
  15. ComponentProperty: Object.freeze({
  16. BUTTON: 'button',
  17. X_AXIS: 'xAxis',
  18. Y_AXIS: 'yAxis',
  19. STATE: 'state'
  20. }),
  21. ComponentType: Object.freeze({
  22. TRIGGER: 'trigger',
  23. SQUEEZE: 'squeeze',
  24. TOUCHPAD: 'touchpad',
  25. THUMBSTICK: 'thumbstick',
  26. BUTTON: 'button'
  27. }),
  28. ButtonTouchThreshold: 0.05,
  29. AxisTouchThreshold: 0.1,
  30. VisualResponseProperty: Object.freeze({
  31. TRANSFORM: 'transform',
  32. VISIBILITY: 'visibility'
  33. })
  34. };
  35. /**
  36. * @description Static helper function to fetch a JSON file and turn it into a JS object
  37. * @param {string} path - Path to JSON file to be fetched
  38. */
  39. async function fetchJsonFile(path) {
  40. const response = await fetch(path);
  41. if (!response.ok) {
  42. throw new Error(response.statusText);
  43. } else {
  44. return response.json();
  45. }
  46. }
  47. async function fetchProfilesList(basePath) {
  48. if (!basePath) {
  49. throw new Error('No basePath supplied');
  50. }
  51. const profileListFileName = 'profilesList.json';
  52. const profilesList = await fetchJsonFile(`${basePath}/${profileListFileName}`);
  53. return profilesList;
  54. }
  55. async function fetchProfile(xrInputSource, basePath, defaultProfile = null, getAssetPath = true) {
  56. if (!xrInputSource) {
  57. throw new Error('No xrInputSource supplied');
  58. }
  59. if (!basePath) {
  60. throw new Error('No basePath supplied');
  61. }
  62. // Get the list of profiles
  63. const supportedProfilesList = await fetchProfilesList(basePath);
  64. // Find the relative path to the first requested profile that is recognized
  65. let match;
  66. xrInputSource.profiles.some((profileId) => {
  67. const supportedProfile = supportedProfilesList[profileId];
  68. if (supportedProfile) {
  69. match = {
  70. profileId,
  71. profilePath: `${basePath}/${supportedProfile.path}`,
  72. deprecated: !!supportedProfile.deprecated
  73. };
  74. }
  75. return !!match;
  76. });
  77. if (!match) {
  78. if (!defaultProfile) {
  79. throw new Error('No matching profile name found');
  80. }
  81. const supportedProfile = supportedProfilesList[defaultProfile];
  82. if (!supportedProfile) {
  83. throw new Error(`No matching profile name found and default profile "${defaultProfile}" missing.`);
  84. }
  85. match = {
  86. profileId: defaultProfile,
  87. profilePath: `${basePath}/${supportedProfile.path}`,
  88. deprecated: !!supportedProfile.deprecated
  89. };
  90. }
  91. const profile = await fetchJsonFile(match.profilePath);
  92. let assetPath;
  93. if (getAssetPath) {
  94. let layout;
  95. if (xrInputSource.handedness === 'any') {
  96. layout = profile.layouts[Object.keys(profile.layouts)[0]];
  97. } else {
  98. layout = profile.layouts[xrInputSource.handedness];
  99. }
  100. if (!layout) {
  101. throw new Error(
  102. `No matching handedness, ${xrInputSource.handedness}, in profile ${match.profileId}`
  103. );
  104. }
  105. if (layout.assetPath) {
  106. assetPath = match.profilePath.replace('profile.json', layout.assetPath);
  107. }
  108. }
  109. return { profile, assetPath };
  110. }
  111. /** @constant {Object} */
  112. const defaultComponentValues = {
  113. xAxis: 0,
  114. yAxis: 0,
  115. button: 0,
  116. state: Constants.ComponentState.DEFAULT
  117. };
  118. /**
  119. * @description Converts an X, Y coordinate from the range -1 to 1 (as reported by the Gamepad
  120. * API) to the range 0 to 1 (for interpolation). Also caps the X, Y values to be bounded within
  121. * a circle. This ensures that thumbsticks are not animated outside the bounds of their physical
  122. * range of motion and touchpads do not report touch locations off their physical bounds.
  123. * @param {number} x The original x coordinate in the range -1 to 1
  124. * @param {number} y The original y coordinate in the range -1 to 1
  125. */
  126. function normalizeAxes(x = 0, y = 0) {
  127. let xAxis = x;
  128. let yAxis = y;
  129. // Determine if the point is outside the bounds of the circle
  130. // and, if so, place it on the edge of the circle
  131. const hypotenuse = Math.sqrt((x * x) + (y * y));
  132. if (hypotenuse > 1) {
  133. const theta = Math.atan2(y, x);
  134. xAxis = Math.cos(theta);
  135. yAxis = Math.sin(theta);
  136. }
  137. // Scale and move the circle so values are in the interpolation range. The circle's origin moves
  138. // from (0, 0) to (0.5, 0.5). The circle's radius scales from 1 to be 0.5.
  139. const result = {
  140. normalizedXAxis: (xAxis * 0.5) + 0.5,
  141. normalizedYAxis: (yAxis * 0.5) + 0.5
  142. };
  143. return result;
  144. }
  145. /**
  146. * Contains the description of how the 3D model should visually respond to a specific user input.
  147. * This is accomplished by initializing the object with the name of a node in the 3D model and
  148. * property that need to be modified in response to user input, the name of the nodes representing
  149. * the allowable range of motion, and the name of the input which triggers the change. In response
  150. * to the named input changing, this object computes the appropriate weighting to use for
  151. * interpolating between the range of motion nodes.
  152. */
  153. class VisualResponse {
  154. constructor(visualResponseDescription) {
  155. this.componentProperty = visualResponseDescription.componentProperty;
  156. this.states = visualResponseDescription.states;
  157. this.valueNodeName = visualResponseDescription.valueNodeName;
  158. this.valueNodeProperty = visualResponseDescription.valueNodeProperty;
  159. if (this.valueNodeProperty === Constants.VisualResponseProperty.TRANSFORM) {
  160. this.minNodeName = visualResponseDescription.minNodeName;
  161. this.maxNodeName = visualResponseDescription.maxNodeName;
  162. }
  163. // Initializes the response's current value based on default data
  164. this.value = 0;
  165. this.updateFromComponent(defaultComponentValues);
  166. }
  167. /**
  168. * Computes the visual response's interpolation weight based on component state
  169. * @param {Object} componentValues - The component from which to update
  170. * @param {number} xAxis - The reported X axis value of the component
  171. * @param {number} yAxis - The reported Y axis value of the component
  172. * @param {number} button - The reported value of the component's button
  173. * @param {string} state - The component's active state
  174. */
  175. updateFromComponent({
  176. xAxis, yAxis, button, state
  177. }) {
  178. const { normalizedXAxis, normalizedYAxis } = normalizeAxes(xAxis, yAxis);
  179. switch (this.componentProperty) {
  180. case Constants.ComponentProperty.X_AXIS:
  181. this.value = (this.states.includes(state)) ? normalizedXAxis : 0.5;
  182. break;
  183. case Constants.ComponentProperty.Y_AXIS:
  184. this.value = (this.states.includes(state)) ? normalizedYAxis : 0.5;
  185. break;
  186. case Constants.ComponentProperty.BUTTON:
  187. this.value = (this.states.includes(state)) ? button : 0;
  188. break;
  189. case Constants.ComponentProperty.STATE:
  190. if (this.valueNodeProperty === Constants.VisualResponseProperty.VISIBILITY) {
  191. this.value = (this.states.includes(state));
  192. } else {
  193. this.value = this.states.includes(state) ? 1.0 : 0.0;
  194. }
  195. break;
  196. default:
  197. throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`);
  198. }
  199. }
  200. }
  201. class Component {
  202. /**
  203. * @param {Object} componentId - Id of the component
  204. * @param {Object} componentDescription - Description of the component to be created
  205. */
  206. constructor(componentId, componentDescription) {
  207. if (!componentId
  208. || !componentDescription
  209. || !componentDescription.visualResponses
  210. || !componentDescription.gamepadIndices
  211. || Object.keys(componentDescription.gamepadIndices).length === 0) {
  212. throw new Error('Invalid arguments supplied');
  213. }
  214. this.id = componentId;
  215. this.type = componentDescription.type;
  216. this.rootNodeName = componentDescription.rootNodeName;
  217. this.touchPointNodeName = componentDescription.touchPointNodeName;
  218. // Build all the visual responses for this component
  219. this.visualResponses = {};
  220. Object.keys(componentDescription.visualResponses).forEach((responseName) => {
  221. const visualResponse = new VisualResponse(componentDescription.visualResponses[responseName]);
  222. this.visualResponses[responseName] = visualResponse;
  223. });
  224. // Set default values
  225. this.gamepadIndices = Object.assign({}, componentDescription.gamepadIndices);
  226. this.values = {
  227. state: Constants.ComponentState.DEFAULT,
  228. button: (this.gamepadIndices.button !== undefined) ? 0 : undefined,
  229. xAxis: (this.gamepadIndices.xAxis !== undefined) ? 0 : undefined,
  230. yAxis: (this.gamepadIndices.yAxis !== undefined) ? 0 : undefined
  231. };
  232. }
  233. get data() {
  234. const data = { id: this.id, ...this.values };
  235. return data;
  236. }
  237. /**
  238. * @description Poll for updated data based on current gamepad state
  239. * @param {Object} gamepad - The gamepad object from which the component data should be polled
  240. */
  241. updateFromGamepad(gamepad) {
  242. // Set the state to default before processing other data sources
  243. this.values.state = Constants.ComponentState.DEFAULT;
  244. // Get and normalize button
  245. if (this.gamepadIndices.button !== undefined
  246. && gamepad.buttons.length > this.gamepadIndices.button) {
  247. const gamepadButton = gamepad.buttons[this.gamepadIndices.button];
  248. this.values.button = gamepadButton.value;
  249. this.values.button = (this.values.button < 0) ? 0 : this.values.button;
  250. this.values.button = (this.values.button > 1) ? 1 : this.values.button;
  251. // Set the state based on the button
  252. if (gamepadButton.pressed || this.values.button === 1) {
  253. this.values.state = Constants.ComponentState.PRESSED;
  254. } else if (gamepadButton.touched || this.values.button > Constants.ButtonTouchThreshold) {
  255. this.values.state = Constants.ComponentState.TOUCHED;
  256. }
  257. }
  258. // Get and normalize x axis value
  259. if (this.gamepadIndices.xAxis !== undefined
  260. && gamepad.axes.length > this.gamepadIndices.xAxis) {
  261. this.values.xAxis = gamepad.axes[this.gamepadIndices.xAxis];
  262. this.values.xAxis = (this.values.xAxis < -1) ? -1 : this.values.xAxis;
  263. this.values.xAxis = (this.values.xAxis > 1) ? 1 : this.values.xAxis;
  264. // If the state is still default, check if the xAxis makes it touched
  265. if (this.values.state === Constants.ComponentState.DEFAULT
  266. && Math.abs(this.values.xAxis) > Constants.AxisTouchThreshold) {
  267. this.values.state = Constants.ComponentState.TOUCHED;
  268. }
  269. }
  270. // Get and normalize Y axis value
  271. if (this.gamepadIndices.yAxis !== undefined
  272. && gamepad.axes.length > this.gamepadIndices.yAxis) {
  273. this.values.yAxis = gamepad.axes[this.gamepadIndices.yAxis];
  274. this.values.yAxis = (this.values.yAxis < -1) ? -1 : this.values.yAxis;
  275. this.values.yAxis = (this.values.yAxis > 1) ? 1 : this.values.yAxis;
  276. // If the state is still default, check if the yAxis makes it touched
  277. if (this.values.state === Constants.ComponentState.DEFAULT
  278. && Math.abs(this.values.yAxis) > Constants.AxisTouchThreshold) {
  279. this.values.state = Constants.ComponentState.TOUCHED;
  280. }
  281. }
  282. // Update the visual response weights based on the current component data
  283. Object.values(this.visualResponses).forEach((visualResponse) => {
  284. visualResponse.updateFromComponent(this.values);
  285. });
  286. }
  287. }
  288. /**
  289. * @description Builds a motion controller with components and visual responses based on the
  290. * supplied profile description. Data is polled from the xrInputSource's gamepad.
  291. * @author Nell Waliczek / https://github.com/NellWaliczek
  292. */
  293. class MotionController {
  294. /**
  295. * @param {Object} xrInputSource - The XRInputSource to build the MotionController around
  296. * @param {Object} profile - The best matched profile description for the supplied xrInputSource
  297. * @param {Object} assetUrl
  298. */
  299. constructor(xrInputSource, profile, assetUrl) {
  300. if (!xrInputSource) {
  301. throw new Error('No xrInputSource supplied');
  302. }
  303. if (!profile) {
  304. throw new Error('No profile supplied');
  305. }
  306. this.xrInputSource = xrInputSource;
  307. this.assetUrl = assetUrl;
  308. this.id = profile.profileId;
  309. // Build child components as described in the profile description
  310. this.layoutDescription = profile.layouts[xrInputSource.handedness];
  311. this.components = {};
  312. Object.keys(this.layoutDescription.components).forEach((componentId) => {
  313. const componentDescription = this.layoutDescription.components[componentId];
  314. this.components[componentId] = new Component(componentId, componentDescription);
  315. });
  316. // Initialize components based on current gamepad state
  317. this.updateFromGamepad();
  318. }
  319. get gripSpace() {
  320. return this.xrInputSource.gripSpace;
  321. }
  322. get targetRaySpace() {
  323. return this.xrInputSource.targetRaySpace;
  324. }
  325. /**
  326. * @description Returns a subset of component data for simplified debugging
  327. */
  328. get data() {
  329. const data = [];
  330. Object.values(this.components).forEach((component) => {
  331. data.push(component.data);
  332. });
  333. return data;
  334. }
  335. /**
  336. * @description Poll for updated data based on current gamepad state
  337. */
  338. updateFromGamepad() {
  339. Object.values(this.components).forEach((component) => {
  340. component.updateFromGamepad(this.xrInputSource.gamepad);
  341. });
  342. }
  343. }
  344. export { Constants, MotionController, fetchProfile, fetchProfilesList };