@margoengine/xr 0.0.0-stage → 0.1.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 (52) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +592 -3
  4. package/dist/ar-extra.d.ts +167 -0
  5. package/dist/ar-extra.js +247 -0
  6. package/dist/ar.d.ts +177 -0
  7. package/dist/ar.js +195 -0
  8. package/dist/body.d.ts +58 -0
  9. package/dist/body.js +134 -0
  10. package/dist/controller.d.ts +32 -0
  11. package/dist/device-check.d.ts +39 -0
  12. package/dist/device-check.js +155 -0
  13. package/dist/errors-XvcwUnU4.js +7 -0
  14. package/dist/eye-target.d.ts +25 -0
  15. package/dist/eyes.d.ts +24 -0
  16. package/dist/gizmo.d.ts +165 -0
  17. package/dist/gizmo.js +198 -0
  18. package/dist/hands.d.ts +48 -0
  19. package/dist/hands.js +198 -0
  20. package/dist/hit-test.d.ts +69 -0
  21. package/dist/index.d.ts +148 -0
  22. package/dist/index.js +957 -0
  23. package/dist/interaction.d.ts +136 -0
  24. package/dist/interaction.js +205 -0
  25. package/dist/launch.d.ts +65 -0
  26. package/dist/launch.js +54 -0
  27. package/dist/layers-BTUTAawG.js +391 -0
  28. package/dist/layers.d.ts +247 -0
  29. package/dist/layers.js +1 -0
  30. package/dist/locomotion.d.ts +63 -0
  31. package/dist/locomotion.js +184 -0
  32. package/dist/models.d.ts +136 -0
  33. package/dist/models.js +335 -0
  34. package/dist/near.d.ts +465 -0
  35. package/dist/near.js +643 -0
  36. package/dist/occlusion.d.ts +49 -0
  37. package/dist/occlusion.js +218 -0
  38. package/dist/performance.d.ts +67 -0
  39. package/dist/performance.js +78 -0
  40. package/dist/pointer.d.ts +93 -0
  41. package/dist/pointer.js +205 -0
  42. package/dist/reflection.d.ts +70 -0
  43. package/dist/reflection.js +147 -0
  44. package/dist/renderer.d.ts +21 -0
  45. package/dist/scene-owner-BRObO-WJ.js +15 -0
  46. package/dist/scene-owner.d.ts +3 -0
  47. package/dist/scene-scope-DufD_3B6.js +42 -0
  48. package/dist/session.d.ts +60 -0
  49. package/dist/session.js +68 -0
  50. package/dist/shared/xr-run.d.ts +64 -0
  51. package/dist/types.d.ts +221 -0
  52. package/package.json +153 -6
