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,233 @@
1
+ // BMP files and classic ICO entries store the same device-independent bitmap.
2
+ // A BMP supplies the pixel offset in a file header. ICO follows its color table
3
+ // immediately with XOR pixels and a separate 1-bit transparency plane.
4
+ function valid(condition, reason) {
5
+ if (!condition) throw new Error("Invalid BMP/ICO: " + reason);
6
+ }
7
+
8
+ function maskChannel(mask, depth) {
9
+ if (!mask) return null;
10
+ const shift = 31 - Math.clz32(mask & -mask);
11
+ const max = mask >>> shift;
12
+ valid((max & (max + 1)) === 0 && (depth === 32 || mask < 2 ** depth), "invalid color mask");
13
+ return { shift, max };
14
+ }
15
+
16
+ function valueFor(word, field) {
17
+ return Math.round(((((word >>> field.shift) & field.max) >>> 0) * 255) / field.max);
18
+ }
19
+
20
+ function writePalette(data, dst, palette, index) {
21
+ const p = index * 3;
22
+ valid(p + 2 < palette.length, "palette index out of range");
23
+ data[dst] = palette[p];
24
+ data[dst + 1] = palette[p + 1];
25
+ data[dst + 2] = palette[p + 2];
26
+ data[dst + 3] = 255;
27
+ }
28
+
29
+ function rlePixels(bytes, offset, width, height, depth, palette, data) {
30
+ let x = 0,
31
+ row = 0;
32
+ while (offset + 2 <= bytes.length) {
33
+ const count = bytes[offset++],
34
+ code = bytes[offset++];
35
+ if (!count) {
36
+ if (code === 1) return offset;
37
+ if (code === 0) {
38
+ x = 0;
39
+ row++;
40
+ continue;
41
+ }
42
+ if (code === 2) {
43
+ valid(offset + 2 <= bytes.length, "truncated RLE delta");
44
+ x += bytes[offset++];
45
+ row += bytes[offset++];
46
+ valid(x <= width && row < height, "RLE delta out of bounds");
47
+ continue;
48
+ }
49
+ }
50
+ const length = count || code;
51
+ valid(row < height && x + length <= width, "RLE run out of bounds");
52
+ const packed = Math.ceil((length * depth) / 8);
53
+ if (!count) valid(offset + ((packed + 1) & ~1) <= bytes.length, "truncated absolute RLE run");
54
+ let dst = ((height - row - 1) * width + x) * 4;
55
+ for (let n = 0; n < length; n++, dst += 4) {
56
+ const value = count ? code : bytes[offset + (depth === 8 ? n : n >> 1)];
57
+ const index = depth === 8 ? value : (value >> (n % 2 ? 0 : 4)) & 15;
58
+ writePalette(data, dst, palette, index);
59
+ }
60
+ if (!count) offset += (packed + 1) & ~1;
61
+ x += length;
62
+ }
63
+ throw new Error("Invalid BMP/ICO: missing RLE end marker");
64
+ }
65
+
66
+ function dib(bytes, pixelOffset, icon) {
67
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
68
+ const u16 = (p) => view.getUint16(p, true);
69
+ const u32 = (p) => view.getUint32(p, true);
70
+ const s32 = (p) => view.getInt32(p, true);
71
+ valid(bytes.length >= 12, "truncated bitmap header");
72
+ const header = u32(0);
73
+ const core = header === 12;
74
+ const os2 = core || header === 16 || header === 64;
75
+ valid(
76
+ [12, 16, 40, 52, 56, 64, 108, 124].includes(header) && header <= bytes.length,
77
+ "unsupported bitmap header",
78
+ );
79
+ const width = core ? u16(4) : s32(4);
80
+ const storedHeight = core ? u16(6) : s32(8);
81
+ const planes = u16(core ? 8 : 12),
82
+ depth = u16(core ? 10 : 14);
83
+ const topDown = storedHeight < 0;
84
+ const height = Math.abs(storedHeight) / (icon ? 2 : 1);
85
+ valid(planes === 1 && [1, 2, 4, 8, 16, 24, 32].includes(depth), "pixel format");
86
+ valid(
87
+ width > 0 &&
88
+ height > 0 &&
89
+ Number.isInteger(height) &&
90
+ height <= 8192 &&
91
+ width <= (height <= 128 ? 16384 : 8192),
92
+ "bitmap dimensions",
93
+ );
94
+ if (icon) valid(width === icon.width && height === icon.height, "icon dimensions disagree");
95
+ const compression = header >= 20 ? u32(16) : 0;
96
+ const bitfields = compression === 3 || compression === 6;
97
+ const rle = compression === 1 || compression === 2;
98
+ valid(
99
+ compression === 0 ||
100
+ (bitfields && !os2 && (depth === 16 || depth === 32)) ||
101
+ (rle && !topDown && ((depth === 8 && compression === 1) || (depth === 4 && compression === 2))),
102
+ "compression",
103
+ );
104
+
105
+ let offset = header;
106
+ let masks = depth === 16 ? [0x7c00, 0x03e0, 0x001f, 0] : [0xff0000, 0xff00, 0xff, 0];
107
+ if (bitfields) {
108
+ const count = compression === 6 || header >= 56 ? 4 : 3;
109
+ valid(
110
+ 40 + 4 * count <= bytes.length && (header === 40 || 40 + 4 * count <= header),
111
+ "truncated bitfields",
112
+ );
113
+ masks = [u32(40), u32(44), u32(48), count === 4 ? u32(52) : 0];
114
+ if (header === 40) offset += 4 * count;
115
+ valid(masks[0] && masks[1] && masks[2], "missing RGB mask");
116
+ } else if (!os2 && header >= 56 && depth >= 16) {
117
+ masks[3] = (u32(52) & (depth === 32 ? 0xffffffff : 2 ** depth - 1)) >>> 0;
118
+ }
119
+ if (icon && depth === 32 && !bitfields && !masks[3]) masks[3] = 0xff000000;
120
+ let fields;
121
+ if (depth === 16 || depth === 32 || masks[3]) {
122
+ let used = 0;
123
+ for (const mask of masks) {
124
+ valid(!(used & mask), "overlapping color masks");
125
+ used |= mask;
126
+ }
127
+ fields = masks.map((mask) => maskChannel(mask, depth));
128
+ }
129
+ const usedColors = header >= 36 ? u32(32) : 0;
130
+ const paletteSize = depth <= 8 ? usedColors || 2 ** depth : usedColors;
131
+ const entrySize = core ? 3 : 4;
132
+ valid(
133
+ (depth > 8 || paletteSize <= 2 ** depth) && offset + paletteSize * entrySize <= bytes.length,
134
+ "truncated palette",
135
+ );
136
+ let palette;
137
+ if (depth <= 8) {
138
+ palette = new Uint8Array(paletteSize * 3);
139
+ for (let n = 0; n < paletteSize; n++) {
140
+ const b = offset + n * entrySize;
141
+ palette[n * 3] = bytes[b + 2];
142
+ palette[n * 3 + 1] = bytes[b + 1];
143
+ palette[n * 3 + 2] = bytes[b];
144
+ }
145
+ }
146
+ offset += paletteSize * entrySize;
147
+ if (!icon) {
148
+ valid(pixelOffset >= offset && pixelOffset <= bytes.length, "invalid pixel offset");
149
+ offset = pixelOffset;
150
+ }
151
+ const stride = 4 * Math.ceil((width * depth) / 32);
152
+ valid(rle || offset + height * stride <= bytes.length, "truncated pixel rows");
153
+ const data = new Uint8ClampedArray(width * height * 4);
154
+ let populatedAlpha = false;
155
+ if (rle) {
156
+ // Delta moves and short rows leave opaque black pixels in browser BMPs.
157
+ for (let i = 3; i < data.length; i += 4) data[i] = 255;
158
+ offset = rlePixels(bytes, offset, width, height, depth, palette, data);
159
+ } else {
160
+ for (let y = 0; y < height; y++, offset += stride) {
161
+ let dst = (topDown ? y : height - 1 - y) * width * 4;
162
+ for (let x = 0; x < width; x++, dst += 4) {
163
+ if (depth <= 8) {
164
+ const bit = x * depth;
165
+ const index = (bytes[offset + (bit >> 3)] >> (8 - depth - (bit & 7))) & ((1 << depth) - 1);
166
+ writePalette(data, dst, palette, index);
167
+ } else if (depth === 24 || (depth === 32 && !bitfields && !masks[3])) {
168
+ const p = offset + x * (depth / 8);
169
+ data[dst] = bytes[p + 2];
170
+ data[dst + 1] = bytes[p + 1];
171
+ data[dst + 2] = bytes[p];
172
+ data[dst + 3] = 255;
173
+ } else {
174
+ const word = depth === 16 ? u16(offset + x * 2) : u32(offset + x * 4);
175
+ data[dst] = valueFor(word, fields[0]);
176
+ data[dst + 1] = valueFor(word, fields[1]);
177
+ data[dst + 2] = valueFor(word, fields[2]);
178
+ data[dst + 3] = fields[3] ? valueFor(word, fields[3]) : 255;
179
+ if (fields[3] && data[dst + 3]) populatedAlpha = true;
180
+ }
181
+ }
182
+ }
183
+ }
184
+ // A populated 32-bit icon alpha channel supersedes the legacy AND mask.
185
+ if (icon && !populatedAlpha) {
186
+ const maskStride = 4 * Math.ceil(width / 32);
187
+ valid(offset + maskStride * height <= bytes.length, "truncated icon transparency mask");
188
+ for (let y = 0; y < height; y++)
189
+ for (let x = 0; x < width; x++) {
190
+ const mask = bytes[offset + y * maskStride + (x >> 3)] & (128 >> (x & 7));
191
+ const dst = ((topDown ? y : height - 1 - y) * width + x) * 4;
192
+ if (mask) data.fill(0, dst, dst + 4);
193
+ else data[dst + 3] = 255;
194
+ }
195
+ }
196
+ return { width, height, data };
197
+ }
198
+
199
+ export function decodeBitmap(bytes) {
200
+ valid(bytes.length >= 26 && bytes[0] === 66 && bytes[1] === 77, "invalid BMP file header");
201
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
202
+ return dib(bytes.subarray(14), view.getUint32(10, true) - 14, null);
203
+ }
204
+
205
+ export async function decodeIcon(bytes, decodePng) {
206
+ valid(bytes.length >= 6, "truncated icon header");
207
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
208
+ const count = view.getUint16(4, true);
209
+ const kind = view.getUint16(2, true);
210
+ valid(
211
+ view.getUint16(0, true) === 0 && (kind === 1 || kind === 2) && count && 6 + count * 16 <= bytes.length,
212
+ "invalid icon directory",
213
+ );
214
+ let best;
215
+ for (let n = 0, p = 6; n < count; n++, p += 16) {
216
+ const width = bytes[p] || 256,
217
+ height = bytes[p + 1] || 256;
218
+ const depth = (kind === 1 && view.getUint16(p + 6, true)) || Math.ceil(Math.log2(bytes[p + 2] || 256));
219
+ const size = view.getUint32(p + 8, true),
220
+ offset = view.getUint32(p + 12, true);
221
+ valid(offset >= 6 + count * 16 && size && offset + size <= bytes.length, "icon entry out of bounds");
222
+ if (!best || width * height > best.area || (width * height === best.area && depth > best.depth)) {
223
+ best = { width, height, depth, area: width * height, offset, size };
224
+ }
225
+ }
226
+ const image = bytes.subarray(best.offset, best.offset + best.size);
227
+ if (image[0] === 137 && image[1] === 80) {
228
+ const rgba = await decodePng(image);
229
+ valid(rgba.width === best.width && rgba.height === best.height, "icon PNG dimensions disagree");
230
+ return rgba;
231
+ }
232
+ return dib(image, 0, best);
233
+ }
@@ -0,0 +1,73 @@
1
+ import { decodeBitmap, decodeIcon } from "./sprite-bitmap.mjs";
2
+ import { MAX_IMAGE_DIM } from "./local-media.mjs";
3
+ import { decodePngPixels } from "./png-decoder.mjs";
4
+ import { pngOrientation, orientImage } from "./sprite-orientation.mjs";
5
+
6
+ // ftyp lists a major brand, a minor version, then compatible brands. AVIF
7
+ // assets can use mif1 as the major brand and advertise avif only in the list.
8
+ function isAvifImage(bytes) {
9
+ if (bytes.length < 16 || bytes[4] !== 102 || bytes[5] !== 116 || bytes[6] !== 121 || bytes[7] !== 112)
10
+ return false;
11
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
12
+ let end = view.getUint32(0), start = 8;
13
+ if (end === 1) {
14
+ if (bytes.length < 24 || view.getUint32(8) !== 0) return false;
15
+ end = view.getUint32(12);
16
+ start = 16;
17
+ }
18
+ end = Math.min(end || bytes.length, bytes.length);
19
+ for (let i = start; i + 4 <= end; i += 4) {
20
+ if (i === start + 4) continue;
21
+ if (bytes[i] === 97 && bytes[i + 1] === 118 && bytes[i + 2] === 105 &&
22
+ (bytes[i + 3] === 102 || bytes[i + 3] === 115)) return true;
23
+ }
24
+ return false;
25
+ }
26
+
27
+ // Node loads the maintained decoder only for formats that need it. Its native
28
+ // binaries are installed with the npm package. The editor uses native bitmaps.
29
+ async function decodeRaster(bytes, format) {
30
+ const { default: sharp } = await import("sharp");
31
+ try {
32
+ const limitInputPixels = format === "JPEG" ? 16_777_216 : MAX_IMAGE_DIM ** 2;
33
+ const image = sharp(bytes, { pages: 1, failOn: "error", limitInputPixels });
34
+ const meta = await image.metadata();
35
+ if (meta.height > MAX_IMAGE_DIM || meta.width > (meta.height <= 128 ? 16384 : MAX_IMAGE_DIM))
36
+ throw new Error("dimensions exceed the sprite image limit");
37
+ // libavif interpolates 4:2:0 chroma the way the editor does. Metadata is
38
+ // bounded above before the WebAssembly decoder allocates its pixel buffer.
39
+ if (format === "AVIF") {
40
+ const { decodeAvif } = await import("./sprite-avif.mjs");
41
+ return await decodeAvif(bytes);
42
+ }
43
+ // JPEG respects EXIF orientation. The editor displays WebP in stored orientation.
44
+ if (format === "JPEG") image.autoOrient();
45
+ const { info, data } = await image.toColourspace("srgb").ensureAlpha().raw().toBuffer({ resolveWithObject: true });
46
+ return { width: info.width, height: info.height, data: new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength) };
47
+ } catch (error) {
48
+ throw new Error("Invalid " + format + " sprite image: " + error.message, { cause: error });
49
+ }
50
+ }
51
+
52
+ // All sprite inputs (textures, palettes and the renderer's strip) use the same
53
+ // straight-alpha pixel layout, independent of their on-disk encoding.
54
+ export async function decodeSpriteBytes(input) {
55
+ const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
56
+ if (bytes[0] === 66 && bytes[1] === 77) return decodeBitmap(bytes);
57
+ if (bytes[0] === 0 && bytes[1] === 0 && (bytes[2] === 1 || bytes[2] === 2) && bytes[3] === 0)
58
+ return decodeIcon(bytes, decodeSpriteBytes);
59
+ if (bytes[0] === 137 && bytes[1] === 80) {
60
+ const { w, h, rgba } = await decodePngPixels(bytes, {
61
+ maxDim: MAX_IMAGE_DIM,
62
+ allowSpriteStrip: true,
63
+ firstAnimationFrame: true,
64
+ });
65
+ return orientImage({ width: w, height: h, data: rgba }, pngOrientation(bytes));
66
+ }
67
+ if (bytes[0] === 255 && bytes[1] === 216) return decodeRaster(bytes, "JPEG");
68
+ if (bytes[0] === 71 && bytes[1] === 73 && bytes[2] === 70) return decodeRaster(bytes, "GIF");
69
+ if (isAvifImage(bytes)) return decodeRaster(bytes, "AVIF");
70
+ if (bytes[0] === 82 && bytes[1] === 73 && bytes[2] === 70 && bytes[3] === 70 &&
71
+ bytes[8] === 87 && bytes[9] === 69 && bytes[10] === 66 && bytes[11] === 80) return decodeRaster(bytes, "WebP");
72
+ throw new Error("Unsupported sprite image encoding. Expected PNG, JPEG, GIF, WebP, AVIF, BMP, ICO or CUR.");
73
+ }
@@ -0,0 +1,297 @@
1
+ import { dataUrlBytes, sniffMime } from "./media.mjs";
2
+
3
+ import { ident, mul, trs, xform, unpackGlb } from "./gltf-scene.mjs";
4
+
5
+ const decodeText = (bytes) => new TextDecoder().decode(bytes);
6
+ const components = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4 };
7
+ const glTypes = {
8
+ 5120: [1, "getInt8", 127],
9
+ 5121: [1, "getUint8", 255],
10
+ 5122: [2, "getInt16", 32767],
11
+ 5123: [2, "getUint16", 65535],
12
+ 5125: [4, "getUint32", 4294967295],
13
+ 5126: [4, "getFloat32", 1],
14
+ };
15
+
16
+ function unpack(bytes) {
17
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
18
+ if (bytes.length < 4 || view.getUint32(0, true) !== 0x46546c67) {
19
+ try {
20
+ return { json: JSON.parse(decodeText(bytes)) };
21
+ } catch {
22
+ throw new Error("Expected a GLB, a self-contained glTF 2 mesh, or a Gaussian PLY.");
23
+ }
24
+ }
25
+ return unpackGlb(bytes);
26
+ }
27
+
28
+ function embedded(uri) {
29
+ if (!uri?.startsWith("data:"))
30
+ throw new Error("External glTF buffers and images require a self-contained .gltf or .glb export.");
31
+ return dataUrlBytes(uri);
32
+ }
33
+
34
+ export async function triangleModel(bytes, imagePixels) {
35
+ const { json, bin } = unpack(bytes);
36
+ if (json?.asset?.version !== "2.0") throw new Error("Expected glTF 2.0.");
37
+ const unsupported = (json.extensionsRequired || []).filter((name) => name !== "EXT_texture_webp");
38
+ if (unsupported.length) throw new Error("Unsupported required glTF extensions: " + unsupported.join(", "));
39
+ const buffers = (json.buffers || []).map((b, i) => {
40
+ const data = b.uri ? embedded(b.uri).bytes : i === 0 && bin;
41
+ if (!data || data.length < b.byteLength) throw new Error("Missing or truncated glTF buffer.");
42
+ return data;
43
+ });
44
+ function bufferView(index) {
45
+ const bv = json.bufferViews?.[index],
46
+ buffer = buffers[bv?.buffer],
47
+ start = bv?.byteOffset ?? 0;
48
+ if (
49
+ !buffer ||
50
+ !Number.isSafeInteger(bv.byteLength) ||
51
+ start < 0 ||
52
+ bv.byteLength < 0 ||
53
+ start + bv.byteLength > buffer.length
54
+ )
55
+ throw new Error("Invalid glTF buffer view.");
56
+ if (bv.extensions?.EXT_meshopt_compression)
57
+ throw new Error("Meshopt-compressed buffers are unsupported.");
58
+ return buffer.subarray(start, start + bv.byteLength);
59
+ }
60
+ function accessor(index, shapes, count) {
61
+ const a = json.accessors?.[index],
62
+ spec = glTypes[a?.componentType];
63
+ if (!a || !spec || !shapes.includes(a.type) || a.sparse || a.bufferView == null)
64
+ throw new Error("Unsupported glTF accessor type or sparse encoding.");
65
+ const n = components[a.type],
66
+ [size, get, max] = spec,
67
+ buf = bufferView(a.bufferView);
68
+ const stride = json.bufferViews[a.bufferView].byteStride ?? n * size,
69
+ offset = a.byteOffset ?? 0;
70
+ if (
71
+ !Number.isSafeInteger(a.count) ||
72
+ a.count < 1 ||
73
+ (count != null && a.count !== count) ||
74
+ offset < 0 ||
75
+ stride < n * size ||
76
+ offset + (a.count - 1) * stride + n * size > buf.length
77
+ )
78
+ throw new Error("Invalid glTF accessor bounds or count.");
79
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength),
80
+ data = new Float64Array(n * a.count);
81
+ for (let i = 0; i < a.count; i++)
82
+ for (let c = 0; c < n; c++) {
83
+ const v = view[get](offset + i * stride + c * size, true);
84
+ if (!Number.isFinite(v)) throw new Error("Non-finite glTF attribute.");
85
+ data[i * n + c] = a.normalized ? Math.max(-1, v / max) : v;
86
+ }
87
+ return { data, n, count: a.count };
88
+ }
89
+ const textures = new Map();
90
+ async function texture(info) {
91
+ const tex = json.textures?.[info.index];
92
+ const useWebp = Object.hasOwn(tex?.extensions || {}, "EXT_texture_webp");
93
+ const source = useWebp ? tex.extensions.EXT_texture_webp?.source : tex?.source;
94
+ const img = json.images?.[source];
95
+ if (useWebp && (!Number.isSafeInteger(source) || source < 0 || !img))
96
+ throw new Error("Invalid EXT_texture_webp image source.");
97
+ if (!img || info.extensions?.KHR_texture_transform)
98
+ throw new Error("Unsupported base-color texture encoding or transform.");
99
+ if (useWebp && !img.uri && img.mimeType !== "image/webp")
100
+ throw new Error("EXT_texture_webp bufferView requires image/webp.");
101
+ if (!textures.has(source)) {
102
+ const image = img.uri ? embedded(img.uri) : { bytes: bufferView(img.bufferView), mime: img.mimeType };
103
+ const webp = sniffMime(image.bytes) === "image/webp";
104
+ if (useWebp && !webp) throw new Error("EXT_texture_webp source must contain a WebP image.");
105
+ textures.set(source, { pixels: await imagePixels(image.bytes, image.mime), webp });
106
+ }
107
+ const cached = textures.get(source);
108
+ if (useWebp && !cached.webp) throw new Error("EXT_texture_webp source must contain a WebP image.");
109
+ return { pixels: cached.pixels, sampler: json.samplers?.[tex.sampler] || {} };
110
+ }
111
+ const meshes = [];
112
+ async function emit(index, world) {
113
+ if (!json.meshes?.[index]) throw new Error("Missing glTF mesh.");
114
+ for (const p of json.meshes[index].primitives) {
115
+ const mode = p.mode ?? 4;
116
+ if (![4, 5, 6].includes(mode))
117
+ throw new Error(
118
+ "Slice 3D requires triangles. For a point-cloud preview, supply the original Gaussian PLY.",
119
+ );
120
+ if (p.targets?.length || p.extensions?.KHR_draco_mesh_compression)
121
+ throw new Error("Morph targets and Draco-compressed meshes are unsupported.");
122
+ const pos = accessor(p.attributes.POSITION, ["VEC3"]);
123
+ for (let i = 0; i < pos.data.length; i += 3) {
124
+ const point = xform(world, pos.data[i], pos.data[i + 1], pos.data[i + 2], false);
125
+ if (!point.every(Number.isFinite)) throw new Error("Invalid glTF scene transform.");
126
+ pos.data.set(point, i);
127
+ }
128
+ if (p.indices != null) {
129
+ const indexSpec = json.accessors?.[p.indices];
130
+ if (!indexSpec || ![5121, 5123, 5125].includes(indexSpec.componentType) || indexSpec.normalized)
131
+ throw new Error("glTF triangle indices must be unsigned integers.");
132
+ }
133
+ const idx = p.indices != null ? accessor(p.indices, ["SCALAR"]).data : null;
134
+ if (idx?.some((v) => !Number.isInteger(v) || v < 0 || v >= pos.count))
135
+ throw new Error("Invalid triangle index.");
136
+ const length = idx?.length ?? pos.count;
137
+ if (length < 3 || (mode === 4 && length % 3)) throw new Error("Incomplete triangle primitive.");
138
+ const mat = json.materials?.[p.material] || {},
139
+ pbr = mat.pbrMetallicRoughness || {},
140
+ info = pbr.baseColorTexture;
141
+ const factor = pbr.baseColorFactor ?? [1, 1, 1, 1];
142
+ if (
143
+ !Array.isArray(factor) ||
144
+ factor.length !== 4 ||
145
+ !factor.every((v) => Number.isFinite(v) && v >= 0 && v <= 1)
146
+ )
147
+ throw new Error("Invalid glTF base color factor.");
148
+ if (mat.alphaMode != null && !["OPAQUE", "MASK", "BLEND"].includes(mat.alphaMode))
149
+ throw new Error("Invalid glTF alpha mode.");
150
+ const color =
151
+ p.attributes.COLOR_0 == null ? null : accessor(p.attributes.COLOR_0, ["VEC3", "VEC4"], pos.count);
152
+ const uv = info
153
+ ? accessor(p.attributes["TEXCOORD_" + (info.texCoord ?? 0)], ["VEC2"], pos.count)
154
+ : null;
155
+ meshes.push({
156
+ positions: pos.data,
157
+ idx,
158
+ mode,
159
+ length,
160
+ color,
161
+ uv,
162
+ texture: info && (await texture(info)),
163
+ factor,
164
+ alphaMode: mat.alphaMode || "OPAQUE",
165
+ cutoff: mat.alphaCutoff ?? 0.5,
166
+ });
167
+ }
168
+ }
169
+ const active = new Set(),
170
+ nodes = json.nodes || [];
171
+ async function walk(i, parent) {
172
+ const node = nodes[i];
173
+ if (!node || active.has(i)) throw new Error("Invalid or cyclic glTF node tree.");
174
+ if (node.skin != null) throw new Error("Skinned meshes require a static mesh export.");
175
+ active.add(i);
176
+ const world = mul(
177
+ parent,
178
+ node.matrix ||
179
+ trs(node.translation || [0, 0, 0], node.rotation || [0, 0, 0, 1], node.scale || [1, 1, 1]),
180
+ );
181
+ if (node.mesh != null) await emit(node.mesh, world);
182
+ for (const child of node.children || []) await walk(child, world);
183
+ active.delete(i);
184
+ }
185
+ if (nodes.length) {
186
+ const children = new Set(nodes.flatMap((n) => n.children || []));
187
+ const roots =
188
+ json.scenes?.[json.scene ?? 0]?.nodes ?? nodes.map((_, i) => i).filter((i) => !children.has(i));
189
+ for (const root of roots) await walk(root, ident());
190
+ } else for (let i = 0; i < (json.meshes || []).length; i++) await emit(i, ident());
191
+ if (!meshes.length) throw new Error("No triangles in the selected glTF scene.");
192
+ return { kind: "mesh", meshes };
193
+ }
194
+
195
+ const plyTypes = {
196
+ char: glTypes[5120],
197
+ int8: glTypes[5120],
198
+ uchar: glTypes[5121],
199
+ uint8: glTypes[5121],
200
+ short: glTypes[5122],
201
+ int16: glTypes[5122],
202
+ ushort: glTypes[5123],
203
+ uint16: glTypes[5123],
204
+ int: [4, "getInt32"],
205
+ int32: [4, "getInt32"],
206
+ uint: glTypes[5125],
207
+ uint32: glTypes[5125],
208
+ float: glTypes[5126],
209
+ float32: glTypes[5126],
210
+ double: [8, "getFloat64"],
211
+ float64: [8, "getFloat64"],
212
+ };
213
+
214
+ export function gaussianModel(bytes) {
215
+ const head = decodeText(bytes.subarray(0, 65536)),
216
+ end = /^end_header\r?\n/m.exec(head);
217
+ if (!end) throw new Error("Missing PLY header terminator.");
218
+ const header = head.slice(0, end.index + end[0].length),
219
+ offset = new TextEncoder().encode(header).length;
220
+ let format,
221
+ count,
222
+ stride = 0,
223
+ element;
224
+ const props = new Map();
225
+ for (const line of header.trim().split(/\r?\n/)) {
226
+ const [key, a, b, version] = line.trim().split(/\s+/);
227
+ if (key === "format") {
228
+ if (b !== "1.0" || !["ascii", "binary_little_endian"].includes(a))
229
+ throw new Error("Supported Gaussian PLY formats are ASCII and binary little-endian 1.0.");
230
+ format = a;
231
+ }
232
+ if (key === "element") {
233
+ element = a;
234
+ if (a !== "vertex" && Number(b) !== 0)
235
+ throw new Error("Expected an uncompressed vertex-only Gaussian PLY.");
236
+ if (a === "vertex") count = Number(b);
237
+ }
238
+ if (key === "property" && element === "vertex") {
239
+ if (!plyTypes[a] || version || props.has(b))
240
+ throw new Error("Unsupported Gaussian PLY property encoding.");
241
+ props.set(b, { type: plyTypes[a], offset: stride, index: props.size });
242
+ stride += plyTypes[a][0];
243
+ }
244
+ }
245
+ const required = [
246
+ "x",
247
+ "y",
248
+ "z",
249
+ "opacity",
250
+ "scale_0",
251
+ "scale_1",
252
+ "scale_2",
253
+ "rot_0",
254
+ "rot_1",
255
+ "rot_2",
256
+ "rot_3",
257
+ ];
258
+ const dc = ["f_dc_0", "f_dc_1", "f_dc_2"],
259
+ rgb = ["red", "green", "blue"];
260
+ const hasDC = dc.every((p) => props.has(p));
261
+ if (!format || !required.every((p) => props.has(p)) || !(hasDC || rgb.every((p) => props.has(p))))
262
+ throw new Error(
263
+ "Expected Gaussian PLY positions, log scales, quaternion, opacity logit, and DC or RGB colors. Ordinary point clouds are unsupported.",
264
+ );
265
+ if (!hasDC && rgb.some((name) => props.get(name).type !== glTypes[5121]))
266
+ throw new Error(
267
+ "Gaussian RGB properties must be unsigned bytes, or supply floating-point DC coefficients.",
268
+ );
269
+ if (!Number.isSafeInteger(count) || count < 1) throw new Error("Invalid Gaussian PLY vertex count.");
270
+ const rows = format === "ascii" ? decodeText(bytes.subarray(offset)).trim().split(/\r?\n/) : null;
271
+ if (rows ? rows.length !== count : count * stride !== bytes.length - offset)
272
+ throw new Error("Gaussian PLY payload does not match its declared vertex count.");
273
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength),
274
+ splats = [];
275
+ for (let i = 0; i < count; i++) {
276
+ const row = rows && rows[i].trim().split(/\s+/);
277
+ if (row && row.length !== props.size) throw new Error("Invalid ASCII PLY vertex.");
278
+ const read = (key) => {
279
+ const p = props.get(key);
280
+ const v = row ? Number(row[p.index]) : view[p.type[1]](offset + i * stride + p.offset, true);
281
+ if (!Number.isFinite(v)) throw new Error("Non-finite Gaussian PLY attribute.");
282
+ return v;
283
+ };
284
+ const center = ["x", "y", "z"].map(read),
285
+ scales = ["scale_0", "scale_1", "scale_2"].map((p) => Math.exp(read(p)));
286
+ const quaternion = ["rot_0", "rot_1", "rot_2", "rot_3"].map(read),
287
+ norm = Math.hypot(...quaternion);
288
+ if (!norm || !scales.every((s) => Number.isFinite(s) && s > 0))
289
+ throw new Error("Invalid Gaussian scale or rotation.");
290
+ const [w, x, y, z] = quaternion.map((v) => v / norm);
291
+ const rotation = trs([0, 0, 0], [x, y, z, w], [1, 1, 1]);
292
+ const extent = center.map((_, k) => 3 * Math.hypot(...scales.map((s, j) => rotation[j * 4 + k] * s)));
293
+ const color = hasDC ? dc.map((p) => 255 * (0.5 + 0.2820947918 * read(p))) : rgb.map(read);
294
+ splats.push({ center, scales, rotation, extent, color, alpha: 1 / (1 + Math.exp(-read("opacity"))) });
295
+ }
296
+ return { kind: "splat", splats };
297
+ }
@@ -0,0 +1,65 @@
1
+ // Camera orientation is tag 0x0112 in TIFF IFD0 (a single SHORT). An invalid
2
+ // optional metadata block leaves the decoded image in its stored orientation.
3
+ function orientation(tiff) {
4
+ if (tiff.length < 8) return 1;
5
+ const view = new DataView(tiff.buffer, tiff.byteOffset, tiff.byteLength);
6
+ const order = view.getUint16(0);
7
+ if (order !== 0x4949 && order !== 0x4d4d) return 1;
8
+ const little = order === 0x4949;
9
+ if (view.getUint16(2, little) !== 42) return 1;
10
+ const start = view.getUint32(4, little);
11
+ if (start < 8 || start + 2 > tiff.length) return 1;
12
+ const count = view.getUint16(start, little);
13
+ if (start + 2 + count * 12 > tiff.length) return 1;
14
+ for (let i = 0, p = start + 2; i < count; i++, p += 12) {
15
+ if (view.getUint16(p, little) !== 0x0112) continue;
16
+ if (view.getUint16(p + 2, little) !== 3 || view.getUint32(p + 4, little) !== 1) return 1;
17
+ const n = view.getUint16(p + 8, little);
18
+ return n >= 1 && n <= 8 ? n : 1;
19
+ }
20
+ return 1;
21
+ }
22
+
23
+ export function pngOrientation(bytes) {
24
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
25
+ for (let p = 8; p + 12 <= bytes.length; ) {
26
+ const size = view.getUint32(p);
27
+ if (p + size + 12 > bytes.length) break;
28
+ const tag = view.getUint32(p + 4);
29
+ if (tag === 0x65584966) return orientation(bytes.subarray(p + 8, p + 8 + size)); // eXIf
30
+ if (tag === 0x49454e44) break;
31
+ p += size + 12;
32
+ }
33
+ return 1;
34
+ }
35
+
36
+ export function orientImage(image, tag) {
37
+ if (tag === 1) return image;
38
+ const { width: w, height: h, data } = image;
39
+ const transpose = tag >= 5;
40
+ const width = transpose ? h : w,
41
+ height = transpose ? w : h;
42
+ const output = new Uint8ClampedArray(data.length);
43
+ const to = new Uint32Array(output.buffer);
44
+ const from = new Uint32Array(data.buffer, data.byteOffset, data.length / 4);
45
+ // Destination position of source (0,0) and the increments for source x/y.
46
+ // Multiplying the row count by dy places each source row in its destination.
47
+ const steps = [
48
+ null,
49
+ null,
50
+ [w - 1, -1, w],
51
+ [w * h - 1, -1, -w],
52
+ [(h - 1) * w, 1, -w],
53
+ [0, h, 1],
54
+ [h - 1, h, -1],
55
+ [w * h - 1, -h, -1],
56
+ [(w - 1) * h, -h, 1],
57
+ ];
58
+ const [origin, dx, dy] = steps[tag];
59
+ let pos = 0;
60
+ for (let y = 0; y < h; y++) {
61
+ let dst = origin + y * dy;
62
+ for (let x = 0; x < w; x++, dst += dx) to[dst] = from[pos++];
63
+ }
64
+ return { width, height, data: output };
65
+ }