WebXRControllerPointerSelection.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. import { WebXRFeaturesManager, WebXRFeatureName } from "../webXRFeaturesManager";
  2. import { WebXRSessionManager } from '../webXRSessionManager';
  3. import { AbstractMesh } from '../../Meshes/abstractMesh';
  4. import { Observer } from '../../Misc/observable';
  5. import { WebXRInput } from '../webXRInput';
  6. import { WebXRInputSource } from '../webXRInputSource';
  7. import { Scene } from '../../scene';
  8. import { WebXRControllerComponent } from '../motionController/webXRControllerComponent';
  9. import { Nullable } from '../../types';
  10. import { Vector3 } from '../../Maths/math.vector';
  11. import { Color3 } from '../../Maths/math.color';
  12. import { Axis } from '../../Maths/math.axis';
  13. import { StandardMaterial } from '../../Materials/standardMaterial';
  14. import { CylinderBuilder } from '../../Meshes/Builders/cylinderBuilder';
  15. import { TorusBuilder } from '../../Meshes/Builders/torusBuilder';
  16. import { Ray } from '../../Culling/ray';
  17. import { PickingInfo } from '../../Collisions/pickingInfo';
  18. import { WebXRAbstractFeature } from './WebXRAbstractFeature';
  19. import { UtilityLayerRenderer } from '../../Rendering/utilityLayerRenderer';
  20. /**
  21. * Options interface for the pointer selection module
  22. */
  23. export interface IWebXRControllerPointerSelectionOptions {
  24. /**
  25. * the xr input to use with this pointer selection
  26. */
  27. xrInput: WebXRInput;
  28. /**
  29. * Different button type to use instead of the main component
  30. */
  31. overrideButtonId?: string;
  32. /**
  33. * The amount of time in miliseconds it takes between pick found something to a pointer down event.
  34. * Used in gaze modes. Tracked pointer uses the trigger, screen uses touch events
  35. * 3000 means 3 seconds between pointing at something and selecting it
  36. */
  37. timeToSelect?: number;
  38. /**
  39. * Disable the pointer up event when the xr controller in screen and gaze mode is disposed (meaning - when the user removed the finger from the screen)
  40. * If not disabled, the last picked point will be used to execute a pointer up event
  41. * If disabled, pointer up event will be triggered right after the pointer down event.
  42. * Used in screen and gaze target ray mode only
  43. */
  44. disablePointerUpOnTouchOut: boolean;
  45. /**
  46. * For gaze mode (time to select instead of press)
  47. */
  48. forceGazeMode: boolean;
  49. /**
  50. * Factor to be applied to the pointer-moved function in the gaze mode. How sensitive should the gaze mode be when checking if the pointer moved
  51. * to start a new countdown to the pointer down event.
  52. * Defaults to 1.
  53. */
  54. gazeModePointerMovedFactor?: number;
  55. /**
  56. * Should meshes created here be added to a utility layer or the main scene
  57. */
  58. useUtilityLayer?: boolean;
  59. /**
  60. * if provided, this scene will be used to render meshes.
  61. */
  62. customUtilityLayerScene?: Scene;
  63. /**
  64. * use this rendering group id for the meshes (optional)
  65. */
  66. renderingGroupId?: number;
  67. }
  68. /**
  69. * A module that will enable pointer selection for motion controllers of XR Input Sources
  70. */
  71. export class WebXRControllerPointerSelection extends WebXRAbstractFeature {
  72. /**
  73. * The module's name
  74. */
  75. public static readonly Name = WebXRFeatureName.POINTER_SELECTION;
  76. /**
  77. * The (Babylon) version of this module.
  78. * This is an integer representing the implementation version.
  79. * This number does not correspond to the webxr specs version
  80. */
  81. public static readonly Version = 1;
  82. /**
  83. * This color will be set to the laser pointer when selection is triggered
  84. */
  85. public laserPointerPickedColor: Color3 = new Color3(0.9, 0.9, 0.9);
  86. /**
  87. * This color will be applied to the selection ring when selection is triggered
  88. */
  89. public selectionMeshPickedColor: Color3 = new Color3(0.3, 0.3, 1.0);
  90. /**
  91. * default color of the selection ring
  92. */
  93. public selectionMeshDefaultColor: Color3 = new Color3(0.8, 0.8, 0.8);
  94. /**
  95. * Default color of the laser pointer
  96. */
  97. public lasterPointerDefaultColor: Color3 = new Color3(0.7, 0.7, 0.7);
  98. /**
  99. * Should the laser pointer be displayed
  100. */
  101. public displayLaserPointer: boolean = true;
  102. /**
  103. * Should the selection mesh be displayed (The ring at the end of the laser pointer)
  104. */
  105. public displaySelectionMesh: boolean = true;
  106. /**
  107. * Disable lighting on the laser pointer (so it will always be visible)
  108. */
  109. public disablePointerLighting: boolean = true;
  110. /**
  111. * Disable lighting on the selection mesh (so it will always be visible)
  112. */
  113. public disableSelectionMeshLighting: boolean = true;
  114. private static _idCounter = 0;
  115. private _controllers: {
  116. [controllerUniqueId: string]: {
  117. xrController: WebXRInputSource;
  118. selectionComponent?: WebXRControllerComponent;
  119. onButtonChangedObserver?: Nullable<Observer<WebXRControllerComponent>>;
  120. onFrameObserver?: Nullable<Observer<XRFrame>>;
  121. laserPointer: AbstractMesh;
  122. selectionMesh: AbstractMesh;
  123. meshUnderPointer: Nullable<AbstractMesh>;
  124. pick: Nullable<PickingInfo>;
  125. id: number;
  126. tmpRay: Ray;
  127. };
  128. } = {};
  129. private _scene: Scene;
  130. /**
  131. * constructs a new background remover module
  132. * @param _xrSessionManager the session manager for this module
  133. * @param _options read-only options to be used in this module
  134. */
  135. constructor(_xrSessionManager: WebXRSessionManager, private readonly _options: IWebXRControllerPointerSelectionOptions) {
  136. super(_xrSessionManager);
  137. this._scene = this._xrSessionManager.scene;
  138. }
  139. /**
  140. * attach this feature
  141. * Will usually be called by the features manager
  142. *
  143. * @returns true if successful.
  144. */
  145. attach(): boolean {
  146. if (!super.attach()) {
  147. return false;
  148. }
  149. this._options.xrInput.controllers.forEach(this._attachController);
  150. this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController);
  151. this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {
  152. // REMOVE the controller
  153. this._detachController(controller.uniqueId);
  154. });
  155. return true;
  156. }
  157. /**
  158. * detach this feature.
  159. * Will usually be called by the features manager
  160. *
  161. * @returns true if successful.
  162. */
  163. detach(): boolean {
  164. if (!super.detach()) {
  165. return false;
  166. }
  167. Object.keys(this._controllers).forEach((controllerId) => {
  168. this._detachController(controllerId);
  169. });
  170. return true;
  171. }
  172. /**
  173. * Get the xr controller that correlates to the pointer id in the pointer event
  174. *
  175. * @param id the pointer id to search for
  176. * @returns the controller that correlates to this id or null if not found
  177. */
  178. public getXRControllerByPointerId(id: number): Nullable<WebXRInputSource> {
  179. const keys = Object.keys(this._controllers);
  180. for (let i = 0; i < keys.length; ++i) {
  181. if (this._controllers[keys[i]].id === id) {
  182. return this._controllers[keys[i]].xrController;
  183. }
  184. }
  185. return null;
  186. }
  187. /**
  188. * Will get the mesh under a specific pointer.
  189. * `scene.meshUnderPointer` will only return one mesh - either left or right.
  190. * @param controllerId the controllerId to check
  191. * @returns The mesh under pointer or null if no mesh is under the pointer
  192. */
  193. public getMeshUnderPointer(controllerId: string): Nullable<AbstractMesh> {
  194. if (this._controllers[controllerId]) {
  195. return this._controllers[controllerId].meshUnderPointer;
  196. } else {
  197. return null;
  198. }
  199. }
  200. protected _onXRFrame(_xrFrame: XRFrame) {
  201. Object.keys(this._controllers).forEach((id) => {
  202. const controllerData = this._controllers[id];
  203. // Every frame check collisions/input
  204. controllerData.xrController.getWorldPointerRayToRef(controllerData.tmpRay);
  205. controllerData.pick = this._scene.pickWithRay(controllerData.tmpRay);
  206. const pick = controllerData.pick;
  207. if (pick && pick.pickedPoint && pick.hit) {
  208. // Update laser state
  209. this._updatePointerDistance(controllerData.laserPointer, pick.distance);
  210. // Update cursor state
  211. controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);
  212. controllerData.selectionMesh.scaling.x = Math.sqrt(pick.distance);
  213. controllerData.selectionMesh.scaling.y = Math.sqrt(pick.distance);
  214. controllerData.selectionMesh.scaling.z = Math.sqrt(pick.distance);
  215. // To avoid z-fighting
  216. let pickNormal = this._convertNormalToDirectionOfRay(pick.getNormal(true), controllerData.tmpRay);
  217. let deltaFighting = 0.001;
  218. controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);
  219. if (pickNormal) {
  220. let axis1 = Vector3.Cross(Axis.Y, pickNormal);
  221. let axis2 = Vector3.Cross(pickNormal, axis1);
  222. Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, controllerData.selectionMesh.rotation);
  223. controllerData.selectionMesh.position.addInPlace(pickNormal.scale(deltaFighting));
  224. }
  225. controllerData.selectionMesh.isVisible = true && this.displaySelectionMesh;
  226. controllerData.meshUnderPointer = pick.pickedMesh;
  227. } else {
  228. controllerData.selectionMesh.isVisible = false;
  229. controllerData.meshUnderPointer = null;
  230. }
  231. });
  232. }
  233. private _attachController = (xrController: WebXRInputSource) => {
  234. if (this._controllers[xrController.uniqueId]) {
  235. // already attached
  236. return;
  237. }
  238. // only support tracker pointer
  239. const { laserPointer, selectionMesh } = this._generateNewMeshPair(xrController);
  240. // get two new meshes
  241. this._controllers[xrController.uniqueId] = {
  242. xrController,
  243. laserPointer,
  244. selectionMesh,
  245. meshUnderPointer: null,
  246. pick: null,
  247. tmpRay: new Ray(new Vector3(), new Vector3()),
  248. id: WebXRControllerPointerSelection._idCounter++
  249. };
  250. switch (xrController.inputSource.targetRayMode) {
  251. case "tracked-pointer":
  252. return this._attachTrackedPointerRayMode(xrController);
  253. case "gaze":
  254. return this._attachGazeMode(xrController);
  255. case "screen":
  256. return this._attachScreenRayMode(xrController);
  257. }
  258. }
  259. private _attachScreenRayMode(xrController: WebXRInputSource) {
  260. const controllerData = this._controllers[xrController.uniqueId];
  261. let downTriggered = false;
  262. controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
  263. if (!controllerData.pick || (this._options.disablePointerUpOnTouchOut && downTriggered)) { return; }
  264. if (!downTriggered) {
  265. this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
  266. downTriggered = true;
  267. if (this._options.disablePointerUpOnTouchOut) {
  268. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  269. }
  270. } else {
  271. this._scene.simulatePointerMove(controllerData.pick, { pointerId: controllerData.id });
  272. }
  273. });
  274. xrController.onDisposeObservable.addOnce(() => {
  275. if (controllerData.pick && downTriggered && !this._options.disablePointerUpOnTouchOut) {
  276. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  277. }
  278. });
  279. }
  280. private _attachGazeMode(xrController: WebXRInputSource) {
  281. const controllerData = this._controllers[xrController.uniqueId];
  282. // attached when touched, detaches when raised
  283. const timeToSelect = this._options.timeToSelect || 3000;
  284. const sceneToRenderTo = this._options.useUtilityLayer ? (this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene) : this._scene;
  285. let oldPick = new PickingInfo();
  286. let discMesh = TorusBuilder.CreateTorus("selection", {
  287. diameter: 0.0035 * 15,
  288. thickness: 0.0025 * 6,
  289. tessellation: 20
  290. }, sceneToRenderTo);
  291. discMesh.isVisible = false;
  292. discMesh.isPickable = false;
  293. discMesh.parent = controllerData.selectionMesh;
  294. let timer = 0;
  295. let downTriggered = false;
  296. controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
  297. if (!controllerData.pick) { return; }
  298. discMesh.isVisible = false;
  299. if (controllerData.pick.hit) {
  300. if (!this._pickingMoved(oldPick, controllerData.pick)) {
  301. if (timer > timeToSelect / 10) {
  302. discMesh.isVisible = true;
  303. }
  304. timer += this._scene.getEngine().getDeltaTime();
  305. if (timer >= timeToSelect) {
  306. this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
  307. downTriggered = true;
  308. // pointer up right after down, if disable on touch out
  309. if (this._options.disablePointerUpOnTouchOut) {
  310. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  311. }
  312. discMesh.isVisible = false;
  313. } else {
  314. const scaleFactor = 1 - (timer / timeToSelect);
  315. discMesh.scaling.set(scaleFactor, scaleFactor, scaleFactor);
  316. }
  317. } else {
  318. if (downTriggered) {
  319. if (!this._options.disablePointerUpOnTouchOut) {
  320. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  321. }
  322. }
  323. downTriggered = false;
  324. timer = 0;
  325. }
  326. } else {
  327. downTriggered = false;
  328. timer = 0;
  329. }
  330. this._scene.simulatePointerMove(controllerData.pick, { pointerId: controllerData.id });
  331. oldPick = controllerData.pick;
  332. });
  333. if (this._options.renderingGroupId !== undefined) {
  334. discMesh.renderingGroupId = this._options.renderingGroupId;
  335. }
  336. xrController.onDisposeObservable.addOnce(() => {
  337. if (controllerData.pick && !this._options.disablePointerUpOnTouchOut && downTriggered) {
  338. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  339. }
  340. discMesh.dispose();
  341. });
  342. }
  343. private _tmpVectorForPickCompare = new Vector3();
  344. private _pickingMoved(oldPick: PickingInfo, newPick: PickingInfo) {
  345. if (!oldPick.hit || !newPick.hit) { return true; }
  346. if (!oldPick.pickedMesh || !oldPick.pickedPoint || !newPick.pickedMesh || !newPick.pickedPoint) { return true; }
  347. if (oldPick.pickedMesh !== newPick.pickedMesh) { return true; }
  348. oldPick.pickedPoint?.subtractToRef(newPick.pickedPoint, this._tmpVectorForPickCompare);
  349. this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x), Math.abs(this._tmpVectorForPickCompare.y), Math.abs(this._tmpVectorForPickCompare.z));
  350. const delta = (this._options.gazeModePointerMovedFactor || 1) * 0.01 / newPick.distance;
  351. const length = this._tmpVectorForPickCompare.length();
  352. if (length > delta) { return true; }
  353. return false;
  354. }
  355. private _attachTrackedPointerRayMode(xrController: WebXRInputSource) {
  356. xrController.onMotionControllerInitObservable.add((motionController) => {
  357. if (this._options.forceGazeMode) {
  358. return this._attachGazeMode(xrController);
  359. }
  360. const controllerData = this._controllers[xrController.uniqueId];
  361. if (this._options.overrideButtonId) {
  362. controllerData.selectionComponent = motionController.getComponent(this._options.overrideButtonId);
  363. }
  364. if (!controllerData.selectionComponent) {
  365. controllerData.selectionComponent = motionController.getMainComponent();
  366. }
  367. controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
  368. if (controllerData.selectionComponent && controllerData.selectionComponent.pressed) {
  369. (<StandardMaterial>controllerData.selectionMesh.material).emissiveColor = this.selectionMeshPickedColor;
  370. (<StandardMaterial>controllerData.laserPointer.material).emissiveColor = this.laserPointerPickedColor;
  371. } else {
  372. (<StandardMaterial>controllerData.selectionMesh.material).emissiveColor = this.selectionMeshDefaultColor;
  373. (<StandardMaterial>controllerData.laserPointer.material).emissiveColor = this.lasterPointerDefaultColor;
  374. }
  375. controllerData.laserPointer.isVisible = this.displayLaserPointer;
  376. (<StandardMaterial>controllerData.laserPointer.material).disableLighting = this.disablePointerLighting;
  377. (<StandardMaterial>controllerData.selectionMesh.material).disableLighting = this.disableSelectionMeshLighting;
  378. if (controllerData.pick) {
  379. this._scene.simulatePointerMove(controllerData.pick, { pointerId: controllerData.id });
  380. }
  381. });
  382. controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChangedObservable.add((component) => {
  383. if (component.changes.pressed) {
  384. const pressed = component.changes.pressed.current;
  385. if (controllerData.pick) {
  386. if (pressed) {
  387. this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
  388. } else {
  389. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  390. }
  391. }
  392. }
  393. });
  394. });
  395. }
  396. private _detachController(xrControllerUniqueId: string) {
  397. const controllerData = this._controllers[xrControllerUniqueId];
  398. if (!controllerData) { return; }
  399. if (controllerData.selectionComponent) {
  400. if (controllerData.onButtonChangedObserver) {
  401. controllerData.selectionComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver);
  402. }
  403. }
  404. if (controllerData.onFrameObserver) {
  405. this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver);
  406. }
  407. controllerData.selectionMesh.dispose();
  408. controllerData.laserPointer.dispose();
  409. // remove from the map
  410. delete this._controllers[xrControllerUniqueId];
  411. }
  412. private _generateNewMeshPair(xrController: WebXRInputSource) {
  413. const sceneToRenderTo = this._options.useUtilityLayer ? (this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene) : this._scene;
  414. const laserPointer = CylinderBuilder.CreateCylinder("laserPointer", {
  415. height: 1,
  416. diameterTop: 0.0002,
  417. diameterBottom: 0.004,
  418. tessellation: 20,
  419. subdivisions: 1
  420. }, sceneToRenderTo);
  421. laserPointer.parent = xrController.pointer;
  422. let laserPointerMaterial = new StandardMaterial("laserPointerMat", sceneToRenderTo);
  423. laserPointerMaterial.emissiveColor = this.lasterPointerDefaultColor;
  424. laserPointerMaterial.alpha = 0.7;
  425. laserPointer.material = laserPointerMaterial;
  426. laserPointer.rotation.x = Math.PI / 2;
  427. this._updatePointerDistance(laserPointer, 1);
  428. laserPointer.isPickable = false;
  429. // Create a gaze tracker for the XR controller
  430. const selectionMesh = TorusBuilder.CreateTorus("gazeTracker", {
  431. diameter: 0.0035 * 3,
  432. thickness: 0.0025 * 3,
  433. tessellation: 20
  434. }, sceneToRenderTo);
  435. selectionMesh.bakeCurrentTransformIntoVertices();
  436. selectionMesh.isPickable = false;
  437. selectionMesh.isVisible = false;
  438. let targetMat = new StandardMaterial("targetMat", sceneToRenderTo);
  439. targetMat.specularColor = Color3.Black();
  440. targetMat.emissiveColor = this.selectionMeshDefaultColor;
  441. targetMat.backFaceCulling = false;
  442. selectionMesh.material = targetMat;
  443. if (this._options.renderingGroupId !== undefined) {
  444. laserPointer.renderingGroupId = this._options.renderingGroupId;
  445. selectionMesh.renderingGroupId = this._options.renderingGroupId;
  446. }
  447. return {
  448. laserPointer,
  449. selectionMesh
  450. };
  451. }
  452. private _convertNormalToDirectionOfRay(normal: Nullable<Vector3>, ray: Ray) {
  453. if (normal) {
  454. let angle = Math.acos(Vector3.Dot(normal, ray.direction));
  455. if (angle < Math.PI / 2) {
  456. normal.scaleInPlace(-1);
  457. }
  458. }
  459. return normal;
  460. }
  461. private _updatePointerDistance(_laserPointer: AbstractMesh, distance: number = 100) {
  462. _laserPointer.scaling.y = distance;
  463. // a bit of distance from the controller
  464. _laserPointer.position.z = (distance / 2) + 0.05;
  465. }
  466. }
  467. //register the plugin
  468. WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPointerSelection.Name, (xrSessionManager, options) => {
  469. return () => new WebXRControllerPointerSelection(xrSessionManager, options);
  470. }, WebXRControllerPointerSelection.Version, true);