WebXRControllerPointerSelection.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. import { WebXRFeaturesManager, IWebXRFeature } 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 { WebXRController } from '../webXRController';
  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. const Name = "xr-controller-pointer-selection";
  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 implements IWebXRFeature {
  59. /**
  60. * The module's name
  61. */
  62. public static readonly Name = Name;
  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.7, 0.7, 0.7);
  73. /**
  74. * This color will be applied to the selection ring when selection is triggered
  75. */
  76. public selectionMeshPickedColor: Color3 = new Color3(0.7, 0.7, 0.7);
  77. /**
  78. * default color of the selection ring
  79. */
  80. public selectionMeshDefaultColor: Color3 = new Color3(0.5, 0.5, 0.5);
  81. /**
  82. * Default color of the laser pointer
  83. */
  84. public lasterPointerDefaultColor: Color3 = new Color3(0.5, 0.5, 0.5);
  85. private static _idCounter = 0;
  86. private _observerTracked: Nullable<Observer<XRFrame>>;
  87. private _observerControllerAdded: Nullable<Observer<WebXRController>>;
  88. private _observerControllerRemoved: Nullable<Observer<WebXRController>>;
  89. private _attached: boolean = false;
  90. private _tmpRay = new Ray(new Vector3(), new Vector3());
  91. private _controllers: {
  92. [controllerUniqueId: string]: {
  93. xrController: WebXRController;
  94. selectionComponent?: WebXRControllerComponent;
  95. onButtonChangedObserver?: Nullable<Observer<WebXRControllerComponent>>;
  96. onFrameObserver?: Nullable<Observer<XRFrame>>;
  97. laserPointer: AbstractMesh;
  98. selectionMesh: AbstractMesh;
  99. pick: Nullable<PickingInfo>;
  100. id: number;
  101. };
  102. } = {};
  103. /**
  104. * Is this feature attached
  105. */
  106. public get attached() {
  107. return this._attached;
  108. }
  109. private _scene: Scene;
  110. /**
  111. * constructs a new background remover module
  112. * @param _xrSessionManager the session manager for this module
  113. * @param _options read-only options to be used in this module
  114. */
  115. constructor(private _xrSessionManager: WebXRSessionManager, private readonly _options: IWebXRControllerPointerSelectionOptions) {
  116. this._scene = this._xrSessionManager.scene;
  117. }
  118. /**
  119. * attach this feature
  120. * Will usually be called by the features manager
  121. *
  122. * @returns true if successful.
  123. */
  124. attach(): boolean {
  125. this._options.xrInput.controllers.forEach(this._attachController);
  126. this._options.xrInput.onControllerAddedObservable.add(this._attachController);
  127. this._options.xrInput.onControllerRemovedObservable.add((controller) => {
  128. // REMOVE the controller
  129. this._detachController(controller.uniqueId);
  130. });
  131. this._observerTracked = this._xrSessionManager.onXRFrameObservable.add(() => {
  132. Object.keys(this._controllers).forEach((id) => {
  133. const controllerData = this._controllers[id];
  134. // Every frame check collisions/input
  135. controllerData.xrController.getWorldPointerRayToRef(this._tmpRay);
  136. controllerData.pick = this._scene.pickWithRay(this._tmpRay);
  137. const pick = controllerData.pick;
  138. if (pick && pick.pickedPoint && pick.hit) {
  139. // Update laser state
  140. this._updatePointerDistance(controllerData.laserPointer, pick.distance);
  141. // Update cursor state
  142. controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);
  143. controllerData.selectionMesh.scaling.x = Math.sqrt(pick.distance);
  144. controllerData.selectionMesh.scaling.y = Math.sqrt(pick.distance);
  145. controllerData.selectionMesh.scaling.z = Math.sqrt(pick.distance);
  146. // To avoid z-fighting
  147. let pickNormal = this._convertNormalToDirectionOfRay(pick.getNormal(true), this._tmpRay);
  148. let deltaFighting = 0.001;
  149. controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);
  150. if (pickNormal) {
  151. let axis1 = Vector3.Cross(Axis.Y, pickNormal);
  152. let axis2 = Vector3.Cross(pickNormal, axis1);
  153. Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, controllerData.selectionMesh.rotation);
  154. controllerData.selectionMesh.position.addInPlace(pickNormal.scale(deltaFighting));
  155. }
  156. controllerData.selectionMesh.isVisible = true;
  157. } else {
  158. controllerData.selectionMesh.isVisible = false;
  159. }
  160. });
  161. });
  162. this._attached = true;
  163. return true;
  164. }
  165. /**
  166. * detach this feature.
  167. * Will usually be called by the features manager
  168. *
  169. * @returns true if successful.
  170. */
  171. detach(): boolean {
  172. if (this._observerTracked) {
  173. this._xrSessionManager.onXRFrameObservable.remove(this._observerTracked);
  174. }
  175. Object.keys(this._controllers).forEach((controllerId) => {
  176. this._detachController(controllerId);
  177. });
  178. if (this._observerControllerAdded) {
  179. this._options.xrInput.onControllerAddedObservable.remove(this._observerControllerAdded);
  180. }
  181. if (this._observerControllerRemoved) {
  182. this._options.xrInput.onControllerRemovedObservable.remove(this._observerControllerRemoved);
  183. }
  184. this._attached = false;
  185. return true;
  186. }
  187. /**
  188. * Get the xr controller that correlates to the pointer id in the pointer event
  189. *
  190. * @param id the pointer id to search for
  191. * @returns the controller that correlates to this id or null if not found
  192. */
  193. public getXRControllerByPointerId(id: number): Nullable<WebXRController> {
  194. const keys = Object.keys(this._controllers);
  195. for (let i = 0; i < keys.length; ++i) {
  196. if (this._controllers[keys[i]].id === id) {
  197. return this._controllers[keys[i]].xrController;
  198. }
  199. }
  200. return null;
  201. }
  202. private _attachController = (xrController: WebXRController) => {
  203. if (this._controllers[xrController.uniqueId]) {
  204. // already attached
  205. return;
  206. }
  207. // only support tracker pointer
  208. const { laserPointer, selectionMesh } = this._generateNewMeshPair(xrController);
  209. // get two new meshes
  210. this._controllers[xrController.uniqueId] = {
  211. xrController,
  212. laserPointer,
  213. selectionMesh,
  214. pick: null,
  215. id: WebXRControllerPointerSelection._idCounter++
  216. };
  217. switch (xrController.inputSource.targetRayMode) {
  218. case "tracked-pointer":
  219. return this._attachTrackedPointerRayMode(xrController);
  220. case "gaze":
  221. return this._attachGazeMode(xrController);
  222. case "screen":
  223. return this._attachScreenRayMode(xrController);
  224. }
  225. }
  226. private _attachScreenRayMode(xrController: WebXRController) {
  227. const controllerData = this._controllers[xrController.uniqueId];
  228. let downTriggered = false;
  229. controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
  230. if (!controllerData.pick || (this._options.disablePointerUpOnTouchOut && downTriggered)) { return; }
  231. if (!downTriggered) {
  232. this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
  233. downTriggered = true;
  234. if (this._options.disablePointerUpOnTouchOut) {
  235. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  236. }
  237. } else {
  238. this._scene.simulatePointerMove(controllerData.pick, { pointerId: controllerData.id });
  239. }
  240. });
  241. xrController.onDisposeObservable.addOnce(() => {
  242. if (controllerData.pick && downTriggered && !this._options.disablePointerUpOnTouchOut) {
  243. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  244. }
  245. });
  246. }
  247. private _attachGazeMode(xrController: WebXRController) {
  248. const controllerData = this._controllers[xrController.uniqueId];
  249. // attached when touched, detaches when raised
  250. const timeToSelect = this._options.timeToSelect || 3000;
  251. let oldPick = new PickingInfo();
  252. let discMesh = TorusBuilder.CreateTorus("selection", {
  253. diameter: 0.0035 * 15,
  254. thickness: 0.0025 * 6,
  255. tessellation: 20
  256. }, this._scene);
  257. discMesh.isVisible = false;
  258. discMesh.isPickable = false;
  259. discMesh.parent = controllerData.selectionMesh;
  260. let timer = 0;
  261. let downTriggered = false;
  262. controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
  263. if (!controllerData.pick) { return; }
  264. discMesh.isVisible = false;
  265. if (controllerData.pick.hit) {
  266. if (!this._pickingMoved(oldPick, controllerData.pick)) {
  267. if (timer > timeToSelect / 10) {
  268. discMesh.isVisible = true;
  269. }
  270. timer += this._scene.getEngine().getDeltaTime();
  271. if (timer >= timeToSelect) {
  272. this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
  273. downTriggered = true;
  274. // pointer up right after down, if disable on touch out
  275. if (this._options.disablePointerUpOnTouchOut) {
  276. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  277. } else {
  278. this._scene.simulatePointerMove(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. oldPick = controllerData.pick;
  299. });
  300. xrController.onDisposeObservable.addOnce(() => {
  301. if (controllerData.pick && !this._options.disablePointerUpOnTouchOut && downTriggered) {
  302. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  303. }
  304. discMesh.dispose();
  305. });
  306. }
  307. private _tmpVectorForPickCompare = new Vector3();
  308. private _pickingMoved(oldPick: PickingInfo, newPick: PickingInfo) {
  309. if (!oldPick.hit || !newPick.hit) { return true; }
  310. if (!oldPick.pickedMesh || !oldPick.pickedPoint || !newPick.pickedMesh || !newPick.pickedPoint) { return true; }
  311. if (oldPick.pickedMesh !== newPick.pickedMesh) { return true; }
  312. oldPick.pickedPoint?.subtractToRef(newPick.pickedPoint, this._tmpVectorForPickCompare);
  313. this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x), Math.abs(this._tmpVectorForPickCompare.y), Math.abs(this._tmpVectorForPickCompare.z));
  314. const delta = (this._options.gazeModePointerMovedFactor || 1) * 0.01 / newPick.distance;
  315. const length = this._tmpVectorForPickCompare.length();
  316. if (length > delta) { return true; }
  317. return false;
  318. }
  319. private _attachTrackedPointerRayMode(xrController: WebXRController) {
  320. if (!xrController.gamepadController) {
  321. return;
  322. }
  323. if (this._options.forceGazeMode) {
  324. return this._attachGazeMode(xrController);
  325. }
  326. const controllerData = this._controllers[xrController.uniqueId];
  327. if (this._options.overrideButtonId) {
  328. controllerData.selectionComponent = xrController.gamepadController.getComponent(this._options.overrideButtonId);
  329. }
  330. if (!controllerData.selectionComponent) {
  331. controllerData.selectionComponent = xrController.gamepadController.getMainComponent();
  332. }
  333. let observer: Nullable<Observer<XRFrame>> = null;
  334. controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
  335. if (controllerData.selectionComponent && controllerData.selectionComponent.pressed) {
  336. (<StandardMaterial>controllerData.selectionMesh.material).emissiveColor = this.selectionMeshPickedColor;
  337. (<StandardMaterial>controllerData.laserPointer.material).emissiveColor = this.laserPointerPickedColor;
  338. } else {
  339. (<StandardMaterial>controllerData.selectionMesh.material).emissiveColor = this.selectionMeshDefaultColor;
  340. (<StandardMaterial>controllerData.laserPointer.material).emissiveColor = this.lasterPointerDefaultColor;
  341. }
  342. });
  343. controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChanged.add((component) => {
  344. if (component.changes.pressed) {
  345. const pressed = component.changes.pressed.current;
  346. if (controllerData.pick) {
  347. if (pressed) {
  348. this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
  349. observer = this._xrSessionManager.onXRFrameObservable.add(() => {
  350. if (controllerData.pick) {
  351. this._scene.simulatePointerMove(controllerData.pick, { pointerId: controllerData.id });
  352. }
  353. });
  354. } else {
  355. this._xrSessionManager.onXRFrameObservable.remove(observer);
  356. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  357. }
  358. }
  359. }
  360. });
  361. }
  362. private _detachController(xrControllerUniqueId: string) {
  363. const controllerData = this._controllers[xrControllerUniqueId];
  364. if (!controllerData) { return; }
  365. if (controllerData.selectionComponent) {
  366. if (controllerData.onButtonChangedObserver) {
  367. controllerData.selectionComponent.onButtonStateChanged.remove(controllerData.onButtonChangedObserver);
  368. }
  369. }
  370. if (controllerData.onFrameObserver) {
  371. this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver);
  372. }
  373. controllerData.selectionMesh.dispose();
  374. controllerData.laserPointer.dispose();
  375. // remove from the map
  376. delete this._controllers[xrControllerUniqueId];
  377. }
  378. private _generateNewMeshPair(xrController: WebXRController) {
  379. const laserPointer = CylinderBuilder.CreateCylinder("laserPointer", {
  380. height: 1,
  381. diameterTop: 0.0002,
  382. diameterBottom: 0.004,
  383. tessellation: 20,
  384. subdivisions: 1
  385. }, this._scene);
  386. laserPointer.parent = xrController.pointer;
  387. let laserPointerMaterial = new StandardMaterial("laserPointerMat", this._scene);
  388. laserPointerMaterial.emissiveColor = this.lasterPointerDefaultColor;
  389. laserPointerMaterial.alpha = 0.6;
  390. laserPointer.material = laserPointerMaterial;
  391. laserPointer.rotation.x = Math.PI / 2;
  392. this._updatePointerDistance(laserPointer, 1);
  393. laserPointer.isPickable = false;
  394. // Create a gaze tracker for the XR controller
  395. const selectionMesh = TorusBuilder.CreateTorus("gazeTracker", {
  396. diameter: 0.0035 * 3,
  397. thickness: 0.0025 * 3,
  398. tessellation: 20
  399. }, this._scene);
  400. selectionMesh.bakeCurrentTransformIntoVertices();
  401. selectionMesh.isPickable = false;
  402. selectionMesh.isVisible = false;
  403. let targetMat = new StandardMaterial("targetMat", this._scene);
  404. targetMat.specularColor = Color3.Black();
  405. targetMat.emissiveColor = this.selectionMeshDefaultColor;
  406. targetMat.backFaceCulling = false;
  407. selectionMesh.material = targetMat;
  408. return {
  409. laserPointer,
  410. selectionMesh
  411. };
  412. }
  413. private _convertNormalToDirectionOfRay(normal: Nullable<Vector3>, ray: Ray) {
  414. if (normal) {
  415. let angle = Math.acos(Vector3.Dot(normal, ray.direction));
  416. if (angle < Math.PI / 2) {
  417. normal.scaleInPlace(-1);
  418. }
  419. }
  420. return normal;
  421. }
  422. private _updatePointerDistance(_laserPointer: AbstractMesh, distance: number = 100) {
  423. _laserPointer.scaling.y = distance;
  424. _laserPointer.position.z = distance / 2;
  425. }
  426. /**
  427. * Dispose this feature and all of the resources attached
  428. */
  429. dispose(): void {
  430. this.detach();
  431. }
  432. }
  433. //register the plugin
  434. WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPointerSelection.Name, (xrSessionManager, options) => {
  435. return () => new WebXRControllerPointerSelection(xrSessionManager, options);
  436. }, WebXRControllerPointerSelection.Version, true);