@margoengine/oit 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/depth.js ADDED
@@ -0,0 +1,111 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const i=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { i as e, n as t, o as n, r } from "./pass-D7U8kWzv.js";
5
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
6
+ import { MargoError as a } from "@margoengine/math/errors";
7
+ //#region src/depth.ts
8
+ var o = 120, s = (e) => `
9
+ override margoKind:u32=0u;
10
+ struct MargoTransparent {@location(0) unused:vec4f}
11
+ @group(${e}) @binding(${o}) var<uniform> margoOIT:vec4f;
12
+ fn margoTransparentTint(share:vec4f)->MargoTransparent {var o:MargoTransparent; return o;}
13
+ fn margoTransparent(color:vec4f,i:Out)->MargoTransparent {
14
+ if(margoKind==1u||margoKind==2u||(margoKind==0u&&color.a<margoOIT.x)){discard;}
15
+ var o:MargoTransparent; return o;
16
+ }
17
+ `, c = 0, l = class l {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
18
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
19
+ let n = new l(t);
20
+ return i(e).use(n), n;
21
+ }
22
+ constructor({ order: e = 8.5, threshold: t = .1 } = {}) {
23
+ if (this.name = "oit-depth:" + c++, this.targets = [], this.blends = !0, this.depthWrite = !0, this.code = /* @__PURE__ */ new Map(), this.models = /* @__PURE__ */ new Set(), this.disposed = !1, !Number.isFinite(e) || e <= 0) throw RangeError("Invalid TransparentDepth order; use a number above 0");
24
+ if (!(t > 0 && t <= 1)) throw RangeError("Invalid TransparentDepth threshold; use a number above 0, at most 1");
25
+ this.order = e, this.threshold = t;
26
+ }
27
+ add(e) {
28
+ if (this.disposed || !this.engine) throw new a(this.disposed ? "disposed" : "state", this.disposed ? "TransparentDepth is disposed; create a new TransparentDepth" : "TransparentDepth.add needs TransparentDepth.attach(engine) first");
29
+ this.models.add(e);
30
+ let t = e.onDispose(() => this.models.delete(e));
31
+ return () => {
32
+ t(), this.models.delete(e);
33
+ };
34
+ }
35
+ velocity(e) {
36
+ return {
37
+ get shadowPrimitives() {
38
+ return e.tintPrimitives;
39
+ },
40
+ get disposed() {
41
+ return e.disposed;
42
+ }
43
+ };
44
+ }
45
+ setup(e) {
46
+ if (this.disposed) throw new a("disposed", "TransparentDepth is disposed; create a new TransparentDepth");
47
+ if (!e.gpu) throw new a("unsupported", "TransparentDepth requires WebGPU; use a WebGPU engine; see https://margoengine.com/errors#webgpu");
48
+ this.engine = e, this.device = e.gpu, this.uniform = e.gpu.createBuffer({
49
+ size: 16,
50
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
51
+ }), e.gpu.queue.writeBuffer(this.uniform, 0, new Float32Array([
52
+ this.threshold,
53
+ 0,
54
+ 0,
55
+ 0
56
+ ]));
57
+ }
58
+ registerPasses(e) {
59
+ e.add({
60
+ name: this.name,
61
+ order: this.order,
62
+ execute: (e) => {
63
+ e.backend === "webgpu" && this.render(e);
64
+ }
65
+ });
66
+ }
67
+ declarations(e) {
68
+ return t(this.code, e, s);
69
+ }
70
+ bindings() {
71
+ return [{
72
+ binding: o,
73
+ resource: { buffer: this.uniform }
74
+ }];
75
+ }
76
+ begin() {
77
+ if (this.pass) return this.pass;
78
+ let e = this.context, t = this.pass = e.encoder.beginRenderPass({
79
+ label: "oit:depth",
80
+ colorAttachments: [],
81
+ depthStencilAttachment: {
82
+ view: e.depth,
83
+ depthLoadOp: "load",
84
+ depthStoreOp: "store",
85
+ stencilReadOnly: !0
86
+ }
87
+ });
88
+ return n(t, e), t;
89
+ }
90
+ render(e) {
91
+ if (r(e.device, e.view ?? e), !this.disposed && this.models.size) {
92
+ this.context = e, this.pass = void 0;
93
+ try {
94
+ for (let t of this.models) t.drawTransparent(e, this);
95
+ } finally {
96
+ this.pass?.end(), this.pass = void 0, this.context = void 0;
97
+ }
98
+ }
99
+ }
100
+ onDeviceRestored(t) {
101
+ e(this.device, this.uniform), this.setup(t);
102
+ }
103
+ dispose() {
104
+ this.disposed || (this.disposed = !0, this.models.clear(), e(this.device, this.uniform), this.uniform = void 0, this.engine?.sceneOf(this)?.removePlugin(this.name));
105
+ }
106
+ [Symbol.dispose ?? Symbol()]() {
107
+ this.dispose();
108
+ }
109
+ };
110
+ //#endregion
111
+ export { l as TransparentDepth };
@@ -0,0 +1,85 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ import { type Engine, type PassContext } from '@margoengine/core/extension';
3
+ import { TransparentPass } from './pass.js';
4
+ export type { TransparentPass };
5
+ type Context = Extract<PassContext, {
6
+ backend: 'webgpu';
7
+ }>;
8
+ /** `ExactOIT` settings, fixed at construction. */
9
+ export interface ExactOITOptions {
10
+ /** Frame graph order of the transparent passes, as in `OITOptions`. Default 8. */
11
+ order?: number;
12
+ /** Nearest layers kept per pixel, 1 to 32; farther ones are left out. Default 8. */
13
+ layers?: number;
14
+ /** Starting list size in fragments per screen pixel; the list grows by itself. Above 0. Default 2. */
15
+ pool?: number;
16
+ }
17
+ /** What the last read-back frame stored, from `ExactOIT.stats`; it trails the picture by a few frames. */
18
+ export interface ExactOITStats {
19
+ /** Transparent fragments of that frame, those behind opaque surfaces included; multisampled, a GPU that runs the list shader once per sample (Apple) counts each sample. */
20
+ fragments: number;
21
+ /** Fragments the list holds now. */
22
+ capacity: number;
23
+ /** Fragments of that frame that found no room; above 0 only for the frames before the list grows, or at `limit`. */
24
+ dropped: number;
25
+ /** The most the device can hold in one storage binding. */
26
+ limit: number;
27
+ }
28
+ /**
29
+ * Exact order-independent transparency: `oit.add(model)` draws the model's BLEND primitives (gltf/pbr) or a transparent
30
+ * materials mesh into per-pixel lists, and the nearest `layers` of each pixel blend in true depth order, per fragment, so
31
+ * parts that cut through each other come out as sorted blending would if every pixel were sorted. Heavier than `OIT` in
32
+ * memory and time: use it where the result must be right, such as CAD glass. Models not added keep sorted blending.
33
+ * WebGPU only; needs storage buffers in fragment shaders.
34
+ * @throws RangeError from the constructor for an `order`, `layers` or `pool` out of range.
35
+ * @throws MargoError `'unsupported'` on a WebGL engine or a device without fragment storage buffers, `'disposed'` after
36
+ * `dispose()`, `'state'` from `add` before `attach`.
37
+ */
38
+ export declare class ExactOIT extends TransparentPass {
39
+ readonly targets: readonly GPUColorTargetState[];
40
+ readonly layers: number;
41
+ readonly layout: readonly GPUBindGroupLayoutEntry[];
42
+ private readonly poolShare;
43
+ private readonly code;
44
+ private readonly surfaceCode;
45
+ private readonly words;
46
+ private readonly values;
47
+ private uniform?;
48
+ /** This view's uniform binding while its models draw (a frame-arena slice for a second view). */
49
+ private binding?;
50
+ private heads?;
51
+ private nodes?;
52
+ private pixels;
53
+ private capacity;
54
+ private wanted;
55
+ private readonly pipelines;
56
+ private readonly sorters;
57
+ private readback?;
58
+ /** The fragment count was copied for the frame now being finished and waits to be mapped. */
59
+ private copied;
60
+ private mapping;
61
+ private counted;
62
+ static attach(engine: EngineKernel, options?: ExactOITOptions): ExactOIT;
63
+ constructor({ order, layers, pool }?: ExactOITOptions);
64
+ /** Fragment counts of a recent frame, and the list's size. */
65
+ get stats(): ExactOITStats;
66
+ private get limit();
67
+ setup(engine: Engine): void;
68
+ /** @internal gltf\/pbr transparency hook. */
69
+ declarations(group: number): string;
70
+ /** @internal Effect hook. */
71
+ surface(group: number): string;
72
+ /** @internal gltf\/pbr transparency hook. */
73
+ bindings(): GPUBindGroupEntry[];
74
+ /** @internal gltf\/pbr transparency hook: the list pass, begun on the first transparent draw of the frame. */
75
+ begin(): GPURenderPassEncoder;
76
+ /** Sizes the buffers for this view. Views of different sizes share the largest, so none is replaced mid-frame. */
77
+ private prepare;
78
+ /** A map ends unread only when the device is lost or the pass disposed: the count of a gone buffer means nothing. */
79
+ private readonly mapEnded;
80
+ /** Reads the count copied on an earlier frame. The list grows on the next frame after a read that found it short. */
81
+ private readCount;
82
+ protected render(c: Context): void;
83
+ protected release(): void;
84
+ protected freeDevice(): void;
85
+ }
package/dist/exact.js ADDED
@@ -0,0 +1,312 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const d=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { n as e, t } from "./compat-CLA5cArM.js";
5
+ import { a as n, i as r, n as i, o as a, r as o, t as s } from "./pass-D7U8kWzv.js";
6
+ import { i as c, r as l, t as u } from "./pass-DdYrWNpT.js";
7
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
8
+ import { MargoError as f } from "@margoengine/math/errors";
9
+ //#region src/exact.ts
10
+ var p = 120, m = 16, h = 268435455, g = (e) => `
11
+ override margoLinear:bool=false;
12
+ struct MargoTransparent {@location(0) unused:vec4f}
13
+ @group(${e}) @binding(${p}) var<uniform> margoOIT:vec4u;
14
+ @group(${e}) @binding(121) var<storage,read_write> margoHeads:array<atomic<u32>>;
15
+ @group(${e}) @binding(122) var<storage,read_write> margoNodes:array<vec4u>;
16
+ var<private> margoCoverage:u32;
17
+ fn margoTransparentAt(color:vec4f,clip:vec4f,depth:f32)->MargoTransparent {
18
+ var o:MargoTransparent; let a=clamp(color.a,0.0,1.0);
19
+ if(a>=1.0/1024.0){
20
+ let slot=atomicAdd(&margoHeads[margoOIT.y],1u)+1u;
21
+ if(slot<margoOIT.z){
22
+ let p=vec2u(clip.xy); let next=atomicExchange(&margoHeads[p.y*margoOIT.x+p.x],slot); let c=min(color.rgb,vec3f(65504.0));
23
+ margoNodes[slot]=vec4u(pack2x16float(c.rg),pack2x16float(vec2f(c.b,select(a,-a,margoLinear))),bitcast<u32>(clip.z),next|(margoCoverage<<28u));
24
+ }
25
+ }
26
+ return o;
27
+ }
28
+ `, _ = (e, t) => `
29
+ @group(0) @binding(0) var<uniform> u:vec4u;
30
+ @group(0) @binding(1) var<storage,read> heads:array<u32>;
31
+ @group(0) @binding(2) var<storage,read_write> nodes:array<vec4u>;
32
+ fn nearer(a:vec4u,b:vec4u)->bool {
33
+ let x=bitcast<f32>(a.z); let y=bitcast<f32>(b.z);
34
+ if(x!=y){return x>y;}
35
+ if(a.x!=b.x){return a.x>b.x;}
36
+ if(a.y!=b.y){return a.y>b.y;}
37
+ return ${t ? "false" : "(a.w>>28u)>(b.w>>28u)"};
38
+ }
39
+ @compute @workgroup_size(8,8) fn main(@builtin(global_invocation_id) g:vec3u) {
40
+ if(g.x>=u.x||g.y>=u.w){return;}
41
+ let first=heads[g.y*u.x+g.x];
42
+ if(first==0u){return;}
43
+ var kept:array<vec4u,${e}>; var count=0u; var slot=first;
44
+ while(slot!=0u){
45
+ let node=nodes[slot]; slot=node.w&${h}u;
46
+ if(count==${e}u&&${t ? "nearer(kept[count-1u],node)" : "!nearer(node,kept[count-1u])"}){continue;}
47
+ var at=count;
48
+ while(at>0u&&nearer(node,kept[at-1u])){at-=1u;}
49
+ ${t ? `if(at>0u&&all(node.xyz==kept[at-1u].xyz)){kept[at-1u].w|=node.w&~${h}u; continue;}\n if(at==${e}u){continue;}` : ""}
50
+ var to=min(count,${e - 1}u);
51
+ while(to>at){kept[to]=kept[to-1u]; to-=1u;}
52
+ kept[at]=node; count=min(count+1u,${e}u);
53
+ }
54
+
55
+ slot=first;
56
+ for(var k=0u;k<count;k+=1u){
57
+ let next=nodes[slot].w&${h}u; let last=k+1u==count;
58
+ nodes[slot]=vec4u(kept[k].xyz,(kept[k].w&~${h}u)|select(next,0u,last)); slot=next;
59
+ }
60
+ }
61
+ `, v = (e, t) => `
62
+ @group(0) @binding(0) var<uniform> u:vec4u;
63
+ @group(0) @binding(1) var<storage,read> heads:array<u32>;
64
+ @group(0) @binding(2) var<storage,read> nodes:array<vec4u>;
65
+ ${t === 2 ? "@group(0) @binding(3) var sceneMap:texture_2d<f32>;" + l : ""}
66
+ struct Layer {@builtin(position) position:vec4f, @location(0) @interpolate(flat) index:u32}
67
+ struct Result {@location(0) color:vec4f, @builtin(frag_depth) depth:f32, @builtin(sample_mask) mask:u32}
68
+ @vertex fn vertex(@builtin(vertex_index) i:u32,@builtin(instance_index) k:u32)->Layer {
69
+ return Layer(vec4f(f32(i&1u)*4-1,f32(i>>1u)*4-1,0,1),${e - 1}u-k);
70
+ }
71
+ @fragment fn fragment(v:Layer)->Result {
72
+ let p=vec2u(v.position.xy); var slot=heads[p.y*u.x+p.x];
73
+ for(var k=0u;k<v.index&&slot!=0u;k+=1u){slot=nodes[slot].w&${h}u;}
74
+ if(slot==0u){discard;}
75
+ let n=nodes[slot]; var c=vec4f(unpack2x16float(n.x),unpack2x16float(n.y));
76
+ ${[
77
+ "c.a=abs(c.a);",
78
+ "if(c.a<0.0){discard;}",
79
+ "if(c.a>0.0){discard;} c=overLinear(vec4f(c.rgb,-c.a),textureLoad(sceneMap,vec2i(v.position.xy),0));"
80
+ ][t]}
81
+ return Result(c,bitcast<f32>(n.z),n.w>>28u);
82
+ }
83
+ `, y = class l extends u {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
84
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
85
+ let n = new l(t);
86
+ return d(e).use(n), n;
87
+ }
88
+ constructor({ order: e = 8, layers: t = 8, pool: n = 2 } = {}) {
89
+ if (!Number.isInteger(t) || t < 1 || t > 32) throw RangeError("Invalid ExactOIT layers; use a whole number from 1 to 32");
90
+ if (!(n > 0 && Number.isFinite(n))) throw RangeError("Invalid ExactOIT pool; use a number above 0");
91
+ super(e), this.targets = [], this.layout = [
92
+ {
93
+ binding: p,
94
+ visibility: 2,
95
+ buffer: {}
96
+ },
97
+ {
98
+ binding: 121,
99
+ visibility: 2,
100
+ buffer: { type: "storage" }
101
+ },
102
+ {
103
+ binding: 122,
104
+ visibility: 2,
105
+ buffer: { type: "storage" }
106
+ }
107
+ ], this.code = /* @__PURE__ */ new Map(), this.surfaceCode = /* @__PURE__ */ new Map(), this.words = /* @__PURE__ */ new Uint32Array(4), this.values = new Float32Array(this.words.buffer), this.pixels = 0, this.capacity = 0, this.wanted = 0, this.pipelines = /* @__PURE__ */ new Map(), this.sorters = /* @__PURE__ */ new Map(), this.copied = !1, this.mapping = !1, this.counted = {
108
+ fragments: 0,
109
+ dropped: 0
110
+ }, this.mapEnded = () => {
111
+ this.mapping = !1;
112
+ }, this.layers = t, this.poolShare = n;
113
+ }
114
+ get stats() {
115
+ return {
116
+ ...this.counted,
117
+ capacity: this.capacity,
118
+ limit: this.limit
119
+ };
120
+ }
121
+ get limit() {
122
+ let { maxStorageBufferBindingSize: e, maxBufferSize: t } = this.device?.limits ?? {};
123
+ return Math.min(h, Math.floor(Math.min(e ?? 0, t ?? 0) / m));
124
+ }
125
+ setup(n) {
126
+ super.setup(n);
127
+ let r = n.gpu, i = r.limits.maxStorageBuffersInFragmentStage;
128
+ if (t(r) === "webgl2" || e(r) || i !== void 0 && i < 2) throw new f("unsupported", "ExactOIT needs storage buffers in fragment shaders; use OIT on this device");
129
+ this.uniform = r.createBuffer({
130
+ size: 16,
131
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
132
+ }), this.readback = r.createBuffer({
133
+ size: 4,
134
+ usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST
135
+ });
136
+ }
137
+ declarations(e) {
138
+ return i(this.code, e, (e) => this.surface(e) + c);
139
+ }
140
+ surface(e) {
141
+ return i(this.surfaceCode, e, g);
142
+ }
143
+ bindings() {
144
+ return [
145
+ {
146
+ binding: p,
147
+ resource: this.binding ?? { buffer: this.uniform }
148
+ },
149
+ {
150
+ binding: 121,
151
+ resource: { buffer: this.heads }
152
+ },
153
+ {
154
+ binding: 122,
155
+ resource: { buffer: this.nodes }
156
+ }
157
+ ];
158
+ }
159
+ begin() {
160
+ if (this.pass) return this.pass;
161
+ let e = this.context, t = this.pass = e.encoder.beginRenderPass({
162
+ label: "oit:list",
163
+ colorAttachments: [],
164
+ depthStencilAttachment: {
165
+ view: e.depth,
166
+ depthReadOnly: !0,
167
+ stencilReadOnly: !0
168
+ }
169
+ });
170
+ return a(t, e), t;
171
+ }
172
+ prepare(e) {
173
+ let t = e.width * e.height, n = this.limit, i = Math.min(n, Math.max(this.wanted, Math.ceil(t * this.poolShare) + 1, this.capacity));
174
+ t > this.pixels && (r(this.device, this.heads), this.pixels = t, this.heads = e.device.createBuffer({
175
+ label: "oit:heads",
176
+ size: (t + 1) * 4,
177
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC
178
+ })), i > this.capacity && (r(this.device, this.nodes), this.capacity = i, this.nodes = e.device.createBuffer({
179
+ label: "oit:nodes",
180
+ size: i * m,
181
+ usage: GPUBufferUsage.STORAGE
182
+ }));
183
+ }
184
+ readCount() {
185
+ if (!this.copied || this.mapping) return;
186
+ let e = this.readback;
187
+ this.copied = !1, this.mapping = !0, e.mapAsync(GPUMapMode.READ).then(() => {
188
+ if (this.readback !== e) return this.mapEnded();
189
+ let t = new Uint32Array(e.getMappedRange())[0];
190
+ e.unmap();
191
+ let n = this.capacity - 1;
192
+ this.counted = {
193
+ fragments: t,
194
+ dropped: Math.max(0, t - n)
195
+ }, t > n && (this.wanted = Math.ceil(t * 1.25) + 1), this.mapping = !1;
196
+ }, this.mapEnded);
197
+ }
198
+ render(e) {
199
+ if (o(e.device, e.view ?? e), this.disposed || this.empty) return;
200
+ this.readCount(), this.prepare(e), this.words.set([
201
+ e.width,
202
+ e.width * e.height,
203
+ this.capacity,
204
+ e.height
205
+ ]), this.binding = n(e.device, this.uniform, this.values, e.view ?? e);
206
+ let t = this.binding ?? { buffer: this.uniform }, r = (e.width * e.height + 1) * 4, i = e.device;
207
+ e.encoder.clearBuffer(this.heads, 0, r);
208
+ let c;
209
+ try {
210
+ if (!this.drawModels(e)) return;
211
+ c = this.scene;
212
+ } finally {
213
+ this.binding = void 0, this.scene = void 0;
214
+ }
215
+ !this.mapping && !this.copied && (e.encoder.copyBufferToBuffer(this.heads, r - 4, this.readback, 0, 4), this.copied = !0);
216
+ let l = e.descriptor.multisample?.count ?? 1, u = l > 1, d = this.sorters.get(u);
217
+ d || this.sorters.set(u, d = i.createComputePipeline({
218
+ label: "oit:sort",
219
+ layout: "auto",
220
+ compute: {
221
+ module: i.createShaderModule({ code: _(this.layers, u) }),
222
+ entryPoint: "main"
223
+ }
224
+ }));
225
+ let f = [
226
+ {
227
+ binding: 0,
228
+ resource: t
229
+ },
230
+ {
231
+ binding: 1,
232
+ resource: { buffer: this.heads }
233
+ },
234
+ {
235
+ binding: 2,
236
+ resource: { buffer: this.nodes }
237
+ }
238
+ ], p = e.encoder.beginComputePass({ label: "oit:sort" });
239
+ p.setPipeline(d), p.setBindGroup(0, i.createBindGroup({
240
+ layout: d.getBindGroupLayout(0),
241
+ entries: f
242
+ })), p.dispatchWorkgroups(Math.ceil(e.width / 8), Math.ceil(e.height / 8)), p.end();
243
+ let m = e.descriptor.depthStencil.format, h = (t) => {
244
+ let n = e.format + l + m + t, r = this.pipelines.get(n);
245
+ if (!r) {
246
+ let a = i.createShaderModule({ code: v(this.layers, t) });
247
+ this.pipelines.set(n, r = i.createRenderPipeline({
248
+ label: "oit:resolve",
249
+ layout: "auto",
250
+ vertex: {
251
+ module: a,
252
+ entryPoint: "vertex"
253
+ },
254
+ fragment: {
255
+ module: a,
256
+ entryPoint: "fragment",
257
+ targets: [{
258
+ format: e.format,
259
+ blend: t === 2 ? void 0 : s
260
+ }]
261
+ },
262
+ depthStencil: {
263
+ format: m,
264
+ depthWriteEnabled: !1,
265
+ depthCompare: "greater-equal"
266
+ },
267
+ multisample: { count: l }
268
+ }));
269
+ }
270
+ return r;
271
+ }, g = () => {
272
+ let t = e.encoder.beginRenderPass({
273
+ label: "oit:resolve",
274
+ colorAttachments: [{
275
+ view: e.color,
276
+ loadOp: "load",
277
+ storeOp: "store"
278
+ }],
279
+ depthStencilAttachment: {
280
+ view: e.depth,
281
+ depthReadOnly: !0,
282
+ stencilReadOnly: !0
283
+ }
284
+ });
285
+ return a(t, e), t;
286
+ }, y = (e, t = []) => i.createBindGroup({
287
+ layout: e.getBindGroupLayout(0),
288
+ entries: [...f, ...t]
289
+ });
290
+ if (!c) {
291
+ let e = g(), t = h(0);
292
+ e.setPipeline(t), e.setBindGroup(0, y(t)), e.draw(3, this.layers), e.end();
293
+ return;
294
+ }
295
+ let b = h(1), x = h(2), S = y(b), C;
296
+ for (let e = 0; e < this.layers; e++) {
297
+ let t = c(), n = g();
298
+ C ??= y(x, [{
299
+ binding: 3,
300
+ resource: t
301
+ }]), n.setPipeline(b), n.setBindGroup(0, S), n.draw(3, 1, 0, e), n.setPipeline(x), n.setBindGroup(0, C), n.draw(3, 1, 0, e), n.end();
302
+ }
303
+ }
304
+ release() {
305
+ r(this.device, this.heads), r(this.device, this.nodes), this.heads = this.nodes = void 0, this.pixels = this.capacity = 0;
306
+ }
307
+ freeDevice() {
308
+ this.release(), this.pipelines.clear(), this.sorters.clear(), r(this.device, this.uniform), r(this.device, this.readback), this.uniform = this.readback = void 0, this.copied = !1;
309
+ }
310
+ };
311
+ //#endregion
312
+ export { y as ExactOIT };
@@ -0,0 +1,68 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type Engine, type PassContext } from '@margoengine/core/extension';
4
+ import { TransparentPass } from './pass.js';
5
+ type Context = Extract<PassContext, {
6
+ backend: 'webgpu';
7
+ }>;
8
+ /** Weighted blended OIT settings, fixed at construction. */
9
+ export interface OITOptions {
10
+ /** Frame graph order of the transparent and composite passes: after the scene and its overlays (edges 6), before SSAO (10), TAA (9) and post composites (30). Default 8. */
11
+ order?: number;
12
+ /** World distance the depth weight is centred on (where a nearer layer starts to dominate). Default: the camera's distance to its target, every frame. */
13
+ depthScale?: number;
14
+ /**
15
+ * Also takes additive and multiply materials and native transmission (a transmission hook keeps its own), so tints and
16
+ * glows blend in any order. Costs one more `rgba16float` target, an `r8unorm` mark for `blendSpace: 'linear'` layers
17
+ * and a second composite draw. Default false.
18
+ */
19
+ blending?: boolean;
20
+ }
21
+ /**
22
+ * Order-independent transparency: `oit.add(model)` draws the model's BLEND primitives (gltf/pbr) or a transparent
23
+ * materials mesh into an accumulation (rgba16float, additive) and a revealage (rg16float, multiplicative) target, depth
24
+ * tested against the opaque scene, then composites them over it, so overlapping transparent parts no longer pop as the
25
+ * camera moves. Materials with `blendSpace: 'linear'` go in too: on a display-encoded target the pixels they touch
26
+ * composite in linear light from the native glass snapshot (from the frame after one first draws; README "Linear-light layers"). Models not added keep gltf/pbr's sorted blending. WebGPU only.
27
+ * @throws RangeError from the constructor when `order` is not > 0 or `depthScale` not a positive number.
28
+ * @throws MargoError `'unsupported'` on a WebGL engine, `'disposed'` after `dispose()`, `'state'` from `add` before
29
+ * `attach`.
30
+ */
31
+ export declare class OIT extends TransparentPass {
32
+ readonly targets: readonly GPUColorTargetState[];
33
+ readonly blends: boolean;
34
+ private readonly depthScale?;
35
+ readonly layout: readonly GPUBindGroupLayoutEntry[];
36
+ private readonly code;
37
+ private readonly surfaceCode;
38
+ private readonly values;
39
+ private uniform?;
40
+ /** This view's uniform binding while its models draw (a frame-arena slice for a second view). */
41
+ private binding?;
42
+ private textures;
43
+ private views;
44
+ private size;
45
+ private readonly pipelines;
46
+ private readonly blendedPipelines;
47
+ private readonly groups;
48
+ private readonly linearPipelines;
49
+ private linearGroup?;
50
+ static attach(engine: EngineKernel, options?: OITOptions): OIT;
51
+ constructor({ order, depthScale, blending }?: OITOptions);
52
+ setup(engine: Engine): void;
53
+ /** @internal gltf\/pbr transparency hook. */
54
+ declarations(group: number): string;
55
+ /** @internal Effect hook. */
56
+ surface(group: number): string;
57
+ /** @internal gltf\/pbr transparency hook. */
58
+ bindings(): GPUBindGroupEntry[];
59
+ /** @internal gltf\/pbr transparency hook: the accumulation pass, begun on the first transparent draw of the frame. */
60
+ begin(): GPURenderPassEncoder;
61
+ protected render(c: Context): void;
62
+ /** KB3148d: the linear-light composite of the pixels a `blendSpace: 'linear'` layer touched, blending off. */
63
+ private drawLinear;
64
+ private compositeBlended;
65
+ protected release(): void;
66
+ protected freeDevice(): void;
67
+ }
68
+ export {};