@margoengine/cameras 0.0.0-stage → 1.0.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.
package/dist/stereo.js ADDED
@@ -0,0 +1,181 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const a=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { n as e } from "./layers-CkdgcqTK.js";
5
+ import { n as t, r as n, t as r } from "./gpu-BRxrrZK3.js";
6
+ import { Camera as i, engineRuntime as __margoRuntime } from "@margoengine/core/extension";
7
+ import { MargoError as o } from "@margoengine/math/errors";
8
+ //#region src/stereo.ts
9
+ var s = class {
10
+ constructor(e = {}) {
11
+ this.left = new i(), this.right = new i(), this.options = { ...e };
12
+ }
13
+ update(e, t = 1) {
14
+ let n = () => typeof t == "function" ? t() : t;
15
+ e.update(n(), !0);
16
+ let r = e.position, i = e.target, a = e.up, o = [
17
+ r[0] - i[0],
18
+ r[1] - i[1],
19
+ r[2] - i[2]
20
+ ], s = Math.hypot(...o), c = [
21
+ a[1] * o[2] - a[2] * o[1],
22
+ a[2] * o[0] - a[0] * o[2],
23
+ a[0] * o[1] - a[1] * o[0]
24
+ ], l = Math.hypot(...c), u = this.options.eyeSeparation ?? .064, d = this.options.focusDistance ?? s;
25
+ if (!Number.isFinite(u) || u < 0 || !(d > 0)) throw RangeError("Invalid stereo geometry; pass finite eyeSeparation >= 0 and focusDistance > 0 or Infinity");
26
+ for (let [t, o] of [[this.left, -1], [this.right, 1]]) {
27
+ let s = o * u / 2, f = c.map((e) => e / l * s);
28
+ t.position = r.map((e, t) => e + f[t]), t.target = i.map((e, t) => e + f[t]), t.up = a, t.fov = e.fov, t.near = e.near, t.far = e.far, t.project = (t, r, i) => {
29
+ let a = n();
30
+ if (!Number.isFinite(a) || a <= 0) throw RangeError("Invalid stereo aspect; pass a finite aspect > 0");
31
+ if (e.project) e.project(t, a, i);
32
+ else {
33
+ let n = 1 / Math.tan(e.fov * Math.PI / 360), r = e.near, o = e.far, s = r - o;
34
+ t[0] = n / a, t[5] = n, t[10] = i ? -r / s : (o + r) / s, t[11] = -1, t[14] = i ? -o * r / s : 2 * o * r / s;
35
+ }
36
+ t[11] === 0 ? t[12] += t[0] * s : t[8] -= t[0] * s / d;
37
+ };
38
+ }
39
+ }
40
+ }, c = [
41
+ "side-by-side",
42
+ "top-bottom",
43
+ "anaglyph",
44
+ "parallax-barrier"
45
+ ], l = `${r}
46
+ @group(0) @binding(0) var leftEye:texture_2d<f32>;
47
+ @group(0) @binding(1) var rightEye:texture_2d<f32>;
48
+ @group(0) @binding(2) var linearSampler:sampler;
49
+ @group(0) @binding(3) var<uniform> settings:array<vec4f,2>;
50
+ fn linear(c:vec3f)->vec3f{return select(pow((c+0.055)/1.055,vec3f(2.4)),c/12.92,c<=vec3f(0.04045));}
51
+ fn srgb(c:vec3f)->vec3f {let x=clamp(c,vec3f(0),vec3f(1));return select(1.055*pow(x,vec3f(1.0/2.4))-0.055,12.92*x,x<=vec3f(0.0031308));}
52
+ @fragment fn fragment(i:Vertex)->@location(0) vec4f {
53
+ let mode=settings[0].z; var uv=i.uv;var eye=0.0;
54
+ if(mode<0.5){eye=select(0.0,1.0,uv.x>=0.5);uv.x=fract(uv.x*2.0);}
55
+ else if(mode<1.5){eye=select(0.0,1.0,uv.y>=0.5);uv.y=fract(uv.y*2.0);}
56
+ else if(mode>2.5){let stripe=select(i.position.x,i.position.y,settings[1].x>0.5);eye=f32((u32(stripe)+u32(settings[1].y))%2u);}
57
+ var l=textureSampleLevel(leftEye,linearSampler,uv,0.0);var r=textureSampleLevel(rightEye,linearSampler,uv,0.0);
58
+ if(settings[0].w>0.5){let hold=l;l=r;r=hold;}
59
+ if(mode>1.5&&mode<2.5){
60
+ let a=linear(l.rgb);let b=linear(r.rgb);
61
+ let lc=vec3f(dot(a,vec3f(0.437,0.449,0.164)),dot(a,vec3f(-0.062,-0.062,-0.024)),dot(a,vec3f(-0.048,-0.050,-0.017)));
62
+ let rc=vec3f(dot(b,vec3f(-0.011,-0.032,-0.007)),dot(b,vec3f(0.377,0.761,0.009)),dot(b,vec3f(-0.026,-0.093,1.234)));
63
+ return vec4f(srgb(clamp(lc,vec3f(0),vec3f(1))+clamp(rc,vec3f(0),vec3f(1))),max(l.a,r.a));
64
+ }
65
+ return select(l,r,eye>0.5);
66
+ }`, u = class r {
67
+ static attach(e, t = {}) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
68
+ return new r(e, t);
69
+ }
70
+ constructor(e, t = {}) {
71
+ this.engine = e, this.disposed = !1, this.options = { ...t }, this.rig = new s(this.options);
72
+ }
73
+ render(t = 0) {
74
+ if (this.disposed) throw new o("disposed", "Stereo output is disposed; create another StereoOutput");
75
+ if (!Number.isFinite(t) || t < 0) throw RangeError("Invalid stereo delta; pass finite seconds >= 0");
76
+ let n = this.engine, r = a(n), i = r.gpu, { mode: s = "side-by-side", swapEyes: l = !1, barrierAxis: u = "columns", barrierPhase: d = 0 } = this.options, f = c.indexOf(s);
77
+ if (f < 0 || !["columns", "rows"].includes(u) || ![0, 1].includes(d) || typeof l != "boolean") throw TypeError("Invalid stereo packing; use a supported mode, columns or rows, parity 0 or 1 and boolean swapEyes");
78
+ if (n.backend !== "webgpu" || !i) throw new o("unsupported", "Stereo output needs WebGPU or the WebGL2 compatibility layer");
79
+ let p = n.canvas, m = Math.max(1, Math.ceil(p.width / (f === 0 ? 2 : 1))), h = Math.max(1, Math.ceil(p.height / (f === 1 ? 2 : 1))), g = r.renderTarget.format, _ = this.ensure(i, m, h, g), v = this.options.camera ?? n.camera;
80
+ v.advance(t), Object.assign(this.rig.options, {
81
+ eyeSeparation: this.options.eyeSeparation,
82
+ focusDistance: this.options.focusDistance
83
+ }), this.rig.update(v, () => p.width / p.height * (f === 0 ? .5 : f === 1 ? 2 : 1));
84
+ let y = this.options.scene, b = this.options.layers ?? e(v);
85
+ n.render({
86
+ delta: t,
87
+ views: [{
88
+ id: "stereo:left",
89
+ camera: this.rig.left,
90
+ viewport: [
91
+ 0,
92
+ 0,
93
+ 1,
94
+ 1
95
+ ],
96
+ target: { color: _.left },
97
+ scene: y,
98
+ layers: b
99
+ }, {
100
+ id: "stereo:right",
101
+ camera: this.rig.right,
102
+ viewport: [
103
+ 0,
104
+ 0,
105
+ 1,
106
+ 1
107
+ ],
108
+ target: { color: _.right },
109
+ scene: y,
110
+ layers: b
111
+ }]
112
+ });
113
+ let x = p.getContext("webgpu");
114
+ if (!x) throw new o("state", "Stereo output needs the engine canvas context; create a WebGPU engine first");
115
+ i.queue.writeBuffer(_.uniform, 0, new Float32Array([
116
+ p.width,
117
+ p.height,
118
+ f,
119
+ +!!l,
120
+ +(u === "rows"),
121
+ d,
122
+ 0,
123
+ 0
124
+ ]));
125
+ let S = i.createCommandEncoder(), C = S.beginRenderPass({ colorAttachments: [{
126
+ view: x.getCurrentTexture().createView(),
127
+ loadOp: "clear",
128
+ storeOp: "store"
129
+ }] });
130
+ C.setPipeline(_.pipeline), C.setBindGroup(0, _.bindings), C.draw(3), C.end(), i.queue.submit([S.finish()]);
131
+ }
132
+ ensure(e, r, i, a) {
133
+ if (this.state?.device === e && this.state.width === r && this.state.height === i && this.state.format === a) return this.state;
134
+ this.release();
135
+ let o = [], s;
136
+ try {
137
+ for (let t = 0; t < 2; t++) o.push(e.createTexture({
138
+ size: [r, i],
139
+ format: "rgba8unorm",
140
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
141
+ }));
142
+ s = e.createBuffer({
143
+ size: 32,
144
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
145
+ });
146
+ let c = n(e, l, a), [u, d] = o, f = t(e, c, [
147
+ u.createView(),
148
+ d.createView(),
149
+ e.createSampler({
150
+ magFilter: "linear",
151
+ minFilter: "linear"
152
+ }),
153
+ { buffer: s }
154
+ ]);
155
+ return this.state = {
156
+ device: e,
157
+ width: r,
158
+ height: i,
159
+ format: a,
160
+ left: u,
161
+ right: d,
162
+ uniform: s,
163
+ pipeline: c,
164
+ bindings: f
165
+ };
166
+ } catch (e) {
167
+ throw o.forEach((e) => e.destroy()), s?.destroy(), e;
168
+ }
169
+ }
170
+ release() {
171
+ this.state?.left.destroy(), this.state?.right.destroy(), this.state?.uniform.destroy(), this.state = void 0;
172
+ }
173
+ dispose() {
174
+ this.disposed = !0, this.release();
175
+ }
176
+ [Symbol.dispose ?? Symbol()]() {
177
+ this.dispose();
178
+ }
179
+ };
180
+ //#endregion
181
+ export { u as StereoOutput, s as StereoRig };
@@ -0,0 +1,38 @@
1
+ //#region ../shared/view-rect.js
2
+ function e(e) {
3
+ return e?.view?.viewport;
4
+ }
5
+ function t(t, n) {
6
+ let r = e(n);
7
+ if (!r) return;
8
+ t.setViewport(r[0], r[1], r[2], r[3], 0, 1);
9
+ let i = n.view.scissor ?? r;
10
+ t.setScissorRect(i[0], i[1], i[2], i[3]);
11
+ }
12
+ function n(e, t = "clear") {
13
+ return e?.view?.index ? "load" : t;
14
+ }
15
+ function r() {
16
+ return globalThis[Symbol.for("margoengine.layers")];
17
+ }
18
+ function i(e) {
19
+ return r()?.maskOf(e) ?? 1;
20
+ }
21
+ function a(e, t) {
22
+ 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`);
23
+ return e >>> 0;
24
+ }
25
+ function o(e, t, n, a, o = e.meshes) {
26
+ let s = r(), c = [], l = (e) => o.get(e.id) === e, u = (t) => {
27
+ l(t) && !e.store.hidden[t.id] && (t.visible = !1, c.push(t));
28
+ };
29
+ if (t !== 4294967295 && (s?.used || s?.source || !(t & 1))) for (let e of o.values()) i(e) & t || u(e);
30
+ if (n) for (let e of n) u(e);
31
+ try {
32
+ return a();
33
+ } finally {
34
+ if (!e.disposed) for (let e of c) l(e) && (e.visible = !0);
35
+ }
36
+ }
37
+ //#endregion
38
+ export { o as i, a as n, n as r, t };
@@ -0,0 +1,123 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel, Mesh } from '@margoengine/core';
3
+ import type { Engine, EnginePlugin, Vec3 } from '@margoengine/core/extension';
4
+ import { type WideAngleMode } from './wide-laws.js';
5
+ /** What {@link WideAngleCube} needs of a cube: a `CubeCamera` from `@margoengine/environment/cube-camera` fits. */
6
+ export interface WideCubeSource {
7
+ /** Capture point, moved to the camera before each capture. */
8
+ position: Vec3;
9
+ /** `texture_cube<f32>` view holding linear light in the standard WebGPU face layout. */
10
+ readonly view: GPUTextureView;
11
+ /** Captures the next `faces` faces. */
12
+ update(faces?: number): number;
13
+ dispose(): void;
14
+ }
15
+ /** Options of {@link WideAngleCubeMap}. */
16
+ export interface WideAngleCubeMapOptions {
17
+ /** Default 'equidistant'. The laws are those of `WideAngle`. */
18
+ mode?: WideAngleMode;
19
+ /** Degrees across the width of the picture. Default 180. Equidistant and equisolid reach 360, stereographic stops below 360, orthographic at 180, Panini below its own limit (below 360 at `distance` 1). */
20
+ fov?: number;
21
+ /** Panini compression d, 0 or more. Default 1. */
22
+ distance?: number;
23
+ /** Fisheye modes: true (default) leaves black past half of `fov` from the centre, a round picture; false fills the corners as far as the law reaches. */
24
+ circle?: boolean;
25
+ }
26
+ /** Options of {@link WideAngleCube}. */
27
+ export interface WideAngleCubeOptions extends WideAngleCubeMapOptions {
28
+ /** A cube you made and attached. `WideAngleCube.attach` makes one when this is left out, and disposes it with the effect. */
29
+ cube?: WideCubeSource;
30
+ /** Face edge in texels of the cube `attach` makes. Default 512. */
31
+ size?: number;
32
+ /** Faces captured before every engine frame, 0 to 6: fewer spreads the cost and lags the picture. 0 captures only on `capture()`. Default 6. */
33
+ facesPerFrame?: number;
34
+ /** Layer mask the cube `attach` makes draws. Default every layer. */
35
+ layers?: number;
36
+ /** Meshes the cube `attach` makes leaves out: the object the camera rides on, say. */
37
+ exclude?: Iterable<Mesh>;
38
+ /** False passes the plain picture through and captures nothing. Default true. Also `effect.enabled`. */
39
+ enabled?: boolean;
40
+ }
41
+ /**
42
+ * The mapping between the projected picture (normalised, x right and y up, -1 to 1) and directions from the camera
43
+ * (x right, y up, z back, as core's view space, so forward is [0, 0, -1]). The same maths runs in the shader; use it to
44
+ * turn a pointer position on the picture into a ray, or to place overlays.
45
+ */
46
+ export declare class WideAngleCubeMap {
47
+ readonly mode: WideAngleMode;
48
+ readonly distance: number;
49
+ readonly fov: number;
50
+ /** Largest angle from the centre shown, in radians; for Panini, across only. */
51
+ readonly limit: number;
52
+ /** Half extent of the output plane, across and up. */
53
+ readonly halfWidth: number;
54
+ readonly halfHeight: number;
55
+ constructor(aspect: number, { mode, fov, distance, circle }?: WideAngleCubeMapOptions);
56
+ /** Unit direction shown at output position (`u`, `v`), or null where the picture shows nothing. */
57
+ toDirection(u: number, v: number): [number, number, number] | null;
58
+ /** Output position of direction ([`x`, `y`, `z`], any length), or null when the picture does not show it. */
59
+ toOutput(x: number, y: number, z: number): [number, number] | null;
60
+ }
61
+ /**
62
+ * Panini and fisheye projection read from a cube capture, as an HDR stage of `PostStack`: unlike `WideAngle` it is not
63
+ * limited by one rectilinear picture, so it reaches 180 degrees across and past it (`fov`). The cube is captured at the
64
+ * camera before each engine frame, six scene draws at `facesPerFrame` 6. Faces run the scene passes only, so HDR effects
65
+ * ahead of this stage do not reach the picture; put those that should after it. The camera's position, target and `up`
66
+ * set the view; its `fov` is not used. For frames you draw with `engine.render()`, call `capture()` before each.
67
+ * @throws RangeError for an unknown `mode`, a negative `distance` or a `fov` the mode cannot reach; MargoError `'state'`
68
+ * outside a PostStack or with no cube, `'unsupported'` on a WebGL engine, `'attached'` when joined twice, `'disposed'`
69
+ * after `dispose()`.
70
+ */
71
+ export declare class WideAngleCube implements EnginePlugin {
72
+ readonly options: WideAngleCubeOptions;
73
+ readonly name = "wide-angle-cube";
74
+ private engine?;
75
+ private stack?;
76
+ private cube?;
77
+ private ownsCube;
78
+ private stacked;
79
+ private disposed;
80
+ private stopFrames?;
81
+ private uniform?;
82
+ private sampler?;
83
+ private pipeline?;
84
+ private key;
85
+ private group?;
86
+ private input?;
87
+ private cubeView?;
88
+ private mapKey;
89
+ private lastMap?;
90
+ private readonly values;
91
+ private readonly attachment;
92
+ private readonly descriptor;
93
+ constructor(options?: WideAngleCubeOptions);
94
+ /**
95
+ * Adds a new WideAngleCube, with its own cube unless `cube` is given, to the scene's PostStack after its last HDR
96
+ * effect, or to a new PostStack when the scene has none (needs `@margoengine/post` and `@margoengine/environment`).
97
+ * Disposing it takes it out with the cube it made, and a stack made for it goes with it.
98
+ */
99
+ static attach(engine: EngineKernel, options?: WideAngleCubeOptions): Promise<WideAngleCube>;
100
+ /** Whether the picture is projected (mirrors `options.enabled`). */
101
+ get enabled(): boolean;
102
+ set enabled(value: boolean);
103
+ /** Faces captured before every engine frame, 0 to 6. */
104
+ facesPerFrame: number;
105
+ /** The mapping for a view of `aspect`, with these options. */
106
+ map(aspect: number): WideAngleCubeMap;
107
+ /**
108
+ * Moves the cube to the camera and captures `faces` faces (default all six). Runs by itself before every frame of
109
+ * `engine.start`; call it before `engine.render()` otherwise. Not from inside a frame pass.
110
+ * @throws MargoError `'state'` when not attached.
111
+ */
112
+ capture(faces?: number): void;
113
+ private joinStack;
114
+ setup(engine: Engine): void;
115
+ onDeviceRestored(engine: Engine): void;
116
+ /** Removes the effect and releases its GPU resources, with the stack and the cube `attach` made. Safe to call twice. */
117
+ dispose(): void;
118
+ [Symbol.dispose]: () => void;
119
+ private axes;
120
+ private draw;
121
+ private pipelineFor;
122
+ private release;
123
+ }
@@ -0,0 +1,215 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import { t as e } from "./errors-Cp7bu2gW.js";
5
+ import { r as t, t as n } from "./view-rect-p0kR0Q6B.js";
6
+ import { n as r, r as i, t as a } from "./gpu-BRxrrZK3.js";
7
+ import { n as o, r as s, t as c } from "./wide-laws-Dj0410P1.js";
8
+ var l = "fn pbrNeutral(input:vec3f)->vec3f {let x=min(input.r,min(input.g,input.b));let offset=select(0.04,x-6.25*x*x,x<0.08);var v=input-offset;let peak=max(v.r,max(v.g,v.b));if(peak<0.76){return v;}let newPeak=1.0-0.24*0.24/(peak+0.24-0.76);v*=newPeak/peak;return mix(v,vec3f(newPeak),1.0-1.0/(0.15*(peak-newPeak)+1.0));}\nfn toDisplay(c:vec3f)->vec3f {let x=pbrNeutral(max(c,vec3f(0)));return select(x*12.92,1.055*pow(x,vec3f(1.0/2.4))-0.055,x>=vec3f(0.0031308));}\n", u = Math.PI / 2, d = 1e-9, f = (e) => Math.acos(e > 1 ? -1 / e : -e), p = {
9
+ equidistant: Math.PI,
10
+ equisolid: Math.PI,
11
+ stereographic: Math.PI - 1e-6,
12
+ orthographic: u
13
+ }, m = class {
14
+ constructor(e, { mode: t = "equidistant", fov: n = 180, distance: r = 1, circle: i = !0 } = {}) {
15
+ if (!(t in s)) throw RangeError("Invalid wide angle mode; use 'panini', 'equidistant', 'equisolid', 'stereographic' or 'orthographic'");
16
+ if (!(r >= 0 && r < Infinity)) throw RangeError("Invalid wide angle distance; use a finite number from 0");
17
+ if (!(e > 0 && e < Infinity)) throw RangeError("Invalid wide angle aspect; use a number above 0");
18
+ let a = n * Math.PI / 360, o = t === "panini" ? f(r) - 1e-6 : p[t];
19
+ if (!(a > 0 && a <= o)) throw RangeError(`Invalid wide angle fov ${n}; ${t} reaches ${Math.floor(o * 360 / Math.PI)} degrees across`);
20
+ this.mode = t, this.distance = r, this.fov = n, this.limit = t === "panini" || i ? a : o, this.halfWidth = t === "panini" ? (r + 1) * Math.sin(a) / (r + Math.cos(a)) : c[t](a), this.halfHeight = this.halfWidth / e;
21
+ }
22
+ toDirection(e, t) {
23
+ let n = e * this.halfWidth, r = t * this.halfHeight;
24
+ if (this.mode === "panini") {
25
+ let e = this.distance, t = n / (e + 1), i = t * e / Math.sqrt(1 + t * t);
26
+ if (Math.abs(i) > 1) return null;
27
+ let a = Math.atan(t) + Math.asin(i);
28
+ if (Math.abs(a) > this.limit + d) return null;
29
+ let o = Math.cos(a), s = r / ((e + 1) / (e + o)), c = Math.hypot(1, s);
30
+ return [
31
+ Math.sin(a) / c,
32
+ s / c,
33
+ -o / c
34
+ ];
35
+ }
36
+ let i = Math.hypot(n, r), a = o[this.mode](i);
37
+ if (a === null || a > this.limit + d) return null;
38
+ let s = i ? Math.sin(a) / i : 0;
39
+ return [
40
+ n * s,
41
+ r * s,
42
+ -Math.cos(a)
43
+ ];
44
+ }
45
+ toOutput(e, t, n) {
46
+ let r, i;
47
+ if (this.mode === "panini") {
48
+ let a = this.distance, o = Math.atan2(e, -n), s = Math.hypot(e, n);
49
+ if (Math.abs(o) > this.limit + d || !s) return null;
50
+ let c = (a + 1) / (a + Math.cos(o));
51
+ r = c * Math.sin(o), i = c * t / s;
52
+ } else {
53
+ let a = Math.hypot(e, t), o = Math.atan2(a, -n);
54
+ if (o > this.limit + d) return null;
55
+ let s = a ? c[this.mode](o) / a : 0;
56
+ r = e * s, i = t * s;
57
+ }
58
+ let a = r / this.halfWidth, o = i / this.halfHeight;
59
+ return Math.abs(a) <= 1.000000001 && Math.abs(o) <= 1.000000001 ? [a, o] : null;
60
+ }
61
+ }, h = (e) => `${a}${e ? "" : l}
62
+ struct Wide {a:vec4f,b:vec4f,right:vec4f,up:vec4f,forward:vec4f}
63
+ @group(0) @binding(0) var<uniform> w:Wide;
64
+ @group(0) @binding(1) var frame:texture_2d<f32>;
65
+ @group(0) @binding(2) var cube:texture_cube<f32>;
66
+ @group(0) @binding(3) var smp:sampler;
67
+ fn shown(c:vec3f)->vec4f {return vec4f(${e ? "c" : "toDisplay(c)"},1);}
68
+
69
+ @fragment fn fragment(v:Vertex)->@location(0) vec4f {
70
+ let mode=i32(w.a.x);
71
+ if (mode<0) {return shown(textureSampleLevel(frame,smp,v.uv,0).rgb);}
72
+ let p=(v.uv*2-1)*vec2f(1,-1)*w.b.xy;
73
+ var dir=vec3f(0);
74
+ if (mode==0) {
75
+ let d=w.a.y;
76
+ let xp=p.x/(d+1);
77
+ let a=xp*d/sqrt(1+xp*xp);
78
+ if (abs(a)>1) {return shown(vec3f(0));}
79
+ let phi=atan(xp)+asin(a);
80
+ if (abs(phi)>w.a.z+1e-6) {return shown(vec3f(0));}
81
+ let c=cos(phi);
82
+ dir=vec3f(sin(phi),p.y*(d+c)/(d+1),c);
83
+ } else {
84
+ let r=length(p);
85
+ var theta=r;
86
+ if (mode==2) {if (r>2) {return shown(vec3f(0));} theta=2*asin(r/2);}
87
+ else if (mode==3) {theta=2*atan(r/2);}
88
+ else if (mode==4) {if (r>1) {return shown(vec3f(0));} theta=asin(r);}
89
+ if (theta>w.a.z+1e-6) {return shown(vec3f(0));}
90
+ var side=vec2f(0);
91
+ if (r>0) {side=p*(sin(theta)/r);}
92
+ dir=vec3f(side,cos(theta));
93
+ }
94
+ let world=w.right.xyz*dir.x+w.up.xyz*dir.y+w.forward.xyz*dir.z;
95
+ return shown(textureSampleLevel(cube,smp,world,0).rgb);
96
+ }`, g = class a {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
97
+ constructor(e = {}) {
98
+ this.options = e, this.name = "wide-angle-cube", this.ownsCube = !1, this.stacked = !1, this.disposed = !1, this.key = "", this.mapKey = "", this.values = /* @__PURE__ */ new Float32Array(20), this.attachment = {
99
+ view: void 0,
100
+ loadOp: "clear",
101
+ storeOp: "store"
102
+ }, this.descriptor = { colorAttachments: [this.attachment] }, this.cube = e.cube, this.facesPerFrame = e.facesPerFrame ?? 6, this.map(1);
103
+ }
104
+ static async attach(e, t = {}) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
105
+ let [{ PostStack: n }, { CubeCamera: r }] = await Promise.all([import("@margoengine/post"), import("@margoengine/environment/cube-camera")]), i = new a(t);
106
+ i.cube || (i.cube = r.attach(e, {
107
+ size: t.size ?? 512,
108
+ near: e.camera.near,
109
+ far: e.camera.far,
110
+ layers: t.layers,
111
+ exclude: t.exclude
112
+ }), i.ownsCube = !0);
113
+ try {
114
+ i.stack = n.join(e, i);
115
+ } catch (e) {
116
+ throw i.dispose(), e;
117
+ }
118
+ return i;
119
+ }
120
+ get enabled() {
121
+ return this.options.enabled ?? !0;
122
+ }
123
+ set enabled(e) {
124
+ if (typeof e != "boolean") throw TypeError("WideAngleCube enabled must be a boolean; pass true or false");
125
+ this.options.enabled = e;
126
+ }
127
+ map(e) {
128
+ let t = this.options, n = `${e}:${t.mode}:${t.fov}:${t.distance}:${t.circle}`;
129
+ return (n !== this.mapKey || !this.lastMap) && (this.lastMap = new m(e, t), this.mapKey = n), this.lastMap;
130
+ }
131
+ capture(t = 6) {
132
+ if (!this.engine) throw e("state", "WideAngleCube is not attached; add it to a PostStack first");
133
+ let n = this.engine.camera.position;
134
+ this.cube.position = [
135
+ n[0],
136
+ n[1],
137
+ n[2]
138
+ ], this.cube.update(t);
139
+ }
140
+ joinStack(t) {
141
+ if (this.engine || this.stacked || this.disposed) throw e("attached", "WideAngleCube is already attached; create a new WideAngleCube");
142
+ return this.stacked = !0, {
143
+ kind: "hdr",
144
+ render: (e, t, n) => this.draw(e, t, n)
145
+ };
146
+ }
147
+ setup(t) {
148
+ if (this.disposed) throw e("disposed", "WideAngleCube is disposed; create a new WideAngleCube");
149
+ if (!this.stacked) throw e("state", "WideAngleCube runs inside a PostStack; use WideAngleCube.attach(engine) or add it to a PostStack");
150
+ if (!t.gpu) throw e("unsupported", "WideAngleCube requires WebGPU; it does not run on the WebGL2 fallback");
151
+ if (!this.cube) throw e("state", "WideAngleCube has no cube; use WideAngleCube.attach(engine) or pass a CubeCamera");
152
+ this.engine = t, this.uniform = t.gpu.createBuffer({
153
+ size: 80,
154
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
155
+ }), this.sampler = t.gpu.createSampler({
156
+ magFilter: "linear",
157
+ minFilter: "linear"
158
+ }), this.stopFrames ??= t.onFrame(() => {
159
+ this.enabled && this.facesPerFrame && this.capture(this.facesPerFrame);
160
+ });
161
+ }
162
+ onDeviceRestored(e) {
163
+ this.release(), this.engine = void 0, this.setup(e);
164
+ }
165
+ dispose() {
166
+ if (this.disposed) return;
167
+ this.disposed = !0, this.stopFrames?.(), this.stopFrames = void 0;
168
+ let e = this.engine;
169
+ this.engine = void 0, e?.sceneOf(this)?.removePlugin(this.name), this.release(), this.stack?.removeEffect(this), this.stack = void 0, this.ownsCube && this.cube?.dispose(), this.cube = void 0;
170
+ }
171
+ [Symbol.dispose ?? Symbol()]() {
172
+ this.dispose();
173
+ }
174
+ axes(e) {
175
+ let { position: t, target: n, up: r } = this.engine.camera, i = n[0] - t[0], a = n[1] - t[1], o = n[2] - t[2], s = Math.hypot(i, a, o);
176
+ i /= s, a /= s, o /= s;
177
+ let c = a * r[2] - o * r[1], l = o * r[0] - i * r[2], u = i * r[1] - a * r[0], d = Math.hypot(c, l, u);
178
+ c /= d, l /= d, u /= d, e.set([
179
+ c,
180
+ l,
181
+ u,
182
+ 0,
183
+ l * o - u * a,
184
+ u * i - c * o,
185
+ c * a - l * i,
186
+ 0,
187
+ i,
188
+ a,
189
+ o,
190
+ 0
191
+ ], 8);
192
+ }
193
+ draw(e, i, a) {
194
+ let o = e.device, c = this.map(e.width / e.height), l = this.values;
195
+ l[0] = this.enabled ? s[c.mode] : -1, l[1] = c.distance, l[2] = c.limit, l[4] = c.halfWidth, l[5] = c.halfHeight, this.axes(l), o.queue.writeBuffer(this.uniform, 0, l);
196
+ let u = this.pipelineFor(o, a), d = this.cube.view;
197
+ (this.input !== i || this.cubeView !== d || !this.group) && (this.input = i, this.cubeView = d, this.group = r(o, u, [
198
+ { buffer: this.uniform },
199
+ i,
200
+ d,
201
+ this.sampler
202
+ ])), this.attachment.view = a.view, this.attachment.loadOp = t(e, "clear");
203
+ let f = e.encoder.beginRenderPass(this.descriptor);
204
+ f.setPipeline(u), f.setBindGroup(0, this.group), n(f, e), f.draw(3), f.end();
205
+ }
206
+ pipelineFor(e, t) {
207
+ let n = t.multisample?.count ?? 1, r = `${t.format}/${n}/${t.hdr}`;
208
+ return this.key !== r && (this.key = r, this.pipeline = i(e, h(t.hdr), t.format, { multisample: t.multisample }), this.group = void 0), this.pipeline;
209
+ }
210
+ release() {
211
+ this.uniform?.destroy(), this.uniform = this.sampler = this.pipeline = this.group = this.input = this.cubeView = void 0, this.key = "";
212
+ }
213
+ };
214
+ //#endregion
215
+ export { g as WideAngleCube, m as WideAngleCubeMap };
@@ -0,0 +1,20 @@
1
+ //#region src/wide-laws.ts
2
+ var e = {
3
+ panini: 0,
4
+ equidistant: 1,
5
+ equisolid: 2,
6
+ stereographic: 3,
7
+ orthographic: 4
8
+ }, t = {
9
+ equidistant: (e) => e,
10
+ equisolid: (e) => 2 * Math.sin(e / 2),
11
+ stereographic: (e) => 2 * Math.tan(e / 2),
12
+ orthographic: (e) => Math.sin(e)
13
+ }, n = {
14
+ equidistant: (e) => e,
15
+ equisolid: (e) => e <= 2 ? 2 * Math.asin(e / 2) : null,
16
+ stereographic: (e) => 2 * Math.atan(e / 2),
17
+ orthographic: (e) => e <= 1 ? Math.asin(e) : null
18
+ };
19
+ //#endregion
20
+ export { n, e as r, t };
@@ -0,0 +1,5 @@
1
+ /** The projection to draw: Panini, or a fisheye with the named radius law. */
2
+ export type WideAngleMode = 'panini' | 'equidistant' | 'equisolid' | 'stereographic' | 'orthographic';
3
+ export declare const MODES: Record<WideAngleMode, number>;
4
+ export declare const GAIN: Record<string, (theta: number) => number>;
5
+ export declare const INVERSE: Record<string, (r: number) => number | null>;