@margoengine/oit 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.
@@ -0,0 +1,393 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const l=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { a as e, i as t, n, o as r, r as i, t as a } from "./pass-D7U8kWzv.js";
5
+ import { i as o, n as s, t as c } from "./pass-DdYrWNpT.js";
6
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
7
+ //#region src/moments.ts
8
+ var u = 120, d = {
9
+ color: {
10
+ srcFactor: "one",
11
+ dstFactor: "one"
12
+ },
13
+ alpha: {
14
+ srcFactor: "one",
15
+ dstFactor: "one"
16
+ }
17
+ }, f = (e) => {
18
+ let t = Math.cos(e), n = Math.sin(e);
19
+ return n >= 0 ? t >= 0 ? n - t : 2 - t - n : t >= 0 ? 6 + t + n : 4 + t - n;
20
+ }, p = Math.PI / 10, m = `
21
+ fn margoWarp(depth:f32)->f32 {
22
+ return clamp(log(max(depth,1e-6))*margoOIT.x+margoOIT.y,-1.0,1.0);
23
+ }
24
+ fn margoAngle(z:f32)->f32 {return ${(2 * Math.PI - p).toFixed(9)}*(z+1.0)*0.5;}
25
+ fn margoHalf(v:vec4f)->vec4f {
26
+ let b=bitcast<vec4u>(v); let near=bitcast<vec4f>((b+vec4u(0xfffu)+((b>>vec4u(13u))&vec4u(1u)))&vec4u(0xffffe000u));
27
+ return select(near,round(v*16777216.0)/16777216.0,abs(v)<vec4f(6.103515625e-5));
28
+ }
29
+ `, h = (e) => `
30
+ override margoLinear:bool=false;
31
+ struct MargoTransparent {@location(0) moments:vec4f, @location(1) optical:vec4f}
32
+ @group(${e}) @binding(${u}) var<uniform> margoOIT:vec4f;
33
+ ${m}
34
+ fn margoTransparentAt(color:vec4f,clip:vec4f,depth:f32)->MargoTransparent {
35
+ let tau=-log(1.0-clamp(color.a,0.0,0.999)); let a=margoAngle(margoWarp(depth)); var o:MargoTransparent;
36
+ o.moments=margoHalf(tau*vec4f(cos(a),sin(a),cos(2.0*a),sin(2.0*a)));
37
+ o.optical=margoHalf(tau*vec4f(1.0,cos(3.0*a),sin(3.0*a),0.0)); o.optical.w=select(0.0,1.0,margoLinear); return o;
38
+ }
39
+ `, g = (e) => `
40
+ override margoLinear:bool=false;
41
+ struct MargoTransparent {@location(0) color:vec4f}
42
+ @group(${e}) @binding(${u}) var<uniform> margoOIT:vec4f;
43
+ @group(${e}) @binding(121) var margoMoments:texture_2d<f32>;
44
+ @group(${e}) @binding(122) var margoOptical:texture_2d<f32>;
45
+ ${m}
46
+ fn margoMul(a:vec2f,b:vec2f)->vec2f {return vec2f(a.x*b.x-a.y*b.y,a.x*b.y+a.y*b.x);}
47
+ fn margoConj(a:vec2f)->vec2f {return vec2f(a.x,-a.y);}
48
+ fn margoDiv(a:vec2f,b:vec2f)->vec2f {return margoMul(a,margoConj(b))/max(dot(b,b),1e-30);}
49
+ fn margoSqrt(a:vec2f)->vec2f {
50
+ let r=length(a); return vec2f(sqrt(max(0.5*(r+a.x),0.0)),select(1.0,-1.0,a.y<0.0)*sqrt(max(0.5*(r-a.x),0.0)));
51
+ }
52
+ fn margoCbrt(a:vec2f)->vec2f {let r=pow(max(length(a),1e-30),1.0/3.0); let t=atan2(a.y,a.x)/3.0; return r*vec2f(cos(t),sin(t));}
53
+ fn margoPsi(x:vec2f)->f32 {
54
+ if(x.y>=0.0){return select(2.0-x.x-x.y,x.y-x.x,x.x>=0.0);}
55
+ return select(4.0+x.x-x.y,6.0+x.x+x.y,x.x>=0.0);
56
+ }
57
+
58
+ fn margoWeight(l:vec2f,a:vec2f,b:vec2f,c:vec2f,m1:vec2f,m2:vec2f,m3:vec2f)->f32 {
59
+ let ab=margoMul(a,b);
60
+ let n=m3-margoMul(a+b+c,m2)+margoMul(ab+margoMul(a+b,c),m1)-margoMul(ab,c);
61
+ return margoDiv(n,margoMul(margoMul(l-a,l-b),l-c)).x;
62
+ }
63
+ fn margoRoot(x:vec2f,q:array<vec2f,4>)->vec2f {
64
+ let f=q[0]+margoMul(x,q[1]+margoMul(x,q[2]+margoMul(x,q[3])));
65
+ let d=q[1]+margoMul(x,2.0*q[2]+3.0*margoMul(x,q[3]));
66
+ let y=x-margoDiv(f,d); return y/max(length(y),1e-30);
67
+ }
68
+ fn margoInFront(m:vec4f,o:vec4f,z:f32)->f32 {
69
+ var b:array<vec2f,4>; b[0]=vec2f(1.0,0.0); b[1]=0.997*m.xy/o.x; b[2]=0.997*m.zw/o.x; b[3]=0.997*o.yz/o.x;
70
+ let a=margoAngle(z); let x0=vec2f(cos(a),sin(a));
71
+ var l:array<array<vec2f,4>,4>; var d:array<f32,4>; var y:array<vec2f,4>; var q:array<vec2f,4>;
72
+ var r=vec2f(1.0,0.0);
73
+ for(var j=0;j<4;j++){
74
+ for(var i=0;i<j;i++){
75
+ var s=margoConj(b[j-i]);
76
+ for(var k=0;k<i;k++){s-=margoMul(l[j][k],margoConj(l[i][k]))*d[k];}
77
+ l[j][i]=s/d[i];
78
+ }
79
+ var e=1.0; for(var k=0;k<j;k++){e-=dot(l[j][k],l[j][k])*d[k];}
80
+ d[j]=max(e,1e-7);
81
+ var t=r; for(var k=0;k<j;k++){t-=margoMul(l[j][k],y[k]);}
82
+ y[j]=t; r=margoMul(r,margoConj(x0));
83
+ }
84
+ for(var j=3;j>=0;j--){
85
+ var t=y[j]/d[j]; for(var k=j+1;k<4;k++){t-=margoMul(margoConj(l[k][j]),q[k]);}
86
+ q[j]=t;
87
+ }
88
+
89
+ let c2=margoDiv(q[2],q[3]); let c1=margoDiv(q[1],q[3]); let c0=margoDiv(q[0],q[3]);
90
+ let s=c2/3.0; let p=c1-margoMul(c2,s); let h=c0-margoMul(c1,s)+2.0*margoMul(s,margoMul(s,s));
91
+ let w=margoSqrt(margoMul(h,h)/4.0+margoMul(p,margoMul(p,p))/27.0);
92
+ let k=select(-h/2.0+w,-h/2.0-w,dot(-h/2.0-w,-h/2.0-w)>dot(-h/2.0+w,-h/2.0+w));
93
+ let u=margoCbrt(k); let turn=vec2f(-0.5,0.866025404);
94
+ let u1=margoMul(u,turn); let u2=margoMul(u1,turn);
95
+ let x1=margoRoot(u-margoDiv(p,3.0*u)-s,q); let x2=margoRoot(u1-margoDiv(p,3.0*u1)-s,q); let x3=margoRoot(u2-margoDiv(p,3.0*u2)-s,q);
96
+ let w0=margoWeight(x0,x1,x2,x3,b[1],b[2],b[3]); let w1=margoWeight(x1,x0,x2,x3,b[1],b[2],b[3]);
97
+ let w2=margoWeight(x2,x0,x1,x3,b[1],b[2],b[3]); let w3=margoWeight(x3,x0,x1,x2,b[1],b[2],b[3]);
98
+ let p0=margoPsi(x0); let edge=${f(2 * Math.PI - p).toFixed(9)};
99
+ let ps=vec3f(margoPsi(x1),margoPsi(x2),margoPsi(x3));
100
+ let v=select(select(vec3f(0.0),(ps-edge)/(7.0-edge),ps>vec3f(edge)),vec3f(1.0),ps<vec3f(p0));
101
+ return o.x*clamp(0.25*w0+dot(v,vec3f(w1,w2,w3)),0.0,1.0);
102
+ }
103
+ fn margoTransparentAt(color:vec4f,clip:vec4f,depth:f32)->MargoTransparent {
104
+ let q=vec2i(clip.xy); let o=textureLoad(margoOptical,q,0); var out:MargoTransparent;
105
+ var t=1.0;
106
+ if(o.x>1e-5){t=exp(-margoInFront(textureLoad(margoMoments,q,0),o,margoWarp(depth)));}
107
+ let w=clamp(color.a,0.0,1.0)*t; out.color=margoHalf(vec4f(color.rgb*w,w)); return out;
108
+ }
109
+ `, _ = "\n@group(0) @binding(0) var colorMap:texture_2d<f32>;\n@group(0) @binding(1) var opticalMap:texture_2d<f32>;\n@vertex fn vertex(@builtin(vertex_index) i:u32)->@builtin(position) vec4f {return vec4f(f32(i&1u)*4-1,f32(i>>1u)*4-1,0,1);}\n@fragment fn fragment(@builtin(position) p:vec4f)->@location(0) vec4f {\n let q=vec2i(p.xy); let a=textureLoad(colorMap,q,0); return vec4f(a.rgb/max(a.a,1e-5),1-exp(-textureLoad(opticalMap,q,0).r));\n}\n", v = s("@group(0) @binding(0) var colorMap:texture_2d<f32>;\n@group(0) @binding(1) var opticalMap:texture_2d<f32>;", "let a=textureLoad(colorMap,q,0); let o=textureLoad(opticalMap,q,0); let avg=a.rgb/max(a.a,1e-5); let cover=1-exp(-o.r); let mark=clamp(1-o.a,0.0,1.0);"), y = [
110
+ "rgba16float",
111
+ "rgba16float",
112
+ "rgba16float"
113
+ ], b = class s extends c {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
114
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
115
+ let n = new s(t);
116
+ return l(e).use(n), n;
117
+ }
118
+ constructor({ order: e = 8, depthRange: t } = {}) {
119
+ if (t && !(t[0] > 0 && t[1] > t[0] && Number.isFinite(t[1]))) throw RangeError("Invalid MomentOIT depthRange; use [near, far] with 0 < near < far");
120
+ super(e), this.targets = [{
121
+ format: "rgba16float",
122
+ blend: d
123
+ }, {
124
+ format: "rgba16float",
125
+ blend: d
126
+ }], this.layout = [{
127
+ binding: u,
128
+ visibility: 2,
129
+ buffer: {}
130
+ }], this.code = /* @__PURE__ */ new Map(), this.surfaceCode = /* @__PURE__ */ new Map(), this.shadeCode = /* @__PURE__ */ new Map(), this.shadeSurface = /* @__PURE__ */ new Map(), this.values = /* @__PURE__ */ new Float32Array(4), this.textures = [], this.views = [], this.size = "", this.pipelines = /* @__PURE__ */ new Map(), this.groups = /* @__PURE__ */ new Map(), this.shader = {
131
+ targets: [{
132
+ format: "rgba16float",
133
+ blend: d
134
+ }],
135
+ layout: [
136
+ ...this.layout,
137
+ {
138
+ binding: 121,
139
+ visibility: 2,
140
+ texture: { sampleType: "unfilterable-float" }
141
+ },
142
+ {
143
+ binding: 122,
144
+ visibility: 2,
145
+ texture: { sampleType: "unfilterable-float" }
146
+ }
147
+ ],
148
+ declarations: (e) => n(this.shadeCode, e, (e) => this.shader.surface(e) + o),
149
+ surface: (e) => n(this.shadeSurface, e, g),
150
+ bindings: () => [
151
+ {
152
+ binding: u,
153
+ resource: this.binding ?? { buffer: this.uniform }
154
+ },
155
+ {
156
+ binding: 121,
157
+ resource: this.views[0]
158
+ },
159
+ {
160
+ binding: 122,
161
+ resource: this.views[1]
162
+ }
163
+ ],
164
+ begin: () => this.shading ??= this.open("oit:shade", [2], [[
165
+ 0,
166
+ 0,
167
+ 0,
168
+ 0
169
+ ]]),
170
+ linearLayers: (e) => this.linearLayers(e)
171
+ }, this.range = t;
172
+ }
173
+ setup(e) {
174
+ super.setup(e), this.uniform = e.gpu.createBuffer({
175
+ size: 16,
176
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
177
+ });
178
+ }
179
+ add(e) {
180
+ return this.box = void 0, super.add(e);
181
+ }
182
+ fit() {
183
+ this.box = void 0;
184
+ }
185
+ depthSpan(e) {
186
+ if (this.effects.size) return [e.camera.near, e.camera.far];
187
+ let t = this.box;
188
+ if (!t) {
189
+ t = this.box = [
190
+ Infinity,
191
+ Infinity,
192
+ Infinity,
193
+ -Infinity,
194
+ -Infinity,
195
+ -Infinity
196
+ ];
197
+ for (let e of this.models.keys()) if (e.primitives.length) {
198
+ let n = e.bounds;
199
+ for (let e = 0; e < 3; e++) t[e] = Math.min(t[e], n[e]), t[e + 3] = Math.max(t[e + 3], n[e + 3]);
200
+ }
201
+ }
202
+ let { position: n, target: r, near: i } = e.camera, a = n.map((e, t) => r[t] - e), o = Math.hypot(...a) || 1, s = Infinity, c = -Infinity;
203
+ for (let e = 0; e < 8; e++) {
204
+ let r = 0;
205
+ for (let i = 0; i < 3; i++) r += (t[e >> i & 1 ? i + 3 : i] - n[i]) * (a[i] / o);
206
+ s = Math.min(s, r), c = Math.max(c, r);
207
+ }
208
+ let l = Math.max(s * .98, i);
209
+ return [l, Math.max(c * 1.02, l * 1.01)];
210
+ }
211
+ declarations(e) {
212
+ return n(this.code, e, (e) => this.surface(e) + o);
213
+ }
214
+ surface(e) {
215
+ return n(this.surfaceCode, e, h);
216
+ }
217
+ bindings() {
218
+ return [{
219
+ binding: u,
220
+ resource: this.binding ?? { buffer: this.uniform }
221
+ }];
222
+ }
223
+ begin() {
224
+ return this.pass ??= this.open("oit:moments", [0, 1], [[
225
+ 0,
226
+ 0,
227
+ 0,
228
+ 0
229
+ ], [
230
+ 0,
231
+ 0,
232
+ 0,
233
+ 0
234
+ ]]);
235
+ }
236
+ open(e, t, n) {
237
+ let i = this.context, a = this.views.length > 3, o = this.views, s = i.encoder.beginRenderPass({
238
+ label: e,
239
+ colorAttachments: t.map((e, t) => ({
240
+ view: a ? o[e + 3] : o[e],
241
+ resolveTarget: a ? o[e] : void 0,
242
+ clearValue: n[t],
243
+ loadOp: "clear",
244
+ storeOp: a ? "discard" : "store"
245
+ })),
246
+ depthStencilAttachment: {
247
+ view: i.depth,
248
+ depthReadOnly: !0,
249
+ stencilReadOnly: !0
250
+ }
251
+ });
252
+ return r(s, i), s;
253
+ }
254
+ render(t) {
255
+ if (i(t.device, t.view ?? t), this.disposed || this.empty) return;
256
+ let n = t.descriptor.multisample?.count ?? 1, o = t.width + "x" + t.height + "x" + n, s = t.device;
257
+ if (o !== this.size) {
258
+ this.release(), this.size = o;
259
+ for (let e of n > 1 ? [
260
+ 1,
261
+ 1,
262
+ 1,
263
+ n,
264
+ n,
265
+ n
266
+ ] : [
267
+ 1,
268
+ 1,
269
+ 1
270
+ ]) {
271
+ let n = y[this.textures.length % 3], r = s.createTexture({
272
+ label: "oit:" + n,
273
+ size: [t.width, t.height],
274
+ format: n,
275
+ sampleCount: e,
276
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | (e === 1 ? GPUTextureUsage.TEXTURE_BINDING : 0)
277
+ });
278
+ this.textures.push(r), this.views.push(r.createView());
279
+ }
280
+ }
281
+ let [c, l] = this.range ?? this.depthSpan(t);
282
+ this.values[0] = 2 / Math.log(l / c), this.values[1] = -1 - this.values[0] * Math.log(c), this.binding = e(s, this.uniform, this.values, t.view ?? t);
283
+ let u;
284
+ try {
285
+ if (!this.drawModels(t)) return;
286
+ this.context = t, this.shading = void 0;
287
+ try {
288
+ for (let e of this.models.keys()) e.drawTransparent(t, this.shader);
289
+ for (let e of this.effects.keys()) e.drawTransparent(t, this.shader);
290
+ } finally {
291
+ this.shading?.end(), this.shading = void 0, this.context = void 0;
292
+ }
293
+ u = this.scene?.();
294
+ } finally {
295
+ this.binding = void 0, this.scene = void 0;
296
+ }
297
+ let d = t.format + n, f = this.pipelines.get(d);
298
+ if (!f) {
299
+ let e = s.createShaderModule({ code: _ });
300
+ this.pipelines.set(d, f = s.createRenderPipeline({
301
+ label: "oit:composite",
302
+ layout: "auto",
303
+ vertex: {
304
+ module: e,
305
+ entryPoint: "vertex"
306
+ },
307
+ fragment: {
308
+ module: e,
309
+ entryPoint: "fragment",
310
+ targets: [{
311
+ format: t.format,
312
+ blend: a
313
+ }]
314
+ },
315
+ multisample: { count: n }
316
+ }));
317
+ }
318
+ let p = this.groups.get(f);
319
+ p || this.groups.set(f, p = s.createBindGroup({
320
+ layout: f.getBindGroupLayout(0),
321
+ entries: [{
322
+ binding: 0,
323
+ resource: this.views[2]
324
+ }, {
325
+ binding: 1,
326
+ resource: this.views[1]
327
+ }]
328
+ }));
329
+ let m = t.encoder.beginRenderPass({
330
+ label: "oit:composite",
331
+ colorAttachments: [{
332
+ view: t.color,
333
+ loadOp: "load",
334
+ storeOp: "store"
335
+ }]
336
+ });
337
+ if (r(m, t), m.setPipeline(f), m.setBindGroup(0, p), m.draw(3), u) {
338
+ let e = this.pipelines.get(d + "l");
339
+ if (!e) {
340
+ let r = s.createShaderModule({ code: v });
341
+ this.pipelines.set(d + "l", e = s.createRenderPipeline({
342
+ label: "oit:composite-linear",
343
+ layout: "auto",
344
+ vertex: {
345
+ module: r,
346
+ entryPoint: "vertex"
347
+ },
348
+ fragment: {
349
+ module: r,
350
+ entryPoint: "fragment",
351
+ targets: [{ format: t.format }]
352
+ },
353
+ multisample: { count: n }
354
+ }));
355
+ }
356
+ m.setPipeline(e), m.setBindGroup(0, this.linearGroup(e, u)), m.draw(3);
357
+ }
358
+ m.end();
359
+ }
360
+ linearGroup(e, t) {
361
+ let n = this.linearGroups;
362
+ return (n?.view !== t || n.pipeline !== e) && (this.linearGroups = n = {
363
+ view: t,
364
+ pipeline: e,
365
+ group: this.device.createBindGroup({
366
+ layout: e.getBindGroupLayout(0),
367
+ entries: [
368
+ {
369
+ binding: 0,
370
+ resource: this.views[2]
371
+ },
372
+ {
373
+ binding: 1,
374
+ resource: this.views[1]
375
+ },
376
+ {
377
+ binding: 9,
378
+ resource: t
379
+ }
380
+ ]
381
+ })
382
+ }), n.group;
383
+ }
384
+ release() {
385
+ for (let e of this.textures) t(this.device, e);
386
+ this.textures = [], this.views = [], this.size = "", this.groups.clear(), this.linearGroups = void 0;
387
+ }
388
+ freeDevice() {
389
+ this.release(), this.pipelines.clear(), t(this.device, this.uniform), this.uniform = void 0;
390
+ }
391
+ };
392
+ //#endregion
393
+ export { b as MomentOIT };
@@ -0,0 +1,92 @@
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
+ //#endregion
13
+ //#region ../shared/frame-resources.js
14
+ var n = (globalThis[Symbol.for("margoengine.frame-resources")] ??= { devices: /* @__PURE__ */ new WeakMap() }).devices;
15
+ function r(e) {
16
+ let t = n.get(e);
17
+ return t || (n.set(e, t = {
18
+ frame: 0,
19
+ open: !1,
20
+ lost: !1,
21
+ views: /* @__PURE__ */ new Set(),
22
+ drawing: 0,
23
+ retired: [],
24
+ written: /* @__PURE__ */ new WeakMap()
25
+ }), e.lost?.then?.(() => {
26
+ t.lost = !0;
27
+ let e = t.retired;
28
+ t.retired = [];
29
+ for (let t of e) t.destroy();
30
+ })), t;
31
+ }
32
+ function i(e, t) {
33
+ let n = r(e);
34
+ return n.open || (n.open = !0, n.frame++, queueMicrotask(n.close ??= () => {
35
+ if (n.open = !1, n.views.clear(), !n.retired.length) return;
36
+ let e = n.retired;
37
+ n.retired = [];
38
+ for (let t of e) t.destroy();
39
+ })), t && n.views.add(t), n.frame;
40
+ }
41
+ function a(e, t) {
42
+ if (!t) return;
43
+ let n = r(e), i = [t, ...n.written.get(t)?.extras ?? []];
44
+ if (n.written.delete(t), !n.lost && n.open && (n.views.size > 1 || n.drawing > 0)) n.retired.push(...i);
45
+ else for (let e of i) e.destroy();
46
+ }
47
+ function o(e, t, n, a) {
48
+ let o = i(e, a), s = r(e), c = s.written.get(t);
49
+ c?.values.length !== n.length && (c && s.retired.push(...c.extras), s.written.set(t, c = {
50
+ frame: 0,
51
+ view: void 0,
52
+ uses: 0,
53
+ values: new Float32Array(n.length),
54
+ extras: []
55
+ }));
56
+ let l = c.frame === o && c.view !== a;
57
+ for (let e = 0; l && e < n.length; e++) l = c.values[e] === n[e];
58
+ if (c.frame !== o || c.view === a || l) {
59
+ c.frame !== o && Object.assign(c, {
60
+ frame: o,
61
+ view: a,
62
+ uses: 0
63
+ }), c.values.set(n), e.queue.writeBuffer(t, 0, n);
64
+ return;
65
+ }
66
+ let u = c.extras[c.uses++] ??= e.createBuffer({
67
+ label: "frame uniform copy",
68
+ size: t.size,
69
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
70
+ });
71
+ return e.queue.writeBuffer(u, 0, n), { buffer: u };
72
+ }
73
+ //#endregion
74
+ //#region ../shared/pass.js
75
+ var s = /* @__PURE__ */ Object.freeze({
76
+ color: {
77
+ srcFactor: "src-alpha",
78
+ dstFactor: "one-minus-src-alpha",
79
+ operation: "add"
80
+ },
81
+ alpha: {
82
+ srcFactor: "one",
83
+ dstFactor: "one-minus-src-alpha",
84
+ operation: "add"
85
+ }
86
+ });
87
+ function c(e, t, n) {
88
+ let r = e.get(t);
89
+ return r === void 0 && e.set(t, r = n(t)), r;
90
+ }
91
+ //#endregion
92
+ export { o as a, a as i, c as n, t as o, i as r, s as t };
@@ -0,0 +1,84 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import { MargoError as e } from "@margoengine/math/errors";
5
+ //#region src/pass.ts
6
+ var t = 0, n = "fn margoTransparent(color:vec4f,i:Out)->MargoTransparent {\n return margoTransparentAt(color,i.clip,-(f.view*vec4f(i.position,1)).z);\n}\n", r = "\nfn decode(c:vec3f)->vec3f {let x=max(c,vec3f(0));return select(x/12.92,pow((x+0.055)/1.055,vec3f(2.4)),x>vec3f(0.04045));}\nfn encode(c:vec3f)->vec3f {let x=max(c,vec3f(0));return select(x*12.92,1.055*pow(x,vec3f(1.0/2.4))-0.055,x>vec3f(0.0031308));}\nfn overLinear(c:vec4f,d:vec4f)->vec4f {return vec4f(encode(decode(c.rgb)*c.a+decode(d.rgb)*(1-c.a)),c.a+d.a*(1-c.a));}\n", i = (e, t) => `
7
+ ${e}
8
+ @group(0) @binding(9) var sceneMap:texture_2d<f32>;
9
+ ${r}
10
+ @vertex fn vertex(@builtin(vertex_index) i:u32)->@builtin(position) vec4f {return vec4f(f32(i&1u)*4-1,f32(i>>1u)*4-1,0,1);}
11
+ @fragment fn fragment(@builtin(position) p:vec4f)->@location(0) vec4f {
12
+ let q=vec2i(p.xy); ${t}
13
+ if(mark>=1.0){discard;}
14
+ let d=textureLoad(sceneMap,q,0); let light=overLinear(vec4f(avg,cover),d);
15
+ return vec4f(mix(light.rgb,avg*cover+d.rgb*(1-cover),mark),light.a);
16
+ }
17
+ `, a = class {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
18
+ constructor(e) {
19
+ if (this.name = "oit:" + t++, this.disposed = !1, this.models = /* @__PURE__ */ new Map(), this.effects = /* @__PURE__ */ new Map(), !Number.isFinite(e) || e <= 0) throw RangeError("OIT order must be > 0");
20
+ this.order = e;
21
+ }
22
+ add(e) {
23
+ this.ready();
24
+ let t = this.models.get(e);
25
+ if (!t) {
26
+ let n = e.setTransparency(this), r = e.onDispose(() => this.models.delete(e));
27
+ t = () => {
28
+ this.models.get(e) === t && (this.models.delete(e), r(), n());
29
+ }, this.models.set(e, t);
30
+ }
31
+ return t;
32
+ }
33
+ ready() {
34
+ if (this.disposed || !this.engine) throw new e(this.disposed ? "disposed" : "state", this.disposed ? "OIT is disposed; create a new OIT" : "OIT.add needs OIT.attach(engine) first");
35
+ }
36
+ setup(t) {
37
+ if (this.disposed) throw new e("disposed", "OIT is disposed; create a new OIT");
38
+ if (!t.gpu) throw new e("unsupported", "OIT requires WebGPU; use a WebGPU engine; see https://margoengine.com/errors#webgpu");
39
+ this.engine = t, this.device = t.gpu;
40
+ }
41
+ registerPasses(e) {
42
+ e.add({
43
+ name: this.name,
44
+ order: this.order,
45
+ execute: (e) => {
46
+ e.backend === "webgpu" && this.render(e);
47
+ }
48
+ });
49
+ }
50
+ linearLayers(e) {
51
+ e && (this.scene = e);
52
+ }
53
+ get empty() {
54
+ return !this.models.size && !this.effects.size;
55
+ }
56
+ drawModels(e) {
57
+ this.context = e, this.pass = void 0, this.scene = void 0;
58
+ try {
59
+ for (let t of this.models.keys()) t.draw(e, "transparent", e.color, e.depth);
60
+ for (let t of this.effects.keys()) t.drawTransparent(e, this);
61
+ } catch (e) {
62
+ throw this.pass?.end(), this.pass = void 0, e;
63
+ } finally {
64
+ this.context = void 0;
65
+ }
66
+ let t = this.pass;
67
+ return t ? (t.end(), this.pass = void 0, !0) : !1;
68
+ }
69
+ onDeviceRestored(e) {
70
+ this.freeDevice(), this.setup(e);
71
+ }
72
+ dispose() {
73
+ if (!this.disposed) {
74
+ this.disposed = !0;
75
+ for (let e of [...this.models.values(), ...this.effects.values()]) e();
76
+ this.freeDevice(), this.engine?.sceneOf(this)?.removePlugin(this.name);
77
+ }
78
+ }
79
+ [Symbol.dispose ?? Symbol()]() {
80
+ this.dispose();
81
+ }
82
+ };
83
+ //#endregion
84
+ export { n as i, i as n, r, a as t };
package/dist/pass.d.ts ADDED
@@ -0,0 +1,80 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { Engine, EnginePlugin, FrameGraph, PassContext } from '@margoengine/core/extension';
3
+ import type { PBRModel, PBRTransparency } from '@margoengine/gltf/pbr';
4
+ import type { SurfaceTransparency } from './shared/pass.js';
5
+ type Context = Extract<PassContext, {
6
+ backend: 'webgpu';
7
+ }>;
8
+ /** A drawable that is no PBR surface and can feed an order-independent pass: `VFX`, `Splats`, `PointsPlugin`. */
9
+ export interface TransparentEffect {
10
+ /** Leaves the effect's own drawing for `drawTransparent`. Returns a remover; `released` runs if the effect is disposed first. */
11
+ setTransparency(hook: SurfaceTransparency, released?: () => void): () => void;
12
+ /** Draws into `hook`'s pass; a pass may ask twice in one frame. */
13
+ drawTransparent(c: Context, hook: SurfaceTransparency): void;
14
+ }
15
+ /** What every PBR surface passes on to `margoTransparentAt`. */
16
+ export declare const pbrLayer = "fn margoTransparent(color:vec4f,i:Out)->MargoTransparent {\n return margoTransparentAt(color,i.clip,-(f.view*vec4f(i.position,1)).z);\n}\n";
17
+ /**
18
+ * KB3148e: sRGB transfer (IEC 61966-2-1) for the linear-light layers of the exact, peeled, moment and float32 passes,
19
+ * and the over operator on linear values (Porter and Duff 1984): what a sorted `blendSpace: 'linear'` draw does, one
20
+ * layer over the colour drawn so far.
21
+ */
22
+ export declare const linearLight = "\nfn decode(c:vec3f)->vec3f {let x=max(c,vec3f(0));return select(x/12.92,pow((x+0.055)/1.055,vec3f(2.4)),x>vec3f(0.04045));}\nfn encode(c:vec3f)->vec3f {let x=max(c,vec3f(0));return select(x*12.92,1.055*pow(x,vec3f(1.0/2.4))-0.055,x>vec3f(0.0031308));}\nfn overLinear(c:vec4f,d:vec4f)->vec4f {return vec4f(encode(decode(c.rgb)*c.a+decode(d.rgb)*(1-c.a)),c.a+d.a*(1-c.a));}\n";
23
+ /**
24
+ * KB3148e: the composite of a weighted pass (moments, float32) over the pixels a linear layer touched, blending off.
25
+ * `body` sets `avg` (encoded average colour), `cover` (coverage) and `mark` (1 where no linear layer drew).
26
+ */
27
+ export declare const linearComposite: (maps: string, body: string) => string;
28
+ /** The part of an order-independent pass that `oit.add(model)` and `addMesh` work on: `OIT`, `ExactOIT` and `MomentOIT`. */
29
+ export declare abstract class TransparentPass implements EnginePlugin, PBRTransparency, SurfaceTransparency {
30
+ readonly name: string;
31
+ readonly order: number;
32
+ abstract readonly targets: readonly GPUColorTargetState[];
33
+ protected engine?: Engine;
34
+ /** Device of the current GPU resources, so a release after device restoration retires them on their own device. */
35
+ protected device?: GPUDevice;
36
+ protected disposed: boolean;
37
+ protected readonly models: Map<PBRModel, () => void>;
38
+ /** @internal Effects added with `addEffect` (`@margoengine/oit/vfx`) and their removers. */
39
+ readonly effects: Map<TransparentEffect, () => void>;
40
+ protected context?: Context;
41
+ protected pass?: GPURenderPassEncoder;
42
+ /** This frame's scene snapshot source, set when a `blendSpace: 'linear'` layer drew (KB3148d, KB3148e). */
43
+ protected scene?: () => GPUTextureView;
44
+ constructor(order: number);
45
+ /** Draws a gltf\/pbr model's BLEND primitives (or a transparent materials mesh) order-independently. Returns a remover. */
46
+ add(model: PBRModel): () => void;
47
+ /** @internal Throws unless the pass can take something to draw. */
48
+ ready(): void;
49
+ setup(engine: Engine): void;
50
+ registerPasses(graph: FrameGraph): void;
51
+ /**
52
+ * @internal gltf/pbr transparency hook: a `blendSpace: 'linear'` layer drew this frame; `scene` copies the colour drawn
53
+ * so far into the native glass snapshot and returns it (absent until the capture joins the frame graph).
54
+ */
55
+ linearLayers(scene?: () => GPUTextureView): void;
56
+ /** @internal gltf\/pbr transparency hook. */
57
+ abstract declarations(group: number): string;
58
+ /** @internal gltf\/pbr transparency hook. */
59
+ abstract bindings(): GPUBindGroupEntry[];
60
+ /** @internal Effect hook: the declarations without what only a PBR surface has. */
61
+ abstract surface(group: number): string;
62
+ /** @internal Effect hook. */
63
+ abstract readonly layout: readonly GPUBindGroupLayoutEntry[];
64
+ /** @internal gltf\/pbr transparency hook: this frame's transparent pass, begun on the first transparent draw. */
65
+ abstract begin(): GPURenderPassEncoder;
66
+ protected abstract render(c: Context): void;
67
+ /** Whether nothing was added. */
68
+ protected get empty(): boolean;
69
+ /** Frees what depends on the render size. */
70
+ protected abstract release(): void;
71
+ /** Frees everything held on the current device. */
72
+ protected abstract freeDevice(): void;
73
+ /** Draws the added models into the pass `begin` opens and ends it. False when nothing drew. */
74
+ protected drawModels(c: Context): boolean;
75
+ onDeviceRestored(engine: Engine): void;
76
+ /** Restores sorted blending on every added model and frees the GPU resources. */
77
+ dispose(): void;
78
+ [Symbol.dispose]: () => void;
79
+ }
80
+ export {};