WebXRPlaneDetector.ts 7.2 KB

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