WebXRHandTracking.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. import { WebXRAbstractFeature } from "./WebXRAbstractFeature";
  2. import { WebXRSessionManager } from "../webXRSessionManager";
  3. import { WebXRFeatureName } from "../webXRFeaturesManager";
  4. import { AbstractMesh } from "../../Meshes/abstractMesh";
  5. import { Mesh } from "../../Meshes/mesh";
  6. import { SphereBuilder } from "../../Meshes/Builders/sphereBuilder";
  7. import { WebXRInput } from "../webXRInput";
  8. import { WebXRInputSource } from "../webXRInputSource";
  9. import { Quaternion } from "../../Maths/math.vector";
  10. import { Nullable } from "../../types";
  11. import { PhysicsImpostor } from "../../Physics/physicsImpostor";
  12. import { WebXRFeaturesManager } from "../webXRFeaturesManager";
  13. import { IDisposable, Scene } from "../../scene";
  14. import { Observable } from "../../Misc/observable";
  15. import { InstancedMesh } from "../../Meshes/instancedMesh";
  16. import { SceneLoader } from "../../Loading/sceneLoader";
  17. import { Color3 } from "../../Maths/math.color";
  18. import { NodeMaterial } from "../../Materials/Node/nodeMaterial";
  19. import { InputBlock } from "../../Materials/Node/Blocks/Input/inputBlock";
  20. import { Material } from "../../Materials/material";
  21. import { Engine } from "../../Engines/engine";
  22. import { Tools } from "../../Misc/tools";
  23. import { Axis } from "../../Maths/math.axis";
  24. import { TransformNode } from "../../Meshes/transformNode";
  25. declare const XRHand: XRHand;
  26. /**
  27. * Configuration interface for the hand tracking feature
  28. */
  29. export interface IWebXRHandTrackingOptions {
  30. /**
  31. * The xrInput that will be used as source for new hands
  32. */
  33. xrInput: WebXRInput;
  34. /**
  35. * Configuration object for the joint meshes
  36. */
  37. jointMeshes?: {
  38. /**
  39. * Should the meshes created be invisible (defaults to false)
  40. */
  41. invisible?: boolean;
  42. /**
  43. * A source mesh to be used to create instances. Defaults to a sphere.
  44. * This mesh will be the source for all other (25) meshes.
  45. * It should have the general size of a single unit, as the instances will be scaled according to the provided radius
  46. */
  47. sourceMesh?: Mesh;
  48. /**
  49. * This function will be called after a mesh was created for a specific joint.
  50. * Using this function you can either manipulate the instance or return a new mesh.
  51. * When returning a new mesh the instance created before will be disposed
  52. */
  53. onHandJointMeshGenerated?: (meshInstance: InstancedMesh, jointId: number, controllerId: string) => Mesh | undefined;
  54. /**
  55. * Should the source mesh stay visible. Defaults to false
  56. */
  57. keepOriginalVisible?: boolean;
  58. /**
  59. * Scale factor for all instances (defaults to 2)
  60. */
  61. scaleFactor?: number;
  62. /**
  63. * Should each instance have its own physics impostor
  64. */
  65. enablePhysics?: boolean;
  66. /**
  67. * If enabled, override default physics properties
  68. */
  69. physicsProps?: { friction?: number; restitution?: number; impostorType?: number };
  70. /**
  71. * Should the default hand mesh be disabled. In this case, the spheres will be visible (unless set invisible).
  72. */
  73. disableDefaultHandMesh?: boolean;
  74. /**
  75. * a rigged hand-mesh that will be updated according to the XRHand data provided. This will override the default hand mesh
  76. */
  77. handMeshes?: {
  78. right: AbstractMesh;
  79. left: AbstractMesh;
  80. };
  81. /**
  82. * If a hand mesh was provided, this array will define what axis will update which node. This will override the default hand mesh
  83. */
  84. rigMapping?: {
  85. right: string[];
  86. left: string[];
  87. };
  88. };
  89. }
  90. /**
  91. * Parts of the hands divided to writs and finger names
  92. */
  93. export const enum HandPart {
  94. /**
  95. * HandPart - Wrist
  96. */
  97. WRIST = "wrist",
  98. /**
  99. * HandPart - The THumb
  100. */
  101. THUMB = "thumb",
  102. /**
  103. * HandPart - Index finger
  104. */
  105. INDEX = "index",
  106. /**
  107. * HandPart - Middle finger
  108. */
  109. MIDDLE = "middle",
  110. /**
  111. * HandPart - Ring finger
  112. */
  113. RING = "ring",
  114. /**
  115. * HandPart - Little finger
  116. */
  117. LITTLE = "little",
  118. }
  119. /**
  120. * Representing a single hand (with its corresponding native XRHand object)
  121. */
  122. export class WebXRHand implements IDisposable {
  123. private _scene: Scene;
  124. private _defaultHandMesh: boolean = false;
  125. private _transformNodeMapping: TransformNode[] = [];
  126. /**
  127. * Hand-parts definition (key is HandPart)
  128. */
  129. public handPartsDefinition: { [key: string]: number[] };
  130. /**
  131. * Observers will be triggered when the mesh for this hand was initialized.
  132. */
  133. public onHandMeshReadyObservable: Observable<WebXRHand> = new Observable();
  134. /**
  135. * Populate the HandPartsDefinition object.
  136. * This is called as a side effect since certain browsers don't have XRHand defined.
  137. */
  138. private generateHandPartsDefinition(hand: XRHand) {
  139. return {
  140. [HandPart.WRIST]: [hand.WRIST],
  141. [HandPart.THUMB]: [hand.THUMB_METACARPAL, hand.THUMB_PHALANX_PROXIMAL, hand.THUMB_PHALANX_DISTAL, hand.THUMB_PHALANX_TIP],
  142. [HandPart.INDEX]: [hand.INDEX_METACARPAL, hand.INDEX_PHALANX_PROXIMAL, hand.INDEX_PHALANX_INTERMEDIATE, hand.INDEX_PHALANX_DISTAL, hand.INDEX_PHALANX_TIP],
  143. [HandPart.MIDDLE]: [hand.MIDDLE_METACARPAL, hand.MIDDLE_PHALANX_PROXIMAL, hand.MIDDLE_PHALANX_INTERMEDIATE, hand.MIDDLE_PHALANX_DISTAL, hand.MIDDLE_PHALANX_TIP],
  144. [HandPart.RING]: [hand.RING_METACARPAL, hand.RING_PHALANX_PROXIMAL, hand.RING_PHALANX_INTERMEDIATE, hand.RING_PHALANX_DISTAL, hand.RING_PHALANX_TIP],
  145. [HandPart.LITTLE]: [hand.LITTLE_METACARPAL, hand.LITTLE_PHALANX_PROXIMAL, hand.LITTLE_PHALANX_INTERMEDIATE, hand.LITTLE_PHALANX_DISTAL, hand.LITTLE_PHALANX_TIP],
  146. };
  147. }
  148. /**
  149. * Construct a new hand object
  150. * @param xrController the controller to which the hand correlates
  151. * @param trackedMeshes the meshes to be used to track the hand joints
  152. * @param _handMesh an optional hand mesh. if not provided, ours will be used
  153. * @param _rigMapping an optional rig mapping for the hand mesh. if not provided, ours will be used
  154. * @param disableDefaultHandMesh should the default mesh creation be disabled
  155. */
  156. constructor(
  157. /** the controller to which the hand correlates */
  158. public readonly xrController: WebXRInputSource,
  159. /** the meshes to be used to track the hand joints */
  160. public readonly trackedMeshes: AbstractMesh[],
  161. private _handMesh?: AbstractMesh,
  162. private _rigMapping?: string[],
  163. disableDefaultHandMesh?: boolean
  164. ) {
  165. this.handPartsDefinition = this.generateHandPartsDefinition(xrController.inputSource.hand!);
  166. this._scene = trackedMeshes[0].getScene();
  167. if (this._handMesh && this._rigMapping) {
  168. this._defaultHandMesh = false;
  169. this.onHandMeshReadyObservable.notifyObservers(this);
  170. } else {
  171. if (!disableDefaultHandMesh) {
  172. this._generateDefaultHandMesh();
  173. }
  174. }
  175. // hide the motion controller, if available/loaded
  176. if (this.xrController.motionController) {
  177. if (this.xrController.motionController.rootMesh) {
  178. this.xrController.motionController.rootMesh.setEnabled(false);
  179. } else {
  180. this.xrController.motionController.onModelLoadedObservable.add((controller) => {
  181. if (controller.rootMesh) {
  182. controller.rootMesh.setEnabled(false);
  183. }
  184. });
  185. }
  186. }
  187. this.xrController.onMotionControllerInitObservable.add((motionController) => {
  188. motionController.onModelLoadedObservable.add((controller) => {
  189. if (controller.rootMesh) {
  190. controller.rootMesh.setEnabled(false);
  191. }
  192. });
  193. if (motionController.rootMesh) {
  194. motionController.rootMesh.setEnabled(false);
  195. }
  196. });
  197. }
  198. /**
  199. * Get the hand mesh. It is possible that the hand mesh is not yet ready!
  200. */
  201. public get handMesh() {
  202. return this._handMesh;
  203. }
  204. /**
  205. * Update this hand from the latest xr frame
  206. * @param xrFrame xrFrame to update from
  207. * @param referenceSpace The current viewer reference space
  208. * @param scaleFactor optional scale factor for the meshes
  209. */
  210. public updateFromXRFrame(xrFrame: XRFrame, referenceSpace: XRReferenceSpace, scaleFactor: number = 2) {
  211. const hand = this.xrController.inputSource.hand;
  212. if (!hand) {
  213. return;
  214. }
  215. this.trackedMeshes.forEach((mesh, idx) => {
  216. const xrJoint = hand[idx];
  217. if (xrJoint) {
  218. let pose = xrFrame.getJointPose!(xrJoint, referenceSpace);
  219. if (!pose || !pose.transform) {
  220. return;
  221. }
  222. // get the transformation. can be done with matrix decomposition as well
  223. const pos = pose.transform.position;
  224. const orientation = pose.transform.orientation;
  225. mesh.position.set(pos.x, pos.y, pos.z);
  226. mesh.rotationQuaternion!.set(orientation.x, orientation.y, orientation.z, orientation.w);
  227. // left handed system conversion
  228. // get the radius of the joint. In general it is static, but just in case it does change we update it on each frame.
  229. const radius = (pose.radius || 0.008) * scaleFactor;
  230. mesh.scaling.set(radius, radius, radius);
  231. // now check for the hand mesh
  232. if (this._handMesh && this._rigMapping) {
  233. if (this._rigMapping[idx]) {
  234. this._transformNodeMapping[idx] = this._transformNodeMapping[idx] || this._scene.getTransformNodeByName(this._rigMapping[idx]);
  235. if (this._transformNodeMapping[idx]) {
  236. this._transformNodeMapping[idx].position.copyFrom(mesh.position);
  237. this._transformNodeMapping[idx].rotationQuaternion!.copyFrom(mesh.rotationQuaternion!);
  238. // no scaling at the moment
  239. // this._transformNodeMapping[idx].scaling.copyFrom(mesh.scaling).scaleInPlace(20);
  240. mesh.isVisible = false;
  241. }
  242. }
  243. }
  244. if (!mesh.getScene().useRightHandedSystem) {
  245. mesh.position.z *= -1;
  246. mesh.rotationQuaternion!.z *= -1;
  247. mesh.rotationQuaternion!.w *= -1;
  248. }
  249. }
  250. });
  251. }
  252. /**
  253. * Get meshes of part of the hand
  254. * @param part the part of hand to get
  255. * @returns An array of meshes that correlate to the hand part requested
  256. */
  257. public getHandPartMeshes(part: HandPart): AbstractMesh[] {
  258. return this.handPartsDefinition[part].map((idx) => this.trackedMeshes[idx]);
  259. }
  260. /**
  261. * Dispose this Hand object
  262. */
  263. public dispose() {
  264. this.trackedMeshes.forEach((mesh) => mesh.dispose());
  265. this.onHandMeshReadyObservable.clear();
  266. // dispose the hand mesh, if it is the default one
  267. if (this._defaultHandMesh && this._handMesh) {
  268. this._handMesh.dispose();
  269. }
  270. }
  271. private async _generateDefaultHandMesh() {
  272. try {
  273. const handedness = this.xrController.inputSource.handedness === "right" ? "right" : "left";
  274. const filename = `${handedness === "right" ? "r" : "l"}_hand_${this._scene.useRightHandedSystem ? "r" : "l"}hs.glb`;
  275. const loaded = await SceneLoader.ImportMeshAsync("", "https://assets.babylonjs.com/meshes/HandMeshes/", filename, this._scene);
  276. // shader
  277. const handColors = {
  278. base: Color3.FromInts(116, 63, 203),
  279. fresnel: Color3.FromInts(149, 102, 229),
  280. fingerColor: Color3.FromInts(177, 130, 255),
  281. tipFresnel: Color3.FromInts(220, 200, 255),
  282. };
  283. const handShader = new NodeMaterial("leftHandShader", this._scene, { emitComments: false });
  284. await handShader.loadAsync("https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json");
  285. // build node materials
  286. handShader.build(false);
  287. // depth prepass and alpha mode
  288. handShader.needDepthPrePass = true;
  289. handShader.transparencyMode = Material.MATERIAL_ALPHABLEND;
  290. handShader.alphaMode = Engine.ALPHA_COMBINE;
  291. const handNodes = {
  292. base: handShader.getBlockByName("baseColor") as InputBlock,
  293. fresnel: handShader.getBlockByName("fresnelColor") as InputBlock,
  294. fingerColor: handShader.getBlockByName("fingerColor") as InputBlock,
  295. tipFresnel: handShader.getBlockByName("tipFresnelColor") as InputBlock,
  296. };
  297. handNodes.base.value = handColors.base;
  298. handNodes.fresnel.value = handColors.fresnel;
  299. handNodes.fingerColor.value = handColors.fingerColor;
  300. handNodes.tipFresnel.value = handColors.tipFresnel;
  301. loaded.meshes[1].material = handShader;
  302. loaded.meshes[1].alwaysSelectAsActiveMesh = true;
  303. this._defaultHandMesh = true;
  304. this._handMesh = loaded.meshes[0];
  305. this._rigMapping = [
  306. "wrist_",
  307. "thumb_metacarpal_",
  308. "thumb_proxPhalanx_",
  309. "thumb_distPhalanx_",
  310. "thumb_tip_",
  311. "index_metacarpal_",
  312. "index_proxPhalanx_",
  313. "index_intPhalanx_",
  314. "index_distPhalanx_",
  315. "index_tip_",
  316. "middle_metacarpal_",
  317. "middle_proxPhalanx_",
  318. "middle_intPhalanx_",
  319. "middle_distPhalanx_",
  320. "middle_tip_",
  321. "ring_metacarpal_",
  322. "ring_proxPhalanx_",
  323. "ring_intPhalanx_",
  324. "ring_distPhalanx_",
  325. "ring_tip_",
  326. "little_metacarpal_",
  327. "little_proxPhalanx_",
  328. "little_intPhalanx_",
  329. "little_distPhalanx_",
  330. "little_tip_",
  331. ].map((joint) => `${joint}${handedness === "right" ? "R" : "L"}`);
  332. // single change for left handed systems
  333. const tm = this._scene.getTransformNodeByName(this._rigMapping[0]);
  334. if (!tm) {
  335. throw new Error("could not find the wrist node");
  336. } else {
  337. tm.parent && (tm.parent as AbstractMesh).rotate(Axis.Y, Math.PI);
  338. }
  339. this.onHandMeshReadyObservable.notifyObservers(this);
  340. } catch (e) {
  341. Tools.Error("error loading hand mesh");
  342. console.log(e);
  343. }
  344. }
  345. }
  346. /**
  347. * WebXR Hand Joint tracking feature, available for selected browsers and devices
  348. */
  349. export class WebXRHandTracking extends WebXRAbstractFeature {
  350. private static _idCounter = 0;
  351. /**
  352. * The module's name
  353. */
  354. public static readonly Name = WebXRFeatureName.HAND_TRACKING;
  355. /**
  356. * The (Babylon) version of this module.
  357. * This is an integer representing the implementation version.
  358. * This number does not correspond to the WebXR specs version
  359. */
  360. public static readonly Version = 1;
  361. /**
  362. * This observable will notify registered observers when a new hand object was added and initialized
  363. */
  364. public onHandAddedObservable: Observable<WebXRHand> = new Observable();
  365. /**
  366. * This observable will notify its observers right before the hand object is disposed
  367. */
  368. public onHandRemovedObservable: Observable<WebXRHand> = new Observable();
  369. private _hands: {
  370. [controllerId: string]: {
  371. id: number;
  372. handObject: WebXRHand;
  373. };
  374. } = {};
  375. /**
  376. * Creates a new instance of the hit test feature
  377. * @param _xrSessionManager an instance of WebXRSessionManager
  378. * @param options options to use when constructing this feature
  379. */
  380. constructor(
  381. _xrSessionManager: WebXRSessionManager,
  382. /**
  383. * options to use when constructing this feature
  384. */
  385. public readonly options: IWebXRHandTrackingOptions
  386. ) {
  387. super(_xrSessionManager);
  388. this.xrNativeFeatureName = "hand-tracking";
  389. }
  390. /**
  391. * Check if the needed objects are defined.
  392. * This does not mean that the feature is enabled, but that the objects needed are well defined.
  393. */
  394. public isCompatible(): boolean {
  395. return typeof XRHand !== "undefined";
  396. }
  397. /**
  398. * attach this feature
  399. * Will usually be called by the features manager
  400. *
  401. * @returns true if successful.
  402. */
  403. public attach(): boolean {
  404. if (!super.attach()) {
  405. return false;
  406. }
  407. this.options.xrInput.controllers.forEach(this._attachHand);
  408. this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable, this._attachHand);
  409. this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable, (controller) => {
  410. // REMOVE the controller
  411. this._detachHand(controller.uniqueId);
  412. });
  413. return true;
  414. }
  415. /**
  416. * detach this feature.
  417. * Will usually be called by the features manager
  418. *
  419. * @returns true if successful.
  420. */
  421. public detach(): boolean {
  422. if (!super.detach()) {
  423. return false;
  424. }
  425. Object.keys(this._hands).forEach((controllerId) => {
  426. this._detachHand(controllerId);
  427. });
  428. return true;
  429. }
  430. /**
  431. * Dispose this feature and all of the resources attached
  432. */
  433. public dispose(): void {
  434. super.dispose();
  435. this.onHandAddedObservable.clear();
  436. }
  437. /**
  438. * Get the hand object according to the controller id
  439. * @param controllerId the controller id to which we want to get the hand
  440. * @returns null if not found or the WebXRHand object if found
  441. */
  442. public getHandByControllerId(controllerId: string): Nullable<WebXRHand> {
  443. return this._hands[controllerId]?.handObject || null;
  444. }
  445. /**
  446. * Get a hand object according to the requested handedness
  447. * @param handedness the handedness to request
  448. * @returns null if not found or the WebXRHand object if found
  449. */
  450. public getHandByHandedness(handedness: XRHandedness): Nullable<WebXRHand> {
  451. const handednesses = Object.keys(this._hands).map((key) => this._hands[key].handObject.xrController.inputSource.handedness);
  452. const found = handednesses.indexOf(handedness);
  453. if (found !== -1) {
  454. return this._hands[found].handObject;
  455. }
  456. return null;
  457. }
  458. protected _onXRFrame(_xrFrame: XRFrame): void {
  459. // iterate over the hands object
  460. Object.keys(this._hands).forEach((id) => {
  461. this._hands[id].handObject.updateFromXRFrame(_xrFrame, this._xrSessionManager.referenceSpace, this.options.jointMeshes?.scaleFactor);
  462. });
  463. }
  464. private _attachHand = (xrController: WebXRInputSource) => {
  465. if (!xrController.inputSource.hand || this._hands[xrController.uniqueId]) {
  466. // already attached
  467. return;
  468. }
  469. const hand = xrController.inputSource.hand;
  470. const trackedMeshes: AbstractMesh[] = [];
  471. const originalMesh = this.options.jointMeshes?.sourceMesh || SphereBuilder.CreateSphere("jointParent", { diameter: 1 });
  472. originalMesh.scaling.set(0.01, 0.01, 0.01);
  473. originalMesh.isVisible = !!this.options.jointMeshes?.keepOriginalVisible;
  474. for (let i = 0; i < hand.length; ++i) {
  475. let newInstance: AbstractMesh = originalMesh.createInstance(`${xrController.uniqueId}-handJoint-${i}`);
  476. if (this.options.jointMeshes?.onHandJointMeshGenerated) {
  477. const returnedMesh = this.options.jointMeshes.onHandJointMeshGenerated(newInstance as InstancedMesh, i, xrController.uniqueId);
  478. if (returnedMesh) {
  479. if (returnedMesh !== newInstance) {
  480. newInstance.dispose();
  481. newInstance = returnedMesh;
  482. }
  483. }
  484. }
  485. newInstance.isPickable = false;
  486. if (this.options.jointMeshes?.enablePhysics) {
  487. const props = this.options.jointMeshes.physicsProps || {};
  488. const type = props.impostorType !== undefined ? props.impostorType : PhysicsImpostor.SphereImpostor;
  489. newInstance.physicsImpostor = new PhysicsImpostor(newInstance, type, { mass: 0, ...props });
  490. }
  491. newInstance.rotationQuaternion = new Quaternion();
  492. if (this.options.jointMeshes?.invisible) {
  493. newInstance.isVisible = false;
  494. }
  495. trackedMeshes.push(newInstance);
  496. }
  497. const handedness = xrController.inputSource.handedness === "right" ? "right" : "left";
  498. const handMesh = this.options.jointMeshes?.handMeshes && this.options.jointMeshes?.handMeshes[handedness];
  499. const rigMapping = this.options.jointMeshes?.rigMapping && this.options.jointMeshes?.rigMapping[handedness];
  500. const webxrHand = new WebXRHand(xrController, trackedMeshes, handMesh, rigMapping, this.options.jointMeshes?.disableDefaultHandMesh);
  501. // get two new meshes
  502. this._hands[xrController.uniqueId] = {
  503. handObject: webxrHand,
  504. id: WebXRHandTracking._idCounter++,
  505. };
  506. this.onHandAddedObservable.notifyObservers(webxrHand);
  507. };
  508. private _detachHand(controllerId: string) {
  509. if (this._hands[controllerId]) {
  510. this.onHandRemovedObservable.notifyObservers(this._hands[controllerId].handObject);
  511. this._hands[controllerId].handObject.dispose();
  512. }
  513. }
  514. }
  515. //register the plugin
  516. WebXRFeaturesManager.AddWebXRFeature(
  517. WebXRHandTracking.Name,
  518. (xrSessionManager, options) => {
  519. return () => new WebXRHandTracking(xrSessionManager, options);
  520. },
  521. WebXRHandTracking.Version,
  522. false
  523. );