WebXRControllerPointerSelection.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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. */
  192. public getMeshUnderPointer(controllerId: string): Nullable<AbstractMesh> {
  193. if (this._controllers[controllerId]) {
  194. return this._controllers[controllerId].meshUnderPointer;
  195. } else {
  196. return null;
  197. }
  198. }
  199. protected _onXRFrame(_xrFrame: XRFrame) {
  200. Object.keys(this._controllers).forEach((id) => {
  201. const controllerData = this._controllers[id];
  202. // Every frame check collisions/input
  203. controllerData.xrController.getWorldPointerRayToRef(controllerData.tmpRay);
  204. controllerData.pick = this._scene.pickWithRay(controllerData.tmpRay);
  205. const pick = controllerData.pick;
  206. if (pick && pick.pickedPoint && pick.hit) {
  207. // Update laser state
  208. this._updatePointerDistance(controllerData.laserPointer, pick.distance);
  209. // Update cursor state
  210. controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);
  211. controllerData.selectionMesh.scaling.x = Math.sqrt(pick.distance);
  212. controllerData.selectionMesh.scaling.y = Math.sqrt(pick.distance);
  213. controllerData.selectionMesh.scaling.z = Math.sqrt(pick.distance);
  214. // To avoid z-fighting
  215. let pickNormal = this._convertNormalToDirectionOfRay(pick.getNormal(true), controllerData.tmpRay);
  216. let deltaFighting = 0.001;
  217. controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);
  218. if (pickNormal) {
  219. let axis1 = Vector3.Cross(Axis.Y, pickNormal);
  220. let axis2 = Vector3.Cross(pickNormal, axis1);
  221. Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, controllerData.selectionMesh.rotation);
  222. controllerData.selectionMesh.position.addInPlace(pickNormal.scale(deltaFighting));
  223. }
  224. controllerData.selectionMesh.isVisible = true && this.displaySelectionMesh;
  225. controllerData.meshUnderPointer = pick.pickedMesh;
  226. } else {
  227. controllerData.selectionMesh.isVisible = false;
  228. controllerData.meshUnderPointer = null;
  229. }
  230. });
  231. }
  232. private _attachController = (xrController: WebXRInputSource) => {
  233. if (this._controllers[xrController.uniqueId]) {
  234. // already attached
  235. return;
  236. }
  237. // only support tracker pointer
  238. const { laserPointer, selectionMesh } = this._generateNewMeshPair(xrController);
  239. // get two new meshes
  240. this._controllers[xrController.uniqueId] = {
  241. xrController,
  242. laserPointer,
  243. selectionMesh,
  244. meshUnderPointer: null,
  245. pick: null,
  246. tmpRay: new Ray(new Vector3(), new Vector3()),
  247. id: WebXRControllerPointerSelection._idCounter++
  248. };
  249. switch (xrController.inputSource.targetRayMode) {
  250. case "tracked-pointer":
  251. return this._attachTrackedPointerRayMode(xrController);
  252. case "gaze":
  253. return this._attachGazeMode(xrController);
  254. case "screen":
  255. return this._attachScreenRayMode(xrController);
  256. }
  257. }
  258. private _attachScreenRayMode(xrController: WebXRInputSource) {
  259. const controllerData = this._controllers[xrController.uniqueId];
  260. let downTriggered = false;
  261. controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
  262. if (!controllerData.pick || (this._options.disablePointerUpOnTouchOut && downTriggered)) { return; }
  263. if (!downTriggered) {
  264. this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
  265. downTriggered = true;
  266. if (this._options.disablePointerUpOnTouchOut) {
  267. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  268. }
  269. } else {
  270. this._scene.simulatePointerMove(controllerData.pick, { pointerId: controllerData.id });
  271. }
  272. });
  273. xrController.onDisposeObservable.addOnce(() => {
  274. if (controllerData.pick && downTriggered && !this._options.disablePointerUpOnTouchOut) {
  275. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  276. }
  277. });
  278. }
  279. private _attachGazeMode(xrController: WebXRInputSource) {
  280. const controllerData = this._controllers[xrController.uniqueId];
  281. // attached when touched, detaches when raised
  282. const timeToSelect = this._options.timeToSelect || 3000;
  283. const sceneToRenderTo = this._options.useUtilityLayer ? (this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene) : this._scene;
  284. let oldPick = new PickingInfo();
  285. let discMesh = TorusBuilder.CreateTorus("selection", {
  286. diameter: 0.0035 * 15,
  287. thickness: 0.0025 * 6,
  288. tessellation: 20
  289. }, sceneToRenderTo);
  290. discMesh.isVisible = false;
  291. discMesh.isPickable = false;
  292. discMesh.parent = controllerData.selectionMesh;
  293. let timer = 0;
  294. let downTriggered = false;
  295. controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
  296. if (!controllerData.pick) { return; }
  297. discMesh.isVisible = false;
  298. if (controllerData.pick.hit) {
  299. if (!this._pickingMoved(oldPick, controllerData.pick)) {
  300. if (timer > timeToSelect / 10) {
  301. discMesh.isVisible = true;
  302. }
  303. timer += this._scene.getEngine().getDeltaTime();
  304. if (timer >= timeToSelect) {
  305. this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
  306. downTriggered = true;
  307. // pointer up right after down, if disable on touch out
  308. if (this._options.disablePointerUpOnTouchOut) {
  309. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  310. }
  311. discMesh.isVisible = false;
  312. } else {
  313. const scaleFactor = 1 - (timer / timeToSelect);
  314. discMesh.scaling.set(scaleFactor, scaleFactor, scaleFactor);
  315. }
  316. } else {
  317. if (downTriggered) {
  318. if (!this._options.disablePointerUpOnTouchOut) {
  319. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  320. }
  321. }
  322. downTriggered = false;
  323. timer = 0;
  324. }
  325. } else {
  326. downTriggered = false;
  327. timer = 0;
  328. }
  329. this._scene.simulatePointerMove(controllerData.pick, { pointerId: controllerData.id });
  330. oldPick = controllerData.pick;
  331. });
  332. if (this._options.renderingGroupId !== undefined) {
  333. discMesh.renderingGroupId = this._options.renderingGroupId;
  334. }
  335. xrController.onDisposeObservable.addOnce(() => {
  336. if (controllerData.pick && !this._options.disablePointerUpOnTouchOut && downTriggered) {
  337. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  338. }
  339. discMesh.dispose();
  340. });
  341. }
  342. private _tmpVectorForPickCompare = new Vector3();
  343. private _pickingMoved(oldPick: PickingInfo, newPick: PickingInfo) {
  344. if (!oldPick.hit || !newPick.hit) { return true; }
  345. if (!oldPick.pickedMesh || !oldPick.pickedPoint || !newPick.pickedMesh || !newPick.pickedPoint) { return true; }
  346. if (oldPick.pickedMesh !== newPick.pickedMesh) { return true; }
  347. oldPick.pickedPoint?.subtractToRef(newPick.pickedPoint, this._tmpVectorForPickCompare);
  348. this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x), Math.abs(this._tmpVectorForPickCompare.y), Math.abs(this._tmpVectorForPickCompare.z));
  349. const delta = (this._options.gazeModePointerMovedFactor || 1) * 0.01 / newPick.distance;
  350. const length = this._tmpVectorForPickCompare.length();
  351. if (length > delta) { return true; }
  352. return false;
  353. }
  354. private _attachTrackedPointerRayMode(xrController: WebXRInputSource) {
  355. xrController.onMotionControllerInitObservable.add((motionController) => {
  356. if (this._options.forceGazeMode) {
  357. return this._attachGazeMode(xrController);
  358. }
  359. const controllerData = this._controllers[xrController.uniqueId];
  360. if (this._options.overrideButtonId) {
  361. controllerData.selectionComponent = motionController.getComponent(this._options.overrideButtonId);
  362. }
  363. if (!controllerData.selectionComponent) {
  364. controllerData.selectionComponent = motionController.getMainComponent();
  365. }
  366. controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
  367. if (controllerData.selectionComponent && controllerData.selectionComponent.pressed) {
  368. (<StandardMaterial>controllerData.selectionMesh.material).emissiveColor = this.selectionMeshPickedColor;
  369. (<StandardMaterial>controllerData.laserPointer.material).emissiveColor = this.laserPointerPickedColor;
  370. } else {
  371. (<StandardMaterial>controllerData.selectionMesh.material).emissiveColor = this.selectionMeshDefaultColor;
  372. (<StandardMaterial>controllerData.laserPointer.material).emissiveColor = this.lasterPointerDefaultColor;
  373. }
  374. controllerData.laserPointer.isVisible = this.displayLaserPointer;
  375. (<StandardMaterial>controllerData.laserPointer.material).disableLighting = this.disablePointerLighting;
  376. (<StandardMaterial>controllerData.selectionMesh.material).disableLighting = this.disableSelectionMeshLighting;
  377. if (controllerData.pick) {
  378. this._scene.simulatePointerMove(controllerData.pick, { pointerId: controllerData.id });
  379. }
  380. });
  381. controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChangedObservable.add((component) => {
  382. if (component.changes.pressed) {
  383. const pressed = component.changes.pressed.current;
  384. if (controllerData.pick) {
  385. if (pressed) {
  386. this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
  387. } else {
  388. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  389. }
  390. }
  391. }
  392. });
  393. });
  394. }
  395. private _detachController(xrControllerUniqueId: string) {
  396. const controllerData = this._controllers[xrControllerUniqueId];
  397. if (!controllerData) { return; }
  398. if (controllerData.selectionComponent) {
  399. if (controllerData.onButtonChangedObserver) {
  400. controllerData.selectionComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver);
  401. }
  402. }
  403. if (controllerData.onFrameObserver) {
  404. this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver);
  405. }
  406. controllerData.selectionMesh.dispose();
  407. controllerData.laserPointer.dispose();
  408. // remove from the map
  409. delete this._controllers[xrControllerUniqueId];
  410. }
  411. private _generateNewMeshPair(xrController: WebXRInputSource) {
  412. const sceneToRenderTo = this._options.useUtilityLayer ? (this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene) : this._scene;
  413. const laserPointer = CylinderBuilder.CreateCylinder("laserPointer", {
  414. height: 1,
  415. diameterTop: 0.0002,
  416. diameterBottom: 0.004,
  417. tessellation: 20,
  418. subdivisions: 1
  419. }, sceneToRenderTo);
  420. laserPointer.parent = xrController.pointer;
  421. let laserPointerMaterial = new StandardMaterial("laserPointerMat", sceneToRenderTo);
  422. laserPointerMaterial.emissiveColor = this.lasterPointerDefaultColor;
  423. laserPointerMaterial.alpha = 0.7;
  424. laserPointer.material = laserPointerMaterial;
  425. laserPointer.rotation.x = Math.PI / 2;
  426. this._updatePointerDistance(laserPointer, 1);
  427. laserPointer.isPickable = false;
  428. // Create a gaze tracker for the XR controller
  429. const selectionMesh = TorusBuilder.CreateTorus("gazeTracker", {
  430. diameter: 0.0035 * 3,
  431. thickness: 0.0025 * 3,
  432. tessellation: 20
  433. }, sceneToRenderTo);
  434. selectionMesh.bakeCurrentTransformIntoVertices();
  435. selectionMesh.isPickable = false;
  436. selectionMesh.isVisible = false;
  437. let targetMat = new StandardMaterial("targetMat", sceneToRenderTo);
  438. targetMat.specularColor = Color3.Black();
  439. targetMat.emissiveColor = this.selectionMeshDefaultColor;
  440. targetMat.backFaceCulling = false;
  441. selectionMesh.material = targetMat;
  442. if (this._options.renderingGroupId !== undefined) {
  443. laserPointer.renderingGroupId = this._options.renderingGroupId;
  444. selectionMesh.renderingGroupId = this._options.renderingGroupId;
  445. }
  446. return {
  447. laserPointer,
  448. selectionMesh
  449. };
  450. }
  451. private _convertNormalToDirectionOfRay(normal: Nullable<Vector3>, ray: Ray) {
  452. if (normal) {
  453. let angle = Math.acos(Vector3.Dot(normal, ray.direction));
  454. if (angle < Math.PI / 2) {
  455. normal.scaleInPlace(-1);
  456. }
  457. }
  458. return normal;
  459. }
  460. private _updatePointerDistance(_laserPointer: AbstractMesh, distance: number = 100) {
  461. _laserPointer.scaling.y = distance;
  462. // a bit of distance from the controller
  463. _laserPointer.position.z = (distance / 2) + 0.05;
  464. }
  465. }
  466. //register the plugin
  467. WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPointerSelection.Name, (xrSessionManager, options) => {
  468. return () => new WebXRControllerPointerSelection(xrSessionManager, options);
  469. }, WebXRControllerPointerSelection.Version, true);