123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526 |
- import { WebXRFeaturesManager, WebXRFeatureName } from "../webXRFeaturesManager";
- import { WebXRSessionManager } from '../webXRSessionManager';
- import { AbstractMesh } from '../../Meshes/abstractMesh';
- import { Observer } from '../../Misc/observable';
- import { WebXRInput } from '../webXRInput';
- import { WebXRInputSource } from '../webXRInputSource';
- import { Scene } from '../../scene';
- import { WebXRControllerComponent } from '../motionController/webXRControllerComponent';
- import { Nullable } from '../../types';
- import { Vector3 } from '../../Maths/math.vector';
- import { Color3 } from '../../Maths/math.color';
- import { Axis } from '../../Maths/math.axis';
- import { StandardMaterial } from '../../Materials/standardMaterial';
- import { CylinderBuilder } from '../../Meshes/Builders/cylinderBuilder';
- import { TorusBuilder } from '../../Meshes/Builders/torusBuilder';
- import { Ray } from '../../Culling/ray';
- import { PickingInfo } from '../../Collisions/pickingInfo';
- import { WebXRAbstractFeature } from './WebXRAbstractFeature';
- import { UtilityLayerRenderer } from '../../Rendering/utilityLayerRenderer';
- /**
- * Options interface for the pointer selection module
- */
- export interface IWebXRControllerPointerSelectionOptions {
- /**
- * the xr input to use with this pointer selection
- */
- xrInput: WebXRInput;
- /**
- * Different button type to use instead of the main component
- */
- overrideButtonId?: string;
- /**
- * The amount of time in miliseconds it takes between pick found something to a pointer down event.
- * Used in gaze modes. Tracked pointer uses the trigger, screen uses touch events
- * 3000 means 3 seconds between pointing at something and selecting it
- */
- timeToSelect?: number;
- /**
- * 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)
- * If not disabled, the last picked point will be used to execute a pointer up event
- * If disabled, pointer up event will be triggered right after the pointer down event.
- * Used in screen and gaze target ray mode only
- */
- disablePointerUpOnTouchOut: boolean;
- /**
- * For gaze mode (time to select instead of press)
- */
- forceGazeMode: boolean;
- /**
- * 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
- * to start a new countdown to the pointer down event.
- * Defaults to 1.
- */
- gazeModePointerMovedFactor?: number;
- /**
- * Should meshes created here be added to a utility layer or the main scene
- */
- useUtilityLayer?: boolean;
- /**
- * if provided, this scene will be used to render meshes.
- */
- customUtilityLayerScene?: Scene;
- /**
- * use this rendering group id for the meshes (optional)
- */
- renderingGroupId?: number;
- }
- /**
- * A module that will enable pointer selection for motion controllers of XR Input Sources
- */
- export class WebXRControllerPointerSelection extends WebXRAbstractFeature {
- /**
- * The module's name
- */
- public static readonly Name = WebXRFeatureName.POINTER_SELECTION;
- /**
- * The (Babylon) version of this module.
- * This is an integer representing the implementation version.
- * This number does not correspond to the webxr specs version
- */
- public static readonly Version = 1;
- /**
- * This color will be set to the laser pointer when selection is triggered
- */
- public laserPointerPickedColor: Color3 = new Color3(0.9, 0.9, 0.9);
- /**
- * This color will be applied to the selection ring when selection is triggered
- */
- public selectionMeshPickedColor: Color3 = new Color3(0.3, 0.3, 1.0);
- /**
- * default color of the selection ring
- */
- public selectionMeshDefaultColor: Color3 = new Color3(0.8, 0.8, 0.8);
- /**
- * Default color of the laser pointer
- */
- public lasterPointerDefaultColor: Color3 = new Color3(0.7, 0.7, 0.7);
- /**
- * Should the laser pointer be displayed
- */
- public displayLaserPointer: boolean = true;
- /**
- * Should the selection mesh be displayed (The ring at the end of the laser pointer)
- */
- public displaySelectionMesh: boolean = true;
- /**
- * Disable lighting on the laser pointer (so it will always be visible)
- */
- public disablePointerLighting: boolean = true;
- /**
- * Disable lighting on the selection mesh (so it will always be visible)
- */
- public disableSelectionMeshLighting: boolean = true;
- private static _idCounter = 0;
- private _controllers: {
- [controllerUniqueId: string]: {
- xrController: WebXRInputSource;
- selectionComponent?: WebXRControllerComponent;
- onButtonChangedObserver?: Nullable<Observer<WebXRControllerComponent>>;
- onFrameObserver?: Nullable<Observer<XRFrame>>;
- laserPointer: AbstractMesh;
- selectionMesh: AbstractMesh;
- meshUnderPointer: Nullable<AbstractMesh>;
- pick: Nullable<PickingInfo>;
- id: number;
- tmpRay: Ray;
- };
- } = {};
- private _scene: Scene;
- /**
- * constructs a new background remover module
- * @param _xrSessionManager the session manager for this module
- * @param _options read-only options to be used in this module
- */
- constructor(_xrSessionManager: WebXRSessionManager, private readonly _options: IWebXRControllerPointerSelectionOptions) {
- super(_xrSessionManager);
- this._scene = this._xrSessionManager.scene;
- }
- /**
- * attach this feature
- * Will usually be called by the features manager
- *
- * @returns true if successful.
- */
- attach(): boolean {
- if (!super.attach()) {
- return false;
- }
- this._options.xrInput.controllers.forEach(this._attachController);
- this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController);
- this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {
- // REMOVE the controller
- this._detachController(controller.uniqueId);
- });
- return true;
- }
- /**
- * detach this feature.
- * Will usually be called by the features manager
- *
- * @returns true if successful.
- */
- detach(): boolean {
- if (!super.detach()) {
- return false;
- }
- Object.keys(this._controllers).forEach((controllerId) => {
- this._detachController(controllerId);
- });
- return true;
- }
- /**
- * Get the xr controller that correlates to the pointer id in the pointer event
- *
- * @param id the pointer id to search for
- * @returns the controller that correlates to this id or null if not found
- */
- public getXRControllerByPointerId(id: number): Nullable<WebXRInputSource> {
- const keys = Object.keys(this._controllers);
- for (let i = 0; i < keys.length; ++i) {
- if (this._controllers[keys[i]].id === id) {
- return this._controllers[keys[i]].xrController;
- }
- }
- return null;
- }
- /**
- * Will get the mesh under a specific pointer.
- * `scene.meshUnderPointer` will only return one mesh - either left or right.
- * @param controllerId the controllerId to check
- */
- public getMeshUnderPointer(controllerId: string): Nullable<AbstractMesh> {
- if (this._controllers[controllerId]) {
- return this._controllers[controllerId].meshUnderPointer;
- } else {
- return null;
- }
- }
- protected _onXRFrame(_xrFrame: XRFrame) {
- Object.keys(this._controllers).forEach((id) => {
- const controllerData = this._controllers[id];
- // Every frame check collisions/input
- controllerData.xrController.getWorldPointerRayToRef(controllerData.tmpRay);
- controllerData.pick = this._scene.pickWithRay(controllerData.tmpRay);
- const pick = controllerData.pick;
- if (pick && pick.pickedPoint && pick.hit) {
- // Update laser state
- this._updatePointerDistance(controllerData.laserPointer, pick.distance);
- // Update cursor state
- controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);
- controllerData.selectionMesh.scaling.x = Math.sqrt(pick.distance);
- controllerData.selectionMesh.scaling.y = Math.sqrt(pick.distance);
- controllerData.selectionMesh.scaling.z = Math.sqrt(pick.distance);
- // To avoid z-fighting
- let pickNormal = this._convertNormalToDirectionOfRay(pick.getNormal(true), controllerData.tmpRay);
- let deltaFighting = 0.001;
- controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);
- if (pickNormal) {
- let axis1 = Vector3.Cross(Axis.Y, pickNormal);
- let axis2 = Vector3.Cross(pickNormal, axis1);
- Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, controllerData.selectionMesh.rotation);
- controllerData.selectionMesh.position.addInPlace(pickNormal.scale(deltaFighting));
- }
- controllerData.selectionMesh.isVisible = true && this.displaySelectionMesh;
- controllerData.meshUnderPointer = pick.pickedMesh;
- } else {
- controllerData.selectionMesh.isVisible = false;
- controllerData.meshUnderPointer = null;
- }
- });
- }
- private _attachController = (xrController: WebXRInputSource) => {
- if (this._controllers[xrController.uniqueId]) {
- // already attached
- return;
- }
- // only support tracker pointer
- const { laserPointer, selectionMesh } = this._generateNewMeshPair(xrController);
- // get two new meshes
- this._controllers[xrController.uniqueId] = {
- xrController,
- laserPointer,
- selectionMesh,
- meshUnderPointer: null,
- pick: null,
- tmpRay: new Ray(new Vector3(), new Vector3()),
- id: WebXRControllerPointerSelection._idCounter++
- };
- switch (xrController.inputSource.targetRayMode) {
- case "tracked-pointer":
- return this._attachTrackedPointerRayMode(xrController);
- case "gaze":
- return this._attachGazeMode(xrController);
- case "screen":
- return this._attachScreenRayMode(xrController);
- }
- }
- private _attachScreenRayMode(xrController: WebXRInputSource) {
- const controllerData = this._controllers[xrController.uniqueId];
- let downTriggered = false;
- controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
- if (!controllerData.pick || (this._options.disablePointerUpOnTouchOut && downTriggered)) { return; }
- if (!downTriggered) {
- this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
- downTriggered = true;
- if (this._options.disablePointerUpOnTouchOut) {
- this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
- }
- } else {
- this._scene.simulatePointerMove(controllerData.pick, { pointerId: controllerData.id });
- }
- });
- xrController.onDisposeObservable.addOnce(() => {
- if (controllerData.pick && downTriggered && !this._options.disablePointerUpOnTouchOut) {
- this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
- }
- });
- }
- private _attachGazeMode(xrController: WebXRInputSource) {
- const controllerData = this._controllers[xrController.uniqueId];
- // attached when touched, detaches when raised
- const timeToSelect = this._options.timeToSelect || 3000;
- const sceneToRenderTo = this._options.useUtilityLayer ? (this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene) : this._scene;
- let oldPick = new PickingInfo();
- let discMesh = TorusBuilder.CreateTorus("selection", {
- diameter: 0.0035 * 15,
- thickness: 0.0025 * 6,
- tessellation: 20
- }, sceneToRenderTo);
- discMesh.isVisible = false;
- discMesh.isPickable = false;
- discMesh.parent = controllerData.selectionMesh;
- let timer = 0;
- let downTriggered = false;
- controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
- if (!controllerData.pick) { return; }
- discMesh.isVisible = false;
- if (controllerData.pick.hit) {
- if (!this._pickingMoved(oldPick, controllerData.pick)) {
- if (timer > timeToSelect / 10) {
- discMesh.isVisible = true;
- }
- timer += this._scene.getEngine().getDeltaTime();
- if (timer >= timeToSelect) {
- this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
- downTriggered = true;
- // pointer up right after down, if disable on touch out
- if (this._options.disablePointerUpOnTouchOut) {
- this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
- }
- discMesh.isVisible = false;
- } else {
- const scaleFactor = 1 - (timer / timeToSelect);
- discMesh.scaling.set(scaleFactor, scaleFactor, scaleFactor);
- }
- } else {
- if (downTriggered) {
- if (!this._options.disablePointerUpOnTouchOut) {
- this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
- }
- }
- downTriggered = false;
- timer = 0;
- }
- } else {
- downTriggered = false;
- timer = 0;
- }
- this._scene.simulatePointerMove(controllerData.pick, { pointerId: controllerData.id });
- oldPick = controllerData.pick;
- });
- if (this._options.renderingGroupId !== undefined) {
- discMesh.renderingGroupId = this._options.renderingGroupId;
- }
- xrController.onDisposeObservable.addOnce(() => {
- if (controllerData.pick && !this._options.disablePointerUpOnTouchOut && downTriggered) {
- this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
- }
- discMesh.dispose();
- });
- }
- private _tmpVectorForPickCompare = new Vector3();
- private _pickingMoved(oldPick: PickingInfo, newPick: PickingInfo) {
- if (!oldPick.hit || !newPick.hit) { return true; }
- if (!oldPick.pickedMesh || !oldPick.pickedPoint || !newPick.pickedMesh || !newPick.pickedPoint) { return true; }
- if (oldPick.pickedMesh !== newPick.pickedMesh) { return true; }
- oldPick.pickedPoint?.subtractToRef(newPick.pickedPoint, this._tmpVectorForPickCompare);
- this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x), Math.abs(this._tmpVectorForPickCompare.y), Math.abs(this._tmpVectorForPickCompare.z));
- const delta = (this._options.gazeModePointerMovedFactor || 1) * 0.01 / newPick.distance;
- const length = this._tmpVectorForPickCompare.length();
- if (length > delta) { return true; }
- return false;
- }
- private _attachTrackedPointerRayMode(xrController: WebXRInputSource) {
- xrController.onMotionControllerInitObservable.add((motionController) => {
- if (this._options.forceGazeMode) {
- return this._attachGazeMode(xrController);
- }
- const controllerData = this._controllers[xrController.uniqueId];
- if (this._options.overrideButtonId) {
- controllerData.selectionComponent = motionController.getComponent(this._options.overrideButtonId);
- }
- if (!controllerData.selectionComponent) {
- controllerData.selectionComponent = motionController.getMainComponent();
- }
- controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
- if (controllerData.selectionComponent && controllerData.selectionComponent.pressed) {
- (<StandardMaterial>controllerData.selectionMesh.material).emissiveColor = this.selectionMeshPickedColor;
- (<StandardMaterial>controllerData.laserPointer.material).emissiveColor = this.laserPointerPickedColor;
- } else {
- (<StandardMaterial>controllerData.selectionMesh.material).emissiveColor = this.selectionMeshDefaultColor;
- (<StandardMaterial>controllerData.laserPointer.material).emissiveColor = this.lasterPointerDefaultColor;
- }
- controllerData.laserPointer.isVisible = this.displayLaserPointer;
- (<StandardMaterial>controllerData.laserPointer.material).disableLighting = this.disablePointerLighting;
- (<StandardMaterial>controllerData.selectionMesh.material).disableLighting = this.disableSelectionMeshLighting;
- if (controllerData.pick) {
- this._scene.simulatePointerMove(controllerData.pick, { pointerId: controllerData.id });
- }
- });
- controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChangedObservable.add((component) => {
- if (component.changes.pressed) {
- const pressed = component.changes.pressed.current;
- if (controllerData.pick) {
- if (pressed) {
- this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
- } else {
- this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
- }
- }
- }
- });
- });
- }
- private _detachController(xrControllerUniqueId: string) {
- const controllerData = this._controllers[xrControllerUniqueId];
- if (!controllerData) { return; }
- if (controllerData.selectionComponent) {
- if (controllerData.onButtonChangedObserver) {
- controllerData.selectionComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver);
- }
- }
- if (controllerData.onFrameObserver) {
- this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver);
- }
- controllerData.selectionMesh.dispose();
- controllerData.laserPointer.dispose();
- // remove from the map
- delete this._controllers[xrControllerUniqueId];
- }
- private _generateNewMeshPair(xrController: WebXRInputSource) {
- const sceneToRenderTo = this._options.useUtilityLayer ? (this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene) : this._scene;
- const laserPointer = CylinderBuilder.CreateCylinder("laserPointer", {
- height: 1,
- diameterTop: 0.0002,
- diameterBottom: 0.004,
- tessellation: 20,
- subdivisions: 1
- }, sceneToRenderTo);
- laserPointer.parent = xrController.pointer;
- let laserPointerMaterial = new StandardMaterial("laserPointerMat", sceneToRenderTo);
- laserPointerMaterial.emissiveColor = this.lasterPointerDefaultColor;
- laserPointerMaterial.alpha = 0.7;
- laserPointer.material = laserPointerMaterial;
- laserPointer.rotation.x = Math.PI / 2;
- this._updatePointerDistance(laserPointer, 1);
- laserPointer.isPickable = false;
- // Create a gaze tracker for the XR controller
- const selectionMesh = TorusBuilder.CreateTorus("gazeTracker", {
- diameter: 0.0035 * 3,
- thickness: 0.0025 * 3,
- tessellation: 20
- }, sceneToRenderTo);
- selectionMesh.bakeCurrentTransformIntoVertices();
- selectionMesh.isPickable = false;
- selectionMesh.isVisible = false;
- let targetMat = new StandardMaterial("targetMat", sceneToRenderTo);
- targetMat.specularColor = Color3.Black();
- targetMat.emissiveColor = this.selectionMeshDefaultColor;
- targetMat.backFaceCulling = false;
- selectionMesh.material = targetMat;
- if (this._options.renderingGroupId !== undefined) {
- laserPointer.renderingGroupId = this._options.renderingGroupId;
- selectionMesh.renderingGroupId = this._options.renderingGroupId;
- }
- return {
- laserPointer,
- selectionMesh
- };
- }
- private _convertNormalToDirectionOfRay(normal: Nullable<Vector3>, ray: Ray) {
- if (normal) {
- let angle = Math.acos(Vector3.Dot(normal, ray.direction));
- if (angle < Math.PI / 2) {
- normal.scaleInPlace(-1);
- }
- }
- return normal;
- }
- private _updatePointerDistance(_laserPointer: AbstractMesh, distance: number = 100) {
- _laserPointer.scaling.y = distance;
- // a bit of distance from the controller
- _laserPointer.position.z = (distance / 2) + 0.05;
- }
- }
- //register the plugin
- WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPointerSelection.Name, (xrSessionManager, options) => {
- return () => new WebXRControllerPointerSelection(xrSessionManager, options);
- }, WebXRControllerPointerSelection.Version, true);
|