@margoengine/dof 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/index.js ADDED
@@ -0,0 +1,1064 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const n=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { t as e } from "./errors-B1DmBK5g.js";
5
+ import { t } from "./projection-CS2tLkwf.js";
6
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
7
+ import { MargoError as r } from "@margoengine/math/errors";
8
+ //#region ../shared/view-rect.js
9
+ function i(e) {
10
+ return e?.view?.viewport;
11
+ }
12
+ function a(e) {
13
+ let t = i(e);
14
+ return t ? [t[2], t[3]] : [e.width, e.height];
15
+ }
16
+ function o(e, t) {
17
+ let n = i(t);
18
+ if (!n) return;
19
+ e.setViewport(n[0], n[1], n[2], n[3], 0, 1);
20
+ let r = t.view.scissor ?? n;
21
+ e.setScissorRect(r[0], r[1], r[2], r[3]);
22
+ }
23
+ function s(e, t = "clear") {
24
+ return e?.view?.index ? "load" : t;
25
+ }
26
+ //#endregion
27
+ //#region ../shared/frame-resources.js
28
+ var c = (globalThis[Symbol.for("margoengine.frame-resources")] ??= { devices: /* @__PURE__ */ new WeakMap() }).devices;
29
+ function l(e) {
30
+ let t = c.get(e);
31
+ return t || (c.set(e, t = {
32
+ frame: 0,
33
+ open: !1,
34
+ lost: !1,
35
+ views: /* @__PURE__ */ new Set(),
36
+ drawing: 0,
37
+ retired: [],
38
+ written: /* @__PURE__ */ new WeakMap()
39
+ }), e.lost?.then?.(() => {
40
+ t.lost = !0;
41
+ let e = t.retired;
42
+ t.retired = [];
43
+ for (let t of e) t.destroy();
44
+ })), t;
45
+ }
46
+ function u(e, t) {
47
+ if (!t) return;
48
+ let n = l(e), r = [t, ...n.written.get(t)?.extras ?? []];
49
+ if (n.written.delete(t), !n.lost && n.open && (n.views.size > 1 || n.drawing > 0)) n.retired.push(...r);
50
+ else for (let e of r) e.destroy();
51
+ }
52
+ //#endregion
53
+ //#region ../shared/compat.js
54
+ function d(t, n, r = "full") {
55
+ let i = {
56
+ ldr: 0,
57
+ "half-float": 1,
58
+ full: 2
59
+ };
60
+ if (!Object.hasOwn(i, r)) throw TypeError("minimum must be full, half-float or ldr");
61
+ let a = t?.adapter?.capabilities?.tier;
62
+ if (a && i[a] < i[r]) throw e("unsupported", `${n} requires the ${r} compatibility tier; this device is ${a}`, "compatibility-layer");
63
+ }
64
+ function f(e) {
65
+ return e?.adapterInfo?.vendor === "margo-webgl2" ? "webgl2" : "native";
66
+ }
67
+ function p(e) {
68
+ return f(e) === "native" && e?.features?.has("core-features-and-limits") === !1;
69
+ }
70
+ function m(e, t) {
71
+ return f(e) === "webgl2" ? t() : void 0;
72
+ }
73
+ function h(e) {
74
+ return e ? e.then(() => void 0, () => void 0) : Promise.resolve();
75
+ }
76
+ //#endregion
77
+ //#region ../shared/msaa.js
78
+ var g = "@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);}", _ = (e, t, n) => e.createBindGroup({
79
+ layout: t.getBindGroupLayout(0),
80
+ entries: [{
81
+ binding: 0,
82
+ resource: n
83
+ }]
84
+ }), v = Symbol.for("margoengine.optional.msaa"), y = g + "\n@group(0) @binding(0) var source:texture_depth_multisampled_2d;\n@fragment fn fragment(@builtin(position) p:vec4f)->@builtin(frag_depth) f32 {\n let q=vec2i(p.xy);\n return max(max(textureLoad(source,q,0),textureLoad(source,q,1)),max(textureLoad(source,q,2),textureLoad(source,q,3)));\n}";
85
+ function b(e, t, n, r, i, a = !1) {
86
+ let o = (e) => y.replace(/return max[^;]+;/, `return textureLoad(source,q,${e});`), s = (n, r) => {
87
+ let a = e.createShaderModule({ code: n }), o = e.createRenderPipeline({
88
+ layout: "auto",
89
+ vertex: {
90
+ module: a,
91
+ entryPoint: "vertex"
92
+ },
93
+ fragment: {
94
+ module: a,
95
+ entryPoint: "fragment",
96
+ targets: []
97
+ },
98
+ depthStencil: {
99
+ format: i,
100
+ depthWriteEnabled: !0,
101
+ depthCompare: "always"
102
+ },
103
+ multisample: r
104
+ });
105
+ return {
106
+ pipeline: o,
107
+ group: _(e, o, t)
108
+ };
109
+ };
110
+ return {
111
+ draws: a ? [s(o(0).replace("_multisampled", ""), { count: r })] : r === 4 ? p(e) ? [
112
+ 0,
113
+ 1,
114
+ 2,
115
+ 3
116
+ ].map((e) => s(o(e), {
117
+ count: r,
118
+ mask: 1 << e
119
+ })) : [s(o("i32(sample)").replace("p:vec4f)", "p:vec4f,@builtin(sample_index) sample:u32)"), { count: r })] : [s(y, { count: r })],
120
+ descriptor: {
121
+ colorAttachments: [],
122
+ depthStencilAttachment: {
123
+ view: n,
124
+ depthLoadOp: "clear",
125
+ depthClearValue: 0,
126
+ depthStoreOp: "store",
127
+ stencilReadOnly: !0
128
+ }
129
+ }
130
+ };
131
+ }
132
+ function x(e, t, n, r, i, a) {
133
+ let s = e.pipelines.get(r);
134
+ s || e.pipelines.set(r, s = /* @__PURE__ */ new Map());
135
+ let c = s.get(i);
136
+ if (!c) {
137
+ let t = e.samples === 1;
138
+ s.set(i, c = b(e.device, e.depthSource, n, r, i, t));
139
+ }
140
+ c.descriptor.depthStencilAttachment.view = n, c.descriptor.depthStencilAttachment.depthLoadOp = a?.view ? "load" : "clear";
141
+ let l = t.beginRenderPass(c.descriptor);
142
+ a && o(l, a);
143
+ let u = c.draws;
144
+ for (let e = 0; e < u.length; e++) l.setPipeline(u[e].pipeline), l.setBindGroup(0, u[e].group), l.draw(3);
145
+ l.end();
146
+ }
147
+ var ee = class {
148
+ constructor(e, t, n, r = 4) {
149
+ if (r !== 1 && r !== 4) throw RangeError("Scene samples must be 1 or 4");
150
+ this.samples = r, this.device = e, this.resolvedColor = t, this.resolvedDepth = n, this.textures = [], this.pipelines = /* @__PURE__ */ new Map();
151
+ try {
152
+ if (r === 1) {
153
+ this.color = t.createView(), this.depth = n.createView();
154
+ return;
155
+ }
156
+ for (let r of [t, n]) this.textures.push(e.createTexture({
157
+ size: [r.width, r.height],
158
+ format: r.format,
159
+ sampleCount: 4,
160
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
161
+ }));
162
+ this.color = this.textures[0].createView(), this.depth = this.textures[1].createView(), this.resolution = { colorAttachments: [{
163
+ view: this.color,
164
+ resolveTarget: t.createView(),
165
+ loadOp: "load",
166
+ storeOp: "store"
167
+ }] }, this.finalResolution = {
168
+ colorAttachments: [{
169
+ ...this.resolution.colorAttachments[0],
170
+ storeOp: "discard"
171
+ }],
172
+ depthStencilAttachment: {
173
+ view: this.depth,
174
+ depthLoadOp: "load",
175
+ depthStoreOp: "discard",
176
+ stencilReadOnly: !0
177
+ }
178
+ }, this.depthSource = this.textures[1].createView({ aspect: "depth-only" }), this.resolvedDepthView = n.createView();
179
+ } catch (e) {
180
+ throw this.dispose(), e;
181
+ }
182
+ }
183
+ begin(e) {
184
+ (this.viewContext ??= {}).view = e.view, Object.assign(this.original ??= {}, {
185
+ color: e.color,
186
+ depth: e.depth,
187
+ format: e.format,
188
+ descriptor: e.descriptor,
189
+ owner: S(e)
190
+ }), e.color = this.color, e.depth = this.depth, e.format = this.resolvedColor.format, this.baseDescriptor !== e.descriptor && (this.baseDescriptor = e.descriptor, this.descriptor = {
191
+ ...e.descriptor,
192
+ depthStencil: {
193
+ ...e.descriptor.depthStencil,
194
+ format: this.resolvedDepth.format
195
+ },
196
+ multisample: { count: this.samples }
197
+ }), e.descriptor = this.descriptor, e[v] = this, this.retired = !1, this.resized = e.width !== void 0 && (e.width !== this.resolvedDepth.width || e.height !== this.resolvedDepth.height);
198
+ }
199
+ copyDepth(e, t, n, r = this.resolvedDepth.format) {
200
+ this.depthSource ??= this.resolvedDepth.createView({ aspect: "depth-only" }), x(this, e, t, n, r, this.viewContext);
201
+ }
202
+ resolve(e, t = !1, n = !0) {
203
+ if (this.samples === 1) t && this.give(e);
204
+ else {
205
+ if (n && this.copyDepth(e, this.resolvedDepthView, 1), t) {
206
+ let t = this.viewContext?.view ? "store" : "discard";
207
+ this.finalResolution.colorAttachments[0].storeOp = t, this.finalResolution.depthStencilAttachment.depthStoreOp = t, this.give(e);
208
+ }
209
+ e.beginRenderPass(t ? this.finalResolution : this.resolution).end();
210
+ }
211
+ }
212
+ give(e) {
213
+ let t = this.original;
214
+ this.retired || !t || this.resized || (this.copyDepth(e, t.depth, t.descriptor.multisample?.count ?? 1, t.descriptor.depthStencil.format), this.retired = !0);
215
+ }
216
+ restore(e) {
217
+ let t = this.original;
218
+ this.give(e.encoder), Object.assign(e, {
219
+ color: t.color,
220
+ depth: t.depth,
221
+ format: t.format,
222
+ descriptor: t.descriptor
223
+ }), e[v] = t.owner;
224
+ }
225
+ present(e) {
226
+ this.resolve(e.encoder, !0), this.restore(e);
227
+ let t = e.descriptor.multisample?.count ?? 1;
228
+ if (!this.presentation || this.presentationFormat !== e.format || this.presentationSamples !== t) {
229
+ let n = this.device.createShaderModule({ code: g + "@group(0) @binding(0) var source:texture_2d<f32>;@fragment fn fragment(@builtin(position) p:vec4f)->@location(0) vec4f{return textureLoad(source,vec2i(p.xy),0);}" });
230
+ this.presentation = this.device.createRenderPipeline({
231
+ layout: "auto",
232
+ vertex: {
233
+ module: n,
234
+ entryPoint: "vertex"
235
+ },
236
+ fragment: {
237
+ module: n,
238
+ entryPoint: "fragment",
239
+ targets: [{ format: e.format }]
240
+ },
241
+ multisample: e.descriptor.multisample
242
+ }), this.presentationGroup = _(this.device, this.presentation, this.resolvedColor.createView()), this.presentationFormat = e.format, this.presentationSamples = t;
243
+ }
244
+ let n = this.presentationPass ??= { colorAttachments: [{
245
+ view: e.color,
246
+ loadOp: "clear",
247
+ storeOp: "store"
248
+ }] };
249
+ n.colorAttachments[0].view = e.color, n.colorAttachments[0].loadOp = s(e, "clear");
250
+ let r = e.encoder.beginRenderPass(n);
251
+ r.setPipeline(this.presentation), r.setBindGroup(0, this.presentationGroup), o(r, e), r.draw(3), r.end();
252
+ }
253
+ dispose() {
254
+ for (let e of this.textures) u(this.device, e);
255
+ this.textures = [], this.pipelines.clear();
256
+ }
257
+ };
258
+ function S(e) {
259
+ let t = e[v];
260
+ return t?.color === e.color && t.depth === e.depth ? t : void 0;
261
+ }
262
+ //#endregion
263
+ //#region ../shared/gpu.js
264
+ function C(e, t, n) {
265
+ return e.createBindGroup({
266
+ layout: t.getBindGroupLayout(0),
267
+ entries: n.map((e, t) => ({
268
+ binding: t,
269
+ resource: e
270
+ }))
271
+ });
272
+ }
273
+ function te(e, t, n, r = {}) {
274
+ let i = e.createShaderModule({ code: t });
275
+ return e.createRenderPipeline({
276
+ layout: "auto",
277
+ vertex: {
278
+ module: i,
279
+ entryPoint: "vertex"
280
+ },
281
+ fragment: {
282
+ module: i,
283
+ entryPoint: "fragment",
284
+ targets: [{ format: n }]
285
+ },
286
+ ...r
287
+ });
288
+ }
289
+ function w(e, t, n = "main") {
290
+ return e.createComputePipeline({
291
+ layout: "auto",
292
+ compute: {
293
+ module: e.createShaderModule({ code: t }),
294
+ entryPoint: n
295
+ }
296
+ });
297
+ }
298
+ //#endregion
299
+ //#region ../shared/output-key.js
300
+ var T = class {
301
+ format = "";
302
+ samples = -1;
303
+ hdr = !1;
304
+ straight = !1;
305
+ extra = void 0;
306
+ #e = "";
307
+ #t = -1;
308
+ #n = !1;
309
+ #r = !1;
310
+ #i = void 0;
311
+ changed(e, t, n) {
312
+ return this.format === e.format && this.samples === e.multisample.count && this.hdr === !!e.hdr && this.straight === t && this.extra === n ? !1 : (this.#e = e.format, this.#t = e.multisample.count, this.#n = !!e.hdr, this.#r = t, this.#i = n, !0);
313
+ }
314
+ done() {
315
+ this.format = this.#e, this.samples = this.#t, this.hdr = this.#n, this.straight = this.#r, this.extra = this.#i;
316
+ }
317
+ reset() {
318
+ this.format = "";
319
+ }
320
+ }, E = Symbol.for("margoengine.premultiplied-canvas"), D = (e) => !!e?.canvas?.[E], O = /vec4f\(toDisplay\(((?:[^()]|\((?:[^()]|\([^()]*\))*\))*)\),([\w.]+)\)/g;
321
+ function k(e) {
322
+ let t = 0, n = e.replace(O, (e, n, r) => (t++, `vec4f(toDisplayStraight(${n},${r}),${r})`));
323
+ if (!t && !e.includes("toDisplayStraight(")) throw RangeError("display shader has no vec4f(toDisplay(colour),alpha) output to convert; write the display output in that form or call toDisplayStraight(colour,alpha) itself");
324
+ return `${n}
325
+ fn toDisplayStraight(c:vec3f,a:f32)->vec3f {if(a>0.0&&a<1.0){return toDisplay(c/a)*a;}return toDisplay(c);}
326
+ `;
327
+ }
328
+ var A = (e, t) => D(e) && t.includes("fn toDisplay(") ? k(t) : t, j = "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", M = /let mapped=pbrNeutral\([\s\S]*?return vec4f\([^\n]+\);/, N = (e) => e.replace(M, "return vec4f(linear,1);"), P = (e) => `${e} requires the standard core lighting shader; remove the plugin that replaced core's shader`, F = "struct Params {lens:vec4f,frame:vec4f,ortho:vec4f}\n@group(0) @binding(0) var<uniform> p:Params;", I = "var<workgroup> lanes:array<f32,64>;\nvar<workgroup> rows:array<f32,8>;\nfn groupMax(v:f32,local:u32)->f32 {\n lanes[local]=v;workgroupBarrier();\n if(local<8u){var m=lanes[local*8u];for(var i=1u;i<8u;i++){m=max(m,lanes[local*8u+i]);}rows[local]=m;}\n workgroupBarrier();\n var m=rows[0];for(var i=1u;i<8u;i++){m=max(m,rows[i]);}return m;\n}", L = `${F}
329
+ @group(0) @binding(1) var depth:texture_depth_2d;
330
+ @group(0) @binding(2) var coc:texture_storage_2d<rg32float,write>;
331
+ @group(0) @binding(3) var tiles:texture_storage_2d<r32float,write>;
332
+ ${I}
333
+ @compute @workgroup_size(8,8) fn main(@builtin(global_invocation_id) id:vec3u,@builtin(workgroup_id) tile:vec3u,@builtin(local_invocation_index) local:u32) {
334
+ var near=0.0;
335
+ if(all(id.xy<textureDimensions(coc))){
336
+ let d=textureLoad(depth,vec2i(id.xy),0);
337
+ let ortho=p.ortho.x>0.5;
338
+ let z=select(p.frame.x*p.frame.y/(p.frame.x+d*(p.frame.y-p.frame.x)),mix(p.frame.y,p.frame.x,d),ortho);
339
+ let radius=clamp(p.frame.z*select(1.0-p.lens.x/z,(z-p.lens.x)/p.lens.x,ortho),-p.lens.w,p.lens.w)*p.frame.w;
340
+ textureStore(coc,vec2i(id.xy),vec4f(radius,z,0,0));near=-radius;
341
+ }
342
+ let m=groupMax(near,local);
343
+ if(local==0u){textureStore(tiles,vec2i(tile.xy),vec4f(m,0,0,0));}
344
+ }`, R = (e) => `var frontColor=vec3f(0);var frontWeight=0.0;var farTotal=farWeight;
345
+ for(var i=0u;i<${e}u;i++){
346
+ let farPixel=clamp(pixel+vec2i(round(spiral(i,${e}.0)*center.x)),vec2i(0),limit);
347
+ let farCoC=textureLoad(coc,farPixel,0).xy;let farW=1.0;farTotal+=farW;
348
+ if(farCoC.x>=0.0&&farCoC.y>=center.y-max(0.001,center.y*0.01)){farColor+=textureLoad(scene,farPixel,0).rgb;farWeight+=1.0;}
349
+ else if(farCoC.x>0.5){
350
+ let w=farW*covers(vec2f(farPixel-pixel),farCoC.x,pixel)*center.x*center.x/(farCoC.x*farCoC.x);
351
+ frontColor+=textureLoad(scene,farPixel,0).rgb*w;frontWeight+=w;
352
+ }
353
+ }
354
+ if(frontWeight>0.0){farColor=mix(farColor/farWeight,frontColor/frontWeight,min(frontWeight/farTotal,1.0));farWeight=1.0;}`, z = "@group(0) @binding(1) var scene:texture_2d<f32>;\n@group(0) @binding(2) var coc:texture_2d<f32>;\nfn spiral(i:u32,n:f32)->vec2f {\n let angle=f32(i)*2.39996323;\n return sqrt((f32(i)+0.5)/n)*vec2f(cos(angle),sin(angle));\n}\nfn covers(o:vec2f,radius:f32,pixel:vec2i)->f32 {return select(0.0,1.0,length(o)<=radius);}", B = `${F}
355
+ ${z}
356
+ @group(0) @binding(3) var coarse:texture_storage_2d<rgba16float,write>;
357
+ @compute @workgroup_size(8,8) fn main(@builtin(global_invocation_id) id:vec3u) {
358
+ if(any(id.xy>=textureDimensions(coarse))){return;}
359
+ let pixel=vec2i(id.xy)*2;let limit=vec2i(textureDimensions(coc))-1;let center=textureLoad(coc,pixel,0).xy;
360
+ var farColor=textureLoad(scene,pixel,0).rgb;var farWeight=1.0;
361
+ let wide=center.x>3.19&&p.frame.w!=0.0;
362
+ if(wide){${R(64)}}
363
+ textureStore(coarse,id.xy,vec4f(farColor/farWeight,select(0.0,center.y,wide)));
364
+ }`;
365
+ function V(e, t, n) {
366
+ return Math.min(128, e * t / n);
367
+ }
368
+ function H(e) {
369
+ let t = Math.max(Math.log2(e * .2215567 / 1.7320508), 0);
370
+ return Math.min(5, Math.max(3, Math.ceil(t)));
371
+ }
372
+ var U = `${F}
373
+ @group(0) @binding(1) var scene:texture_2d<f32>;
374
+ @group(0) @binding(2) var coc:texture_2d<f32>;
375
+ @group(0) @binding(3) var nearTaps:texture_storage_2d<rgba16float,write>;
376
+ @group(0) @binding(4) var nearShapes:texture_storage_2d<rgba16float,write>;
377
+ @group(0) @binding(5) var nearScene:texture_storage_2d<rgba16float,write>;
378
+ @compute @workgroup_size(8,8) fn main(@builtin(global_invocation_id) id:vec3u) {
379
+ if(any(id.xy>=textureDimensions(nearTaps))||p.frame.w==0.0){return;}
380
+ let at=vec2i(id.xy);let s=textureLoad(coc,at,0).xy;let color=textureLoad(scene,at,0).rgb;
381
+ let g=select(0.0,1.0/max(s.x*s.x,1.0),s.x< -0.5);
382
+ textureStore(nearTaps,at,vec4f(color*g,g));
383
+ textureStore(nearShapes,at,vec4f(-s.x*g,s.y*g,0,0));
384
+ textureStore(nearScene,at,vec4f(color,1));
385
+ }`, W = "@group(0) @binding(0) var tapsBelow:texture_2d<f32>;\n@group(0) @binding(1) var shapesBelow:texture_2d<f32>;\n@group(0) @binding(2) var sceneBelow:texture_2d<f32>;\n@group(0) @binding(3) var nearTaps:texture_storage_2d<rgba16float,write>;\n@group(0) @binding(4) var nearShapes:texture_storage_2d<rgba16float,write>;\n@group(0) @binding(5) var nearScene:texture_storage_2d<rgba16float,write>;\n@compute @workgroup_size(8,8) fn main(@builtin(global_invocation_id) id:vec3u) {\n if(any(id.xy>=textureDimensions(nearTaps))){return;}\n let last=vec2i(textureDimensions(tapsBelow))-1;var taps=vec4f(0);var shapes=vec4f(0);var plain=vec4f(0);\n for(var k=0;k<4;k++){\n let at=min(vec2i(id.xy)*2+vec2i(k%2,k/2),last);\n taps+=textureLoad(tapsBelow,at,0);shapes+=textureLoad(shapesBelow,at,0);plain+=textureLoad(sceneBelow,at,0);\n }\n textureStore(nearTaps,vec2i(id.xy),taps*0.25);\n textureStore(nearShapes,vec2i(id.xy),shapes*0.25);\n textureStore(nearScene,vec2i(id.xy),plain*0.25);\n}", G = (e, t) => `var ${e}=textureSampleLevel(${t},filtered,at,low);if(blend>0.0){${e}=mix(${e},textureSampleLevel(${t},filtered,at,low+1.0),blend);}`, K = `${F}
386
+ ${z}
387
+ @group(0) @binding(3) var result:texture_storage_2d<rgba16float,write>;
388
+ @group(0) @binding(4) var tiles:texture_2d<f32>;
389
+ @group(0) @binding(5) var coarse:texture_2d<f32>;
390
+ @group(0) @binding(6) var filtered:sampler;
391
+ @group(0) @binding(7) var nearTaps:texture_2d<f32>;
392
+ @group(0) @binding(8) var nearShapes:texture_2d<f32>;
393
+ @group(0) @binding(9) var nearScene:texture_2d<f32>;
394
+ ${I}
395
+ fn disk(i:u32)->vec2f {return spiral(i,64.0);}
396
+ const tapArea=1.0;
397
+ fn nearLod(radius:f32)->f32 {return max(log2(radius*0.2215567*sqrt(tapArea)/1.7320508),0.0);}
398
+ @compute @workgroup_size(8,8) fn main(@builtin(global_invocation_id) id:vec3u,@builtin(workgroup_id) tile:vec3u,@builtin(local_invocation_index) local:u32) {
399
+ let count=vec2i(textureDimensions(tiles));let footprint=1.5*exp2(min(ceil(nearLod(p.lens.w)),5.0));let reach=i32(ceil((p.lens.w+1.0+footprint)/8.0));let span=2*reach+1;
400
+ var mine=0.0;
401
+ for(var t=i32(local);t<span*span;t+=64){
402
+ let o=vec2i(t%span,t/span)-reach;let at=vec2i(tile.xy)+o;
403
+ if(all(at>=vec2i(0))&&all(at<count)){
404
+ let m=textureLoad(tiles,at,0).x;let gap=vec2f(max(abs(o)*8-7,vec2i(0)));
405
+ if(length(gap)<=m+1.0+footprint){mine=max(mine,m);}
406
+ }
407
+ }
408
+ let nearMax=groupMax(mine,local);
409
+ let size=textureDimensions(result);if(any(id.xy>=size)){return;}
410
+ let pixel=vec2i(id.xy);let center=textureLoad(coc,pixel,0).xy;
411
+ let sharp=textureLoad(scene,pixel,0);
412
+ if(p.frame.w==0.0){textureStore(result,pixel,sharp);return;}
413
+ var farColor=sharp.rgb;var farWeight=1.0;
414
+ var nearColor=vec3f(0);var nearWeight=0.0;var backColor=vec3f(0);var backWeight=0.0;
415
+ let limit=vec2i(size)-1;
416
+ if(center.x>3.19){
417
+ let q=pixel/2;let f=vec2f(pixel%2)*0.5;let last=vec2i(textureDimensions(coarse))-1;var up=vec4f(0);
418
+ for(var k=0;k<4;k++){
419
+ let o=vec2i(k%2,k/2);let w=mix(1.0-f.x,f.x,f32(o.x))*mix(1.0-f.y,f.y,f32(o.y));
420
+ let s=textureLoad(coarse,min(q+o,last),0);
421
+ if(w>0.0&&abs(s.w-center.y)<=0.05*center.y){up+=vec4f(s.rgb,1.0)*w;}
422
+ }
423
+ if(up.w>0.999){farColor=up.rgb;farWeight=up.w;}else{${R(64)}}
424
+ }else if(center.x>2.26){${R(32)}}else if(center.x>0.5){${R(16)}}
425
+ let reachTaps=select(0u,64u,nearMax>0.5);let R=min(p.lens.w,nearMax+1.0);let lod=min(nearLod(R),5.0);
426
+ let low=floor(lod);let blend=lod-low;
427
+ let nearSize=vec2f(textureDimensions(nearTaps));
428
+ for(var i=0u;i<reachTaps;i++){
429
+ let nearTap=disk(i)*R;let nearPixel=pixel+vec2i(round(nearTap));
430
+ if(any(nearPixel<vec2i(0))||any(nearPixel>limit)){continue;}
431
+ let at=(vec2f(pixel)+0.5+nearTap)/nearSize;${G("source", "nearTaps")}
432
+ var share=0.0;var tint=vec3f(0);
433
+ if(source.w>0.0){
434
+ ${G("nearForm", "nearShapes")}let form=nearForm.xy/source.w;let radius=form.x;tint=source.rgb/source.w;
435
+ if(form.y<=center.y+max(0.001,center.y*0.01)){
436
+ share=min(source.w*max(radius*radius,1.0),1.0);
437
+ let inside=clamp(radius-length(nearTap)+0.5,0.0,1.0);
438
+ let weight=R*R*source.w*inside;
439
+ nearColor+=tint*weight;nearWeight+=weight;
440
+ }
441
+ }
442
+ if(center.x< -0.5&&share<1.0&&covers(nearTap,-center.x,pixel)>0.0){
443
+ ${G("behind", "nearScene")}backColor+=max(behind.rgb-tint*share,vec3f(0));backWeight+=1.0-share;
444
+ }
445
+ }
446
+ if(center.x< -0.5){
447
+ let weight=R*R/(center.x*center.x);nearColor+=sharp.rgb*weight;nearWeight+=weight;
448
+ if(backWeight>0.0){farColor=backColor;farWeight=backWeight;}
449
+ }
450
+ let coverage=clamp(nearWeight/64.0,0.0,1.0);
451
+ let color=mix(farColor/farWeight,nearColor/max(nearWeight,0.0001),coverage);
452
+ textureStore(result,pixel,vec4f(color,sharp.a));
453
+ }`, q = `
454
+ @group(0) @binding(0) var scene:texture_2d<f32>;
455
+ @vertex fn vertex(@builtin(vertex_index) i:u32)->@builtin(position) vec4f {
456
+ let xy=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3));return vec4f(xy[i],0,1);
457
+ }
458
+ ${j}
459
+ @fragment fn fragment(@builtin(position) pos:vec4f)->@location(0) vec4f {
460
+ let c=textureLoad(scene,vec2i(pos.xy),0);return vec4f(toDisplay(c.rgb),c.a);
461
+ }`, J = `@group(0) @binding(0) var scene:texture_2d<f32>;
462
+ @group(0) @binding(1) var coc:texture_2d<f32>;
463
+ @group(0) @binding(2) var halfScene:texture_storage_2d<rgba16float,write>;
464
+ @group(0) @binding(3) var halfCoc:texture_storage_2d<rg32float,write>;
465
+ @group(0) @binding(4) var tiles:texture_storage_2d<r32float,write>;
466
+ ${I}
467
+ @compute @workgroup_size(8,8) fn main(@builtin(global_invocation_id) id:vec3u,@builtin(workgroup_id) tile:vec3u,@builtin(local_invocation_index) local:u32) {
468
+ var near=0.0;
469
+ if(all(id.xy<textureDimensions(halfCoc))){
470
+ let last=vec2i(textureDimensions(coc))-1;var color=vec4f(0);var c=vec2f(0,3.4e38);
471
+ for(var k=0;k<4;k++){
472
+ let at=min(vec2i(id.xy)*2+vec2i(k%2,k/2),last);color+=textureLoad(scene,at,0);
473
+ let s=textureLoad(coc,at,0).xy;if(s.y<c.y){c=s;}
474
+ }
475
+ textureStore(halfScene,vec2i(id.xy),color*0.25);textureStore(halfCoc,vec2i(id.xy),vec4f(c.x*0.5,c.y,0,0));near=-c.x*0.5;
476
+ }
477
+ let m=groupMax(near,local);
478
+ if(local==0u){textureStore(tiles,vec2i(tile.xy),vec4f(m,0,0,0));}
479
+ }`, Y = "@group(0) @binding(0) var scene:texture_2d<f32>;\n@group(0) @binding(1) var coc:texture_2d<f32>;\n@group(0) @binding(2) var blurred:texture_2d<f32>;\n@group(0) @binding(3) var result:texture_storage_2d<rgba16float,write>;\n@compute @workgroup_size(8,8) fn main(@builtin(global_invocation_id) id:vec3u) {\n if(any(id.xy>=textureDimensions(result))){return;}\n let pixel=vec2i(id.xy);let sharp=textureLoad(scene,pixel,0);\n let g=(vec2f(pixel)+0.5)*0.5-0.5;let q=vec2i(floor(g));let f=g-floor(g);let last=vec2i(textureDimensions(blurred))-1;\n let b=mix(mix(textureLoad(blurred,clamp(q,vec2i(0),last),0),textureLoad(blurred,clamp(q+vec2i(1,0),vec2i(0),last),0),f.x),\n mix(textureLoad(blurred,clamp(q+vec2i(0,1),vec2i(0),last),0),textureLoad(blurred,clamp(q+vec2i(1,1),vec2i(0),last),0),f.x),f.y);\n let w=max(smoothstep(0.5,1.5,abs(textureLoad(coc,pixel,0).x)),b.a);\n textureStore(result,pixel,vec4f(mix(sharp.rgb,b.rgb,w),sharp.a));\n}";
480
+ function X(e) {
481
+ let t = (e) => {
482
+ let t = e.split("f32(i)*2.39996323");
483
+ if (t.length < 2) throw new r("unsupported", "DOF temporal needs the gather kernels of its own version");
484
+ return t.join("(f32(i)*2.39996323+p.ortho.w)");
485
+ }, n = "textureStore(result,pixel,vec4f(color,sharp.a));", i = "if(p.frame.w==0.0){textureStore(result,pixel,sharp);return;}";
486
+ if (e.bokehShader.split(n).length !== 2 || e.bokehShader.split(i).length !== 2) throw new r("unsupported", "DOF temporal needs the gather kernels of its own version");
487
+ return {
488
+ ...e,
489
+ coarseShader: t(e.coarseShader),
490
+ bokehShader: t(e.bokehShader).replace(n, "textureStore(result,pixel,vec4f(color,coverage));").replace(i, "if(p.frame.w==0.0){textureStore(result,pixel,vec4f(sharp.rgb,0));return;}")
491
+ };
492
+ }
493
+ //#endregion
494
+ //#region src/alpha.ts
495
+ function Z(e, t) {
496
+ return t.reduce((e, [t, n, i]) => {
497
+ let a = e.split(t);
498
+ if (i === void 0 ? a.length < 2 : a.length !== i + 1) throw new r("unsupported", "DOF on a transparent canvas needs the gather kernels of its own version");
499
+ return a.join(n);
500
+ }, e);
501
+ }
502
+ var Q = [["var frontColor=vec3f(0)", "var frontColor=vec4f(0)"], ["textureLoad(scene,farPixel,0).rgb", "textureLoad(scene,farPixel,0)"]];
503
+ function ne(e, t) {
504
+ let n = Z(e.nearShader, [[
505
+ "vec4f(-s.x*g,s.y*g,0,0)",
506
+ "vec4f(-s.x*g,s.y*g,textureLoad(scene,at,0).a*g,0)",
507
+ 1
508
+ ], [
509
+ "textureStore(nearScene,at,vec4f(color,1));",
510
+ "textureStore(nearScene,at,textureLoad(scene,at,0));",
511
+ 1
512
+ ]]), r = Z(e.coarseShader, [
513
+ ...Q,
514
+ [
515
+ "@compute",
516
+ "@group(0) @binding(4) var coarseAlpha:texture_storage_2d<r32float,write>;\n@compute",
517
+ 1
518
+ ],
519
+ [
520
+ "var farColor=textureLoad(scene,pixel,0).rgb;",
521
+ "var farColor=textureLoad(scene,pixel,0);",
522
+ 1
523
+ ],
524
+ [
525
+ "textureStore(coarse,id.xy,vec4f(farColor/farWeight,select(0.0,center.y,wide)));",
526
+ "let tone=farColor/farWeight;textureStore(coarse,id.xy,vec4f(tone.rgb,select(0.0,center.y,wide)));textureStore(coarseAlpha,id.xy,vec4f(tone.a));",
527
+ 1
528
+ ]
529
+ ]), i = "@group(0) @binding(10) var coarseAlpha:texture_2d<f32>;\n" + (t ? "@group(0) @binding(11) var resultAlpha:texture_storage_2d<r32float,write>;\n" : ""), a = Z(e.bokehShader, [
530
+ ...Q,
531
+ [
532
+ "fn disk(i:u32)",
533
+ i + "fn disk(i:u32)",
534
+ 1
535
+ ],
536
+ [
537
+ "var farColor=sharp.rgb;",
538
+ "var farColor=sharp;",
539
+ 1
540
+ ],
541
+ [
542
+ "var nearColor=vec3f(0);",
543
+ "var nearColor=vec4f(0);",
544
+ 1
545
+ ],
546
+ [
547
+ "var backColor=vec3f(0);",
548
+ "var backColor=vec4f(0);",
549
+ 1
550
+ ],
551
+ [
552
+ "var up=vec4f(0);",
553
+ "var up=vec4f(0);var upAlpha=0.0;",
554
+ 1
555
+ ],
556
+ [
557
+ "up+=vec4f(s.rgb,1.0)*w;",
558
+ "up+=vec4f(s.rgb,1.0)*w;upAlpha+=textureLoad(coarseAlpha,min(q+o,last),0).r*w;",
559
+ 1
560
+ ],
561
+ [
562
+ "farColor=up.rgb;",
563
+ "farColor=vec4f(up.rgb,upAlpha);",
564
+ 1
565
+ ],
566
+ [
567
+ "var tint=vec3f(0);",
568
+ "var tint=vec4f(0);",
569
+ 1
570
+ ],
571
+ [
572
+ "tint=source.rgb/source.w;",
573
+ "tint=vec4f(source.rgb,nearForm.z)/source.w;",
574
+ 1
575
+ ],
576
+ [
577
+ "backColor+=max(behind.rgb-tint*share,vec3f(0));",
578
+ "backColor+=max(behind-tint*share,vec4f(0));",
579
+ 1
580
+ ],
581
+ [
582
+ "nearColor+=sharp.rgb*weight;",
583
+ "nearColor+=sharp*weight;",
584
+ 1
585
+ ]
586
+ ]), o = t ? Z(a, [[
587
+ "textureStore(result,pixel,vec4f(color,coverage));",
588
+ "textureStore(result,pixel,vec4f(color.rgb,coverage));textureStore(resultAlpha,pixel,vec4f(color.a));",
589
+ 1
590
+ ], [
591
+ "textureStore(result,pixel,vec4f(sharp.rgb,0));",
592
+ "textureStore(result,pixel,vec4f(sharp.rgb,0));textureStore(resultAlpha,pixel,vec4f(sharp.a));",
593
+ 1
594
+ ]]) : Z(a, [[
595
+ "textureStore(result,pixel,vec4f(color,sharp.a));",
596
+ "textureStore(result,pixel,color);",
597
+ 1
598
+ ]]), s = t ? Z(e.joinShader, [[
599
+ "@compute",
600
+ "@group(0) @binding(4) var blurredAlpha:texture_2d<f32>;\n@compute",
601
+ 1
602
+ ], [
603
+ "textureStore(result,pixel,vec4f(mix(sharp.rgb,b.rgb,w),sharp.a));",
604
+ "let a=mix(mix(textureLoad(blurredAlpha,clamp(q,vec2i(0),last),0).r,textureLoad(blurredAlpha,clamp(q+vec2i(1,0),vec2i(0),last),0).r,f.x),\n mix(textureLoad(blurredAlpha,clamp(q+vec2i(0,1),vec2i(0),last),0).r,textureLoad(blurredAlpha,clamp(q+vec2i(1,1),vec2i(0),last),0).r,f.x),f.y);\n textureStore(result,pixel,mix(sharp,vec4f(b.rgb,a),w));",
605
+ 1
606
+ ]]) : e.joinShader;
607
+ return {
608
+ ...e,
609
+ nearShader: n,
610
+ coarseShader: r,
611
+ bokehShader: o,
612
+ joinShader: s
613
+ };
614
+ }
615
+ //#endregion
616
+ //#region src/index.ts
617
+ var $ = (...e) => e.filter((e) => e !== void 0), re = class e {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
618
+ constructor(e = {}) {
619
+ this.options = e, this.name = "dof", this.nearViews = [], this.nearBase = [], this.nearLevels = [], this.waiting = !1, this.routeReady = Promise.resolve(), this.groups = [], this.values = /* @__PURE__ */ new Float32Array(12), this.halfValues = /* @__PURE__ */ new Float32Array(12), this.turn = 0, this.alpha = !1, this.shaders = /* @__PURE__ */ new Map(), this.attachment = {
620
+ view: void 0,
621
+ loadOp: "clear",
622
+ storeOp: "store"
623
+ }, this.presentation = { colorAttachments: [this.attachment] }, this.disposed = !1, this.key = new T(), this.validate();
624
+ }
625
+ static attach(t, r = {}) {__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));
626
+ let i = new e(r);
627
+ return n(t).use(i), i;
628
+ }
629
+ get depthTexture() {
630
+ return this.host ? this.host.depthTexture : this.depth;
631
+ }
632
+ get outputTexture() {
633
+ return this.paused ? this.scene : this.output;
634
+ }
635
+ get focalLength() {
636
+ return this.values[1] || (this.options.focalLength ?? .05);
637
+ }
638
+ get enabled() {
639
+ return this.options.enabled ?? !0;
640
+ }
641
+ set enabled(e) {
642
+ if (typeof e != "boolean") throw TypeError("DOF enabled must be boolean");
643
+ this.options.enabled = e;
644
+ }
645
+ joinStack(e) {
646
+ if (this.engine || this.host || this.disposed) throw new r("attached", "DOF is already attached; create a new DOF");
647
+ return this.host = e, {
648
+ kind: "hdr",
649
+ render: (e, t, n) => this.stage(e, t, n)
650
+ };
651
+ }
652
+ validate() {
653
+ let e = this.options, t = e.filmGauge, n = t === void 0 ? e.focalLength ?? .05 : 0, r = e.focalDistance ?? 5, i = e.aperture ?? 2.8, a = e.maxRadius ?? 16;
654
+ if (!Number.isFinite(Math.fround(n)) || t === void 0 && Math.fround(n) <= 0 || !Number.isFinite(Math.fround(r)) || Math.fround(r) <= Math.fround(n) || !Number.isFinite(Math.fround(i)) || Math.fround(i) <= 0 || !Number.isFinite(a) || a < 1 || a > 32 || e.referenceHeight !== void 0 && !(Number.isFinite(e.referenceHeight) && e.referenceHeight > 0) || e.enabled !== void 0 && typeof e.enabled != "boolean" || e.temporal !== void 0 && typeof e.temporal != "boolean") throw RangeError("Invalid DOF options; use focalLength > 0, focalDistance > focalLength, aperture > 0, maxRadius from 1 to 32, referenceHeight > 0 and a boolean enabled and temporal");
655
+ if (t !== void 0 && !(Number.isFinite(t) && t > 0) || e.sensorFit !== void 0 && ![
656
+ "auto",
657
+ "horizontal",
658
+ "vertical"
659
+ ].includes(e.sensorFit)) throw RangeError("Invalid DOF filmGauge or sensorFit; use millimetres > 0 and 'auto', 'horizontal' or 'vertical'");
660
+ }
661
+ setup(e) {
662
+ if (this.disposed || !e.gpu) throw new r(this.disposed ? "disposed" : "unsupported", "DOF requires WebGPU and a live effect; attach a new DOF to a WebGPU engine; see https://margoengine.com/errors#webgpu");
663
+ if (d(e.gpu, "DOF HDR processing", "half-float"), !this.host && (e.hasPlugin("ssao") || e.hasPlugin("bloom") || e.hasPlugin("post-processing") || e.hasPlugin("tonemap") && !e.hasPlugin(this.name))) throw new r("state", "DOF owns scene capture; attach it before Tonemap, without SSAO or PostProcessing");
664
+ this.engine = e, this.uniform = e.gpu.createBuffer({
665
+ size: 48,
666
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
667
+ }), this.build(D(e));
668
+ let t = this.uniform, n = m(e.gpu, () => import("./compat-CkmQH9nh.js"));
669
+ this.waiting = !!n, n?.then(({ dofCompatPipelines: e }) => {
670
+ this.uniform === t && (this.waiting = !1, this.compatPipelines = e, this.useCompat(), this.releaseTextures());
671
+ }, (e) => {
672
+ throw this.waiting = !1, e;
673
+ }), this.routeReady = h(n);
674
+ }
675
+ build(e) {
676
+ let t = this.engine.gpu, n = {
677
+ cocShader: L,
678
+ coarseShader: B,
679
+ bokehShader: K,
680
+ groupMax: I
681
+ }, r = this.options.lens?.shaders(n) ?? n, i = this.options.temporal === !0, a = {
682
+ ...i ? X(r) : r,
683
+ nearShader: U,
684
+ joinShader: Y
685
+ }, o = e ? ne(a, i) : a;
686
+ this.alpha = e, this.kernels = o, i && (this.halfUniform ??= t.createBuffer({
687
+ size: 48,
688
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
689
+ }), this.halvePipeline = w(t, J), this.joinPipeline = w(t, o.joinShader)), this.cocPipeline = t.createComputePipeline({
690
+ layout: "auto",
691
+ compute: {
692
+ module: t.createShaderModule({ code: o.cocShader }),
693
+ entryPoint: "main"
694
+ }
695
+ }), this.bokehPipeline = w(t, o.bokehShader), this.coarsePipeline = w(t, o.coarseShader), this.nearPipeline = w(t, o.nearShader), this.nearDownPipeline = w(t, W), this.nearSampler = t.createSampler({
696
+ magFilter: "linear",
697
+ minFilter: "linear",
698
+ mipmapFilter: "linear"
699
+ }), this.tilesPipeline = void 0, this.useCompat();
700
+ }
701
+ useCompat() {
702
+ let e = this.compatPipelines;
703
+ if (!e || !this.kernels) return;
704
+ let t = !!this.halfUniform, n = e(this.engine.gpu, this.kernels, t ? J : void 0);
705
+ ({coc: this.cocPipeline, tiles: this.tilesPipeline, bokeh: this.bokehPipeline} = n), t && (this.halvePipeline = n.halve);
706
+ }
707
+ get ready() {
708
+ return this.routeReady;
709
+ }
710
+ get paused() {
711
+ return this.waiting && !this.host;
712
+ }
713
+ registerPasses(e) {
714
+ e.add({
715
+ name: "dof:capture",
716
+ order: -55,
717
+ execute: (e) => {
718
+ e.backend === "webgpu" && this.capture(e);
719
+ }
720
+ }), !this.host && (e.add({
721
+ name: "dof:coc",
722
+ order: 29.8,
723
+ execute: (e) => {
724
+ e.backend === "webgpu" && !this.paused && this.circles(e);
725
+ }
726
+ }), e.add({
727
+ name: "dof:bokeh",
728
+ order: 29.9,
729
+ execute: (e) => {
730
+ e.backend === "webgpu" && !this.paused && this.blur(e);
731
+ }
732
+ }), e.add({
733
+ name: "dof:present",
734
+ order: 30,
735
+ execute: (e) => {
736
+ e.backend === "webgpu" && this.present(e);
737
+ }
738
+ }));
739
+ }
740
+ lens(e, t, n) {
741
+ let r = this.options.sensorFit ?? "auto";
742
+ return e / (2e3 * Math.tan(t * Math.PI / 360) * (r === "horizontal" || r === "auto" && n >= 1 ? n : 1));
743
+ }
744
+ capture(e) {
745
+ this.validate();
746
+ let n = D(this.engine);
747
+ n !== this.alpha && (this.releaseTextures(), this.build(n));
748
+ let i = this.options, o = this.values, [s, c] = a(e);
749
+ if (o[0] = i.focalDistance ?? 5, o[1] = i.filmGauge === void 0 ? i.focalLength ?? .05 : this.lens(i.filmGauge, e.camera.fov, s / c), !(Math.fround(o[0]) > Math.fround(o[1]))) throw RangeError(`DOF focalDistance must lie beyond the focal length the camera gives, ${o[1]}`);
750
+ o[2] = i.aperture ?? 2.8, o[3] = V(i.maxRadius ?? 16, c, i.referenceHeight ?? 1080), o[4] = e.camera.near, o[5] = e.camera.far, o[6] = o[1] * c / (4 * o[2] * (o[0] - o[1]) * Math.tan(e.camera.fov * Math.PI / 360)), o[7] = +this.enabled, o[8] = 0, o[11] = +(!!this.tilesPipeline && (e.descriptor.multisample?.count ?? 4) > 1);
751
+ let l = t(e.camera.matrix, e.camera.position);
752
+ if (l && (o[4] = l.near, o[5] = l.far, o[6] = o[1] * c * l.sy * o[0] / (4 * o[2] * (o[0] - o[1])), o[8] = 1), i.lens?.write(o, e.camera, s / c), !Number.isFinite(o[6])) throw RangeError("DOF lens scale exceeds float32; use a larger aperture or a focalDistance further from focalLength");
753
+ if (!this.host) {
754
+ if (this.engine.hasPlugin("ssao") || this.engine.hasPlugin("post-processing") || this.engine.hasPlugin("bloom")) throw new r("state", "DOF cannot share scene capture with another post effect; put both effects in one PostStack");
755
+ this.resize(e), this.originalColor = e.color, this.originalDepth = e.depth;
756
+ let t = this.shaders.get(e.shader);
757
+ if (t === void 0) {
758
+ if (t = N(e.shader), t === e.shader) throw new r("unsupported", P("DOF"));
759
+ this.shaders.set(e.shader, t);
760
+ }
761
+ e.shader = t, this.captureTarget.begin(e);
762
+ }
763
+ if (e.device.queue.writeBuffer(this.uniform, 0, o), this.halfUniform) {
764
+ let t = this.halfValues;
765
+ t.set(o), t[3] = o[3] / 2, t[11] = this.turn++ * 2.39996323 % (2 * Math.PI), e.device.queue.writeBuffer(this.halfUniform, 0, t);
766
+ }
767
+ }
768
+ resize(e) {
769
+ let t = e.descriptor.depthStencil.format;
770
+ if (this.presentPipeline && this.scene?.width === e.width && this.scene.height === e.height && this.format === e.format && this.depthFormat === t && this.captureTarget?.samples === (e.descriptor.multisample?.count ?? 4)) return;
771
+ this.releaseTextures(), this.format = e.format, this.depthFormat = t;
772
+ let n = GPUTextureUsage.TEXTURE_BINDING;
773
+ this.scene = e.device.createTexture({
774
+ size: [e.width, e.height],
775
+ format: "rgba16float",
776
+ usage: n | GPUTextureUsage.RENDER_ATTACHMENT
777
+ }), this.depth = e.device.createTexture({
778
+ size: [e.width, e.height],
779
+ format: t,
780
+ usage: n | GPUTextureUsage.RENDER_ATTACHMENT
781
+ }), this.targets(e.device, e.width, e.height), this.captureTarget = new ee(e.device, this.scene, this.depth, e.descriptor.multisample?.count ?? 4), this.sceneView = this.scene.createView(), this.depthView = this.depth.createView();
782
+ let r = this.cocView, i = this.outputView, a = this.tileView, o = this.coarseView, s = e.device.createShaderModule({ code: A(this.engine, q) });
783
+ this.presentPipeline = e.device.createRenderPipeline({
784
+ layout: "auto",
785
+ vertex: {
786
+ module: s,
787
+ entryPoint: "vertex"
788
+ },
789
+ fragment: {
790
+ module: s,
791
+ entryPoint: "fragment",
792
+ targets: [{ format: e.format }]
793
+ },
794
+ multisample: e.descriptor.multisample
795
+ }), this.groups = [
796
+ this.cocGroup(e.device, this.depth, !0),
797
+ this.halfUniform ? void 0 : e.device.createBindGroup({
798
+ layout: this.bokehPipeline.getBindGroupLayout(0),
799
+ entries: [
800
+ {
801
+ binding: 0,
802
+ resource: { buffer: this.uniform }
803
+ },
804
+ {
805
+ binding: 1,
806
+ resource: this.sceneView
807
+ },
808
+ {
809
+ binding: 2,
810
+ resource: r
811
+ },
812
+ {
813
+ binding: 3,
814
+ resource: i
815
+ },
816
+ {
817
+ binding: 4,
818
+ resource: a
819
+ },
820
+ {
821
+ binding: 5,
822
+ resource: o
823
+ },
824
+ {
825
+ binding: 6,
826
+ resource: this.nearSampler
827
+ },
828
+ ...this.nearViews.map((e, t) => ({
829
+ binding: 7 + t,
830
+ resource: e
831
+ })),
832
+ ...$(this.coarseAlphaView, this.blurredAlphaView).map((e, t) => ({
833
+ binding: 10 + t,
834
+ resource: e
835
+ }))
836
+ ]
837
+ }),
838
+ e.device.createBindGroup({
839
+ layout: this.presentPipeline.getBindGroupLayout(0),
840
+ entries: [{
841
+ binding: 0,
842
+ resource: i
843
+ }]
844
+ }),
845
+ this.halfUniform ? void 0 : C(e.device, this.coarsePipeline, [
846
+ { buffer: this.uniform },
847
+ this.sceneView,
848
+ r,
849
+ o,
850
+ ...$(this.coarseAlphaView)
851
+ ])
852
+ ], this.halfUniform || (this.groups[8] = this.nearGroup(e.device, { buffer: this.uniform }, this.sceneView, r)), this.halfUniform && this.halfGroups(e.device, this.sceneView);
853
+ }
854
+ halfGroups(e, t) {
855
+ let n = { buffer: this.halfUniform }, r = this.halfScene.createView(), i = this.halfCoc.createView(), a = this.halfTiles.createView(), o = this.blurred.createView();
856
+ this.groups[1] = C(e, this.bokehPipeline, [
857
+ n,
858
+ r,
859
+ i,
860
+ o,
861
+ a,
862
+ this.coarseView,
863
+ this.nearSampler,
864
+ ...this.nearViews,
865
+ ...$(this.coarseAlphaView, this.blurredAlphaView)
866
+ ]), this.groups[3] = C(e, this.coarsePipeline, [
867
+ n,
868
+ r,
869
+ i,
870
+ this.coarseView,
871
+ ...$(this.coarseAlphaView)
872
+ ]), this.groups[8] = this.nearGroup(e, n, r, i), this.groups[5] = C(e, this.halvePipeline, [
873
+ t,
874
+ this.cocView,
875
+ r,
876
+ i,
877
+ ...this.tilesPipeline ? [] : [a]
878
+ ]), this.groups[6] = C(e, this.joinPipeline, [
879
+ t,
880
+ this.cocView,
881
+ o,
882
+ this.outputView,
883
+ ...$(this.blurredAlphaView)
884
+ ]), this.tilesPipeline && (this.groups[7] = C(e, this.tilesPipeline, [i, a]));
885
+ }
886
+ nearGroup(e, t, n, r) {
887
+ return C(e, this.nearPipeline, [
888
+ t,
889
+ n,
890
+ r,
891
+ ...this.nearBase
892
+ ]);
893
+ }
894
+ cocGroup(e, t, n = !1) {
895
+ return this.tilesPipeline ? (this.tilesGroup = C(e, this.tilesPipeline, [this.cocView, this.tileView]), C(e, this.cocPipeline, [
896
+ { buffer: this.uniform },
897
+ t.createView({ aspect: "depth-only" }),
898
+ this.cocView
899
+ ])) : n ? e.createBindGroup({
900
+ layout: this.cocPipeline.getBindGroupLayout(0),
901
+ entries: [
902
+ {
903
+ binding: 0,
904
+ resource: { buffer: this.uniform }
905
+ },
906
+ {
907
+ binding: 1,
908
+ resource: t.createView({ aspect: "depth-only" })
909
+ },
910
+ {
911
+ binding: 2,
912
+ resource: this.cocView
913
+ },
914
+ {
915
+ binding: 3,
916
+ resource: this.tileView
917
+ }
918
+ ]
919
+ }) : C(e, this.cocPipeline, [
920
+ { buffer: this.uniform },
921
+ t.createView({ aspect: "depth-only" }),
922
+ this.cocView,
923
+ this.tileView
924
+ ]);
925
+ }
926
+ circles(e) {
927
+ this.dispatch(e, this.cocPipeline, this.groups[0]), this.tilesPipeline && !this.halvePipeline && this.dispatch(e, this.tilesPipeline, this.tilesGroup, 64), this.halvePipeline && this.dispatch(e, this.halvePipeline, this.groups[5], 16), this.tilesPipeline && this.halvePipeline && this.dispatch(e, this.tilesPipeline, this.groups[7], 128);
928
+ }
929
+ blur(e) {
930
+ let t = this.halvePipeline ? 2 : 1;
931
+ this.dispatch(e, this.nearPipeline, this.groups[8], 8 * t), this.nearLevels.slice(0, H(this.values[3])).forEach((n, r) => this.dispatch(e, this.nearDownPipeline, n, 16 * t << r)), this.dispatch(e, this.coarsePipeline, this.groups[3], 16 * t), this.dispatch(e, this.bokehPipeline, this.groups[1], 8 * t), this.joinPipeline && this.dispatch(e, this.joinPipeline, this.groups[6]);
932
+ }
933
+ dispatch(e, t, n, r = 8) {
934
+ t === this.cocPipeline && this.captureTarget?.resolve(e.encoder, !0);
935
+ let i = e.encoder.beginComputePass();
936
+ i.setPipeline(t), i.setBindGroup(0, n), i.dispatchWorkgroups(Math.ceil(e.width / r), Math.ceil(e.height / r)), i.end();
937
+ }
938
+ present(e) {
939
+ let t = this.paused;
940
+ t && (this.captureTarget.resolve(e.encoder, !0), this.groups[4] ??= C(e.device, this.presentPipeline, [this.sceneView])), this.attachment.view = this.originalColor, this.attachment.loadOp = s(e, "clear");
941
+ let n = e.encoder.beginRenderPass(this.presentation);
942
+ n.setPipeline(this.presentPipeline), n.setBindGroup(0, this.groups[t ? 4 : 2]), o(n, e), n.draw(3), n.end(), this.captureTarget.restore(e);
943
+ }
944
+ stage(e, t, n) {
945
+ let r = e.device, i = this.host.depthTexture;
946
+ if ((this.coc?.width !== e.width || this.coc.height !== e.height) && (this.releaseTextures(), this.targets(r, e.width, e.height)), this.sceneDepth !== i && (this.sceneDepth = i, this.groups[0] = this.cocGroup(r, i)), this.input !== t && this.halfUniform ? (this.input = t, this.halfGroups(r, t)) : this.input !== t && (this.input = t, this.groups[1] = C(r, this.bokehPipeline, [
947
+ { buffer: this.uniform },
948
+ t,
949
+ this.cocView,
950
+ this.outputView,
951
+ this.tileView,
952
+ this.coarseView,
953
+ this.nearSampler,
954
+ ...this.nearViews,
955
+ ...$(this.coarseAlphaView, this.blurredAlphaView)
956
+ ]), this.groups[3] = C(r, this.coarsePipeline, [
957
+ { buffer: this.uniform },
958
+ t,
959
+ this.cocView,
960
+ this.coarseView,
961
+ ...$(this.coarseAlphaView)
962
+ ]), this.groups[8] = this.nearGroup(r, { buffer: this.uniform }, t, this.cocView)), this.circles(e), this.blur(e), n.hdr) return this.outputView;
963
+ if (this.key.changed(n, D(this.engine))) {
964
+ let e = A(this.engine, q);
965
+ this.presentPipeline = te(r, e, n.format, { multisample: n.multisample }), this.groups[2] = C(r, this.presentPipeline, [this.outputView]), this.key.done();
966
+ }
967
+ this.attachment.view = n.view, this.attachment.loadOp = s(e, "clear");
968
+ let a = e.encoder.beginRenderPass(this.presentation);
969
+ a.setPipeline(this.presentPipeline), a.setBindGroup(0, this.groups[2]), o(a, e), a.draw(3), a.end();
970
+ }
971
+ targets(e, t, n) {
972
+ let r = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.STORAGE_BINDING;
973
+ this.coc = e.createTexture({
974
+ size: [t, n],
975
+ format: "rg32float",
976
+ usage: r
977
+ }), this.output = e.createTexture({
978
+ size: [t, n],
979
+ format: "rgba16float",
980
+ usage: r | GPUTextureUsage.COPY_SRC
981
+ }), this.tiles = e.createTexture({
982
+ size: [Math.ceil(t / 8), Math.ceil(n / 8)],
983
+ format: "r32float",
984
+ usage: r
985
+ });
986
+ let i = this.halfUniform ? 2 : 1, a = Math.ceil(t / i), o = Math.ceil(n / i);
987
+ if (this.coarse = e.createTexture({
988
+ size: [Math.ceil(a / 2), Math.ceil(o / 2)],
989
+ format: "rgba16float",
990
+ usage: r
991
+ }), this.halfUniform && (this.halfScene = e.createTexture({
992
+ size: [a, o],
993
+ format: "rgba16float",
994
+ usage: r
995
+ }), this.halfCoc = e.createTexture({
996
+ size: [a, o],
997
+ format: "rg32float",
998
+ usage: r
999
+ }), this.halfTiles = e.createTexture({
1000
+ size: [Math.ceil(a / 8), Math.ceil(o / 8)],
1001
+ format: "r32float",
1002
+ usage: r
1003
+ }), this.blurred = e.createTexture({
1004
+ size: [a, o],
1005
+ format: "rgba16float",
1006
+ usage: r
1007
+ })), this.alpha) {
1008
+ let t = (t) => e.createTexture({
1009
+ size: t,
1010
+ format: "r32float",
1011
+ usage: r
1012
+ });
1013
+ this.coarseAlpha = t([Math.ceil(a / 2), Math.ceil(o / 2)]), this.coarseAlphaView = this.coarseAlpha.createView(), this.halfUniform && (this.blurredAlpha = t([a, o]), this.blurredAlphaView = this.blurredAlpha.createView());
1014
+ }
1015
+ let s = Math.min(6, Math.floor(Math.log2(Math.max(a, o))) + 1), c = () => e.createTexture({
1016
+ size: [a, o],
1017
+ format: "rgba16float",
1018
+ usage: r,
1019
+ mipLevelCount: s
1020
+ }), l = [
1021
+ this.nearTaps = c(),
1022
+ this.nearShapes = c(),
1023
+ this.nearScene = c()
1024
+ ], u = (e) => l.map((t) => t.createView({
1025
+ baseMipLevel: e,
1026
+ mipLevelCount: 1
1027
+ }));
1028
+ this.nearViews = l.map((e) => e.createView()), this.nearBase = u(0);
1029
+ let d = this.nearBase;
1030
+ this.nearLevels = [];
1031
+ for (let t = 1; t < s; t++) {
1032
+ let n = u(t);
1033
+ this.nearLevels.push(C(e, this.nearDownPipeline, [...d, ...n])), d = n;
1034
+ }
1035
+ this.cocView = this.coc.createView(), this.outputView = this.output.createView(), this.tileView = this.tiles.createView(), this.coarseView = this.coarse.createView();
1036
+ }
1037
+ releaseTextures() {
1038
+ this.captureTarget?.dispose(), this.captureTarget = void 0, this.scene?.destroy(), this.depth?.destroy(), this.coc?.destroy(), this.output?.destroy(), this.tiles?.destroy(), this.coarse?.destroy(), this.halfScene?.destroy(), this.halfCoc?.destroy(), this.halfTiles?.destroy(), this.blurred?.destroy(), this.nearTaps?.destroy(), this.nearShapes?.destroy(), this.nearScene?.destroy(), this.coarseAlpha?.destroy(), this.blurredAlpha?.destroy(), this.coarseAlpha = this.blurredAlpha = this.coarseAlphaView = this.blurredAlphaView = void 0, this.nearTaps = this.nearShapes = this.nearScene = void 0, this.nearViews = this.nearBase = [], this.nearLevels = [], this.scene = this.depth = this.coc = this.output = this.tiles = this.coarse = void 0, this.halfScene = this.halfCoc = this.halfTiles = this.blurred = void 0, this.sceneView = this.depthView = void 0, this.groups = [], this.presentPipeline = void 0, this.input = this.sceneDepth = this.cocView = this.outputView = this.tileView = this.coarseView = void 0, this.key.reset();
1039
+ }
1040
+ release() {
1041
+ this.releaseTextures(), this.uniform?.destroy(), this.halfUniform?.destroy(), this.uniform = this.halfUniform = void 0, this.halvePipeline = this.joinPipeline = void 0, this.cocPipeline = this.bokehPipeline = this.coarsePipeline = this.tilesPipeline = void 0, this.nearPipeline = this.nearDownPipeline = void 0, this.kernels = this.compatPipelines = void 0, this.nearSampler = void 0, this.originalColor = this.originalDepth = void 0, this.shaders.clear();
1042
+ }
1043
+ onDeviceRestored(e) {
1044
+ if (!this.disposed) {
1045
+ this.release();
1046
+ try {
1047
+ this.setup(e);
1048
+ } catch (e) {
1049
+ throw this.dispose(), e;
1050
+ }
1051
+ }
1052
+ }
1053
+ dispose() {
1054
+ this.disposed || (this.disposed = !0, this.engine?.sceneOf(this)?.removePlugin(this.name), this.release(), this.engine = void 0);
1055
+ }
1056
+ [Symbol.dispose ?? Symbol()]() {
1057
+ this.dispose();
1058
+ }
1059
+ destroy() {
1060
+ this.dispose();
1061
+ }
1062
+ };
1063
+ //#endregion
1064
+ export { re as DOF };