@margoengine/labels 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,91 @@
1
+ import { n as e } from "./errors-52P7hKm0.js";
2
+ //#region src/distance.ts
3
+ function t(t) {
4
+ let n = t.near ?? 0, r = t.far ?? Infinity;
5
+ if (!Number.isFinite(n) || n < 0 || !(r >= n) || r !== Infinity && !Number.isFinite(r)) throw e("use finite near >= 0 and far >= near (Infinity allowed for far)", "labels");
6
+ let i = {
7
+ near: n,
8
+ far: r
9
+ };
10
+ for (let n of ["opacity", "scale"]) {
11
+ let r = t[n];
12
+ if (r) {
13
+ if (![
14
+ r.near,
15
+ r.nearValue,
16
+ r.far,
17
+ r.farValue
18
+ ].every(Number.isFinite) || r.near < 0 || r.far <= r.near || r.nearValue < 0 || r.farValue < 0 || n === "opacity" && (r.nearValue > 1 || r.farValue > 1)) throw e("use finite curve distances with 0 <= near < far, nonnegative scale and opacity in [0,1]", "labels");
19
+ i[n] = { ...r };
20
+ }
21
+ }
22
+ return i;
23
+ }
24
+ function n(e, t) {
25
+ if (!t) return 1;
26
+ if (e <= t.near) return t.nearValue;
27
+ if (e >= t.far) return t.farValue;
28
+ let n = Math.min(1, Math.max(0, (e - t.near) / (t.far - t.near)));
29
+ return t.nearValue + (t.farValue - t.nearValue) * n;
30
+ }
31
+ function r(r, i = {}) {
32
+ if (!Number.isFinite(r) || r < 0) throw e("distance must be finite and nonnegative", "labels");
33
+ let a = t(i), o = n(r, a.opacity), s = n(r, a.scale);
34
+ return {
35
+ opacity: o,
36
+ scale: s,
37
+ visible: r >= a.near && r <= a.far && o > 0 && s > 0
38
+ };
39
+ }
40
+ var i = class {
41
+ constructor(e = {}) {
42
+ this.policies = /* @__PURE__ */ new Map(), this.styles = /* @__PURE__ */ new Map(), this.hidden = 0, this.defaults = t(e.defaults ?? {}), this.layout = e.layout;
43
+ }
44
+ set(e, n) {
45
+ return this.policies.set(e, t(n)), this;
46
+ }
47
+ delete(e) {
48
+ return this.restore(e), this.policies.delete(e);
49
+ }
50
+ arrange(e, t) {
51
+ let r = [];
52
+ this.hidden = 0;
53
+ for (let i of e) {
54
+ let e = this.policies.get(i) ?? this.defaults, a = n(i.distance, e.opacity), o = n(i.distance, e.scale);
55
+ if (!Number.isFinite(i.distance) || i.distance < e.near || i.distance > e.far || a <= 0 || o <= 0) t.hide(i), this.hidden++;
56
+ else {
57
+ if (i.scale *= o, e.opacity) {
58
+ let e = this.styles.get(i);
59
+ if (!e) {
60
+ let t = i.element.style.opacity ?? "";
61
+ this.styles.set(i, e = {
62
+ original: t,
63
+ last: t
64
+ });
65
+ }
66
+ let t = e.original === "" ? 1 : Number(e.original), n = String(a * (Number.isFinite(t) ? t : 1));
67
+ e.last !== n && (i.element.style.opacity = n, e.last = n);
68
+ } else this.restore(i);
69
+ r.push(i);
70
+ }
71
+ }
72
+ for (let e of /* @__PURE__ */ new Set([...this.styles.keys(), ...this.policies.keys()])) e.owner === null && (this.restore(e), this.policies.delete(e));
73
+ this.layout?.arrange(r, t);
74
+ }
75
+ restore(e) {
76
+ let t = this.styles.get(e);
77
+ t && (e.element.style.opacity = t.original, this.styles.delete(e));
78
+ }
79
+ clear() {
80
+ for (let e of this.styles.keys()) this.restore(e);
81
+ this.policies.clear();
82
+ }
83
+ dispose() {
84
+ this.clear();
85
+ }
86
+ [Symbol.dispose]() {
87
+ this.clear();
88
+ }
89
+ };
90
+ //#endregion
91
+ export { i as DistanceLabels, r as evaluateLabelDistance };
@@ -0,0 +1,9 @@
1
+ //#region ../shared/errors.js
2
+ var e = (e, t) => Object.assign(Error(t), {
3
+ name: "MargoError",
4
+ code: e
5
+ }), t = (e, t) => `${e}; see https://margoengine.com/errors#${t}`, n = (n, r, i = n) => e(n, t(r, i)), r = (e, n) => TypeError(t(e, n)), i = (e, n) => RangeError(t(e, n)), a = () => {
6
+ throw Object.assign(r("Retained vector: use a transform setter", "transform"), { code: "transform" });
7
+ };
8
+ //#endregion
9
+ export { i as n, a as r, n as t };
@@ -0,0 +1,19 @@
1
+ import type { PassContext } from '@margoengine/core/extension';
2
+ import type { AtlasSlot, GlyphBitmap } from '@margoengine/text';
3
+ export declare class LabelGL {
4
+ private readonly gl;
5
+ private program;
6
+ private vao;
7
+ private buffer;
8
+ private texture?;
9
+ private uploaded;
10
+ constructor(gl: WebGL2RenderingContext);
11
+ draw(context: Extract<PassContext, {
12
+ backend: 'webgl2';
13
+ }>, data: Float32Array, matrix: Float32Array, width: number, height: number, size: number, pages: number, records: {
14
+ bitmap: GlyphBitmap;
15
+ slot: AtlasSlot;
16
+ pixels: Uint8Array;
17
+ }[]): void;
18
+ dispose(): void;
19
+ }
@@ -0,0 +1,3 @@
1
+ export declare const gpuLabelShader = "\nstruct Frame { matrix: mat4x4f, viewport: vec4f }\n@group(0) @binding(0) var<uniform> frame: Frame;\n@group(0) @binding(1) var atlasSampler: sampler;\n@group(0) @binding(2) var atlas: texture_2d_array<f32>;\nstruct Out {\n @builtin(position) position: vec4f,\n @location(0) uv: vec2f,\n @location(1) color: vec4f,\n @location(2) @interpolate(flat) glyphInfo: vec4f,\n}\n@vertex fn vertex(@builtin(vertex_index) vi: u32,\n @location(0) anchor: vec4f, @location(1) rect: vec4f,\n @location(2) uv: vec4f, @location(3) color: vec4f, @location(4) glyphInfo: vec4f) -> Out {\n let c = vec2f(f32((0x32u >> vi) & 1u), f32((0x2cu >> vi) & 1u));\n let offset = mix(rect.xy, rect.zw, c);\n var o: Out;\n o.position = frame.matrix * vec4f(anchor.xyz, 1.0);\n o.position.x += offset.x * 2.0 / frame.viewport.x * o.position.w;\n o.position.y -= offset.y * 2.0 / frame.viewport.y * o.position.w;\n o.uv = mix(uv.xy, uv.zw, c);\n o.color = color;\n o.glyphInfo = glyphInfo;\n return o;\n}\n@fragment fn fragment(i: Out) -> @location(0) vec4f {\n let field = textureSampleLevel(atlas, atlasSampler, i.uv, i32(i.glyphInfo.x), 0.0);\n let w = max(fwidth(field.r), 0.0001);\n let coverage = smoothstep(1.0 - i.glyphInfo.w - w * 0.5, 1.0 - i.glyphInfo.w + w * 0.5, field.r);\n if (i.glyphInfo.y > 0.5) { return field * i.color.a; }\n let a = coverage * i.color.a;\n return vec4f(i.color.rgb * a, a);\n}\n";
2
+ export declare const glLabelVertex = "#version 300 es\nprecision highp float;\nlayout(location=0) in vec4 anchor;\nlayout(location=1) in vec4 rect;\nlayout(location=2) in vec4 texcoord;\nlayout(location=3) in vec4 tint;\nlayout(location=4) in vec4 info;\nuniform mat4 matrix;\nuniform vec2 viewport;\nout vec2 uv;\nout vec4 color;\nflat out vec4 glyphInfo;\nvoid main() {\n vec2 c = vec2(float((0x32u >> uint(gl_VertexID)) & 1u), float((0x2cu >> uint(gl_VertexID)) & 1u));\n vec2 offset = mix(rect.xy, rect.zw, c);\n gl_Position = matrix * vec4(anchor.xyz, 1.0);\n gl_Position.xy += offset * vec2(2.0, -2.0) / viewport * gl_Position.w;\n uv = mix(texcoord.xy, texcoord.zw, c); color = tint; glyphInfo = info;\n}";
3
+ export declare const glLabelFragment = "#version 300 es\nprecision highp float;\nprecision highp sampler2DArray;\nuniform sampler2DArray atlas;\nin vec2 uv;\nin vec4 color;\nflat in vec4 glyphInfo;\nout vec4 outputColor;\nvoid main() {\n vec4 field = texture(atlas, vec3(uv, glyphInfo.x));\n float w = max(fwidth(field.r), 0.0001);\n float a = smoothstep(1.0-glyphInfo.w-w*0.5, 1.0-glyphInfo.w+w*0.5, field.r) * color.a;\n outputColor = glyphInfo.y > 0.5 ? field * color.a : vec4(color.rgb * a, a);\n}";
package/dist/gpu.d.ts ADDED
@@ -0,0 +1,97 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { Engine, EnginePlugin, FrameGraph } from '@margoengine/core/extension';
3
+ import type { EngineKernel } from '@margoengine/core';
4
+ import type { Font } from '@margoengine/text';
5
+ /** A GPU label. Positions use world units; fontSize and offset use CSS pixels. */
6
+ export interface GPULabel {
7
+ text: string;
8
+ position: readonly [number, number, number];
9
+ /** Default 16 CSS pixels, independent of camera distance and device pixel ratio. */
10
+ fontSize?: number;
11
+ /** Straight RGBA in [0, 1]. Default white. */
12
+ color?: readonly [number, number, number, number];
13
+ /** Higher priorities win decluttering. Default 0; ties keep input order. */
14
+ priority?: number;
15
+ offset?: readonly [number, number];
16
+ visible?: boolean;
17
+ }
18
+ /** Options for the optional, one-draw GPU label plugin. */
19
+ export interface GPULabelOptions {
20
+ font?: Font;
21
+ /** Default 'gpu-labels'. */
22
+ name?: string;
23
+ /** Default 24, after opaque geometry. */
24
+ order?: number;
25
+ /** Default true. Exact glyph bounds are tested through a screen-space grid. */
26
+ declutter?: boolean;
27
+ /** Grid side in CSS pixels. Default 64. */
28
+ cell?: number;
29
+ /** Label spacing in CSS pixels. Default 2. */
30
+ padding?: number;
31
+ /** Atlas page side in texels. Default 1024. */
32
+ atlasSize?: number;
33
+ /** Maximum atlas pages. Default 32; device limits still apply. */
34
+ maxPages?: number;
35
+ signal?: AbortSignal;
36
+ }
37
+ /**
38
+ * Screen-constant, SDF label layer with one instanced draw across all labels and atlas pages.
39
+ * Create asynchronously, then attach with engine.use(layer). No DOM elements per point.
40
+ */
41
+ export declare class GPULabelLayer implements EnginePlugin {
42
+ private readonly api;
43
+ /** Loads the font and registers the layer. Default options match create(). */
44
+ static attach(engine: EngineKernel, options?: GPULabelOptions): Promise<GPULabelLayer>;
45
+ readonly name: string;
46
+ readonly order: number;
47
+ readonly font: Font;
48
+ /** Latest prepared label and glyph counts, exact grid comparisons, and actual draw calls. */
49
+ readonly stats: {
50
+ labels: number;
51
+ glyphs: number;
52
+ hidden: number;
53
+ comparisons: number;
54
+ drawCalls: number;
55
+ };
56
+ private labels;
57
+ private readonly shapes;
58
+ private readonly records;
59
+ private readonly packer;
60
+ private readonly options;
61
+ private revision;
62
+ private engine?;
63
+ private device?;
64
+ private uniform?;
65
+ private instances?;
66
+ private texture?;
67
+ private group?;
68
+ private sampler?;
69
+ private pipeline?;
70
+ private pipelineKey;
71
+ private capacity;
72
+ private uploaded;
73
+ private gl?;
74
+ private data;
75
+ private readonly matrix;
76
+ private readonly frame;
77
+ private constructor();
78
+ /** Lazily loads text support and fonts. Cancellation is checked before and after loading. */
79
+ static create(options?: GPULabelOptions): Promise<GPULabelLayer>;
80
+ /** Replaces the collection. Label fields may also be edited between frames. */
81
+ setLabels(labels: readonly GPULabel[]): this;
82
+ /**
83
+ * Prepares packed glyph instances without drawing, also useful for headless layout inspection.
84
+ * matrix is the camera view-projection; dimensions are positive CSS pixels. Returned storage is reused.
85
+ */
86
+ prepare(matrix: ArrayLike<number>, width: number, height: number, backend?: 'webgpu' | 'webgl2'): Float32Array;
87
+ private shape;
88
+ setup(engine: Engine): void;
89
+ registerPasses(graph: FrameGraph): void;
90
+ private draw;
91
+ private drawGPU;
92
+ private releaseGPU;
93
+ onDeviceRestored(engine: Engine): void;
94
+ /** Releases GPU resources; CPU labels can be reused after attaching again. */
95
+ dispose(): void;
96
+ [Symbol.dispose](): void;
97
+ }
package/dist/gpu.js ADDED
@@ -0,0 +1,446 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import { n as e, t } from "./errors-52P7hKm0.js";
5
+ //#region ../shared/view-rect.js
6
+ function n(e) {
7
+ return e?.view?.viewport;
8
+ }
9
+ function r(e, t) {
10
+ let r = n(t);
11
+ if (!r) return;
12
+ e.setViewport(r[0], r[1], r[2], r[3], 0, 1);
13
+ let i = t.view.scissor ?? r;
14
+ e.setScissorRect(i[0], i[1], i[2], i[3]);
15
+ }
16
+ //#endregion
17
+ //#region src/gpu-shader.ts
18
+ var i = "\nstruct Frame { matrix: mat4x4f, viewport: vec4f }\n@group(0) @binding(0) var<uniform> frame: Frame;\n@group(0) @binding(1) var atlasSampler: sampler;\n@group(0) @binding(2) var atlas: texture_2d_array<f32>;\nstruct Out {\n @builtin(position) position: vec4f,\n @location(0) uv: vec2f,\n @location(1) color: vec4f,\n @location(2) @interpolate(flat) glyphInfo: vec4f,\n}\n@vertex fn vertex(@builtin(vertex_index) vi: u32,\n @location(0) anchor: vec4f, @location(1) rect: vec4f,\n @location(2) uv: vec4f, @location(3) color: vec4f, @location(4) glyphInfo: vec4f) -> Out {\n let c = vec2f(f32((0x32u >> vi) & 1u), f32((0x2cu >> vi) & 1u));\n let offset = mix(rect.xy, rect.zw, c);\n var o: Out;\n o.position = frame.matrix * vec4f(anchor.xyz, 1.0);\n o.position.x += offset.x * 2.0 / frame.viewport.x * o.position.w;\n o.position.y -= offset.y * 2.0 / frame.viewport.y * o.position.w;\n o.uv = mix(uv.xy, uv.zw, c);\n o.color = color;\n o.glyphInfo = glyphInfo;\n return o;\n}\n@fragment fn fragment(i: Out) -> @location(0) vec4f {\n let field = textureSampleLevel(atlas, atlasSampler, i.uv, i32(i.glyphInfo.x), 0.0);\n let w = max(fwidth(field.r), 0.0001);\n let coverage = smoothstep(1.0 - i.glyphInfo.w - w * 0.5, 1.0 - i.glyphInfo.w + w * 0.5, field.r);\n if (i.glyphInfo.y > 0.5) { return field * i.color.a; }\n let a = coverage * i.color.a;\n return vec4f(i.color.rgb * a, a);\n}\n", a = "#version 300 es\nprecision highp float;\nlayout(location=0) in vec4 anchor;\nlayout(location=1) in vec4 rect;\nlayout(location=2) in vec4 texcoord;\nlayout(location=3) in vec4 tint;\nlayout(location=4) in vec4 info;\nuniform mat4 matrix;\nuniform vec2 viewport;\nout vec2 uv;\nout vec4 color;\nflat out vec4 glyphInfo;\nvoid main() {\n vec2 c = vec2(float((0x32u >> uint(gl_VertexID)) & 1u), float((0x2cu >> uint(gl_VertexID)) & 1u));\n vec2 offset = mix(rect.xy, rect.zw, c);\n gl_Position = matrix * vec4(anchor.xyz, 1.0);\n gl_Position.xy += offset * vec2(2.0, -2.0) / viewport * gl_Position.w;\n uv = mix(texcoord.xy, texcoord.zw, c); color = tint; glyphInfo = info;\n}", o = "#version 300 es\nprecision highp float;\nprecision highp sampler2DArray;\nuniform sampler2DArray atlas;\nin vec2 uv;\nin vec4 color;\nflat in vec4 glyphInfo;\nout vec4 outputColor;\nvoid main() {\n vec4 field = texture(atlas, vec3(uv, glyphInfo.x));\n float w = max(fwidth(field.r), 0.0001);\n float a = smoothstep(1.0-glyphInfo.w-w*0.5, 1.0-glyphInfo.w+w*0.5, field.r) * color.a;\n outputColor = glyphInfo.y > 0.5 ? field * color.a : vec4(color.rgb * a, a);\n}", s = class {
19
+ constructor(e) {
20
+ this.gl = e, this.uploaded = -1;
21
+ let n = [a, o].map((n, r) => {
22
+ let i = e.createShader(r === 0 ? e.VERTEX_SHADER : e.FRAGMENT_SHADER);
23
+ if (e.shaderSource(i, n), e.compileShader(i), !e.getShaderParameter(i, e.COMPILE_STATUS)) {
24
+ let n = e.getShaderInfoLog(i);
25
+ throw e.deleteShader(i), t("failed", `label shader compilation failed: ${n}; check WebGL2 support`, "labels");
26
+ }
27
+ return i;
28
+ });
29
+ this.program = e.createProgram();
30
+ for (let t of n) e.attachShader(this.program, t);
31
+ e.linkProgram(this.program);
32
+ for (let t of n) e.deleteShader(t);
33
+ if (!e.getProgramParameter(this.program, e.LINK_STATUS)) {
34
+ let n = e.getProgramInfoLog(this.program);
35
+ throw e.deleteProgram(this.program), t("failed", `label shader linking failed: ${n}; check WebGL2 support`, "labels");
36
+ }
37
+ this.vao = e.createVertexArray(), this.buffer = e.createBuffer();
38
+ }
39
+ draw(t, n, r, i, a, o, s, c) {
40
+ let l = this.gl;
41
+ if (o > l.getParameter(l.MAX_TEXTURE_SIZE) || s > l.getParameter(l.MAX_ARRAY_TEXTURE_LAYERS)) throw e("atlas exceeds WebGL2 limits; reduce atlasSize or font coverage", "labels");
42
+ let u = l.getParameter(l.CURRENT_PROGRAM), d = l.getParameter(l.VERTEX_ARRAY_BINDING), f = l.getParameter(l.ARRAY_BUFFER_BINDING), p = l.getParameter(l.ACTIVE_TEXTURE), m = l.getParameter(l.VIEWPORT), h = l.getParameter(l.SCISSOR_BOX), g = [
43
+ l.BLEND,
44
+ l.DEPTH_TEST,
45
+ l.CULL_FACE,
46
+ l.SCISSOR_TEST
47
+ ].map((e) => [e, l.isEnabled(e)]), _ = [
48
+ l.BLEND_SRC_RGB,
49
+ l.BLEND_DST_RGB,
50
+ l.BLEND_SRC_ALPHA,
51
+ l.BLEND_DST_ALPHA,
52
+ l.BLEND_EQUATION_RGB,
53
+ l.BLEND_EQUATION_ALPHA
54
+ ].map((e) => l.getParameter(e));
55
+ l.activeTexture(l.TEXTURE0);
56
+ let v = l.getParameter(l.TEXTURE_BINDING_2D_ARRAY), y = l.getParameter(l.SAMPLER_BINDING), b = l.getParameter(l.PIXEL_UNPACK_BUFFER_BINDING), x = l.getParameter(l.UNPACK_ALIGNMENT), S = [
57
+ l.UNPACK_ROW_LENGTH,
58
+ l.UNPACK_IMAGE_HEIGHT,
59
+ l.UNPACK_SKIP_PIXELS,
60
+ l.UNPACK_SKIP_ROWS,
61
+ l.UNPACK_SKIP_IMAGES,
62
+ l.UNPACK_FLIP_Y_WEBGL,
63
+ l.UNPACK_PREMULTIPLY_ALPHA_WEBGL
64
+ ], C = S.map((e) => l.getParameter(e));
65
+ try {
66
+ if (l.bindSampler(0, null), this.uploaded !== c.length) {
67
+ this.texture && l.deleteTexture(this.texture), this.texture = l.createTexture(), l.bindTexture(l.TEXTURE_2D_ARRAY, this.texture), l.bindBuffer(l.PIXEL_UNPACK_BUFFER, null), l.pixelStorei(l.UNPACK_ALIGNMENT, 1);
68
+ for (let e of S) l.pixelStorei(e, 0);
69
+ l.texImage3D(l.TEXTURE_2D_ARRAY, 0, l.RGBA8, o, o, s, 0, l.RGBA, l.UNSIGNED_BYTE, null);
70
+ for (let e of c) l.texSubImage3D(l.TEXTURE_2D_ARRAY, 0, e.slot.x, e.slot.y, e.slot.page, e.bitmap.width, e.bitmap.height, 1, l.RGBA, l.UNSIGNED_BYTE, e.pixels);
71
+ l.texParameteri(l.TEXTURE_2D_ARRAY, l.TEXTURE_MIN_FILTER, l.LINEAR), l.texParameteri(l.TEXTURE_2D_ARRAY, l.TEXTURE_MAG_FILTER, l.LINEAR), l.texParameteri(l.TEXTURE_2D_ARRAY, l.TEXTURE_WRAP_S, l.CLAMP_TO_EDGE), l.texParameteri(l.TEXTURE_2D_ARRAY, l.TEXTURE_WRAP_T, l.CLAMP_TO_EDGE), this.uploaded = c.length;
72
+ } else l.bindTexture(l.TEXTURE_2D_ARRAY, this.texture);
73
+ l.useProgram(this.program), l.bindVertexArray(this.vao), l.bindBuffer(l.ARRAY_BUFFER, this.buffer), l.bufferData(l.ARRAY_BUFFER, n, l.DYNAMIC_DRAW);
74
+ for (let e = 0; e < 5; e++) l.enableVertexAttribArray(e), l.vertexAttribPointer(e, 4, l.FLOAT, !1, 80, e * 16), l.vertexAttribDivisor(e, 1);
75
+ l.uniformMatrix4fv(l.getUniformLocation(this.program, "matrix"), !1, r), l.uniform2f(l.getUniformLocation(this.program, "viewport"), i, a), l.uniform1i(l.getUniformLocation(this.program, "atlas"), 0), l.enable(l.BLEND), l.blendFuncSeparate(l.ONE, l.ONE_MINUS_SRC_ALPHA, l.ONE, l.ONE_MINUS_SRC_ALPHA), l.blendEquationSeparate(l.FUNC_ADD, l.FUNC_ADD), l.disable(l.DEPTH_TEST), l.disable(l.CULL_FACE);
76
+ let e = t.view?.viewport ?? [
77
+ 0,
78
+ 0,
79
+ t.width,
80
+ t.height
81
+ ], u = t.view?.scissor ?? e;
82
+ l.viewport(e[0], t.height - e[1] - e[3], e[2], e[3]), l.enable(l.SCISSOR_TEST), l.scissor(u[0], t.height - u[1] - u[3], u[2], u[3]), l.drawArraysInstanced(l.TRIANGLES, 0, 6, n.length / 20);
83
+ } finally {
84
+ l.useProgram(u), l.bindVertexArray(d), l.bindBuffer(l.ARRAY_BUFFER, f), l.bindTexture(l.TEXTURE_2D_ARRAY, v), l.bindSampler(0, y), l.activeTexture(p), l.bindBuffer(l.PIXEL_UNPACK_BUFFER, b), l.pixelStorei(l.UNPACK_ALIGNMENT, x), S.forEach((e, t) => l.pixelStorei(e, C[t])), l.viewport(m[0], m[1], m[2], m[3]), l.scissor(h[0], h[1], h[2], h[3]), l.blendFuncSeparate(_[0], _[1], _[2], _[3]), l.blendEquationSeparate(_[4], _[5]);
85
+ for (let [e, t] of g) t ? l.enable(e) : l.disable(e);
86
+ }
87
+ }
88
+ dispose() {
89
+ let e = this.gl;
90
+ e.deleteBuffer(this.buffer), e.deleteVertexArray(this.vao), e.deleteProgram(this.program), this.texture && e.deleteTexture(this.texture);
91
+ }
92
+ }, c = 0;
93
+ async function l(e, t) {
94
+ if (!t) {
95
+ await e;
96
+ return;
97
+ }
98
+ t.throwIfAborted();
99
+ let n, r = new Promise((e, r) => {
100
+ n = () => r(t.reason), t.addEventListener("abort", n, { once: !0 });
101
+ });
102
+ e.catch(() => {});
103
+ try {
104
+ await Promise.race([e, r]);
105
+ } finally {
106
+ t.removeEventListener("abort", n);
107
+ }
108
+ t.throwIfAborted();
109
+ }
110
+ function u(e) {
111
+ let t = e.getBoundingClientRect();
112
+ if (typeof Element > "u" || !(e instanceof Element) || typeof getComputedStyle != "function") return t;
113
+ let n = getComputedStyle(e), r = (e) => Number.parseFloat(n.getPropertyValue(e)) || 0;
114
+ return {
115
+ width: t.width - r("border-left-width") - r("border-right-width") - r("padding-left") - r("padding-right"),
116
+ height: t.height - r("border-top-width") - r("border-bottom-width") - r("padding-top") - r("padding-bottom")
117
+ };
118
+ }
119
+ var d = class n {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
120
+ static async attach(e, t = {}) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
121
+ let r = e, i, a = {coreRequirement:/*@__PURE__*/__margoCoreRequirement("0.1.0",import.meta.url),
122
+ name: "gpu-labels:attach:" + c++,
123
+ setup() {
124
+ i = r.sceneOf(a);
125
+ }
126
+ };
127
+ r.use(a), i.removePlugin(a.name);
128
+ let o = await n.create(t);
129
+ try {
130
+ return t.signal?.throwIfAborted(), i.use(o), o;
131
+ } catch (e) {
132
+ throw o.dispose(), e;
133
+ }
134
+ }
135
+ constructor(t, n) {
136
+ if (this.api = t, this.stats = {
137
+ labels: 0,
138
+ glyphs: 0,
139
+ hidden: 0,
140
+ comparisons: 0,
141
+ drawCalls: 0
142
+ }, this.labels = [], this.shapes = /* @__PURE__ */ new Map(), this.records = /* @__PURE__ */ new Map(), this.revision = -1, this.pipelineKey = "", this.capacity = 0, this.uploaded = -1, this.data = /* @__PURE__ */ new Float32Array(), this.matrix = /* @__PURE__ */ new Float32Array(16), this.frame = /* @__PURE__ */ new Float32Array(20), this.name = n.name ?? "gpu-labels", this.order = n.order ?? 24, this.font = n.font ?? new t.Font(), this.options = {
143
+ declutter: n.declutter ?? !0,
144
+ cell: n.cell ?? 64,
145
+ padding: n.padding ?? 2,
146
+ atlasSize: n.atlasSize ?? 1024,
147
+ maxPages: n.maxPages ?? 32
148
+ }, !this.name || !Number.isFinite(this.order)) throw e("give a nonempty name and finite order", "labels");
149
+ let { cell: r, padding: i, atlasSize: a, maxPages: o } = this.options;
150
+ if (!Number.isFinite(r) || r < 1 || !Number.isFinite(i) || i < 0) throw e("use cell >= 1 and padding >= 0 in CSS pixels", "labels");
151
+ this.packer = new t.ShelfPacker(a, o, 1);
152
+ }
153
+ static async create(e = {}) {
154
+ e.signal?.throwIfAborted();
155
+ let t = new n(await import("@margoengine/text"), e);
156
+ return await l(t.font.load(), e.signal), t;
157
+ }
158
+ setLabels(e) {
159
+ return this.labels = e, this;
160
+ }
161
+ prepare(t, n, r, i = "webgpu") {
162
+ if (t.length !== 16 || !Array.from(t).every(Number.isFinite) || !Number.isFinite(n) || n <= 0 || !Number.isFinite(r) || r <= 0) throw e("provide a finite 4x4 matrix and positive CSS viewport dimensions", "labels");
163
+ this.revision !== this.font.revision && (this.shapes.clear(), this.revision = this.font.revision);
164
+ let a = this.stats;
165
+ a.labels = a.glyphs = a.hidden = a.comparisons = a.drawCalls = 0;
166
+ let o = /* @__PURE__ */ new Map(), s = [], c = this.labels.map((e, t) => t);
167
+ for (let t of this.labels) if (typeof t.text != "string" || t.position.length !== 3 || !t.position.every(Number.isFinite) || !Number.isFinite(t.fontSize ?? 16) || (t.fontSize ?? 16) <= 0 || !Number.isFinite(t.priority ?? 0) || t.offset && (t.offset.length !== 2 || !t.offset.every(Number.isFinite)) || t.color && (t.color.length !== 4 || !t.color.every((e) => Number.isFinite(e) && e >= 0 && e <= 1))) throw e("use text, finite positions and priorities, positive fontSize, and RGBA in [0,1]", "labels");
168
+ c.sort((e, t) => (this.labels[t].priority ?? 0) - (this.labels[e].priority ?? 0) || e - t);
169
+ let { cell: l, padding: u, declutter: d } = this.options, f = /* @__PURE__ */ new Set();
170
+ for (let e of c) {
171
+ let c = this.labels[e];
172
+ if (c.visible === !1 || !c.text) {
173
+ a.hidden++;
174
+ continue;
175
+ }
176
+ let [p, m, h] = c.position, g = t[0] * p + t[4] * m + t[8] * h + t[12], _ = t[1] * p + t[5] * m + t[9] * h + t[13], v = t[2] * p + t[6] * m + t[10] * h + t[14], y = t[3] * p + t[7] * m + t[11] * h + t[15];
177
+ if (y <= 0 || v > y || v < (i === "webgpu" ? 0 : -y)) {
178
+ a.hidden++;
179
+ continue;
180
+ }
181
+ let b = JSON.stringify([c.text, c.fontSize ?? 16]);
182
+ f.add(b);
183
+ let x = this.shape(b, c), S = c.offset?.[0] ?? 0, C = c.offset?.[1] ?? 0, w = (g / y + 1) * n / 2 + S, T = (1 - _ / y) * r / 2 + C, E = [
184
+ w + x.bounds[0],
185
+ T + x.bounds[1],
186
+ w + x.bounds[2],
187
+ T + x.bounds[3]
188
+ ];
189
+ if (E[2] < 0 || E[0] > n || E[3] < 0 || E[1] > r) {
190
+ a.hidden++;
191
+ continue;
192
+ }
193
+ let D = [];
194
+ for (let e = Math.floor(Math.max(-u, E[1] - u) / l); e <= Math.floor(Math.min(r + u, E[3] + u) / l); e++) for (let t = Math.floor(Math.max(-u, E[0] - u) / l); t <= Math.floor(Math.min(n + u, E[2] + u) / l); t++) D.push(`${t},${e}`);
195
+ let O = !1;
196
+ if (d) {
197
+ let e = /* @__PURE__ */ new Set();
198
+ for (let t of D) for (let n of o.get(t) ?? []) {
199
+ if (e.has(n)) continue;
200
+ e.add(n), a.comparisons++;
201
+ let t = s[n];
202
+ E[0] < t[2] + u && t[0] < E[2] + u && E[1] < t[3] + u && t[1] < E[3] + u && (O = !0);
203
+ }
204
+ }
205
+ if (O) a.hidden++;
206
+ else {
207
+ if (d) {
208
+ let e = s.push(E) - 1;
209
+ for (let t of D) {
210
+ let n = o.get(t);
211
+ n || o.set(t, n = []), n.push(e);
212
+ }
213
+ }
214
+ if (this.data.length < (a.glyphs + x.glyphs.length) * 20) {
215
+ let e = new Float32Array(Math.max((a.glyphs + x.glyphs.length) * 20, this.data.length * 2, 320));
216
+ e.set(this.data), this.data = e;
217
+ }
218
+ for (let e of x.glyphs) {
219
+ let { bitmap: t, slot: n } = e.record, r = a.glyphs++ * 20, i = this.options.atlasSize;
220
+ this.data.set([
221
+ p,
222
+ m,
223
+ h,
224
+ 1,
225
+ e.rect[0] + S,
226
+ e.rect[1] + C,
227
+ e.rect[2] + S,
228
+ e.rect[3] + C,
229
+ n.x / i,
230
+ n.y / i,
231
+ (n.x + t.width) / i,
232
+ (n.y + t.height) / i,
233
+ ...c.color ?? [
234
+ 1,
235
+ 1,
236
+ 1,
237
+ 1
238
+ ],
239
+ n.page,
240
+ +!!t.color,
241
+ this.font.radius,
242
+ this.font.cutoff
243
+ ], r);
244
+ }
245
+ a.labels++;
246
+ }
247
+ }
248
+ for (let e of this.shapes.keys()) f.has(e) || this.shapes.delete(e);
249
+ return this.data.subarray(0, a.glyphs * 20);
250
+ }
251
+ shape(e, n) {
252
+ let r = this.shapes.get(e);
253
+ if (r) return r;
254
+ let i = n.fontSize ?? 16, a = i / this.font.size, o = this.api.layoutText(n.text, {
255
+ fontSize: i,
256
+ anchorX: "center",
257
+ anchorY: "middle"
258
+ }, this.font);
259
+ r = {
260
+ layout: o,
261
+ glyphs: [],
262
+ bounds: [
263
+ Infinity,
264
+ Infinity,
265
+ -Infinity,
266
+ -Infinity
267
+ ]
268
+ };
269
+ for (let e of o.glyphs) {
270
+ if (e.whitespace) continue;
271
+ let n = this.font.glyph(e.cluster);
272
+ if (!n) continue;
273
+ let i = this.records.get(n);
274
+ if (!i) {
275
+ let e = this.packer.pack(n.width, n.height);
276
+ if (!e) throw t("state", "label atlas full; increase atlasSize or maxPages", "labels");
277
+ let r = new Uint8Array(n.width * n.height * 4);
278
+ if (n.color) r.set(n.data);
279
+ else for (let e = 0; e < n.data.length; e++) r[e * 4] = n.data[e], r[e * 4 + 3] = 255;
280
+ i = {
281
+ bitmap: n,
282
+ slot: e,
283
+ pixels: r
284
+ }, this.records.set(n, i);
285
+ }
286
+ let o = e.x + n.left * a, s = -e.y - n.top * a, c = [
287
+ o,
288
+ s,
289
+ o + n.width * a,
290
+ s + n.height * a
291
+ ];
292
+ for (let e = 0; e < 4; e++) r.bounds[e] = e < 2 ? Math.min(r.bounds[e], c[e]) : Math.max(r.bounds[e], c[e]);
293
+ r.glyphs.push({
294
+ record: i,
295
+ rect: c
296
+ });
297
+ }
298
+ return this.shapes.set(e, r), r;
299
+ }
300
+ setup(e) {
301
+ this.engine = e;
302
+ }
303
+ registerPasses(e) {
304
+ e.add({
305
+ name: this.name,
306
+ order: this.order,
307
+ execute: (e) => this.draw(e)
308
+ });
309
+ }
310
+ draw(e) {
311
+ let t = this.engine.canvas, n = u(t), r = e.view?.viewport ?? [
312
+ 0,
313
+ 0,
314
+ e.width,
315
+ e.height
316
+ ], i = r[2] * (n.width || e.width) / e.width, a = r[3] * (n.height || e.height) / e.height;
317
+ this.matrix.set(e.camera.matrix);
318
+ let o = this.prepare(this.matrix, i, a, e.backend);
319
+ if (!o.length) return;
320
+ let c = [...this.records.values()];
321
+ e.backend === "webgl2" ? (this.gl ??= new s(e.gl), this.gl.draw(e, o, this.matrix, i, a, this.options.atlasSize, this.packer.pageCount, c)) : this.drawGPU(e, o, i, a, c), this.stats.drawCalls = 1;
322
+ }
323
+ drawGPU(t, n, a, o, s) {
324
+ let c = t.device;
325
+ c !== this.device && (this.releaseGPU(), this.device = c);
326
+ let l = `${t.format}/${t.descriptor.multisample?.count ?? 1}`;
327
+ if (!this.pipeline || l !== this.pipelineKey) {
328
+ let e = c.createShaderModule({ code: i });
329
+ this.pipeline = c.createRenderPipeline({
330
+ layout: "auto",
331
+ vertex: {
332
+ module: e,
333
+ entryPoint: "vertex",
334
+ buffers: [{
335
+ arrayStride: 80,
336
+ stepMode: "instance",
337
+ attributes: Array.from({ length: 5 }, (e, t) => ({
338
+ shaderLocation: t,
339
+ offset: t * 16,
340
+ format: "float32x4"
341
+ }))
342
+ }]
343
+ },
344
+ fragment: {
345
+ module: e,
346
+ entryPoint: "fragment",
347
+ targets: [{
348
+ format: t.format,
349
+ blend: {
350
+ color: {
351
+ srcFactor: "one",
352
+ dstFactor: "one-minus-src-alpha"
353
+ },
354
+ alpha: {
355
+ srcFactor: "one",
356
+ dstFactor: "one-minus-src-alpha"
357
+ }
358
+ }
359
+ }]
360
+ },
361
+ primitive: { topology: "triangle-list" },
362
+ multisample: t.descriptor.multisample
363
+ }), this.pipelineKey = l, this.group = void 0;
364
+ }
365
+ if (this.uniform ??= c.createBuffer({
366
+ size: 80,
367
+ usage: 72
368
+ }), this.sampler ??= c.createSampler({
369
+ minFilter: "linear",
370
+ magFilter: "linear"
371
+ }), !this.instances || n.byteLength > this.capacity) {
372
+ if (this.instances?.destroy(), this.capacity = Math.max(320, n.byteLength), this.capacity > c.limits.maxBufferSize) throw e("glyph buffer exceeds device limit; reduce collection size", "labels");
373
+ this.instances = c.createBuffer({
374
+ size: this.capacity,
375
+ usage: 40
376
+ });
377
+ }
378
+ if (this.uploaded !== s.length) {
379
+ this.texture?.destroy(), this.texture = c.createTexture({
380
+ size: [
381
+ this.options.atlasSize,
382
+ this.options.atlasSize,
383
+ this.packer.pageCount
384
+ ],
385
+ format: "rgba8unorm",
386
+ usage: 6
387
+ });
388
+ for (let e of s) c.queue.writeTexture({
389
+ texture: this.texture,
390
+ origin: [
391
+ e.slot.x,
392
+ e.slot.y,
393
+ e.slot.page
394
+ ]
395
+ }, e.pixels, { bytesPerRow: e.bitmap.width * 4 }, [
396
+ e.bitmap.width,
397
+ e.bitmap.height,
398
+ 1
399
+ ]);
400
+ this.uploaded = s.length, this.group = void 0;
401
+ }
402
+ this.group ??= c.createBindGroup({
403
+ layout: this.pipeline.getBindGroupLayout(0),
404
+ entries: [
405
+ {
406
+ binding: 0,
407
+ resource: { buffer: this.uniform }
408
+ },
409
+ {
410
+ binding: 1,
411
+ resource: this.sampler
412
+ },
413
+ {
414
+ binding: 2,
415
+ resource: this.texture.createView({ dimension: "2d-array" })
416
+ }
417
+ ]
418
+ }), this.frame.set(this.matrix), this.frame.set([
419
+ a,
420
+ o,
421
+ 0,
422
+ 0
423
+ ], 16), c.queue.writeBuffer(this.uniform, 0, this.frame), c.queue.writeBuffer(this.instances, 0, n);
424
+ let u = t.encoder.beginRenderPass({ colorAttachments: [{
425
+ view: t.color,
426
+ loadOp: "load",
427
+ storeOp: "store"
428
+ }] });
429
+ r(u, t), u.setPipeline(this.pipeline), u.setBindGroup(0, this.group), u.setVertexBuffer(0, this.instances), u.draw(6, n.length / 20), u.end();
430
+ }
431
+ releaseGPU() {
432
+ this.uniform?.destroy(), this.instances?.destroy(), this.texture?.destroy(), this.uniform = this.instances = void 0, this.texture = void 0, this.group = void 0, this.pipeline = void 0, this.sampler = void 0, this.device = void 0, this.uploaded = -1;
433
+ }
434
+ onDeviceRestored(e) {
435
+ this.releaseGPU(), this.gl?.dispose(), this.gl = void 0, this.engine = e;
436
+ }
437
+ dispose() {
438
+ let e = this.engine;
439
+ this.engine = void 0, e?.sceneOf(this)?.removePlugin(this.name), this.releaseGPU(), this.gl?.dispose(), this.gl = void 0, this.engine = void 0;
440
+ }
441
+ [Symbol.dispose]() {
442
+ this.dispose();
443
+ }
444
+ };
445
+ //#endregion
446
+ export { d as GPULabelLayer };