@rulecad/model-link 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +36 -2
- package/model-link.d.mts +107 -0
- package/model-link.mjs +364 -0
- package/package.json +36 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 JoniBach and contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,37 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @rulecad/model-link
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Share a printable model as a link. The model is compressed into the URL's `#fragment`, which browsers never send to
|
|
4
|
+
the server, so a public web page can open a private design and nothing is uploaded. It also writes STL files, and 3MF
|
|
5
|
+
files in Bambu Studio's project layout with each part on its own filament (AMS) slot. No dependencies: it uses the
|
|
6
|
+
browser's own `CompressionStream`, which Node 18+ has too.
|
|
7
|
+
|
|
8
|
+
```js
|
|
9
|
+
import { fromParts, encode, decode, stl, threemf } from '@rulecad/model-link';
|
|
10
|
+
|
|
11
|
+
const model = {
|
|
12
|
+
title: 'Soap tray', version: '1.0.0',
|
|
13
|
+
...fromParts([
|
|
14
|
+
{ name: 'tray', triangles }, // [[[x, y, z] ×3], …], mm, Z up
|
|
15
|
+
{ name: 'logo', triangles: logoTriangles, slot: 2 }, // printed in the AMS's second filament
|
|
16
|
+
]),
|
|
17
|
+
};
|
|
18
|
+
const link = `https://your-viewer.example/#m=${await encode(model)}`;
|
|
19
|
+
|
|
20
|
+
const back = await decode(link.split('#m=')[1]);
|
|
21
|
+
const stlBytes = stl(back); // Uint8Array, binary STL
|
|
22
|
+
const zip = await threemf(back); // Uint8Array, a .3mf (one object, two parts on slots 1 and 2)
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
- **Precision:** corners are snapped to a grid about 1/5000 of the model's size, and shared corners are stored once.
|
|
26
|
+
- **Many copies of one shape** (nine keycaps): `fromShapes()` stores each shape once and a transform per copy, and
|
|
27
|
+
`decode()` expands them.
|
|
28
|
+
- **Safety:** links are data, never code. `decode()` checks the format and sizes (`LIMITS`), refuses damaged links,
|
|
29
|
+
and refuses links from a newer format version.
|
|
30
|
+
- **Short links:** `parseHash(location.hash)` also reads `#s=<id>`, a GitHub Gist holding the data, and
|
|
31
|
+
`fromGist(id)` fetches it without signing in.
|
|
32
|
+
- **The file says who made it:** `stl(m, keep, { generator })` and `threemf(m, keep, { generator })`; the default is
|
|
33
|
+
`rulecad`.
|
|
34
|
+
- **Reproducible files:** a 3MF records the day it was made; `bambu3mf(objects, { date: '2026-10-14' })` fixes it, so
|
|
35
|
+
the same model gives the same bytes.
|
|
36
|
+
- `bambu3mf([{ name, parts: [{ name, triangles, slot }] }])` writes a 3MF from triangles directly. It has been
|
|
37
|
+
checked by loading the files back into Bambu Studio; other slicers read the same file as plain objects.
|
package/model-link.d.mts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/** @param {Triangle[]} tris @returns {{ q: number, p: number[], t: number[] }} */
|
|
2
|
+
export function fromTriangles(tris: Triangle[]): {
|
|
3
|
+
q: number;
|
|
4
|
+
p: number[];
|
|
5
|
+
t: number[];
|
|
6
|
+
};
|
|
7
|
+
/** @param {{ name: string, role?: 'part' | 'support' | 'reference', label?: string, slot?: number, triangles: Triangle[] }[]} list @returns {{ q: number, p: number[], t: number[], parts: any[] }} */
|
|
8
|
+
export function fromParts(list: {
|
|
9
|
+
name: string;
|
|
10
|
+
role?: "part" | "support" | "reference";
|
|
11
|
+
label?: string;
|
|
12
|
+
slot?: number;
|
|
13
|
+
triangles: Triangle[];
|
|
14
|
+
}[]): {
|
|
15
|
+
q: number;
|
|
16
|
+
p: number[];
|
|
17
|
+
t: number[];
|
|
18
|
+
parts: any[];
|
|
19
|
+
};
|
|
20
|
+
/** A model as a link token ('1.' + compressed data), for #m= in a URL. @param {Model} model @returns {Promise<string>} */
|
|
21
|
+
export function encode(model: Model): Promise<string>;
|
|
22
|
+
/** @param {string} hash location.hash @returns {{ token: string | null, gist: string | null, get: string | null }} */
|
|
23
|
+
export function parseHash(hash: string): {
|
|
24
|
+
token: string | null;
|
|
25
|
+
gist: string | null;
|
|
26
|
+
get: string | null;
|
|
27
|
+
};
|
|
28
|
+
/** A short link's token, from its GitHub Gist. @param {string} id @returns {Promise<string>} */
|
|
29
|
+
export function fromGist(id: string): Promise<string>;
|
|
30
|
+
/** A link token back to a model, checked: damaged, newer or oversized links are refused. @param {string} token @returns {Promise<Model>} */
|
|
31
|
+
export function decode(token: string): Promise<Model>;
|
|
32
|
+
export function check(m: any): string[];
|
|
33
|
+
export function expand(m: any): any;
|
|
34
|
+
export function fromShapes(list: any): {
|
|
35
|
+
shapes: {
|
|
36
|
+
q: number;
|
|
37
|
+
p: number[];
|
|
38
|
+
t: number[];
|
|
39
|
+
slot?: any;
|
|
40
|
+
role: any;
|
|
41
|
+
label: any;
|
|
42
|
+
}[];
|
|
43
|
+
place: any[][];
|
|
44
|
+
};
|
|
45
|
+
/** The model's triangles, or one part's. @param {Model} m @param {any[]} [part] @returns {Triangle[]} */
|
|
46
|
+
export function triangles(m: Model, part?: any[]): Triangle[];
|
|
47
|
+
/** @param {ArrayBuffer | Uint8Array} bytes binary or text STL @returns {Triangle[]} */
|
|
48
|
+
export function fromSTL(bytes: ArrayBuffer | Uint8Array): Triangle[];
|
|
49
|
+
/** A binary STL of the printed parts (or those kept). @param {Model} m @param {(part: any[]) => boolean} [keep] @param {{ generator?: string }} [options] @returns {Uint8Array} */
|
|
50
|
+
export function stl(m: Model, keep?: (part: any[]) => boolean, { generator }?: {
|
|
51
|
+
generator?: string;
|
|
52
|
+
}): Uint8Array;
|
|
53
|
+
/** A 3MF in Bambu Studio's layout, each part on its filament slot. @param {Model} m @param {(part: any[]) => boolean} [keep] @param {{ generator?: string }} [options] @returns {Promise<Uint8Array>} */
|
|
54
|
+
export function threemf(m: Model, keep?: (part: any[]) => boolean, { generator }?: {
|
|
55
|
+
generator?: string;
|
|
56
|
+
}): Promise<Uint8Array>;
|
|
57
|
+
export function mesh(tris: any): {
|
|
58
|
+
verts: any[];
|
|
59
|
+
tris: any[][];
|
|
60
|
+
};
|
|
61
|
+
/** @param {{ name: string, parts: { name: string, triangles: Triangle[], slot?: number }[] }[]} objects @param {{ centre?: [number, number], generator?: string, date?: string, title?: string }} [options] @returns {Promise<Uint8Array>} a .3mf (a zip) */
|
|
62
|
+
export function bambu3mf(objects: {
|
|
63
|
+
name: string;
|
|
64
|
+
parts: {
|
|
65
|
+
name: string;
|
|
66
|
+
triangles: Triangle[];
|
|
67
|
+
slot?: number;
|
|
68
|
+
}[];
|
|
69
|
+
}[], { centre, generator, date }?: {
|
|
70
|
+
centre?: [number, number];
|
|
71
|
+
generator?: string;
|
|
72
|
+
date?: string;
|
|
73
|
+
title?: string;
|
|
74
|
+
}): Promise<Uint8Array>;
|
|
75
|
+
/** @typedef {[[number, number, number], [number, number, number], [number, number, number]]} Triangle corners in mm, counter-clockwise seen from outside, Z up */
|
|
76
|
+
/** @typedef {{ title?: string, version?: string, src?: string, material?: string, orientation?: string, rules?: [string, any, string][], q?: number, p?: number[], t?: number[], parts?: any[], shapes?: any[], place?: any[], views?: [string, string][] }} Model */
|
|
77
|
+
export const VERSION: 1;
|
|
78
|
+
export namespace LIMITS {
|
|
79
|
+
let vertices: number;
|
|
80
|
+
let triangles: number;
|
|
81
|
+
let shapes: number;
|
|
82
|
+
let places: number;
|
|
83
|
+
let views: number;
|
|
84
|
+
let viewSize: number;
|
|
85
|
+
}
|
|
86
|
+
export function partsOf(m: any): any;
|
|
87
|
+
export function filename(m: any, ext: any, picked?: string): string;
|
|
88
|
+
export function thingOf(name: any): string;
|
|
89
|
+
/**
|
|
90
|
+
* corners in mm, counter-clockwise seen from outside, Z up
|
|
91
|
+
*/
|
|
92
|
+
export type Triangle = [[number, number, number], [number, number, number], [number, number, number]];
|
|
93
|
+
export type Model = {
|
|
94
|
+
title?: string;
|
|
95
|
+
version?: string;
|
|
96
|
+
src?: string;
|
|
97
|
+
material?: string;
|
|
98
|
+
orientation?: string;
|
|
99
|
+
rules?: [string, any, string][];
|
|
100
|
+
q?: number;
|
|
101
|
+
p?: number[];
|
|
102
|
+
t?: number[];
|
|
103
|
+
parts?: any[];
|
|
104
|
+
shapes?: any[];
|
|
105
|
+
place?: any[];
|
|
106
|
+
views?: [string, string][];
|
|
107
|
+
};
|
package/model-link.mjs
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
// Model links: a printable model in a URL fragment. The fragment never reaches the web
|
|
2
|
+
// host, so a public page can open private designs. Data only, never code. Runs in browsers and Node (18+).
|
|
3
|
+
//
|
|
4
|
+
// https://<host>/#m=1.<base64url(deflate-raw(JSON))>[&get=stl|3mf]
|
|
5
|
+
// JSON: { title, version, src, set, material, orientation, rules: [[label, value, unit]], q, p, t, parts }
|
|
6
|
+
// p: [x, y, z, …] whole multiples of q (mm); t: [a, b, c, …] triangles as vertex indices, counter-clockwise
|
|
7
|
+
// seen from outside; Z up, the bed at z = 0.
|
|
8
|
+
// parts (optional): [[name, role, label, first, count, slot?]], runs of triangles in t; role "support" is printed,
|
|
9
|
+
// then removed; slot is the part's AMS slot (1 without one). Without parts, the whole model is one part.
|
|
10
|
+
// views (optional): [[name, svg]], 2D drawings shown beside the 3D model (a board's copper, a schematic); "Group:
|
|
11
|
+
// view" names share a tab. The page shows them as images, so nothing in them runs.
|
|
12
|
+
// Or placed shapes, for things made of repeated parts (nine keys): each shape once, then where each copy goes:
|
|
13
|
+
// { …, shapes: [{ role, label, slot?, q, p, t }], place: [[shape, a, b, c, d, e, f, g, h, i, j, k, l, name?]] }
|
|
14
|
+
// (a 3 × 4 transform by rows, in mm). decode() expands them, so the rest of the page sees one model.
|
|
15
|
+
// "1." is the format version: newer pages must keep reading old links.
|
|
16
|
+
|
|
17
|
+
/** @typedef {[[number, number, number], [number, number, number], [number, number, number]]} Triangle corners in mm, counter-clockwise seen from outside, Z up */
|
|
18
|
+
/** @typedef {{ title?: string, version?: string, src?: string, material?: string, orientation?: string, rules?: [string, any, string][], q?: number, p?: number[], t?: number[], parts?: any[], shapes?: any[], place?: any[], views?: [string, string][] }} Model */
|
|
19
|
+
|
|
20
|
+
export const VERSION = 1;
|
|
21
|
+
export const LIMITS = { vertices: 200000, triangles: 400000, shapes: 512, places: 2048, views: 8, viewSize: 4e6 }; // every keycap with its own legend is its own shape
|
|
22
|
+
|
|
23
|
+
const b64 = (bytes) => { let s = ''; for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); };
|
|
24
|
+
const unb64 = (s) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0));
|
|
25
|
+
async function pipe(bytes, stream) { return new Uint8Array(await new Response(new Blob([bytes]).stream().pipeThrough(stream)).arrayBuffer()); }
|
|
26
|
+
|
|
27
|
+
// fromTriangles([[[x,y,z] ×3], …]) -> { q, p, t }: shared corners merged on a grid ~1/5000 of the model's size.
|
|
28
|
+
/** @param {Triangle[]} tris @returns {{ q: number, p: number[], t: number[] }} */
|
|
29
|
+
export function fromTriangles(tris) {
|
|
30
|
+
const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity]; // a loop: spreading big models overflows the stack
|
|
31
|
+
for (const tri of tris) for (const v of tri) for (let k = 0; k < 3; k++) { if (v[k] < lo[k]) lo[k] = v[k]; if (v[k] > hi[k]) hi[k] = v[k]; }
|
|
32
|
+
const extent = tris.length ? Math.max(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]) : 0;
|
|
33
|
+
const q = Number((10 ** Math.floor(Math.log10(extent / 5000 || 1))).toPrecision(1));
|
|
34
|
+
const p = [], t = [], index = new Map();
|
|
35
|
+
for (const tri of tris) {
|
|
36
|
+
const ids = tri.map((v) => { const g = v.map((c) => Math.round(c / q)), k = g.join(','); if (!index.has(k)) { index.set(k, p.length / 3); p.push(...g); } return index.get(k); });
|
|
37
|
+
if (ids[0] !== ids[1] && ids[1] !== ids[2] && ids[0] !== ids[2]) t.push(...ids); // snapping can collapse slivers
|
|
38
|
+
}
|
|
39
|
+
return { q, p, t };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// fromParts([{ name, role, label, triangles }]) -> { q, p, t, parts }: shared corners merged across parts.
|
|
43
|
+
/** @param {{ name: string, role?: 'part' | 'support' | 'reference', label?: string, slot?: number, triangles: Triangle[] }[]} list @returns {{ q: number, p: number[], t: number[], parts: any[] }} */
|
|
44
|
+
export function fromParts(list) {
|
|
45
|
+
const m = fromTriangles(list.flatMap((x) => x.triangles)), parts = [];
|
|
46
|
+
// fromTriangles drops triangles that snapping collapses, so count each part's survivors in order
|
|
47
|
+
let at = 0, kept = 0;
|
|
48
|
+
const grid = (v) => v.map((c) => Math.round(c / m.q)).join(',');
|
|
49
|
+
for (const x of list) {
|
|
50
|
+
const first = kept;
|
|
51
|
+
for (const tri of x.triangles) { const k = tri.map(grid); if (k[0] !== k[1] && k[1] !== k[2] && k[0] !== k[2]) kept++; at++; }
|
|
52
|
+
parts.push([x.name, x.role || 'part', x.label || x.name, first, kept - first, ...(x.slot > 1 ? [x.slot] : [])]);
|
|
53
|
+
}
|
|
54
|
+
return { ...m, parts };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A model as a link token ('1.' + compressed data), for #m= in a URL. @param {Model} model @returns {Promise<string>} */
|
|
58
|
+
export async function encode(model) {
|
|
59
|
+
const bytes = await pipe(new TextEncoder().encode(JSON.stringify(model)), new CompressionStream('deflate-raw'));
|
|
60
|
+
return `${VERSION}.${b64(bytes)}`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// The model link's parts from a location hash: { token, gist, get }. A short link (#s=<id>) names a GitHub Gist
|
|
64
|
+
// holding the token.
|
|
65
|
+
/** @param {string} hash location.hash @returns {{ token: string | null, gist: string | null, get: string | null }} */
|
|
66
|
+
export function parseHash(hash) {
|
|
67
|
+
const params = new URLSearchParams(String(hash).replace(/^#/, ''));
|
|
68
|
+
return { token: params.get('m'), gist: params.get('s'), get: params.get('get') };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// The token from a short link's Gist (GitHub's API allows this without signing in, about 60 times an hour).
|
|
72
|
+
/** A short link's token, from its GitHub Gist. @param {string} id @returns {Promise<string>} */
|
|
73
|
+
export async function fromGist(id) {
|
|
74
|
+
if (!/^[0-9a-f]{20,40}$/i.test(String(id))) throw new Error("this short link's ID isn't a Gist ID");
|
|
75
|
+
const r = await fetch(`https://api.github.com/gists/${id}`);
|
|
76
|
+
if (r.status === 404) throw new Error('This short link points to a Gist that no longer exists.');
|
|
77
|
+
if (!r.ok) throw new Error(`GitHub didn't send the model (${r.status}). Try again in a minute.`);
|
|
78
|
+
const f = (await r.json()).files?.['model.txt'];
|
|
79
|
+
if (!f) throw new Error('This Gist holds no model.');
|
|
80
|
+
return (f.truncated ? await (await fetch(f.raw_url)).text() : f.content).trim();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** A link token back to a model, checked: damaged, newer or oversized links are refused. @param {string} token @returns {Promise<Model>} */
|
|
84
|
+
export async function decode(token) {
|
|
85
|
+
const m = String(token || '').match(/^(\d+)\.([\w-]+)$/);
|
|
86
|
+
if (!m) throw new Error("this isn't a model link");
|
|
87
|
+
if (Number(m[1]) > VERSION) throw new Error(`this link needs a newer page (format ${m[1]})`);
|
|
88
|
+
let model;
|
|
89
|
+
try { model = JSON.parse(new TextDecoder().decode(await pipe(unb64(m[2]), new DecompressionStream('deflate-raw')))); }
|
|
90
|
+
catch { throw new Error('This link is damaged: it may have been cut short when it was shared. Copy the whole link again.'); }
|
|
91
|
+
if (model && Array.isArray(model.shapes)) model = expand(model);
|
|
92
|
+
const errors = check(model);
|
|
93
|
+
if (errors.length) throw new Error(errors[0]);
|
|
94
|
+
return model;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function check(m) {
|
|
98
|
+
if (!m || typeof m !== 'object' || !Array.isArray(m.p) || !Array.isArray(m.t)) return ['no model in the link'];
|
|
99
|
+
if (!(m.q > 0)) return ['bad grid size'];
|
|
100
|
+
if (m.p.length % 3 || m.t.length % 3) return ['broken model data'];
|
|
101
|
+
if (m.p.length / 3 > LIMITS.vertices || m.t.length / 3 > LIMITS.triangles) return ['model too big for a link'];
|
|
102
|
+
const n = m.p.length / 3;
|
|
103
|
+
if (m.p.some((x) => !Number.isInteger(x)) || m.t.some((i) => !Number.isInteger(i) || i < 0 || i >= n)) return ['broken model data'];
|
|
104
|
+
if (m.views != null && (!Array.isArray(m.views) || m.views.length > LIMITS.views || m.views.some((v) => !Array.isArray(v) || typeof v[0] !== 'string' || typeof v[1] !== 'string' || v[1].length > LIMITS.viewSize))) return ['broken views'];
|
|
105
|
+
if (m.parts != null && (!Array.isArray(m.parts) || m.parts.some((x) => !Array.isArray(x) || !Number.isInteger(x[3]) || !Number.isInteger(x[4]) || x[3] < 0 || x[3] + x[4] > m.t.length / 3))) return ['broken parts list'];
|
|
106
|
+
return [];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Placed shapes -> one model ({ q, p, t, parts }), each copy its own part.
|
|
110
|
+
export function expand(m) {
|
|
111
|
+
const { shapes, place, ...meta } = m;
|
|
112
|
+
if (!Array.isArray(place) || shapes.length > LIMITS.shapes || place.length > LIMITS.places) throw new Error('model too big for a link');
|
|
113
|
+
for (const sh of shapes) { const e = check(sh); if (e.length) throw new Error(e[0]); }
|
|
114
|
+
const list = place.map(([i, ...rest], n) => {
|
|
115
|
+
const sh = shapes[i], t = rest.slice(0, 12);
|
|
116
|
+
if (!sh || t.length !== 12 || t.some((x) => !Number.isFinite(x))) throw new Error('broken placement');
|
|
117
|
+
const at = ([x, y, z]) => [t[0] * x + t[1] * y + t[2] * z + t[3], t[4] * x + t[5] * y + t[6] * z + t[7], t[8] * x + t[9] * y + t[10] * z + t[11]];
|
|
118
|
+
return { name: rest[12] || `${sh.label || 'shape'} ${n + 1}`, role: sh.role || 'part', label: sh.label || 'shape', slot: sh.slot, triangles: triangles(sh).map((tri) => tri.map(at)) };
|
|
119
|
+
});
|
|
120
|
+
return { ...meta, ...fromParts(list) };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// fromShapes(parts) for tools: [{ shape, role, label, triangles (local), matrix: 12 numbers, name }] -> { shapes, place }
|
|
124
|
+
export function fromShapes(list) {
|
|
125
|
+
const index = new Map(), shapes = [], place = [];
|
|
126
|
+
for (const x of list) {
|
|
127
|
+
if (!index.has(x.shape)) { index.set(x.shape, shapes.length); shapes.push({ role: x.role, label: x.label, ...(x.slot > 1 ? { slot: x.slot } : {}), ...fromTriangles(x.triangles) }); }
|
|
128
|
+
place.push([index.get(x.shape), ...x.matrix, x.name]);
|
|
129
|
+
}
|
|
130
|
+
return { shapes, place };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Triangles in mm: [[[x,y,z] ×3], …], all of them or one part's ([name, role, label, first, count]).
|
|
134
|
+
/** The model's triangles, or one part's. @param {Model} m @param {any[]} [part] @returns {Triangle[]} */
|
|
135
|
+
export function triangles(m, part) {
|
|
136
|
+
const v = (i) => [m.p[3 * i] * m.q, m.p[3 * i + 1] * m.q, m.p[3 * i + 2] * m.q], out = [];
|
|
137
|
+
const [from, to] = part ? [part[3] * 3, (part[3] + part[4]) * 3] : [0, m.t.length];
|
|
138
|
+
for (let i = from; i < to; i += 3) out.push([v(m.t[i]), v(m.t[i + 1]), v(m.t[i + 2])]);
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// The model's parts, always at least one: [[name, role, label, first, count]]
|
|
143
|
+
export const partsOf = (m) => (m.parts?.length ? m.parts : [['body', 'part', m.title || 'model', 0, m.t.length / 3]]);
|
|
144
|
+
|
|
145
|
+
// ---------- files ----------
|
|
146
|
+
// cap@0.6.0.stl; with what was picked, if not everything: staggered-cap-2-4.3mf
|
|
147
|
+
export const filename = (m, ext, picked = '') => `${[String(m.src || m.title || 'model').split('/').pop(), m.set && m.set.replace(/,/g, '-'), picked].filter(Boolean).join('-').replace(/[^\w@.=-]+/g, '-')}.${ext}`;
|
|
148
|
+
|
|
149
|
+
// Which parts a file holds: all the printed ones (references are only there to check a fit), or the indices picked
|
|
150
|
+
const chosen = (m, keep) => partsOf(m).filter((x, i) => (keep ? keep.has(i) : x[1] !== 'reference'));
|
|
151
|
+
|
|
152
|
+
// Binary STL (mm): the parts picked, as one mesh, each part mended (mesh) as for 3MF.
|
|
153
|
+
// fromSTL(bytes) -> triangles [[[x, y, z] ×3], …] from an STL file, binary or text (ASCII). Units are as the file has
|
|
154
|
+
// them (millimetres, by convention). Throws on anything that isn't an STL.
|
|
155
|
+
/** @param {ArrayBuffer | Uint8Array} bytes binary or text STL @returns {Triangle[]} */
|
|
156
|
+
export function fromSTL(bytes) {
|
|
157
|
+
const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
158
|
+
const view = new DataView(u8.buffer, u8.byteOffset, u8.byteLength);
|
|
159
|
+
const count = u8.byteLength >= 84 ? view.getUint32(80, true) : -1;
|
|
160
|
+
if (count >= 0 && 84 + count * 50 === u8.byteLength) { // binary: a header, a count, then 50 bytes a triangle
|
|
161
|
+
if (count > LIMITS.triangles) throw new Error(`${count} triangles: more than a link can hold (${LIMITS.triangles})`);
|
|
162
|
+
const tris = [];
|
|
163
|
+
for (let i = 0, o = 84; i < count; i++, o += 50) tris.push([0, 1, 2].map((v) => [0, 1, 2].map((k) => view.getFloat32(o + 12 + v * 12 + k * 4, true))));
|
|
164
|
+
return tris;
|
|
165
|
+
}
|
|
166
|
+
const text = new TextDecoder().decode(u8);
|
|
167
|
+
if (!/^\s*solid\b/.test(text) || !/\bvertex\b/.test(text)) throw new Error("this isn't an STL file");
|
|
168
|
+
const v = [...text.matchAll(/vertex\s+(\S+)\s+(\S+)\s+(\S+)/g)].map((m) => [Number(m[1]), Number(m[2]), Number(m[3])]);
|
|
169
|
+
if (v.length % 3 || v.some((p) => p.some((c) => !Number.isFinite(c)))) throw new Error('this STL file is damaged');
|
|
170
|
+
if (v.length / 3 > LIMITS.triangles) throw new Error(`${v.length / 3} triangles: more than a link can hold (${LIMITS.triangles})`);
|
|
171
|
+
return Array.from({ length: v.length / 3 }, (_, i) => v.slice(i * 3, i * 3 + 3));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// generator: the name the file says made it (rulecad by default)
|
|
175
|
+
/** A binary STL of the printed parts (or those kept). @param {Model} m @param {(part: any[]) => boolean} [keep] @param {{ generator?: string }} [options] @returns {Uint8Array} */
|
|
176
|
+
export function stl(m, keep, { generator = 'rulecad' } = {}) {
|
|
177
|
+
const tris = chosen(m, keep).flatMap((x) => { const { verts, tris: t } = mesh(triangles(m, x)); return t.map((ids) => ids.map((i) => verts[i])); }), buf = new ArrayBuffer(84 + 50 * tris.length), dv = new DataView(buf);
|
|
178
|
+
const head = `${generator} ${m.src || m.title || ''}`.slice(0, 80);
|
|
179
|
+
for (let i = 0; i < head.length; i++) dv.setUint8(i, head.charCodeAt(i) & 0x7f);
|
|
180
|
+
dv.setUint32(80, tris.length, true);
|
|
181
|
+
tris.forEach(([a, b, c], i) => {
|
|
182
|
+
const u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]], w = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
|
|
183
|
+
let n = [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]];
|
|
184
|
+
const l = Math.hypot(...n) || 1; n = n.map((x) => x / l);
|
|
185
|
+
[...n, ...a, ...b, ...c].forEach((x, k) => dv.setFloat32(84 + 50 * i + 4 * k, x, true));
|
|
186
|
+
});
|
|
187
|
+
return new Uint8Array(buf);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// The printed thing a part belongs to: key-1-1.cap.legend -> key-1-1.cap, case.body -> case; a single object's parts
|
|
191
|
+
// (cap, legend, pillar) are all one thing
|
|
192
|
+
export const thingOf = (name) => { const bits = String(name).split('.'); return bits.length > 2 ? bits.slice(0, -1).join('.') : bits.length > 1 ? bits[0] : ''; };
|
|
193
|
+
|
|
194
|
+
// 3MF of the parts picked, in Bambu Studio's layout (bambu3mf): one object per printed thing, its parts on their AMS
|
|
195
|
+
// slots (parts' sixth field; slot 1 without one).
|
|
196
|
+
/** A 3MF in Bambu Studio's layout, each part on its filament slot. @param {Model} m @param {(part: any[]) => boolean} [keep] @param {{ generator?: string }} [options] @returns {Promise<Uint8Array>} */
|
|
197
|
+
export async function threemf(m, keep, { generator = 'rulecad' } = {}) {
|
|
198
|
+
const things = new Map();
|
|
199
|
+
for (const x of chosen(m, keep)) {
|
|
200
|
+
const id = thingOf(x[0]);
|
|
201
|
+
if (!things.has(id)) things.set(id, []);
|
|
202
|
+
things.get(id).push({ name: id ? x[0].split('.').pop() : x[2] || x[0], triangles: triangles(m, x), slot: x[5] || 1 });
|
|
203
|
+
}
|
|
204
|
+
return bambu3mf([...things].map(([id, parts]) => ({ name: id || m.title || 'model', parts })), { title: m.title, generator });
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// ---------- Bambu Studio's 3MF ----------
|
|
208
|
+
// A 3MF in Bambu Studio's own project layout, so it opens as objects made of parts, each part already on its filament
|
|
209
|
+
// (AMS slot):
|
|
210
|
+
// 3D/3dmodel.model one object per printed thing (a keycap), its components the parts' meshes
|
|
211
|
+
// 3D/Objects/object_N.model that object's meshes, one per part (cap, legend, breakaway supports)
|
|
212
|
+
// Metadata/model_settings.config each object's parts with their names and extruder; the objects on plate 1
|
|
213
|
+
// Other slicers read the same file as plain objects with components. The layout was copied from a project Bambu Studio
|
|
214
|
+
// 01.09 saved itself (BambuStudio --assemble … --export-3mf), and checked by loading ours back the same way: one object
|
|
215
|
+
// per keycap, its parts and their filaments come through. The file names its generator (rulecad by default), not Bambu Studio: a file
|
|
216
|
+
// that claims to be a Bambu project but has no printer settings makes Bambu Studio 01.09 crash. There are no project
|
|
217
|
+
// settings in it at all, so opening it never touches your printer, process or filament settings; the parts' AMS slots
|
|
218
|
+
// map onto the filaments you have loaded. Works the same in a browser and in Node.
|
|
219
|
+
// await bambu3mf([{ name, parts: [{ name, triangles, slot }] }], { centre }) -> Uint8Array (a zip)
|
|
220
|
+
const esc = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
221
|
+
const num = (x) => String(Number(x.toFixed(5)));
|
|
222
|
+
|
|
223
|
+
// triangles -> { verts, tris }: corners within a micron merged, zero-area triangles (three corners in a line) dropped,
|
|
224
|
+
// and the part closed. JSCAD's booleans leave T-junctions (a corner of one face in the middle of a neighbour's edge) and
|
|
225
|
+
// lose the odd sliver face, so a part's faces don't join up: Bambu Studio says "manifold = no", splits it into fragments
|
|
226
|
+
// and its repair can fill a legend's letters with sheets. So a triangle with a loose corner lying along its open edge is
|
|
227
|
+
// split there, one corner at a time until none is left, and any pinhole still open (a loop of open edges less than a
|
|
228
|
+
// millimetre round) is closed with a fan. Each part comes out as one closed body per piece (a keycap; each letter).
|
|
229
|
+
export function mesh(tris) {
|
|
230
|
+
const MERGE = 1e-3, verts = [], index = new Map(), out = [];
|
|
231
|
+
const key = (v) => v.map((c) => Math.round(c / MERGE)).join(',');
|
|
232
|
+
const at = (v) => { // the same corner as one already seen within MERGE (it may sit across a rounding boundary)
|
|
233
|
+
const g = v.map((c) => Math.round(c / MERGE));
|
|
234
|
+
for (let dx = -1; dx <= 1; dx++) for (let dy = -1; dy <= 1; dy++) for (let dz = -1; dz <= 1; dz++) {
|
|
235
|
+
for (const i of index.get(`${g[0] + dx},${g[1] + dy},${g[2] + dz}`) || []) if (Math.hypot(verts[i][0] - v[0], verts[i][1] - v[1], verts[i][2] - v[2]) < MERGE) return i;
|
|
236
|
+
}
|
|
237
|
+
const k = key(v); if (!index.has(k)) index.set(k, []); index.get(k).push(verts.length); verts.push(v); return verts.length - 1;
|
|
238
|
+
};
|
|
239
|
+
const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]], dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
|
240
|
+
const cross = (u, w) => [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]];
|
|
241
|
+
const area2 = (ids) => { const [a, b, c] = ids.map((i) => verts[i]); return Math.hypot(...cross(sub(b, a), sub(c, a))); };
|
|
242
|
+
for (const t of tris) for (let i = 1; i < t.length - 1; i++) { const ids = [at(t[0]), at(t[i]), at(t[i + 1])]; if (new Set(ids).size === 3 && area2(ids) > 1e-9) out.push(ids); }
|
|
243
|
+
|
|
244
|
+
// Mend: split a triangle at a loose corner lying along its open edge, one corner at a time, until none is left
|
|
245
|
+
const TOL = 2e-3, CELL = 1, cell = (x) => Math.floor(x / CELL);
|
|
246
|
+
for (let pass = 0; pass < 50; pass++) {
|
|
247
|
+
const edges = new Set(); for (const [a, b, c] of out) edges.add(`${a},${b}`).add(`${b},${c}`).add(`${c},${a}`);
|
|
248
|
+
const isOpen = (a, b) => !edges.has(`${b},${a}`), loose = new Set();
|
|
249
|
+
for (const [a, b, c] of out) for (const [x, y] of [[a, b], [b, c], [c, a]]) if (isOpen(x, y)) loose.add(x).add(y);
|
|
250
|
+
if (!loose.size) break;
|
|
251
|
+
const grid = new Map();
|
|
252
|
+
for (const i of loose) { const k = verts[i].map(cell).join(','); if (!grid.has(k)) grid.set(k, []); grid.get(k).push(i); }
|
|
253
|
+
// The loose corner along a -> b nearest the line, if any
|
|
254
|
+
const along = (a, b) => {
|
|
255
|
+
const p = verts[a], d = sub(verts[b], p), len = Math.sqrt(dot(d, d));
|
|
256
|
+
const lo = [0, 1, 2].map((k) => cell(Math.min(p[k], verts[b][k]) - TOL)), hi = [0, 1, 2].map((k) => cell(Math.max(p[k], verts[b][k]) + TOL));
|
|
257
|
+
let best = null;
|
|
258
|
+
for (let x = lo[0]; x <= hi[0]; x++) for (let y = lo[1]; y <= hi[1]; y++) for (let z = lo[2]; z <= hi[2]; z++) {
|
|
259
|
+
for (const i of grid.get(`${x},${y},${z}`) || []) {
|
|
260
|
+
if (i === a || i === b) continue;
|
|
261
|
+
const w = sub(verts[i], p), t = dot(w, d) / (len * len);
|
|
262
|
+
if (t * len < TOL || (1 - t) * len < TOL) continue;
|
|
263
|
+
const off = Math.hypot(...cross(w, d)) / len;
|
|
264
|
+
if (off < TOL && (!best || off < best[1])) best = [i, off];
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return best;
|
|
268
|
+
};
|
|
269
|
+
let split = 0;
|
|
270
|
+
const n = out.length;
|
|
271
|
+
for (let k = 0; k < n; k++) {
|
|
272
|
+
const t = out[k];
|
|
273
|
+
let pick = null;
|
|
274
|
+
for (let e = 0; e < 3; e++) {
|
|
275
|
+
const a = t[e], b = t[(e + 1) % 3];
|
|
276
|
+
if (!isOpen(a, b)) continue;
|
|
277
|
+
const f = along(a, b);
|
|
278
|
+
if (f && (!pick || f[1] < pick[1])) pick = [f[0], f[1], e];
|
|
279
|
+
}
|
|
280
|
+
if (!pick) continue;
|
|
281
|
+
const [v, , e] = pick, a = t[e], b = t[(e + 1) % 3], c = t[(e + 2) % 3];
|
|
282
|
+
out[k] = [a, v, c]; out.push([v, b, c]); split++;
|
|
283
|
+
}
|
|
284
|
+
if (!split) break;
|
|
285
|
+
}
|
|
286
|
+
// What's left are pinholes: a sliver face the booleans lost, a loop of open edges a fraction of a millimetre round.
|
|
287
|
+
// Close each with a fan.
|
|
288
|
+
const kept = out.filter((ids) => area2(ids) > 1e-9), edges = new Set();
|
|
289
|
+
for (const [a, b, c] of kept) edges.add(`${a},${b}`).add(`${b},${c}`).add(`${c},${a}`);
|
|
290
|
+
const next = new Map();
|
|
291
|
+
for (const k of edges) { const [a, b] = k.split(',').map(Number); if (!edges.has(`${b},${a}`)) next.set(a, b); }
|
|
292
|
+
const PINHOLE = 1;
|
|
293
|
+
for (const start of [...next.keys()]) {
|
|
294
|
+
if (!next.has(start)) continue;
|
|
295
|
+
const loop = [start];
|
|
296
|
+
for (let v = next.get(start); v !== start && v != null && loop.length < 64; v = next.get(v)) loop.push(v);
|
|
297
|
+
if (next.get(loop[loop.length - 1]) !== start) continue;
|
|
298
|
+
const round = loop.reduce((sum, v, i) => sum + Math.hypot(...sub(verts[loop[(i + 1) % loop.length]], verts[v])), 0);
|
|
299
|
+
if (round > PINHOLE) continue;
|
|
300
|
+
for (let i = 1; i < loop.length - 1; i++) kept.push([loop[0], loop[i + 1], loop[i]]);
|
|
301
|
+
for (const v of loop) next.delete(v);
|
|
302
|
+
}
|
|
303
|
+
return { verts, tris: kept };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const meshXml = ({ verts, tris }) => `<mesh><vertices>${verts.map((v) => `<vertex x="${num(v[0])}" y="${num(v[1])}" z="${num(v[2])}"/>`).join('')}</vertices>`
|
|
307
|
+
+ `<triangles>${tris.map(([a, b, c]) => `<triangle v1="${a}" v2="${b}" v3="${c}"/>`).join('')}</triangles></mesh>`;
|
|
308
|
+
|
|
309
|
+
const uuid = (n, kind) => `${kind.toString(16).padStart(4, '0')}${(n & 0xffff).toString(16).padStart(4, '0')}-81cb-4c03-9d28-80fed5dfa1dc`;
|
|
310
|
+
const IDENTITY = '1 0 0 0 1 0 0 0 1 0 0 0', IDENTITY4 = '1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1';
|
|
311
|
+
const NS = 'xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02" xmlns:BambuStudio="http://schemas.bambulab.com/package/2021" xmlns:p="http://schemas.microsoft.com/3dmanufacturing/production/2015/06" requiredextensions="p"';
|
|
312
|
+
|
|
313
|
+
/** @param {{ name: string, parts: { name: string, triangles: Triangle[], slot?: number }[] }[]} objects @param {{ centre?: [number, number], generator?: string, date?: string, title?: string }} [options] @returns {Promise<Uint8Array>} a .3mf (a zip) */
|
|
314
|
+
export async function bambu3mf(objects, { centre = [128, 128], generator = 'rulecad', date } = {}) {
|
|
315
|
+
const files = {}, rels = [], resources = [], build = [], settings = [], instances = [];
|
|
316
|
+
let id = 0;
|
|
317
|
+
objects.forEach((o, n) => {
|
|
318
|
+
const path = `/3D/Objects/object_${n + 1}.model`, parts = o.parts.map((p) => ({ ...p, id: ++id }));
|
|
319
|
+
files[path.slice(1)] = `<?xml version="1.0" encoding="UTF-8"?>\n<model unit="millimeter" xml:lang="en-US" ${NS}>\n <metadata name="BambuStudio:3mfVersion">1</metadata>\n <resources>\n`
|
|
320
|
+
+ parts.map((p) => ` <object id="${p.id}" p:UUID="${uuid(p.id, 1)}" type="model">${meshXml(mesh(p.triangles))}</object>\n`).join('') + ' </resources>\n <build/>\n</model>\n';
|
|
321
|
+
rels.push(`<Relationship Target="${path}" Id="rel-${n + 1}" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/>`);
|
|
322
|
+
const parent = 100000 + n + 1;
|
|
323
|
+
resources.push(` <object id="${parent}" p:UUID="${uuid(n + 1, 0)}" type="model">\n <components>\n`
|
|
324
|
+
+ parts.map((p) => ` <component p:path="${path}" objectid="${p.id}" p:UUID="${uuid(p.id, 2)}" transform="${IDENTITY}"/>\n`).join('') + ' </components>\n </object>\n');
|
|
325
|
+
build.push(` <item objectid="${parent}" p:UUID="${uuid(n + 1, 3)}" transform="1 0 0 0 1 0 0 0 1 ${centre[0]} ${centre[1]} 0" printable="1"/>\n`);
|
|
326
|
+
settings.push(` <object id="${parent}">\n <metadata key="name" value="${esc(o.name)}"/>\n <metadata key="extruder" value="${parts[0]?.slot || 1}"/>\n`
|
|
327
|
+
+ parts.map((p) => ` <part id="${p.id}" subtype="normal_part">\n <metadata key="name" value="${esc(p.name)}"/>\n <metadata key="matrix" value="${IDENTITY4}"/>\n <metadata key="extruder" value="${p.slot || 1}"/>\n </part>\n`).join('') + ' </object>\n');
|
|
328
|
+
instances.push(` <model_instance>\n <metadata key="object_id" value="${parent}"/>\n <metadata key="instance_id" value="0"/>\n <metadata key="identify_id" value="${n + 1}"/>\n </model_instance>\n`);
|
|
329
|
+
});
|
|
330
|
+
const xml = '<?xml version="1.0" encoding="UTF-8"?>\n', today = date || new Date().toISOString().slice(0, 10); // date: '2026-10-14' for a reproducible file
|
|
331
|
+
return zip([
|
|
332
|
+
['[Content_Types].xml', `${xml}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\n <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>\n <Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/>\n</Types>\n`],
|
|
333
|
+
['_rels/.rels', `${xml}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n <Relationship Target="/3D/3dmodel.model" Id="rel-1" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/>\n</Relationships>\n`],
|
|
334
|
+
['3D/_rels/3dmodel.model.rels', `${xml}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n ${rels.join('\n ')}\n</Relationships>\n`],
|
|
335
|
+
['3D/3dmodel.model', `${xml}<model unit="millimeter" xml:lang="en-US" ${NS}>\n <metadata name="Application">${generator}</metadata>\n <metadata name="BambuStudio:3mfVersion">1</metadata>\n <metadata name="Title">mirror-cad</metadata>\n <metadata name="CreationDate">${today}</metadata>\n <resources>\n${resources.join('')} </resources>\n <build p:UUID="${uuid(0, 4)}">\n${build.join('')} </build>\n</model>\n`],
|
|
336
|
+
['Metadata/model_settings.config', `${xml}<config>\n${settings.join('')} <plate>\n <metadata key="plater_id" value="1"/>\n <metadata key="plater_name" value=""/>\n <metadata key="locked" value="false"/>\n${instances.join('')} </plate>\n</config>\n`],
|
|
337
|
+
...Object.entries(files),
|
|
338
|
+
]);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const CRC = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
|
|
342
|
+
const crc32 = (b) => { let c = 0xffffffff; for (const x of b) c = CRC[(c ^ x) & 255] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
|
|
343
|
+
|
|
344
|
+
// A ZIP, each file deflated with the browser's (or Node's) own CompressionStream: no library needed.
|
|
345
|
+
async function zip(entries) {
|
|
346
|
+
const enc = new TextEncoder(), parts = [], dir = [];
|
|
347
|
+
let offset = 0;
|
|
348
|
+
for (const [name, text] of entries) {
|
|
349
|
+
const n = enc.encode(name), raw = enc.encode(text), crc = crc32(raw), d = await pipe(raw, new CompressionStream('deflate-raw'));
|
|
350
|
+
const local = new DataView(new ArrayBuffer(30));
|
|
351
|
+
[[0, 0x04034b50, 4], [4, 20, 2], [8, 8, 2], [14, crc, 4], [18, d.length, 4], [22, raw.length, 4], [26, n.length, 2]].forEach(([o, v, s]) => (s === 4 ? local.setUint32(o, v, true) : local.setUint16(o, v, true)));
|
|
352
|
+
const central = new DataView(new ArrayBuffer(46));
|
|
353
|
+
[[0, 0x02014b50, 4], [4, 20, 2], [6, 20, 2], [10, 8, 2], [16, crc, 4], [20, d.length, 4], [24, raw.length, 4], [28, n.length, 2], [42, offset, 4]].forEach(([o, v, s]) => (s === 4 ? central.setUint32(o, v, true) : central.setUint16(o, v, true)));
|
|
354
|
+
parts.push(new Uint8Array(local.buffer), n, d);
|
|
355
|
+
dir.push(new Uint8Array(central.buffer), n);
|
|
356
|
+
offset += 30 + n.length + d.length;
|
|
357
|
+
}
|
|
358
|
+
const size = dir.reduce((s, b) => s + b.length, 0), end = new DataView(new ArrayBuffer(22));
|
|
359
|
+
[[0, 0x06054b50, 4], [8, entries.length, 2], [10, entries.length, 2], [12, size, 4], [16, offset, 4]].forEach(([o, v, s]) => (s === 4 ? end.setUint32(o, v, true) : end.setUint16(o, v, true)));
|
|
360
|
+
const all = [...parts, ...dir, new Uint8Array(end.buffer)], out = new Uint8Array(all.reduce((s, b) => s + b.length, 0));
|
|
361
|
+
let at = 0;
|
|
362
|
+
for (const b of all) { out.set(b, at); at += b.length; }
|
|
363
|
+
return out;
|
|
364
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/model-link",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Share a printable model as a link (the model lives in the URL), and write STL or multi-colour Bambu Studio 3MF files, in the browser or Node.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
"types": "./model-link.d.mts",
|
|
8
|
+
"default": "./model-link.mjs"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"model-link.mjs",
|
|
12
|
+
"model-link.d.mts",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"keywords": [
|
|
18
|
+
"3mf",
|
|
19
|
+
"stl",
|
|
20
|
+
"bambu",
|
|
21
|
+
"3d-printing",
|
|
22
|
+
"share",
|
|
23
|
+
"url"
|
|
24
|
+
],
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=18"
|
|
27
|
+
},
|
|
28
|
+
"sideEffects": false,
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/JoniBach/rulecad.git",
|
|
32
|
+
"directory": "packages/model-link"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"test": "node --test"
|
|
36
|
+
},
|
|
37
|
+
"types": "./model-link.d.mts"
|
|
38
|
+
}
|