WebXRControllerPointerSelection.ts 20 KB

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