@rulecad/model-link 0.2.0 → 0.2.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/model-link.d.mts +12 -5
- package/model-link.mjs +49 -16
- package/package.json +1 -1
package/model-link.d.mts
CHANGED
|
@@ -69,12 +69,12 @@ export function placeItems(motion: {
|
|
|
69
69
|
}, values: Record<string, number[]>): number[][];
|
|
70
70
|
/** @param {ArrayBuffer | Uint8Array} bytes binary or text STL @returns {Triangle[]} */
|
|
71
71
|
export function fromSTL(bytes: ArrayBuffer | Uint8Array): Triangle[];
|
|
72
|
-
/** A binary STL of the printed parts (or those kept). @param {Model} m @param {(part: any[]) => boolean} [keep] @param {{ generator?: string }} [options] @returns {Uint8Array} */
|
|
73
|
-
export function stl(m: Model, keep?: (part: any[]) => boolean, { generator }?: {
|
|
72
|
+
/** A binary STL of the printed parts (or those kept). @param {Model} m @param {Set<number> | ((part: any[], index: number) => boolean)} [keep] the parts to write: their places in partsOf(m), or a test of each @param {{ generator?: string }} [options] @returns {Uint8Array} */
|
|
73
|
+
export function stl(m: Model, keep?: Set<number> | ((part: any[], index: number) => boolean), { generator }?: {
|
|
74
74
|
generator?: string;
|
|
75
75
|
}): Uint8Array;
|
|
76
|
-
/** 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>} */
|
|
77
|
-
export function threemf(m: Model, keep?: (part: any[]) => boolean, { generator }?: {
|
|
76
|
+
/** A 3MF in Bambu Studio's layout, each part on its filament slot. @param {Model} m @param {Set<number> | ((part: any[], index: number) => boolean)} [keep] the parts to write: their places in partsOf(m), or a test of each @param {{ generator?: string }} [options] @returns {Promise<Uint8Array>} */
|
|
77
|
+
export function threemf(m: Model, keep?: Set<number> | ((part: any[], index: number) => boolean), { generator }?: {
|
|
78
78
|
generator?: string;
|
|
79
79
|
}): Promise<Uint8Array>;
|
|
80
80
|
export function mesh(tris: any): {
|
|
@@ -89,7 +89,7 @@ export function bambu3mf(objects: {
|
|
|
89
89
|
triangles: Triangle[];
|
|
90
90
|
slot?: number;
|
|
91
91
|
}[];
|
|
92
|
-
}[], { centre, generator, date }?: {
|
|
92
|
+
}[], { centre, generator, date, title }?: {
|
|
93
93
|
centre?: [number, number];
|
|
94
94
|
generator?: string;
|
|
95
95
|
date?: string;
|
|
@@ -112,8 +112,15 @@ export namespace LIMITS {
|
|
|
112
112
|
let views: number;
|
|
113
113
|
let viewSize: number;
|
|
114
114
|
let sheet: number;
|
|
115
|
+
let size: number;
|
|
116
|
+
let text: number;
|
|
117
|
+
let bytes: number;
|
|
115
118
|
}
|
|
116
119
|
export function partsOf(m: any): any;
|
|
120
|
+
export function posesOf(m: Model): {
|
|
121
|
+
k: number;
|
|
122
|
+
part: any[];
|
|
123
|
+
}[];
|
|
117
124
|
export namespace DOFS {
|
|
118
125
|
let fixed: any[];
|
|
119
126
|
let revolute: string[];
|
package/model-link.mjs
CHANGED
|
@@ -6,7 +6,9 @@
|
|
|
6
6
|
// p: [x, y, z, …] whole multiples of q (mm); t: [a, b, c, …] triangles as vertex indices, counter-clockwise
|
|
7
7
|
// seen from outside; Z up, the bed at z = 0.
|
|
8
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.
|
|
9
|
+
// then removed; slot is the part's AMS slot (1 without one). Without parts, the whole model is one part. Role
|
|
10
|
+
// "pose": another shape of a part, shown only in a pose (a flexure bent; see motion.swap), never printed or checked;
|
|
11
|
+
// these come after the parts they stand in for.
|
|
10
12
|
// views (optional): [[name, svg]], 2D drawings shown beside the 3D model (a board's copper, a schematic); "Group:
|
|
11
13
|
// view" names share a tab. The page shows them as images, so nothing in them runs.
|
|
12
14
|
// Or placed shapes, for things made of repeated parts (nine keys): each shape once, then where each copy goes:
|
|
@@ -19,11 +21,29 @@
|
|
|
19
21
|
/** @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][], motion?: any }} Model */
|
|
20
22
|
|
|
21
23
|
export const VERSION = 1;
|
|
22
|
-
export const LIMITS = { vertices: 200000, triangles: 400000, shapes: 512, places: 2048, views: 32, viewSize: 4e6, sheet: 5000
|
|
24
|
+
export const LIMITS = { vertices: 200000, triangles: 400000, shapes: 512, places: 2048, views: 32, viewSize: 4e6, sheet: 5000, // every keycap with its own legend is its own shape
|
|
25
|
+
size: 1e5, // mm: no corner further than this from the origin (a link is a part or an assembly, not a map)
|
|
26
|
+
text: 2000, // characters in a title, a name or a label
|
|
27
|
+
bytes: 160e6 }; // of a link once unpacked: its views at their largest, and the biggest model, with room to spare
|
|
23
28
|
|
|
24
29
|
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(/=+$/, ''); };
|
|
25
30
|
const unb64 = (s) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0));
|
|
26
|
-
|
|
31
|
+
// most: stop reading once this many bytes have come out (a small link can unpack to a great deal)
|
|
32
|
+
async function pipe(bytes, stream, most = Infinity) {
|
|
33
|
+
const reader = new Blob([bytes]).stream().pipeThrough(stream).getReader(), chunks = [];
|
|
34
|
+
let size = 0;
|
|
35
|
+
for (;;) {
|
|
36
|
+
const { done, value } = await reader.read();
|
|
37
|
+
if (done) break;
|
|
38
|
+
size += value.length;
|
|
39
|
+
if (size > most) { await reader.cancel(); throw Object.assign(new Error('model too big for a link'), { tooBig: true }); }
|
|
40
|
+
chunks.push(value);
|
|
41
|
+
}
|
|
42
|
+
const out = new Uint8Array(size);
|
|
43
|
+
let at = 0;
|
|
44
|
+
for (const c of chunks) { out.set(c, at); at += c.length; }
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
27
47
|
|
|
28
48
|
// fromTriangles([[[x,y,z] ×3], …]) -> { q, p, t }: shared corners merged on a grid ~1/5000 of the model's size.
|
|
29
49
|
/** @param {Triangle[]} tris @returns {{ q: number, p: number[], t: number[] }} */
|
|
@@ -87,8 +107,8 @@ export async function decode(token) {
|
|
|
87
107
|
if (!m) throw new Error("this isn't a model link");
|
|
88
108
|
if (Number(m[1]) > VERSION) throw new Error(`this link needs a newer page (format ${m[1]})`);
|
|
89
109
|
let model;
|
|
90
|
-
try { model = JSON.parse(new TextDecoder().decode(await pipe(unb64(m[2]), new DecompressionStream('deflate-raw')))); }
|
|
91
|
-
catch { throw new Error('This link is damaged: it may have been cut short when it was shared. Copy the whole link again.'); }
|
|
110
|
+
try { model = JSON.parse(new TextDecoder().decode(await pipe(unb64(m[2]), new DecompressionStream('deflate-raw'), LIMITS.bytes))); }
|
|
111
|
+
catch (e) { if (e?.tooBig) throw e; throw new Error('This link is damaged: it may have been cut short when it was shared. Copy the whole link again.'); }
|
|
92
112
|
if (model && Array.isArray(model.shapes)) model = expand(model);
|
|
93
113
|
const errors = check(model);
|
|
94
114
|
if (errors.length) throw new Error(errors[0]);
|
|
@@ -97,16 +117,19 @@ export async function decode(token) {
|
|
|
97
117
|
|
|
98
118
|
export function check(m) {
|
|
99
119
|
if (!m || typeof m !== 'object' || !Array.isArray(m.p) || !Array.isArray(m.t)) return ['no model in the link'];
|
|
100
|
-
if (!(m.q > 0)) return ['bad grid size'];
|
|
120
|
+
if (typeof m.q !== 'number' || !Number.isFinite(m.q) || !(m.q > 0)) return ['bad grid size'];
|
|
101
121
|
if (m.p.length % 3 || m.t.length % 3) return ['broken model data'];
|
|
102
122
|
if (m.p.length / 3 > LIMITS.vertices || m.t.length / 3 > LIMITS.triangles) return ['model too big for a link'];
|
|
103
|
-
const n = m.p.length / 3;
|
|
123
|
+
const n = m.p.length / 3, far = LIMITS.size / m.q;
|
|
104
124
|
if (m.p.some((x) => !Number.isInteger(x)) || m.t.some((i) => !Number.isInteger(i) || i < 0 || i >= n)) return ['broken model data'];
|
|
125
|
+
if (m.p.some((x) => Math.abs(x) > far)) return [`a corner is more than ${LIMITS.size / 1000} m from the origin: too far for a link`];
|
|
126
|
+
// what the page and the file writers read as text is text, and short
|
|
127
|
+
for (const k of ['title', 'version', 'src', 'set', 'material', 'orientation']) if (m[k] != null && (typeof m[k] !== 'string' || m[k].length > LIMITS.text)) return [`broken ${k}`];
|
|
105
128
|
if (m.sheet != null && (!Array.isArray(m.sheet) || m.sheet.length > LIMITS.sheet || m.sheet.some((r) => !Array.isArray(r) || r.length > 9 || r.some((c) => typeof c !== 'string')))) return ['broken rules sheet'];
|
|
106
129
|
if (Array.isArray(m.views) && m.views.length > LIMITS.views) return [`${m.views.length} flat views: more than a link can hold (${LIMITS.views})`];
|
|
107
130
|
if (m.views != null && (!Array.isArray(m.views) || m.views.some((v) => !Array.isArray(v) || typeof v[0] !== 'string' || typeof v[1] !== 'string' || v[1].length > LIMITS.viewSize))) return ['broken views'];
|
|
108
131
|
if (m.motion != null && !motionOk(m.motion, m.parts?.length ?? 1)) return ['broken motion'];
|
|
109
|
-
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'];
|
|
132
|
+
if (m.parts != null && (!Array.isArray(m.parts) || m.parts.some((x) => !Array.isArray(x) || x.slice(0, 3).some((name, k) => (k === 2 && name == null ? false : typeof name !== 'string' || name.length > LIMITS.text)) || !Number.isInteger(x[3]) || !Number.isInteger(x[4]) || x[3] < 0 || x[4] < 0 || x[3] + x[4] > m.t.length / 3))) return ['broken parts list'];
|
|
110
133
|
return [];
|
|
111
134
|
}
|
|
112
135
|
|
|
@@ -122,7 +145,9 @@ function motionOk(mo, places) {
|
|
|
122
145
|
|| (j.follow != null && !(Array.isArray(j.follow) && typeof j.follow[0] === 'string' && nums(j.follow.slice(1)))))) return false;
|
|
123
146
|
if (!Array.isArray(mo.part) || mo.part.length !== places || !mo.part.every(item)) return false;
|
|
124
147
|
if (mo.poses != null && (typeof mo.poses !== 'object' || Object.values(mo.poses).some((p) => !p || typeof p !== 'object' || Object.values(p).some((v) => !(typeof v === 'number' || nums(v)))))) return false;
|
|
125
|
-
|
|
148
|
+
const pair = (x) => Array.isArray(x) && x.length === 2 && x.every((i) => Number.isInteger(i) && i >= 0 && i < places);
|
|
149
|
+
if (mo.swap != null && (typeof mo.swap !== 'object' || Object.entries(mo.swap).some(([n, list]) => !mo.poses?.[n] || !Array.isArray(list) || !list.every(pair)))) return false;
|
|
150
|
+
return mo.allow == null || (Array.isArray(mo.allow) && mo.allow.every(pair));
|
|
126
151
|
}
|
|
127
152
|
|
|
128
153
|
// Placed shapes -> one model ({ q, p, t, parts }), each copy its own part.
|
|
@@ -130,6 +155,9 @@ export function expand(m) {
|
|
|
130
155
|
const { shapes, place, ...meta } = m;
|
|
131
156
|
if (!Array.isArray(place) || shapes.length > LIMITS.shapes || place.length > LIMITS.places) throw new Error('model too big for a link');
|
|
132
157
|
for (const sh of shapes) { const e = check(sh); if (e.length) throw new Error(e[0]); }
|
|
158
|
+
// (counted before any copy is made: a few placements of a big shape would otherwise be built in full, then refused)
|
|
159
|
+
let count = 0;
|
|
160
|
+
for (const [i] of place) { count += (shapes[i]?.t.length || 0) / 3; if (count > LIMITS.triangles) throw new Error('model too big for a link'); }
|
|
133
161
|
const list = place.map(([i, ...rest], n) => {
|
|
134
162
|
const sh = shapes[i], t = rest.slice(0, 12);
|
|
135
163
|
if (!sh || t.length !== 12 || t.some((x) => !Number.isFinite(x))) throw new Error('broken placement');
|
|
@@ -159,14 +187,18 @@ export function triangles(m, part) {
|
|
|
159
187
|
}
|
|
160
188
|
|
|
161
189
|
// The model's parts, always at least one: [[name, role, label, first, count]]
|
|
162
|
-
export const partsOf = (m) => (m.parts?.length ? m.parts : [['body', 'part', m.title || 'model', 0, m.t.length / 3]]);
|
|
190
|
+
export const partsOf = (m) => (m.parts?.length ? m.parts.filter((x) => x[1] !== 'pose') : [['body', 'part', m.title || 'model', 0, m.t.length / 3]]);
|
|
191
|
+
// The shapes parts take only in poses (role "pose"), with their places: [{ k, part }]
|
|
192
|
+
/** @param {Model} m @returns {{ k: number, part: any[] }[]} */
|
|
193
|
+
export const posesOf = (m) => (m.parts || []).map((part, k) => ({ k, part })).filter((x) => x.part[1] === 'pose');
|
|
163
194
|
|
|
164
195
|
// ---------- motion ----------
|
|
165
196
|
// Joints between items, so a page (or a tool) can move them: an assembly's hinges, rails and ball joints.
|
|
166
197
|
// motion: { items: [[name, …12?]], joints: [joint], poses: { name: { joint: value } }, pose?, part: [item per place],
|
|
167
|
-
// allow?: [[place, place]] }
|
|
198
|
+
// allow?: [[place, place]], swap?: { pose: [[place, place]] } }
|
|
168
199
|
// An item with 12 numbers sits there (a 3 × 4 transform by rows, as in place); one without is placed by the joint
|
|
169
200
|
// whose child it is. part[n] is the item place n moves with (-1: it never moves); allow pairs may overlap (press fits).
|
|
201
|
+
// swap: in a pose, each part (its place) is drawn as another (a "pose" part's place): the shape it takes there.
|
|
170
202
|
// joint: { id, type, parent (item, -1 the world), child (item), a (the parent's anchor, 12 numbers, in its own
|
|
171
203
|
// frame), b (the child's anchor), dofs: [[min, max, value]], label?, follow?: [joint id, ratio, offset],
|
|
172
204
|
// path?: [[x, y, z], …], cone? }. At value 0 the child's anchor lies on the parent's: same place, same axes.
|
|
@@ -282,7 +314,8 @@ export function placeItems(motion, values) {
|
|
|
282
314
|
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}`;
|
|
283
315
|
|
|
284
316
|
// Which parts a file holds: all the printed ones (references are only there to check a fit), or the indices picked
|
|
285
|
-
|
|
317
|
+
// keep: which parts, as a Set of their places in partsOf(m), or a function of each part and its place
|
|
318
|
+
const chosen = (m, keep) => partsOf(m).filter((x, i) => (keep ? (typeof keep === 'function' ? keep(x, i) : keep.has(i)) : x[1] !== 'reference'));
|
|
286
319
|
|
|
287
320
|
// Binary STL (mm): the parts picked, as one mesh, each part mended (mesh) as for 3MF.
|
|
288
321
|
// fromSTL(bytes) -> triangles [[[x, y, z] ×3], …] from an STL file, binary or text (ASCII). Units are as the file has
|
|
@@ -307,7 +340,7 @@ export function fromSTL(bytes) {
|
|
|
307
340
|
}
|
|
308
341
|
|
|
309
342
|
// generator: the name the file says made it (rulecad by default)
|
|
310
|
-
/** A binary STL of the printed parts (or those kept). @param {Model} m @param {(part: any[]) => boolean} [keep] @param {{ generator?: string }} [options] @returns {Uint8Array} */
|
|
343
|
+
/** A binary STL of the printed parts (or those kept). @param {Model} m @param {Set<number> | ((part: any[], index: number) => boolean)} [keep] the parts to write: their places in partsOf(m), or a test of each @param {{ generator?: string }} [options] @returns {Uint8Array} */
|
|
311
344
|
export function stl(m, keep, { generator = 'rulecad' } = {}) {
|
|
312
345
|
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);
|
|
313
346
|
const head = `${generator} ${m.src || m.title || ''}`.slice(0, 80);
|
|
@@ -328,7 +361,7 @@ export const thingOf = (name) => { const bits = String(name).split('.'); return
|
|
|
328
361
|
|
|
329
362
|
// 3MF of the parts picked, in Bambu Studio's layout (bambu3mf): one object per printed thing, its parts on their AMS
|
|
330
363
|
// slots (parts' sixth field; slot 1 without one).
|
|
331
|
-
/** 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>} */
|
|
364
|
+
/** A 3MF in Bambu Studio's layout, each part on its filament slot. @param {Model} m @param {Set<number> | ((part: any[], index: number) => boolean)} [keep] the parts to write: their places in partsOf(m), or a test of each @param {{ generator?: string }} [options] @returns {Promise<Uint8Array>} */
|
|
332
365
|
export async function threemf(m, keep, { generator = 'rulecad' } = {}) {
|
|
333
366
|
const things = new Map();
|
|
334
367
|
for (const x of chosen(m, keep)) {
|
|
@@ -446,7 +479,7 @@ 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
|
|
|
446
479
|
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"';
|
|
447
480
|
|
|
448
481
|
/** @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) */
|
|
449
|
-
export async function bambu3mf(objects, { centre = [128, 128], generator = 'rulecad', date } = {}) {
|
|
482
|
+
export async function bambu3mf(objects, { centre = [128, 128], generator = 'rulecad', date, title } = {}) {
|
|
450
483
|
const files = {}, rels = [], resources = [], build = [], settings = [], instances = [];
|
|
451
484
|
let id = 0;
|
|
452
485
|
objects.forEach((o, n) => {
|
|
@@ -467,7 +500,7 @@ export async function bambu3mf(objects, { centre = [128, 128], generator = 'rule
|
|
|
467
500
|
['[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`],
|
|
468
501
|
['_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`],
|
|
469
502
|
['3D/_rels/3dmodel.model.rels', `${xml}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n ${rels.join('\n ')}\n</Relationships>\n`],
|
|
470
|
-
['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"
|
|
503
|
+
['3D/3dmodel.model', `${xml}<model unit="millimeter" xml:lang="en-US" ${NS}>\n <metadata name="Application">${esc(generator)}</metadata>\n <metadata name="BambuStudio:3mfVersion">1</metadata>\n <metadata name="Title">${esc(title || objects[0]?.name || 'model')}</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`],
|
|
471
504
|
['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`],
|
|
472
505
|
...Object.entries(files),
|
|
473
506
|
]);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/model-link",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
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
5
|
"type": "module",
|
|
6
6
|
"exports": {
|