WebXRControllerPointerSelection.ts 23 KB

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