WebXRAbstractFeature.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { IWebXRFeature } from '../webXRFeaturesManager';
  2. import { Observer, Observable, EventState } from '../../../Misc/observable';
  3. import { Nullable } from '../../../types';
  4. import { WebXRSessionManager } from '../webXRSessionManager';
  5. export abstract class WebXRAbstractFeature implements IWebXRFeature {
  6. constructor(protected _xrSessionManager: WebXRSessionManager) {
  7. }
  8. private _attached: boolean = false;
  9. private _removeOnDetach: {
  10. observer: Nullable<Observer<any>>;
  11. observable: Observable<any>;
  12. }[] = [];
  13. /**
  14. * Is this feature attached
  15. */
  16. public get attached() {
  17. return this._attached;
  18. }
  19. /**
  20. * attach this feature
  21. *
  22. * @returns true if successful.
  23. */
  24. public attach(): boolean {
  25. this._attached = true;
  26. this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable, (frame) => this._onXRFrame(frame));
  27. return true;
  28. }
  29. /**
  30. * detach this feature.
  31. *
  32. * @returns true if successful.
  33. */
  34. public detach(): boolean {
  35. this._attached = false;
  36. this._removeOnDetach.forEach((toRemove) => {
  37. toRemove.observable.remove(toRemove.observer);
  38. });
  39. return true;
  40. }
  41. /**
  42. * Dispose this feature and all of the resources attached
  43. */
  44. public dispose(): void {
  45. this.detach();
  46. }
  47. /**
  48. * Code in this function will be executed on each xrFrame received from the browser.
  49. * This function will not execute after the feature is detached.
  50. * @param _xrFrame the current frame
  51. */
  52. protected _onXRFrame(_xrFrame: XRFrame): void {
  53. // no-op
  54. }
  55. /**
  56. * This is used to register callbacks that will automatically be removed when detach is called.
  57. * @param observable the observable to which the observer will be attached
  58. * @param callback the callback to register
  59. */
  60. protected _addNewAttachObserver<T>(observable: Observable<T>, callback: (eventData: T, eventState: EventState) => void) {
  61. this._removeOnDetach.push({
  62. observable,
  63. observer: observable.add(callback)
  64. });
  65. }
  66. }