@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
@@ -0,0 +1,167 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import { PbrMaterial, type EngineKernel, type Scene } from '@margoengine/core';
3
+ import type { XRSessionOptions } from './index.js';
4
+ import type { XRAnchor, XRFrameState, XRNativeSession, XRSpace } from './types.js';
5
+ /** Session and frame hooks accepted by AR tracking extras. */
6
+ export interface ARExtraHost {
7
+ readonly session: XRNativeSession | null;
8
+ readonly referenceSpace: XRSpace | undefined;
9
+ onFrame(callback: (state: XRFrameState) => void): () => void;
10
+ }
11
+ /** DOM overlay options. */
12
+ export interface DOMOverlayOptions {
13
+ /** Suppress duplicate XR-world select actions over the overlay. Default true. */
14
+ preventWorldSelect?: boolean;
15
+ /** Remove event listeners on abort. */
16
+ signal?: AbortSignal;
17
+ }
18
+ /** Adds the standard dom-overlay session feature and root while preserving other session init members. */
19
+ export declare function domOverlaySessionOptions(root: Element, base?: XRSessionOptions): XRSessionOptions;
20
+ /** Owns beforexrselect handling for a browser-managed DOM overlay. */
21
+ export declare class DOMOverlay {
22
+ private disposed;
23
+ private readonly stop;
24
+ /** Attaches after negotiating domOverlaySessionOptions. */
25
+ static attach(xr: ARExtraHost, root: Element, options?: DOMOverlayOptions): DOMOverlay;
26
+ private constructor();
27
+ /** Browser overlay presentation type, or null if it does not report a type. */
28
+ readonly type: string | null;
29
+ /** Removes listeners; the caller retains the DOM element. Idempotent. */
30
+ dispose(): void;
31
+ [Symbol.dispose]: () => void;
32
+ }
33
+ /** A bitmap and its physical printed width. The caller owns the bitmap. */
34
+ export interface TrackedImageInit {
35
+ readonly image: ImageBitmap;
36
+ readonly widthInMeters: number;
37
+ }
38
+ /** Chooses the current marker-tracking feature or legacy image-tracking feature explicitly. */
39
+ export interface ImageTrackingSessionOptions {
40
+ /** Use image-tracking/getImageTrackingScores on older runtimes. Default false. */
41
+ legacy?: boolean;
42
+ }
43
+ /** Configures image targets before session negotiation. Default current marker-tracking feature. */
44
+ export declare function imageTrackingSessionOptions(images: readonly TrackedImageInit[], options?: ImageTrackingSessionOptions, base?: XRSessionOptions): XRSessionOptions;
45
+ /** A copied image observation, retained independently of the browser frame. */
46
+ export interface TrackedImage {
47
+ readonly index: number;
48
+ readonly trackingState: 'tracked' | 'emulated';
49
+ readonly measuredWidthInMeters: number;
50
+ /** Pose in the host reference space, or null while the image pose is unavailable. */
51
+ readonly matrix: Float32Array | null;
52
+ }
53
+ /** Image tracking subscriptions. */
54
+ export interface ImageTrackingOptions {
55
+ /** Called once per frame with copied observations. Default no callback; images remains available. */
56
+ onUpdate?: (images: readonly TrackedImage[]) => void;
57
+ /** Remove frame and session listeners on abort. */
58
+ signal?: AbortSignal;
59
+ }
60
+ /** Tracks supplied image targets with both the current and legacy browser module. */
61
+ export declare class ImageTracking {
62
+ private readonly host;
63
+ private readonly options;
64
+ /** Current copied observations, keyed by target index. */
65
+ readonly images: Map<number, TrackedImage>;
66
+ private readonly lifetime;
67
+ private disposed;
68
+ /** Attaches to the negotiated current or legacy image tracking session. */
69
+ static attach(host: ARExtraHost, options?: ImageTrackingOptions): ImageTracking;
70
+ private constructor();
71
+ /** Returns trackable/untrackable scores in target order; abort cancels the wait. */
72
+ trackability(signal?: AbortSignal): Promise<readonly string[]>;
73
+ private update;
74
+ /** Unsubscribes, cancels pending score waits and clears observations. Idempotent. */
75
+ dispose(): void;
76
+ [Symbol.dispose]: () => void;
77
+ }
78
+ /** Browser mesh detection object. */
79
+ export interface XRDetectedMesh {
80
+ readonly meshSpace: XRSpace;
81
+ readonly vertices: Float32Array;
82
+ readonly indices: Uint32Array;
83
+ readonly lastChangedTime: number;
84
+ readonly semanticLabel?: string | null;
85
+ }
86
+ /** Copied mesh geometry plus a current pose, usable after the browser frame ends. */
87
+ export interface DetectedMesh {
88
+ readonly source: XRDetectedMesh;
89
+ readonly vertices: Float32Array;
90
+ readonly indices: Uint32Array;
91
+ readonly matrix: Float32Array | null;
92
+ readonly label: string;
93
+ readonly lastChangedTime: number;
94
+ }
95
+ /** Mesh tracking options. */
96
+ export interface MeshDetectionOptions {
97
+ /** Called for new geometry. */
98
+ onAdd?: (mesh: DetectedMesh) => void;
99
+ /** Called when geometry or semantic label changes; pose alone does not count as geometry change. */
100
+ onChange?: (mesh: DetectedMesh) => void;
101
+ /** Called when the browser removes a mesh, or the tracker closes. */
102
+ onRemove?: (mesh: DetectedMesh) => void;
103
+ /** Optional drawing. Default no visualization. Scene defaults to engine.scene; material defaults to grey. */
104
+ show?: {
105
+ engine: EngineKernel;
106
+ scene?: Scene;
107
+ material?: PbrMaterial;
108
+ };
109
+ /** Close on abort. */
110
+ signal?: AbortSignal;
111
+ }
112
+ /** Tracks native triangle meshes and optionally displays them as Margo meshes. */
113
+ export declare class MeshDetection {
114
+ private readonly host;
115
+ private readonly options;
116
+ private readonly geometry;
117
+ /** Current copied records by the browser's stable mesh identity. */
118
+ readonly meshes: Map<XRDetectedMesh, DetectedMesh>;
119
+ private readonly lifetime;
120
+ private readonly visible;
121
+ private readonly drawScene?;
122
+ private disposed;
123
+ /** Loads normal generation lazily only for show, then subscribes to an active mesh-detection session. */
124
+ static create(host: ARExtraHost, options?: MeshDetectionOptions): Promise<MeshDetection>;
125
+ private constructor();
126
+ private update;
127
+ private draw;
128
+ /** Releases visualization meshes and subscriptions, and cancels waits. Idempotent. */
129
+ dispose(): void;
130
+ [Symbol.dispose]: () => void;
131
+ }
132
+ /** A browser anchor that can persist across sessions. */
133
+ export interface XRPersistentAnchor extends XRAnchor {
134
+ requestPersistentHandle(): Promise<string>;
135
+ }
136
+ /** The native persistent-anchor session API. */
137
+ export interface PersistentAnchorSession extends XRNativeSession {
138
+ readonly persistentAnchors: readonly string[];
139
+ restorePersistentAnchor(handle: string): Promise<XRAnchor>;
140
+ deletePersistentAnchor(handle: string): Promise<void>;
141
+ }
142
+ /** Persistent anchors remain browser/origin-owned until explicitly deleted. */
143
+ export declare class PersistentAnchors {
144
+ private readonly host;
145
+ private readonly lifetime;
146
+ private readonly session;
147
+ private disposed;
148
+ private readonly pendingSave;
149
+ private readonly pendingRestore;
150
+ /** Binds to an active anchors session. */
151
+ static attach(host: ARExtraHost, options?: {
152
+ signal?: AbortSignal;
153
+ }): PersistentAnchors;
154
+ private constructor();
155
+ /** Known origin-scoped persistent handles; the array is copied. */
156
+ get handles(): readonly string[];
157
+ private active;
158
+ /** Saves an anchor and returns the browser's handle. Abort is checked before and after the native operation. */
159
+ save(anchor: XRPersistentAnchor, signal?: AbortSignal): Promise<string>;
160
+ /** Restores tracking of a persistent handle; abort releases unclaimed tracking, retaining the saved handle. */
161
+ restore(handle: string, signal?: AbortSignal): Promise<XRAnchor>;
162
+ /** Explicitly deletes a saved anchor from the browser store. Abort checked before starting the native deletion. */
163
+ delete(handle: string, signal?: AbortSignal): Promise<void>;
164
+ /** Removes subscriptions. Persistent handles are kept until delete is called. Idempotent. */
165
+ dispose(): void;
166
+ [Symbol.dispose]: () => void;
167
+ }
@@ -0,0 +1,247 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import { n as e } from "./errors-XvcwUnU4.js";
5
+ import { t } from "./scene-owner-BRObO-WJ.js";
6
+ import { Geometry as n, PbrMaterial as r } from "@margoengine/core";
7
+ import { splitTRS as i } from "@margoengine/math/quat";
8
+ //#region src/ar-extra.ts
9
+ function a(e, t = {}) {
10
+ if (!e || e.nodeType !== 1) throw TypeError("DOM overlay needs an element; pass a container from document.createElement");
11
+ return {
12
+ ...t,
13
+ requiredFeatures: [.../* @__PURE__ */ new Set([...t.requiredFeatures ?? [], "dom-overlay"])],
14
+ init: {
15
+ ...t.init,
16
+ domOverlay: { root: e }
17
+ }
18
+ };
19
+ }
20
+ var o = class e {
21
+ static attach(t, n, r = {}) {__margoAssertCore(t,__margoCoreRequirement("0.1.0",import.meta.url));
22
+ return new e(t, n, r);
23
+ }
24
+ constructor(e, t, n) {
25
+ this.disposed = !1, n.signal?.throwIfAborted();
26
+ let r = c(e, "dom-overlay");
27
+ if (!t || t.nodeType !== 1) throw TypeError("DOM overlay needs an element; pass the root used to request the session");
28
+ let i = (e) => {
29
+ (n.preventWorldSelect ?? !0) && e.preventDefault();
30
+ }, a = () => this.dispose();
31
+ t.addEventListener("beforexrselect", i), r.addEventListener("end", a), n.signal?.addEventListener("abort", a, { once: !0 }), this.stop = () => {
32
+ t.removeEventListener("beforexrselect", i), r.removeEventListener("end", a), n.signal?.removeEventListener("abort", a);
33
+ }, this.type = r.domOverlayState?.type ?? null;
34
+ }
35
+ dispose() {
36
+ this.disposed || (this.disposed = !0, this.stop());
37
+ }
38
+ [Symbol.dispose ?? Symbol()]() {
39
+ this.dispose();
40
+ }
41
+ };
42
+ function s(e, t = {}, n = {}) {
43
+ if (!Array.isArray(e) || !e.length) throw TypeError("Provide image targets before entering AR; pass [{ image, widthInMeters: 0.2 }]");
44
+ let r = e.map((e) => {
45
+ if (!e?.image || !Number.isFinite(e.widthInMeters) || e.widthInMeters <= 0) throw RangeError("Each image target needs a bitmap and positive finite widthInMeters; pass the printed image width in metres");
46
+ return {
47
+ image: e.image,
48
+ widthInMeters: e.widthInMeters
49
+ };
50
+ }), i = t.legacy ? "image-tracking" : "marker-tracking";
51
+ return {
52
+ ...n,
53
+ requiredFeatures: [.../* @__PURE__ */ new Set([...n.requiredFeatures ?? [], i])],
54
+ init: {
55
+ ...n.init,
56
+ trackedImages: r
57
+ }
58
+ };
59
+ }
60
+ var c = (t, n) => {
61
+ let r = t.session;
62
+ if (!r) throw e("state", "AR tracking needs an active session; await xr.requestSession first");
63
+ if (r.enabledFeatures && !r.enabledFeatures.includes(n)) throw e("unsupported", `The session has no '${n}' feature; request it before entering AR`);
64
+ return r;
65
+ }, l = class {
66
+ constructor(e, t, n) {
67
+ this.session = e, this.close = n, this.abort = new AbortController(), this.stops = [], t?.throwIfAborted();
68
+ let r = () => n();
69
+ e.addEventListener("end", r), t?.addEventListener("abort", r, { once: !0 }), this.stops.push(() => e.removeEventListener("end", r), () => t?.removeEventListener("abort", r));
70
+ }
71
+ stop() {
72
+ this.abort.abort(e("disposed", "AR tracking is disposed; create a tracker for an active session"));
73
+ for (let e of this.stops) e();
74
+ this.stops.length = 0;
75
+ }
76
+ async wait(e, t) {
77
+ let n = t ? AbortSignal.any([this.abort.signal, t]) : this.abort.signal;
78
+ n.throwIfAborted();
79
+ let r = () => {}, i = new Promise((e, t) => {
80
+ let i = () => t(n.reason);
81
+ n.addEventListener("abort", i, { once: !0 }), r = () => n.removeEventListener("abort", i);
82
+ });
83
+ try {
84
+ return await Promise.race([e, i]);
85
+ } finally {
86
+ r();
87
+ }
88
+ }
89
+ }, u = class t {
90
+ static attach(e, n = {}) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
91
+ return new t(e, n);
92
+ }
93
+ constructor(e, t) {
94
+ this.host = e, this.options = t, this.images = /* @__PURE__ */ new Map(), this.disposed = !1;
95
+ let n = e.session?.enabledFeatures?.includes("marker-tracking") ? "marker-tracking" : "image-tracking";
96
+ this.lifetime = new l(c(e, n), t.signal, () => this.dispose()), this.lifetime.stops.push(e.onFrame((e) => this.update(e)));
97
+ }
98
+ async trackability(t) {
99
+ let n = this.lifetime.session, r = n.getImageTrackability ?? n.getImageTrackingScores;
100
+ if (!r) throw e("unsupported", "The session cannot report image trackability; use a runtime with the image tracking module");
101
+ return this.lifetime.abort.signal.throwIfAborted(), t?.throwIfAborted(), Object.freeze([...await this.lifetime.wait(r.call(n), t)]);
102
+ }
103
+ update(t) {
104
+ if (this.disposed || t.frame.session !== this.lifetime.session) return;
105
+ let n = t.frame.getImageTrackingResults;
106
+ if (!n) throw e("unsupported", "The frame has no image tracking results; request marker-tracking or legacy image-tracking");
107
+ let r = /* @__PURE__ */ new Map(), i = this.host.referenceSpace;
108
+ for (let e of n.call(t.frame)) {
109
+ let n = i ? t.frame.getPose(e.imageSpace, i) : null;
110
+ r.set(e.index, Object.freeze({
111
+ index: e.index,
112
+ trackingState: e.trackingState,
113
+ measuredWidthInMeters: e.measuredWidthInMeters,
114
+ matrix: n ? new Float32Array(n.transform.matrix) : null
115
+ }));
116
+ }
117
+ this.images.clear();
118
+ for (let [e, t] of r) this.images.set(e, t);
119
+ this.options.onUpdate?.(Object.freeze([...this.images.values()]));
120
+ }
121
+ dispose() {
122
+ this.disposed || (this.disposed = !0, this.lifetime.stop(), this.images.clear());
123
+ }
124
+ [Symbol.dispose ?? Symbol()]() {
125
+ this.dispose();
126
+ }
127
+ }, d = class a {
128
+ static async create(t, n = {}) {
129
+ let r = c(t, "mesh-detection");
130
+ n.signal?.throwIfAborted();
131
+ let i = n.show ? await import("@margoengine/geometry") : void 0;
132
+ if (n.signal?.throwIfAborted(), t.session !== r) throw e("state", "The XR session changed while preparing mesh display; create a tracker for the active session");
133
+ return new a(t, n, i);
134
+ }
135
+ constructor(e, n, r) {
136
+ this.host = e, this.options = n, this.geometry = r, this.meshes = /* @__PURE__ */ new Map(), this.visible = /* @__PURE__ */ new Map(), this.disposed = !1, this.lifetime = new l(c(e, "mesh-detection"), n.signal, () => this.dispose()), this.drawScene = n.show?.scene ?? n.show?.engine.scene, this.drawScene && this.lifetime.stops.push(t(this.drawScene, () => this.dispose())), this.lifetime.stops.push(e.onFrame((e) => this.update(e)));
137
+ }
138
+ update(t) {
139
+ if (this.disposed || t.frame.session !== this.lifetime.session) return;
140
+ let n = t.frame.detectedMeshes;
141
+ if (!n) throw e("unsupported", "The frame has no detected meshes; request the mesh-detection feature");
142
+ let r = [];
143
+ for (let [e, t] of this.meshes) n.has(e) || (this.meshes.delete(e), this.visible.get(e)?.dispose(), this.visible.delete(e), r.push(t));
144
+ for (let e of r) if (this.options.onRemove?.(e), this.disposed) return;
145
+ for (let e of n) {
146
+ let n = this.meshes.get(e), r = !n || n.lastChangedTime !== e.lastChangedTime || n.label !== (e.semanticLabel ?? ""), i = this.host.referenceSpace ? t.frame.getPose(e.meshSpace, this.host.referenceSpace) : null, a = Object.freeze({
147
+ source: e,
148
+ vertices: r ? e.vertices.slice() : n.vertices,
149
+ indices: r ? e.indices.slice() : n.indices,
150
+ matrix: i ? new Float32Array(i.transform.matrix) : null,
151
+ label: e.semanticLabel ?? "",
152
+ lastChangedTime: e.lastChangedTime
153
+ });
154
+ if (this.meshes.set(e, a), this.options.show && this.draw(a, r), n ? r && this.options.onChange?.(a) : this.options.onAdd?.(a), this.disposed) return;
155
+ }
156
+ }
157
+ draw(e, t) {
158
+ let a = this.options.show, o = this.drawScene, s = this.visible.get(e.source);
159
+ if (s || (s = o.createMesh().setMaterial(a.material ?? new r({ color: "#8899aa" })), this.visible.set(e.source, s)), s.visible = e.matrix !== null, t) {
160
+ let t = this.geometry.geometryData(e.vertices, new Float32Array(e.vertices.length), new Float32Array(e.vertices.length / 3 * 2), e.indices), r = this.geometry.computeVertexNormals(t).normals;
161
+ s.setGeometry(new n(e.vertices, r, e.indices));
162
+ }
163
+ if (e.matrix) {
164
+ let t = i(e.matrix);
165
+ if (!t.ok) throw RangeError("Detected mesh pose is not rigid; use a WebXR runtime that returns rigid mesh poses");
166
+ s.setPosition(t.position).setQuaternion(t.rotation).setScale(t.scale);
167
+ }
168
+ }
169
+ dispose() {
170
+ if (this.disposed) return;
171
+ this.disposed = !0, this.lifetime.stop();
172
+ for (let e of this.visible.values()) e.dispose();
173
+ this.visible.clear();
174
+ let e = [...this.meshes.values()];
175
+ this.meshes.clear();
176
+ for (let t of e) this.options.onRemove?.(t);
177
+ }
178
+ [Symbol.dispose ?? Symbol()]() {
179
+ this.dispose();
180
+ }
181
+ }, f = class t {
182
+ static attach(e, n = {}) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
183
+ return new t(e, n.signal);
184
+ }
185
+ constructor(t, n) {
186
+ this.host = t, this.disposed = !1, this.pendingSave = /* @__PURE__ */ new WeakMap(), this.pendingRestore = /* @__PURE__ */ new Map();
187
+ let r = c(t, "anchors");
188
+ if (!Array.isArray(r.persistentAnchors) || typeof r.restorePersistentAnchor != "function" || typeof r.deletePersistentAnchor != "function") throw e("unsupported", "Persistent anchors are unavailable; use a browser with persistentAnchors and restorePersistentAnchor");
189
+ this.session = r, this.lifetime = new l(r, n, () => this.dispose());
190
+ }
191
+ get handles() {
192
+ return this.active(), Object.freeze([...this.session.persistentAnchors]);
193
+ }
194
+ active() {
195
+ if (this.disposed) throw e("disposed", "PersistentAnchors is disposed; attach to an active anchors session");
196
+ if (this.host.session !== this.session) throw e("state", "The XR session changed; attach to the active session");
197
+ }
198
+ async save(t, n) {
199
+ if (this.active(), n?.throwIfAborted(), typeof t?.requestPersistentHandle != "function") throw e("unsupported", "This anchor cannot persist; use an anchor with requestPersistentHandle");
200
+ let r = this.pendingSave.get(t);
201
+ if (!r) {
202
+ let e = new Set(this.session.persistentAnchors);
203
+ r = {
204
+ work: t.requestPersistentHandle(),
205
+ before: e,
206
+ waiters: 0,
207
+ claimed: !1
208
+ }, this.pendingSave.set(t, r);
209
+ }
210
+ r.waiters++;
211
+ let i;
212
+ try {
213
+ if (i = await r.work, n?.aborted) throw n.reason;
214
+ return this.active(), r.claimed = !0, i;
215
+ } finally {
216
+ r.waiters--, r.waiters === 0 && (this.pendingSave.delete(t), !r.claimed && i && !r.before.has(i) && await this.session.deletePersistentAnchor(i));
217
+ }
218
+ }
219
+ async restore(e, t) {
220
+ if (this.active(), t?.throwIfAborted(), typeof e != "string" || !e) throw TypeError("Pass a nonempty browser persistent anchor handle; read handles or save an anchor first");
221
+ let n = this.pendingRestore.get(e);
222
+ n || (n = {
223
+ work: this.session.restorePersistentAnchor(e),
224
+ waiters: 0,
225
+ claimed: !1
226
+ }, this.pendingRestore.set(e, n)), n.waiters++;
227
+ let r;
228
+ try {
229
+ if (r = await n.work, t?.aborted) throw t.reason;
230
+ return this.active(), n.claimed = !0, r;
231
+ } finally {
232
+ n.waiters--, n.waiters === 0 && (this.pendingRestore.delete(e), n.claimed || r?.delete());
233
+ }
234
+ }
235
+ async delete(e, t) {
236
+ if (this.active(), t?.throwIfAborted(), typeof e != "string" || !e) throw TypeError("Pass a nonempty persistent handle; read handles first");
237
+ await this.session.deletePersistentAnchor(e);
238
+ }
239
+ dispose() {
240
+ this.disposed || (this.disposed = !0, this.lifetime.stop());
241
+ }
242
+ [Symbol.dispose ?? Symbol()]() {
243
+ this.dispose();
244
+ }
245
+ };
246
+ //#endregion
247
+ export { o as DOMOverlay, u as ImageTracking, d as MeshDetection, f as PersistentAnchors, a as domOverlaySessionOptions, s as imageTrackingSessionOptions };
package/dist/ar.d.ts ADDED
@@ -0,0 +1,177 @@
1
+ import { Geometry, type EngineKernel, type PbrMaterial } from '@margoengine/core';
2
+ import type { XRFrameState, XRNativeFrame, XRNativeSession, XRSpace, XRView } from './types.js';
3
+ /** What the AR helpers need of an `XR`. */
4
+ export interface ARHost {
5
+ readonly session: XRNativeSession | null;
6
+ readonly referenceSpace: XRSpace | undefined;
7
+ onFrame(callback: (state: XRFrameState) => void): () => void;
8
+ }
9
+ /** The browser's XRPlane, as far as Margo reads it. */
10
+ export interface XRPlaneLike {
11
+ readonly planeSpace: XRSpace;
12
+ readonly polygon: readonly {
13
+ x: number;
14
+ y: number;
15
+ z: number;
16
+ }[];
17
+ readonly orientation?: 'horizontal' | 'vertical' | null;
18
+ readonly lastChangedTime: number;
19
+ readonly semanticLabel?: string | null;
20
+ }
21
+ /** One detected plane this frame. */
22
+ export interface DetectedPlane {
23
+ /** The browser's plane; the same object every frame while it is tracked. */
24
+ readonly plane: XRPlaneLike;
25
+ /** Column-major pose of the plane's centre in the reference space; its y axis is the plane's normal. */
26
+ readonly matrix: Float32Array;
27
+ /** The outline, x and z per point in the plane's own space (y is always 0 there). */
28
+ readonly polygon: Float32Array;
29
+ readonly orientation: 'horizontal' | 'vertical' | null;
30
+ /** What the device says the plane is, such as 'floor', 'wall' or 'table'; empty when it does not say. */
31
+ readonly label: string;
32
+ /** False while the plane's pose is unknown this frame. */
33
+ tracked: boolean;
34
+ }
35
+ /** Options for {@link ARPlanes.create}. */
36
+ export interface ARPlanesOptions {
37
+ /** Called when a plane is first seen. */
38
+ onAdd?: (plane: DetectedPlane) => void;
39
+ /** Called when a plane's outline, orientation or label changes. */
40
+ onChange?: (plane: DetectedPlane) => void;
41
+ /** Called when the device stops tracking a plane. */
42
+ onRemove?: (plane: DetectedPlane) => void;
43
+ /** Draws each plane as a mesh with this material; default none. */
44
+ show?: {
45
+ engine: EngineKernel;
46
+ material: PbrMaterial;
47
+ };
48
+ }
49
+ /**
50
+ * Triangles of a simple polygon given as x, z pairs, by ear clipping; works for both windings and for concave outlines.
51
+ * Every triangle winds counter-clockwise seen from +y (its right-hand normal is +y), whichever way the outline runs.
52
+ * @throws RangeError for fewer than 3 points or a non-finite one.
53
+ */
54
+ export declare function triangulate(polygon: ArrayLike<number>): Uint32Array;
55
+ /** A flat mesh of a plane outline (x, z pairs), in the plane's space, normal +y. */
56
+ export declare function planeGeometry(polygon: ArrayLike<number>): Geometry;
57
+ /**
58
+ * The planes an AR device has found, kept in step every frame. Start the session with the 'plane-detection' feature.
59
+ * `planes` holds this frame's planes; `onAdd`, `onChange` and `onRemove` tell what changed; `show` draws them.
60
+ * @throws MargoError 'state' without a session, 'unsupported' when the session has no 'plane-detection'.
61
+ */
62
+ export declare class ARPlanes {
63
+ private readonly host;
64
+ private readonly options;
65
+ /** This frame's planes by the browser's plane object. */
66
+ readonly planes: Map<XRPlaneLike, DetectedPlane>;
67
+ private readonly changed;
68
+ private readonly meshes;
69
+ private readonly unsubscribe;
70
+ private constructor();
71
+ static create(xr: ARHost, options?: ARPlanesOptions): ARPlanes;
72
+ /** Reads `frame.detectedPlanes`; runs from the XR frame hook. */
73
+ update(frame: XRNativeFrame): void;
74
+ private draw;
75
+ /** Stops following the planes and removes their meshes. */
76
+ dispose(): void;
77
+ [Symbol.dispose](): void;
78
+ }
79
+ /** The browser's XRCPUDepthInformation, as far as Margo reads it. */
80
+ export interface XRDepthLike {
81
+ readonly width: number;
82
+ readonly height: number;
83
+ readonly rawValueToMeters: number;
84
+ readonly normDepthBufferFromNormView: {
85
+ readonly matrix: Float32Array;
86
+ };
87
+ getDepthInMeters(x: number, y: number): number;
88
+ /** XRViewGeometry of the sensor, where it differs from the view. */
89
+ readonly projectionMatrix?: Float32Array;
90
+ readonly transform?: XRView['transform'];
91
+ }
92
+ /** What `depthSensing` to start an AR session with, for {@link ARDepth}: CPU data, 32-bit floats or 16-bit integers. */
93
+ export declare const DEPTH_SENSING: {
94
+ readonly usagePreference: readonly ['cpu-optimized'];
95
+ readonly dataFormatPreference: readonly ['float32', 'luminance-alpha', 'unsigned-short'];
96
+ };
97
+ /**
98
+ * Real-world depth in an AR session started with the 'depth-sensing' feature and `init: {depthSensing: DEPTH_SENSING}`:
99
+ * distances at points of a view, and the world points behind them, to place things on real surfaces or test whether
100
+ * something is behind a real object.
101
+ * @throws MargoError 'state' without a session, 'unsupported' without depth sensing or with GPU-optimized depth.
102
+ */
103
+ export declare class ARDepth {
104
+ private readonly host;
105
+ private constructor();
106
+ static create(xr: ARHost): ARDepth;
107
+ /** This frame's depth information for `view`, or null while the device has none. */
108
+ information(frame: XRNativeFrame, view: XRView): XRDepthLike | null;
109
+ /**
110
+ * Metres from the sensor to the real world at (`x`, `y`) of `view`, in normalized view coordinates (0 to 1, from the
111
+ * top left), or null without depth this frame.
112
+ * @throws RangeError for a point outside 0 to 1.
113
+ */
114
+ depthAt(frame: XRNativeFrame, view: XRView, x: number, y: number): number | null;
115
+ /**
116
+ * The real-world point at (`x`, `y`) of `view`, in the reference space, or null without depth this frame. The depth
117
+ * is taken along the sensor's view axis.
118
+ */
119
+ pointAt(frame: XRNativeFrame, view: XRView, x: number, y: number): [number, number, number] | null;
120
+ }
121
+ /** The light of the room this frame, in the reference space. */
122
+ export interface LightEstimate {
123
+ /**
124
+ * Nine RGB spherical harmonics coefficients of the room's light, coefficient-major (the order of @margoengine/math
125
+ * SH3), turned from the light probe's space into the reference space.
126
+ */
127
+ readonly sh: Float32Array;
128
+ /** Unit direction towards the brightest light. */
129
+ readonly direction: [number, number, number];
130
+ /** The brightest light's RGB intensity. */
131
+ readonly intensity: [number, number, number];
132
+ }
133
+ /**
134
+ * The parts of `engine.lighting` that {@link ARLight} sets: `direction` xyz towards the sun with w its strength,
135
+ * `radiance` rgb the sun's colour with w the ambient strength, `ambient` the ambient colour.
136
+ */
137
+ export interface LightingLike {
138
+ direction: Float32Array | number[];
139
+ radiance: Float32Array | number[];
140
+ ambient: Float32Array | number[];
141
+ }
142
+ /**
143
+ * Light estimation in an AR session started with the 'light-estimation' feature: each frame's estimate in `estimate`,
144
+ * and, with `lighting` given (such as `engine.lighting`), the engine's sun turned to the room's brightest light and its
145
+ * ambient set to the room's average light, so virtual things are lit like the real ones next to them.
146
+ * @throws MargoError 'state' without a session, 'unsupported' without the feature or the browser's light probes.
147
+ */
148
+ export declare class ARLight {
149
+ private readonly host;
150
+ /** The browser's XRLightProbe; its `reflectionchange` event and `getReflectionCubeMap` serve ARReflection. */
151
+ readonly probe: {
152
+ probeSpace: XRSpace;
153
+ };
154
+ private readonly lighting?;
155
+ /** This frame's estimate, or null while the device has none. */
156
+ estimate: LightEstimate | null;
157
+ private readonly unsubscribe;
158
+ private readonly sh;
159
+ private readonly turn;
160
+ private readonly value;
161
+ private constructor();
162
+ static create(xr: ARHost, { lighting }?: {
163
+ lighting?: LightingLike;
164
+ }): Promise<ARLight>;
165
+ /**
166
+ * As {@link ARLight.create}, with the light probe asked for a reflection cube map in `reflectionFormat` (the WebXR
167
+ * Lighting Estimation API's XRLightProbeInit); `probe` then serves {@link ARReflection}.
168
+ */
169
+ static withReflection(xr: ARHost, { lighting, reflectionFormat }?: {
170
+ lighting?: LightingLike;
171
+ reflectionFormat?: 'srgb8' | 'rgba16f';
172
+ }): Promise<ARLight>;
173
+ /** Reads this frame's estimate and applies it; runs from the XR frame hook. */
174
+ update(frame: XRNativeFrame): void;
175
+ dispose(): void;
176
+ [Symbol.dispose](): void;
177
+ }