WebXRPlaneDetector.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import { WebXRFeaturesManager, IWebXRFeature } from '../webXRFeaturesManager';
  2. import { TransformNode } from '../../../Meshes/transformNode';
  3. import { WebXRSessionManager } from '../webXRSessionManager';
  4. import { Observable, Observer } from '../../../Misc/observable';
  5. import { Vector3, Matrix } from '../../../Maths/math.vector';
  6. import { Nullable } from '../../../types';
  7. const Name = "xr-plane-detector";
  8. /**
  9. * Options used in the plane detector module
  10. */
  11. export interface IWebXRPlaneDetectorOptions {
  12. /**
  13. * The node to use to transform the local results to world coordinates
  14. */
  15. worldParentNode?: TransformNode;
  16. }
  17. /**
  18. * A babylon interface for a webxr plane.
  19. * A Plane is actually a polygon, built from N points in space
  20. */
  21. export interface IWebXRPlane {
  22. /**
  23. * a babylon-assigned ID for this polygon
  24. */
  25. id: number;
  26. /**
  27. * the native xr-plane object
  28. */
  29. xrPlane: XRPlane;
  30. /**
  31. * an array of vector3 points in babylon space. right/left hand system is taken into account.
  32. */
  33. polygonDefinition: Array<Vector3>;
  34. /**
  35. * A transformation matrix to apply on the mesh that will be built using the polygonDefinition
  36. * Local vs. World are decided if worldParentNode was provided or not in the options when constructing the module
  37. */
  38. transformationMatrix: Matrix;
  39. }
  40. let planeIdProvider = 0;
  41. /**
  42. * The plane detector is used to detect planes in the real world when in AR
  43. * For more information see https://github.com/immersive-web/real-world-geometry/
  44. */
  45. export class WebXRPlaneDetector implements IWebXRFeature {
  46. /**
  47. * The module's name
  48. */
  49. public static readonly Name = Name;
  50. /**
  51. * The (Babylon) version of this module.
  52. * This is an integer representing the implementation version.
  53. * This number does not correspond to the webxr specs version
  54. */
  55. public static readonly Version = 1;
  56. /**
  57. * Observers registered here will be executed when a new plane was added to the session
  58. */
  59. public onPlaneAddedObservable: Observable<IWebXRPlane> = new Observable();
  60. /**
  61. * Observers registered here will be executed when a plane is no longer detected in the session
  62. */
  63. public onPlaneRemovedObservable: Observable<IWebXRPlane> = new Observable();
  64. /**
  65. * Observers registered here will be executed when an existing plane updates (for example - expanded)
  66. * This can execute N times every frame
  67. */
  68. public onPlaneUpdatedObservable: Observable<IWebXRPlane> = new Observable();
  69. private _enabled: boolean = false;
  70. private _attached: boolean = false;
  71. private _detectedPlanes: Array<IWebXRPlane> = [];
  72. private _lastFrameDetected: XRPlaneSet = new Set();
  73. private _observerTracked: Nullable<Observer<XRFrame>>;
  74. /**
  75. * construct a new Plane Detector
  76. * @param _xrSessionManager an instance of xr Session manager
  77. * @param _options configuration to use when constructing this feature
  78. */
  79. constructor(private _xrSessionManager: WebXRSessionManager, private _options: IWebXRPlaneDetectorOptions = {}) {
  80. if (this._xrSessionManager.session) {
  81. this._xrSessionManager.session.updateWorldTrackingState({ planeDetectionState: { enabled: true } });
  82. this._enabled = true;
  83. } else {
  84. this._xrSessionManager.onXRSessionInit.addOnce(() => {
  85. this._xrSessionManager.session.updateWorldTrackingState({ planeDetectionState: { enabled: true } });
  86. this._enabled = true;
  87. });
  88. }
  89. }
  90. /**
  91. * attach this feature
  92. * Will usually be called by the features manager
  93. *
  94. * @returns true if successful.
  95. */
  96. attach(): boolean {
  97. this._observerTracked = this._xrSessionManager.onXRFrameObservable.add(() => {
  98. const frame = this._xrSessionManager.currentFrame;
  99. if (!this._attached || !this._enabled || !frame) { return; }
  100. // const timestamp = this.xrSessionManager.currentTimestamp;
  101. const detectedPlanes = frame.worldInformation.detectedPlanes;
  102. if (detectedPlanes && detectedPlanes.size) {
  103. this._detectedPlanes.filter((plane) => !detectedPlanes.has(plane.xrPlane)).map((plane) => {
  104. const index = this._detectedPlanes.indexOf(plane);
  105. this._detectedPlanes.splice(index, 1);
  106. this.onPlaneRemovedObservable.notifyObservers(plane);
  107. });
  108. // now check for new ones
  109. detectedPlanes.forEach((xrPlane) => {
  110. if (!this._lastFrameDetected.has(xrPlane)) {
  111. const newPlane: Partial<IWebXRPlane> = {
  112. id: planeIdProvider++,
  113. xrPlane: xrPlane,
  114. polygonDefinition: []
  115. };
  116. const plane = this._updatePlaneWithXRPlane(xrPlane, newPlane, frame);
  117. this._detectedPlanes.push(plane);
  118. this.onPlaneAddedObservable.notifyObservers(plane);
  119. } else {
  120. // updated?
  121. if (xrPlane.lastChangedTime === this._xrSessionManager.currentTimestamp) {
  122. let index = this.findIndexInPlaneArray(xrPlane);
  123. const plane = this._detectedPlanes[index];
  124. this._updatePlaneWithXRPlane(xrPlane, plane, frame);
  125. this.onPlaneUpdatedObservable.notifyObservers(plane);
  126. }
  127. }
  128. });
  129. this._lastFrameDetected = detectedPlanes;
  130. }
  131. });
  132. this._attached = true;
  133. return true;
  134. }
  135. /**
  136. * detach this feature.
  137. * Will usually be called by the features manager
  138. *
  139. * @returns true if successful.
  140. */
  141. detach(): boolean {
  142. this._attached = false;
  143. if (this._observerTracked) {
  144. this._xrSessionManager.onXRFrameObservable.remove(this._observerTracked);
  145. }
  146. return true;
  147. }
  148. /**
  149. * Dispose this feature and all of the resources attached
  150. */
  151. dispose(): void {
  152. this.detach();
  153. this.onPlaneAddedObservable.clear();
  154. this.onPlaneRemovedObservable.clear();
  155. this.onPlaneUpdatedObservable.clear();
  156. }
  157. private _updatePlaneWithXRPlane(xrPlane: XRPlane, plane: Partial<IWebXRPlane>, xrFrame: XRFrame): IWebXRPlane {
  158. plane.polygonDefinition = xrPlane.polygon.map((xrPoint) => {
  159. const rightHandedSystem = this._xrSessionManager.scene.useRightHandedSystem ? 1 : -1;
  160. return new Vector3(xrPoint.x, xrPoint.y, xrPoint.z * rightHandedSystem);
  161. });
  162. // matrix
  163. const pose = xrFrame.getPose(xrPlane.planeSpace, this._xrSessionManager.referenceSpace);
  164. if (pose) {
  165. const mat = plane.transformationMatrix || new Matrix();
  166. Matrix.FromArrayToRef(pose.transform.matrix, 0, mat);
  167. if (!this._xrSessionManager.scene.useRightHandedSystem) {
  168. mat.toggleModelMatrixHandInPlace();
  169. }
  170. plane.transformationMatrix = mat;
  171. if (this._options.worldParentNode) {
  172. mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat);
  173. }
  174. }
  175. return <IWebXRPlane>plane;
  176. }
  177. /**
  178. * avoiding using Array.find for global support.
  179. * @param xrPlane the plane to find in the array
  180. */
  181. private findIndexInPlaneArray(xrPlane: XRPlane) {
  182. for (let i = 0; i < this._detectedPlanes.length; ++i) {
  183. if (this._detectedPlanes[i].xrPlane === xrPlane) {
  184. return i;
  185. }
  186. }
  187. return -1;
  188. }
  189. }
  190. //register the plugin
  191. WebXRFeaturesManager.AddWebXRFeature(WebXRPlaneDetector.Name, (xrSessionManager, options) => {
  192. return () => new WebXRPlaneDetector(xrSessionManager, options);
  193. }, WebXRPlaneDetector.Version);