webXRMotionControllerManager.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import {
  2. WebXRAbstractMotionController, IMotionControllerProfile,
  3. } from './webXRAbstractMotionController';
  4. import { WebXRGenericTriggerMotionController } from './webXRGenericMotionController';
  5. import { Scene } from '../../scene';
  6. import { Tools } from '../../Misc/tools';
  7. import { WebXRProfiledMotionController } from './webXRProfiledMotionController';
  8. /**
  9. * A construction function type to create a new controller based on an xrInput object
  10. */
  11. export type MotionControllerConstructor = (xrInput: XRInputSource, scene: Scene) => WebXRAbstractMotionController;
  12. /**
  13. * The MotionController Manager manages all registered motion controllers and loads the right one when needed.
  14. *
  15. * When this repository is complete: https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/assets
  16. * it should be replaced with auto-loaded controllers.
  17. *
  18. * When using a model try to stay as generic as possible. Eventually there will be no need in any of the controller classes
  19. */
  20. export class WebXRMotionControllerManager {
  21. /**
  22. * The base URL of the online controller repository. Can be changed at any time.
  23. */
  24. public static BaseRepositoryUrl = "https://immersive-web.github.io/webxr-input-profiles/packages/viewer/dist";
  25. /**
  26. * Use the online repository, or use only locally-defined controllers
  27. */
  28. public static UseOnlineRepository: boolean = true;
  29. /**
  30. * Which repository gets priority - local or online
  31. */
  32. public static PrioritizeOnlineRepository: boolean = true;
  33. private static _AvailableControllers: { [type: string]: MotionControllerConstructor } = {};
  34. private static _Fallbacks: { [profileId: string]: string[] } = {};
  35. /**
  36. * Register a new controller based on its profile. This function will be called by the controller classes themselves.
  37. *
  38. * If you are missing a profile, make sure it is imported in your source, otherwise it will not register.
  39. *
  40. * @param type the profile type to register
  41. * @param constructFunction the function to be called when loading this profile
  42. */
  43. public static RegisterController(type: string, constructFunction: MotionControllerConstructor) {
  44. this._AvailableControllers[type] = constructFunction;
  45. }
  46. /**
  47. * When acquiring a new xrInput object (usually by the WebXRInput class), match it with the correct profile.
  48. * The order of search:
  49. *
  50. * 1) Iterate the profiles array of the xr input and try finding a corresponding motion controller
  51. * 2) (If not found) search in the gamepad id and try using it (legacy versions only)
  52. * 3) search for registered fallbacks (should be redundant, nonetheless it makes sense to check)
  53. * 4) return the generic trigger controller if none were found
  54. *
  55. * @param xrInput the xrInput to which a new controller is initialized
  56. * @param scene the scene to which the model will be added
  57. * @param forceProfile force a certain profile for this controller
  58. * @return A promise that fulfils with the motion controller class for this profile id or the generic standard class if none was found
  59. */
  60. public static GetMotionControllerWithXRInput(xrInput: XRInputSource, scene: Scene, forceProfile?: string): Promise<WebXRAbstractMotionController> {
  61. const profileArray: string[] = [];
  62. if (forceProfile) {
  63. profileArray.push(forceProfile);
  64. }
  65. profileArray.push(...(xrInput.profiles || []));
  66. // emulator support
  67. if (profileArray.length && !profileArray[0]) {
  68. // remove the first "undefined" that the emulator is adding
  69. profileArray.pop();
  70. }
  71. // legacy support - try using the gamepad id
  72. if (xrInput.gamepad && xrInput.gamepad.id) {
  73. switch (xrInput.gamepad.id) {
  74. case (xrInput.gamepad.id.match(/oculus touch/gi) ? xrInput.gamepad.id : undefined):
  75. // oculus in gamepad id
  76. profileArray.push("oculus-touch-v2");
  77. break;
  78. }
  79. }
  80. // make sure microsoft/windows mixed reality works correctly
  81. const windowsMRIdx = profileArray.indexOf("windows-mixed-reality");
  82. if (windowsMRIdx !== -1) {
  83. profileArray.splice(windowsMRIdx, 0, "microsoft-mixed-reality");
  84. }
  85. if (!profileArray.length) {
  86. profileArray.push("generic-trigger");
  87. }
  88. if (this.UseOnlineRepository) {
  89. const firstFunction = this.PrioritizeOnlineRepository ? this._LoadProfileFromRepository : this._LoadProfilesFromAvailableControllers;
  90. const secondFunction = this.PrioritizeOnlineRepository ? this._LoadProfilesFromAvailableControllers : this._LoadProfileFromRepository;
  91. return firstFunction.call(this, profileArray, xrInput, scene).catch(() => {
  92. return secondFunction.call(this, profileArray, xrInput, scene);
  93. });
  94. } else {
  95. // use only available functions
  96. return this._LoadProfilesFromAvailableControllers(profileArray, xrInput, scene);
  97. }
  98. }
  99. private static _LoadProfilesFromAvailableControllers(profileArray: string[], xrInput: XRInputSource, scene: Scene) {
  100. // check fallbacks
  101. for (let i = 0; i < profileArray.length; ++i) {
  102. // defensive
  103. if (!profileArray[i]) {
  104. continue;
  105. }
  106. const fallbacks = this.FindFallbackWithProfileId(profileArray[i]);
  107. for (let j = 0; j < fallbacks.length; ++j) {
  108. const constructionFunction = this._AvailableControllers[fallbacks[j]];
  109. if (constructionFunction) {
  110. return Promise.resolve(constructionFunction(xrInput, scene));
  111. }
  112. }
  113. }
  114. throw new Error(`no controller requested was found in the available controllers list`);
  115. }
  116. private static _ProfilesList: Promise<{ [profile: string]: string }>;
  117. // cache for loading
  118. private static _ProfileLoadingPromises: { [profileName: string]: Promise<IMotionControllerProfile> } = {};
  119. private static _LoadProfileFromRepository(profileArray: string[], xrInput: XRInputSource, scene: Scene): Promise<WebXRAbstractMotionController> {
  120. return Promise.resolve().then(() => {
  121. if (!this._ProfilesList) {
  122. return this.UpdateProfilesList();
  123. } else {
  124. return this._ProfilesList;
  125. }
  126. }).then((profilesList: { [profile: string]: string }) => {
  127. // load the right profile
  128. for (let i = 0; i < profileArray.length; ++i) {
  129. // defensive
  130. if (!profileArray[i]) {
  131. continue;
  132. }
  133. if (profilesList[profileArray[i]]) {
  134. return profileArray[i];
  135. }
  136. }
  137. throw new Error(`neither controller ${profileArray[0]} nor all fallbacks were found in the repository,`);
  138. }).then((profileToLoad: string) => {
  139. // load the profile
  140. if (!this._ProfileLoadingPromises[profileToLoad]) {
  141. this._ProfileLoadingPromises[profileToLoad] = Tools.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${profileToLoad}/profile.json`, false).then((data) => <IMotionControllerProfile>JSON.parse(data as string));
  142. }
  143. return this._ProfileLoadingPromises[profileToLoad];
  144. }).then((profile: IMotionControllerProfile) => {
  145. return new WebXRProfiledMotionController(scene, xrInput, profile, this.BaseRepositoryUrl);
  146. });
  147. }
  148. /**
  149. * Clear the cache used for profile loading and reload when requested again
  150. */
  151. public static ClearProfilesCache() {
  152. delete this._ProfilesList;
  153. this._ProfileLoadingPromises = {};
  154. }
  155. /**
  156. * Will update the list of profiles available in the repository
  157. * @return a promise that resolves to a map of profiles available online
  158. */
  159. public static UpdateProfilesList() {
  160. this._ProfilesList = Tools.LoadFileAsync(this.BaseRepositoryUrl + '/profiles/profilesList.json', false).then((data) => {
  161. return JSON.parse(data.toString());
  162. });
  163. return this._ProfilesList;
  164. }
  165. /**
  166. * Find a fallback profile if the profile was not found. There are a few predefined generic profiles.
  167. * @param profileId the profile to which a fallback needs to be found
  168. * @return an array with corresponding fallback profiles
  169. */
  170. public static FindFallbackWithProfileId(profileId: string): string[] {
  171. const returnArray = this._Fallbacks[profileId] || [];
  172. returnArray.unshift(profileId);
  173. return returnArray;
  174. }
  175. /**
  176. * Register a fallback to a specific profile.
  177. * @param profileId the profileId that will receive the fallbacks
  178. * @param fallbacks A list of fallback profiles
  179. */
  180. public static RegisterFallbacksForProfileId(profileId: string, fallbacks: string[]): void {
  181. if (this._Fallbacks[profileId]) {
  182. this._Fallbacks[profileId].push(...fallbacks);
  183. } else {
  184. this._Fallbacks[profileId] = fallbacks;
  185. }
  186. }
  187. /**
  188. * Register the default fallbacks.
  189. * This function is called automatically when this file is imported.
  190. */
  191. public static DefaultFallbacks() {
  192. this.RegisterFallbacksForProfileId("google-daydream", ["generic-touchpad"]);
  193. this.RegisterFallbacksForProfileId("htc-vive-focus", ["generic-trigger-touchpad"]);
  194. this.RegisterFallbacksForProfileId("htc-vive", ["generic-trigger-squeeze-touchpad"]);
  195. this.RegisterFallbacksForProfileId("magicleap-one", ["generic-trigger-squeeze-touchpad"]);
  196. this.RegisterFallbacksForProfileId("windows-mixed-reality", ["generic-trigger-squeeze-touchpad-thumbstick"]);
  197. this.RegisterFallbacksForProfileId("microsoft-mixed-reality", ["windows-mixed-reality", "generic-trigger-squeeze-touchpad-thumbstick"]);
  198. this.RegisterFallbacksForProfileId("oculus-go", ["generic-trigger-touchpad"]);
  199. this.RegisterFallbacksForProfileId("oculus-touch-v2", ["oculus-touch", "generic-trigger-squeeze-thumbstick"]);
  200. this.RegisterFallbacksForProfileId("oculus-touch", ["generic-trigger-squeeze-thumbstick"]);
  201. this.RegisterFallbacksForProfileId("samsung-gearvr", ["windows-mixed-reality", "generic-trigger-squeeze-touchpad-thumbstick"]);
  202. this.RegisterFallbacksForProfileId("samsung-odyssey", ["generic-touchpad"]);
  203. this.RegisterFallbacksForProfileId("valve-index", ["generic-trigger-squeeze-touchpad-thumbstick"]);
  204. }
  205. }
  206. // register the generic profile(s) here so we will at least have them
  207. WebXRMotionControllerManager.RegisterController(WebXRGenericTriggerMotionController.ProfileId, (xrInput: XRInputSource, scene: Scene) => {
  208. return new WebXRGenericTriggerMotionController(scene, <any>(xrInput.gamepad), xrInput.handedness);
  209. });
  210. // register fallbacks
  211. WebXRMotionControllerManager.DefaultFallbacks();