webXRFeaturesManager.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import { WebXRSessionManager } from "./webXRSessionManager";
  2. import { IDisposable } from "../scene";
  3. import { Tools } from "../Misc/tools";
  4. /**
  5. * Defining the interface required for a (webxr) feature
  6. */
  7. export interface IWebXRFeature extends IDisposable {
  8. /**
  9. * Is this feature attached
  10. */
  11. attached: boolean;
  12. /**
  13. * Should auto-attach be disabled?
  14. */
  15. disableAutoAttach: boolean;
  16. /**
  17. * Attach the feature to the session
  18. * Will usually be called by the features manager
  19. *
  20. * @param force should attachment be forced (even when already attached)
  21. * @returns true if successful.
  22. */
  23. attach(force?: boolean): boolean;
  24. /**
  25. * Detach the feature from the session
  26. * Will usually be called by the features manager
  27. *
  28. * @returns true if successful.
  29. */
  30. detach(): boolean;
  31. /**
  32. * This function will be executed during before enabling the feature and can be used to not-allow enabling it.
  33. * Note that at this point the session has NOT started, so this is purely checking if the browser supports it
  34. *
  35. * @returns whether or not the feature is compatible in this environment
  36. */
  37. isCompatible(): boolean;
  38. /**
  39. * The name of the native xr feature name, if applicable (like anchor, hit-test, or hand-tracking)
  40. */
  41. xrNativeFeatureName?: string;
  42. /**
  43. * A list of (Babylon WebXR) features this feature depends on
  44. */
  45. dependsOn?: string[];
  46. }
  47. /**
  48. * A list of the currently available features without referencing them
  49. */
  50. export class WebXRFeatureName {
  51. /**
  52. * The name of the anchor system feature
  53. */
  54. public static readonly ANCHOR_SYSTEM = "xr-anchor-system";
  55. /**
  56. * The name of the background remover feature
  57. */
  58. public static readonly BACKGROUND_REMOVER = "xr-background-remover";
  59. /**
  60. * The name of the hit test feature
  61. */
  62. public static readonly HIT_TEST = "xr-hit-test";
  63. /**
  64. * physics impostors for xr controllers feature
  65. */
  66. public static readonly PHYSICS_CONTROLLERS = "xr-physics-controller";
  67. /**
  68. * The name of the plane detection feature
  69. */
  70. public static readonly PLANE_DETECTION = "xr-plane-detection";
  71. /**
  72. * The name of the pointer selection feature
  73. */
  74. public static readonly POINTER_SELECTION = "xr-controller-pointer-selection";
  75. /**
  76. * The name of the teleportation feature
  77. */
  78. public static readonly TELEPORTATION = "xr-controller-teleportation";
  79. /**
  80. * The name of the feature points feature.
  81. */
  82. public static readonly FEATURE_POINTS = "xr-feature-points";
  83. /**
  84. * The name of the hand tracking feature.
  85. */
  86. public static readonly HAND_TRACKING = "xr-hand-tracking";
  87. }
  88. /**
  89. * Defining the constructor of a feature. Used to register the modules.
  90. */
  91. export type WebXRFeatureConstructor = (xrSessionManager: WebXRSessionManager, options?: any) => () => IWebXRFeature;
  92. /**
  93. * The WebXR features manager is responsible of enabling or disabling features required for the current XR session.
  94. * It is mainly used in AR sessions.
  95. *
  96. * A feature can have a version that is defined by Babylon (and does not correspond with the webxr version).
  97. */
  98. export class WebXRFeaturesManager implements IDisposable {
  99. private static readonly _AvailableFeatures: {
  100. [name: string]: {
  101. stable: number;
  102. latest: number;
  103. [version: number]: WebXRFeatureConstructor;
  104. };
  105. } = {};
  106. private _features: {
  107. [name: string]: {
  108. featureImplementation: IWebXRFeature;
  109. version: number;
  110. enabled: boolean;
  111. required: boolean;
  112. };
  113. } = {};
  114. /**
  115. * constructs a new features manages.
  116. *
  117. * @param _xrSessionManager an instance of WebXRSessionManager
  118. */
  119. constructor(private _xrSessionManager: WebXRSessionManager) {
  120. // when session starts / initialized - attach
  121. this._xrSessionManager.onXRSessionInit.add(() => {
  122. this.getEnabledFeatures().forEach((featureName) => {
  123. const feature = this._features[featureName];
  124. if (feature.enabled && !feature.featureImplementation.attached && !feature.featureImplementation.disableAutoAttach) {
  125. this.attachFeature(featureName);
  126. }
  127. });
  128. });
  129. // when session ends - detach
  130. this._xrSessionManager.onXRSessionEnded.add(() => {
  131. this.getEnabledFeatures().forEach((featureName) => {
  132. const feature = this._features[featureName];
  133. if (feature.enabled && feature.featureImplementation.attached) {
  134. // detach, but don't disable!
  135. this.detachFeature(featureName);
  136. }
  137. });
  138. });
  139. }
  140. /**
  141. * Used to register a module. After calling this function a developer can use this feature in the scene.
  142. * Mainly used internally.
  143. *
  144. * @param featureName the name of the feature to register
  145. * @param constructorFunction the function used to construct the module
  146. * @param version the (babylon) version of the module
  147. * @param stable is that a stable version of this module
  148. */
  149. public static AddWebXRFeature(featureName: string, constructorFunction: WebXRFeatureConstructor, version: number = 1, stable: boolean = false) {
  150. this._AvailableFeatures[featureName] = this._AvailableFeatures[featureName] || { latest: version };
  151. if (version > this._AvailableFeatures[featureName].latest) {
  152. this._AvailableFeatures[featureName].latest = version;
  153. }
  154. if (stable) {
  155. this._AvailableFeatures[featureName].stable = version;
  156. }
  157. this._AvailableFeatures[featureName][version] = constructorFunction;
  158. }
  159. /**
  160. * Returns a constructor of a specific feature.
  161. *
  162. * @param featureName the name of the feature to construct
  163. * @param version the version of the feature to load
  164. * @param xrSessionManager the xrSessionManager. Used to construct the module
  165. * @param options optional options provided to the module.
  166. * @returns a function that, when called, will return a new instance of this feature
  167. */
  168. public static ConstructFeature(featureName: string, version: number = 1, xrSessionManager: WebXRSessionManager, options?: any): () => IWebXRFeature {
  169. const constructorFunction = this._AvailableFeatures[featureName][version];
  170. if (!constructorFunction) {
  171. // throw an error? return nothing?
  172. throw new Error("feature not found");
  173. }
  174. return constructorFunction(xrSessionManager, options);
  175. }
  176. /**
  177. * Can be used to return the list of features currently registered
  178. *
  179. * @returns an Array of available features
  180. */
  181. public static GetAvailableFeatures() {
  182. return Object.keys(this._AvailableFeatures);
  183. }
  184. /**
  185. * Gets the versions available for a specific feature
  186. * @param featureName the name of the feature
  187. * @returns an array with the available versions
  188. */
  189. public static GetAvailableVersions(featureName: string) {
  190. return Object.keys(this._AvailableFeatures[featureName]);
  191. }
  192. /**
  193. * Return the latest unstable version of this feature
  194. * @param featureName the name of the feature to search
  195. * @returns the version number. if not found will return -1
  196. */
  197. public static GetLatestVersionOfFeature(featureName: string): number {
  198. return (this._AvailableFeatures[featureName] && this._AvailableFeatures[featureName].latest) || -1;
  199. }
  200. /**
  201. * Return the latest stable version of this feature
  202. * @param featureName the name of the feature to search
  203. * @returns the version number. if not found will return -1
  204. */
  205. public static GetStableVersionOfFeature(featureName: string): number {
  206. return (this._AvailableFeatures[featureName] && this._AvailableFeatures[featureName].stable) || -1;
  207. }
  208. /**
  209. * Attach a feature to the current session. Mainly used when session started to start the feature effect.
  210. * Can be used during a session to start a feature
  211. * @param featureName the name of feature to attach
  212. */
  213. public attachFeature(featureName: string) {
  214. const feature = this._features[featureName];
  215. if (feature && feature.enabled && !feature.featureImplementation.attached) {
  216. feature.featureImplementation.attach();
  217. }
  218. }
  219. /**
  220. * Can be used inside a session or when the session ends to detach a specific feature
  221. * @param featureName the name of the feature to detach
  222. */
  223. public detachFeature(featureName: string) {
  224. const feature = this._features[featureName];
  225. if (feature && feature.featureImplementation.attached) {
  226. feature.featureImplementation.detach();
  227. }
  228. }
  229. /**
  230. * Used to disable an already-enabled feature
  231. * The feature will be disposed and will be recreated once enabled.
  232. * @param featureName the feature to disable
  233. * @returns true if disable was successful
  234. */
  235. public disableFeature(featureName: string | { Name: string }): boolean {
  236. const name = typeof featureName === "string" ? featureName : featureName.Name;
  237. const feature = this._features[name];
  238. if (feature && feature.enabled) {
  239. feature.enabled = false;
  240. this.detachFeature(name);
  241. feature.featureImplementation.dispose();
  242. return true;
  243. }
  244. return false;
  245. }
  246. /**
  247. * dispose this features manager
  248. */
  249. public dispose(): void {
  250. this.getEnabledFeatures().forEach((feature) => {
  251. this.disableFeature(feature);
  252. this._features[feature].featureImplementation.dispose();
  253. });
  254. }
  255. /**
  256. * Enable a feature using its name and a version. This will enable it in the scene, and will be responsible to attach it when the session starts.
  257. * If used twice, the old version will be disposed and a new one will be constructed. This way you can re-enable with different configuration.
  258. *
  259. * @param featureName the name of the feature to load or the class of the feature
  260. * @param version optional version to load. if not provided the latest version will be enabled
  261. * @param moduleOptions options provided to the module. Ses the module documentation / constructor
  262. * @param attachIfPossible if set to true (default) the feature will be automatically attached, if it is currently possible
  263. * @param required is this feature required to the app. If set to true the session init will fail if the feature is not available.
  264. * @returns a new constructed feature or throws an error if feature not found.
  265. */
  266. public enableFeature(featureName: string | { Name: string }, version: number | string = "latest", moduleOptions: any = {}, attachIfPossible: boolean = true, required: boolean = true): IWebXRFeature {
  267. const name = typeof featureName === "string" ? featureName : featureName.Name;
  268. let versionToLoad = 0;
  269. if (typeof version === "string") {
  270. if (!version) {
  271. throw new Error(`Error in provided version - ${name} (${version})`);
  272. }
  273. if (version === "stable") {
  274. versionToLoad = WebXRFeaturesManager.GetStableVersionOfFeature(name);
  275. } else if (version === "latest") {
  276. versionToLoad = WebXRFeaturesManager.GetLatestVersionOfFeature(name);
  277. } else {
  278. // try loading the number the string represents
  279. versionToLoad = +version;
  280. }
  281. if (versionToLoad === -1 || isNaN(versionToLoad)) {
  282. throw new Error(`feature not found - ${name} (${version})`);
  283. }
  284. } else {
  285. versionToLoad = version;
  286. }
  287. // check if already initialized
  288. const feature = this._features[name];
  289. const constructFunction = WebXRFeaturesManager.ConstructFeature(name, versionToLoad, this._xrSessionManager, moduleOptions);
  290. if (!constructFunction) {
  291. // report error?
  292. throw new Error(`feature not found - ${name}`);
  293. }
  294. /* If the feature is already enabled, detach and dispose it, and create a new one */
  295. if (feature) {
  296. this.disableFeature(name);
  297. }
  298. const constructed = constructFunction();
  299. if (constructed.dependsOn) {
  300. const dependentsFound = constructed.dependsOn.every((featureName) => !!this._features[featureName]);
  301. if (!dependentsFound) {
  302. throw new Error(`Dependant features missing. Make sure the following features are enabled - ${constructed.dependsOn.join(", ")}`);
  303. }
  304. }
  305. if (constructed.isCompatible()) {
  306. this._features[name] = {
  307. featureImplementation: constructed,
  308. enabled: true,
  309. version: versionToLoad,
  310. required,
  311. };
  312. if (attachIfPossible) {
  313. // if session started already, request and enable
  314. if (this._xrSessionManager.session && !feature.featureImplementation.attached) {
  315. // enable feature
  316. this.attachFeature(name);
  317. }
  318. } else {
  319. // disable auto-attach when session starts
  320. this._features[name].featureImplementation.disableAutoAttach = true;
  321. }
  322. return this._features[name].featureImplementation;
  323. } else {
  324. if (required) {
  325. throw new Error("required feature not compatible");
  326. } else {
  327. Tools.Warn(`Feature ${name} not compatible with the current environment/browser and was not enabled.`);
  328. return constructed;
  329. }
  330. }
  331. }
  332. /**
  333. * get the implementation of an enabled feature.
  334. * @param featureName the name of the feature to load
  335. * @returns the feature class, if found
  336. */
  337. public getEnabledFeature(featureName: string): IWebXRFeature {
  338. return this._features[featureName] && this._features[featureName].featureImplementation;
  339. }
  340. /**
  341. * Get the list of enabled features
  342. * @returns an array of enabled features
  343. */
  344. public getEnabledFeatures() {
  345. return Object.keys(this._features);
  346. }
  347. /**
  348. * This function will exten the session creation configuration object with enabled features.
  349. * If, for example, the anchors feature is enabled, it will be automatically added to the optional or required features list,
  350. * according to the defined "required" variable, provided during enableFeature call
  351. * @param xrSessionInit the xr Session init object to extend
  352. *
  353. * @returns an extended XRSessionInit object
  354. */
  355. public extendXRSessionInitObject(xrSessionInit: XRSessionInit): XRSessionInit {
  356. const enabledFeatures = this.getEnabledFeatures();
  357. enabledFeatures.forEach((featureName) => {
  358. const feature = this._features[featureName];
  359. const nativeName = feature.featureImplementation.xrNativeFeatureName;
  360. if (nativeName) {
  361. if (feature.required) {
  362. xrSessionInit.requiredFeatures = xrSessionInit.requiredFeatures || [];
  363. if (xrSessionInit.requiredFeatures.indexOf(nativeName) === -1) {
  364. xrSessionInit.requiredFeatures.push(nativeName);
  365. }
  366. } else {
  367. xrSessionInit.optionalFeatures = xrSessionInit.optionalFeatures || [];
  368. if (xrSessionInit.optionalFeatures.indexOf(nativeName) === -1) {
  369. xrSessionInit.optionalFeatures.push(nativeName);
  370. }
  371. }
  372. }
  373. });
  374. return xrSessionInit;
  375. }
  376. }