WebXRPlaneDetector.ts 7.4 KB

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