iwer 2.1.1 → 2.2.0

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.
Files changed (43) hide show
  1. package/build/iwer.js +1606 -5
  2. package/build/iwer.min.js +12 -12
  3. package/build/iwer.module.js +1599 -6
  4. package/build/iwer.module.min.js +12 -12
  5. package/lib/device/XRController.d.ts +20 -0
  6. package/lib/device/XRController.d.ts.map +1 -1
  7. package/lib/device/XRController.js +56 -0
  8. package/lib/device/XRController.js.map +1 -1
  9. package/lib/device/XRDevice.d.ts +43 -1
  10. package/lib/device/XRDevice.d.ts.map +1 -1
  11. package/lib/device/XRDevice.js +88 -0
  12. package/lib/device/XRDevice.js.map +1 -1
  13. package/lib/index.d.ts +4 -0
  14. package/lib/index.d.ts.map +1 -1
  15. package/lib/index.js +4 -0
  16. package/lib/index.js.map +1 -1
  17. package/lib/remote/RemoteControlInterface.d.ts +172 -0
  18. package/lib/remote/RemoteControlInterface.d.ts.map +1 -0
  19. package/lib/remote/RemoteControlInterface.js +1194 -0
  20. package/lib/remote/RemoteControlInterface.js.map +1 -0
  21. package/lib/remote/index.d.ts +9 -0
  22. package/lib/remote/index.d.ts.map +1 -0
  23. package/lib/remote/index.js +8 -0
  24. package/lib/remote/index.js.map +1 -0
  25. package/lib/remote/types.d.ts +348 -0
  26. package/lib/remote/types.d.ts.map +1 -0
  27. package/lib/remote/types.js +8 -0
  28. package/lib/remote/types.js.map +1 -0
  29. package/lib/types/state.d.ts +46 -0
  30. package/lib/types/state.d.ts.map +1 -0
  31. package/lib/types/state.js +8 -0
  32. package/lib/types/state.js.map +1 -0
  33. package/lib/utils/control-math.d.ts +64 -0
  34. package/lib/utils/control-math.d.ts.map +1 -0
  35. package/lib/utils/control-math.js +238 -0
  36. package/lib/utils/control-math.js.map +1 -0
  37. package/lib/version.d.ts +1 -1
  38. package/lib/version.js +1 -1
  39. package/package.json +10 -5
  40. package/lib/layers/XRWebGLBinding.d.ts +0 -92
  41. package/lib/layers/XRWebGLBinding.d.ts.map +0 -1
  42. package/lib/layers/XRWebGLBinding.js +0 -186
  43. package/lib/layers/XRWebGLBinding.js.map +0 -1
