nanoodle 0.13.3 → 0.14.1

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,112 @@
1
+ export function number(fields, key, fallback, min, max, integer = false) {
2
+ const value = fields[key] == null || fields[key] === "" ? fallback : Number(fields[key]);
3
+ if (!Number.isFinite(value) || value < min || value > max || (integer && !Number.isInteger(value)))
4
+ throw new Error(
5
+ key + " must be " + (integer ? "an integer " : "") + "between " + min + " and " + max + ".",
6
+ );
7
+ return value;
8
+ }
9
+
10
+ export function viewPlan(sheet, fields) {
11
+ const tile = sheet.height,
12
+ layers = sheet.width / tile;
13
+ if (!Number.isInteger(layers) || layers < 8 || layers > 128 || tile < 16 || tile > 128)
14
+ throw new Error("Expected a horizontal Slice 3D sheet with 8–128 square tiles of 16–128 pixels.");
15
+ const pitch = (number(fields, "pitch", 30, 0, 90) * Math.PI) / 180,
16
+ scale = number(fields, "scale", 3, 1, 8);
17
+ const spacing = (number(fields, "spacing", 1, 0, 4) * (tile - 2)) / layers;
18
+ const rise = spacing * Math.cos(pitch),
19
+ squash = Math.max(1 / tile, Math.sin(pitch));
20
+ // Fixed even bounds for every yaw, including both turntable endpoints.
21
+ const floor = tile * Math.SQRT2;
22
+ const w = 2 * Math.ceil((floor * scale + 4) / 2),
23
+ h = 2 * Math.ceil(((floor * squash + rise * (layers - 1)) * scale + 4) / 2);
24
+ return { tile, layers, scale, rise, squash, w, h };
25
+ }
26
+
27
+ // Scan transparency once per sheet. Empty sky and empty layers are common in a sliced mesh.
28
+ function occupiedLayers(sheet, plan) {
29
+ const { tile, layers, rise, scale, h } = plan;
30
+ const result = [];
31
+ for (let layer = 0; layer < layers; layer++) {
32
+ let left = tile, top = tile, right = 0, bottom = 0;
33
+ for (let y = 0; y < tile; y++) {
34
+ let alpha = (y * sheet.width + layer * tile) * 4 + 3;
35
+ for (let x = 0; x < tile; x++, alpha += 4) {
36
+ if (!sheet.data[alpha]) continue;
37
+ left = Math.min(left, x);
38
+ right = Math.max(right, x + 1);
39
+ top = Math.min(top, y);
40
+ bottom = y + 1;
41
+ }
42
+ }
43
+ if (right === 0) continue;
44
+ result.push({
45
+ offset: layer * tile,
46
+ x: (left + right - tile) / 2, y: (top + bottom - tile) / 2,
47
+ halfWidth: (right - left) / 2, halfHeight: (bottom - top) / 2,
48
+ cy: h / 2 + ((layers - 1) / 2 - layer) * rise * scale,
49
+ });
50
+ }
51
+ return result;
52
+ }
53
+
54
+ // Invert the orthographic transform at each output pixel center, then composite
55
+ // layers in ground-to-top order. draw() can be reused for every turntable angle.
56
+ export function softwareView(sheet, fields) {
57
+ const plan = viewPlan(sheet, fields);
58
+ const { tile, scale, squash, w, h } = plan;
59
+ const layers = occupiedLayers(sheet, plan);
60
+ return function draw(yaw) {
61
+ const data = new Uint8ClampedArray(w * h * 4);
62
+ const angle = (yaw * Math.PI) / 180, c = Math.cos(angle), s = Math.sin(angle);
63
+ const cosX = new Float64Array(w), sinX = new Float64Array(w);
64
+ for (let x = 0; x < w; x++) {
65
+ const dx = (x + 0.5 - w / 2) / scale;
66
+ cosX[x] = c * dx;
67
+ sinX[x] = -s * dx;
68
+ }
69
+ for (const layer of layers) {
70
+ const cx = w / 2 + scale * (c * layer.x - s * layer.y);
71
+ const cy = layer.cy + scale * squash * (s * layer.x + c * layer.y);
72
+ const rx = scale * (Math.abs(c) * layer.halfWidth + Math.abs(s) * layer.halfHeight);
73
+ const ry = scale * squash * (Math.abs(s) * layer.halfWidth + Math.abs(c) * layer.halfHeight);
74
+ const left = Math.max(0, Math.floor(cx - rx)), right = Math.min(w, Math.ceil(cx + rx));
75
+ const top = Math.max(0, Math.floor(cy - ry)), bottom = Math.min(h, Math.ceil(cy + ry));
76
+ for (let y = top; y < bottom; y++) {
77
+ const dy = (y + 0.5 - layer.cy) / (scale * squash);
78
+ const sinY = s * dy, cosY = c * dy;
79
+ for (let x = left; x < right; x++) {
80
+ const u = Math.floor(cosX[x] + sinY + tile / 2), v = Math.floor(sinX[x] + cosY + tile / 2);
81
+ if (u < 0 || u >= tile || v < 0 || v >= tile) continue;
82
+ const src = (v * sheet.width + layer.offset + u) * 4, alpha = sheet.data[src + 3];
83
+ if (!alpha) continue;
84
+ const dst = (y * w + x) * 4;
85
+ if (alpha === 255 || !data[dst + 3]) {
86
+ data[dst] = sheet.data[src];
87
+ data[dst + 1] = sheet.data[src + 1];
88
+ data[dst + 2] = sheet.data[src + 2];
89
+ data[dst + 3] = alpha;
90
+ } else {
91
+ const under = data[dst + 3] * (1 - alpha / 255), a = alpha + under;
92
+ for (let k = 0; k < 3; k++)
93
+ data[dst + k] = (sheet.data[src + k] * alpha + data[dst + k] * under) / a;
94
+ data[dst + 3] = a;
95
+ }
96
+ }
97
+ }
98
+ }
99
+ return { width: w, height: h, data };
100
+ };
101
+ }
102
+
103
+ export function flag(value, fallback) {
104
+ return value == null ? fallback : value === true || value === "true";
105
+ }
106
+ export function turntablePlan(fields) {
107
+ const fps = number(fields, "fps", 24, 1, 60, true),
108
+ duration = number(fields, "duration", 3, 0.25, 30);
109
+ const from = number(fields, "yawStart", 0, -3600, 3600),
110
+ to = number(fields, "yawEnd", 360, -3600, 3600);
111
+ return { fps, duration, from, to, count: Math.max(2, Math.round(fps * duration)) };
112
+ }
@@ -0,0 +1,357 @@
1
+ // Grid coordinates are (column, row, layer). Each square tile has the same
2
+ // world-to-pixel scale in both directions; layer thickness is recorded separately.
3
+ function gridFor(model, axis, size, layers) {
4
+ const axes = { x: [1, 2, 0, -1], y: [0, 2, 1, 1], z: [0, 1, 2, -1] }[axis];
5
+ if (!axes) throw new Error("Up axis must be auto, x, y or z.");
6
+ const [u, v, h, sign] = axes,
7
+ min = [Infinity, Infinity, Infinity],
8
+ max = min.map(() => -Infinity);
9
+ function grow(x, y, z) {
10
+ min[0] = Math.min(min[0], x);
11
+ min[1] = Math.min(min[1], y);
12
+ min[2] = Math.min(min[2], z);
13
+ max[0] = Math.max(max[0], x);
14
+ max[1] = Math.max(max[1], y);
15
+ max[2] = Math.max(max[2], z);
16
+ }
17
+ for (const m of model.meshes || []) {
18
+ const p = m.positions;
19
+ for (let i = 0; i < p.length; i += 3) grow(p[i], p[i + 1], p[i + 2]);
20
+ }
21
+ for (const s of model.splats || []) {
22
+ const [x, y, z] = s.center,
23
+ [a, b, c] = s.extent;
24
+ grow(x - a, y - b, z - c);
25
+ grow(x + a, y + b, z + c);
26
+ }
27
+ const span = Math.max(...min.map((n, i) => max[i] - n));
28
+ if (!(span > 0) || !Number.isFinite(span)) throw new Error("Model bounds have no usable extent.");
29
+ const unit = span / (size - 2),
30
+ step = span / layers,
31
+ cu = (max[u] + min[u]) / 2,
32
+ cv = (max[v] + min[v]) / 2;
33
+ return {
34
+ size,
35
+ layers,
36
+ unit,
37
+ step,
38
+ axes,
39
+ min,
40
+ max,
41
+ project(p) {
42
+ return [(p[u] - cu) / unit + size / 2, (sign * (p[v] - cv)) / unit + size / 2, (p[h] - min[h]) / step];
43
+ },
44
+ world(x, y, l) {
45
+ const p = [];
46
+ p[u] = (x - size / 2) * unit + cu;
47
+ p[v] = sign * (y - size / 2) * unit + cv;
48
+ p[h] = min[h] + l * step;
49
+ return p;
50
+ },
51
+ };
52
+ }
53
+
54
+ function wrap(t, mode) {
55
+ if (mode === 33071) return Math.min(1, Math.max(0, t));
56
+ if (mode === 33648) return 1 - Math.abs((((t % 2) + 2) % 2) - 1);
57
+ return t - Math.floor(t);
58
+ }
59
+ function srgb(v) {
60
+ return v < 0.0031308 ? 12.92 * v : 1.055 * Math.pow(v, 1 / 2.4) - 0.055;
61
+ }
62
+ function linear(v) {
63
+ return v < 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
64
+ }
65
+
66
+ function sample(mesh, ids, weights) {
67
+ const color = mesh.factor.slice();
68
+ function interpolate(attr, channel) {
69
+ return weights.reduce((sum, w, j) => sum + w * attr.data[ids[j] * attr.n + channel], 0);
70
+ }
71
+ if (mesh.color) for (let k = 0; k < mesh.color.n; k++) color[k] *= interpolate(mesh.color, k);
72
+ if (mesh.texture) {
73
+ const { pixels, sampler } = mesh.texture;
74
+ const x = Math.min(
75
+ pixels.width - 1,
76
+ Math.floor(wrap(interpolate(mesh.uv, 0), sampler.wrapS) * pixels.width),
77
+ );
78
+ const y = Math.min(
79
+ pixels.height - 1,
80
+ Math.floor(wrap(interpolate(mesh.uv, 1), sampler.wrapT) * pixels.height),
81
+ );
82
+ const p = (y * pixels.width + x) * 4;
83
+ for (let k = 0; k < 3; k++) color[k] *= linear(pixels.data[p + k] / 255);
84
+ color[3] *= pixels.data[p + 3] / 255;
85
+ }
86
+ const alpha =
87
+ mesh.alphaMode === "OPAQUE" ? 1 : mesh.alphaMode === "MASK" ? Number(color[3] >= mesh.cutoff) : color[3];
88
+ return [srgb(color[0]) * 255, srgb(color[1]) * 255, srgb(color[2]) * 255, alpha * 255];
89
+ }
90
+
91
+ // Scan a triangle in an axis-aligned projection at cell centers. The dominant
92
+ // projection catches vertical walls and flat caps. A floor projection also
93
+ // supplies signed ray intersections for filling closed interiors.
94
+ function scanTriangle(verts, a, b, width, height, visit) {
95
+ const [p, q, r] = verts;
96
+ const dx = q[a] - p[a],
97
+ dy = q[b] - p[b],
98
+ ex = r[a] - p[a],
99
+ ey = r[b] - p[b];
100
+ const det = dx * ey - dy * ex;
101
+ if (Math.abs(det) < 1e-12) return;
102
+ const startX = Math.max(0, Math.ceil(Math.min(p[a], q[a], r[a]) - 0.5));
103
+ const startY = Math.max(0, Math.ceil(Math.min(p[b], q[b], r[b]) - 0.5));
104
+ const endX = Math.min(width - 1, Math.floor(Math.max(p[a], q[a], r[a]) - 0.5));
105
+ const endY = Math.min(height - 1, Math.floor(Math.max(p[b], q[b], r[b]) - 0.5));
106
+ for (let y = startY; y <= endY; y++)
107
+ for (let x = startX; x <= endX; x++) {
108
+ const px = x + 0.5 - p[a],
109
+ py = y + 0.5 - p[b];
110
+ const v = (px * ey - py * ex) / det,
111
+ w = (dx * py - dy * px) / det,
112
+ u = 1 - v - w;
113
+ if (Math.min(u, v, w) >= -1e-8) visit(x, y, [u, v, w], Math.sign(det));
114
+ }
115
+ }
116
+
117
+ function paintMesh(grid, model, put) {
118
+ const { size, layers } = grid,
119
+ dims = [size, size, layers],
120
+ rays = new Array(size * size);
121
+ for (const mesh of model.meshes) {
122
+ const points = [];
123
+ for (let i = 0; i < mesh.positions.length; i += 3)
124
+ points.push(grid.project(mesh.positions.subarray(i, i + 3)));
125
+ for (let i = 0; i + 2 < mesh.length; i += mesh.mode === 4 ? 3 : 1) {
126
+ const corners =
127
+ mesh.mode === 6
128
+ ? [0, i + 1, i + 2]
129
+ : mesh.mode === 5 && i % 2
130
+ ? [i + 1, i, i + 2]
131
+ : [i, i + 1, i + 2];
132
+ const ids = mesh.idx ? corners.map((k) => mesh.idx[k]) : corners,
133
+ verts = ids.map((k) => points[k]);
134
+ const [p, q, r] = verts,
135
+ planes = [
136
+ [0, 1, 2],
137
+ [1, 2, 0],
138
+ [2, 0, 1],
139
+ ];
140
+ const areas = planes.map(([a, b]) =>
141
+ Math.abs((q[a] - p[a]) * (r[b] - p[b]) - (q[b] - p[b]) * (r[a] - p[a])),
142
+ );
143
+ const dominant = areas.indexOf(Math.max(...areas));
144
+ if (!areas[dominant]) continue;
145
+ let painted = false;
146
+ for (const j of dominant === 0 ? [0] : [dominant, 0]) {
147
+ const [a, b, c] = planes[j];
148
+ scanTriangle(verts, a, b, dims[a], dims[b], (x, y, weights, sign) => {
149
+ const depth = weights.reduce((s, w, k) => s + w * verts[k][c], 0);
150
+ const color = sample(mesh, ids, weights);
151
+ if (j === dominant) {
152
+ const cell = [];
153
+ cell[a] = x;
154
+ cell[b] = y;
155
+ cell[c] = Math.min(dims[c] - 1, Math.max(0, Math.floor(depth)));
156
+ put(...cell, color);
157
+ painted = true;
158
+ }
159
+ if (j === 0) (rays[y * size + x] ||= []).push({ depth, sign, color });
160
+ });
161
+ }
162
+ // A subpixel triangle may cover no cell center in any projection.
163
+ if (!painted) {
164
+ const cell = dims.map((d, k) => Math.min(d - 1, Math.max(0, Math.floor((p[k] + q[k] + r[k]) / 3))));
165
+ put(...cell, sample(mesh, ids, [1 / 3, 1 / 3, 1 / 3]));
166
+ }
167
+ }
168
+ }
169
+ for (let i = 0; i < rays.length; i++) {
170
+ const ray = rays[i];
171
+ if (!ray || ray.length < 2) continue;
172
+ ray.sort((a, b) => a.depth - b.depth);
173
+ // Collapse shared triangle edges before counting volume crossings.
174
+ const hits = [];
175
+ for (const hit of ray) {
176
+ const prev = hits.at(-1);
177
+ if (prev && Math.abs(prev.depth - hit.depth) < 1e-6) prev.sum += hit.sign;
178
+ else hits.push({ ...hit, sum: hit.sign });
179
+ }
180
+ if (hits.reduce((n, h) => n + Math.sign(h.sum), 0) !== 0) continue;
181
+ let winding = 0;
182
+ for (let k = 0; k + 1 < hits.length; k++) {
183
+ const a = hits[k],
184
+ b = hits[k + 1];
185
+ winding += Math.sign(a.sum);
186
+ if (!winding) continue;
187
+ for (let l = Math.max(0, Math.ceil(a.depth - 0.5)); l < layers && l + 0.5 < b.depth; l++)
188
+ put(i % size, Math.floor(i / size), l, l + 0.5 < (a.depth + b.depth) / 2 ? a.color : b.color, true);
189
+ }
190
+ }
191
+ }
192
+
193
+ function paintSplats(grid, model, rgba, index) {
194
+ const { size, layers, axes, unit, step } = grid,
195
+ weights = new Float32Array(rgba.length / 4);
196
+ const dims = [size, size, layers];
197
+ for (const s of model.splats) {
198
+ const center = grid.project(s.center);
199
+ const radius = [s.extent[axes[0]] / unit, s.extent[axes[1]] / unit, s.extent[axes[2]] / step];
200
+ const lo = center.map((n, i) => Math.max(0, Math.floor(n - radius[i])));
201
+ const hi = center.map((n, i) => Math.min(dims[i] - 1, Math.floor(n + radius[i])));
202
+ const peak = center.map((n, i) => Math.min(dims[i] - 1, Math.max(0, Math.floor(n))));
203
+ for (let l = lo[2]; l <= hi[2]; l++)
204
+ for (let y = lo[1]; y <= hi[1]; y++)
205
+ for (let x = lo[0]; x <= hi[0]; x++) {
206
+ const d = grid.world(x + 0.5, y + 0.5, l + 0.5).map((v, k) => v - s.center[k]);
207
+ const atCenter = x === peak[0] && y === peak[1] && l === peak[2];
208
+ let distance = 0;
209
+ for (let k = 0; k < 3; k++)
210
+ distance +=
211
+ ((d[0] * s.rotation[k * 4] + d[1] * s.rotation[k * 4 + 1] + d[2] * s.rotation[k * 4 + 2]) /
212
+ s.scales[k]) **
213
+ 2;
214
+ if (distance > 9 && !atCenter) continue;
215
+ const alpha = s.alpha * Math.exp(-0.5 * (atCenter ? 0 : distance));
216
+ if (alpha < 0.5 / 255) continue;
217
+ const p = index(x, y, l),
218
+ old = weights[p / 4],
219
+ sum = old + alpha;
220
+ for (let k = 0; k < 3; k++) rgba[p + k] = (rgba[p + k] * old + s.color[k] * alpha) / sum;
221
+ rgba[p + 3] += alpha * (255 - rgba[p + 3]);
222
+ weights[p / 4] = sum;
223
+ }
224
+ }
225
+ }
226
+
227
+ // Weighted median-cut over 5-bit RGB bins. Small supplied palettes keep their
228
+ // exact colors, including near-neighbors in the same histogram bin.
229
+ function paletteOf(data, limit) {
230
+ const exact = new Set(),
231
+ hist = new Map();
232
+ for (let p = 0; p < data.length; p += 4) {
233
+ if (!data[p + 3]) continue;
234
+ const r = data[p],
235
+ g = data[p + 1],
236
+ b = data[p + 2],
237
+ key = (r >> 3) * 1024 + (g >> 3) * 32 + (b >> 3);
238
+ if (exact.size <= limit) exact.add(r * 65536 + g * 256 + b);
239
+ const bin = hist.get(key) || [0, 0, 0, 0];
240
+ bin[0] += r;
241
+ bin[1] += g;
242
+ bin[2] += b;
243
+ bin[3]++;
244
+ hist.set(key, bin);
245
+ }
246
+ if (!exact.size) throw new Error("Palette source has no visible pixels.");
247
+ if (exact.size <= limit) return [...exact].map((c) => [c >> 16, (c >> 8) & 255, c & 255]);
248
+ const bins = [...hist.values()].map(([r, g, b, n]) => [r / n, g / n, b / n, n]);
249
+ function box(colors) {
250
+ const low = [255, 255, 255],
251
+ high = [0, 0, 0];
252
+ let count = 0;
253
+ for (const c of colors) {
254
+ for (let k = 0; k < 3; k++) {
255
+ low[k] = Math.min(low[k], c[k]);
256
+ high[k] = Math.max(high[k], c[k]);
257
+ }
258
+ count += c[3];
259
+ }
260
+ const range = high.map((v, k) => v - low[k]),
261
+ span = Math.max(...range);
262
+ return { colors, count, axis: range.indexOf(span), score: colors.length > 1 ? span * count : 0 };
263
+ }
264
+ const boxes = [box(bins)];
265
+ while (boxes.length < limit) {
266
+ boxes.sort((a, b) => b.score - a.score);
267
+ if (!boxes[0].score) break;
268
+ const { colors, count, axis } = boxes.shift();
269
+ colors.sort((a, b) => a[axis] - b[axis]);
270
+ let cut = 0,
271
+ weight = 0;
272
+ do {
273
+ weight += colors[cut++][3];
274
+ } while (cut < colors.length - 1 && weight < count / 2);
275
+ boxes.push(box(colors.slice(0, cut)), box(colors.slice(cut)));
276
+ }
277
+ return boxes.map(({ colors, count }) =>
278
+ [0, 1, 2].map((k) => Math.round(colors.reduce((n, c) => n + c[k] * c[3], 0) / count)),
279
+ );
280
+ }
281
+
282
+ export function slicePixels(model, { size, layers, axis, palette, outline }, supplied) {
283
+ if (axis === "auto") axis = model.kind === "splat" ? "z" : "y";
284
+ const grid = gridFor(model, axis, size, layers),
285
+ width = size * layers,
286
+ rgba = new Uint8ClampedArray(width * size * 4);
287
+ const index = (x, y, l) => (y * width + l * size + x) * 4;
288
+ if (model.kind === "splat") paintSplats(grid, model, rgba, index);
289
+ else
290
+ paintMesh(grid, model, (x, y, l, c, onlyEmpty = false) => {
291
+ const p = index(x, y, l);
292
+ if (c[3] && (!onlyEmpty || !rgba[p + 3])) rgba.set(c, p);
293
+ });
294
+ let ink = [24, 24, 24];
295
+ if (palette && (supplied || rgba.some((v, i) => i % 4 === 3 && v))) {
296
+ // Reserve one ink color for generated palettes. An explicit reference
297
+ // palette supplies its own darkest color for the outline.
298
+ const reserveInk = outline && !supplied && palette > 1;
299
+ const colors = paletteOf(supplied?.data || rgba, palette - Number(reserveInk));
300
+ if (!reserveInk) ink = colors.reduce((a, b) => (a[0] + a[1] + a[2] <= b[0] + b[1] + b[2] ? a : b));
301
+ const cache = new Map();
302
+ for (let p = 0; p < rgba.length; p += 4) {
303
+ if (!rgba[p + 3]) continue;
304
+ const key = rgba[p] * 65536 + rgba[p + 1] * 256 + rgba[p + 2];
305
+ let color = cache.get(key);
306
+ if (!color) {
307
+ let best = Infinity;
308
+ for (const c of colors) {
309
+ const d = (c[0] - rgba[p]) ** 2 + (c[1] - rgba[p + 1]) ** 2 + (c[2] - rgba[p + 2]) ** 2;
310
+ if (d < best) {
311
+ best = d;
312
+ color = c;
313
+ }
314
+ }
315
+ cache.set(key, color);
316
+ }
317
+ rgba.set(color, p);
318
+ }
319
+ }
320
+ if (outline) {
321
+ const before = rgba.slice();
322
+ for (let l = 0; l < layers; l++)
323
+ for (let y = 0; y < size; y++)
324
+ for (let x = 0; x < size; x++) {
325
+ const p = index(x, y, l);
326
+ if (before[p + 3]) continue;
327
+ const alpha = Math.max(
328
+ x > 0 ? before[p - 4 + 3] : 0,
329
+ x + 1 < size ? before[p + 4 + 3] : 0,
330
+ y > 0 ? before[p - width * 4 + 3] : 0,
331
+ y + 1 < size ? before[p + width * 4 + 3] : 0,
332
+ );
333
+ if (alpha) {
334
+ rgba.set(ink, p);
335
+ rgba[p + 3] = alpha;
336
+ }
337
+ }
338
+ }
339
+ return {
340
+ rgba,
341
+ width,
342
+ height: size,
343
+ layout: {
344
+ version: 1,
345
+ order: "bottom-to-top",
346
+ columns: layers,
347
+ rows: 1,
348
+ tileWidth: size,
349
+ tileHeight: size,
350
+ upAxis: axis,
351
+ source: model.kind,
352
+ bounds: { min: grid.min, max: grid.max },
353
+ pixelSize: grid.unit,
354
+ layerHeight: grid.step,
355
+ },
356
+ };
357
+ }
@@ -0,0 +1,152 @@
1
+ import { number, viewPlan, softwareView, flag, turntablePlan } from "./sprite-projection.mjs";
2
+ import { encodePngRgba } from "./local-media.mjs";
3
+ import { encodeSpriteMp4 } from "./sprite-video.mjs";
4
+ import { MediaRef, bytesToDataUrl } from "./media.mjs";
5
+ import { gaussianModel, triangleModel } from "./sprite-model.mjs";
6
+ import { slicePixels } from "./sprite-slices.mjs";
7
+
8
+ function canvas(width, height) {
9
+ if (typeof document === "undefined") throw new Error("Sprite stacking requires a browser with Canvas 2D.");
10
+ const el = document.createElement("canvas");
11
+ el.width = width;
12
+ el.height = height;
13
+ return el;
14
+ }
15
+ async function bitmap(blob) {
16
+ if (typeof createImageBitmap === "function") return createImageBitmap(blob);
17
+ const url = URL.createObjectURL(blob),
18
+ img = new Image();
19
+ try {
20
+ img.src = url;
21
+ await img.decode();
22
+ return img;
23
+ } finally {
24
+ URL.revokeObjectURL(url);
25
+ }
26
+ }
27
+ async function imagePixels(blob) {
28
+ const img = await bitmap(blob);
29
+ try {
30
+ const ctx = canvas(img.width, img.height).getContext("2d", { willReadFrequently: true });
31
+ ctx.drawImage(img, 0, 0);
32
+ return ctx.getImageData(0, 0, img.width, img.height);
33
+ } finally {
34
+ img.close?.();
35
+ }
36
+ }
37
+ async function readMedia(value, ctx) {
38
+ const media = new MediaRef(String(value), { fetch: ctx?.fetch });
39
+ return media.bytes({ signal: ctx?.signal });
40
+ }
41
+ function png(el) {
42
+ const result = el.toDataURL("image/png");
43
+ if (!result.startsWith("data:image/png")) throw new Error("The atlas exceeds this browser’s canvas limit.");
44
+ return result;
45
+ }
46
+
47
+ function stackView(sheet, fields) {
48
+ const { tile, layers, scale, rise, squash, w, h } = viewPlan(sheet, fields);
49
+ const el = canvas(w, h),
50
+ ctx = el.getContext("2d", { willReadFrequently: flag(fields.turntable, false) });
51
+ function draw(yaw) {
52
+ ctx.resetTransform();
53
+ ctx.clearRect(0, 0, w, h);
54
+ ctx.imageSmoothingEnabled = false;
55
+ const a = (yaw * Math.PI) / 180,
56
+ c = Math.cos(a) * scale,
57
+ s = Math.sin(a) * scale;
58
+ for (let l = 0; l < layers; l++) {
59
+ ctx.setTransform(c, s * squash, -s, c * squash, w / 2, h / 2 + ((layers - 1) / 2 - l) * rise * scale);
60
+ ctx.drawImage(sheet, l * tile, 0, tile, tile, -tile / 2, -tile / 2, tile, tile);
61
+ }
62
+ ctx.resetTransform();
63
+ }
64
+ return { el, ctx, draw };
65
+ }
66
+
67
+ async function frameUrl(frame) {
68
+ return bytesToDataUrl(await encodePngRgba(frame.width, frame.height, frame.data), "image/png");
69
+ }
70
+
71
+ async function encodeTurntable(draw, fields, signal) {
72
+ const { duration, from, to, count } = turntablePlan(fields);
73
+ async function* frames() {
74
+ let lastYield = performance.now();
75
+ for (let i = 0; i < count; i++) {
76
+ // Give the editor and Node event loop time to deliver cancellation between frames.
77
+ if (performance.now() - lastYield >= 16) {
78
+ await new Promise((resolve) => setTimeout(resolve, 0));
79
+ lastYield = performance.now();
80
+ }
81
+ signal?.throwIfAborted();
82
+ yield draw(from + ((to - from) * i) / (count - 1));
83
+ }
84
+ }
85
+ return bytesToDataUrl(await encodeSpriteMp4(frames(), duration), "video/mp4");
86
+ }
87
+
88
+ export async function slice3d(node, inp, ctx) {
89
+ if (!inp.model) throw new Error("Wire a 3D model into Slice 3D.");
90
+ const fields = node.fields || {},
91
+ size = number(fields, "resolution", 48, 16, 128, true),
92
+ layers = number(fields, "slices", 48, 8, 128, true);
93
+ const headless = typeof document === "undefined";
94
+ const pixels = headless
95
+ ? (await import("./sprite-image.mjs")).decodeSpriteBytes
96
+ : (raw, mime) => imagePixels(new Blob([raw], { type: mime }));
97
+ const bytes = await readMedia(inp.model, ctx);
98
+ const model =
99
+ bytes[0] === 112 && bytes[1] === 108 && bytes[2] === 121
100
+ ? gaussianModel(bytes)
101
+ : await triangleModel(bytes, pixels);
102
+ const palette = number(fields, "palette", 16, 0, 64, true);
103
+ const supplied = palette && inp.paletteImage ? await pixels(await readMedia(inp.paletteImage, ctx)) : null;
104
+ ctx?.signal?.throwIfAborted();
105
+ const sliced = slicePixels(
106
+ model,
107
+ { size, layers, axis: fields.upAxis || "auto", outline: flag(fields.outline, true), palette },
108
+ supplied,
109
+ );
110
+ if (headless) {
111
+ const sheet = { width: sliced.width, height: sliced.height, data: sliced.rgba };
112
+ return {
113
+ sheet: await frameUrl(sheet),
114
+ layout: JSON.stringify(sliced.layout),
115
+ image: await frameUrl(softwareView(sheet, {})(35)),
116
+ };
117
+ }
118
+ const el = canvas(size * layers, size);
119
+ el.getContext("2d").putImageData(new ImageData(sliced.rgba, sliced.width, sliced.height), 0, 0);
120
+ const view = stackView(el, {});
121
+ view.draw(35);
122
+ return { sheet: png(el), layout: JSON.stringify(sliced.layout), image: png(view.el) };
123
+ }
124
+
125
+ export async function renderSpriteStack(node, inp, ctx) {
126
+ if (!inp.sheet) throw new Error("Wire the Slice 3D sheet into Sprite stack render.");
127
+ const fields = node.fields || {},
128
+ bytes = await readMedia(inp.sheet, ctx);
129
+ const yaw = number(fields, "yaw", 35, -3600, 3600);
130
+ if (typeof document === "undefined") {
131
+ const { decodeSpriteBytes } = await import("./sprite-image.mjs");
132
+ const sheet = await decodeSpriteBytes(bytes);
133
+ const draw = softwareView(sheet, fields);
134
+ const image = await frameUrl(draw(yaw));
135
+ if (!flag(fields.turntable, false)) return { image };
136
+ return { image, video: await encodeTurntable(draw, fields, ctx?.signal) };
137
+ }
138
+ const sheet = await bitmap(new Blob([bytes]));
139
+ try {
140
+ const view = stackView(sheet, fields);
141
+ view.draw(yaw);
142
+ const image = png(view.el);
143
+ if (!flag(fields.turntable, false)) return { image };
144
+ const draw = (angle) => {
145
+ view.draw(angle);
146
+ return view.ctx.getImageData(0, 0, view.el.width, view.el.height);
147
+ };
148
+ return { image, video: await encodeTurntable(draw, fields, ctx?.signal) };
149
+ } finally {
150
+ sheet.close?.();
151
+ }
152
+ }