@playcanvas/supersplat-viewer 1.11.0 → 1.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  const TRACEID_GPU_TIMINGS = 'GpuTimings';
2
2
 
3
- const version$1 = '2.15.1';
4
- const revision = '70fef1e';
3
+ const version$1 = '2.15.2';
4
+ const revision = 'c026827';
5
5
  function extend(target, ex) {
6
6
  for(const prop in ex){
7
7
  const copy = ex[prop];
@@ -3770,6 +3770,16 @@ class Frustum {
3770
3770
  }
3771
3771
  return true;
3772
3772
  }
3773
+ add(other) {
3774
+ const planes = this.planes;
3775
+ const otherPlanes = other.planes;
3776
+ for(let p = 0; p < 6; p++){
3777
+ if (otherPlanes[p].distance > planes[p].distance) {
3778
+ planes[p].copy(otherPlanes[p]);
3779
+ }
3780
+ }
3781
+ return this;
3782
+ }
3773
3783
  containsSphere(sphere) {
3774
3784
  const { center, radius } = sphere;
3775
3785
  let c = 0;
@@ -23560,6 +23570,7 @@ const viewInvMat = new Mat4();
23560
23570
  const viewMat = new Mat4();
23561
23571
  const viewMat3 = new Mat3();
23562
23572
  const tempSphere$1 = new BoundingSphere();
23573
+ const tempFrustum = new Frustum();
23563
23574
  const _flipYMat = new Mat4().setScale(1, -1, 1);
23564
23575
  const _tempLightSet = new Set();
23565
23576
  const _tempLayerSet = new Set();
@@ -23652,7 +23663,6 @@ class Renderer {
23652
23663
  for(let v = 0; v < viewList.length; v++){
23653
23664
  const view = viewList[v];
23654
23665
  view.updateTransforms(transform);
23655
- camera.frustum.setFromMat4(view.projViewOffMat);
23656
23666
  }
23657
23667
  } else {
23658
23668
  let projMat = camera.projectionMatrix;
@@ -23770,9 +23780,14 @@ class Renderer {
23770
23780
  }
23771
23781
  updateCameraFrustum(camera) {
23772
23782
  if (camera.xr && camera.xr.views.list.length) {
23773
- const view = camera.xr.views.list[0];
23774
- viewProjMat.mul2(view.projMat, view.viewOffMat);
23783
+ const views = camera.xr.views.list;
23784
+ viewProjMat.mul2(views[0].projMat, views[0].viewOffMat);
23775
23785
  camera.frustum.setFromMat4(viewProjMat);
23786
+ for(let v = 1; v < views.length; v++){
23787
+ viewProjMat.mul2(views[v].projMat, views[v].viewOffMat);
23788
+ tempFrustum.setFromMat4(viewProjMat);
23789
+ camera.frustum.add(tempFrustum);
23790
+ }
23776
23791
  return;
23777
23792
  }
23778
23793
  const projMat = camera.projectionMatrix;
@@ -80905,6 +80920,26 @@ function DracoWorker(jsUrl, wasmUrl) {
80905
80920
  }
80906
80921
  return 1;
80907
80922
  };
80923
+ const toEngineDataType = (dataType)=>{
80924
+ switch(dataType){
80925
+ case draco.DT_INT8:
80926
+ return 0;
80927
+ case draco.DT_UINT8:
80928
+ return 1;
80929
+ case draco.DT_INT16:
80930
+ return 2;
80931
+ case draco.DT_UINT16:
80932
+ return 3;
80933
+ case draco.DT_INT32:
80934
+ return 4;
80935
+ case draco.DT_UINT32:
80936
+ return 5;
80937
+ case draco.DT_FLOAT32:
80938
+ return 6;
80939
+ default:
80940
+ return 6;
80941
+ }
80942
+ };
80908
80943
  const attributeSizeInBytes = (attribute)=>{
80909
80944
  return attribute.num_components() * componentSizeInBytes(attribute.data_type());
80910
80945
  };
@@ -81027,7 +81062,6 @@ function DracoWorker(jsUrl, wasmUrl) {
81027
81062
  attributes.sort((a, b)=>{
81028
81063
  return (attributeOrder[a.attribute_type()] ?? attributeOrder.length) - (attributeOrder[b.attribute_type()] ?? attributeOrder.length);
81029
81064
  });
81030
- result.attributes = attributes.map((a)=>a.unique_id());
81031
81065
  let totalVertexSize = 0;
81032
81066
  const offsets = attributes.map((a)=>{
81033
81067
  const offset = totalVertexSize;
@@ -81035,13 +81069,29 @@ function DracoWorker(jsUrl, wasmUrl) {
81035
81069
  return offset;
81036
81070
  });
81037
81071
  const hasNormals = attributes.some((a)=>a.attribute_type() === NORMAL_ATTRIBUTE);
81038
- const normalOffset = offsets[1];
81072
+ let normalOffset = offsets[1] ?? 0;
81039
81073
  if (!hasNormals) {
81074
+ normalOffset = offsets[0] + Math.ceil(attributeSizeInBytes(attributes[0]) / 4) * 4;
81040
81075
  for(let i = 1; i < offsets.length; ++i){
81041
81076
  offsets[i] += 12;
81042
81077
  }
81043
81078
  totalVertexSize += 12;
81044
81079
  }
81080
+ result.attributes = attributes.map((a, i)=>({
81081
+ id: a.unique_id(),
81082
+ dataType: toEngineDataType(a.data_type()),
81083
+ numComponents: a.num_components(),
81084
+ offset: offsets[i]
81085
+ }));
81086
+ if (!hasNormals) {
81087
+ result.attributes.splice(1, 0, {
81088
+ id: -1,
81089
+ dataType: 6,
81090
+ numComponents: 3,
81091
+ offset: normalOffset
81092
+ });
81093
+ }
81094
+ result.stride = totalVertexSize;
81045
81095
  result.vertices = new ArrayBuffer(mesh.num_points() * totalVertexSize);
81046
81096
  const dst = new Uint8Array(result.vertices);
81047
81097
  for(let i = 0; i < mesh.num_attributes(); ++i){
@@ -81078,7 +81128,8 @@ function DracoWorker(jsUrl, wasmUrl) {
81078
81128
  error: result.error,
81079
81129
  indices: result.indices,
81080
81130
  vertices: result.vertices,
81081
- attributes: result.attributes
81131
+ attributes: result.attributes,
81132
+ stride: result.stride
81082
81133
  }, [
81083
81134
  result.indices,
81084
81135
  result.vertices
@@ -81121,7 +81172,8 @@ class JobQueue {
81121
81172
  callback(data.error, {
81122
81173
  indices: data.indices,
81123
81174
  vertices: data.vertices,
81124
- attributes: data.attributes
81175
+ attributes: data.attributes,
81176
+ stride: data.stride
81125
81177
  });
81126
81178
  }
81127
81179
  this.jobCallbacks.delete(data.jobId);
@@ -81759,18 +81811,6 @@ const createSkin = (device, gltfSkin, accessors, bufferViews, nodes, glbSkins)=>
81759
81811
  const createDracoMesh = (device, primitive, accessors, bufferViews, meshVariants, meshDefaultMaterials, promises)=>{
81760
81812
  const result = new Mesh(device);
81761
81813
  result.aabb = getAccessorBoundingBox(accessors[primitive.attributes.POSITION]);
81762
- const vertexDesc = [];
81763
- for (const [name, index] of Object.entries(primitive.attributes)){
81764
- const accessor = accessors[index];
81765
- const semantic = gltfToEngineSemanticMap[name];
81766
- const componentType = getComponentType(accessor.componentType);
81767
- vertexDesc.push({
81768
- semantic: semantic,
81769
- components: getNumComponents(accessor.type),
81770
- type: componentType,
81771
- normalize: accessor.normalized ?? (semantic === SEMANTIC_COLOR && (componentType === TYPE_UINT8 || componentType === TYPE_UINT16))
81772
- });
81773
- }
81774
81814
  promises.push(new Promise((resolve, reject)=>{
81775
81815
  const dracoExt = primitive.extensions.KHR_draco_mesh_compression;
81776
81816
  dracoDecode(bufferViews[dracoExt.bufferView].slice().buffer, (err, decompressedData)=>{
@@ -81778,22 +81818,37 @@ const createDracoMesh = (device, primitive, accessors, bufferViews, meshVariants
81778
81818
  console.log(err);
81779
81819
  reject(err);
81780
81820
  } else {
81781
- const order = {};
81782
- for (const [name, index] of Object.entries(dracoExt.attributes)){
81783
- order[gltfToEngineSemanticMap[name]] = decompressedData.attributes.indexOf(index);
81784
- }
81785
- vertexDesc.sort((a, b)=>{
81786
- return order[a.semantic] - order[b.semantic];
81787
- });
81788
- if (!primitive.attributes?.NORMAL) {
81789
- vertexDesc.splice(1, 0, {
81790
- semantic: 'NORMAL',
81791
- components: 3,
81792
- type: TYPE_FLOAT32
81793
- });
81821
+ const idToSemantic = {};
81822
+ for (const [name, id] of Object.entries(dracoExt.attributes)){
81823
+ idToSemantic[id] = gltfToEngineSemanticMap[name];
81824
+ }
81825
+ idToSemantic[-1] = SEMANTIC_NORMAL;
81826
+ const vertexDesc = [];
81827
+ for (const attr of decompressedData.attributes){
81828
+ const semantic = idToSemantic[attr.id];
81829
+ if (semantic !== undefined) {
81830
+ let normalize = false;
81831
+ if (attr.id !== -1) {
81832
+ for (const [name, id] of Object.entries(dracoExt.attributes)){
81833
+ if (id === attr.id && primitive.attributes[name] !== undefined) {
81834
+ const accessor = accessors[primitive.attributes[name]];
81835
+ normalize = accessor.normalized ?? (semantic === SEMANTIC_COLOR && (attr.dataType === TYPE_UINT8 || attr.dataType === TYPE_UINT16));
81836
+ break;
81837
+ }
81838
+ }
81839
+ }
81840
+ vertexDesc.push({
81841
+ semantic: semantic,
81842
+ components: attr.numComponents,
81843
+ type: attr.dataType,
81844
+ normalize: normalize,
81845
+ offset: attr.offset,
81846
+ stride: decompressedData.stride
81847
+ });
81848
+ }
81794
81849
  }
81795
81850
  const vertexFormat = new VertexFormat(device, vertexDesc);
81796
- const numVertices = decompressedData.vertices.byteLength / vertexFormat.size;
81851
+ const numVertices = decompressedData.vertices.byteLength / decompressedData.stride;
81797
81852
  const indexFormat = numVertices <= 65535 ? INDEXFORMAT_UINT16 : INDEXFORMAT_UINT32;
81798
81853
  const numIndices = decompressedData.indices.byteLength / (numVertices <= 65535 ? 2 : 4);
81799
81854
  const vertexBuffer = new VertexBuffer(device, vertexFormat, numVertices, {
@@ -89825,7 +89880,7 @@ class XrInputSource extends EventHandler {
89825
89880
  this._dirtyRay = false;
89826
89881
  const parent = this._manager.camera.parent;
89827
89882
  if (parent) {
89828
- const parentTransform = this._manager.camera.parent.getWorldTransform();
89883
+ const parentTransform = parent.getWorldTransform();
89829
89884
  parentTransform.getTranslation(this._position);
89830
89885
  this._rotation.setFromMat4(parentTransform);
89831
89886
  this._rotation.transformVector(this._rayLocal.origin, this._ray.origin);
@@ -89837,7 +89892,7 @@ class XrInputSource extends EventHandler {
89837
89892
  }
89838
89893
  }
89839
89894
  getPosition() {
89840
- if (!this._position) return null;
89895
+ if (!this._grip) return null;
89841
89896
  this._updateTransforms();
89842
89897
  this._worldTransform.getTranslation(this._position);
89843
89898
  return this._position;
@@ -89846,7 +89901,7 @@ class XrInputSource extends EventHandler {
89846
89901
  return this._localPosition;
89847
89902
  }
89848
89903
  getRotation() {
89849
- if (!this._rotation) return null;
89904
+ if (!this._grip) return null;
89850
89905
  this._updateTransforms();
89851
89906
  this._rotation.setFromMat4(this._worldTransform);
89852
89907
  return this._rotation;
@@ -91208,6 +91263,9 @@ class XrManager extends EventHandler {
91208
91263
  const onClipPlanesChange = ()=>{
91209
91264
  this._setClipPlanes(this._camera.nearClip, this._camera.farClip);
91210
91265
  };
91266
+ const onFrameRateChange = ()=>{
91267
+ this.fire('frameratechange', this._session?.frameRate);
91268
+ };
91211
91269
  const onEnd = ()=>{
91212
91270
  if (this._camera) {
91213
91271
  this._camera.off('set_nearClip', onClipPlanesChange);
@@ -91217,6 +91275,7 @@ class XrManager extends EventHandler {
91217
91275
  }
91218
91276
  session.removeEventListener('end', onEnd);
91219
91277
  session.removeEventListener('visibilitychange', onVisibilityChange);
91278
+ session.removeEventListener('frameratechange', onFrameRateChange);
91220
91279
  if (!failed) this.fire('end');
91221
91280
  this._session = null;
91222
91281
  this._referenceSpace = null;
@@ -91238,9 +91297,7 @@ class XrManager extends EventHandler {
91238
91297
  } else {
91239
91298
  this._supportedFrameRates = null;
91240
91299
  }
91241
- this._session.addEventListener('frameratechange', ()=>{
91242
- this.fire('frameratechange', this._session?.frameRate);
91243
- });
91300
+ this._session.addEventListener('frameratechange', onFrameRateChange);
91244
91301
  session.requestReferenceSpace(spaceType).then((referenceSpace)=>{
91245
91302
  this._referenceSpace = referenceSpace;
91246
91303
  this.app.requestAnimationFrame();
@@ -91426,7 +91483,6 @@ class XrManager extends EventHandler {
91426
91483
  this._available[XRTYPE_INLINE] = false;
91427
91484
  this._available[XRTYPE_VR] = false;
91428
91485
  this._available[XRTYPE_AR] = false;
91429
- this.views = new XrViews(this);
91430
91486
  this.domOverlay = new XrDomOverlay(this);
91431
91487
  this.hitTest = new XrHitTest(this);
91432
91488
  this.imageTracking = new XrImageTracking(this);
@@ -101614,7 +101670,9 @@ const initUI = (global) => {
101614
101670
  };
101615
101671
  const exitFullscreen = () => {
101616
101672
  if (hasFullscreenAPI) {
101617
- document.exitFullscreen();
101673
+ if (document.fullscreenElement) {
101674
+ document.exitFullscreen().catch(() => { });
101675
+ }
101618
101676
  }
101619
101677
  else {
101620
101678
  window.parent.postMessage('exitFullscreen', '*');
@@ -103652,6 +103710,33 @@ class Viewer {
103652
103710
  }
103653
103711
  }
103654
103712
 
103713
+ /** @import { XrInputSource } from 'playcanvas' */
103714
+
103715
+ /**
103716
+ * Automatically loads and displays WebXR controller models (hands or gamepads) based on the
103717
+ * WebXR Input Profiles specification. The script fetches controller models from the WebXR
103718
+ * Input Profiles asset repository and updates their transforms each frame to match the
103719
+ * tracked input sources.
103720
+ *
103721
+ * Features:
103722
+ * - Automatic controller model loading from WebXR Input Profiles repository
103723
+ * - Support for both hand tracking and gamepad controllers
103724
+ * - Automatic cleanup on input source removal or XR session end
103725
+ * - Visibility control for integration with other XR scripts
103726
+ * - Fires events for controller lifecycle coordination
103727
+ *
103728
+ * This script should be attached to a parent entity (typically the same entity as XrSession).
103729
+ * Use it in conjunction with the `XrNavigation` and `XrMenu` scripts.
103730
+ *
103731
+ * @example
103732
+ * // Add to camera parent entity
103733
+ * cameraParent.addComponent('script');
103734
+ * cameraParent.script.create(XrControllers, {
103735
+ * properties: {
103736
+ * basePath: 'https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets/dist/profiles'
103737
+ * }
103738
+ * });
103739
+ */
103655
103740
  class XrControllers extends Script {
103656
103741
  static scriptName = 'xrControllers';
103657
103742
 
@@ -103663,96 +103748,291 @@ class XrControllers extends Script {
103663
103748
  */
103664
103749
  basePath = 'https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets/dist/profiles';
103665
103750
 
103751
+ /**
103752
+ * Map of input sources to their controller data (entity, joint mappings, and asset).
103753
+ *
103754
+ * @type {Map<XrInputSource, { entity: import('playcanvas').Entity, jointMap: Map, asset: import('playcanvas').Asset }>}
103755
+ */
103666
103756
  controllers = new Map();
103667
103757
 
103758
+ /**
103759
+ * Set of input sources currently being loaded (to handle race conditions).
103760
+ *
103761
+ * @type {Set<XrInputSource>}
103762
+ * @private
103763
+ */
103764
+ _pendingInputSources = new Set();
103765
+
103766
+ /**
103767
+ * Whether controller models are currently visible.
103768
+ *
103769
+ * @type {boolean}
103770
+ * @private
103771
+ */
103772
+ _visible = true;
103773
+
103774
+ /**
103775
+ * Bound event handlers for proper cleanup.
103776
+ *
103777
+ * @type {{ onAdd: (inputSource: XrInputSource) => void, onRemove: (inputSource: XrInputSource) => void, onXrEnd: () => void } | null}
103778
+ * @private
103779
+ */
103780
+ _handlers = null;
103781
+
103668
103782
  initialize() {
103669
103783
  if (!this.app.xr) {
103670
103784
  console.error('XrControllers script requires XR to be enabled on the application');
103671
103785
  return;
103672
103786
  }
103673
103787
 
103674
- this.app.xr.input.on('add', async (inputSource) => {
103675
- if (!inputSource.profiles?.length) {
103676
- console.warn('No profiles available for input source');
103677
- return;
103678
- }
103788
+ // Create bound handlers for proper cleanup
103789
+ this._handlers = {
103790
+ onAdd: this._onInputSourceAdd.bind(this),
103791
+ onRemove: this._onInputSourceRemove.bind(this),
103792
+ onXrEnd: this._onXrEnd.bind(this)
103793
+ };
103679
103794
 
103680
- // Process all profiles concurrently
103681
- const profilePromises = inputSource.profiles.map(async (profileId) => {
103682
- const profileUrl = `${this.basePath}/${profileId}/profile.json`;
103795
+ // Listen for input source changes
103796
+ this.app.xr.input.on('add', this._handlers.onAdd);
103797
+ this.app.xr.input.on('remove', this._handlers.onRemove);
103683
103798
 
103684
- try {
103685
- const response = await fetch(profileUrl);
103686
- if (!response.ok) {
103687
- return null;
103688
- }
103799
+ // Listen for XR session end to clean up all controllers
103800
+ this.app.xr.on('end', this._handlers.onXrEnd);
103689
103801
 
103690
- const profile = await response.json();
103691
- const layoutPath = profile.layouts[inputSource.handedness]?.assetPath || '';
103692
- const assetPath = `${this.basePath}/${profile.profileId}/${inputSource.handedness}${layoutPath.replace(/^\/?(left|right)/, '')}`;
103802
+ // Clean up on script destroy
103803
+ this.once('destroy', () => {
103804
+ this._onDestroy();
103805
+ });
103806
+ }
103693
103807
 
103694
- // Load the model
103695
- const asset = await new Promise((resolve, reject) => {
103696
- this.app.assets.loadFromUrl(assetPath, 'container', (err, asset) => {
103697
- if (err) reject(err);
103698
- else resolve(asset);
103699
- });
103700
- });
103808
+ /**
103809
+ * Cleans up all resources when the script is destroyed.
103810
+ *
103811
+ * @private
103812
+ */
103813
+ _onDestroy() {
103814
+ if (this._handlers && this.app.xr) {
103815
+ this.app.xr.input.off('add', this._handlers.onAdd);
103816
+ this.app.xr.input.off('remove', this._handlers.onRemove);
103817
+ this.app.xr.off('end', this._handlers.onXrEnd);
103818
+ }
103701
103819
 
103702
- return { profileId, asset };
103703
- } catch (error) {
103704
- console.warn(`Failed to process profile ${profileId}`);
103705
- return null;
103706
- }
103707
- });
103820
+ // Destroy all controller entities
103821
+ this._destroyAllControllers();
103708
103822
 
103709
- // Wait for all profile attempts to complete
103710
- const results = await Promise.all(profilePromises);
103711
- const successfulResult = results.find(result => result !== null);
103712
-
103713
- if (successfulResult) {
103714
- const { asset } = successfulResult;
103715
- const container = asset.resource;
103716
- const entity = container.instantiateRenderEntity();
103717
- this.app.root.addChild(entity);
103718
-
103719
- const jointMap = new Map();
103720
- if (inputSource.hand) {
103721
- for (const joint of inputSource.hand.joints) {
103722
- const jointEntity = entity.findByName(joint.id);
103723
- if (jointEntity) {
103724
- jointMap.set(joint, jointEntity);
103725
- }
103823
+ this._handlers = null;
103824
+ this._pendingInputSources.clear();
103825
+ }
103826
+
103827
+ /**
103828
+ * Handles XR session end by cleaning up all controllers.
103829
+ *
103830
+ * @private
103831
+ */
103832
+ _onXrEnd() {
103833
+ this._destroyAllControllers();
103834
+ this._pendingInputSources.clear();
103835
+ }
103836
+
103837
+ /**
103838
+ * Destroys a single controller and its associated resources.
103839
+ *
103840
+ * @param {XrInputSource} inputSource - The input source to destroy.
103841
+ * @private
103842
+ */
103843
+ _destroyController(inputSource) {
103844
+ const controller = this.controllers.get(inputSource);
103845
+ if (!controller) return;
103846
+
103847
+ controller.entity.destroy();
103848
+
103849
+ if (controller.asset) {
103850
+ this.app.assets.remove(controller.asset);
103851
+ controller.asset.unload();
103852
+ }
103853
+
103854
+ this.controllers.delete(inputSource);
103855
+ this.app.fire('xr:controller:remove', inputSource);
103856
+ }
103857
+
103858
+ /**
103859
+ * Destroys all controller entities and clears the map.
103860
+ *
103861
+ * @private
103862
+ */
103863
+ _destroyAllControllers() {
103864
+ for (const inputSource of this.controllers.keys()) {
103865
+ this._destroyController(inputSource);
103866
+ }
103867
+ }
103868
+
103869
+ /**
103870
+ * Tries to load profiles sequentially, returning the first successful result.
103871
+ *
103872
+ * @param {XrInputSource} inputSource - The input source.
103873
+ * @param {string[]} profiles - Array of profile IDs to try.
103874
+ * @param {number} [index=0] - Current index in the profiles array.
103875
+ * @returns {Promise<{ profileId: string, asset: import('playcanvas').Asset } | null>} The result or null.
103876
+ * @private
103877
+ */
103878
+ async _tryLoadProfiles(inputSource, profiles, index = 0) {
103879
+ if (index >= profiles.length) return null;
103880
+ if (!this._pendingInputSources.has(inputSource)) return null;
103881
+
103882
+ const result = await this._loadProfile(inputSource, profiles[index]);
103883
+ if (result) return result;
103884
+
103885
+ return this._tryLoadProfiles(inputSource, profiles, index + 1);
103886
+ }
103887
+
103888
+ /**
103889
+ * Called when an input source is added.
103890
+ *
103891
+ * @param {XrInputSource} inputSource - The input source that was added.
103892
+ * @private
103893
+ */
103894
+ async _onInputSourceAdd(inputSource) {
103895
+ if (!inputSource.profiles?.length) {
103896
+ console.warn('XrControllers: No profiles available for input source');
103897
+ return;
103898
+ }
103899
+
103900
+ // Track this input source as pending to handle race conditions
103901
+ this._pendingInputSources.add(inputSource);
103902
+
103903
+ // Load profiles sequentially and stop on first success
103904
+ const successfulResult = await this._tryLoadProfiles(inputSource, inputSource.profiles);
103905
+
103906
+ // Check if input source was removed during loading
103907
+ if (!this._pendingInputSources.has(inputSource)) {
103908
+ // Clean up the loaded asset if we got one
103909
+ if (successfulResult?.asset) {
103910
+ this.app.assets.remove(successfulResult.asset);
103911
+ successfulResult.asset.unload();
103912
+ }
103913
+ return;
103914
+ }
103915
+
103916
+ // Remove from pending set
103917
+ this._pendingInputSources.delete(inputSource);
103918
+
103919
+ if (successfulResult) {
103920
+ const { asset } = successfulResult;
103921
+ const container = asset.resource;
103922
+ const entity = container.instantiateRenderEntity();
103923
+ this.app.root.addChild(entity);
103924
+
103925
+ // Apply current visibility state
103926
+ entity.enabled = this._visible;
103927
+
103928
+ // Build joint map for hand tracking
103929
+ const jointMap = new Map();
103930
+ if (inputSource.hand) {
103931
+ for (const joint of inputSource.hand.joints) {
103932
+ const jointEntity = entity.findByName(joint.id);
103933
+ if (jointEntity) {
103934
+ jointMap.set(joint, jointEntity);
103726
103935
  }
103727
103936
  }
103728
-
103729
- this.controllers.set(inputSource, { entity, jointMap });
103730
- } else {
103731
- console.warn('No compatible profiles found');
103732
103937
  }
103733
- });
103734
103938
 
103735
- this.app.xr.input.on('remove', (inputSource) => {
103736
- const controller = this.controllers.get(inputSource);
103737
- if (controller) {
103738
- controller.entity.destroy();
103739
- this.controllers.delete(inputSource);
103939
+ this.controllers.set(inputSource, { entity, jointMap, asset });
103940
+
103941
+ // Fire event for other scripts to coordinate
103942
+ this.app.fire('xr:controller:add', inputSource, entity);
103943
+ } else {
103944
+ console.warn('XrControllers: No compatible profiles found for input source');
103945
+ }
103946
+ }
103947
+
103948
+ /**
103949
+ * Loads a single profile and its model.
103950
+ *
103951
+ * @param {XrInputSource} inputSource - The input source.
103952
+ * @param {string} profileId - The profile ID to load.
103953
+ * @returns {Promise<{ profileId: string, asset: import('playcanvas').Asset } | null>} The result or null on failure.
103954
+ * @private
103955
+ */
103956
+ async _loadProfile(inputSource, profileId) {
103957
+ const profileUrl = `${this.basePath}/${profileId}/profile.json`;
103958
+
103959
+ try {
103960
+ const response = await fetch(profileUrl);
103961
+ if (!response.ok) {
103962
+ return null;
103740
103963
  }
103741
- });
103964
+
103965
+ const profile = await response.json();
103966
+ const layoutPath = profile.layouts[inputSource.handedness]?.assetPath || '';
103967
+ const assetPath = `${this.basePath}/${profile.profileId}/${inputSource.handedness}${layoutPath.replace(/^\/?(left|right)/, '')}`;
103968
+
103969
+ // Load the model
103970
+ const asset = await new Promise((resolve, reject) => {
103971
+ this.app.assets.loadFromUrl(assetPath, 'container', (err, asset) => {
103972
+ if (err) reject(err);
103973
+ else resolve(asset);
103974
+ });
103975
+ });
103976
+
103977
+ return { profileId, asset };
103978
+ } catch (error) {
103979
+ // Silently fail for individual profiles - we'll try the next one
103980
+ return null;
103981
+ }
103982
+ }
103983
+
103984
+ /**
103985
+ * Called when an input source is removed.
103986
+ *
103987
+ * @param {XrInputSource} inputSource - The input source that was removed.
103988
+ * @private
103989
+ */
103990
+ _onInputSourceRemove(inputSource) {
103991
+ // Remove from pending set if still loading
103992
+ this._pendingInputSources.delete(inputSource);
103993
+ this._destroyController(inputSource);
103994
+ }
103995
+
103996
+ /**
103997
+ * Sets the visibility state of controller models.
103998
+ *
103999
+ * @type {boolean}
104000
+ */
104001
+ set visible(value) {
104002
+ if (this._visible === value) return;
104003
+
104004
+ this._visible = value;
104005
+
104006
+ for (const [, controller] of this.controllers) {
104007
+ controller.entity.enabled = value;
104008
+ }
104009
+ }
104010
+
104011
+ /**
104012
+ * Gets the visibility state of controller models.
104013
+ *
104014
+ * @type {boolean}
104015
+ */
104016
+ get visible() {
104017
+ return this._visible;
103742
104018
  }
103743
104019
 
103744
104020
  update(dt) {
103745
- if (this.app.xr?.active) {
103746
- for (const [inputSource, { entity, jointMap }] of this.controllers) {
103747
- if (inputSource.hand) {
103748
- for (const [joint, jointEntity] of jointMap) {
103749
- jointEntity.setPosition(joint.getPosition());
103750
- jointEntity.setRotation(joint.getRotation());
103751
- }
103752
- } else {
103753
- entity.setPosition(inputSource.getPosition());
103754
- entity.setRotation(inputSource.getRotation());
104021
+ if (!this.app.xr?.active || !this._visible) return;
104022
+
104023
+ for (const [inputSource, { entity, jointMap }] of this.controllers) {
104024
+ if (inputSource.hand) {
104025
+ // Update hand joint positions
104026
+ for (const [joint, jointEntity] of jointMap) {
104027
+ jointEntity.setPosition(joint.getPosition());
104028
+ jointEntity.setRotation(joint.getRotation());
103755
104029
  }
104030
+ } else {
104031
+ // Update controller position
104032
+ const position = inputSource.getPosition();
104033
+ const rotation = inputSource.getRotation();
104034
+ if (position) entity.setPosition(position);
104035
+ if (rotation) entity.setRotation(rotation);
103756
104036
  }
103757
104037
  }
103758
104038
  }
@@ -104007,6 +104287,13 @@ class XrNavigation extends Script {
104007
104287
 
104008
104288
  const hitPoint = this.findPlaneIntersection(origin, direction);
104009
104289
  if (hitPoint) {
104290
+ // Adjust for camera's local XZ offset so the user's head ends up at the target
104291
+ if (this.cameraEntity) {
104292
+ const cameraLocalPos = this.cameraEntity.getLocalPosition();
104293
+ hitPoint.x -= cameraLocalPos.x;
104294
+ hitPoint.z -= cameraLocalPos.z;
104295
+ }
104296
+
104010
104297
  const cameraY = this.entity.getPosition().y;
104011
104298
  hitPoint.y = cameraY;
104012
104299
  this.entity.setPosition(hitPoint);
@@ -104222,7 +104509,7 @@ const initXr = (global) => {
104222
104509
  });
104223
104510
  };
104224
104511
 
104225
- var version = "1.11.0";
104512
+ var version = "1.11.1";
104226
104513
 
104227
104514
  const loadGsplat = async (app, config, progressCallback) => {
104228
104515
  const { contents, contentUrl, unified, aa } = config;