@@ -758,7 +758,7 @@ function cross(out, a, b) {
758
758
  * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
759
759
  * @returns {vec3} out
760
760
  */
761
- function lerp(out, a, b, t) {
761
+ function lerp$1(out, a, b, t) {
762
762
  var ax = a[0];
763
763
  var ay = a[1];
764
764
  var az = a[2];
@@ -768,6 +768,27 @@ function lerp(out, a, b, t) {
768
768
  return out;
769
769
  }
770
770
 
771
+ /**
772
+ * Transforms the vec3 with a mat4.
773
+ * 4th vector component is implicitly '1'
774
+ *
775
+ * @param {vec3} out the receiving vector
776
+ * @param {ReadonlyVec3} a the vector to transform
777
+ * @param {ReadonlyMat4} m matrix to transform with
778
+ * @returns {vec3} out
779
+ */
780
+ function transformMat4$1(out, a, m) {
781
+ var x = a[0],
782
+ y = a[1],
783
+ z = a[2];
784
+ var w = m[3] * x + m[7] * y + m[11] * z + m[15];
785
+ w = w || 1.0;
786
+ out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
787
+ out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
788
+ out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
789
+ return out;
790
+ }
791
+
771
792
  /**
772
793
  * Transforms the vec3 with a quat
773
794
  * Can also be used for dual quaternions. (Multiply it with the real part)
@@ -1532,6 +1553,1435 @@ class Quaternion {
1532
1553
  }
1533
1554
  }
1534
1555
 
1556
+ /**
1557
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1558
+ *
1559
+ * This source code is licensed under the MIT license found in the
1560
+ * LICENSE file in the root directory of this source tree.
1561
+ */
1562
+ /**
1563
+ * Convert a Vector3-like object to a plain Vec3 object
1564
+ */
1565
+ function vec3ToObj(v) {
1566
+ return { x: v.x, y: v.y, z: v.z };
1567
+ }
1568
+ /**
1569
+ * Convert a Quaternion-like object to a plain Quat object
1570
+ */
1571
+ function quatToObj(q) {
1572
+ return { x: q.x, y: q.y, z: q.z, w: q.w };
1573
+ }
1574
+ /**
1575
+ * Convert quaternion to euler angles (in degrees)
1576
+ * Uses YXZ order (yaw-pitch-roll) which is standard for XR:
1577
+ * - Yaw: rotation around Y axis (turning left/right)
1578
+ * - Pitch: rotation around X axis (looking up/down)
1579
+ * - Roll: rotation around Z axis (tilting head)
1580
+ */
1581
+ function quatToEuler(q) {
1582
+ const { x, y, z, w } = q;
1583
+ const RAD_TO_DEG = 180 / Math.PI;
1584
+ // YXZ order
1585
+ const sinp = Math.max(-1, Math.min(1, 2 * (w * x - y * z)));
1586
+ let pitch;
1587
+ if (Math.abs(sinp) >= 1) {
1588
+ pitch = (Math.sign(sinp) * Math.PI) / 2;
1589
+ }
1590
+ else {
1591
+ pitch = Math.asin(sinp);
1592
+ }
1593
+ const siny_cosp = 2 * (w * y + x * z);
1594
+ const cosy_cosp = 1 - 2 * (x * x + y * y);
1595
+ const yaw = Math.atan2(siny_cosp, cosy_cosp);
1596
+ const sinr_cosp = 2 * (w * z + x * y);
1597
+ const cosr_cosp = 1 - 2 * (x * x + z * z);
1598
+ const roll = Math.atan2(sinr_cosp, cosr_cosp);
1599
+ return {
1600
+ pitch: pitch * RAD_TO_DEG,
1601
+ yaw: yaw * RAD_TO_DEG,
1602
+ roll: roll * RAD_TO_DEG,
1603
+ };
1604
+ }
1605
+ /**
1606
+ * Convert euler angles (in degrees) to quaternion
1607
+ * Uses YXZ order (yaw-pitch-roll) which is standard for XR:
1608
+ * - Yaw: rotation around Y axis (turning left/right)
1609
+ * - Pitch: rotation around X axis (looking up/down)
1610
+ * - Roll: rotation around Z axis (tilting head)
1611
+ * Missing angles default to 0.
1612
+ */
1613
+ function eulerToQuat(euler) {
1614
+ var _a, _b, _c;
1615
+ const DEG_TO_RAD = Math.PI / 180;
1616
+ const pitch = ((_a = euler.pitch) !== null && _a !== void 0 ? _a : 0) * DEG_TO_RAD; // X-axis
1617
+ const yaw = ((_b = euler.yaw) !== null && _b !== void 0 ? _b : 0) * DEG_TO_RAD; // Y-axis
1618
+ const roll = ((_c = euler.roll) !== null && _c !== void 0 ? _c : 0) * DEG_TO_RAD; // Z-axis
1619
+ // Half angles
1620
+ const cx = Math.cos(pitch * 0.5);
1621
+ const sx = Math.sin(pitch * 0.5);
1622
+ const cy = Math.cos(yaw * 0.5);
1623
+ const sy = Math.sin(yaw * 0.5);
1624
+ const cz = Math.cos(roll * 0.5);
1625
+ const sz = Math.sin(roll * 0.5);
1626
+ // YXZ order: first yaw, then pitch, then roll
1627
+ return {
1628
+ w: cx * cy * cz + sx * sy * sz,
1629
+ x: sx * cy * cz + cx * sy * sz,
1630
+ y: cx * sy * cz - sx * cy * sz,
1631
+ z: cx * cy * sz - sx * sy * cz,
1632
+ };
1633
+ }
1634
+ /**
1635
+ * Calculate normalized direction vector from one point to another
1636
+ * Returns default forward direction (0, 0, -1) if points are coincident
1637
+ */
1638
+ function directionTo(from, to) {
1639
+ const dx = to.x - from.x;
1640
+ const dy = to.y - from.y;
1641
+ const dz = to.z - from.z;
1642
+ const length = Math.sqrt(dx * dx + dy * dy + dz * dz);
1643
+ if (length === 0) {
1644
+ return { x: 0, y: 0, z: -1 }; // Default forward (WebXR convention)
1645
+ }
1646
+ return {
1647
+ x: dx / length,
1648
+ y: dy / length,
1649
+ z: dz / length,
1650
+ };
1651
+ }
1652
+ /**
1653
+ * Calculate gimbal-style look rotation (yaw + pitch only, roll = 0)
1654
+ * This keeps the camera/headset level while looking at a target.
1655
+ * @param direction - The direction to look towards
1656
+ * @returns Quaternion with only yaw and pitch, no roll
1657
+ */
1658
+ function lookRotationGimbal(direction) {
1659
+ // Calculate horizontal distance
1660
+ const horizontalDist = Math.sqrt(direction.x * direction.x + direction.z * direction.z);
1661
+ // Calculate yaw: rotation around Y axis to face target horizontally
1662
+ // atan2(-z, -x) gives angle from negative Z axis (forward in WebXR)
1663
+ // We use -z, x to match WebXR's -Z forward convention
1664
+ let yaw = 0;
1665
+ if (horizontalDist > 0.0001) {
1666
+ yaw = Math.atan2(-direction.x, -direction.z);
1667
+ }
1668
+ // Calculate pitch: rotation around X axis to look up/down
1669
+ // Positive direction.y (target above) = positive pitch (look up)
1670
+ // Negative direction.y (target below) = negative pitch (look down)
1671
+ const pitch = Math.atan2(direction.y, horizontalDist);
1672
+ // Convert to degrees and create quaternion (roll = 0)
1673
+ const RAD_TO_DEG = 180 / Math.PI;
1674
+ return eulerToQuat({
1675
+ pitch: pitch * RAD_TO_DEG,
1676
+ yaw: yaw * RAD_TO_DEG,
1677
+ roll: 0,
1678
+ });
1679
+ }
1680
+ /**
1681
+ * Calculate quaternion that looks from origin towards a direction
1682
+ * @param direction - The direction to look towards (will be normalized)
1683
+ * @param up - The up vector (default: world up Y-axis)
1684
+ */
1685
+ function lookRotation(direction, up = { x: 0, y: 1, z: 0 }) {
1686
+ // Normalize direction
1687
+ const dirLen = Math.sqrt(direction.x * direction.x +
1688
+ direction.y * direction.y +
1689
+ direction.z * direction.z);
1690
+ if (dirLen === 0) {
1691
+ return { x: 0, y: 0, z: 0, w: 1 }; // Identity quaternion
1692
+ }
1693
+ const forward = {
1694
+ x: direction.x / dirLen,
1695
+ y: direction.y / dirLen,
1696
+ z: direction.z / dirLen,
1697
+ };
1698
+ // Calculate right vector (cross product of forward and up, NOT up and forward)
1699
+ // forward × up gives correct right-hand orientation
1700
+ const right = {
1701
+ x: forward.y * up.z - forward.z * up.y,
1702
+ y: forward.z * up.x - forward.x * up.z,
1703
+ z: forward.x * up.y - forward.y * up.x,
1704
+ };
1705
+ const rightLen = Math.sqrt(right.x * right.x + right.y * right.y + right.z * right.z);
1706
+ if (rightLen === 0) {
1707
+ // Direction is parallel to up, choose a different up
1708
+ const altUp = { x: 1, y: 0, z: 0 };
1709
+ right.x = forward.y * altUp.z - forward.z * altUp.y;
1710
+ right.y = forward.z * altUp.x - forward.x * altUp.z;
1711
+ right.z = forward.x * altUp.y - forward.y * altUp.x;
1712
+ const altRightLen = Math.sqrt(right.x * right.x + right.y * right.y + right.z * right.z);
1713
+ right.x /= altRightLen;
1714
+ right.y /= altRightLen;
1715
+ right.z /= altRightLen;
1716
+ }
1717
+ else {
1718
+ right.x /= rightLen;
1719
+ right.y /= rightLen;
1720
+ right.z /= rightLen;
1721
+ }
1722
+ // Recalculate up (cross product of right and forward for proper orientation)
1723
+ const newUp = {
1724
+ x: right.y * forward.z - right.z * forward.y,
1725
+ y: right.z * forward.x - right.x * forward.z,
1726
+ z: right.x * forward.y - right.y * forward.x,
1727
+ };
1728
+ // Build rotation matrix and convert to quaternion
1729
+ // Matrix: [right, newUp, -forward] (column vectors)
1730
+ const m00 = right.x, m01 = newUp.x, m02 = -forward.x;
1731
+ const m10 = right.y, m11 = newUp.y, m12 = -forward.y;
1732
+ const m20 = right.z, m21 = newUp.z, m22 = -forward.z;
1733
+ const trace = m00 + m11 + m22;
1734
+ let qw, qx, qy, qz;
1735
+ if (trace > 0) {
1736
+ const s = 0.5 / Math.sqrt(trace + 1.0);
1737
+ qw = 0.25 / s;
1738
+ qx = (m21 - m12) * s;
1739
+ qy = (m02 - m20) * s;
1740
+ qz = (m10 - m01) * s;
1741
+ }
1742
+ else if (m00 > m11 && m00 > m22) {
1743
+ const s = 2.0 * Math.sqrt(1.0 + m00 - m11 - m22);
1744
+ qw = (m21 - m12) / s;
1745
+ qx = 0.25 * s;
1746
+ qy = (m01 + m10) / s;
1747
+ qz = (m02 + m20) / s;
1748
+ }
1749
+ else if (m11 > m22) {
1750
+ const s = 2.0 * Math.sqrt(1.0 + m11 - m00 - m22);
1751
+ qw = (m02 - m20) / s;
1752
+ qx = (m01 + m10) / s;
1753
+ qy = 0.25 * s;
1754
+ qz = (m12 + m21) / s;
1755
+ }
1756
+ else {
1757
+ const s = 2.0 * Math.sqrt(1.0 + m22 - m00 - m11);
1758
+ qw = (m10 - m01) / s;
1759
+ qx = (m02 + m20) / s;
1760
+ qy = (m12 + m21) / s;
1761
+ qz = 0.25 * s;
1762
+ }
1763
+ // Normalize the quaternion to ensure unit length
1764
+ const len = Math.sqrt(qx * qx + qy * qy + qz * qz + qw * qw);
1765
+ if (len > 0) {
1766
+ qx /= len;
1767
+ qy /= len;
1768
+ qz /= len;
1769
+ qw /= len;
1770
+ }
1771
+ return { x: qx, y: qy, z: qz, w: qw };
1772
+ }
1773
+ /**
1774
+ * Wait for a condition to become true, checking each animation frame
1775
+ */
1776
+ function waitForCondition(condition, timeoutMs = 5000) {
1777
+ return new Promise((resolve, reject) => {
1778
+ const startTime = Date.now();
1779
+ const check = () => {
1780
+ if (condition()) {
1781
+ resolve();
1782
+ }
1783
+ else if (Date.now() - startTime > timeoutMs) {
1784
+ reject(new Error('Timeout waiting for condition'));
1785
+ }
1786
+ else {
1787
+ requestAnimationFrame(check);
1788
+ }
1789
+ };
1790
+ check();
1791
+ });
1792
+ }
1793
+
1794
+ /**
1795
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1796
+ *
1797
+ * This source code is licensed under the MIT license found in the
1798
+ * LICENSE file in the root directory of this source tree.
1799
+ */
1800
+ /**
1801
+ * Check if an orientation input is euler angles (has any of pitch, yaw, or roll)
1802
+ */
1803
+ function isEulerRotation(orientation) {
1804
+ return 'pitch' in orientation || 'yaw' in orientation || 'roll' in orientation;
1805
+ }
1806
+ /**
1807
+ * Normalize an orientation input to a quaternion
1808
+ */
1809
+ function normalizeOrientation(orientation) {
1810
+ if (isEulerRotation(orientation)) {
1811
+ return eulerToQuat(orientation);
1812
+ }
1813
+ return orientation;
1814
+ }
1815
+ /**
1816
+ * Linear interpolation for numbers
1817
+ */
1818
+ function lerp(a, b, t) {
1819
+ return a + (b - a) * t;
1820
+ }
1821
+ /**
1822
+ * Linear interpolation for Vec3
1823
+ */
1824
+ function lerpVec3(a, b, t) {
1825
+ return {
1826
+ x: lerp(a.x, b.x, t),
1827
+ y: lerp(a.y, b.y, t),
1828
+ z: lerp(a.z, b.z, t),
1829
+ };
1830
+ }
1831
+ /**
1832
+ * Spherical linear interpolation for quaternions
1833
+ */
1834
+ function slerpQuat(a, b, t) {
1835
+ // Compute dot product
1836
+ let dot = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
1837
+ // If dot is negative, negate one quaternion to take shorter path
1838
+ let bx = b.x, by = b.y, bz = b.z, bw = b.w;
1839
+ if (dot < 0) {
1840
+ dot = -dot;
1841
+ bx = -bx;
1842
+ by = -by;
1843
+ bz = -bz;
1844
+ bw = -bw;
1845
+ }
1846
+ // If quaternions are very close, use linear interpolation
1847
+ if (dot > 0.9995) {
1848
+ const result = {
1849
+ x: lerp(a.x, bx, t),
1850
+ y: lerp(a.y, by, t),
1851
+ z: lerp(a.z, bz, t),
1852
+ w: lerp(a.w, bw, t),
1853
+ };
1854
+ // Normalize
1855
+ const len = Math.sqrt(result.x * result.x +
1856
+ result.y * result.y +
1857
+ result.z * result.z +
1858
+ result.w * result.w);
1859
+ return {
1860
+ x: result.x / len,
1861
+ y: result.y / len,
1862
+ z: result.z / len,
1863
+ w: result.w / len,
1864
+ };
1865
+ }
1866
+ // Standard slerp
1867
+ const theta0 = Math.acos(dot);
1868
+ const theta = theta0 * t;
1869
+ const sinTheta = Math.sin(theta);
1870
+ const sinTheta0 = Math.sin(theta0);
1871
+ const s0 = Math.cos(theta) - (dot * sinTheta) / sinTheta0;
1872
+ const s1 = sinTheta / sinTheta0;
1873
+ return {
1874
+ x: s0 * a.x + s1 * bx,
1875
+ y: s0 * a.y + s1 * by,
1876
+ z: s0 * a.z + s1 * bz,
1877
+ w: s0 * a.w + s1 * bw,
1878
+ };
1879
+ }
1880
+ /**
1881
+ * RemoteControlInterface provides frame-synchronized programmatic control of an XRDevice.
1882
+ *
1883
+ * This class implements a command queue that processes actions during each frame update,
1884
+ * enabling smooth animations and coordinated control with DevUI.
1885
+ *
1886
+ * Key features:
1887
+ * - Frame-synchronized execution: Commands are queued and processed during frame update
1888
+ * - Duration-based actions: Smooth animations via lerp over multiple frames
1889
+ * - Automatic capture/release: Captures device on first command, releases 30s after queue empties
1890
+ * - Unified device identifiers: 'headset', 'controller-left', 'hand-right', etc.
1891
+ *
1892
+ * Usage:
1893
+ * ```typescript
1894
+ * import { XRDevice, metaQuest3 } from 'iwer';
1895
+ *
1896
+ * const device = new XRDevice(metaQuest3);
1897
+ * device.installRuntime();
1898
+ *
1899
+ * // Get transform
1900
+ * const result = await device.remote.dispatch('get_transform', { device: 'headset' });
1901
+ *
1902
+ * // Animate headset to new position over 1 second
1903
+ * await device.remote.dispatch('animate_to', {
1904
+ * device: 'headset',
1905
+ * position: { x: 0, y: 1.6, z: -1 },
1906
+ * duration: 1.0
1907
+ * });
1908
+ * ```
1909
+ */
1910
+ class RemoteControlInterface {
1911
+ constructor(device) {
1912
+ this.commandQueue = [];
1913
+ this._isCaptured = false;
1914
+ this.releaseTimer = null;
1915
+ this.actionIdCounter = 0;
1916
+ /** Release timeout in milliseconds (default: 30000 = 30 seconds) */
1917
+ this.RELEASE_TIMEOUT_MS = 30000;
1918
+ this.device = device;
1919
+ }
1920
+ generateActionId() {
1921
+ return `action_${++this.actionIdCounter}`;
1922
+ }
1923
+ // =============================================================================
1924
+ // Public Properties
1925
+ // =============================================================================
1926
+ /**
1927
+ * Whether the device is currently captured for programmatic control.
1928
+ * When true, DevUI should go into passive mode (sync FROM device only).
1929
+ */
1930
+ get isCaptured() {
1931
+ return this._isCaptured;
1932
+ }
1933
+ /**
1934
+ * Number of pending actions in the queue
1935
+ */
1936
+ get queueLength() {
1937
+ return this.commandQueue.length;
1938
+ }
1939
+ // =============================================================================
1940
+ // Queue Management
1941
+ // =============================================================================
1942
+ /**
1943
+ * Enqueue a discrete action for processing
1944
+ */
1945
+ enqueueDiscrete(method, params) {
1946
+ return new Promise((resolve, reject) => {
1947
+ const action = {
1948
+ type: 'discrete',
1949
+ id: this.generateActionId(),
1950
+ method,
1951
+ params,
1952
+ resolve,
1953
+ reject,
1954
+ };
1955
+ this.commandQueue.push(action);
1956
+ });
1957
+ }
1958
+ /**
1959
+ * Enqueue a duration action for processing
1960
+ */
1961
+ enqueueDuration(method, params, durationMs, startState, targetState) {
1962
+ return new Promise((resolve, reject) => {
1963
+ const action = {
1964
+ type: 'duration',
1965
+ id: this.generateActionId(),
1966
+ method,
1967
+ params,
1968
+ durationMs,
1969
+ elapsedMs: 0,
1970
+ startState,
1971
+ targetState,
1972
+ resolve,
1973
+ reject,
1974
+ };
1975
+ this.commandQueue.push(action);
1976
+ });
1977
+ }
1978
+ /**
1979
+ * Update method called each frame by XRDevice.
1980
+ * Processes the command queue and handles duration-based animations.
1981
+ *
1982
+ * @param deltaTimeMs - Time since last frame in milliseconds
1983
+ */
1984
+ update(deltaTimeMs) {
1985
+ if (this.commandQueue.length === 0) {
1986
+ return;
1987
+ }
1988
+ // Always cancel pending release while queue is active
1989
+ this.cancelReleaseTimer();
1990
+ // Activate capture mode
1991
+ if (!this._isCaptured) {
1992
+ this._isCaptured = true;
1993
+ this.device.controlMode = 'programmatic';
1994
+ }
1995
+ while (this.commandQueue.length > 0) {
1996
+ const action = this.commandQueue[0];
1997
+ if (action.type === 'discrete') {
1998
+ // Execute discrete action immediately
1999
+ try {
2000
+ const result = this.executeDiscreteAction(action);
2001
+ action.resolve(result);
2002
+ }
2003
+ catch (error) {
2004
+ action.reject(error);
2005
+ }
2006
+ this.commandQueue.shift();
2007
+ // Continue to next action
2008
+ }
2009
+ else {
2010
+ // Duration action - lerp by delta time
2011
+ action.elapsedMs += deltaTimeMs;
2012
+ if (action.elapsedMs >= action.durationMs) {
2013
+ // Complete - apply final state
2014
+ this.applyDurationFinalState(action);
2015
+ action.resolve(this.getDurationResult(action));
2016
+ this.commandQueue.shift();
2017
+ // Continue to next action
2018
+ }
2019
+ else {
2020
+ // In progress - lerp
2021
+ const t = action.elapsedMs / action.durationMs;
2022
+ this.applyDurationLerpState(action, t);
2023
+ // Stop processing - wait for next frame
2024
+ break;
2025
+ }
2026
+ }
2027
+ }
2028
+ // Notify state change
2029
+ this.device.notifyStateChange();
2030
+ // Start release timer if queue is empty
2031
+ if (this.commandQueue.length === 0) {
2032
+ this.startReleaseTimer();
2033
+ }
2034
+ }
2035
+ startReleaseTimer() {
2036
+ this.cancelReleaseTimer();
2037
+ this.releaseTimer = setTimeout(() => {
2038
+ this._isCaptured = false;
2039
+ this.device.controlMode = 'manual';
2040
+ this.releaseTimer = null;
2041
+ }, this.RELEASE_TIMEOUT_MS);
2042
+ }
2043
+ cancelReleaseTimer() {
2044
+ if (this.releaseTimer !== null) {
2045
+ clearTimeout(this.releaseTimer);
2046
+ this.releaseTimer = null;
2047
+ }
2048
+ }
2049
+ // =============================================================================
2050
+ // Device Resolution
2051
+ // =============================================================================
2052
+ /**
2053
+ * Get the transform (position, quaternion) for a device
2054
+ */
2055
+ getDeviceTransform(deviceId) {
2056
+ switch (deviceId) {
2057
+ case 'headset':
2058
+ return {
2059
+ position: vec3ToObj(this.device.position),
2060
+ orientation: quatToObj(this.device.quaternion),
2061
+ };
2062
+ case 'controller-left': {
2063
+ const controller = this.device.controllers.left;
2064
+ if (!controller)
2065
+ throw new Error('Left controller not available');
2066
+ return {
2067
+ position: vec3ToObj(controller.position),
2068
+ orientation: quatToObj(controller.quaternion),
2069
+ };
2070
+ }
2071
+ case 'controller-right': {
2072
+ const controller = this.device.controllers.right;
2073
+ if (!controller)
2074
+ throw new Error('Right controller not available');
2075
+ return {
2076
+ position: vec3ToObj(controller.position),
2077
+ orientation: quatToObj(controller.quaternion),
2078
+ };
2079
+ }
2080
+ case 'hand-left': {
2081
+ const hand = this.device.hands.left;
2082
+ if (!hand)
2083
+ throw new Error('Left hand not available');
2084
+ return {
2085
+ position: vec3ToObj(hand.position),
2086
+ orientation: quatToObj(hand.quaternion),
2087
+ };
2088
+ }
2089
+ case 'hand-right': {
2090
+ const hand = this.device.hands.right;
2091
+ if (!hand)
2092
+ throw new Error('Right hand not available');
2093
+ return {
2094
+ position: vec3ToObj(hand.position),
2095
+ orientation: quatToObj(hand.quaternion),
2096
+ };
2097
+ }
2098
+ default:
2099
+ throw new Error(`Unknown device: ${deviceId}`);
2100
+ }
2101
+ }
2102
+ /**
2103
+ * Set the transform for a device
2104
+ */
2105
+ setDeviceTransform(deviceId, position, orientation) {
2106
+ switch (deviceId) {
2107
+ case 'headset':
2108
+ if (position) {
2109
+ this.device.position.set(position.x, position.y, position.z);
2110
+ }
2111
+ if (orientation) {
2112
+ this.device.quaternion.set(orientation.x, orientation.y, orientation.z, orientation.w);
2113
+ }
2114
+ break;
2115
+ case 'controller-left': {
2116
+ const controller = this.device.controllers.left;
2117
+ if (!controller)
2118
+ throw new Error('Left controller not available');
2119
+ if (position) {
2120
+ controller.position.set(position.x, position.y, position.z);
2121
+ }
2122
+ if (orientation) {
2123
+ controller.quaternion.set(orientation.x, orientation.y, orientation.z, orientation.w);
2124
+ }
2125
+ break;
2126
+ }
2127
+ case 'controller-right': {
2128
+ const controller = this.device.controllers.right;
2129
+ if (!controller)
2130
+ throw new Error('Right controller not available');
2131
+ if (position) {
2132
+ controller.position.set(position.x, position.y, position.z);
2133
+ }
2134
+ if (orientation) {
2135
+ controller.quaternion.set(orientation.x, orientation.y, orientation.z, orientation.w);
2136
+ }
2137
+ break;
2138
+ }
2139
+ case 'hand-left': {
2140
+ const hand = this.device.hands.left;
2141
+ if (!hand)
2142
+ throw new Error('Left hand not available');
2143
+ if (position) {
2144
+ hand.position.set(position.x, position.y, position.z);
2145
+ }
2146
+ if (orientation) {
2147
+ hand.quaternion.set(orientation.x, orientation.y, orientation.z, orientation.w);
2148
+ }
2149
+ break;
2150
+ }
2151
+ case 'hand-right': {
2152
+ const hand = this.device.hands.right;
2153
+ if (!hand)
2154
+ throw new Error('Right hand not available');
2155
+ if (position) {
2156
+ hand.position.set(position.x, position.y, position.z);
2157
+ }
2158
+ if (orientation) {
2159
+ hand.quaternion.set(orientation.x, orientation.y, orientation.z, orientation.w);
2160
+ }
2161
+ break;
2162
+ }
2163
+ default:
2164
+ throw new Error(`Unknown device: ${deviceId}`);
2165
+ }
2166
+ }
2167
+ /**
2168
+ * Transform a position from XR-origin-relative coordinates to GlobalSpace.
2169
+ * The XR origin is defined by the first reference space requested by the app.
2170
+ * This is necessary because device positions are in GlobalSpace, but positions
2171
+ * from get_object_transform are relative to the XR origin.
2172
+ */
2173
+ transformXROriginToGlobal(position) {
2174
+ var _a, _b;
2175
+ const session = this.device.activeSession;
2176
+ if (!session) {
2177
+ return position;
2178
+ }
2179
+ const refSpaces = (_a = session[P_SESSION]) === null || _a === void 0 ? void 0 : _a.referenceSpaces;
2180
+ if (!refSpaces || refSpaces.length === 0) {
2181
+ return position;
2182
+ }
2183
+ // Use the first reference space (primary one requested by app)
2184
+ const primaryRefSpace = refSpaces[0];
2185
+ const offsetMatrix = (_b = primaryRefSpace[P_SPACE]) === null || _b === void 0 ? void 0 : _b.offsetMatrix;
2186
+ if (!offsetMatrix) {
2187
+ return position;
2188
+ }
2189
+ // Transform position from XR-origin space to GlobalSpace
2190
+ const posVec = fromValues$2(position.x, position.y, position.z);
2191
+ transformMat4$1(posVec, posVec, offsetMatrix);
2192
+ return {
2193
+ x: posVec[0],
2194
+ y: posVec[1],
2195
+ z: posVec[2],
2196
+ };
2197
+ }
2198
+ /**
2199
+ * Get the select value for an input device (trigger for controller, pinch for hand)
2200
+ */
2201
+ getDeviceSelectValue(deviceId) {
2202
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2203
+ switch (deviceId) {
2204
+ case 'controller-left':
2205
+ return (_b = (_a = this.device.controllers.left) === null || _a === void 0 ? void 0 : _a.getButtonValue('trigger')) !== null && _b !== void 0 ? _b : 0;
2206
+ case 'controller-right':
2207
+ return (_d = (_c = this.device.controllers.right) === null || _c === void 0 ? void 0 : _c.getButtonValue('trigger')) !== null && _d !== void 0 ? _d : 0;
2208
+ case 'hand-left':
2209
+ return (_f = (_e = this.device.hands.left) === null || _e === void 0 ? void 0 : _e.pinchValue) !== null && _f !== void 0 ? _f : 0;
2210
+ case 'hand-right':
2211
+ return (_h = (_g = this.device.hands.right) === null || _g === void 0 ? void 0 : _g.pinchValue) !== null && _h !== void 0 ? _h : 0;
2212
+ default:
2213
+ throw new Error(`Unknown input device: ${deviceId}`);
2214
+ }
2215
+ }
2216
+ /**
2217
+ * Set the select value for an input device
2218
+ */
2219
+ setDeviceSelectValue(deviceId, value) {
2220
+ var _a, _b, _c, _d;
2221
+ switch (deviceId) {
2222
+ case 'controller-left':
2223
+ (_a = this.device.controllers.left) === null || _a === void 0 ? void 0 : _a.updateButtonValue('trigger', value);
2224
+ break;
2225
+ case 'controller-right':
2226
+ (_b = this.device.controllers.right) === null || _b === void 0 ? void 0 : _b.updateButtonValue('trigger', value);
2227
+ break;
2228
+ case 'hand-left':
2229
+ (_c = this.device.hands.left) === null || _c === void 0 ? void 0 : _c.updatePinchValue(value);
2230
+ break;
2231
+ case 'hand-right':
2232
+ (_d = this.device.hands.right) === null || _d === void 0 ? void 0 : _d.updatePinchValue(value);
2233
+ break;
2234
+ default:
2235
+ throw new Error(`Unknown input device: ${deviceId}`);
2236
+ }
2237
+ }
2238
+ /**
2239
+ * Set connected state for an input device
2240
+ */
2241
+ setDeviceConnected(deviceId, connected) {
2242
+ switch (deviceId) {
2243
+ case 'controller-left':
2244
+ if (this.device.controllers.left) {
2245
+ this.device.controllers.left.connected = connected;
2246
+ }
2247
+ break;
2248
+ case 'controller-right':
2249
+ if (this.device.controllers.right) {
2250
+ this.device.controllers.right.connected = connected;
2251
+ }
2252
+ break;
2253
+ case 'hand-left':
2254
+ if (this.device.hands.left) {
2255
+ this.device.hands.left.connected = connected;
2256
+ }
2257
+ break;
2258
+ case 'hand-right':
2259
+ if (this.device.hands.right) {
2260
+ this.device.hands.right.connected = connected;
2261
+ }
2262
+ break;
2263
+ default:
2264
+ throw new Error(`Unknown input device: ${deviceId}`);
2265
+ }
2266
+ }
2267
+ // =============================================================================
2268
+ // Discrete Action Execution
2269
+ // =============================================================================
2270
+ executeDiscreteAction(action) {
2271
+ const { method, params } = action;
2272
+ switch (method) {
2273
+ // Session tools
2274
+ case 'get_session_status':
2275
+ return this.executeGetSessionStatus();
2276
+ case 'accept_session':
2277
+ return this.executeAcceptSession();
2278
+ case 'end_session':
2279
+ return this.executeEndSession();
2280
+ // Transform tools
2281
+ case 'get_transform':
2282
+ return this.executeGetTransform(params);
2283
+ case 'set_transform':
2284
+ return this.executeSetTransform(params);
2285
+ case 'look_at':
2286
+ return this.executeLookAt(params);
2287
+ // Input tools
2288
+ case 'set_input_mode':
2289
+ return this.executeSetInputMode(params);
2290
+ case 'set_connected':
2291
+ return this.executeSetConnected(params);
2292
+ case 'get_select_value':
2293
+ return this.executeGetSelectValue(params);
2294
+ case 'set_select_value':
2295
+ return this.executeSetSelectValue(params);
2296
+ // Gamepad tools
2297
+ case 'get_gamepad_state':
2298
+ return this.executeGetGamepadState(params);
2299
+ case 'set_gamepad_state':
2300
+ return this.executeSetGamepadState(params);
2301
+ // State tools
2302
+ case 'get_device_state':
2303
+ return this.executeGetDeviceState();
2304
+ case 'set_device_state':
2305
+ return this.executeSetDeviceState(params);
2306
+ case 'capture_canvas':
2307
+ return this.executeCaptureCanvas(params);
2308
+ // Internal select sequence actions
2309
+ case '_select_press': {
2310
+ const deviceId = params.device;
2311
+ this.setDeviceSelectValue(deviceId, 1);
2312
+ return undefined;
2313
+ }
2314
+ case '_select_release': {
2315
+ const deviceId = params.device;
2316
+ this.setDeviceSelectValue(deviceId, 0);
2317
+ return undefined;
2318
+ }
2319
+ default:
2320
+ throw new Error(`Unknown method: ${method}`);
2321
+ }
2322
+ }
2323
+ // =============================================================================
2324
+ // Session Tool Implementations
2325
+ // =============================================================================
2326
+ executeGetSessionStatus() {
2327
+ const session = this.device.activeSession;
2328
+ return {
2329
+ deviceName: this.device.name,
2330
+ isRuntimeInstalled: true,
2331
+ sessionActive: !!session,
2332
+ sessionOffered: this.device.sessionOffered,
2333
+ sessionMode: session ? session.mode : null,
2334
+ enabledFeatures: session
2335
+ ? Array.from(session.enabledFeatures || [])
2336
+ : [],
2337
+ visibilityState: this.device.visibilityState,
2338
+ };
2339
+ }
2340
+ executeAcceptSession() {
2341
+ if (!this.device.sessionOffered) {
2342
+ throw new Error('No session has been offered');
2343
+ }
2344
+ this.device.grantOfferedSession();
2345
+ // Session activation is async - caller should use get_session_status to poll
2346
+ return { success: true };
2347
+ }
2348
+ executeEndSession() {
2349
+ const session = this.device.activeSession;
2350
+ if (!session) {
2351
+ throw new Error('No active session');
2352
+ }
2353
+ session.end();
2354
+ return { success: true };
2355
+ }
2356
+ // =============================================================================
2357
+ // Transform Tool Implementations
2358
+ // =============================================================================
2359
+ executeGetTransform(params) {
2360
+ const { device: deviceId } = params;
2361
+ const transform = this.getDeviceTransform(deviceId);
2362
+ return {
2363
+ device: deviceId,
2364
+ position: transform.position,
2365
+ orientation: transform.orientation,
2366
+ euler: quatToEuler(transform.orientation),
2367
+ };
2368
+ }
2369
+ executeSetTransform(params) {
2370
+ const { device: deviceId, position, orientation } = params;
2371
+ const targetOrientation = orientation
2372
+ ? normalizeOrientation(orientation)
2373
+ : undefined;
2374
+ this.setDeviceTransform(deviceId, position, targetOrientation);
2375
+ const newTransform = this.getDeviceTransform(deviceId);
2376
+ return {
2377
+ device: deviceId,
2378
+ position: newTransform.position,
2379
+ orientation: newTransform.orientation,
2380
+ };
2381
+ }
2382
+ executeLookAt(params) {
2383
+ const { device: deviceId, target, moveToDistance } = params;
2384
+ const currentTransform = this.getDeviceTransform(deviceId);
2385
+ // Transform target from XR-origin-relative to GlobalSpace
2386
+ const targetInGlobal = this.transformXROriginToGlobal(target);
2387
+ // Calculate direction to target
2388
+ const direction = directionTo(currentTransform.position, targetInGlobal);
2389
+ // Calculate look rotation
2390
+ // Use gimbal rotation for headset (keeps it level, no roll)
2391
+ // Use standard lookRotation for controllers/hands (can tilt freely)
2392
+ const lookQuat = deviceId === 'headset'
2393
+ ? lookRotationGimbal(direction)
2394
+ : lookRotation(direction);
2395
+ // Optionally move to a specific distance from target
2396
+ let newPosition;
2397
+ if (moveToDistance !== undefined) {
2398
+ newPosition = {
2399
+ x: targetInGlobal.x - direction.x * moveToDistance,
2400
+ y: targetInGlobal.y - direction.y * moveToDistance,
2401
+ z: targetInGlobal.z - direction.z * moveToDistance,
2402
+ };
2403
+ }
2404
+ this.setDeviceTransform(deviceId, newPosition, lookQuat);
2405
+ const newTransform = this.getDeviceTransform(deviceId);
2406
+ return {
2407
+ device: deviceId,
2408
+ position: newTransform.position,
2409
+ orientation: newTransform.orientation,
2410
+ };
2411
+ }
2412
+ // =============================================================================
2413
+ // Input Tool Implementations
2414
+ // =============================================================================
2415
+ executeSetInputMode(params) {
2416
+ var _a, _b, _c, _d;
2417
+ const { mode } = params;
2418
+ this.device.primaryInputMode = mode;
2419
+ const activeDevices = [];
2420
+ if (mode === 'controller') {
2421
+ if ((_a = this.device.controllers.left) === null || _a === void 0 ? void 0 : _a.connected) {
2422
+ activeDevices.push('controller-left');
2423
+ }
2424
+ if ((_b = this.device.controllers.right) === null || _b === void 0 ? void 0 : _b.connected) {
2425
+ activeDevices.push('controller-right');
2426
+ }
2427
+ }
2428
+ else {
2429
+ if ((_c = this.device.hands.left) === null || _c === void 0 ? void 0 : _c.connected) {
2430
+ activeDevices.push('hand-left');
2431
+ }
2432
+ if ((_d = this.device.hands.right) === null || _d === void 0 ? void 0 : _d.connected) {
2433
+ activeDevices.push('hand-right');
2434
+ }
2435
+ }
2436
+ return { mode, activeDevices };
2437
+ }
2438
+ executeSetConnected(params) {
2439
+ const { device: deviceId, connected } = params;
2440
+ this.setDeviceConnected(deviceId, connected);
2441
+ return { device: deviceId, connected };
2442
+ }
2443
+ executeGetSelectValue(params) {
2444
+ const { device: deviceId } = params;
2445
+ const value = this.getDeviceSelectValue(deviceId);
2446
+ return { device: deviceId, value };
2447
+ }
2448
+ executeSetSelectValue(params) {
2449
+ const { device: deviceId, value } = params;
2450
+ this.setDeviceSelectValue(deviceId, value);
2451
+ return { device: deviceId, value };
2452
+ }
2453
+ // =============================================================================
2454
+ // Gamepad Tool Implementations
2455
+ // =============================================================================
2456
+ executeGetGamepadState(params) {
2457
+ const { device: deviceId } = params;
2458
+ const hand = deviceId === 'controller-left' ? 'left' : 'right';
2459
+ const controller = this.device.controllers[hand];
2460
+ if (!controller) {
2461
+ throw new Error(`Controller ${hand} not available`);
2462
+ }
2463
+ // Button layout for Meta Quest Touch Plus controllers
2464
+ // Use hand-conditional internal names for lookup
2465
+ const buttonInternalNames = [
2466
+ 'trigger',
2467
+ 'squeeze',
2468
+ 'thumbstick',
2469
+ hand === 'left' ? 'x-button' : 'a-button',
2470
+ hand === 'left' ? 'y-button' : 'b-button',
2471
+ 'thumbrest',
2472
+ ];
2473
+ const buttons = buttonInternalNames.map((name, index) => ({
2474
+ index,
2475
+ name: name
2476
+ .replace('x-button', 'x')
2477
+ .replace('y-button', 'y')
2478
+ .replace('a-button', 'a')
2479
+ .replace('b-button', 'b'),
2480
+ value: controller.getButtonValue(name),
2481
+ touched: controller.getButtonTouched(name),
2482
+ pressed: controller.getButtonValue(name) > 0.5,
2483
+ }));
2484
+ const axesData = controller.getAxes();
2485
+ const axes = [
2486
+ { index: 0, name: 'thumbstick-x', value: axesData.x },
2487
+ { index: 1, name: 'thumbstick-y', value: axesData.y },
2488
+ ];
2489
+ return {
2490
+ device: deviceId,
2491
+ connected: controller.connected,
2492
+ buttons,
2493
+ axes,
2494
+ };
2495
+ }
2496
+ executeSetGamepadState(params) {
2497
+ const { device: deviceId, buttons, axes } = params;
2498
+ const hand = deviceId === 'controller-left' ? 'left' : 'right';
2499
+ const controller = this.device.controllers[hand];
2500
+ if (!controller) {
2501
+ throw new Error(`Controller ${hand} not available`);
2502
+ }
2503
+ let buttonsSet = 0;
2504
+ let axesSet = 0;
2505
+ // Button index to name mapping
2506
+ const buttonIndexToName = [
2507
+ 'trigger',
2508
+ 'squeeze',
2509
+ 'thumbstick',
2510
+ hand === 'left' ? 'x-button' : 'a-button',
2511
+ hand === 'left' ? 'y-button' : 'b-button',
2512
+ 'thumbrest',
2513
+ ];
2514
+ if (buttons) {
2515
+ for (const btn of buttons) {
2516
+ const buttonName = buttonIndexToName[btn.index];
2517
+ if (buttonName) {
2518
+ // Use updateButtonValue for proper event triggering
2519
+ controller.updateButtonValue(buttonName, btn.value);
2520
+ if (btn.touched !== undefined) {
2521
+ controller.updateButtonTouch(buttonName, btn.touched);
2522
+ }
2523
+ buttonsSet++;
2524
+ }
2525
+ }
2526
+ }
2527
+ if (axes) {
2528
+ let xValue;
2529
+ let yValue;
2530
+ for (const axis of axes) {
2531
+ if (axis.index === 0) {
2532
+ xValue = axis.value;
2533
+ axesSet++;
2534
+ }
2535
+ else if (axis.index === 1) {
2536
+ yValue = axis.value;
2537
+ axesSet++;
2538
+ }
2539
+ }
2540
+ if (xValue !== undefined || yValue !== undefined) {
2541
+ const currentAxes = controller.getAxes();
2542
+ controller.updateAxes('thumbstick', xValue !== null && xValue !== void 0 ? xValue : currentAxes.x, yValue !== null && yValue !== void 0 ? yValue : currentAxes.y);
2543
+ }
2544
+ }
2545
+ return { device: deviceId, buttonsSet, axesSet };
2546
+ }
2547
+ // =============================================================================
2548
+ // State Tool Implementations
2549
+ // =============================================================================
2550
+ executeGetDeviceState() {
2551
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z;
2552
+ return {
2553
+ headset: {
2554
+ position: vec3ToObj(this.device.position),
2555
+ orientation: quatToObj(this.device.quaternion),
2556
+ },
2557
+ inputMode: this.device.primaryInputMode,
2558
+ controllers: {
2559
+ left: {
2560
+ connected: (_b = (_a = this.device.controllers.left) === null || _a === void 0 ? void 0 : _a.connected) !== null && _b !== void 0 ? _b : false,
2561
+ position: vec3ToObj((_d = (_c = this.device.controllers.left) === null || _c === void 0 ? void 0 : _c.position) !== null && _d !== void 0 ? _d : { x: 0, y: 0, z: 0 }),
2562
+ orientation: quatToObj((_f = (_e = this.device.controllers.left) === null || _e === void 0 ? void 0 : _e.quaternion) !== null && _f !== void 0 ? _f : {
2563
+ x: 0,
2564
+ y: 0,
2565
+ z: 0,
2566
+ w: 1,
2567
+ }),
2568
+ },
2569
+ right: {
2570
+ connected: (_h = (_g = this.device.controllers.right) === null || _g === void 0 ? void 0 : _g.connected) !== null && _h !== void 0 ? _h : false,
2571
+ position: vec3ToObj((_k = (_j = this.device.controllers.right) === null || _j === void 0 ? void 0 : _j.position) !== null && _k !== void 0 ? _k : { x: 0, y: 0, z: 0 }),
2572
+ orientation: quatToObj((_m = (_l = this.device.controllers.right) === null || _l === void 0 ? void 0 : _l.quaternion) !== null && _m !== void 0 ? _m : {
2573
+ x: 0,
2574
+ y: 0,
2575
+ z: 0,
2576
+ w: 1,
2577
+ }),
2578
+ },
2579
+ },
2580
+ hands: {
2581
+ left: {
2582
+ connected: (_p = (_o = this.device.hands.left) === null || _o === void 0 ? void 0 : _o.connected) !== null && _p !== void 0 ? _p : false,
2583
+ position: vec3ToObj((_r = (_q = this.device.hands.left) === null || _q === void 0 ? void 0 : _q.position) !== null && _r !== void 0 ? _r : { x: 0, y: 0, z: 0 }),
2584
+ orientation: quatToObj((_t = (_s = this.device.hands.left) === null || _s === void 0 ? void 0 : _s.quaternion) !== null && _t !== void 0 ? _t : { x: 0, y: 0, z: 0, w: 1 }),
2585
+ },
2586
+ right: {
2587
+ connected: (_v = (_u = this.device.hands.right) === null || _u === void 0 ? void 0 : _u.connected) !== null && _v !== void 0 ? _v : false,
2588
+ position: vec3ToObj((_x = (_w = this.device.hands.right) === null || _w === void 0 ? void 0 : _w.position) !== null && _x !== void 0 ? _x : { x: 0, y: 0, z: 0 }),
2589
+ orientation: quatToObj((_z = (_y = this.device.hands.right) === null || _y === void 0 ? void 0 : _y.quaternion) !== null && _z !== void 0 ? _z : { x: 0, y: 0, z: 0, w: 1 }),
2590
+ },
2591
+ },
2592
+ stereoEnabled: this.device.stereoEnabled,
2593
+ fov: this.device.fovy * (180 / Math.PI), // Convert to degrees
2594
+ };
2595
+ }
2596
+ executeSetDeviceState(params) {
2597
+ const { state } = params;
2598
+ if (!state) {
2599
+ // Reset to initial state
2600
+ this.device.position.set(0, 1.6, 0);
2601
+ this.device.quaternion.set(0, 0, 0, 1);
2602
+ this.device.primaryInputMode = 'controller';
2603
+ this.device.stereoEnabled = false;
2604
+ // Reset controllers and hands to default positions
2605
+ if (this.device.controllers.left) {
2606
+ this.device.controllers.left.position.set(-0.2, 1.4, -0.3);
2607
+ this.device.controllers.left.quaternion.set(0, 0, 0, 1);
2608
+ this.device.controllers.left.connected = true;
2609
+ }
2610
+ if (this.device.controllers.right) {
2611
+ this.device.controllers.right.position.set(0.2, 1.4, -0.3);
2612
+ this.device.controllers.right.quaternion.set(0, 0, 0, 1);
2613
+ this.device.controllers.right.connected = true;
2614
+ }
2615
+ if (this.device.hands.left) {
2616
+ this.device.hands.left.position.set(-0.15, 1.3, -0.4);
2617
+ this.device.hands.left.quaternion.set(0, 0, 0, 1);
2618
+ this.device.hands.left.connected = true;
2619
+ }
2620
+ if (this.device.hands.right) {
2621
+ this.device.hands.right.position.set(0.15, 1.3, -0.4);
2622
+ this.device.hands.right.quaternion.set(0, 0, 0, 1);
2623
+ this.device.hands.right.connected = true;
2624
+ }
2625
+ }
2626
+ else {
2627
+ // Apply partial state
2628
+ if (state.headset) {
2629
+ if (state.headset.position) {
2630
+ this.device.position.set(state.headset.position.x, state.headset.position.y, state.headset.position.z);
2631
+ }
2632
+ if (state.headset.orientation) {
2633
+ this.device.quaternion.set(state.headset.orientation.x, state.headset.orientation.y, state.headset.orientation.z, state.headset.orientation.w);
2634
+ }
2635
+ }
2636
+ if (state.inputMode !== undefined) {
2637
+ this.device.primaryInputMode = state.inputMode;
2638
+ }
2639
+ if (state.stereoEnabled !== undefined) {
2640
+ this.device.stereoEnabled = state.stereoEnabled;
2641
+ }
2642
+ if (state.fov !== undefined) {
2643
+ this.device.fovy = state.fov * (Math.PI / 180); // Convert to radians
2644
+ }
2645
+ if (state.controllers) {
2646
+ this.applyInputState('controller-left', state.controllers.left);
2647
+ this.applyInputState('controller-right', state.controllers.right);
2648
+ }
2649
+ if (state.hands) {
2650
+ this.applyInputState('hand-left', state.hands.left);
2651
+ this.applyInputState('hand-right', state.hands.right);
2652
+ }
2653
+ }
2654
+ return { state: this.executeGetDeviceState() };
2655
+ }
2656
+ applyInputState(deviceId, state) {
2657
+ if (!state)
2658
+ return;
2659
+ if (state.connected !== undefined) {
2660
+ this.setDeviceConnected(deviceId, state.connected);
2661
+ }
2662
+ if (state.position || state.orientation) {
2663
+ this.setDeviceTransform(deviceId, state.position, state.orientation);
2664
+ }
2665
+ }
2666
+ executeCaptureCanvas(params) {
2667
+ const { maxWidth = 800, format = 'png', quality = 0.92 } = params;
2668
+ // Get the app canvas - try device first, then fallback to DOM query
2669
+ let canvas = this.device.appCanvas;
2670
+ if (!canvas) {
2671
+ // No active session - try to find the canvas in the DOM
2672
+ // Before XR session, only the app's canvas is in the DOM
2673
+ // (IWER's canvases are not added until session starts)
2674
+ const canvases = document.querySelectorAll('canvas');
2675
+ if (canvases.length === 1) {
2676
+ canvas = canvases[0];
2677
+ }
2678
+ else if (canvases.length > 1) {
2679
+ // Multiple canvases - try to find the most likely app canvas
2680
+ // Prefer the largest visible canvas
2681
+ let bestCanvas = null;
2682
+ let bestArea = 0;
2683
+ canvases.forEach((c) => {
2684
+ const rect = c.getBoundingClientRect();
2685
+ const area = rect.width * rect.height;
2686
+ if (area > bestArea && rect.width > 0 && rect.height > 0) {
2687
+ bestArea = area;
2688
+ bestCanvas = c;
2689
+ }
2690
+ });
2691
+ canvas = bestCanvas;
2692
+ }
2693
+ }
2694
+ if (!canvas) {
2695
+ throw new Error('No canvas available. Either start an XR session or ensure an app canvas is in the DOM.');
2696
+ }
2697
+ // Create a temporary canvas for scaling
2698
+ const tempCanvas = document.createElement('canvas');
2699
+ const ctx = tempCanvas.getContext('2d');
2700
+ if (!ctx) {
2701
+ throw new Error('Failed to create canvas context');
2702
+ }
2703
+ // Calculate scaled dimensions
2704
+ const aspectRatio = canvas.height / canvas.width;
2705
+ const targetWidth = Math.min(canvas.width, maxWidth);
2706
+ const targetHeight = Math.round(targetWidth * aspectRatio);
2707
+ tempCanvas.width = targetWidth;
2708
+ tempCanvas.height = targetHeight;
2709
+ // Draw scaled image
2710
+ ctx.drawImage(canvas, 0, 0, targetWidth, targetHeight);
2711
+ // Convert to base64
2712
+ const mimeType = `image/${format}`;
2713
+ const dataUrl = tempCanvas.toDataURL(mimeType, quality);
2714
+ const imageData = dataUrl.split(',')[1]; // Remove data URL prefix
2715
+ return {
2716
+ imageData,
2717
+ width: targetWidth,
2718
+ height: targetHeight,
2719
+ format,
2720
+ timestamp: Date.now(),
2721
+ };
2722
+ }
2723
+ // =============================================================================
2724
+ // Duration Action Handling
2725
+ // =============================================================================
2726
+ applyDurationLerpState(action, t) {
2727
+ const { startState, targetState, params } = action;
2728
+ const deviceId = params.device;
2729
+ let newPosition;
2730
+ let newOrientation;
2731
+ if (startState.position && targetState.position) {
2732
+ newPosition = lerpVec3(startState.position, targetState.position, t);
2733
+ }
2734
+ if (startState.orientation && targetState.orientation) {
2735
+ newOrientation = slerpQuat(startState.orientation, targetState.orientation, t);
2736
+ }
2737
+ this.setDeviceTransform(deviceId, newPosition, newOrientation);
2738
+ }
2739
+ applyDurationFinalState(action) {
2740
+ const { targetState, params } = action;
2741
+ const deviceId = params.device;
2742
+ this.setDeviceTransform(deviceId, targetState.position, targetState.orientation);
2743
+ }
2744
+ getDurationResult(action) {
2745
+ const { params, elapsedMs } = action;
2746
+ const deviceId = params.device;
2747
+ const transform = this.getDeviceTransform(deviceId);
2748
+ return {
2749
+ device: deviceId,
2750
+ position: transform.position,
2751
+ orientation: transform.orientation,
2752
+ actualDuration: elapsedMs / 1000,
2753
+ };
2754
+ }
2755
+ /**
2756
+ * Activate capture mode for programmatic control.
2757
+ * Called when active methods are executed.
2758
+ */
2759
+ activateCaptureMode() {
2760
+ if (!this._isCaptured) {
2761
+ this._isCaptured = true;
2762
+ this.cancelReleaseTimer();
2763
+ this.device.controlMode = 'programmatic';
2764
+ }
2765
+ // Reset the release timer
2766
+ this.startReleaseTimer();
2767
+ }
2768
+ /**
2769
+ * Dispatch a method call.
2770
+ *
2771
+ * Immediate methods (queries, session management) execute synchronously.
2772
+ * State-modifying methods require an active session and are queued for frame-synchronized execution.
2773
+ *
2774
+ * @param method - The method name (e.g., 'get_transform', 'animate_to')
2775
+ * @param params - The method parameters
2776
+ * @returns Promise that resolves with the method result
2777
+ */
2778
+ async dispatch(method, params = {}) {
2779
+ var _a;
2780
+ // Immediate methods execute synchronously without queue
2781
+ if (RemoteControlInterface.IMMEDIATE_METHODS.has(method)) {
2782
+ // Active immediate methods trigger capture mode
2783
+ if (RemoteControlInterface.ACTIVE_IMMEDIATE_METHODS.has(method)) {
2784
+ this.activateCaptureMode();
2785
+ }
2786
+ return this.executeImmediateMethod(method, params);
2787
+ }
2788
+ // Methods that modify state require an active session
2789
+ if (RemoteControlInterface.SESSION_REQUIRED_METHODS.has(method)) {
2790
+ if (!this.device.activeSession) {
2791
+ throw new Error(`Cannot execute '${method}': No active XR session. ` +
2792
+ `Use 'get_session_status' to check session state, and 'accept_session' to start a session.`);
2793
+ }
2794
+ }
2795
+ // Handle animate_to specially - it's a duration action
2796
+ if (method === 'animate_to') {
2797
+ const animateParams = params;
2798
+ const currentTransform = this.getDeviceTransform(animateParams.device);
2799
+ const durationMs = ((_a = animateParams.duration) !== null && _a !== void 0 ? _a : 0.5) * 1000;
2800
+ const targetOrientation = animateParams.orientation
2801
+ ? normalizeOrientation(animateParams.orientation)
2802
+ : undefined;
2803
+ // Transform target position from XR-origin-relative to GlobalSpace
2804
+ const targetPosition = animateParams.position
2805
+ ? this.transformXROriginToGlobal(animateParams.position)
2806
+ : undefined;
2807
+ return this.enqueueDuration(method, params, durationMs, {
2808
+ position: animateParams.position
2809
+ ? currentTransform.position
2810
+ : undefined,
2811
+ orientation: targetOrientation
2812
+ ? currentTransform.orientation
2813
+ : undefined,
2814
+ }, {
2815
+ position: targetPosition,
2816
+ orientation: targetOrientation,
2817
+ });
2818
+ }
2819
+ // Handle select specially - it's a discrete action that enqueues multiple sub-actions
2820
+ if (method === 'select') {
2821
+ const selectParams = params;
2822
+ return this.executeSelectSequence(selectParams);
2823
+ }
2824
+ // All other methods are discrete actions that go through the queue
2825
+ return this.enqueueDiscrete(method, params);
2826
+ }
2827
+ /**
2828
+ * Execute an immediate method synchronously (not queued).
2829
+ * Used for queries and session management that must work outside XR frames.
2830
+ */
2831
+ executeImmediateMethod(method, params) {
2832
+ switch (method) {
2833
+ case 'get_session_status':
2834
+ return this.executeGetSessionStatus();
2835
+ case 'accept_session':
2836
+ return this.executeAcceptSession();
2837
+ case 'end_session':
2838
+ return this.executeEndSession();
2839
+ case 'get_transform':
2840
+ return this.executeGetTransform(params);
2841
+ case 'get_select_value':
2842
+ return this.executeGetSelectValue(params);
2843
+ case 'get_gamepad_state':
2844
+ return this.executeGetGamepadState(params);
2845
+ case 'get_device_state':
2846
+ return this.executeGetDeviceState();
2847
+ case 'capture_canvas':
2848
+ return this.executeCaptureCanvas(params);
2849
+ default:
2850
+ throw new Error(`Unknown immediate method: ${method}`);
2851
+ }
2852
+ }
2853
+ /**
2854
+ * Execute select action - this directly enqueues the three sub-actions without awaiting
2855
+ * The caller's promise resolves when all sub-actions complete
2856
+ */
2857
+ executeSelectSequence(params) {
2858
+ const { device: deviceId, duration = 0.15 } = params;
2859
+ return new Promise((resolve, reject) => {
2860
+ // Track completion of all three actions
2861
+ let actionsCompleted = 0;
2862
+ const totalActions = 3;
2863
+ const checkComplete = () => {
2864
+ actionsCompleted++;
2865
+ if (actionsCompleted === totalActions) {
2866
+ resolve({
2867
+ device: deviceId,
2868
+ duration,
2869
+ });
2870
+ }
2871
+ };
2872
+ // Enqueue: set value to 1
2873
+ const action1 = {
2874
+ type: 'discrete',
2875
+ id: this.generateActionId(),
2876
+ method: '_select_press',
2877
+ params: { device: deviceId },
2878
+ resolve: checkComplete,
2879
+ reject,
2880
+ };
2881
+ // Enqueue: wait for duration
2882
+ const action2 = {
2883
+ type: 'duration',
2884
+ id: this.generateActionId(),
2885
+ method: '_select_wait',
2886
+ params: { device: deviceId },
2887
+ durationMs: duration * 1000,
2888
+ elapsedMs: 0,
2889
+ startState: {},
2890
+ targetState: {},
2891
+ resolve: checkComplete,
2892
+ reject,
2893
+ };
2894
+ // Enqueue: set value to 0
2895
+ const action3 = {
2896
+ type: 'discrete',
2897
+ id: this.generateActionId(),
2898
+ method: '_select_release',
2899
+ params: { device: deviceId },
2900
+ resolve: checkComplete,
2901
+ reject,
2902
+ };
2903
+ this.commandQueue.push(action1, action2, action3);
2904
+ });
2905
+ }
2906
+ /**
2907
+ * Accept an offered XR session (async wrapper for proper session activation)
2908
+ */
2909
+ async acceptSession() {
2910
+ if (!this.device.sessionOffered) {
2911
+ throw new Error('No session has been offered');
2912
+ }
2913
+ this.device.grantOfferedSession();
2914
+ // Wait for session to become active
2915
+ await waitForCondition(() => !!this.device.activeSession, 5000);
2916
+ // Just return success - caller can use get_session_status for details
2917
+ return { success: true };
2918
+ }
2919
+ /**
2920
+ * Force release capture mode (for testing/cleanup)
2921
+ */
2922
+ forceRelease() {
2923
+ this.cancelReleaseTimer();
2924
+ this._isCaptured = false;
2925
+ this.device.controlMode = 'manual';
2926
+ // Clear pending actions
2927
+ for (const action of this.commandQueue) {
2928
+ action.reject(new Error('Capture released'));
2929
+ }
2930
+ this.commandQueue = [];
2931
+ // Reset any stuck select/trigger values
2932
+ for (const hand of ['left', 'right']) {
2933
+ const controller = this.device.controllers[hand];
2934
+ if (controller) {
2935
+ controller.updateButtonValue('trigger', 0);
2936
+ controller.updateButtonValue('squeeze', 0);
2937
+ }
2938
+ }
2939
+ }
2940
+ }
2941
+ // =============================================================================
2942
+ // Public API - Dispatch
2943
+ // =============================================================================
2944
+ /**
2945
+ * Set of methods that execute immediately (synchronously) without going through the queue.
2946
+ * These are queries and session management commands that need to work outside of XR frames.
2947
+ */
2948
+ RemoteControlInterface.IMMEDIATE_METHODS = new Set([
2949
+ // Session management - must work before/after XR session
2950
+ 'get_session_status',
2951
+ 'accept_session',
2952
+ 'end_session',
2953
+ // Pure queries - just read current state
2954
+ 'get_transform',
2955
+ 'get_select_value',
2956
+ 'get_gamepad_state',
2957
+ 'get_device_state',
2958
+ // Canvas capture - reads current canvas state
2959
+ 'capture_canvas',
2960
+ ]);
2961
+ /**
2962
+ * Set of immediate methods that are "active" - they modify state and should trigger capture mode.
2963
+ * Passive methods (queries) should NOT trigger capture mode.
2964
+ */
2965
+ RemoteControlInterface.ACTIVE_IMMEDIATE_METHODS = new Set([
2966
+ 'accept_session',
2967
+ 'end_session',
2968
+ ]);
2969
+ /**
2970
+ * Set of methods that require an active XR session.
2971
+ * These are state-modifying methods that are processed during frame updates.
2972
+ */
2973
+ RemoteControlInterface.SESSION_REQUIRED_METHODS = new Set([
2974
+ 'set_transform',
2975
+ 'look_at',
2976
+ 'animate_to',
2977
+ 'set_input_mode',
2978
+ 'set_connected',
2979
+ 'set_select_value',
2980
+ 'select',
2981
+ 'set_gamepad_state',
2982
+ 'set_device_state',
2983
+ ]);
2984
+
1535
2985
  /**
1536
2986
  * Copyright (c) Meta Platforms, Inc. and affiliates.
1537
2987
  *
@@ -1878,6 +3328,31 @@ class XRController extends XRTrackedInput {
1878
3328
  console.warn(`Current controller does not have button ${id}.`);
1879
3329
  }
1880
3330
  }
3331
+ /**
3332
+ * Set button value immediately (bypasses pending mechanism).
3333
+ * Use this for programmatic control where value should be readable immediately.
3334
+ */
3335
+ setButtonValueImmediate(id, value) {
3336
+ if (value > 1 || value < 0) {
3337
+ console.warn(`Out-of-range value ${value} provided for button ${id}.`);
3338
+ return;
3339
+ }
3340
+ const gamepadButton = this[P_TRACKED_INPUT].inputSource.gamepad[P_GAMEPAD].buttonsMap[id];
3341
+ if (gamepadButton) {
3342
+ if (gamepadButton[P_GAMEPAD].type === 'binary' &&
3343
+ value != 1 &&
3344
+ value != 0) {
3345
+ console.warn(`Non-binary value ${value} provided for binary button ${id}.`);
3346
+ return;
3347
+ }
3348
+ // Set both value and pendingValue for immediate effect
3349
+ gamepadButton[P_GAMEPAD].value = value;
3350
+ gamepadButton[P_GAMEPAD].pendingValue = value;
3351
+ }
3352
+ else {
3353
+ console.warn(`Current controller does not have button ${id}.`);
3354
+ }
3355
+ }
1881
3356
  updateButtonTouch(id, touched) {
1882
3357
  const gamepadButton = this[P_TRACKED_INPUT].inputSource.gamepad[P_GAMEPAD].buttonsMap[id];
1883
3358
  if (gamepadButton) {
@@ -1919,6 +3394,37 @@ class XRController extends XRTrackedInput {
1919
3394
  console.warn(`Current controller does not have ${id} axes.`);
1920
3395
  }
1921
3396
  }
3397
+ /**
3398
+ * Get the current value of a button by id
3399
+ */
3400
+ getButtonValue(id) {
3401
+ var _a;
3402
+ const gamepadButton = this[P_TRACKED_INPUT].inputSource.gamepad[P_GAMEPAD].buttonsMap[id];
3403
+ if (gamepadButton) {
3404
+ return (_a = gamepadButton[P_GAMEPAD].pendingValue) !== null && _a !== void 0 ? _a : gamepadButton.value;
3405
+ }
3406
+ return 0;
3407
+ }
3408
+ /**
3409
+ * Get the touched state of a button by id
3410
+ */
3411
+ getButtonTouched(id) {
3412
+ const gamepadButton = this[P_TRACKED_INPUT].inputSource.gamepad[P_GAMEPAD].buttonsMap[id];
3413
+ if (gamepadButton) {
3414
+ return gamepadButton.touched;
3415
+ }
3416
+ return false;
3417
+ }
3418
+ /**
3419
+ * Get the current axes values for a given id (e.g., 'thumbstick')
3420
+ */
3421
+ getAxes(id = 'thumbstick') {
3422
+ const axesById = this[P_TRACKED_INPUT].inputSource.gamepad[P_GAMEPAD].axesMap[id];
3423
+ if (axesById) {
3424
+ return { x: axesById.x, y: axesById.y };
3425
+ }
3426
+ return { x: 0, y: 0 };
3427
+ }
1922
3428
  }
1923
3429
 
1924
3430
  /**
@@ -4175,9 +5681,9 @@ const interpolateMatrix = (out, fromMatrix, toMatrix, alpha) => {
4175
5681
  getTranslation(toPosition, toMatrix);
4176
5682
  getRotation(toQuaternion, toMatrix);
4177
5683
  getScaling(toScale, toMatrix);
4178
- lerp(interpolatedPosition, fromPosition, toPosition, alpha);
5684
+ lerp$1(interpolatedPosition, fromPosition, toPosition, alpha);
4179
5685
  slerp(interpolatedQuaternion, fromQuaternion, toQuaternion, alpha);
4180
- lerp(interpolatedScale, fromScale, toScale, alpha);
5686
+ lerp$1(interpolatedScale, fromScale, toScale, alpha);
4181
5687
  fromRotationTranslationScale(out, interpolatedQuaternion, interpolatedPosition, interpolatedScale);
4182
5688
  return out;
4183
5689
  };
@@ -4502,7 +6008,7 @@ class ActionPlayer {
4502
6008
  const f1q = fromValues(lastTransform[3], lastTransform[4], lastTransform[5], lastTransform[6]);
4503
6009
  const f2p = fromValues$2(nextTransform[0], nextTransform[1], nextTransform[2]);
4504
6010
  const f2q = fromValues(nextTransform[3], nextTransform[4], nextTransform[5], nextTransform[6]);
4505
- lerp(this[P_ACTION_PLAYER].vec3, f1p, f2p, alpha);
6011
+ lerp$1(this[P_ACTION_PLAYER].vec3, f1p, f2p, alpha);
4506
6012
  slerp(this[P_ACTION_PLAYER].quat, f1q, f2q, alpha);
4507
6013
  fromRotationTranslation(space[P_SPACE].offsetMatrix, this[P_ACTION_PLAYER].quat, this[P_ACTION_PLAYER].vec3);
4508
6014
  }
@@ -4527,7 +6033,7 @@ class ActionPlayer {
4527
6033
  }
4528
6034
  }
4529
6035
 
4530
- const VERSION = "2.1.1";
6036
+ const VERSION = "2.2.0";
4531
6037
 
4532
6038
  /**
4533
6039
  * Copyright (c) Meta Platforms, Inc. and affiliates.
@@ -7834,6 +9340,16 @@ class XRDevice {
7834
9340
  },
7835
9341
  onFrameStart: (frame) => {
7836
9342
  var _a;
9343
+ // Calculate delta time for remote control
9344
+ const now = performance.now();
9345
+ const deltaTimeMs = this[P_DEVICE].lastFrameTime > 0
9346
+ ? now - this[P_DEVICE].lastFrameTime
9347
+ : 16.67; // Default to ~60fps
9348
+ this[P_DEVICE].lastFrameTime = now;
9349
+ // Update remote control interface
9350
+ if (this[P_DEVICE].remote) {
9351
+ this[P_DEVICE].remote.update(deltaTimeMs);
9352
+ }
7837
9353
  if ((_a = this[P_DEVICE].actionPlayer) === null || _a === void 0 ? void 0 : _a.playing) {
7838
9354
  this[P_DEVICE].actionPlayer.playFrame();
7839
9355
  }
@@ -7867,7 +9383,17 @@ class XRDevice {
7867
9383
  }
7868
9384
  this[P_DEVICE].updateViews();
7869
9385
  },
9386
+ // control mode for programmatic access
9387
+ controlMode: 'manual',
9388
+ controlModeListeners: new Set(),
9389
+ stateChangeListeners: new Set(),
9390
+ // remote control interface - initialized after this object
9391
+ remote: null,
9392
+ // frame timing for remote update
9393
+ lastFrameTime: 0,
7870
9394
  };
9395
+ // Initialize remote control interface
9396
+ this[P_DEVICE].remote = new RemoteControlInterface(this);
7871
9397
  this[P_DEVICE].updateViews();
7872
9398
  }
7873
9399
  installRuntime(options) {
@@ -8030,6 +9556,14 @@ class XRDevice {
8030
9556
  }
8031
9557
  return;
8032
9558
  }
9559
+ /**
9560
+ * Get the app canvas when an XR session is active.
9561
+ * Returns undefined if no session is active or no canvas is available.
9562
+ */
9563
+ get appCanvas() {
9564
+ var _a;
9565
+ return (_a = this[P_DEVICE].canvasData) === null || _a === void 0 ? void 0 : _a.canvas;
9566
+ }
8033
9567
  get activeSession() {
8034
9568
  var _a;
8035
9569
  return (_a = this[P_DEVICE].xrSystem) === null || _a === void 0 ? void 0 : _a[P_SYSTEM].activeSession;
@@ -8095,6 +9629,65 @@ class XRDevice {
8095
9629
  get sem() {
8096
9630
  return this[P_DEVICE].sem;
8097
9631
  }
9632
+ get remote() {
9633
+ return this[P_DEVICE].remote;
9634
+ }
9635
+ // =============================================================================
9636
+ // Control Mode API
9637
+ // =============================================================================
9638
+ /**
9639
+ * Get the current control mode
9640
+ * - 'manual': User controls device via DevUI (default)
9641
+ * - 'programmatic': External API controls device
9642
+ */
9643
+ get controlMode() {
9644
+ return this[P_DEVICE].controlMode;
9645
+ }
9646
+ /**
9647
+ * Set the control mode
9648
+ * Notifies all registered listeners of the change
9649
+ */
9650
+ set controlMode(mode) {
9651
+ if (mode !== 'manual' && mode !== 'programmatic') {
9652
+ console.warn('control mode can only be "manual" or "programmatic"');
9653
+ return;
9654
+ }
9655
+ const prevMode = this[P_DEVICE].controlMode;
9656
+ if (prevMode !== mode) {
9657
+ this[P_DEVICE].controlMode = mode;
9658
+ this[P_DEVICE].controlModeListeners.forEach((listener) => listener(mode));
9659
+ }
9660
+ }
9661
+ /**
9662
+ * Register a listener to be notified when control mode changes
9663
+ * @param listener - Callback function that receives the new mode
9664
+ * @returns Unsubscribe function to remove the listener
9665
+ */
9666
+ onControlModeChange(listener) {
9667
+ this[P_DEVICE].controlModeListeners.add(listener);
9668
+ return () => {
9669
+ this[P_DEVICE].controlModeListeners.delete(listener);
9670
+ };
9671
+ }
9672
+ /**
9673
+ * Register a listener to be notified when device state changes
9674
+ * Called after programmatic state modifications
9675
+ * @param listener - Callback function
9676
+ * @returns Unsubscribe function to remove the listener
9677
+ */
9678
+ onStateChange(listener) {
9679
+ this[P_DEVICE].stateChangeListeners.add(listener);
9680
+ return () => {
9681
+ this[P_DEVICE].stateChangeListeners.delete(listener);
9682
+ };
9683
+ }
9684
+ /**
9685
+ * Notify all state change listeners that device state has been modified
9686
+ * Should be called after programmatic state modifications
9687
+ */
9688
+ notifyStateChange() {
9689
+ this[P_DEVICE].stateChangeListeners.forEach((listener) => listener());
9690
+ }
8098
9691
  }
8099
9692
 
8100
9693
  /**
@@ -8528,4 +10121,4 @@ class ActionRecorder {
8528
10121
  }
8529
10122
  }
8530
10123
 
8531
- export { ActionRecorder, NativeMesh, NativePlane, P_ACTION_PLAYER, P_ACTION_RECORDER, P_ANCHOR, P_CONTROLLER, P_DEVICE, P_FRAME, P_GAMEPAD, P_HAND_INPUT, P_HIT_TEST, P_INPUT_SOURCE, P_JOINT_POSE, P_JOINT_SPACE, P_MESH, P_PLANE, P_POSE, P_RAY, P_REF_SPACE, P_RENDER_STATE, P_RIGID_TRANSFORM, P_SESSION, P_SPACE, P_SYSTEM, P_TRACKED_INPUT, P_VIEW, P_VIEWER_POSE, P_VIEWPORT, P_WEBGL_LAYER, XRAnchor, XRAnchorSet, XRDevice, XRFrame, XRHand, XRInputSource, XRInputSourceArray, XRInputSourceEvent, XRInputSourcesChangeEvent, XRJointPose, XRJointSpace, XRLayer, XRMesh, XRMeshSet, XRPlane, XRPlaneSet, XRPose, XRRay, XRReferenceSpace, XRReferenceSpaceEvent, XRRenderState, XRRigidTransform, XRSemanticLabels, XRSession, XRSessionEvent, XRSpace, XRSystem, XRView, XRViewerPose, XRViewport, XRWebGLLayer, metaQuest2, metaQuest3, metaQuestPro, oculusQuest1 };
10124
+ export { ActionRecorder, NativeMesh, NativePlane, P_ACTION_PLAYER, P_ACTION_RECORDER, P_ANCHOR, P_CONTROLLER, P_DEVICE, P_FRAME, P_GAMEPAD, P_HAND_INPUT, P_HIT_TEST, P_INPUT_SOURCE, P_JOINT_POSE, P_JOINT_SPACE, P_MESH, P_PLANE, P_POSE, P_RAY, P_REF_SPACE, P_RENDER_STATE, P_RIGID_TRANSFORM, P_SESSION, P_SPACE, P_SYSTEM, P_TRACKED_INPUT, P_VIEW, P_VIEWER_POSE, P_VIEWPORT, P_WEBGL_LAYER, RemoteControlInterface, XRAnchor, XRAnchorSet, XRDevice, XRFrame, XRHand, XRInputSource, XRInputSourceArray, XRInputSourceEvent, XRInputSourcesChangeEvent, XRJointPose, XRJointSpace, XRLayer, XRMesh, XRMeshSet, XRPlane, XRPlaneSet, XRPose, XRRay, XRReferenceSpace, XRReferenceSpaceEvent, XRRenderState, XRRigidTransform, XRSemanticLabels, XRSession, XRSessionEvent, XRSpace, XRSystem, XRView, XRViewerPose, XRViewport, XRWebGLLayer, directionTo, eulerToQuat, lookRotation, metaQuest2, metaQuest3, metaQuestPro, oculusQuest1, quatToEuler, quatToObj, vec3ToObj, waitForCondition };