@margoengine/pixel 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,124 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin } from '@margoengine/core/extension';
4
+ /** A palette colour: `#rrggbb` or `[r, g, b]` bytes. */
5
+ export type PaletteColor = string | readonly [number, number, number];
6
+ /** How close two colours are: in Oklab, which follows what the eye sees, or plain sRGB values. */
7
+ export type PaletteDistance = 'oklab' | 'srgb';
8
+ /** The pattern that nudges colours before matching. `'none'` matches each colour as it is. */
9
+ export type PaletteDither = 'none' | 'bayer2' | 'bayer4' | 'bayer8' | 'blue-noise';
10
+ /** A palette as sRGB values from 0 to 1, `[r, g, b]` per colour. */
11
+ export type PaletteRGB = readonly (readonly [number, number, number])[];
12
+ /** Reads palette colours to sRGB values from 0 to 1. @throws RangeError for an empty, oversized or unreadable palette. */
13
+ export declare function readPalette(colors: readonly PaletteColor[]): [number, number, number][];
14
+ /** sRGB values from 0 to 1 to Oklab `[L, a, b]`. */
15
+ export declare function oklabFromSRGB(r: number, g: number, b: number): [number, number, number];
16
+ /** Oklab `[L, a, b]` to sRGB values, clamped to 0 to 1. */
17
+ export declare function sRGBFromOklab(L: number, a: number, b: number): [number, number, number];
18
+ /** Turns each colour's hue by `degrees` in Oklab, keeping its lightness and chroma as far as sRGB can. Returns `#rrggbb`. */
19
+ export declare function shiftPaletteHue(colors: readonly PaletteColor[], degrees: number): string[];
20
+ /** `steps` colours from `from` to `to`, evenly spaced in Oklab, ends included. Returns `#rrggbb`. */
21
+ export declare function paletteRamp(from: PaletteColor, to: PaletteColor, steps: number): string[];
22
+ /** A run of palette entries that cycles: {@link cyclePalette}. */
23
+ export interface PaletteCycle {
24
+ /** First index of the run. */
25
+ from: number;
26
+ /** Last index of the run, included; above `from`. */
27
+ to: number;
28
+ /** Entries a second the colours move toward `to`; below 0 toward `from`. */
29
+ rate: number;
30
+ /** Mixes each step in Oklab instead of jumping a whole entry at a time. Default false. */
31
+ blend?: boolean;
32
+ }
33
+ /**
34
+ * The palette at time `seconds` with each run's colours rotated along it, for water, fire and conveyor belts drawn in
35
+ * a few palette entries: entry `from + i` shows the colour that started at `from + (i - rate * seconds)`, wrapping
36
+ * inside the run. Entries outside every run stay. Feed it to {@link PaletteQuantize.setSwap} each frame. Returns
37
+ * `#rrggbb`.
38
+ */
39
+ export declare function cyclePalette(colors: readonly PaletteColor[], cycles: readonly PaletteCycle[], seconds: number): string[];
40
+ /**
41
+ * Each entry mixed from `a` toward `b` by `t` (0 gives `a`, 1 gives `b`) in Oklab, for day and night or seasons: two
42
+ * palettes of the same length, one index meaning the same thing in both. Returns `#rrggbb`.
43
+ */
44
+ export declare function mixPalettes(a: readonly PaletteColor[], b: readonly PaletteColor[], t: number): string[];
45
+ /**
46
+ * The ordered dither matrix of side `size` (2, 4 or 8), row by row: each value `(rank + 0.5) / size^2`, so every value is
47
+ * above 0 and below 1. @throws RangeError for another size.
48
+ */
49
+ export declare function bayerMatrix(size: 2 | 4 | 8): Float32Array;
50
+ /**
51
+ * A tiling blue-noise threshold matrix of side `size`, by the void-and-cluster method: a seeded pattern settles until its
52
+ * tightest cluster is also its largest void, then pixels are ranked by removing clusters and filling voids. Same size and
53
+ * seed, same matrix. Each value is `(rank + 0.5) / size^2`.
54
+ */
55
+ export declare function blueNoise(size?: number, seed?: number): Float32Array;
56
+ /** The threshold matrix of a dither mode and its side, or undefined for `'none'`. @throws RangeError for another mode. */
57
+ export declare function ditherMatrix(mode: PaletteDither): {
58
+ size: number;
59
+ values: Float32Array;
60
+ } | undefined;
61
+ /**
62
+ * Which palette entry a colour (sRGB values from 0 to 1) matches: the CPU form of the pass, for tools and tests. `palette`
63
+ * is what {@link readPalette} returns; `threshold` is the pattern's value at this pixel, if any.
64
+ */
65
+ export declare function nearestPaletteIndex(r: number, g: number, b: number, palette: PaletteRGB, distance?: PaletteDistance, threshold?: number, spread?: number): number;
66
+ /** Settings of {@link PaletteQuantize}. */
67
+ export interface PaletteQuantizeOptions {
68
+ /** The colours to reduce to, 1 to 256. Required. */
69
+ palette: readonly PaletteColor[];
70
+ /** What each match draws instead of its palette colour: palette swap, same length. Default the palette itself. */
71
+ swap?: readonly PaletteColor[];
72
+ /** The picture to read, one sample per pixel, or a function returning it such as a pixel layer's `target`. Required. */
73
+ source: GPUTexture | (() => GPUTexture);
74
+ /** Where the result goes, as large as `source` or larger; pixels past `source` clear. It must be another texture. Required. */
75
+ target: GPUTexture | (() => GPUTexture);
76
+ /** Default `'oklab'`. */
77
+ distance?: PaletteDistance;
78
+ /** Read each frame. Default `'none'`. */
79
+ dither?: PaletteDither;
80
+ /** Finite, non-negative pattern strength in sRGB values, read each frame. Default 0.125. */
81
+ spread?: number;
82
+ /** Colours in `source` are multiplied by alpha, as in a pixel layer, and stay so in `target`. Default true. */
83
+ premultiplied?: boolean;
84
+ /** Frame-graph order. Runs after the sprites and maps (10), before a compositor (30). Default 20. */
85
+ order?: number;
86
+ /** Plugin name, unique per scene. Default `palette-1`, `palette-2`, ... */
87
+ name?: string;
88
+ }
89
+ /**
90
+ * Reduces a low-res picture to a palette, with optional ordered or blue-noise dithering and palette swap: one frame-graph
91
+ * pass from `source` to `target`, once a frame. Each pixel becomes exactly one palette colour (alpha kept). WebGPU only.
92
+ * @throws TypeError / RangeError on invalid options or, each frame, an invalid field.
93
+ * @throws MargoError `'unsupported'` on a WebGL engine, `'disposed'` after `dispose()`, `'state'` when the source and the
94
+ * target are the same texture.
95
+ */
96
+ export declare class PaletteQuantize implements EnginePlugin {
97
+ #private;
98
+ readonly name: string;
99
+ /** The pattern, read each frame. */
100
+ dither: PaletteDither;
101
+ /** How far the pattern moves a colour, read each frame. */
102
+ spread: number;
103
+ constructor(options: PaletteQuantizeOptions);
104
+ /** Creates a pass and attaches it to `instance`. */
105
+ static attach(instance: EngineKernel, options: PaletteQuantizeOptions): PaletteQuantize;
106
+ /** Replaces the palette and the swap colours from the next frame. */
107
+ setPalette(palette: readonly PaletteColor[], swap?: readonly PaletteColor[]): void;
108
+ /**
109
+ * Replaces only the colours drawn for each match, from the next frame, writing them into the texture already made:
110
+ * the matching stays, so it is cheap enough for every frame (palette cycling, day and night).
111
+ */
112
+ setSwap(swap: readonly PaletteColor[]): void;
113
+ /**
114
+ * Replaces the source from the next frame. A plain texture belongs to the engine's device as it is now, so call this from
115
+ * `onDeviceRestored` to bring a lost one back; a function is read every frame and needs nothing.
116
+ */
117
+ setSource(source: GPUTexture | (() => GPUTexture)): void;
118
+ /** Replaces the target from the next frame, by the same rule as `setSource`. */
119
+ setTarget(target: GPUTexture | (() => GPUTexture)): void;
120
+ setup(engine: Engine): void;
121
+ onDeviceRestored(): void;
122
+ dispose(): void;
123
+ [Symbol.dispose]: () => void;
124
+ }
@@ -0,0 +1,344 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const i=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { n as e, r as t, t as n } from "./errors-CDgOgzCd.js";
5
+ import { t as r } from "./texture-option-3VFmNske.js";
6
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
7
+ import { hexColor as a } from "@margoengine/math";
8
+ //#region src/palette.ts
9
+ function o(t) {
10
+ if (!Array.isArray(t) || !t.length || t.length > 256) throw e("A palette holds 1 to 256 colours", "pixel-palette");
11
+ return t.map((t, n) => {
12
+ let r = typeof t == "string" ? a(t)?.slice(0, 3) : Array.isArray(t) && t.length === 3 && t.every((e) => e >= 0 && e <= 255) ? t.map((e) => e / 255) : void 0;
13
+ if (!r) throw e(`Invalid palette colour at index ${n}: use #rrggbb or three RGB bytes in [0, 255]`, "pixel-palette");
14
+ return r;
15
+ });
16
+ }
17
+ var s = (e) => e <= .04045 ? e / 12.92 : ((e + .055) / 1.055) ** 2.4, c = (e) => e <= .0031308 ? e * 12.92 : 1.055 * e ** (1 / 2.4) - .055;
18
+ function l(e, t, n) {
19
+ let r = s(e), i = s(t), a = s(n), o = Math.cbrt(.4122214708 * r + .5363325363 * i + .0514459929 * a), c = Math.cbrt(.2119034982 * r + .6806995451 * i + .1073969566 * a), l = Math.cbrt(.0883024619 * r + .2817188376 * i + .6299787005 * a);
20
+ return [
21
+ .2104542553 * o + .793617785 * c - .0040720468 * l,
22
+ 1.9779984951 * o - 2.428592205 * c + .4505937099 * l,
23
+ .0259040371 * o + .7827717662 * c - .808675766 * l
24
+ ];
25
+ }
26
+ function u(e, t, n) {
27
+ let r = (e + .3963377774 * t + .2158037573 * n) ** 3, i = (e - .1055613458 * t - .0638541728 * n) ** 3, a = (e - .0894841775 * t - 1.291485548 * n) ** 3, o = (e) => Math.min(1, Math.max(0, c(Math.max(0, e))));
28
+ return [
29
+ o(4.0767416621 * r - 3.3077115913 * i + .2309699292 * a),
30
+ o(-1.2684380046 * r + 2.6097574011 * i - .3413193965 * a),
31
+ o(-.0041960863 * r - .7034186147 * i + 1.707614701 * a)
32
+ ];
33
+ }
34
+ var d = (e) => `#${e.map((e) => Math.round(e * 255).toString(16).padStart(2, "0")).join("")}`;
35
+ function f(t, n) {
36
+ if (!Number.isFinite(n)) throw e("Invalid degrees: must be finite", "pixel-palette");
37
+ let r = Math.cos(n * Math.PI / 180), i = Math.sin(n * Math.PI / 180);
38
+ return o(t).map(([e, t, n]) => {
39
+ let [a, o, s] = l(e, t, n);
40
+ return d(u(a, o * r - s * i, o * i + s * r));
41
+ });
42
+ }
43
+ function p(t, n, r) {
44
+ if (!Number.isInteger(r) || r < 2) throw e("Invalid steps: must be an integer of at least 2", "pixel-palette");
45
+ let [i, a] = o([t, n]).map(([e, t, n]) => l(e, t, n));
46
+ return Array.from({ length: r }, (e, t) => {
47
+ let n = t / (r - 1);
48
+ return d(u(...i.map((e, t) => e + (a[t] - e) * n)));
49
+ });
50
+ }
51
+ function m(t, r, i) {
52
+ let a = o(t), s = a.map((e) => d(e));
53
+ if (!Number.isFinite(i)) throw e("cyclePalette seconds must be a finite number", "pixel-palette");
54
+ let c = new Int32Array(a.length).fill(-1);
55
+ return r.forEach((t, r) => {
56
+ let { from: o, to: f, rate: p } = t;
57
+ if (!Number.isInteger(o) || !Number.isInteger(f) || o < 0 || f >= a.length || f <= o) throw e(`A palette cycle needs whole from < to inside the palette, got ${o} to ${f}`, "pixel-palette");
58
+ if (!Number.isFinite(p)) throw e("A palette cycle rate must be a finite number", "pixel-palette");
59
+ for (let t = o; t <= f; t++) {
60
+ if (c[t] >= 0) throw e(`Palette cycles ${c[t]} and ${r} must not share entry ${t}`, "pixel-palette");
61
+ c[t] = r;
62
+ }
63
+ let m = p * i;
64
+ if (!Number.isFinite(m)) throw n("state", "cyclePalette rate * seconds must be finite; reduce rate or seconds", "pixel-palette");
65
+ let h = f - o + 1, g = m % h, _ = Math.floor(g), v = t.blend ? g - _ : 0, y = (e) => o + (e % h + h) % h;
66
+ for (let e = 0; e < h; e++) {
67
+ let t = a[y(e - _)];
68
+ if (!v) {
69
+ s[o + e] = d(t);
70
+ continue;
71
+ }
72
+ let n = a[y(e - _ - 1)], r = l(...t), i = l(...n);
73
+ s[o + e] = d(u(...r.map((e, t) => e + (i[t] - e) * v)));
74
+ }
75
+ }), s;
76
+ }
77
+ function h(t, n, r) {
78
+ let i = o(t), a = o(n);
79
+ if (i.length !== a.length) throw e("mixPalettes needs two palettes of the same length", "pixel-palette");
80
+ if (!(r >= 0 && r <= 1)) throw e(`mixPalettes t must be between 0 and 1, got ${r}`, "pixel-palette");
81
+ return i.map((e, t) => {
82
+ let n = l(...e), i = l(...a[t]);
83
+ return d(u(...n.map((e, t) => e + (i[t] - e) * r)));
84
+ });
85
+ }
86
+ function g(t) {
87
+ if (![
88
+ 2,
89
+ 4,
90
+ 8
91
+ ].includes(t)) throw e("Invalid Bayer size: use 2, 4 or 8", "pixel-palette");
92
+ let n = new Float32Array(t * t);
93
+ for (let e = 0; e < t; e++) for (let r = 0; r < t; r++) {
94
+ let i = 0;
95
+ for (let n = 1; n < t; n <<= 1) i = i * 4 + ((r & n ? 2 : 0) ^ (e & n ? 3 : 0));
96
+ n[e * t + r] = (i + .5) / (t * t);
97
+ }
98
+ return n;
99
+ }
100
+ function _(t = 64, n = 1) {
101
+ if (!Number.isInteger(t) || t < 4 || t > 256) throw e("Invalid blue-noise size: must be an integer in [4, 256]", "pixel-palette");
102
+ let r = t * t, i = new Float64Array(r), a = new Float64Array(r), o = new Uint8Array(r), s = new Float32Array(r);
103
+ for (let e = 0; e < t; e++) for (let n = 0; n < t; n++) {
104
+ let r = Math.min(n, t - n), a = Math.min(e, t - e);
105
+ i[e * t + n] = Math.exp(-(r * r + a * a) / 4.5);
106
+ }
107
+ let c = (e, n) => {
108
+ o[e] = n;
109
+ let r = n ? 1 : -1, s = e % t, c = (e - s) / t;
110
+ for (let e = 0; e < t; e++) for (let n = 0; n < t; n++) a[e * t + n] += r * i[(e - c + t) % t * t + (n - s + t) % t];
111
+ }, l = (e) => {
112
+ let t = -1;
113
+ for (let n = 0; n < r; n++) o[n] === e && (t < 0 || (e ? a[n] > a[t] : a[n] < a[t])) && (t = n);
114
+ return t;
115
+ }, u = (Math.floor(n) ^ 2654435769) >>> 0 || 1, d = 0;
116
+ for (; d < r >> 3;) {
117
+ u ^= u << 13, u >>>= 0, u ^= u >>> 17, u ^= u << 5, u >>>= 0;
118
+ let e = u % r;
119
+ o[e] || (c(e, 1), d++);
120
+ }
121
+ for (let e = 0; e < r; e++) {
122
+ let e = l(1);
123
+ c(e, 0);
124
+ let t = l(0);
125
+ if (c(t, 1), t === e) break;
126
+ }
127
+ let f = o.slice(), p = a.slice();
128
+ for (let e = d - 1; e >= 0; e--) {
129
+ let t = l(1);
130
+ s[t] = e, c(t, 0);
131
+ }
132
+ o.set(f), a.set(p);
133
+ for (let e = d; e < r; e++) {
134
+ let t = l(0);
135
+ s[t] = e, c(t, 1);
136
+ }
137
+ for (let e = 0; e < r; e++) s[e] = (s[e] + .5) / r;
138
+ return s;
139
+ }
140
+ var v = {
141
+ none: 0,
142
+ bayer2: 2,
143
+ bayer4: 4,
144
+ bayer8: 8,
145
+ "blue-noise": 64
146
+ };
147
+ function y(t) {
148
+ let n = v[t];
149
+ if (!(n >= 0)) throw e("Invalid dither: use none, bayer2, bayer4, bayer8 or blue-noise", "pixel-palette");
150
+ return n ? {
151
+ size: n,
152
+ values: n > 8 ? _() : g(n)
153
+ } : void 0;
154
+ }
155
+ function b(e, t, n, r, i = "oklab", a, o = .125) {
156
+ let s = a === void 0 ? 0 : o * (a - .5), c = (e) => Math.min(1, Math.max(0, e + s)), u = (e, t, n) => i === "oklab" ? l(e, t, n) : [
157
+ e,
158
+ t,
159
+ n
160
+ ], d = u(c(e), c(t), c(n)), f = 0, p = Infinity;
161
+ return r.forEach((e, t) => {
162
+ let n = u(e[0], e[1], e[2]), r = (d[0] - n[0]) ** 2 + (d[1] - n[1]) ** 2 + (d[2] - n[2]) ** 2;
163
+ r < p && (p = r, f = t);
164
+ }), f;
165
+ }
166
+ var x = "\nstruct Settings {\n count: u32,\n side: u32,\n oklab: u32,\n straight: u32,\n spread: f32\n}\n@group(0) @binding(0) var<uniform> settings: Settings;\n@group(0) @binding(1) var image: texture_2d<f32>;\n@group(0) @binding(2) var candidates: texture_2d<f32>;\n@group(0) @binding(3) var shown: texture_2d<f32>;\n@group(0) @binding(4) var pattern: texture_2d<f32>;\n\n@vertex fn vertexMain(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {\n return vec4f(f32(i & 1u) * 4 - 1, f32(i >> 1u) * 4 - 1, 0, 1);\n}\n\nfn linear(v: f32) -> f32 {\n if (v <= 0.04045) { return v / 12.92; }\n return pow((v + 0.055) / 1.055, 2.4);\n}\n\nfn oklab(c: vec3f) -> vec3f {\n let r = linear(c.r);\n let g = linear(c.g);\n let b = linear(c.b);\n let l = pow(0.4122214708*r + 0.5363325363*g + 0.0514459929*b, 1.0/3.0);\n let m = pow(0.2119034982*r + 0.6806995451*g + 0.1073969566*b, 1.0/3.0);\n let k = pow(0.0883024619*r + 0.2817188376*g + 0.6299787005*b, 1.0/3.0);\n return vec3f(\n 0.2104542553*l + 0.793617785*m - 0.0040720468*k,\n 1.9779984951*l - 2.428592205*m + 0.4505937099*k,\n 0.0259040371*l + 0.7827717662*m - 0.808675766*k\n );\n}\n\n@fragment fn fragmentMain(@builtin(position) p: vec4f) -> @location(0) vec4f {\n let t = vec2i(p.xy);\n if (any(t >= vec2i(textureDimensions(image)))) { return vec4f(0); }\n let source = textureLoad(image, t, 0);\n if (source.a == 0) { return vec4f(0); }\n var c = source.rgb;\n if (settings.straight == 0u) { c /= source.a; }\n if (settings.side > 0u) {\n c += settings.spread * (textureLoad(pattern, vec2u(t) % settings.side, 0).r - 0.5);\n }\n c = clamp(c, vec3f(0), vec3f(1));\n if (settings.oklab == 1u) { c = oklab(c); }\n\n var best = 0u;\n var least = 1e30;\n for (var i = 0u; i < settings.count; i++) {\n let d = c - textureLoad(candidates, vec2u(i, 0u), 0).rgb;\n let e = dot(d, d);\n if (e < least) { least = e; best = i; }\n }\n let color = textureLoad(shown, vec2u(best, 0u), 0).rgb;\n if (settings.straight == 1u) { return vec4f(color, source.a); }\n return vec4f(color * source.a, source.a);\n}", S = 32, C = 0, w = class a {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
167
+ #e;
168
+ #t;
169
+ #n;
170
+ #r;
171
+ #i;
172
+ #a;
173
+ #o;
174
+ #s;
175
+ #c;
176
+ #l;
177
+ #u;
178
+ #d;
179
+ #f;
180
+ #p;
181
+ #m;
182
+ #h = /* @__PURE__ */ new Map();
183
+ #g;
184
+ #_;
185
+ #v;
186
+ #y = /* @__PURE__ */ new ArrayBuffer(S);
187
+ #b = !1;
188
+ constructor(n) {
189
+ if (!n?.palette || !n.source || !n.target) throw t("PaletteQuantize needs a palette, a source and a target", "pixel-palette");
190
+ let i = n.order ?? 20;
191
+ if (!Number.isFinite(i)) throw e("Invalid palette order: must be finite", "pixel-palette");
192
+ if (this.#e = new r(n.source, "PaletteQuantize source", "setSource"), this.#t = new r(n.target, "PaletteQuantize target", "setTarget"), this.#n = i, this.#r = n.distance ?? "oklab", this.#r !== "oklab" && this.#r !== "srgb") throw e("Invalid distance: use oklab or srgb", "pixel-palette");
193
+ this.dither = n.dither ?? "none", this.spread = n.spread ?? .125, this.#i = n.premultiplied === !1, this.name = n.name ?? `palette-${++C}`, this.setPalette(n.palette, n.swap);
194
+ }
195
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
196
+ let n = new a(t);
197
+ return i(e).use(n), n;
198
+ }
199
+ setPalette(t, n) {
200
+ let r = o(t), i = n ? o(n) : r;
201
+ if (i.length !== r.length) throw e("A palette swap has as many colours as its palette", "pixel-palette");
202
+ this.#a = r, this.#o = i, this.#x();
203
+ }
204
+ setSwap(t) {
205
+ let n = o(t);
206
+ if (n.length !== this.#a.length) throw e("A palette swap has as many colours as its palette", "pixel-palette");
207
+ if (this.#o = n, this.#m && this.#c) {
208
+ let e = new Uint8Array(n.length * 4);
209
+ n.forEach((t, n) => e.set([...t.map((e) => Math.round(e * 255)), 255], n * 4)), this.#c.queue.writeTexture({ texture: this.#m }, e, { bytesPerRow: e.byteLength }, [n.length, 1]);
210
+ }
211
+ }
212
+ setSource(e) {
213
+ if (!e) throw t("PaletteQuantize needs a source texture", "pixel-palette");
214
+ this.#e.set(e, this.#s?.gpu);
215
+ }
216
+ setTarget(e) {
217
+ if (!e) throw t("PaletteQuantize needs a target texture", "pixel-palette");
218
+ this.#t.set(e, this.#s?.gpu);
219
+ }
220
+ setup(e) {
221
+ if (this.#b) throw n("disposed", "PaletteQuantize disposed; create a new one");
222
+ if (e.backend !== "webgpu") throw n("unsupported", "PaletteQuantize needs WebGPU", "webgpu");
223
+ this.#s = e, this.#e.fix(e.gpu), this.#t.fix(e.gpu), e.frameGraph.add({
224
+ name: this.name,
225
+ order: this.#n,
226
+ execute: (e) => {
227
+ e.backend === "webgpu" && this.#E(e);
228
+ }
229
+ });
230
+ }
231
+ onDeviceRestored() {
232
+ this.#S();
233
+ }
234
+ dispose() {
235
+ this.#b || (this.#b = !0, this.#s?.sceneOf(this)?.removePlugin(this.name), this.#s = void 0, this.#S());
236
+ }
237
+ [Symbol.dispose ?? Symbol()]() {
238
+ this.dispose();
239
+ }
240
+ #x() {
241
+ this.#p?.destroy(), this.#m?.destroy(), this.#p = this.#m = this.#g = this.#_ = void 0;
242
+ }
243
+ #S() {
244
+ this.#x();
245
+ for (let e of this.#h.values()) e.destroy();
246
+ this.#h.clear(), this.#f?.destroy(), this.#f = this.#l = this.#c = this.#u = this.#d = void 0;
247
+ }
248
+ #C(e, t, n, r, i = 1) {
249
+ let a = e.createTexture({
250
+ size: [r, i],
251
+ format: t,
252
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST
253
+ });
254
+ return e.queue.writeTexture({ texture: a }, n, { bytesPerRow: n.byteLength / i }, [r, i]), a;
255
+ }
256
+ #w(e, t) {
257
+ let n = this.#h.get(t);
258
+ if (!n) {
259
+ let r = y(t);
260
+ n = r ? this.#C(e, "r32float", r.values, r.size, r.size) : this.#C(e, "r32float", /* @__PURE__ */ new Float32Array(1), 1), this.#h.set(t, n);
261
+ }
262
+ return n;
263
+ }
264
+ #T(e) {
265
+ if (this.#c !== e && (this.#c && this.#S(), this.#c = e), this.#l || (this.#l = e.createShaderModule({
266
+ label: "pixel palette",
267
+ code: x
268
+ }), this.#f = e.createBuffer({
269
+ label: "pixel palette",
270
+ size: S,
271
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
272
+ })), !this.#p) {
273
+ let t = this.#a.length, n = new Float32Array(t * 4), r = new Uint8Array(t * 4);
274
+ this.#a.forEach(([e, t, i], a) => {
275
+ n.set(this.#r === "oklab" ? l(e, t, i) : [
276
+ e,
277
+ t,
278
+ i
279
+ ], a * 4);
280
+ let o = this.#o[a];
281
+ r.set([...o.map((e) => Math.round(e * 255)), 255], a * 4);
282
+ }), this.#p = this.#C(e, "rgba32float", n, t), this.#m = this.#C(e, "rgba8unorm", r, t);
283
+ }
284
+ }
285
+ #E(t) {
286
+ if (t.view?.index) return;
287
+ let r = t.device, i = this.dither;
288
+ if (!Number.isFinite(this.spread) || this.spread < 0) throw e("Invalid spread: must be finite and non-negative", "pixel-palette");
289
+ this.#T(r);
290
+ let a = this.#e.get(r, this.#s), o = this.#t.get(r, this.#s);
291
+ if (!a || !o) return;
292
+ if (a === o) throw n("state", "Palette source and target must differ", "pixel-palette");
293
+ let s = this.#w(r, i);
294
+ o.format !== this.#d && (this.#d = o.format, this.#u = r.createRenderPipeline({
295
+ label: "pixel palette",
296
+ layout: "auto",
297
+ vertex: { module: this.#l },
298
+ fragment: {
299
+ module: this.#l,
300
+ targets: [{ format: o.format }]
301
+ }
302
+ }), this.#g = void 0), (!this.#g || this.#_ !== a || this.#v !== i) && (this.#g = r.createBindGroup({
303
+ layout: this.#u.getBindGroupLayout(0),
304
+ entries: [
305
+ {
306
+ binding: 0,
307
+ resource: { buffer: this.#f }
308
+ },
309
+ {
310
+ binding: 1,
311
+ resource: a.createView()
312
+ },
313
+ {
314
+ binding: 2,
315
+ resource: this.#p.createView()
316
+ },
317
+ {
318
+ binding: 3,
319
+ resource: this.#m.createView()
320
+ },
321
+ {
322
+ binding: 4,
323
+ resource: s.createView()
324
+ }
325
+ ]
326
+ }), this.#_ = a, this.#v = i);
327
+ let c = new Uint32Array(this.#y);
328
+ c[0] = this.#a.length, c[1] = i === "none" ? 0 : s.width, c[2] = +(this.#r === "oklab"), c[3] = +!!this.#i, new Float32Array(this.#y)[4] = this.spread, r.queue.writeBuffer(this.#f, 0, this.#y);
329
+ let l = t.encoder.beginRenderPass({ colorAttachments: [{
330
+ view: o.createView(),
331
+ loadOp: "clear",
332
+ clearValue: [
333
+ 0,
334
+ 0,
335
+ 0,
336
+ 0
337
+ ],
338
+ storeOp: "store"
339
+ }] });
340
+ l.setPipeline(this.#u), l.setBindGroup(0, this.#g), l.draw(3), l.end();
341
+ }
342
+ };
343
+ //#endregion
344
+ export { w as PaletteQuantize, g as bayerMatrix, _ as blueNoise, m as cyclePalette, y as ditherMatrix, h as mixPalettes, b as nearestPaletteIndex, l as oklabFromSRGB, p as paletteRamp, o as readPalette, u as sRGBFromOklab, f as shiftPaletteHue };
@@ -0,0 +1,139 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { Camera, EngineKernel, RenderView, Scene } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin } from '@margoengine/core/extension';
4
+ /** The outline drawn around what a low-res 3D view shows. */
5
+ export interface OutlineOptions {
6
+ /** `#rrggbb`. Default `#000000`. */
7
+ color?: string;
8
+ /** How much farther a neighbouring pixel must be to draw an outline on the nearer one, in world units. Default 0.1. */
9
+ depthEdge?: number;
10
+ /** The angle between surfaces that draws a crease line, in radians; 0 draws none. Default 0.6. */
11
+ crease?: number;
12
+ }
13
+ /** Settings of {@link Render3D}. */
14
+ export interface Render3DOptions {
15
+ /** The camera of the view. Required. */
16
+ camera: Camera;
17
+ /** Low-res size in pixels, whole numbers. Required. */
18
+ width: number;
19
+ /** Low-res size in pixels, whole numbers. Required. */
20
+ height: number;
21
+ /** Where the picture ends up, the same size, or a function returning it such as a pixel layer's `target`. Default a texture of its own, {@link Render3D.output}. */
22
+ target?: GPUTexture | (() => GPUTexture);
23
+ /** Outlines from depth and surface direction, or false for none. Default on. */
24
+ outline?: OutlineOptions | false;
25
+ /** What the view clears to, `#rrggbb`. Default transparent. */
26
+ background?: string;
27
+ /** The scene to draw. Default the engine's. */
28
+ scene?: Scene;
29
+ /** Render-layer bits of the view. Default every layer. */
30
+ layers?: number;
31
+ /** The engine's samples per pixel, `sceneSamples(engine)`: 1 with `exactSize` (unless `antialias: true`) or `antialias: false`, else its quality tier's. Default 1. */
32
+ samples?: number;
33
+ /** Frame-graph order of the outline pass, before a compositor (30). Default 20. */
34
+ order?: number;
35
+ /** Plugin name, unique per scene. Default `render3d-1`, `render3d-2`, ... */
36
+ name?: string;
37
+ }
38
+ /** What {@link outlineMask} reads, in the scene's own numbers. */
39
+ export interface OutlineFrame {
40
+ /** Depth values row by row; 0 is the far plane, where nothing was drawn. */
41
+ depth: Float32Array;
42
+ width: number;
43
+ height: number;
44
+ /** The camera's world-to-clip matrix, column-major. */
45
+ matrix: ArrayLike<number>;
46
+ /** The camera's position. */
47
+ eye: readonly [number, number, number];
48
+ /** The direction it looks in, unit length. */
49
+ forward: readonly [number, number, number];
50
+ }
51
+ /**
52
+ * The CPU form of the outline pass, for tools and tests: 1 where the outline draws. A drawn pixel is outlined when a
53
+ * neighbour is empty or farther by `depthEdge`, or when the surface direction turns by `crease` to the pixel right or below.
54
+ */
55
+ export declare function outlineMask(frame: OutlineFrame, options?: OutlineOptions): Uint8Array;
56
+ /**
57
+ * Draws the 3D scene small, for a pixel-art look: a view into a low-res target with depth, then an outline from depth and
58
+ * surface direction on the same pixels. Pass {@link view} to `render({views: [...]})` along with your canvas view, and
59
+ * draw the result through a compositor layer (`target: layer.target`). Each pixel is one source colour or the outline
60
+ * colour, never a blend. WebGPU only.
61
+ * @throws TypeError / RangeError on invalid options or, each frame, an invalid camera or outline value.
62
+ * @throws MargoError `'unsupported'` on a WebGL engine, `'disposed'` after `dispose()`, `'state'` when the view is read before
63
+ * the plugin is attached or the target does not fit.
64
+ */
65
+ export declare class Render3D implements EnginePlugin {
66
+ #private;
67
+ readonly name: string;
68
+ readonly width: number;
69
+ readonly height: number;
70
+ /** The outline settings, read each frame. False turns it off. */
71
+ outline: OutlineOptions | false;
72
+ constructor(options: Render3DOptions);
73
+ /** Creates a low-res view and attaches it to `instance`. */
74
+ static attach(instance: EngineKernel, options: Render3DOptions): Render3D;
75
+ /** The view to draw this frame. Read it each frame: it changes after a device loss. */
76
+ get view(): RenderView;
77
+ /**
78
+ * Replaces the target from the next frame (undefined: the picture goes to {@link Render3D.output}'s own texture). A plain
79
+ * texture belongs to the engine's device as it is now, so call this from `onDeviceRestored` to bring a lost one back; a
80
+ * function is read every frame and needs nothing.
81
+ */
82
+ setTarget(target: GPUTexture | (() => GPUTexture) | undefined): void;
83
+ /**
84
+ * The picture with its outline, when no `target` was given. A plain `target` lost with its device is reported once
85
+ * through `engine.onError`, and until `setTarget` hands in a new one the picture goes to the pass's own texture here.
86
+ */
87
+ get output(): GPUTexture;
88
+ /** The depth the view drew, for reading back with one sample per pixel. */
89
+ get depth(): GPUTexture;
90
+ /** The colour the view drew, before the outline. */
91
+ get color(): GPUTexture;
92
+ setup(engine: Engine): void;
93
+ onDeviceRestored(): void;
94
+ dispose(): void;
95
+ [Symbol.dispose]: () => void;
96
+ }
97
+ /** A captured sprite sheet. */
98
+ export interface SpriteFrames {
99
+ /** `rgba8unorm`, ready as a sprite atlas. Yours to destroy. */
100
+ texture: GPUTexture;
101
+ /** One frame per angle, in order: where it sits, and its angle in radians. */
102
+ frames: {
103
+ x: number;
104
+ y: number;
105
+ width: number;
106
+ height: number;
107
+ angle: number;
108
+ }[];
109
+ }
110
+ /** What to capture in {@link renderSpriteFrames}. */
111
+ export interface SpriteFramesOptions {
112
+ /** The camera to shoot with. Required. */
113
+ camera: Camera;
114
+ /** The turns about the Y axis to shoot, radians. At least one. */
115
+ angles: readonly number[];
116
+ /** Frame size in pixels. Required. */
117
+ width: number;
118
+ /** Frame size in pixels. Required. */
119
+ height: number;
120
+ /** Frames per row of the sheet. Default as many as angles. */
121
+ columns?: number;
122
+ /** Outlines on the frames, or false. Default on. */
123
+ outline?: OutlineOptions | false;
124
+ /** See {@link Render3DOptions.background}. Default transparent. */
125
+ background?: string;
126
+ /** See {@link Render3DOptions.samples}. Default 1. */
127
+ samples?: number;
128
+ }
129
+ /**
130
+ * Renders a mesh at several turns into one sprite sheet. Draws frames right away, with delta 0, and puts the mesh's
131
+ * rotation back. @throws RangeError for no angles or a bad size.
132
+ */
133
+ export declare function renderSpriteFrames(instance: EngineKernel, mesh: {
134
+ rotation: {
135
+ x: number;
136
+ y: number;
137
+ z: number;
138
+ };
139
+ }, options: SpriteFramesOptions): SpriteFrames;