package/dist/ar.js ADDED
@@ -0,0 +1,195 @@
1
+ import { n as e } from "./errors-XvcwUnU4.js";
2
+ import { Geometry as t } from "@margoengine/core";
3
+ import { SH3 as n } from "@margoengine/math/sh";
4
+ //#region src/ar.ts
5
+ function r(e) {
6
+ let t = e.length / 2;
7
+ if (!Number.isInteger(t) || t < 3) throw RangeError("triangulate needs 3 or more x, z points; pass a plane outline");
8
+ for (let t = 0; t < e.length; t++) if (!Number.isFinite(e[t])) throw RangeError("triangulate needs finite points; pass a plane outline");
9
+ let n = (t) => e[t * 2], r = (t) => e[t * 2 + 1], i = 0;
10
+ for (let e = 0, a = t - 1; e < t; a = e++) i += n(a) * r(e) - n(e) * r(a);
11
+ let a = i >= 0 ? 1 : -1, o = (e, t, i) => ((n(t) - n(e)) * (r(i) - r(e)) - (r(t) - r(e)) * (n(i) - n(e))) * a, s = Array.from({ length: t }, (e, t) => t), c = [], l = 0;
12
+ for (; s.length > 3 && l++ < t * t;) {
13
+ let e = !1;
14
+ for (let t = 0; t < s.length; t++) {
15
+ let n = s[(t + s.length - 1) % s.length], r = s[t], i = s[(t + 1) % s.length];
16
+ if (o(n, r, i) <= 0) continue;
17
+ let a = !1;
18
+ for (let e of s) if (e !== n && e !== r && e !== i && o(n, r, e) >= 0 && o(r, i, e) >= 0 && o(i, n, e) >= 0) {
19
+ a = !0;
20
+ break;
21
+ }
22
+ if (!a) {
23
+ c.push(n, r, i), s.splice(t, 1), e = !0;
24
+ break;
25
+ }
26
+ }
27
+ e || s.splice(1, 1);
28
+ }
29
+ if (s.length === 3 && o(s[0], s[1], s[2]) > 0 && c.push(s[0], s[1], s[2]), a > 0) for (let e = 0; e < c.length; e += 3) [c[e + 1], c[e + 2]] = [c[e + 2], c[e + 1]];
30
+ return Uint32Array.from(c);
31
+ }
32
+ function i(e) {
33
+ let n = e.length / 2, i = r(e), a = new Float32Array(n * 3), o = new Float32Array(n * 3);
34
+ for (let t = 0; t < n; t++) a[t * 3] = e[t * 2], a[t * 3 + 2] = e[t * 2 + 1], o[t * 3 + 1] = 1;
35
+ return new t(a, o, i);
36
+ }
37
+ var a = (e, t) => !e?.enabledFeatures || e.enabledFeatures.includes(t), o = class t {
38
+ constructor(e, t) {
39
+ this.host = e, this.options = t, this.planes = /* @__PURE__ */ new Map(), this.changed = /* @__PURE__ */ new Map(), this.meshes = /* @__PURE__ */ new Map(), this.unsubscribe = e.onFrame((e) => this.update(e.frame));
40
+ }
41
+ static create(n, r = {}) {
42
+ if (!n?.session) throw e("state", "ARPlanes needs an active XR session; await xr.requestSession first");
43
+ if (!a(n.session, "plane-detection")) throw e("unsupported", "The XR session has no 'plane-detection' feature; ask for it when starting the session");
44
+ return new t(n, r);
45
+ }
46
+ update(e) {
47
+ let t = this.host.referenceSpace, n = e.detectedPlanes;
48
+ if (t && n) {
49
+ for (let [e, t] of this.planes) n.has(e) || (this.planes.delete(e), this.changed.delete(e), this.meshes.get(e)?.dispose(), this.meshes.delete(e), this.options.onRemove?.(t));
50
+ for (let r of n) {
51
+ let n = e.getPose(r.planeSpace, t), i = this.planes.get(r), a = !i, o = !a && r.lastChangedTime > (this.changed.get(r) ?? -Infinity);
52
+ if (a || o) {
53
+ let e = new Float32Array(r.polygon.length * 2);
54
+ r.polygon.forEach((t, n) => {
55
+ e[n * 2] = t.x, e[n * 2 + 1] = t.z;
56
+ }), i = {
57
+ plane: r,
58
+ matrix: i?.matrix ?? /* @__PURE__ */ new Float32Array(16),
59
+ polygon: e,
60
+ orientation: r.orientation ?? null,
61
+ label: r.semanticLabel ?? "",
62
+ tracked: !1
63
+ }, this.planes.set(r, i), this.changed.set(r, r.lastChangedTime);
64
+ }
65
+ i = i, i.tracked = !!n, n && i.matrix.set(n.transform.matrix), a ? this.options.onAdd?.(i) : o && this.options.onChange?.(i), this.options.show && this.draw(i, n, a || o);
66
+ }
67
+ }
68
+ }
69
+ draw(e, t, n) {
70
+ let { engine: r, material: a } = this.options.show, o = this.meshes.get(e.plane);
71
+ if (o || this.meshes.set(e.plane, o = r.createMesh().setMaterial(a)), n && e.polygon.length >= 6 && o.setGeometry(i(e.polygon)), o.visible = !!t, t) {
72
+ let { position: e, orientation: n } = t.transform;
73
+ o.setPosition([
74
+ e.x,
75
+ e.y,
76
+ e.z
77
+ ]).setQuaternion([
78
+ n.x,
79
+ n.y,
80
+ n.z,
81
+ n.w
82
+ ]);
83
+ }
84
+ }
85
+ dispose() {
86
+ this.unsubscribe();
87
+ for (let e of this.meshes.values()) e.dispose();
88
+ this.meshes.clear(), this.planes.clear();
89
+ }
90
+ [Symbol.dispose]() {
91
+ this.dispose();
92
+ }
93
+ }, s = {
94
+ usagePreference: ["cpu-optimized"],
95
+ dataFormatPreference: [
96
+ "float32",
97
+ "luminance-alpha",
98
+ "unsigned-short"
99
+ ]
100
+ }, c = class t {
101
+ constructor(e) {
102
+ this.host = e;
103
+ }
104
+ static create(n) {
105
+ let r = n?.session;
106
+ if (!r) throw e("state", "ARDepth needs an active XR session; await xr.requestSession first");
107
+ if (!a(r, "depth-sensing")) throw e("unsupported", "The XR session has no 'depth-sensing' feature; ask for it with init: {depthSensing}");
108
+ let i;
109
+ try {
110
+ i = r.depthUsage;
111
+ } catch (t) {
112
+ throw Object.assign(e("unsupported", "The XR session has no depth sensing; start it with init: {depthSensing: DEPTH_SENSING}"), { cause: t });
113
+ }
114
+ if (i !== void 0 && i !== "cpu-optimized") throw e("unsupported", "ARDepth reads CPU depth; start the session with usagePreference ['cpu-optimized']");
115
+ return new t(n);
116
+ }
117
+ information(e, t) {
118
+ let n = e.getDepthInformation;
119
+ return n ? n.call(e, t) ?? null : null;
120
+ }
121
+ depthAt(e, t, n, r) {
122
+ if (!(n >= 0 && n <= 1 && r >= 0 && r <= 1)) throw RangeError("ARDepth points run from 0 to 1 from the top left of the view; pass normalized coordinates");
123
+ return this.information(e, t)?.getDepthInMeters(n, r) ?? null;
124
+ }
125
+ pointAt(e, t, n, r) {
126
+ let i = this.information(e, t);
127
+ if (!i) return null;
128
+ let a = i.getDepthInMeters(n, r);
129
+ if (!(a > 0)) return null;
130
+ let o = i.projectionMatrix ?? t.projectionMatrix, s = (i.transform ?? t.transform).matrix, c = 2 * n - 1, l = 1 - 2 * r, u = (c + o[8]) / o[0], d = (l + o[9]) / o[5], f = u * a, p = d * a, m = -a;
131
+ return [
132
+ s[0] * f + s[4] * p + s[8] * m + s[12],
133
+ s[1] * f + s[5] * p + s[9] * m + s[13],
134
+ s[2] * f + s[6] * p + s[10] * m + s[14]
135
+ ];
136
+ }
137
+ }, l = .28209479177387814, u = class t {
138
+ constructor(e, t, r) {
139
+ this.host = e, this.probe = t, this.lighting = r, this.estimate = null, this.sh = new n(), this.turn = {
140
+ x: 0,
141
+ y: 0,
142
+ z: 0,
143
+ w: 1
144
+ }, this.value = {
145
+ sh: /* @__PURE__ */ new Float32Array(27),
146
+ direction: [
147
+ 0,
148
+ 1,
149
+ 0
150
+ ],
151
+ intensity: [
152
+ 0,
153
+ 0,
154
+ 0
155
+ ]
156
+ }, this.unsubscribe = e.onFrame((e) => this.update(e.frame));
157
+ }
158
+ static create(e, { lighting: n } = {}) {
159
+ return t.withReflection(e, { lighting: n });
160
+ }
161
+ static async withReflection(n, { lighting: r, reflectionFormat: i } = {}) {
162
+ let o = n?.session;
163
+ if (!o) throw e("state", "ARLight needs an active XR session; await xr.requestSession first");
164
+ if (!a(o, "light-estimation") || !o.requestLightProbe) throw e("unsupported", "The XR session has no 'light-estimation' feature; ask for it when starting the session");
165
+ return new t(n, await o.requestLightProbe(i ? { reflectionFormat: i } : void 0), r);
166
+ }
167
+ update(e) {
168
+ let t = e.getLightEstimate?.call(e, this.probe), n = this.host.referenceSpace;
169
+ if (!t || !n) {
170
+ this.estimate = null;
171
+ return;
172
+ }
173
+ let r = this.value, i = t.primaryLightDirection, a = e.getPose(this.probe.probeSpace, n), o = a?.transform.matrix;
174
+ if (this.sh.fromArray(t.sphericalHarmonicsCoefficients), a) {
175
+ let e = a.transform.orientation;
176
+ this.turn.x = e.x, this.turn.y = e.y, this.turn.z = e.z, this.turn.w = e.w, this.sh.rotate(this.turn);
177
+ }
178
+ this.sh.toArray(r.sh), r.direction[0] = o ? o[0] * i.x + o[4] * i.y + o[8] * i.z : i.x, r.direction[1] = o ? o[1] * i.x + o[5] * i.y + o[9] * i.z : i.y, r.direction[2] = o ? o[2] * i.x + o[6] * i.y + o[10] * i.z : i.z;
179
+ let s = t.primaryLightIntensity;
180
+ r.intensity[0] = s.x, r.intensity[1] = s.y, r.intensity[2] = s.z, this.estimate = r;
181
+ let c = this.lighting;
182
+ if (!c) return;
183
+ let u = Math.max(s.x, s.y, s.z);
184
+ c.direction[0] = r.direction[0], c.direction[1] = r.direction[1], c.direction[2] = r.direction[2], c.direction[3] = u, u > 0 && (c.radiance[0] = s.x / u, c.radiance[1] = s.y / u, c.radiance[2] = s.z / u), c.radiance[3] = 1;
185
+ for (let e = 0; e < 3; e++) c.ambient[e] = Math.max(0, r.sh[e] * l);
186
+ }
187
+ dispose() {
188
+ this.unsubscribe();
189
+ }
190
+ [Symbol.dispose]() {
191
+ this.dispose();
192
+ }
193
+ };
194
+ //#endregion
195
+ export { c as ARDepth, u as ARLight, o as ARPlanes, s as DEPTH_SENSING, i as planeGeometry, r as triangulate };
package/dist/body.d.ts ADDED
@@ -0,0 +1,58 @@
1
+ import type { XRNativeFrame, XRNativeSession, XRSpace } from './types.js';
2
+ /** The session feature descriptor that asks the browser for body tracking. */
3
+ export declare const BODY_TRACKING_FEATURE = "body-tracking";
4
+ /** The 83 XRBodyJoint names, in the spec's order. */
5
+ export declare const BODY_JOINT_NAMES: readonly string[];
6
+ /** XRBodyJoint to the humanoid bone name `@margoengine/rigging` uses (`HumanoidBone`); joints with no bone are absent. */
7
+ export declare const BODY_JOINT_TO_HUMANOID: Readonly<Record<string, string>>;
8
+ /** What `BodyTracking.create` needs of an `XR`: its session and reference space. */
9
+ export interface BodyTrackingHost {
10
+ readonly session: XRNativeSession | null;
11
+ readonly referenceSpace: XRSpace | undefined;
12
+ }
13
+ /** Options for {@link BodyTracking.create}. */
14
+ export interface BodyTrackingOptions {
15
+ /** Throw MargoError 'unsupported' instead of reporting `available: false` when body tracking is missing. Default false. */
16
+ required?: boolean;
17
+ }
18
+ /** One frame of body joint poses in the session's reference space; the object is reused, so copy what you keep. */
19
+ export interface BodyPose {
20
+ /** Joint order is {@link BODY_JOINT_NAMES}: 83 x [x, y, z] in metres. */
21
+ readonly positions: Float32Array;
22
+ /** 83 x unit quaternion [x, y, z, w]. */
23
+ readonly rotations: Float32Array;
24
+ /** True when the device emulated (guessed) any joint position. */
25
+ emulated: boolean;
26
+ /** A joint's [x, y, z] (a view into `positions`), or undefined for an unknown name. */
27
+ position(joint: string): Float32Array | undefined;
28
+ /** A joint's [x, y, z, w] (a view into `rotations`), or undefined for an unknown name. */
29
+ rotation(joint: string): Float32Array | undefined;
30
+ }
31
+ /** One humanoid bone's world pose. */
32
+ export interface HumanoidBonePose {
33
+ position: [number, number, number];
34
+ rotation: [number, number, number, number];
35
+ }
36
+ /**
37
+ * Body tracking in a session started with the 'body-tracking' feature (an optional feature: few devices have it).
38
+ * `BodyTracking.create(xr)` never throws without the feature: check `available`, or pass `{required: true}` for a
39
+ * MargoError 'unsupported'. `read(frame)` gives all 83 joints or null (the spec reports every joint or none).
40
+ */
41
+ export declare class BodyTracking {
42
+ private readonly host;
43
+ /** Whether the session was granted the 'body-tracking' feature. */
44
+ readonly available: boolean;
45
+ private readonly pose;
46
+ private readonly spaces;
47
+ private spacesFor?;
48
+ private constructor();
49
+ /** Reads the session's granted features. Throws 'state' without a session, 'unsupported' only with `required`. */
50
+ static create(xr: BodyTrackingHost, options?: BodyTrackingOptions): BodyTracking;
51
+ /**
52
+ * This frame's joint poses, or null without the feature, for another session's frame, while tracking is lost or when
53
+ * any joint has no pose.
54
+ */
55
+ read(frame: XRNativeFrame): BodyPose | null;
56
+ }
57
+ /** A pose as world position and rotation per humanoid bone name, ready for `@margoengine/rigging` retargeting. */
58
+ export declare function humanoidPose(pose: BodyPose): Map<string, HumanoidBonePose>;
package/dist/body.js ADDED
@@ -0,0 +1,134 @@
1
+ import { n as e } from "./errors-XvcwUnU4.js";
2
+ //#region src/body.ts
3
+ var t = "body-tracking", n = [
4
+ "index",
5
+ "middle",
6
+ "ring",
7
+ "little"
8
+ ], r = (e) => [
9
+ `${e}-hand-palm`,
10
+ `${e}-hand-wrist`,
11
+ ...[
12
+ "metacarpal",
13
+ "phalanx-proximal",
14
+ "phalanx-distal",
15
+ "tip"
16
+ ].map((t) => `${e}-hand-thumb-${t}`),
17
+ ...n.flatMap((t) => [
18
+ "metacarpal",
19
+ "phalanx-proximal",
20
+ "phalanx-intermediate",
21
+ "phalanx-distal",
22
+ "tip"
23
+ ].map((n) => t === "middle" && n === "metacarpal" ? `${e}-hand-middle-phalanx-metacarpal` : `${e}-hand-${t}-${n}`))
24
+ ], i = (e) => [
25
+ "shoulder",
26
+ "scapula",
27
+ "arm-upper",
28
+ "arm-lower",
29
+ "hand-wrist-twist"
30
+ ].map((t) => `${e}-${t}`), a = (e) => [
31
+ "upper-leg",
32
+ "lower-leg",
33
+ "foot-ankle-twist",
34
+ "foot-ankle",
35
+ "foot-subtalar",
36
+ "foot-transverse",
37
+ "foot-ball"
38
+ ].map((t) => `${e}-${t}`), o = Object.freeze([
39
+ "hips",
40
+ "spine-lower",
41
+ "spine-middle",
42
+ "spine-upper",
43
+ "chest",
44
+ "neck",
45
+ "head",
46
+ ...i("left"),
47
+ ...i("right"),
48
+ ...r("left"),
49
+ ...r("right"),
50
+ ...a("left"),
51
+ ...a("right")
52
+ ]), s = {
53
+ hips: "hips",
54
+ "spine-lower": "spine",
55
+ "spine-middle": "chest",
56
+ "spine-upper": "upperChest",
57
+ neck: "neck",
58
+ head: "head"
59
+ }, c = {
60
+ shoulder: "Shoulder",
61
+ "arm-upper": "UpperArm",
62
+ "arm-lower": "LowerArm",
63
+ "hand-wrist": "Hand",
64
+ "upper-leg": "UpperLeg",
65
+ "lower-leg": "LowerLeg",
66
+ "foot-ankle": "Foot",
67
+ "foot-ball": "Toes"
68
+ }, l = (e) => e[0].toUpperCase() + e.slice(1), u = Object.freeze(Object.fromEntries(o.flatMap((e) => {
69
+ if (s[e]) return [[e, s[e]]];
70
+ let t = /^(left|right)-(.+)$/.exec(e);
71
+ if (!t) return [];
72
+ let [, n, r] = t;
73
+ if (c[r]) return [[e, n + c[r]]];
74
+ let i = /^hand-(thumb|index|middle|ring|little)-(?:phalanx-)?(metacarpal|proximal|intermediate|distal)$/.exec(r.replace("middle-phalanx-metacarpal", "middle-metacarpal"));
75
+ return !i || i[2] === "metacarpal" && i[1] !== "thumb" ? [] : [[e, n + l(i[1]) + l(i[2])]];
76
+ }))), d = new Map(o.map((e, t) => [e, t])), f = class t {
77
+ constructor(e, t) {
78
+ this.host = e, this.available = t, this.spaces = [];
79
+ let n = new Float32Array(o.length * 3), r = new Float32Array(o.length * 4);
80
+ this.pose = {
81
+ positions: n,
82
+ rotations: r,
83
+ emulated: !1,
84
+ position: (e) => d.has(e) ? n.subarray(d.get(e) * 3, d.get(e) * 3 + 3) : void 0,
85
+ rotation: (e) => d.has(e) ? r.subarray(d.get(e) * 4, d.get(e) * 4 + 4) : void 0
86
+ };
87
+ }
88
+ static create(n, r = {}) {
89
+ let i = n?.session;
90
+ if (!i) throw e("state", "BodyTracking needs an active XR session; await xr.requestSession first");
91
+ let a = !i.enabledFeatures || i.enabledFeatures.includes("body-tracking");
92
+ if (!a && r.required) throw e("unsupported", "The XR session has no 'body-tracking' feature; request it in optionalFeatures and use a device that supports it");
93
+ return new t(n, a);
94
+ }
95
+ read(e) {
96
+ let t = this.host.referenceSpace, n = e?.body;
97
+ if (!this.available || !t || !n || e.session !== this.host.session) return null;
98
+ if (this.spacesFor !== n) {
99
+ this.spaces.length = 0;
100
+ for (let e of o) this.spaces.push(n.get(e));
101
+ this.spacesFor = n;
102
+ }
103
+ let { positions: r, rotations: i } = this.pose, a = !1;
104
+ for (let n = 0; n < o.length; n++) {
105
+ let o = this.spaces[n], s = o && e.getPose(o, t);
106
+ if (!s) return null;
107
+ let c = s.transform;
108
+ r[n * 3] = c.position.x, r[n * 3 + 1] = c.position.y, r[n * 3 + 2] = c.position.z, i[n * 4] = c.orientation.x, i[n * 4 + 1] = c.orientation.y, i[n * 4 + 2] = c.orientation.z, i[n * 4 + 3] = c.orientation.w, a ||= s.emulatedPosition;
109
+ }
110
+ return this.pose.emulated = a, this.pose;
111
+ }
112
+ };
113
+ function p(e) {
114
+ let t = /* @__PURE__ */ new Map();
115
+ for (let [n, r] of Object.entries(u)) {
116
+ let i = d.get(n);
117
+ t.set(r, {
118
+ position: [
119
+ e.positions[i * 3],
120
+ e.positions[i * 3 + 1],
121
+ e.positions[i * 3 + 2]
122
+ ],
123
+ rotation: [
124
+ e.rotations[i * 4],
125
+ e.rotations[i * 4 + 1],
126
+ e.rotations[i * 4 + 2],
127
+ e.rotations[i * 4 + 3]
128
+ ]
129
+ });
130
+ }
131
+ return t;
132
+ }
133
+ //#endregion
134
+ export { o as BODY_JOINT_NAMES, u as BODY_JOINT_TO_HUMANOID, t as BODY_TRACKING_FEATURE, f as BodyTracking, p as humanoidPose };
@@ -0,0 +1,32 @@
1
+ import type { XRInputSource, XRNativeFrame, XRSpace, XRPose } from './types.js';
2
+ /** Buffers are reused; read them during the frame callback or copy to retain a snapshot. */
3
+ export declare class XRController {
4
+ readonly source: XRInputSource;
5
+ /** Pose of the pointing ray this frame, or null when untracked. */
6
+ targetRay: XRPose | null;
7
+ /** Pose of the held grip this frame, or null when untracked or absent. */
8
+ grip: XRPose | null;
9
+ /** Column-major target-ray matrix; zero when untracked. */
10
+ readonly targetRayMatrix: Float32Array<ArrayBuffer>;
11
+ /** Column-major grip matrix; zero when untracked. */
12
+ readonly gripMatrix: Float32Array<ArrayBuffer>;
13
+ /** Per button: value, pressed, touched (32 buttons). */
14
+ readonly buttons: Float32Array<ArrayBuffer>;
15
+ /** Gamepad axes (up to 16). */
16
+ readonly axes: Float32Array<ArrayBuffer>;
17
+ /** 25 column-major joint matrices when hand tracking is granted. */
18
+ readonly handMatrices: Float32Array<ArrayBuffer>;
19
+ /** 1 for each joint that has a pose this frame. */
20
+ readonly handTracked: Uint8Array<ArrayBuffer>;
21
+ /** Each joint's radius in metres (WebXR Hand Input: a sphere at the joint touching the skin); 0 when untracked. */
22
+ readonly handRadii: Float32Array<ArrayBuffer>;
23
+ /** Buttons the gamepad reports. */
24
+ buttonCount: number;
25
+ /** Axes the gamepad reports. */
26
+ axisCount: number;
27
+ private readonly joints;
28
+ /** @param source The browser's input source. */
29
+ constructor(source: XRInputSource);
30
+ /** Reads this frame's poses and gamepad into the reused buffers. */
31
+ update(frame: XRNativeFrame, space: XRSpace): void;
32
+ }
@@ -0,0 +1,39 @@
1
+ import { checkXRRun, xrRunGaps, XR_RUN_MIN_FRAMES, XR_RUN_TARGETS } from './shared/xr-run.js';
2
+ import type { XRRun, XRRunObserved, XRRunTarget } from './shared/xr-run.js';
3
+ import type { XRFrameState, XRMode, XRNativeSession } from './types.js';
4
+ export { checkXRRun, xrRunGaps, XR_RUN_MIN_FRAMES, XR_RUN_TARGETS };
5
+ export type { XRRun, XRRunObserved, XRRunTarget };
6
+ /** What `runDeviceCheck` needs of an `XR`. */
7
+ export interface DeviceCheckHost {
8
+ requestSession(mode: XRMode, options: {
9
+ optionalFeatures?: string[];
10
+ requiredFeatures?: string[];
11
+ signal?: AbortSignal;
12
+ onFrame?: (state: XRFrameState) => void;
13
+ }): Promise<XRNativeSession>;
14
+ end(): Promise<void>;
15
+ }
16
+ /** Options for {@link runDeviceCheck}. */
17
+ export interface DeviceCheckOptions {
18
+ /** Session to run. Default 'immersive-vr'. */
19
+ mode?: XRMode;
20
+ /** How long the session runs in seconds, from its first frame. Default 20, about 1,400 frames on a 72 Hz headset. */
21
+ seconds?: number;
22
+ /** Features the session must have. Default none. */
23
+ requiredFeatures?: string[];
24
+ /** Features to ask for and record when granted. Default hand tracking, hit testing, anchors, planes, depth and light. */
25
+ optionalFeatures?: string[];
26
+ /** Asks the tester what they saw once the session is over. Default none: the run then proves no route. */
27
+ observe?: (run: XRRun) => Promise<XRRunObserved>;
28
+ /** Ends the session early; the promise rejects with the reason. */
29
+ signal?: AbortSignal;
30
+ /** Called every frame, for the page's own scene updates. */
31
+ onFrame?: (state: XRFrameState) => void;
32
+ }
33
+ /**
34
+ * Runs one session for `seconds` and resolves with what happened. Call it from a user gesture. A failure in `onFrame`
35
+ * is recorded in `errors`, since finding those is what the run is for; one that stops the session starting rejects.
36
+ * A run with `native` false is a stand-in and proves no route (`xrRunGaps`).
37
+ * @throws RangeError when `seconds` is not above 0.
38
+ */
39
+ export declare function runDeviceCheck(xr: DeviceCheckHost, options?: DeviceCheckOptions): Promise<XRRun>;
@@ -0,0 +1,155 @@
1
+ import { n as e } from "./errors-XvcwUnU4.js";
2
+ //#region ../shared/xr-run.js
3
+ var t = [
4
+ {
5
+ id: "vr-webgpu",
6
+ mode: "immersive-vr",
7
+ route: "webgpu",
8
+ needs: "a VR headset whose browser has WebXR's WebGPU binding (XRGPUBinding)"
9
+ },
10
+ {
11
+ id: "vr-webgl2",
12
+ mode: "immersive-vr",
13
+ route: "webgl2",
14
+ needs: "a VR headset whose browser has WebXR on WebGL2"
15
+ },
16
+ {
17
+ id: "ar-webgpu",
18
+ mode: "immersive-ar",
19
+ route: "webgpu",
20
+ needs: "an AR phone or headset whose browser has WebXR's WebGPU binding (XRGPUBinding)"
21
+ },
22
+ {
23
+ id: "ar-webgl2",
24
+ mode: "immersive-ar",
25
+ route: "webgl2",
26
+ needs: "an AR phone or headset with WebXR on WebGL2"
27
+ }
28
+ ], n = 300, r = (e) => typeof e == "string" && e.length > 0, i = (e) => Number.isInteger(e) && e >= 0, a = (e) => Number.isFinite(e) && e >= 0;
29
+ function o(e) {
30
+ if (typeof e != "object" || !e) return ["the run is not an object"];
31
+ let t = [], n = (e, n) => {
32
+ e || t.push(`${n} is missing or wrong`);
33
+ };
34
+ n(e.schema === 1, "schema"), n(r(e.date) && !Number.isNaN(Date.parse(e.date)), "date"), n(r(e.userAgent), "userAgent"), n(typeof e.native == "boolean", "native"), n([
35
+ "inline",
36
+ "immersive-vr",
37
+ "immersive-ar"
38
+ ].includes(e.mode), "mode"), n([
39
+ "webgpu",
40
+ "webgl2",
41
+ "none"
42
+ ].includes(e.route), "route"), n(Array.isArray(e.features) && e.features.every(r), "features");
43
+ for (let t of [
44
+ "views",
45
+ "frames",
46
+ "tracked",
47
+ "emulated"
48
+ ]) n(i(e[t]), t);
49
+ n(e.tracked <= e.frames && e.emulated <= e.tracked, "tracked");
50
+ for (let t of [
51
+ "median",
52
+ "p95",
53
+ "max"
54
+ ]) n(a(e.frameMs?.[t]), `frameMs.${t}`);
55
+ if (n(Array.isArray(e.inputs) && e.inputs.every((e) => r(e?.handedness) && r(e.targetRayMode) && Array.isArray(e.profiles) && typeof e.hand == "boolean" && i(e.buttons) && i(e.axes)), "inputs"), n(typeof e.endedEarly == "boolean", "endedEarly"), n(Array.isArray(e.errors) && e.errors.every((e) => typeof e == "string"), "errors"), e.observed !== void 0) for (let t of [
56
+ "scene",
57
+ "tracking",
58
+ "input",
59
+ "exit"
60
+ ]) n(typeof e.observed?.[t] == "boolean", `observed.${t}`);
61
+ return t;
62
+ }
63
+ function s(e, t) {
64
+ let n = [], r = (e, t) => {
65
+ e || n.push(t);
66
+ };
67
+ r(e.native, "navigator.xr was a stand-in, not the browser"), r(e.mode === t.mode, `the mode was ${e.mode}, not ${t.mode}`), r(e.route === t.route, `the route was ${e.route}, not ${t.route}`), r(e.tracked >= 300, `only ${e.tracked} tracked frames, under 300`), r(e.views >= (t.mode === "immersive-vr" ? 2 : 1), `only ${e.views} views`), r(!e.errors.length, `${e.errors.length} errors`), r(!e.endedEarly, "the session ended early"), r(e.inputs.length > 0, "no input source was seen");
68
+ for (let t of [
69
+ "scene",
70
+ "tracking",
71
+ "input",
72
+ "exit"
73
+ ]) r(e.observed?.[t] === !0, `the tester did not confirm ${t}`);
74
+ return n;
75
+ }
76
+ //#endregion
77
+ //#region src/device-check.ts
78
+ var c = [
79
+ "hand-tracking",
80
+ "hit-test",
81
+ "anchors",
82
+ "plane-detection",
83
+ "depth-sensing",
84
+ "light-estimation"
85
+ ];
86
+ function l() {
87
+ let e = globalThis.navigator?.xr?.requestSession;
88
+ return typeof e == "function" && /\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(e));
89
+ }
90
+ function u(e) {
91
+ return e === "inline" ? "none" : globalThis.XRGPUBinding?.webgl ? "webgl2" : "webgpu";
92
+ }
93
+ var d = (e, t) => e.length ? e[Math.min(e.length - 1, Math.floor(e.length * t))] : 0, f = (e) => ({
94
+ handedness: e.handedness,
95
+ targetRayMode: e.targetRayMode,
96
+ profiles: [...e.profiles],
97
+ hand: !!e.hand,
98
+ buttons: e.gamepad?.buttons.length ?? 0,
99
+ axes: e.gamepad?.axes.length ?? 0
100
+ });
101
+ async function p(t, n = {}) {
102
+ let { mode: r = "immersive-vr", seconds: i = 20, requiredFeatures: a, optionalFeatures: s = c, observe: p, signal: m, onFrame: h } = n;
103
+ if (!(i > 0) || !Number.isFinite(i)) throw RangeError("runDeviceCheck seconds must be above 0; pass the session length, such as 20");
104
+ let g = [], _ = /* @__PURE__ */ new Map(), v = [], y = {
105
+ schema: 1,
106
+ date: (/* @__PURE__ */ new Date()).toISOString(),
107
+ userAgent: globalThis.navigator?.userAgent ?? "unknown",
108
+ native: l(),
109
+ mode: r,
110
+ route: u(r),
111
+ features: [],
112
+ views: 0,
113
+ frames: 0,
114
+ tracked: 0,
115
+ emulated: 0,
116
+ frameMs: {
117
+ median: 0,
118
+ p95: 0,
119
+ max: 0
120
+ },
121
+ inputs: [],
122
+ endedEarly: !1,
123
+ errors: v
124
+ }, b = null, x = null, S = () => {}, C = !1, w = new Promise((e) => {
125
+ S = e;
126
+ }), T = await t.requestSession(r, {
127
+ ...a && { requiredFeatures: a },
128
+ optionalFeatures: s,
129
+ ...m && { signal: m },
130
+ onFrame(e) {
131
+ y.frames++, x !== null && g.push(e.time - x), x = e.time, b ??= e.time, e.viewer && (y.tracked++, e.viewer.emulatedPosition && y.emulated++, y.views = Math.max(y.views, e.viewer.views.length));
132
+ for (let t of e.inputs) _.has(t.source) || _.set(t.source, f(t.source));
133
+ try {
134
+ h?.(e);
135
+ } catch (e) {
136
+ v.push(String(e));
137
+ }
138
+ e.time - b >= i * 1e3 && (C = !0, S());
139
+ }
140
+ });
141
+ y.features = [...T.enabledFeatures ?? []], T.addEventListener("end", () => S(), { once: !0 });
142
+ let E = () => S();
143
+ m?.addEventListener("abort", E, { once: !0 }), m?.aborted && S(), await w, m?.removeEventListener("abort", E), y.endedEarly = !C, await t.end().catch((e) => v.push(String(e))), m?.throwIfAborted();
144
+ let D = g.sort((e, t) => e - t);
145
+ y.frameMs = {
146
+ median: d(D, .5),
147
+ p95: d(D, .95),
148
+ max: D.at(-1) ?? 0
149
+ }, y.inputs = [..._.values()], p && (y.observed = await p(y));
150
+ let O = o(y);
151
+ if (O.length) throw e("failed", `The device run is not well formed (${O.join("; ")}); report this as a bug`);
152
+ return y;
153
+ }
154
+ //#endregion
155
+ export { n as XR_RUN_MIN_FRAMES, t as XR_RUN_TARGETS, o as checkXRRun, p as runDeviceCheck, s as xrRunGaps };
@@ -0,0 +1,7 @@
1
+ //#region ../shared/errors.js
2
+ var e = (e, t) => Object.assign(Error(t), {
3
+ name: "MargoError",
4
+ code: e
5
+ }), t = (e, t) => `${e}; see https://margoengine.com/errors#${t}`, n = (n, r, i = n) => e(n, t(r, i)), r = (e, n) => RangeError(t(e, n));
6
+ //#endregion
7
+ export { e as n, r, n as t };
@@ -0,0 +1,25 @@
1
+ import type { XRBinding, XRSubImage, XRView } from './types.js';
2
+ /** The scene depth of one eye, as the eye's renderer left it, for passes that compare against it. */
3
+ export interface XREyeSceneDepth {
4
+ /** Depth-only texture, multisampled where the eye renders with MSAA; read it with `textureLoad`. */
5
+ readonly texture: GPUTexture;
6
+ /** The column-major projection that wrote it: clip w is the view-space distance (-z), clip z / w the stored depth. */
7
+ readonly projection: ArrayLike<number>;
8
+ /** The texel of the eye's top-left pixel in `texture`. */
9
+ readonly origin: readonly [number, number];
10
+ /** The value an empty sample holds: 1 for forward depth, 0 for reversed. */
11
+ readonly clear: number;
12
+ }
13
+ /** One eye after scene rendering, before submission to the XR compositor. */
14
+ export interface XREyeTarget {
15
+ /** Stable index of the view within this frame. */
16
+ readonly index: number;
17
+ readonly device: GPUDevice;
18
+ readonly encoder: GPUCommandEncoder;
19
+ readonly image: XRSubImage;
20
+ readonly view: XRView;
21
+ /** The eye's scene depth, valid until the encoder is submitted. */
22
+ readonly scene?: XREyeSceneDepth;
23
+ /** The session's XR binding, for per-view resources such as GPU depth information. */
24
+ readonly binding?: XRBinding;
25
+ }
package/dist/eyes.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ import type { XREyeTarget } from './eye-target.js';
2
+ import { type Engine } from '@margoengine/core/extension';
3
+ import type { XRBinding, XRProjectionLayer, XRViewerPose } from './types.js';
4
+ /** Draws every eye of a viewer pose through `engine.render({views})` on the engine's device. */
5
+ export declare class EyeViews {
6
+ private readonly engine;
7
+ private readonly device;
8
+ private readonly eyes;
9
+ private readonly views;
10
+ private readonly offset;
11
+ private pipelines?;
12
+ private readonly options;
13
+ constructor(engine: Engine, device: GPUDevice);
14
+ /** Moves eye `i`'s camera to `view`: its pose and its projection, with depth reversed. */
15
+ private place;
16
+ private eye;
17
+ /** Makes the eye's textures for a sub-image of `width` by `height`, keeping them while the size holds. */
18
+ private size;
19
+ private build;
20
+ /** Draws this frame's eyes and puts them in `layer`. `delta` in seconds; `ar` keeps the real world behind the scene. */
21
+ render(binding: XRBinding, layer: XRProjectionLayer, viewer: XRViewerPose, delta: number, ar: boolean, onEye?: (target: XREyeTarget) => boolean | void, layers?: number): void;
22
+ /** Frees the eyes' textures and buffers; the engine and its device stay. */
23
+ dispose(): void;
24
+ }