@margoengine/html 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,88 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type FrameGraph } from '@margoengine/core/extension';
4
+ import { LabelRenderer, type Label, type CSS3DObject, type LabelRendererOptions, type LabelOptions } from '@margoengine/labels';
5
+ export type { Label, CSS3DObject } from '@margoengine/labels';
6
+ export type { LabelOptions, CSS3DOptions, LabelInfo } from '@margoengine/labels';
7
+ /**
8
+ * Options of HTML: label renderer options plus optional depth-texture occlusion, the anchor capacity and a depth bias.
9
+ */
10
+ export interface HTMLOptions extends LabelRendererOptions {
11
+ depth?: false | (() => GPUTexture | undefined);
12
+ /** Most anchors at once, 1 to 1,048,576 (default 1024). Storage starts at 64 slots and doubles as anchors are added. */
13
+ capacity?: number;
14
+ depthBias?: number;
15
+ /**
16
+ * Fade an anchor as geometry covers it instead of hiding it at once: its element's opacity follows the share of a
17
+ * grid of depth tests around the anchor that pass. `true` uses the defaults of {@link HTMLFadeOptions}. Default off.
18
+ */
19
+ fade?: boolean | HTMLFadeOptions;
20
+ }
21
+ /** How HTML fades partly occluded anchors. */
22
+ export interface HTMLFadeOptions {
23
+ /** Half the side of the sampled square around the anchor, in CSS pixels, 0 to 256. Default 8. */
24
+ radius?: number;
25
+ /** Depth tests per side of the square's grid, 2 to 8. Default 4 (16 tests an anchor). */
26
+ samples?: number;
27
+ /** Seconds the opacity takes to go from 1 to 0, 0 to 10; 0 follows each result at once. Default 0.15. */
28
+ duration?: number;
29
+ }
30
+ /** DOM projection from labels, with asynchronous rendered-depth occlusion for 2D anchors. */
31
+ export declare class HTML extends LabelRenderer {
32
+ private readonly settings;
33
+ private runtime?;
34
+ private readonly records;
35
+ private readonly slots;
36
+ /** Point data of every slot up to `allocated`; grows by doubling as anchors are added. */
37
+ private values;
38
+ private readonly capacity;
39
+ /** Slots with storage on the CPU, and on the GPU (the GPU buffers grow at the next depth sample). */
40
+ private allocated;
41
+ private gpuSlots;
42
+ /** One past the highest slot ever used: per-frame work runs to here, not to `capacity`. */
43
+ private used;
44
+ private readonly free;
45
+ private shared?;
46
+ private source?;
47
+ private input?;
48
+ private output?;
49
+ private read?;
50
+ private pipeline?;
51
+ private pending;
52
+ private generation;
53
+ private disposed;
54
+ private sampledDepth?;
55
+ private depthGroup?;
56
+ /** Snapshot of the slots submitted with the current depth read. The next sample waits until that read finishes. */
57
+ private readonly depthRequests;
58
+ private readonly fade?;
59
+ private radius?;
60
+ private readonly radiusValues;
61
+ private delta;
62
+ private glOcclusion?;
63
+ constructor(settings?: HTMLOptions);
64
+ static attach(engine: EngineKernel, options?: HTMLOptions): HTML;
65
+ add(element: HTMLElement, options?: LabelOptions): Label;
66
+ private grow;
67
+ remove(item: Label | CSS3DObject): void;
68
+ setup(instance: EngineKernel): void;
69
+ private setupGPU;
70
+ /** Point, result and readback buffers for `allocated` slots. Only called while no depth read is in flight. */
71
+ private buffers;
72
+ onPreUpdate(delta: number): void;
73
+ /** Positions every anchor; with `fade`, first moves each opacity toward its visible share, then writes it. */
74
+ update(): void;
75
+ registerPasses(graph: FrameGraph): void;
76
+ private sample;
77
+ /**
78
+ * WebGL2: reads every finished query round, then draws a new round for each anchor that has none in flight. Results
79
+ * become available a frame or more later (WebGL 2.0 never makes them available in the frame that issued them).
80
+ */
81
+ private query;
82
+ private releaseGL;
83
+ /** Frees this overlay's own GPU objects; with `lease`, also its share of the scene depth (which restores itself). */
84
+ private release;
85
+ onDeviceRestored(): void;
86
+ dispose(): void;
87
+ [Symbol.dispose]: () => void;
88
+ }
package/dist/index.js ADDED
@@ -0,0 +1,599 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const r=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { t as e } from "./errors-fc4i1pSL.js";
5
+ import { n as t, t as n } from "./view-rect-Be4T67Kk.js";
6
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
7
+ import { LabelRenderer as i } from "@margoengine/labels";
8
+ //#region ../shared/frame-resources.js
9
+ var a = (globalThis[Symbol.for("margoengine.frame-resources")] ??= { devices: /* @__PURE__ */ new WeakMap() }).devices;
10
+ function o(e) {
11
+ let t = a.get(e);
12
+ return t || (a.set(e, t = {
13
+ frame: 0,
14
+ open: !1,
15
+ lost: !1,
16
+ views: /* @__PURE__ */ new Set(),
17
+ drawing: 0,
18
+ retired: [],
19
+ written: /* @__PURE__ */ new WeakMap()
20
+ }), e.lost?.then?.(() => {
21
+ t.lost = !0;
22
+ let e = t.retired;
23
+ t.retired = [];
24
+ for (let t of e) t.destroy();
25
+ })), t;
26
+ }
27
+ function s(e, t) {
28
+ if (!t) return;
29
+ let n = o(e), r = [t, ...n.written.get(t)?.extras ?? []];
30
+ if (n.written.delete(t), !n.lost && n.open && (n.views.size > 1 || n.drawing > 0)) n.retired.push(...r);
31
+ else for (let e of r) e.destroy();
32
+ }
33
+ function c(e) {
34
+ return e?.adapterInfo?.vendor === "margo-webgl2" ? "webgl2" : "native";
35
+ }
36
+ function l(e) {
37
+ return c(e) === "native" && e?.features?.has("core-features-and-limits") === !1;
38
+ }
39
+ //#endregion
40
+ //#region ../shared/msaa.js
41
+ var u = "@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);}", d = (e, t, n) => e.createBindGroup({
42
+ layout: t.getBindGroupLayout(0),
43
+ entries: [{
44
+ binding: 0,
45
+ resource: n
46
+ }]
47
+ }), f = Symbol.for("margoengine.optional.msaa"), p = u + "\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}";
48
+ function m(e, t, n, r, i, a = !1) {
49
+ let o = (e) => p.replace(/return max[^;]+;/, `return textureLoad(source,q,${e});`), s = (n, r) => {
50
+ let a = e.createShaderModule({ code: n }), o = e.createRenderPipeline({
51
+ layout: "auto",
52
+ vertex: {
53
+ module: a,
54
+ entryPoint: "vertex"
55
+ },
56
+ fragment: {
57
+ module: a,
58
+ entryPoint: "fragment",
59
+ targets: []
60
+ },
61
+ depthStencil: {
62
+ format: i,
63
+ depthWriteEnabled: !0,
64
+ depthCompare: "always"
65
+ },
66
+ multisample: r
67
+ });
68
+ return {
69
+ pipeline: o,
70
+ group: d(e, o, t)
71
+ };
72
+ };
73
+ return {
74
+ draws: a ? [s(o(0).replace("_multisampled", ""), { count: r })] : r === 4 ? l(e) ? [
75
+ 0,
76
+ 1,
77
+ 2,
78
+ 3
79
+ ].map((e) => s(o(e), {
80
+ count: r,
81
+ mask: 1 << e
82
+ })) : [s(o("i32(sample)").replace("p:vec4f)", "p:vec4f,@builtin(sample_index) sample:u32)"), { count: r })] : [s(p, { count: r })],
83
+ descriptor: {
84
+ colorAttachments: [],
85
+ depthStencilAttachment: {
86
+ view: n,
87
+ depthLoadOp: "clear",
88
+ depthClearValue: 0,
89
+ depthStoreOp: "store",
90
+ stencilReadOnly: !0
91
+ }
92
+ }
93
+ };
94
+ }
95
+ var h = class {
96
+ constructor(e, t, n, r = 4) {
97
+ if (r !== 1 && r !== 4) throw RangeError("Scene samples must be 1 or 4");
98
+ this.samples = r, this.device = e, this.resolvedColor = t, this.resolvedDepth = n, this.textures = [], this.pipelines = /* @__PURE__ */ new Map();
99
+ try {
100
+ if (r === 1) {
101
+ this.color = t.createView(), this.depth = n.createView();
102
+ return;
103
+ }
104
+ for (let r of [t, n]) this.textures.push(e.createTexture({
105
+ size: [r.width, r.height],
106
+ format: r.format,
107
+ sampleCount: 4,
108
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
109
+ }));
110
+ this.color = this.textures[0].createView(), this.depth = this.textures[1].createView(), this.resolution = { colorAttachments: [{
111
+ view: this.color,
112
+ resolveTarget: t.createView(),
113
+ loadOp: "load",
114
+ storeOp: "store"
115
+ }] }, this.finalResolution = {
116
+ colorAttachments: [{
117
+ ...this.resolution.colorAttachments[0],
118
+ storeOp: "discard"
119
+ }],
120
+ depthStencilAttachment: {
121
+ view: this.depth,
122
+ depthLoadOp: "load",
123
+ depthStoreOp: "discard",
124
+ stencilReadOnly: !0
125
+ }
126
+ }, this.depthSource = this.textures[1].createView({ aspect: "depth-only" }), this.resolvedDepthView = n.createView();
127
+ } catch (e) {
128
+ throw this.dispose(), e;
129
+ }
130
+ }
131
+ begin(e) {
132
+ (this.viewContext ??= {}).view = e.view, Object.assign(this.original ??= {}, {
133
+ color: e.color,
134
+ depth: e.depth,
135
+ format: e.format,
136
+ descriptor: e.descriptor,
137
+ owner: g(e)
138
+ }), e.color = this.color, e.depth = this.depth, e.format = this.resolvedColor.format, this.baseDescriptor !== e.descriptor && (this.baseDescriptor = e.descriptor, this.descriptor = {
139
+ ...e.descriptor,
140
+ depthStencil: {
141
+ ...e.descriptor.depthStencil,
142
+ format: this.resolvedDepth.format
143
+ },
144
+ multisample: { count: this.samples }
145
+ }), e.descriptor = this.descriptor, e[f] = this, this.retired = !1;
146
+ }
147
+ copyDepth(e, t, r, i = this.resolvedDepth.format) {
148
+ let a = this.pipelines.get(r);
149
+ a || this.pipelines.set(r, a = /* @__PURE__ */ new Map());
150
+ let o = a.get(i);
151
+ o || (this.depthSource ??= this.resolvedDepth.createView({ aspect: "depth-only" }), a.set(i, o = m(this.device, this.depthSource, t, r, i, this.samples === 1))), o.descriptor.depthStencilAttachment.view = t, o.descriptor.depthStencilAttachment.depthLoadOp = this.viewContext?.view ? "load" : "clear";
152
+ let s = e.beginRenderPass(o.descriptor);
153
+ this.viewContext && n(s, this.viewContext);
154
+ let c = o.draws;
155
+ for (let e = 0; e < c.length; e++) s.setPipeline(c[e].pipeline), s.setBindGroup(0, c[e].group), s.draw(3);
156
+ s.end();
157
+ }
158
+ resolve(e, t = !1, n = !0) {
159
+ if (this.samples !== 1) {
160
+ if (n && this.copyDepth(e, this.resolvedDepthView, 1), t) {
161
+ let t = this.viewContext?.view ? "store" : "discard";
162
+ this.finalResolution.colorAttachments[0].storeOp = t, this.finalResolution.depthStencilAttachment.depthStoreOp = t, this.original && this.copyDepth(e, this.original.depth, this.original.descriptor.multisample?.count ?? 1, this.original.descriptor.depthStencil.format), this.retired = !0;
163
+ }
164
+ e.beginRenderPass(t ? this.finalResolution : this.resolution).end();
165
+ }
166
+ }
167
+ restore(e) {
168
+ let t = this.original;
169
+ this.samples === 1 ? (Object.assign(e, {
170
+ color: t.color,
171
+ depth: t.depth,
172
+ format: t.format,
173
+ descriptor: t.descriptor
174
+ }), e[f] = t.owner) : (this.retired || this.copyDepth(e.encoder, t.depth, t.descriptor.multisample?.count ?? 1, t.descriptor.depthStencil.format), Object.assign(e, {
175
+ color: t.color,
176
+ depth: t.depth,
177
+ format: t.format,
178
+ descriptor: t.descriptor
179
+ }), e[f] = t.owner);
180
+ }
181
+ present(e) {
182
+ this.resolve(e.encoder, !0), this.restore(e);
183
+ let r = e.descriptor.multisample?.count ?? 1;
184
+ if (!this.presentation || this.presentationFormat !== e.format || this.presentationSamples !== r) {
185
+ let t = this.device.createShaderModule({ code: u + "@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);}" });
186
+ this.presentation = this.device.createRenderPipeline({
187
+ layout: "auto",
188
+ vertex: {
189
+ module: t,
190
+ entryPoint: "vertex"
191
+ },
192
+ fragment: {
193
+ module: t,
194
+ entryPoint: "fragment",
195
+ targets: [{ format: e.format }]
196
+ },
197
+ multisample: e.descriptor.multisample
198
+ }), this.presentationGroup = d(this.device, this.presentation, this.resolvedColor.createView()), this.presentationFormat = e.format, this.presentationSamples = r;
199
+ }
200
+ let i = this.presentationPass ??= { colorAttachments: [{
201
+ view: e.color,
202
+ loadOp: "clear",
203
+ storeOp: "store"
204
+ }] };
205
+ i.colorAttachments[0].view = e.color, i.colorAttachments[0].loadOp = t(e, "clear");
206
+ let a = e.encoder.beginRenderPass(i);
207
+ a.setPipeline(this.presentation), a.setBindGroup(0, this.presentationGroup), n(a, e), a.draw(3), a.end();
208
+ }
209
+ dispose() {
210
+ for (let e of this.textures) s(this.device, e);
211
+ this.textures = [], this.pipelines.clear();
212
+ }
213
+ };
214
+ function g(e) {
215
+ let t = e[f];
216
+ return t?.color === e.color && t.depth === e.depth ? t : void 0;
217
+ }
218
+ function _(e) {
219
+ g(e)?.resolve(e.encoder);
220
+ }
221
+ //#endregion
222
+ //#region ../shared/gpu.js
223
+ function v(e, t, n) {
224
+ return e.createBindGroup({
225
+ layout: t.getBindGroupLayout(0),
226
+ entries: n.map((e, t) => ({
227
+ binding: t,
228
+ resource: e
229
+ }))
230
+ });
231
+ }
232
+ function y(e, t, n = "main") {
233
+ return e.createComputePipeline({
234
+ layout: "auto",
235
+ compute: {
236
+ module: e.createShaderModule({ code: t }),
237
+ entryPoint: n
238
+ }
239
+ });
240
+ }
241
+ function b(e, t, n, r, i = 1) {
242
+ let a = e.encoder.beginComputePass();
243
+ a.setPipeline(t), a.setBindGroup(0, n), a.dispatchWorkgroups(r, i), a.end();
244
+ }
245
+ function x(t) {
246
+ if (!t.gpu) throw e("unsupported", "Scene depth requires WebGPU; see https://margoengine.com/errors#webgpu");
247
+ if (t.hasPlugin("ssao") || t.hasPlugin("dof")) throw e("state", "Another effect owns scene capture; use its depth texture");
248
+ let n = t.plugins.get("optional:scene-depth");
249
+ n || (n = {coreRequirement:/*@__PURE__*/__margoCoreRequirement("0.1.0",import.meta.url),
250
+ name: "optional:scene-depth",
251
+ references: 0,
252
+ texture: void 0,
253
+ color: void 0,
254
+ target: void 0,
255
+ borrowed: !1,
256
+ setup() {},
257
+ registerPasses(n) {
258
+ n.add({
259
+ name: this.name + ":capture",
260
+ order: -15,
261
+ execute: (n) => {
262
+ if (n.backend !== "webgpu") return;
263
+ if (t.hasPlugin("ssao") || t.hasPlugin("dof")) throw e("state", "Another effect owns scene capture; use its depth texture");
264
+ let r = g(n);
265
+ if (this.borrowed = !!r, r) {
266
+ this.borrowedDepth = r.resolvedDepth;
267
+ return;
268
+ }
269
+ let i = n.descriptor.multisample?.count ?? 4;
270
+ try {
271
+ if (i === 1) {
272
+ (!this.depthView || this.texture?.width !== n.width || this.texture?.height !== n.height || this.texture?.format !== n.descriptor.depthStencil.format) && (this.onDeviceRestored(), this.texture = n.device.createTexture({
273
+ size: [n.width, n.height],
274
+ format: n.descriptor.depthStencil.format,
275
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
276
+ }), this.depthView = this.texture.createView()), n.depth = this.depthView;
277
+ return;
278
+ }
279
+ (this.target?.samples !== i || this.texture?.width !== n.width || this.texture?.height !== n.height || this.texture?.format !== n.descriptor.depthStencil.format || this.color?.format !== n.format) && (this.onDeviceRestored(), this.texture = n.device.createTexture({
280
+ size: [n.width, n.height],
281
+ format: n.descriptor.depthStencil.format,
282
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
283
+ }), this.color = n.device.createTexture({
284
+ size: [n.width, n.height],
285
+ format: n.format,
286
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
287
+ }), this.target = new h(n.device, this.color, this.texture, i)), this.target.begin(n);
288
+ } catch (e) {
289
+ throw this.onDeviceRestored(), e;
290
+ }
291
+ }
292
+ }), n.add({
293
+ name: this.name + ":restore",
294
+ order: 1e4,
295
+ execute: (e) => {
296
+ e.backend === "webgpu" && !this.borrowed && e.descriptor.multisample?.count !== 1 && this.target.present(e);
297
+ }
298
+ });
299
+ },
300
+ onDeviceRestored() {
301
+ this.target?.dispose(), this.texture?.destroy(), this.color?.destroy(), this.target = this.texture = this.color = this.depthView = void 0;
302
+ },
303
+ dispose() {
304
+ this.onDeviceRestored();
305
+ }
306
+ }, t.use(n)), n.references++;
307
+ let r = !1;
308
+ return {
309
+ texture: () => n.borrowed ? n.borrowedDepth : n.texture,
310
+ release() {
311
+ r || (r = !0, --n.references === 0 && t.sceneOf(n)?.removePlugin(n.name));
312
+ }
313
+ };
314
+ }
315
+ //#endregion
316
+ //#region src/index.ts
317
+ var S = "\n@group(0) @binding(0) var depth:texture_depth_2d;\n@group(0) @binding(1) var<storage,read> points:array<vec4f>;\n@group(0) @binding(2) var<storage,read_write> output:array<u32>;\n@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id:vec3u){\n if(id.x>=arrayLength(&points)){return;}let point=points[id.x];let p=vec2i(point.xy);let size=vec2i(textureDimensions(depth));\n output[id.x]=0u;if(any(p<vec2i(0))||any(p>=size)){return;}\n let d=textureLoad(depth,p,0);output[id.x]=select(0u,1u,d>point.z+point.w);\n}", C = (e) => `
318
+ @group(0) @binding(0) var depth:texture_depth_2d;
319
+ @group(0) @binding(1) var<storage,read> points:array<vec4f>;
320
+ @group(0) @binding(2) var<storage,read_write> output:array<u32>;
321
+ @group(0) @binding(3) var<uniform> radius:vec4f;
322
+ @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id:vec3u){
323
+ if(id.x>=arrayLength(&points)){return;}let point=points[id.x];let size=vec2i(textureDimensions(depth));var covered=0u;
324
+ for(var j=0u;j<${e}u;j++){for(var i=0u;i<${e}u;i++){
325
+ let o=(vec2f(f32(i),f32(j))+.5)*(2./${e}.)-1.;let p=vec2i(floor(point.xy+o*radius.xy));
326
+ if(all(p>=vec2i(0))&&all(p<size)){if(textureLoad(depth,p,0)>point.z+point.w){covered++;}}
327
+ }}
328
+ output[id.x]=covered;
329
+ }`;
330
+ function w(e) {
331
+ if (e === void 0 || e === !1) return;
332
+ let t = e === !0 ? {} : e;
333
+ if (typeof t != "object" || !t) throw RangeError("Invalid HTML fade options; pass fade: true or an object of radius, samples and duration");
334
+ let n = t.radius ?? 8, r = t.samples ?? 4, i = t.duration ?? .15;
335
+ if (!(n >= 0 && n <= 256) || !Number.isInteger(r) || r < 2 || r > 8 || !(i >= 0 && i <= 10)) throw RangeError("Invalid HTML fade options; pass radius 0 to 256 CSS pixels, samples a whole number 2 to 8 and duration 0 to 10 seconds");
336
+ return {
337
+ radius: n,
338
+ samples: r,
339
+ duration: i
340
+ };
341
+ }
342
+ var T = "#version 300 es\nuniform mat4 camera;uniform vec3 world;uniform vec2 offset;uniform float bias;\nvoid main(){vec4 p=camera*vec4(world,1.0);p.xy+=offset*p.w;p.z-=2.0*bias*p.w;gl_Position=p;gl_PointSize=1.0;}", E = "#version 300 es\nprecision lowp float;out vec4 color;void main(){color=vec4(0.0);}";
343
+ function D(t) {
344
+ let n = t.createProgram(), r = t.createShader(t.VERTEX_SHADER), i = t.createShader(t.FRAGMENT_SHADER);
345
+ if (t.shaderSource(r, T), t.shaderSource(i, E), t.compileShader(r), t.compileShader(i), t.attachShader(n, r), t.attachShader(n, i), t.linkProgram(n), t.deleteShader(r), t.deleteShader(i), !t.getProgramParameter(n, t.LINK_STATUS) && !t.isContextLost()) throw e("failed", `HTML could not build its WebGL2 occlusion shaders (${t.getProgramInfoLog(n)}); pass depth: false to draw without occlusion`);
346
+ return {
347
+ gl: t,
348
+ program: n,
349
+ vao: t.createVertexArray(),
350
+ camera: t.getUniformLocation(n, "camera"),
351
+ world: t.getUniformLocation(n, "world"),
352
+ offset: t.getUniformLocation(n, "offset"),
353
+ bias: t.getUniformLocation(n, "bias"),
354
+ slots: []
355
+ };
356
+ }
357
+ var O = 1048576, k = class t extends i {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
358
+ constructor(e = {}) {
359
+ super({
360
+ ...e,
361
+ name: e.name ?? "html",
362
+ order: 1e3
363
+ }), this.settings = e, this.records = /* @__PURE__ */ new Map(), this.slots = [], this.gpuSlots = 0, this.used = 0, this.free = [], this.pending = !1, this.generation = 0, this.disposed = !1, this.depthRequests = [], this.radiusValues = /* @__PURE__ */ new Float32Array(4), this.delta = 0;
364
+ let t = e.capacity ?? 1024, n = e.depthBias ?? 1e-4;
365
+ if (!Number.isInteger(t) || t < 1 || t > O) throw RangeError("Invalid HTML capacity; pass a whole number of anchors from 1 to 1,048,576");
366
+ if (!Number.isFinite(n) || n < 0 || n > .05 || e.depth !== void 0 && e.depth !== !1 && typeof e.depth != "function") throw RangeError("Invalid HTML depth options; pass depth: false or a function returning a depth texture, and a finite depthBias");
367
+ this.fade = w(e.fade), this.capacity = t, this.allocated = Math.min(t, 64), this.values = new Float32Array(this.allocated * 4);
368
+ for (let e = 0; e < this.values.length; e += 4) this.values[e] = this.values[e + 1] = -1;
369
+ }
370
+ static attach(e, n = {}) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
371
+ let i = new t(n);
372
+ return r(e).use(i), i;
373
+ }
374
+ add(t, n = {}) {
375
+ if (this.disposed) throw e("disposed", "HTML is disposed; create a new HTML renderer");
376
+ let r = this.free.length ? this.free[this.free.length - 1] : this.used;
377
+ if (r >= this.capacity) throw RangeError("HTML anchor capacity exceeded; raise capacity or remove anchors");
378
+ let i = super.add(t, {
379
+ ...n,
380
+ occlude: (e, t) => {
381
+ let i = this.records.get(e);
382
+ i.x = t.x, i.y = t.y, i.z = 1 - t.depth;
383
+ let a = this.runtime?.canvas;
384
+ if (a) {
385
+ let e = this.view, n = a.width / (a.clientWidth || a.width), o = a.height / (a.clientHeight || a.height), s = r * 4;
386
+ this.values[s] = t.x * n + (e ? e.viewport[0] * (e.pixels ? 1 : a.width) : 0), this.values[s + 1] = t.y * o + (e ? e.viewport[1] * (e.pixels ? 1 : a.height) : 0), this.values[s + 2] = i.z, this.values[s + 3] = this.settings.depthBias ?? 1e-4;
387
+ }
388
+ return !!(n.occlude ?? this.settings.occlude)?.(e, t) || i.hidden;
389
+ }
390
+ });
391
+ r === this.used ? this.used++ : this.free.pop(), r >= this.allocated && this.grow(r + 1);
392
+ let a = {
393
+ label: i,
394
+ index: r,
395
+ hidden: !1,
396
+ x: 0,
397
+ y: 0,
398
+ z: 0,
399
+ target: 1,
400
+ opacity: 1,
401
+ written: 1
402
+ };
403
+ return this.records.set(i, a), this.slots[r] = a, i;
404
+ }
405
+ grow(e) {
406
+ let t = this.allocated;
407
+ for (; t < e;) t *= 2;
408
+ t = Math.min(t, this.capacity);
409
+ let n = new Float32Array(t * 4);
410
+ n.set(this.values);
411
+ for (let e = this.allocated * 4; e < n.length; e += 4) n[e] = n[e + 1] = -1;
412
+ this.values = n, this.allocated = t;
413
+ }
414
+ remove(e) {
415
+ let t = this.records.get(e);
416
+ t && (this.free.push(t.index), this.free.sort((e, t) => t - e), this.slots[t.index] = void 0, this.records.delete(e), this.values.set([
417
+ -1,
418
+ -1,
419
+ 0,
420
+ 0
421
+ ], t.index * 4)), super.remove(e);
422
+ }
423
+ setup(t) {
424
+ if (this.disposed) throw e("disposed", "HTML is disposed; create a new HTML renderer");
425
+ this.runtime = r(t), super.setup(t), this.setupGPU();
426
+ }
427
+ setupGPU() {
428
+ let e = this.runtime;
429
+ e.gpu && this.settings.depth !== !1 && (this.shared = this.settings.depth ? void 0 : this.shared ?? x(e), this.source = this.settings.depth || this.shared.texture, this.buffers(e.gpu), this.fade && (this.radius = e.gpu.createBuffer({
430
+ size: 16,
431
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
432
+ })), this.pipeline = y(e.gpu, this.fade ? C(this.fade.samples) : S));
433
+ }
434
+ buffers(e) {
435
+ this.input?.destroy(), this.output?.destroy(), this.read?.destroy();
436
+ let t = this.gpuSlots = this.allocated;
437
+ this.input = e.createBuffer({
438
+ size: t * 16,
439
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
440
+ }), this.output = e.createBuffer({
441
+ size: t * 4,
442
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC
443
+ }), this.read = e.createBuffer({
444
+ size: t * 4,
445
+ usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
446
+ }), this.depthGroup = void 0;
447
+ }
448
+ onPreUpdate(e) {
449
+ this.delta += e;
450
+ }
451
+ update() {
452
+ let e = this.fade;
453
+ if (e) {
454
+ let t = e.duration > 0 ? this.delta / e.duration : Infinity;
455
+ this.delta = 0;
456
+ for (let e of this.records.values()) {
457
+ let n = e.target - e.opacity;
458
+ e.opacity = Math.abs(n) <= t ? e.target : e.opacity + Math.sign(n) * t, e.hidden = e.opacity <= 0;
459
+ }
460
+ }
461
+ if (super.update(), e) for (let e of this.records.values()) {
462
+ let t = Math.round(e.opacity * 1e3) / 1e3;
463
+ e.label.onScreen && t !== e.written && (e.written = t, e.label.element.style.opacity = t === 1 ? "" : String(t));
464
+ }
465
+ }
466
+ registerPasses(e) {
467
+ super.registerPasses(e), e.add({
468
+ name: this.name + ":depth",
469
+ order: 1001,
470
+ execute: (e) => {
471
+ e.backend === "webgpu" ? this.pipeline && !this.pending && this.sample(e) : this.settings.depth !== !1 && !e.gl.isContextLost() && this.query(e.gl, e.camera.matrix, e.view?.viewport);
472
+ }
473
+ });
474
+ }
475
+ sample(t) {
476
+ _(t);
477
+ let n = this.source();
478
+ if (!n || n.width !== t.width || n.height !== t.height || !n.format.startsWith("depth")) throw e("state", "HTML requires viewport-sized scene depth; pass a depth texture that matches the canvas, or depth: false");
479
+ if (!this.records.size) return;
480
+ this.gpuSlots !== this.allocated && this.buffers(t.device);
481
+ let r = this.used;
482
+ for (let e = 0; e < r; e++) if (!this.slots[e] || !this.slots[e].label.visible || !this.slots[e].label.screen.inFrustum) {
483
+ let t = e * 4;
484
+ this.values[t] = this.values[t + 1] = -1, this.values[t + 2] = this.values[t + 3] = 0;
485
+ }
486
+ if (t.device.queue.writeBuffer(this.input, 0, this.values, 0, r * 4), this.fade) {
487
+ let e = this.runtime.canvas, n = this.radiusValues, r = this.fade.radius * e.width / (e.clientWidth || e.width), i = this.fade.radius * e.height / (e.clientHeight || e.height);
488
+ (n[0] !== r || n[1] !== i || !this.depthGroup) && (n[0] = r, n[1] = i, t.device.queue.writeBuffer(this.radius, 0, n));
489
+ }
490
+ if (!this.depthGroup || n !== this.sampledDepth) {
491
+ let e = [
492
+ n.createView({ aspect: "depth-only" }),
493
+ { buffer: this.input },
494
+ { buffer: this.output }
495
+ ];
496
+ this.radius && e.push({ buffer: this.radius }), this.depthGroup = v(t.device, this.pipeline, e), this.sampledDepth = n;
497
+ }
498
+ b(t, this.pipeline, this.depthGroup, Math.ceil(r / 64));
499
+ let i = this.read, a = this.generation, o = this.depthRequests;
500
+ for (let e = 0; e < r; e++) {
501
+ let t = this.slots[e];
502
+ if (!t) {
503
+ o[e] = void 0;
504
+ continue;
505
+ }
506
+ let n = o[e];
507
+ n || (o[e] = n = {
508
+ record: t,
509
+ x: 0,
510
+ y: 0,
511
+ z: 0
512
+ }), n.record = t, n.x = t.x, n.y = t.y, n.z = t.z;
513
+ }
514
+ o.length = r, t.encoder.copyBufferToBuffer(this.output, 0, i, 0, r * 4), this.pending = !0, queueMicrotask(async () => {
515
+ try {
516
+ if (await i.mapAsync(GPUMapMode.READ), this.disposed || a !== this.generation) return;
517
+ let e = new Uint32Array(i.getMappedRange(0, r * 4)), t = this.fade, n = t ? Math.max(4, t.radius) : 4, s = t ? t.samples * t.samples : 1;
518
+ for (let i = 0; i < r; i++) {
519
+ let r = o[i];
520
+ if (!r || this.slots[i] !== r.record) continue;
521
+ let a = r.record, c = Math.abs(r.x - a.x) + Math.abs(r.y - a.y) < n && Math.abs(r.z - a.z) < .001;
522
+ t ? a.target = c ? 1 - Math.min(e[i], s) / s : 1 : a.hidden = c && !!e[i];
523
+ }
524
+ } catch {
525
+ for (let e of this.records.values()) e.hidden = !1, e.target = 1;
526
+ } finally {
527
+ i.mapState === "mapped" && i.unmap(), a === this.generation && (this.pending = !1);
528
+ }
529
+ });
530
+ }
531
+ query(e, t, n) {
532
+ let r = this.glOcclusion;
533
+ r && r.gl !== e && this.releaseGL(), r = this.glOcclusion ??= D(e);
534
+ let i = this.fade, a = i ? i.samples : 1, o = a * a, s = i ? Math.max(4, i.radius) : 4, c = this.runtime?.canvas, l = c ? c.clientWidth || c.width : 1, u = c ? c.clientHeight || c.height : 1, [d, f, p, m] = n ?? [
535
+ 0,
536
+ 0,
537
+ e.drawingBufferWidth,
538
+ e.drawingBufferHeight
539
+ ], h = p * l / e.drawingBufferWidth, g = m * u / e.drawingBufferHeight, _ = i?.radius ?? 0, v = this.settings.depthBias ?? 1e-4, y = !1;
540
+ for (let n = 0; n < this.used; n++) {
541
+ let c = this.slots[n], l = r.slots[n];
542
+ if (l?.pending) {
543
+ let t = !0;
544
+ for (let n = 0; n < o && t; n++) t = !l.drawn[n] || !!e.getQueryParameter(l.queries[n], e.QUERY_RESULT_AVAILABLE);
545
+ if (!t) continue;
546
+ if (l.pending = !1, c && l.record === c) {
547
+ let t = 0;
548
+ for (let n = 0; n < o; n++) l.drawn[n] && !e.getQueryParameter(l.queries[n], e.QUERY_RESULT) && t++;
549
+ let n = Math.abs(l.x - c.x) + Math.abs(l.y - c.y) < s && Math.abs(l.z - c.z) < .001;
550
+ i ? c.target = n ? 1 - t / o : 1 : c.hidden = n && t > 0;
551
+ }
552
+ }
553
+ if (!c || !c.label.visible || !c.label.screen.inFront || !c.label.screen.inFrustum) continue;
554
+ if (!l) {
555
+ l = r.slots[n] = {
556
+ queries: [],
557
+ drawn: [],
558
+ pending: !1,
559
+ x: 0,
560
+ y: 0,
561
+ z: 0
562
+ };
563
+ for (let t = 0; t < o; t++) l.queries.push(e.createQuery());
564
+ }
565
+ y || (y = !0, e.viewport(d, e.drawingBufferHeight - f - m, p, m), e.useProgram(r.program), e.bindVertexArray(r.vao), e.colorMask(!1, !1, !1, !1), e.depthMask(!1), e.enable(e.DEPTH_TEST), e.depthFunc(e.LESS), e.uniformMatrix4fv(r.camera, !1, t), e.uniform1f(r.bias, v));
566
+ let u = c.label.world;
567
+ e.uniform3f(r.world, u[0], u[1], u[2]);
568
+ for (let t = 0; t < o; t++) {
569
+ let n = a > 1 ? (t % a + .5) * 2 / a - 1 : 0, i = a > 1 ? (Math.floor(t / a) + .5) * 2 / a - 1 : 0, o = c.x + n * _, s = c.y + i * _;
570
+ l.drawn[t] = o >= 0 && o < h && s >= 0 && s < g, l.drawn[t] && (e.beginQuery(e.ANY_SAMPLES_PASSED, l.queries[t]), e.uniform2f(r.offset, n * _ / h * 2, -(i * _) / g * 2), e.drawArrays(e.POINTS, 0, 1), e.endQuery(e.ANY_SAMPLES_PASSED));
571
+ }
572
+ l.pending = !0, l.record = c, l.x = c.x, l.y = c.y, l.z = c.z;
573
+ }
574
+ y && (e.colorMask(!0, !0, !0, !0), e.depthMask(!0), e.bindVertexArray(null), e.useProgram(null));
575
+ }
576
+ releaseGL() {
577
+ let e = this.glOcclusion;
578
+ if (this.glOcclusion = void 0, e && !e.gl.isContextLost()) {
579
+ for (let t of e.slots) for (let n of t?.queries ?? []) e.gl.deleteQuery(n);
580
+ e.gl.deleteVertexArray(e.vao), e.gl.deleteProgram(e.program);
581
+ }
582
+ }
583
+ release(e = !0) {
584
+ this.releaseGL(), this.generation++, this.pending = !1, e && (this.shared?.release(), this.shared = void 0), this.input?.destroy(), this.output?.destroy(), this.read?.destroy(), this.radius?.destroy(), this.input = this.output = this.read = this.radius = void 0, this.gpuSlots = 0, this.pipeline = void 0, this.sampledDepth = this.depthGroup = void 0;
585
+ }
586
+ onDeviceRestored() {
587
+ this.release(!1);
588
+ for (let e of this.records.values()) e.hidden = !1, e.target = 1;
589
+ this.setupGPU();
590
+ }
591
+ dispose() {
592
+ this.disposed || (this.disposed = !0, this.release(), super.dispose(), this.records.clear(), this.slots.length = 0, this.runtime = void 0);
593
+ }
594
+ [Symbol.dispose ?? Symbol()]() {
595
+ this.dispose();
596
+ }
597
+ };
598
+ //#endregion
599
+ export { k as HTML };