@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/index.js ADDED
@@ -0,0 +1,957 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const r=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { n as e } from "./errors-XvcwUnU4.js";
5
+ import { t } from "./scene-scope-DufD_3B6.js";
6
+ import { Camera as n, engineRuntime as __margoRuntime } from "@margoengine/core/extension";
7
+ import { Engine as i } from "@margoengine/core";
8
+ import { MargoError as a } from "@margoengine/math/errors";
9
+ //#endregion
10
+ //#region ../shared/view-rect.js
11
+ function o() {
12
+ return globalThis[Symbol.for("margoengine.layers")];
13
+ }
14
+ function s(e) {
15
+ return o()?.maskOf(e) ?? 1;
16
+ }
17
+ function c(e, t) {
18
+ if (!Number.isInteger(e) || e < 0 || e > 4294967295) throw RangeError(`${t} ${e} is not a 32-bit layer mask; pass an integer from 0 to 0xffffffff`);
19
+ return e >>> 0;
20
+ }
21
+ //#endregion
22
+ //#region ../shared/mesh-source.js
23
+ var l = Symbol.for("margoengine.mesh-sources.v1"), u = globalThis[l] ?? /* @__PURE__ */ new WeakMap();
24
+ globalThis[l] || Object.defineProperty(globalThis, l, { value: u });
25
+ var d = Symbol.for("margoengine.geometry-surfaces.v1"), f = globalThis[d] ?? /* @__PURE__ */ new WeakMap();
26
+ globalThis[d] || Object.defineProperty(globalThis, d, { value: f });
27
+ function p(e) {
28
+ if (e?.geometry) return {
29
+ kind: "core",
30
+ geometry: e.geometry
31
+ };
32
+ let t = e && u.get(e);
33
+ if (!t || t.model.disposed) return null;
34
+ try {
35
+ e.check?.();
36
+ } catch {
37
+ return null;
38
+ }
39
+ return {
40
+ kind: "pbr",
41
+ source: t
42
+ };
43
+ }
44
+ //#endregion
45
+ //#region ../shared/unit-light.js
46
+ function m(e, t, n) {
47
+ let r = Math.hypot(n[0], n[1], n[2]);
48
+ e[t] = n[0] / r, e[t + 1] = n[1] / r, e[t + 2] = n[2] / r, e[t + 3] = n[3];
49
+ }
50
+ //#endregion
51
+ //#region ../shared/hdr-format.js
52
+ var h = (e) => typeof e == "string" && e.endsWith("float");
53
+ //#endregion
54
+ //#region ../shared/pbr-transmission.js
55
+ function g(e) {
56
+ return !!e.tint && !e.renderState && !e.extension?.replacesPhysical;
57
+ }
58
+ //#endregion
59
+ //#region src/renderer.ts
60
+ var _ = class {
61
+ constructor(e) {
62
+ this.device = e, this.resources = /* @__PURE__ */ new Map(), this.eyes = [], this.used = /* @__PURE__ */ new Set(), this.pbr = /* @__PURE__ */ new Map();
63
+ }
64
+ configure(e, t) {
65
+ this.dispose(), this.context = e;
66
+ let n = this.device.createShaderModule({ code: e.shader });
67
+ this.pipeline = this.device.createRenderPipeline({
68
+ ...e.descriptor,
69
+ multisample: { count: 4 },
70
+ vertex: {
71
+ ...e.descriptor.vertex,
72
+ module: n
73
+ },
74
+ fragment: {
75
+ module: n,
76
+ entryPoint: "fragment",
77
+ targets: [{ format: t }]
78
+ },
79
+ depthStencil: {
80
+ format: "depth24plus",
81
+ depthWriteEnabled: !0,
82
+ depthCompare: "less-equal"
83
+ }
84
+ });
85
+ let r = this.device.createShaderModule({ code: "@group(0) @binding(0) var depth:texture_depth_multisampled_2d;\n@vertex fn vertex(@builtin(vertex_index) i:u32)->@builtin(position) vec4f{return vec4f(array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i],0,1);}\n@fragment fn fragment(@builtin(position) p:vec4f)->@builtin(frag_depth) f32{let q=vec2i(p.xy);return min(min(textureLoad(depth,q,0),textureLoad(depth,q,1)),min(textureLoad(depth,q,2),textureLoad(depth,q,3)));}" });
86
+ this.depthPipeline = this.device.createRenderPipeline({
87
+ layout: "auto",
88
+ vertex: {
89
+ module: r,
90
+ entryPoint: "vertex"
91
+ },
92
+ fragment: {
93
+ module: r,
94
+ entryPoint: "fragment",
95
+ targets: []
96
+ },
97
+ depthStencil: {
98
+ format: "depth24plus",
99
+ depthWriteEnabled: !0,
100
+ depthCompare: "always"
101
+ }
102
+ });
103
+ }
104
+ render(e, t, n, r, i, o, c) {
105
+ let l = this.device, u = this.pipeline, d = /* @__PURE__ */ new Set();
106
+ for (let t of e.meshes.values()) {
107
+ let e = p(t);
108
+ e?.kind === "pbr" && d.add(e.source.model);
109
+ }
110
+ for (let [e, t] of this.pbr) if (!d.has(e) || e.disposed) {
111
+ for (let e of t) e.dispose();
112
+ this.pbr.delete(e);
113
+ }
114
+ for (let e of d) !e.disposed && !this.pbr.has(e) && this.pbr.set(e, []);
115
+ let f = this.used;
116
+ f.clear();
117
+ for (let e of this.resources.values()) e.count = 0;
118
+ for (let t of e.meshes.values()) if (t.geometry && e.store.visible[t.id] && (c === void 0 || s(t) & c)) {
119
+ let n = t.geometry;
120
+ f.add(n);
121
+ let r = this.resources.get(n);
122
+ if (!r) {
123
+ let t = [], i = (e, n) => {
124
+ if (e.byteLength > l.limits.maxBufferSize) throw RangeError("XR buffer exceeds device limit; use a smaller geometry or split it");
125
+ let r = l.createBuffer({
126
+ size: e.byteLength,
127
+ usage: n | GPUBufferUsage.COPY_DST
128
+ });
129
+ return t.push(r), l.queue.writeBuffer(r, 0, e), r;
130
+ };
131
+ try {
132
+ let t = new Float32Array(e.store.capacity * 24);
133
+ r = {
134
+ vertex: i(n.vertices, GPUBufferUsage.VERTEX),
135
+ index: i(n.indices, GPUBufferUsage.INDEX),
136
+ instance: i(t, GPUBufferUsage.VERTEX),
137
+ data: t,
138
+ count: 0
139
+ }, this.resources.set(n, r);
140
+ } catch (e) {
141
+ for (let e of t) e.destroy();
142
+ throw e;
143
+ }
144
+ }
145
+ if (r.data.length < e.store.capacity * 24) {
146
+ let t = new Float32Array(e.store.capacity * 24);
147
+ if (t.byteLength > l.limits.maxBufferSize) throw RangeError("XR buffer exceeds device limit; lower the engine store capacity");
148
+ let n = l.createBuffer({
149
+ size: t.byteLength,
150
+ usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
151
+ });
152
+ r.instance.destroy(), r.instance = n, r.data = t;
153
+ }
154
+ let i = r.count++ * 24;
155
+ r.data.set(t.matrix, i), r.data.set(t.material.data, i + 16);
156
+ }
157
+ for (let [e, t] of this.resources) f.has(e) ? l.queue.writeBuffer(t.instance, 0, t.data, 0, t.count * 24) : (t.vertex.destroy(), t.index.destroy(), t.instance.destroy(), this.resources.delete(e));
158
+ let g = l.createCommandEncoder(), _ = [];
159
+ for (let s = 0; s < r.views.length; s++) {
160
+ let d = r.views[s], f = t.getViewSubImage(n, d), p = f.getViewDescriptor(), v = this.eyes[s];
161
+ if (!v) {
162
+ let e = l.createBuffer({
163
+ size: 128,
164
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
165
+ });
166
+ try {
167
+ v = {
168
+ uniform: e,
169
+ group: l.createBindGroup({
170
+ layout: u.getBindGroupLayout(0),
171
+ entries: [{
172
+ binding: 0,
173
+ resource: { buffer: e }
174
+ }]
175
+ }),
176
+ data: /* @__PURE__ */ new Float32Array(32)
177
+ }, this.eyes.push(v);
178
+ } catch (t) {
179
+ throw e.destroy(), t;
180
+ }
181
+ }
182
+ let y = t.projection?.(d) ?? d.projectionMatrix, b = d.transform.inverse.matrix, x = v.data;
183
+ for (let e = 0; e < 4; e++) for (let t = 0; t < 4; t++) x[e * 4 + t] = y[t] * b[e * 4] + y[4 + t] * b[e * 4 + 1] + y[8 + t] * b[e * 4 + 2] + y[12 + t] * b[e * 4 + 3];
184
+ let S = d.transform.position;
185
+ if (x[16] = S.x, x[17] = S.y, x[18] = S.z, x[19] = 1, m(x, 20, e.lighting.direction), x.set(e.lighting.radiance, 24), x.fill(1, 28, 31), e.lighting.ambient && x.set(e.lighting.ambient, 28), l.queue.writeBuffer(v.uniform, 0, x), !f.depthStencilTexture && !t.present) throw new a("unsupported", "XR projection layer has no depth texture; use a runtime that provides a depth buffer for the layer");
186
+ if (v.color?.width !== f.colorTexture.width || v.color?.height !== f.colorTexture.height || v.color?.format !== f.colorTexture.format) {
187
+ v.color?.destroy(), v.depth?.destroy(), v.color = void 0, v.depth = void 0, v.colorView = v.depthView = v.depthGroup = void 0;
188
+ try {
189
+ v.color = l.createTexture({
190
+ size: [f.colorTexture.width, f.colorTexture.height],
191
+ format: f.colorTexture.format,
192
+ sampleCount: 4,
193
+ usage: GPUTextureUsage.RENDER_ATTACHMENT
194
+ }), v.depth = l.createTexture({
195
+ size: [f.colorTexture.width, f.colorTexture.height],
196
+ format: "depth24plus",
197
+ sampleCount: 4,
198
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
199
+ }), v.colorView = v.color.createView(), v.depthView = v.depth.createView(), v.depthGroup = l.createBindGroup({
200
+ layout: this.depthPipeline.getBindGroupLayout(0),
201
+ entries: [{
202
+ binding: 0,
203
+ resource: v.depthView
204
+ }]
205
+ });
206
+ } catch (e) {
207
+ throw v.color?.destroy(), v.depth?.destroy(), v.color = v.depth = void 0, v.colorView = v.depthView = v.depthGroup = void 0, e;
208
+ }
209
+ }
210
+ let C = Object.assign(Object.create(e.camera), {
211
+ matrix: x.subarray(0, 16),
212
+ position: [
213
+ S.x,
214
+ S.y,
215
+ S.z
216
+ ]
217
+ });
218
+ if (c !== void 0) {
219
+ let e = f.viewport;
220
+ v.view = {
221
+ id: `xr-${s}`,
222
+ camera: C,
223
+ viewport: [
224
+ e.x,
225
+ e.y,
226
+ e.width,
227
+ e.height
228
+ ],
229
+ index: s,
230
+ count: r.views.length,
231
+ layers: c
232
+ };
233
+ }
234
+ let w = {
235
+ ...this.context,
236
+ ...c === void 0 ? {} : { view: v.view },
237
+ backend: "webgpu",
238
+ device: l,
239
+ encoder: g,
240
+ width: f.colorTexture.width,
241
+ height: f.colorTexture.height,
242
+ format: f.colorTexture.format,
243
+ color: v.colorView,
244
+ depth: v.depthView,
245
+ camera: C,
246
+ descriptor: {
247
+ ...this.context.descriptor,
248
+ multisample: { count: 4 },
249
+ depthStencil: {
250
+ format: "depth24plus",
251
+ depthWriteEnabled: !0,
252
+ depthCompare: "less-equal"
253
+ }
254
+ }
255
+ };
256
+ for (let [e, t] of this.pbr) {
257
+ let n = t[s];
258
+ n || (n = e.createRenderer(l), t[s] = n), n.prepare(w);
259
+ }
260
+ let T = !h(f.colorTexture.format) && this.glass(), E = f.colorTexture.createView(p), D = f.viewport, O = (e) => {
261
+ let t = g.beginRenderPass({
262
+ colorAttachments: [{
263
+ view: v.colorView,
264
+ resolveTarget: E,
265
+ loadOp: e ? "clear" : "load",
266
+ storeOp: T ? "store" : "discard",
267
+ clearValue: {
268
+ r: 0,
269
+ g: 0,
270
+ b: 0,
271
+ a: +!i
272
+ }
273
+ }],
274
+ depthStencilAttachment: {
275
+ view: v.depthView,
276
+ depthLoadOp: e ? "clear" : "load",
277
+ depthStoreOp: "store",
278
+ depthClearValue: 1
279
+ }
280
+ });
281
+ return t.setViewport(D.x, D.y, D.width, D.height, 0, 1), t;
282
+ }, k = O(!0);
283
+ k.setPipeline(u), k.setBindGroup(0, v.group);
284
+ for (let [e, t] of this.resources) t.count && (k.setVertexBuffer(0, t.vertex), k.setVertexBuffer(1, t.instance), k.setIndexBuffer(t.index, "uint32"), k.drawIndexed(e.indices.length, t.count));
285
+ let A = T ? { snapshot(e, t) {
286
+ return e.end(), g.beginRenderPass({ colorAttachments: [{
287
+ view: v.colorView,
288
+ resolveTarget: t.createView(),
289
+ loadOp: "load",
290
+ storeOp: "store"
291
+ }] }).end(), O(!1);
292
+ } } : void 0;
293
+ for (let e of this.pbr.values()) k = e[s].draw(w, k, d.transform.inverse.matrix, A) ?? k;
294
+ if (k.end(), !f.depthStencilTexture) continue;
295
+ let j = g.beginRenderPass({
296
+ colorAttachments: [],
297
+ depthStencilAttachment: {
298
+ view: f.depthStencilTexture.createView(p),
299
+ depthLoadOp: "clear",
300
+ depthStoreOp: "store",
301
+ depthClearValue: 1
302
+ }
303
+ });
304
+ j.setViewport(D.x, D.y, D.width, D.height, 0, 1), j.setPipeline(this.depthPipeline), j.setBindGroup(0, v.depthGroup), j.draw(3), j.end();
305
+ let M = () => g.beginRenderPass({
306
+ colorAttachments: [],
307
+ depthStencilAttachment: {
308
+ view: v.depthView,
309
+ depthLoadOp: "load",
310
+ depthStoreOp: "discard"
311
+ }
312
+ }).end();
313
+ o ? _.push(M) : M();
314
+ }
315
+ if (o) for (let [e, i] of r.views.entries()) {
316
+ let r = t.getViewSubImage(n, i);
317
+ if (o({
318
+ index: e,
319
+ device: l,
320
+ encoder: g,
321
+ image: r,
322
+ view: i,
323
+ scene: {
324
+ texture: this.eyes[e].depth,
325
+ projection: t.projection?.(i) ?? i.projectionMatrix,
326
+ origin: [r.viewport.x, r.viewport.y],
327
+ clear: 1
328
+ },
329
+ binding: t
330
+ }) === !1) return;
331
+ }
332
+ for (let e of _) e();
333
+ l.queue.submit([g.finish()]), t.present?.(n);
334
+ }
335
+ glass() {
336
+ for (let e of this.pbr.keys()) for (let t of e.primitives) if (g(t.material)) return !0;
337
+ return !1;
338
+ }
339
+ dispose() {
340
+ for (let e of this.pbr.values()) for (let t of e) t.dispose();
341
+ this.pbr.clear(), this.context = void 0;
342
+ for (let e of this.resources.values()) e.vertex.destroy(), e.index.destroy(), e.instance.destroy();
343
+ this.resources.clear();
344
+ for (let e of this.eyes) e.uniform.destroy(), e.color?.destroy(), e.depth?.destroy();
345
+ this.eyes.length = 0, this.pipeline = this.depthPipeline = void 0;
346
+ }
347
+ };
348
+ //#endregion
349
+ //#region src/eyes.ts
350
+ function v(e, t) {
351
+ let n = e > 1 ? "texture_depth_multisampled_2d" : "texture_depth_2d", r = "0.0";
352
+ for (let t = 0; t < e; t++) r += ` + select(0.0, 1.0, textureLoad(d, q, ${t}) > 0.0)`;
353
+ let i = "textureLoad(d, q, 0)";
354
+ for (let t = 1; t < e; t++) i = `max(${i}, textureLoad(d, q, ${t}))`;
355
+ return `@group(0) @binding(0) var c: texture_2d<f32>;
356
+ @group(0) @binding(1) var d: ${n};
357
+ @group(0) @binding(2) var<uniform> o: vec4i;
358
+ @vertex fn vertex(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {
359
+ return vec4f(array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3))[i], 0, 1);
360
+ }
361
+ @fragment fn color(@builtin(position) p: vec4f) -> @location(0) vec4f {
362
+ let q = vec2i(p.xy) - o.xy;
363
+ let c = textureLoad(c, q, 0);
364
+ ${t ? `return vec4f(c.rgb, clamp(max((${r}) / ${e}.0, max(c.r, max(c.g, c.b))), 0.0, 1.0));` : "return vec4f(c.rgb, 1.0);"}
365
+ }
366
+ @fragment fn depth(@builtin(position) p: vec4f) -> @builtin(frag_depth) f32 {
367
+ let q = vec2i(p.xy) - o.xy;
368
+ return 1.0 - ${i};
369
+ }
370
+ `;
371
+ }
372
+ var y = class {
373
+ constructor(e, t) {
374
+ this.engine = e, this.device = t, this.eyes = [], this.views = [], this.offset = /* @__PURE__ */ new Int32Array(4), this.options = {
375
+ views: this.views,
376
+ delta: 0,
377
+ culling: !0
378
+ };
379
+ }
380
+ place(e, t, n) {
381
+ let r = t.transform.matrix, i = e.camera, a = e.projection;
382
+ i.position = [
383
+ r[12],
384
+ r[13],
385
+ r[14]
386
+ ], i.target = [
387
+ r[12] - r[8],
388
+ r[13] - r[9],
389
+ r[14] - r[10]
390
+ ], i.up = [
391
+ r[4],
392
+ r[5],
393
+ r[6]
394
+ ];
395
+ for (let e = 0; e < 16; e++) a[e] = n[e];
396
+ for (let e = 0; e < 16; e += 4) a[e + 2] = n[e + 3] - n[e + 2];
397
+ i.near = this.engine.camera.near, i.far = this.engine.camera.far, i.fov = 2 * Math.atan(1 / n[5]) * 180 / Math.PI;
398
+ }
399
+ eye(e) {
400
+ let t = this.eyes[e];
401
+ if (!t) {
402
+ let r = /* @__PURE__ */ new Float64Array(16), i = new n();
403
+ i.project = (e) => e.set(r), t = {
404
+ camera: i,
405
+ projection: r,
406
+ uniform: this.device.createBuffer({
407
+ size: 16,
408
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
409
+ }),
410
+ view: {
411
+ camera: i,
412
+ viewport: [
413
+ 0,
414
+ 0,
415
+ 1,
416
+ 1
417
+ ],
418
+ id: `xr-${e}`,
419
+ target: void 0
420
+ }
421
+ }, this.eyes[e] = t;
422
+ }
423
+ return t;
424
+ }
425
+ size(e, t, n) {
426
+ if (e.color?.width === t && e.color.height === n) return;
427
+ e.color?.destroy(), e.depth?.destroy(), e.color = e.depth = e.colorGroup = e.depthGroup = void 0;
428
+ let r = this.engine.renderTarget;
429
+ e.color = this.device.createTexture({
430
+ size: [t, n],
431
+ format: r.format,
432
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
433
+ label: "XR eye"
434
+ }), e.depth = this.device.createTexture({
435
+ size: [t, n],
436
+ format: r.depthFormat,
437
+ sampleCount: r.samples,
438
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
439
+ label: "XR eye depth"
440
+ }), e.view.target = {
441
+ color: e.color,
442
+ depth: e.depth
443
+ };
444
+ }
445
+ build(e, t, n) {
446
+ let r = `${e} ${t}`;
447
+ if (this.pipelines?.key === r && (!n || this.pipelines.depth)) return;
448
+ let i = this.engine.renderTarget.samples, a = this.device.createShaderModule({
449
+ code: v(i, t),
450
+ label: "XR eye blit"
451
+ }), o = this.device.createBindGroupLayout({ entries: [
452
+ {
453
+ binding: 0,
454
+ visibility: 2,
455
+ texture: { sampleType: "unfilterable-float" }
456
+ },
457
+ {
458
+ binding: 1,
459
+ visibility: 2,
460
+ texture: {
461
+ sampleType: "depth",
462
+ multisampled: i > 1
463
+ }
464
+ },
465
+ {
466
+ binding: 2,
467
+ visibility: 2,
468
+ buffer: {}
469
+ }
470
+ ] }), s = this.device.createPipelineLayout({ bindGroupLayouts: [o] }), c = {
471
+ module: a,
472
+ entryPoint: "vertex"
473
+ };
474
+ this.pipelines = {
475
+ key: r,
476
+ color: this.device.createRenderPipeline({
477
+ layout: s,
478
+ vertex: c,
479
+ fragment: {
480
+ module: a,
481
+ entryPoint: "color",
482
+ targets: [{ format: e }]
483
+ }
484
+ }),
485
+ depth: n ? this.device.createRenderPipeline({
486
+ layout: s,
487
+ vertex: c,
488
+ fragment: {
489
+ module: a,
490
+ entryPoint: "depth",
491
+ targets: []
492
+ },
493
+ depthStencil: {
494
+ format: "depth24plus",
495
+ depthWriteEnabled: !0,
496
+ depthCompare: "always"
497
+ }
498
+ }) : void 0
499
+ };
500
+ for (let e of this.eyes) e.colorGroup = e.depthGroup = void 0;
501
+ }
502
+ render(t, n, r, i, a, o, s) {
503
+ let c = this.views, l = [];
504
+ c.length = 0;
505
+ for (let e = 0; e < r.views.length; e++) {
506
+ let i = r.views[e], o = t.getViewSubImage(n, i), u = this.eye(e);
507
+ this.place(u, i, t.projection?.(i) ?? i.projectionMatrix), this.size(u, o.viewport.width, o.viewport.height), u.view.clear = a ? { color: "#000000" } : void 0, u.view.layers = s, c.push(u.view), l.push(o);
508
+ }
509
+ this.options.delta = i, this.engine.render(this.options);
510
+ let u = this.device.createCommandEncoder({ label: "XR eyes" });
511
+ for (let t = 0; t < l.length; t++) {
512
+ let n = l[t], r = this.eyes[t], { x: i, y: o, width: s, height: c } = n.viewport, d = n.getViewDescriptor(), f = n.depthStencilTexture;
513
+ if (f && f.format !== "depth24plus") throw e("unsupported", `The XR layer's depth is ${f.format}; create the layer with depth24plus`);
514
+ this.build(n.colorTexture.format, a, !!f);
515
+ let p = this.pipelines;
516
+ this.offset[0] = i, this.offset[1] = o, this.device.queue.writeBuffer(r.uniform, 0, this.offset), r.colorGroup ??= this.device.createBindGroup({
517
+ layout: p.color.getBindGroupLayout(0),
518
+ entries: [
519
+ {
520
+ binding: 0,
521
+ resource: r.color.createView()
522
+ },
523
+ {
524
+ binding: 1,
525
+ resource: r.depth.createView({ aspect: "depth-only" })
526
+ },
527
+ {
528
+ binding: 2,
529
+ resource: { buffer: r.uniform }
530
+ }
531
+ ]
532
+ });
533
+ let m = u.beginRenderPass({ colorAttachments: [{
534
+ view: n.colorTexture.createView(d),
535
+ loadOp: "load",
536
+ storeOp: "store"
537
+ }] });
538
+ if (m.setViewport(i, o, s, c, 0, 1), m.setPipeline(p.color), m.setBindGroup(0, r.colorGroup), m.draw(3), m.end(), !f || !p.depth) continue;
539
+ let h = u.beginRenderPass({
540
+ colorAttachments: [],
541
+ depthStencilAttachment: {
542
+ view: f.createView(d),
543
+ depthLoadOp: "load",
544
+ depthStoreOp: "store"
545
+ }
546
+ });
547
+ h.setViewport(i, o, s, c, 0, 1), h.setPipeline(p.depth), h.setBindGroup(0, r.colorGroup), h.draw(3), h.end();
548
+ }
549
+ if (o) {
550
+ for (let e = 0; e < l.length; e++) if (o({
551
+ index: e,
552
+ device: this.device,
553
+ encoder: u,
554
+ image: l[e],
555
+ view: r.views[e],
556
+ scene: {
557
+ texture: this.eyes[e].depth,
558
+ projection: this.eyes[e].projection,
559
+ origin: [0, 0],
560
+ clear: 0
561
+ },
562
+ binding: t
563
+ }) === !1) return;
564
+ }
565
+ this.device.queue.submit([u.finish()]), t.present?.(n);
566
+ }
567
+ dispose() {
568
+ for (let e of this.eyes) e.color?.destroy(), e.depth?.destroy(), e.uniform.destroy();
569
+ this.eyes.length = 0, this.views.length = 0, this.pipelines = void 0;
570
+ }
571
+ }, b = class {
572
+ constructor(e) {
573
+ if (this.source = e, this.targetRay = null, this.grip = null, this.targetRayMatrix = /* @__PURE__ */ new Float32Array(16), this.gripMatrix = /* @__PURE__ */ new Float32Array(16), this.buttons = /* @__PURE__ */ new Float32Array(96), this.axes = /* @__PURE__ */ new Float32Array(16), this.handMatrices = /* @__PURE__ */ new Float32Array(400), this.handTracked = /* @__PURE__ */ new Uint8Array(25), this.handRadii = /* @__PURE__ */ new Float32Array(25), this.buttonCount = 0, this.axisCount = 0, this.joints = e.hand ? Array.from(e.hand.values()) : [], this.joints.length > 25) throw RangeError("XR hand exceeds 25 joints; the controller buffers hold the 25 WebXR hand joints");
574
+ }
575
+ update(e, t) {
576
+ this.targetRay = e.getPose(this.source.targetRaySpace, t), this.grip = this.source.gripSpace ? e.getPose(this.source.gripSpace, t) : null, this.targetRayMatrix.fill(0), this.gripMatrix.fill(0), this.targetRay && this.targetRayMatrix.set(this.targetRay.transform.matrix), this.grip && this.gripMatrix.set(this.grip.transform.matrix);
577
+ let n = this.source.gamepad;
578
+ if (this.buttonCount = n?.buttons.length ?? 0, this.axisCount = n?.axes.length ?? 0, this.buttonCount > 32 || this.axisCount > 16) throw RangeError("XR gamepad exceeds controller buffer capacity; at most 32 buttons and 16 axes are supported");
579
+ if (this.buttons.fill(0), this.axes.fill(0), n) {
580
+ for (let e = 0; e < this.buttonCount; e++) {
581
+ let t = n.buttons[e];
582
+ this.buttons[e * 3] = t.value, this.buttons[e * 3 + 1] = +t.pressed, this.buttons[e * 3 + 2] = +t.touched;
583
+ }
584
+ this.axes.set(n.axes);
585
+ }
586
+ this.handMatrices.fill(0), this.handTracked.fill(0), this.handRadii.fill(0);
587
+ for (let n = 0; n < this.joints.length; n++) {
588
+ let r = e.getJointPose?.(this.joints[n], t);
589
+ r && (this.handMatrices.set(r.transform.matrix, n * 16), this.handTracked[n] = 1, this.handRadii[n] = r.radius ?? 0);
590
+ }
591
+ }
592
+ }, x = [
593
+ "point",
594
+ "plane",
595
+ "mesh"
596
+ ], S = class t {
597
+ constructor(e, t, n, r) {
598
+ this.host = e, this.session = t, this.source = n, this.transient = r, this.cancelled = !1, this.ended = () => this.cancel(), t.addEventListener("end", this.ended, { once: !0 });
599
+ }
600
+ static async create(n, r = {}) {
601
+ let i = n?.session;
602
+ if (!i) throw e("state", "HitTest needs an active XR session; await xr.requestSession first");
603
+ if (i.enabledFeatures && !i.enabledFeatures.includes("hit-test")) throw e("unsupported", "The XR session has no 'hit-test' feature; request it in requiredFeatures or optionalFeatures");
604
+ if (!i.requestHitTestSource || !i.requestHitTestSourceForTransientInput) throw e("unsupported", "This browser has no WebXR hit testing; use an AR-capable browser and device");
605
+ let a = [...r.entityTypes ?? ["plane"]];
606
+ if (!a.length || a.some((e) => !x.includes(e))) throw TypeError("HitTest entityTypes must list 'point', 'plane' or 'mesh'");
607
+ let o = r.offsetRay === void 0 ? void 0 : w(r.offsetRay), s = r.from ?? "viewer";
608
+ if (s !== "viewer" && (typeof s != "object" || !s)) throw TypeError("HitTest from must be 'viewer', an XRInputSource or {profile}");
609
+ if (s !== "viewer" && "profile" in s) {
610
+ if (typeof s.profile != "string" || !s.profile) throw TypeError("HitTest profile must be a non-empty string such as 'generic-touchscreen'");
611
+ let e = await i.requestHitTestSourceForTransientInput({
612
+ profile: s.profile,
613
+ entityTypes: a,
614
+ ...o && { offsetRay: o }
615
+ });
616
+ return new t(n, i, void 0, e);
617
+ }
618
+ let c = s === "viewer" ? await i.requestReferenceSpace("viewer") : s.targetRaySpace;
619
+ if (!c) throw TypeError("HitTest input source has no targetRaySpace; pass an XRInputSource");
620
+ let l = await i.requestHitTestSource({
621
+ space: c,
622
+ entityTypes: a,
623
+ ...o && { offsetRay: o }
624
+ });
625
+ return new t(n, i, l, void 0);
626
+ }
627
+ get active() {
628
+ return !this.cancelled;
629
+ }
630
+ results(e) {
631
+ let t = this.host.referenceSpace;
632
+ if (this.cancelled || !t || e?.session !== this.session) return [];
633
+ let n = [];
634
+ if (this.source) for (let r of e.getHitTestResults?.(this.source) ?? []) {
635
+ let e = C(r, t);
636
+ e && n.push(e);
637
+ }
638
+ if (this.transient) for (let r of e.getHitTestResultsForTransientInput?.(this.transient) ?? []) for (let e of r.results) {
639
+ let i = C(e, t, r.inputSource);
640
+ i && n.push(i);
641
+ }
642
+ return n;
643
+ }
644
+ first(e) {
645
+ return this.results(e)[0] ?? null;
646
+ }
647
+ anchor(t) {
648
+ return t?.result?.createAnchor ? t.result.createAnchor() : Promise.reject(e("unsupported", "This hit cannot be anchored; request the 'anchors' feature on a supporting browser"));
649
+ }
650
+ cancel() {
651
+ this.cancelled || (this.cancelled = !0, this.session.removeEventListener("end", this.ended), this.source?.cancel(), this.transient?.cancel());
652
+ }
653
+ };
654
+ function C(e, t, n) {
655
+ let r = e.getPose(t);
656
+ if (!r) return null;
657
+ let { matrix: i, position: a, orientation: o } = r.transform;
658
+ return {
659
+ matrix: Float32Array.from(i),
660
+ position: [
661
+ a.x,
662
+ a.y,
663
+ a.z
664
+ ],
665
+ orientation: [
666
+ o.x,
667
+ o.y,
668
+ o.z,
669
+ o.w
670
+ ],
671
+ result: e,
672
+ ...n && { inputSource: n }
673
+ };
674
+ }
675
+ function w(t) {
676
+ let n = t.origin ?? [
677
+ 0,
678
+ 0,
679
+ 0
680
+ ], r = t.direction ?? [
681
+ 0,
682
+ 0,
683
+ -1
684
+ ];
685
+ if (![...n, ...r].every((e) => typeof e == "number" && Number.isFinite(e)) || n.length !== 3) throw TypeError("HitTest offsetRay needs finite [x, y, z] origin and direction");
686
+ if (r.length !== 3 || !Math.hypot(r[0], r[1], r[2])) throw RangeError("HitTest offsetRay direction must be non-zero; pass a direction such as [0, 0, -1]");
687
+ let i = globalThis.XRRay;
688
+ if (!i) throw e("unsupported", "This browser has no XRRay; omit offsetRay");
689
+ return new i({
690
+ x: n[0],
691
+ y: n[1],
692
+ z: n[2],
693
+ w: 1
694
+ }, {
695
+ x: r[0],
696
+ y: r[1],
697
+ z: r[2],
698
+ w: 0
699
+ });
700
+ }
701
+ //#endregion
702
+ //#region src/index.ts
703
+ var T = () => globalThis, E = () => globalThis.navigator?.xr, D = /* @__PURE__ */ new WeakSet();
704
+ async function O(e, t = {}) {
705
+ let n = globalThis.navigator?.gpu;
706
+ if (!n) throw new a("unsupported", "createXREngine needs WebGPU; use a browser with WebGPU and WebXR");
707
+ let o = Object.getOwnPropertyDescriptor(n, "requestAdapter"), s = n.requestAdapter;
708
+ Object.defineProperty(n, "requestAdapter", {
709
+ configurable: !0,
710
+ writable: !0,
711
+ value: (e) => s.call(n, {
712
+ ...e,
713
+ xrCompatible: !0
714
+ })
715
+ });
716
+ let c;
717
+ try {
718
+ c = await i.create(e, {
719
+ ...t,
720
+ backend: "webgpu"
721
+ });
722
+ } finally {
723
+ o ? Object.defineProperty(n, "requestAdapter", o) : delete n.requestAdapter;
724
+ }
725
+ let l = r(c).gpu;
726
+ return l && D.add(l), c;
727
+ }
728
+ var k = /* @__PURE__ */ new WeakMap();
729
+ function A(e) {
730
+ let t = k.get(e);
731
+ if (!t) {
732
+ let n = t = /* @__PURE__ */ new Set();
733
+ k.set(e, n), e.lost.then((e) => {
734
+ for (let t of [...n]) t.lostDevice(e);
735
+ });
736
+ }
737
+ return t;
738
+ }
739
+ var j = class e {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
740
+ get layers() {
741
+ return this.mask;
742
+ }
743
+ set layers(e) {
744
+ this.mask = e === void 0 ? void 0 : c(e, "XR layers");
745
+ }
746
+ static async isSupported(e = "immersive-vr") {
747
+ return !E() || e !== "inline" && (!T().XRGPUBinding || !globalThis.navigator?.gpu) ? !1 : E().isSessionSupported(e);
748
+ }
749
+ static attach(t, n = {}) {__margoAssertCore(t,__margoCoreRequirement("0.1.0",import.meta.url));
750
+ return e.create(t, n);
751
+ }
752
+ static async create(n, i = {}) {
753
+ let { signal: o } = i;
754
+ o?.throwIfAborted(), i.layers !== void 0 && c(i.layers, "XR layers");
755
+ let s = r(n);
756
+ if (s.backend !== "webgpu") throw new a("unsupported", "XR requires WebGPU or the full WebGL2 compatibility layer; use autoEngine with loadCompat; see https://margoengine.com/errors#webgpu");
757
+ if (s.disposed || s.hasPlugin("xr")) throw new a("state", "XR requires a live WebGPU engine without an XR plugin; create the engine with backend 'webgpu' and call XR.create once.");
758
+ if (!E()) throw new a("unsupported", "WebXR is unavailable; use a WebXR browser over HTTPS or localhost.");
759
+ if (s.gpu && D.has(s.gpu)) {
760
+ let t = new e(s.gpu, !0);
761
+ return t.layers = i.layers, s.use(t), t;
762
+ }
763
+ let l = t(s), u = await navigator.gpu.requestAdapter({ xrCompatible: !!T().XRGPUBinding });
764
+ if (!u) throw new a("unsupported", "XR-compatible WebGPU adapter unavailable; use a headset browser with WebGPU XR support.; see https://margoengine.com/errors#webgpu");
765
+ if (u.info?.vendor === "margo-webgl2" && !T().XRGPUBinding?.webgl) throw new a("unsupported", "XR needs the browser's own WebGPU (XRGPUBinding) or, on the WebGL2 compatibility layer, its route: call installXR() from the layer's xr entry first; see https://margoengine.com/errors#webgpu");
766
+ o?.throwIfAborted();
767
+ let d = s.gpu ? [...s.gpu.features].filter((e) => u.features?.has(e)) : [], f = await u.requestDevice({ requiredFeatures: d }), p = new e(f);
768
+ p.layers = i.layers;
769
+ try {
770
+ return o?.throwIfAborted(), l.run(() => s.use(p)), p;
771
+ } catch (e) {
772
+ throw p.dispose(), e;
773
+ }
774
+ }
775
+ constructor(e, t = !1) {
776
+ this.device = e, this.name = "xr", this.session = null, this.handle = null, this.pending = !1, this.disposed = !1, this.lost = !1, this.last = null, this.mode = "immersive-vr", this.listeners = /* @__PURE__ */ new Set(), this.controllers = [], this.state = {
777
+ time: 0,
778
+ delta: 0,
779
+ frame: null,
780
+ viewer: null,
781
+ inputs: this.controllers
782
+ }, this.renderOptions = {
783
+ culling: !1,
784
+ delta: 0
785
+ }, this.insideFrame = !1, this.resume = !1, this.seeThrough = !1, this.eyeListeners = /* @__PURE__ */ new Set(), this.drawEye = (e) => {
786
+ for (let t of this.eyeListeners) if (t(e), this.disposed) return !1;
787
+ return !this.disposed;
788
+ }, this.uncaptured = (e) => {
789
+ this.disposed || this.fail(new a("failed", `XR GPU error: ${e.error.message}`));
790
+ }, this.frame = (e, t) => {
791
+ if (this.handle = null, !(this.disposed || t.session !== this.session)) try {
792
+ this.insideFrame = !0;
793
+ let n = this.last === null ? 0 : Math.max(0, Math.min((e - this.last) / 1e3, .1));
794
+ this.last = e;
795
+ let r = t.getViewerPose(this.space);
796
+ for (let e = 0; e < this.controllers.length; e++) this.controllers[e].update(t, this.space);
797
+ this.state.time = e, this.state.delta = n, this.state.frame = t, this.state.viewer = r;
798
+ for (let e of this.listeners) e(this.state);
799
+ let i = this.callback?.(this.state) !== !1;
800
+ if (this.disposed || t.session !== this.session) return;
801
+ i && this.renderFrame(), this.session === t.session && !this.disposed && (this.handle = t.session.requestAnimationFrame(this.frame));
802
+ } catch (e) {
803
+ this.fail(e);
804
+ } finally {
805
+ this.insideFrame = !1;
806
+ }
807
+ }, this.sourcesChanged = () => {
808
+ let e = this.session?.inputSources ?? [];
809
+ for (let t = this.controllers.length - 1; t >= 0; t--) Array.prototype.includes.call(e, this.controllers[t].source) || this.controllers.splice(t, 1);
810
+ for (let t of e) this.controllers.some((e) => e.source === t) || this.controllers.push(new b(t));
811
+ }, this.ended = () => {
812
+ let e = this.session;
813
+ e && this.handle !== null && e.cancelAnimationFrame(this.handle), e?.removeEventListener("end", this.ended), e?.removeEventListener("inputsourceschange", this.sourcesChanged), this.controllers.length = 0, this.session = null, this.handle = null, this.last = null, this.callback = void 0, this.space = void 0, this.binding = void 0, this.seeThrough = !1, this.layer?.destroy(), this.layer = void 0, this.renderer?.dispose(), this.eyes?.dispose(), this.resume && (this.resume = !1, !this.disposed && !this.engine.disposed && this.engine.start());
814
+ }, this.route = t ? "engine" : "separate", t || (this.renderer = new _(e)), A(e).add(this), t || e.addEventListener("uncapturederror", this.uncaptured);
815
+ }
816
+ lostDevice(e) {
817
+ this.disposed || (this.lost = !0, this.fail(new a("failed", `XR GPU device lost: ${e.message}; create a new XR with XR.create.`)));
818
+ }
819
+ setup(e) {
820
+ this.engine = e, this.route === "engine" && (this.eyes = new y(e, this.device));
821
+ }
822
+ onFrame(e) {
823
+ if (typeof e != "function") throw TypeError("xr.onFrame needs a function; pass (state) => {...}");
824
+ return this.listeners.add(e), () => void this.listeners.delete(e);
825
+ }
826
+ onEye(e) {
827
+ if (typeof e != "function") throw TypeError("xr.onEye needs a function; pass (target) => {...}");
828
+ if (this.disposed) throw new a("disposed", "XR is disposed; create a new XR before adding an eye effect");
829
+ return this.eyeListeners.add(e), () => void this.eyeListeners.delete(e);
830
+ }
831
+ get referenceSpace() {
832
+ return this.space;
833
+ }
834
+ useReferenceSpace(e) {
835
+ if (!this.session || !this.space) throw new a("state", "useReferenceSpace needs an active session; call it after xr.requestSession resolves");
836
+ if (!e || typeof e != "object") throw TypeError("useReferenceSpace needs an XRReferenceSpace; pass xr.referenceSpace.getOffsetReferenceSpace(transform)");
837
+ this.space = e;
838
+ }
839
+ get projectionLayer() {
840
+ return this.layer;
841
+ }
842
+ get layerBinding() {
843
+ return this.session && this.binding && this.layer ? {
844
+ binding: this.binding,
845
+ device: this.device
846
+ } : void 0;
847
+ }
848
+ setLayers(e, t) {
849
+ if (!this.session || !this.layer) throw new a("state", "setLayers needs an immersive session; call it after xr.requestSession resolves");
850
+ if (this.layer.baseLayer) throw new a("unsupported", "Composition layers need the browser's own XRGPUBinding; the WebGL2 layer's route shows a single XRWebGLLayer");
851
+ this.seeThrough = e.length > 0, this.session.updateRenderState({ layers: [
852
+ ...e,
853
+ this.layer,
854
+ ...t
855
+ ] });
856
+ }
857
+ registerPasses(e) {
858
+ e.add({
859
+ name: "xr-scene-descriptor",
860
+ order: -1e6,
861
+ execute: (e) => {
862
+ e.backend === "webgpu" && (this.context = e);
863
+ }
864
+ });
865
+ }
866
+ async requestSession(e = "immersive-vr", t = {}) {
867
+ if (this.disposed || this.lost) throw new a("disposed", "XR is disposed or its device was lost; create a new XR with XR.create.");
868
+ if (this.session || this.pending) throw new a("state", "An XR session is already active or pending; await xr.end() before requesting another.");
869
+ if (![
870
+ "inline",
871
+ "immersive-vr",
872
+ "immersive-ar"
873
+ ].includes(e)) throw TypeError("Unknown XR mode; use 'inline', 'immersive-vr' or 'immersive-ar'");
874
+ if (e !== "inline" && !T().XRGPUBinding) throw new a("unsupported", "Native WebGPU XR bindings are unavailable; desktop rendering remains active. Use a browser with XRGPUBinding or request an inline session.");
875
+ t.signal?.throwIfAborted();
876
+ let n = t.referenceSpace ?? (e === "inline" ? "viewer" : "local");
877
+ if (![
878
+ "viewer",
879
+ "local",
880
+ "local-floor",
881
+ "bounded-floor",
882
+ "unbounded"
883
+ ].includes(n)) throw TypeError("Unknown XR reference space; use 'viewer', 'local', 'local-floor', 'bounded-floor' or 'unbounded'");
884
+ if (t.framebufferScale !== void 0 && (!Number.isFinite(Math.fround(t.framebufferScale)) || Math.fround(t.framebufferScale) <= 0)) throw RangeError("framebufferScale must be finite and positive; pass 1 for the runtime recommendation");
885
+ this.pending = !0;
886
+ let r;
887
+ try {
888
+ if (e === "inline" && [...t.requiredFeatures ?? [], ...t.optionalFeatures ?? []].includes("webgpu")) throw TypeError("WebGPU XR bindings do not support inline sessions; remove 'webgpu' from the features or request an immersive mode");
889
+ if (r = await E().requestSession(e, {
890
+ ...t.init,
891
+ requiredFeatures: [.../* @__PURE__ */ new Set([
892
+ ...e === "inline" || T().XRGPUBinding?.webgl ? [] : ["webgpu"],
893
+ ...n === "viewer" ? [] : [n],
894
+ ...t.requiredFeatures ?? []
895
+ ])],
896
+ optionalFeatures: t.optionalFeatures ?? []
897
+ }), this.disposed || this.lost) throw new a("disposed", "XR was disposed during session negotiation; keep the XR alive until requestSession settles.");
898
+ if (t.signal?.throwIfAborted(), this.session = r, r.addEventListener("end", this.ended, { once: !0 }), this.mode = e, this.callback = t.onFrame, r.addEventListener("inputsourceschange", this.sourcesChanged), this.sourcesChanged(), e === "inline") {
899
+ if (this.space = await r.requestReferenceSpace(n), this.disposed || this.session !== r) throw new a("state", "XR session ended during initialization; request a new session.");
900
+ return t.signal?.throwIfAborted(), this.last = null, this.handle = r.requestAnimationFrame(this.frame), r;
901
+ }
902
+ this.binding = new (T()).XRGPUBinding(r, this.device);
903
+ let i = this.binding.getPreferredColorFormat();
904
+ if (this.layer = this.binding.createProjectionLayer({
905
+ colorFormat: i,
906
+ depthStencilFormat: "depth24plus",
907
+ ...t.framebufferScale === void 0 ? {} : { scaleFactor: t.framebufferScale }
908
+ }), r.updateRenderState({
909
+ ...this.layer.baseLayer ? { baseLayer: this.layer.baseLayer } : { layers: [this.layer] },
910
+ depthNear: this.engine.camera.near,
911
+ depthFar: this.engine.camera.far
912
+ }), this.space = await r.requestReferenceSpace(n), this.disposed || this.session !== r) throw new a("state", "XR session ended during initialization; request a new session.");
913
+ if (t.signal?.throwIfAborted(), this.eyes) return this.engine.stop(), this.resume = !0, this.last = null, this.handle = r.requestAnimationFrame(this.frame), r;
914
+ if (this.engine.render({ culling: !1 }), !this.context) throw new a("state", "WebGPU scene descriptor unavailable; add the XR plugin before the first frame renders.");
915
+ return this.renderer.configure(this.context, i), this.engine.stop(), this.resume = !0, this.last = null, this.handle = r.requestAnimationFrame(this.frame), r;
916
+ } catch (e) {
917
+ if (r) try {
918
+ await r.end();
919
+ } catch {} finally {
920
+ this.session === r && this.ended();
921
+ }
922
+ throw e;
923
+ } finally {
924
+ this.pending = !1;
925
+ }
926
+ }
927
+ renderFrame() {
928
+ if (!this.insideFrame || this.disposed || !this.session) throw new a("state", "renderFrame requires an active XR frame; call it inside the session onFrame callback.");
929
+ let { viewer: e, delta: t } = this.state;
930
+ this.mode !== "inline" && this.eyes ? e && this.eyes.render(this.binding, this.layer, e, t, this.mode === "immersive-ar" || this.seeThrough, this.eyeListeners.size ? this.drawEye : void 0, this.mask) : this.mode !== "inline" && (this.renderOptions.delta = t, this.engine.render(this.renderOptions), e && this.renderer.render(this.engine, this.binding, this.layer, e, this.mode === "immersive-ar" || this.seeThrough, this.eyeListeners.size ? this.drawEye : void 0, this.mask));
931
+ }
932
+ fail(e) {
933
+ this.end().catch((e) => this.engine.onError(e)), this.engine.onError(e);
934
+ }
935
+ async end() {
936
+ let e = this.session;
937
+ if (e) try {
938
+ await e.end();
939
+ } finally {
940
+ this.session === e && this.ended();
941
+ }
942
+ }
943
+ dispose() {
944
+ if (this.disposed) return;
945
+ this.disposed = !0, this.eyeListeners.clear();
946
+ let e = this.session;
947
+ this.ended(), this.device.removeEventListener("uncapturederror", this.uncaptured), k.get(this.device)?.delete(this), this.route === "separate" && this.device.destroy(), e && e.end().catch((e) => this.engine.onError(e)), this.engine?.sceneOf(this)?.removePlugin(this.name);
948
+ }
949
+ [Symbol.dispose ?? Symbol()]() {
950
+ this.dispose();
951
+ }
952
+ };
953
+ function M(e, t = "immersive-vr", n = {}) {
954
+ return e.requestSession(t, n);
955
+ }
956
+ //#endregion
957
+ export { S as HitTest, j as XR, j as XRManager, b as XRController, O as createXREngine, M as useXRSession };