WebXRPlaneDetector.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 _attached: boolean = false;
  70. /**
  71. * Is this feature attached
  72. */
  73. public get attached() {
  74. return this._attached;
  75. }
  76. private _enabled: boolean = false;
  77. private _detectedPlanes: Array<IWebXRPlane> = [];
  78. private _lastFrameDetected: XRPlaneSet = new Set();
  79. private _observerTracked: Nullable<Observer<XRFrame>>;
  80. /**
  81. * construct a new Plane Detector
  82. * @param _xrSessionManager an instance of xr Session manager
  83. * @param _options configuration to use when constructing this feature
  84. */
  85. constructor(private _xrSessionManager: WebXRSessionManager, private _options: IWebXRPlaneDetectorOptions = {}) {
  86. if (this._xrSessionManager.session) {
  87. this._xrSessionManager.session.updateWorldTrackingState({ planeDetectionState: { enabled: true } });
  88. this._enabled = true;
  89. } else {
  90. this._xrSessionManager.onXRSessionInit.addOnce(() => {
  91. this._xrSessionManager.session.updateWorldTrackingState({ planeDetectionState: { enabled: true } });
  92. this._enabled = true;
  93. });
  94. }
  95. }
  96. /**
  97. * attach this feature
  98. * Will usually be called by the features manager
  99. *
  100. * @returns true if successful.
  101. */
  102. attach(): boolean {
  103. this._observerTracked = this._xrSessionManager.onXRFrameObservable.add(() => {
  104. const frame = this._xrSessionManager.currentFrame;
  105. if (!this._attached || !this._enabled || !frame) { return; }
  106. // const timestamp = this.xrSessionManager.currentTimestamp;
  107. const detectedPlanes = frame.worldInformation.detectedPlanes;
  108. if (detectedPlanes && detectedPlanes.size) {
  109. this._detectedPlanes.filter((plane) => !detectedPlanes.has(plane.xrPlane)).map((plane) => {
  110. const index = this._detectedPlanes.indexOf(plane);
  111. this._detectedPlanes.splice(index, 1);
  112. this.onPlaneRemovedObservable.notifyObservers(plane);
  113. });
  114. // now check for new ones
  115. detectedPlanes.forEach((xrPlane) => {
  116. if (!this._lastFrameDetected.has(xrPlane)) {
  117. const newPlane: Partial<IWebXRPlane> = {
  118. id: planeIdProvider++,
  119. xrPlane: xrPlane,
  120. polygonDefinition: []
  121. };
  122. const plane = this._updatePlaneWithXRPlane(xrPlane, newPlane, frame);
  123. this._detectedPlanes.push(plane);
  124. this.onPlaneAddedObservable.notifyObservers(plane);
  125. } else {
  126. // updated?
  127. if (xrPlane.lastChangedTime === this._xrSessionManager.currentTimestamp) {
  128. let index = this.findIndexInPlaneArray(xrPlane);
  129. const plane = this._detectedPlanes[index];
  130. this._updatePlaneWithXRPlane(xrPlane, plane, frame);
  131. this.onPlaneUpdatedObservable.notifyObservers(plane);
  132. }
  133. }
  134. });
  135. this._lastFrameDetected = detectedPlanes;
  136. }
  137. });
  138. this._attached = true;
  139. return true;
  140. }
  141. /**
  142. * detach this feature.
  143. * Will usually be called by the features manager
  144. *
  145. * @returns true if successful.
  146. */
  147. detach(): boolean {
  148. this._attached = false;
  149. if (this._observerTracked) {
  150. this._xrSessionManager.onXRFrameObservable.remove(this._observerTracked);
  151. }
  152. return true;
  153. }
  154. /**
  155. * Dispose this feature and all of the resources attached
  156. */
  157. dispose(): void {
  158. this.detach();
  159. this.onPlaneAddedObservable.clear();
  160. this.onPlaneRemovedObservable.clear();
  161. this.onPlaneUpdatedObservable.clear();
  162. }
  163. private _updatePlaneWithXRPlane(xrPlane: XRPlane, plane: Partial<IWebXRPlane>, xrFrame: XRFrame): IWebXRPlane {
  164. plane.polygonDefinition = xrPlane.polygon.map((xrPoint) => {
  165. const rightHandedSystem = this._xrSessionManager.scene.useRightHandedSystem ? 1 : -1;
  166. return new Vector3(xrPoint.x, xrPoint.y, xrPoint.z * rightHandedSystem);
  167. });
  168. // matrix
  169. const pose = xrFrame.getPose(xrPlane.planeSpace, this._xrSessionManager.referenceSpace);
  170. if (pose) {
  171. const mat = plane.transformationMatrix || new Matrix();
  172. Matrix.FromArrayToRef(pose.transform.matrix, 0, mat);
  173. if (!this._xrSessionManager.scene.useRightHandedSystem) {
  174. mat.toggleModelMatrixHandInPlace();
  175. }
  176. plane.transformationMatrix = mat;
  177. if (this._options.worldParentNode) {
  178. mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat);
  179. }
  180. }
  181. return <IWebXRPlane>plane;
  182. }
  183. /**
  184. * avoiding using Array.find for global support.
  185. * @param xrPlane the plane to find in the array
  186. */
  187. private findIndexInPlaneArray(xrPlane: XRPlane) {
  188. for (let i = 0; i < this._detectedPlanes.length; ++i) {
  189. if (this._detectedPlanes[i].xrPlane === xrPlane) {
  190. return i;
  191. }
  192. }
  193. return -1;
  194. }
  195. }
  196. //register the plugin
  197. WebXRFeaturesManager.AddWebXRFeature(WebXRPlaneDetector.Name, (xrSessionManager, options) => {
  198. return () => new WebXRPlaneDetector(xrSessionManager, options);
  199. }, WebXRPlaneDetector.Version);