WebXRHitTest.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. import { WebXRFeaturesManager, WebXRFeatureName } from "../webXRFeaturesManager";
  2. import { WebXRSessionManager } from "../webXRSessionManager";
  3. import { Observable } from "../../Misc/observable";
  4. import { Vector3, Matrix, Quaternion } from "../../Maths/math.vector";
  5. import { WebXRAbstractFeature } from "./WebXRAbstractFeature";
  6. import { IWebXRLegacyHitTestOptions, IWebXRLegacyHitResult, IWebXRHitTestFeature } from "./WebXRHitTestLegacy";
  7. import { Tools } from "../../Misc/tools";
  8. import { Nullable } from "../../types";
  9. /**
  10. * Options used for hit testing (version 2)
  11. */
  12. export interface IWebXRHitTestOptions extends IWebXRLegacyHitTestOptions {
  13. /**
  14. * Do not create a permanent hit test. Will usually be used when only
  15. * transient inputs are needed.
  16. */
  17. disablePermanentHitTest?: boolean;
  18. /**
  19. * Enable transient (for example touch-based) hit test inspections
  20. */
  21. enableTransientHitTest?: boolean;
  22. /**
  23. * Offset ray for the permanent hit test
  24. */
  25. offsetRay?: Vector3;
  26. /**
  27. * Offset ray for the transient hit test
  28. */
  29. transientOffsetRay?: Vector3;
  30. /**
  31. * Instead of using viewer space for hit tests, use the reference space defined in the session manager
  32. */
  33. useReferenceSpace?: boolean;
  34. }
  35. /**
  36. * Interface defining the babylon result of hit-test
  37. */
  38. export interface IWebXRHitResult extends IWebXRLegacyHitResult {
  39. /**
  40. * The input source that generated this hit test (if transient)
  41. */
  42. inputSource?: XRInputSource;
  43. /**
  44. * Is this a transient hit test
  45. */
  46. isTransient?: boolean;
  47. /**
  48. * Position of the hit test result
  49. */
  50. position: Vector3;
  51. /**
  52. * Rotation of the hit test result
  53. */
  54. rotationQuaternion: Quaternion;
  55. /**
  56. * The native hit test result
  57. */
  58. xrHitResult: XRHitTestResult;
  59. }
  60. /**
  61. * The currently-working hit-test module.
  62. * Hit test (or Ray-casting) is used to interact with the real world.
  63. * For further information read here - https://github.com/immersive-web/hit-test
  64. *
  65. * Tested on chrome (mobile) 80.
  66. */
  67. export class WebXRHitTest extends WebXRAbstractFeature implements IWebXRHitTestFeature<IWebXRHitResult> {
  68. private _tmpMat: Matrix = new Matrix();
  69. private _tmpPos: Vector3 = new Vector3();
  70. private _tmpQuat: Quaternion = new Quaternion();
  71. private _transientXrHitTestSource: Nullable<XRTransientInputHitTestSource>;
  72. // in XR space z-forward is negative
  73. private _xrHitTestSource: Nullable<XRHitTestSource>;
  74. private initHitTestSource = (referenceSpace: XRReferenceSpace) => {
  75. if (!referenceSpace) {
  76. return;
  77. }
  78. const offsetRay = new XRRay(this.options.offsetRay || {});
  79. const options: XRHitTestOptionsInit = {
  80. space: this.options.useReferenceSpace ? referenceSpace : this._xrSessionManager.viewerReferenceSpace,
  81. offsetRay: offsetRay,
  82. };
  83. if (!options.space) {
  84. Tools.Warn("waiting for viewer reference space to initialize");
  85. return;
  86. }
  87. this._xrSessionManager.session.requestHitTestSource(options).then((hitTestSource) => {
  88. if (this._xrHitTestSource) {
  89. this._xrHitTestSource.cancel();
  90. }
  91. this._xrHitTestSource = hitTestSource;
  92. });
  93. };
  94. /**
  95. * The module's name
  96. */
  97. public static readonly Name = WebXRFeatureName.HIT_TEST;
  98. /**
  99. * The (Babylon) version of this module.
  100. * This is an integer representing the implementation version.
  101. * This number does not correspond to the WebXR specs version
  102. */
  103. public static readonly Version = 2;
  104. /**
  105. * When set to true, each hit test will have its own position/rotation objects
  106. * When set to false, position and rotation objects will be reused for each hit test. It is expected that
  107. * the developers will clone them or copy them as they see fit.
  108. */
  109. public autoCloneTransformation: boolean = false;
  110. /**
  111. * Triggered when new babylon (transformed) hit test results are available
  112. */
  113. public onHitTestResultObservable: Observable<IWebXRHitResult[]> = new Observable();
  114. /**
  115. * Use this to temporarily pause hit test checks.
  116. */
  117. public paused: boolean = false;
  118. /**
  119. * Creates a new instance of the hit test feature
  120. * @param _xrSessionManager an instance of WebXRSessionManager
  121. * @param options options to use when constructing this feature
  122. */
  123. constructor(
  124. _xrSessionManager: WebXRSessionManager,
  125. /**
  126. * options to use when constructing this feature
  127. */
  128. public readonly options: IWebXRHitTestOptions = {}
  129. ) {
  130. super(_xrSessionManager);
  131. Tools.Warn("Hit test is an experimental and unstable feature. make sure you enable optionalFeatures when creating the XR session");
  132. }
  133. /**
  134. * attach this feature
  135. * Will usually be called by the features manager
  136. *
  137. * @returns true if successful.
  138. */
  139. public attach(): boolean {
  140. if (!super.attach()) {
  141. return false;
  142. }
  143. if (!this.options.disablePermanentHitTest) {
  144. if (this._xrSessionManager.referenceSpace) {
  145. this.initHitTestSource(this._xrSessionManager.referenceSpace);
  146. }
  147. this._xrSessionManager.onXRReferenceSpaceChanged.add(this.initHitTestSource);
  148. }
  149. if (this.options.enableTransientHitTest) {
  150. const offsetRay = new XRRay(this.options.transientOffsetRay || {});
  151. this._xrSessionManager.session
  152. .requestHitTestSourceForTransientInput({
  153. profile: "generic-touchscreen",
  154. offsetRay,
  155. })
  156. .then((hitSource) => {
  157. this._transientXrHitTestSource = hitSource;
  158. });
  159. }
  160. return true;
  161. }
  162. /**
  163. * detach this feature.
  164. * Will usually be called by the features manager
  165. *
  166. * @returns true if successful.
  167. */
  168. public detach(): boolean {
  169. if (!super.detach()) {
  170. return false;
  171. }
  172. if (this._xrHitTestSource) {
  173. this._xrHitTestSource.cancel();
  174. this._xrHitTestSource = null;
  175. }
  176. this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this.initHitTestSource);
  177. if (this._transientXrHitTestSource) {
  178. this._transientXrHitTestSource.cancel();
  179. this._transientXrHitTestSource = null;
  180. }
  181. return true;
  182. }
  183. /**
  184. * Dispose this feature and all of the resources attached
  185. */
  186. public dispose(): void {
  187. super.dispose();
  188. this.onHitTestResultObservable.clear();
  189. }
  190. protected _onXRFrame(frame: XRFrame) {
  191. // make sure we do nothing if (async) not attached
  192. if (!this.attached || this.paused) {
  193. return;
  194. }
  195. if (this._xrHitTestSource) {
  196. const results = frame.getHitTestResults(this._xrHitTestSource);
  197. if (results.length) {
  198. this._processWebXRHitTestResult(results);
  199. }
  200. }
  201. if (this._transientXrHitTestSource) {
  202. let hitTestResultsPerInputSource = frame.getHitTestResultsForTransientInput(this._transientXrHitTestSource);
  203. hitTestResultsPerInputSource.forEach((resultsPerInputSource) => {
  204. if (resultsPerInputSource.results.length > 0) {
  205. this._processWebXRHitTestResult(resultsPerInputSource.results, resultsPerInputSource.inputSource);
  206. }
  207. });
  208. }
  209. }
  210. private _processWebXRHitTestResult(hitTestResults: XRHitTestResult[], inputSource?: XRInputSource) {
  211. const results: IWebXRHitResult[] = [];
  212. hitTestResults.forEach((hitTestResult) => {
  213. const pose = hitTestResult.getPose(this._xrSessionManager.referenceSpace);
  214. if (!pose) {
  215. return;
  216. }
  217. const pos = pose.transform.position;
  218. const quat = pose.transform.orientation;
  219. this._tmpPos.set(pos.x, pos.y, pos.z);
  220. this._tmpQuat.set(quat.x, quat.y, quat.z, quat.w);
  221. Matrix.FromFloat32ArrayToRefScaled(pose.transform.matrix, 0, 1, this._tmpMat);
  222. if (!this._xrSessionManager.scene.useRightHandedSystem) {
  223. this._tmpPos.z *= -1;
  224. this._tmpQuat.z *= -1;
  225. this._tmpQuat.w *= -1;
  226. this._tmpMat.toggleModelMatrixHandInPlace();
  227. }
  228. const result: IWebXRHitResult = {
  229. position: this.autoCloneTransformation ? this._tmpPos.clone() : this._tmpPos,
  230. rotationQuaternion: this.autoCloneTransformation ? this._tmpQuat.clone() : this._tmpQuat,
  231. transformationMatrix: this.autoCloneTransformation ? this._tmpMat.clone() : this._tmpMat,
  232. inputSource: inputSource,
  233. isTransient: !!inputSource,
  234. xrHitResult: hitTestResult,
  235. };
  236. results.push(result);
  237. });
  238. if (results.length) {
  239. this.onHitTestResultObservable.notifyObservers(results);
  240. }
  241. }
  242. }
  243. //register the plugin versions
  244. WebXRFeaturesManager.AddWebXRFeature(
  245. WebXRHitTest.Name,
  246. (xrSessionManager, options) => {
  247. return () => new WebXRHitTest(xrSessionManager, options);
  248. },
  249. WebXRHitTest.Version,
  250. false
  251. );