@rulecad/model-link 0.1.5 → 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/README.md +5 -0
- package/model-link.d.mts +49 -6
- package/model-link.mjs +181 -15
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -25,6 +25,11 @@ const zip = await threemf(back); // Uint8Array, a .3mf (one object, two
|
|
|
25
25
|
- **Precision:** corners are snapped to a grid about 1/5000 of the model's size, and shared corners are stored once.
|
|
26
26
|
- **Many copies of one shape** (nine keycaps): `fromShapes()` stores each shape once and a transform per copy, and
|
|
27
27
|
`decode()` expands them.
|
|
28
|
+
- **Things that move:** a model can carry `motion`: its items, the joints between them (fixed, revolute, prismatic,
|
|
29
|
+
cylindrical, ball, path), named poses, and which item each part moves with. `jointValues(motion, pose)` gives every
|
|
30
|
+
joint's values, followers included, and `placeItems(motion, values)` gives where each item is. The page uses these
|
|
31
|
+
for its sliders, and `cad` uses the same functions to place an assembly, so both agree. The format is described at
|
|
32
|
+
the top of the motion section in `model-link.mjs`.
|
|
28
33
|
- **Safety:** links are data, never code. `decode()` checks the format and sizes (`LIMITS`), refuses damaged links,
|
|
29
34
|
and refuses links from a newer format version.
|
|
30
35
|
- **Short links:** `parseHash(location.hash)` also reads `#s=<id>`, a GitHub Gist holding the data, and
|
package/model-link.d.mts
CHANGED
|
@@ -44,14 +44,37 @@ export function fromShapes(list: any): {
|
|
|
44
44
|
};
|
|
45
45
|
/** The model's triangles, or one part's. @param {Model} m @param {any[]} [part] @returns {Triangle[]} */
|
|
46
46
|
export function triangles(m: Model, part?: any[]): Triangle[];
|
|
47
|
+
/** m · n, two 3 × 4 transforms by rows @param {number[]} m @param {number[]} n @returns {number[]} */
|
|
48
|
+
export function mul(m: number[], n: number[]): number[];
|
|
49
|
+
/** The inverse of a rigid 3 × 4 transform @param {number[]} m @returns {number[]} */
|
|
50
|
+
export function inv(m: number[]): number[];
|
|
51
|
+
/** @param {number[]} at @param {number[]} [axis] @param {number[]} [ref] @returns {number[]} */
|
|
52
|
+
export function frame(at: number[], axis?: number[], ref?: number[]): number[];
|
|
53
|
+
/** @param {{ id: string, type: string, path?: number[][] }} j @param {number[]} v @returns {number[]} */
|
|
54
|
+
export function jointMatrix(j: {
|
|
55
|
+
id: string;
|
|
56
|
+
type: string;
|
|
57
|
+
path?: number[][];
|
|
58
|
+
}, v: number[]): number[];
|
|
59
|
+
/** @param {{ joints: any[], poses?: Record<string, Record<string, number | number[]>>, pose?: string }} motion @param {string | Record<string, number | number[]> | null} [pose] @returns {Record<string, number[]>} */
|
|
60
|
+
export function jointValues(motion: {
|
|
61
|
+
joints: any[];
|
|
62
|
+
poses?: Record<string, Record<string, number | number[]>>;
|
|
63
|
+
pose?: string;
|
|
64
|
+
}, pose?: string | Record<string, number | number[]> | null): Record<string, number[]>;
|
|
65
|
+
/** @param {{ items: any[][], joints: any[] }} motion @param {Record<string, number[]>} values @returns {number[][]} */
|
|
66
|
+
export function placeItems(motion: {
|
|
67
|
+
items: any[][];
|
|
68
|
+
joints: any[];
|
|
69
|
+
}, values: Record<string, number[]>): number[][];
|
|
47
70
|
/** @param {ArrayBuffer | Uint8Array} bytes binary or text STL @returns {Triangle[]} */
|
|
48
71
|
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 }?: {
|
|
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 }?: {
|
|
51
74
|
generator?: string;
|
|
52
75
|
}): 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 }?: {
|
|
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 }?: {
|
|
55
78
|
generator?: string;
|
|
56
79
|
}): Promise<Uint8Array>;
|
|
57
80
|
export function mesh(tris: any): {
|
|
@@ -66,7 +89,7 @@ export function bambu3mf(objects: {
|
|
|
66
89
|
triangles: Triangle[];
|
|
67
90
|
slot?: number;
|
|
68
91
|
}[];
|
|
69
|
-
}[], { centre, generator, date }?: {
|
|
92
|
+
}[], { centre, generator, date, title }?: {
|
|
70
93
|
centre?: [number, number];
|
|
71
94
|
generator?: string;
|
|
72
95
|
date?: string;
|
|
@@ -79,7 +102,7 @@ export function bambu3mf(objects: {
|
|
|
79
102
|
*/
|
|
80
103
|
export function zip(entries: [string, string][]): Promise<Uint8Array>;
|
|
81
104
|
/** @typedef {[[number, number, number], [number, number, number], [number, number, number]]} Triangle corners in mm, counter-clockwise seen from outside, Z up */
|
|
82
|
-
/** @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 */
|
|
105
|
+
/** @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 */
|
|
83
106
|
export const VERSION: 1;
|
|
84
107
|
export namespace LIMITS {
|
|
85
108
|
let vertices: number;
|
|
@@ -89,8 +112,27 @@ export namespace LIMITS {
|
|
|
89
112
|
let views: number;
|
|
90
113
|
let viewSize: number;
|
|
91
114
|
let sheet: number;
|
|
115
|
+
let size: number;
|
|
116
|
+
let text: number;
|
|
117
|
+
let bytes: number;
|
|
92
118
|
}
|
|
93
119
|
export function partsOf(m: any): any;
|
|
120
|
+
export function posesOf(m: Model): {
|
|
121
|
+
k: number;
|
|
122
|
+
part: any[];
|
|
123
|
+
}[];
|
|
124
|
+
export namespace DOFS {
|
|
125
|
+
let fixed: any[];
|
|
126
|
+
let revolute: string[];
|
|
127
|
+
let prismatic: string[];
|
|
128
|
+
let cylindrical: string[];
|
|
129
|
+
let ball: string[];
|
|
130
|
+
let path: string[];
|
|
131
|
+
}
|
|
132
|
+
/** @type {(degrees: number[]) => number[]} */
|
|
133
|
+
export const turn: (degrees: number[]) => number[];
|
|
134
|
+
/** @type {(points: number[][]) => number} */
|
|
135
|
+
export const pathLength: (points: number[][]) => number;
|
|
94
136
|
export function filename(m: any, ext: any, picked?: string): string;
|
|
95
137
|
export function thingOf(name: any): string;
|
|
96
138
|
/**
|
|
@@ -111,4 +153,5 @@ export type Model = {
|
|
|
111
153
|
shapes?: any[];
|
|
112
154
|
place?: any[];
|
|
113
155
|
views?: [string, string][];
|
|
156
|
+
motion?: any;
|
|
114
157
|
};
|
package/model-link.mjs
CHANGED
|
@@ -6,23 +6,44 @@
|
|
|
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:
|
|
13
15
|
// { …, shapes: [{ role, label, slot?, q, p, t }], place: [[shape, a, b, c, d, e, f, g, h, i, j, k, l, name?]] }
|
|
14
16
|
// (a 3 × 4 transform by rows, in mm). decode() expands them, so the rest of the page sees one model.
|
|
17
|
+
// motion (optional): joints a page can move, each part with its item (see "motion" below); without it, nothing moves.
|
|
15
18
|
// "1." is the format version: newer pages must keep reading old links.
|
|
16
19
|
|
|
17
20
|
/** @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 */
|
|
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 */
|
|
19
22
|
|
|
20
23
|
export const VERSION = 1;
|
|
21
|
-
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
|
|
22
28
|
|
|
23
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(/=+$/, ''); };
|
|
24
30
|
const unb64 = (s) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0));
|
|
25
|
-
|
|
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
|
+
}
|
|
26
47
|
|
|
27
48
|
// fromTriangles([[[x,y,z] ×3], …]) -> { q, p, t }: shared corners merged on a grid ~1/5000 of the model's size.
|
|
28
49
|
/** @param {Triangle[]} tris @returns {{ q: number, p: number[], t: number[] }} */
|
|
@@ -86,8 +107,8 @@ export async function decode(token) {
|
|
|
86
107
|
if (!m) throw new Error("this isn't a model link");
|
|
87
108
|
if (Number(m[1]) > VERSION) throw new Error(`this link needs a newer page (format ${m[1]})`);
|
|
88
109
|
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.'); }
|
|
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.'); }
|
|
91
112
|
if (model && Array.isArray(model.shapes)) model = expand(model);
|
|
92
113
|
const errors = check(model);
|
|
93
114
|
if (errors.length) throw new Error(errors[0]);
|
|
@@ -96,23 +117,47 @@ export async function decode(token) {
|
|
|
96
117
|
|
|
97
118
|
export function check(m) {
|
|
98
119
|
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'];
|
|
120
|
+
if (typeof m.q !== 'number' || !Number.isFinite(m.q) || !(m.q > 0)) return ['bad grid size'];
|
|
100
121
|
if (m.p.length % 3 || m.t.length % 3) return ['broken model data'];
|
|
101
122
|
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;
|
|
123
|
+
const n = m.p.length / 3, far = LIMITS.size / m.q;
|
|
103
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}`];
|
|
104
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'];
|
|
105
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})`];
|
|
106
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'];
|
|
107
|
-
if (m.
|
|
131
|
+
if (m.motion != null && !motionOk(m.motion, m.parts?.length ?? 1)) return ['broken motion'];
|
|
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'];
|
|
108
133
|
return [];
|
|
109
134
|
}
|
|
110
135
|
|
|
136
|
+
// A link's motion, as data: numbers where numbers go, items and joints that exist, nothing that could run
|
|
137
|
+
const nums = (a, n) => Array.isArray(a) && (n == null || a.length === n) && a.every((x) => typeof x === 'number' && Number.isFinite(x));
|
|
138
|
+
function motionOk(mo, places) {
|
|
139
|
+
if (!mo || typeof mo !== 'object' || !Array.isArray(mo.items) || !Array.isArray(mo.joints) || mo.items.length > LIMITS.places || mo.joints.length > LIMITS.places) return false;
|
|
140
|
+
const n = mo.items.length, item = (i) => Number.isInteger(i) && i >= -1 && i < n;
|
|
141
|
+
if (mo.items.some((x) => !Array.isArray(x) || typeof x[0] !== 'string' || !(x.length === 1 || nums(x.slice(1), 12)))) return false;
|
|
142
|
+
if (mo.joints.some((j) => !j || typeof j.id !== 'string' || !Object.hasOwn(DOFS, j.type) || (j.cone != null && !nums([j.cone])) || !item(j.parent) || !item(j.child) || j.child < 0 || !nums(j.a, 12) || !nums(j.b, 12)
|
|
143
|
+
|| !Array.isArray(j.dofs) || j.dofs.length !== DOFS[j.type].length || !j.dofs.every((d) => nums(d, 3))
|
|
144
|
+
|| (j.type === 'path' && !(Array.isArray(j.path) && j.path.length >= 2 && j.path.length <= LIMITS.places && j.path.every((p) => nums(p, 3))))
|
|
145
|
+
|| (j.follow != null && !(Array.isArray(j.follow) && typeof j.follow[0] === 'string' && nums(j.follow.slice(1)))))) return false;
|
|
146
|
+
if (!Array.isArray(mo.part) || mo.part.length !== places || !mo.part.every(item)) return false;
|
|
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;
|
|
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));
|
|
151
|
+
}
|
|
152
|
+
|
|
111
153
|
// Placed shapes -> one model ({ q, p, t, parts }), each copy its own part.
|
|
112
154
|
export function expand(m) {
|
|
113
155
|
const { shapes, place, ...meta } = m;
|
|
114
156
|
if (!Array.isArray(place) || shapes.length > LIMITS.shapes || place.length > LIMITS.places) throw new Error('model too big for a link');
|
|
115
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'); }
|
|
116
161
|
const list = place.map(([i, ...rest], n) => {
|
|
117
162
|
const sh = shapes[i], t = rest.slice(0, 12);
|
|
118
163
|
if (!sh || t.length !== 12 || t.some((x) => !Number.isFinite(x))) throw new Error('broken placement');
|
|
@@ -142,14 +187,135 @@ export function triangles(m, part) {
|
|
|
142
187
|
}
|
|
143
188
|
|
|
144
189
|
// The model's parts, always at least one: [[name, role, label, first, count]]
|
|
145
|
-
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');
|
|
194
|
+
|
|
195
|
+
// ---------- motion ----------
|
|
196
|
+
// Joints between items, so a page (or a tool) can move them: an assembly's hinges, rails and ball joints.
|
|
197
|
+
// motion: { items: [[name, …12?]], joints: [joint], poses: { name: { joint: value } }, pose?, part: [item per place],
|
|
198
|
+
// allow?: [[place, place]], swap?: { pose: [[place, place]] } }
|
|
199
|
+
// An item with 12 numbers sits there (a 3 × 4 transform by rows, as in place); one without is placed by the joint
|
|
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.
|
|
202
|
+
// joint: { id, type, parent (item, -1 the world), child (item), a (the parent's anchor, 12 numbers, in its own
|
|
203
|
+
// frame), b (the child's anchor), dofs: [[min, max, value]], label?, follow?: [joint id, ratio, offset],
|
|
204
|
+
// path?: [[x, y, z], …], cone? }. At value 0 the child's anchor lies on the parent's: same place, same axes.
|
|
205
|
+
// Types and their dofs (angles in degrees, distances in mm, along and about the anchor's z axis):
|
|
206
|
+
// fixed []; revolute [angle]; prismatic [distance]; cylindrical [angle, distance]; ball [x, y, z] (turned about x,
|
|
207
|
+
// then y, then z; cone: how far z may tip, in degrees); path [distance along path, a polyline in the parent's anchor
|
|
208
|
+
// frame, the child's z along it]
|
|
209
|
+
export const DOFS = { fixed: [], revolute: ['angle'], prismatic: ['distance'], cylindrical: ['angle', 'distance'], ball: ['angle', 'angle', 'angle'], path: ['distance'] };
|
|
210
|
+
const I3 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
|
|
211
|
+
// 3 × 4 transforms by rows: m · n, the inverse of a rigid one, and the turns and moves they're made from
|
|
212
|
+
/** m · n, two 3 × 4 transforms by rows @param {number[]} m @param {number[]} n @returns {number[]} */
|
|
213
|
+
export function mul(m, n) {
|
|
214
|
+
const o = [];
|
|
215
|
+
for (let r = 0; r < 3; r++) for (let c = 0; c < 4; c++) o.push(m[r * 4] * n[c] + m[r * 4 + 1] * n[4 + c] + m[r * 4 + 2] * n[8 + c] + (c === 3 ? m[r * 4 + 3] : 0));
|
|
216
|
+
return o;
|
|
217
|
+
}
|
|
218
|
+
/** The inverse of a rigid 3 × 4 transform @param {number[]} m @returns {number[]} */
|
|
219
|
+
export function inv(m) {
|
|
220
|
+
const t = [m[3], m[7], m[11]], o = [];
|
|
221
|
+
for (let r = 0; r < 3; r++) { const row = [m[r], m[4 + r], m[8 + r]]; o.push(...row, -(row[0] * t[0] + row[1] * t[1] + row[2] * t[2])); }
|
|
222
|
+
return o;
|
|
223
|
+
}
|
|
224
|
+
const D = Math.PI / 180;
|
|
225
|
+
const rx = (a) => { const c = Math.cos(a * D), s = Math.sin(a * D); return [1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0]; };
|
|
226
|
+
const ry = (a) => { const c = Math.cos(a * D), s = Math.sin(a * D); return [c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0]; };
|
|
227
|
+
const rz = (a) => { const c = Math.cos(a * D), s = Math.sin(a * D); return [c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0]; };
|
|
228
|
+
const tz = (d) => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, d];
|
|
229
|
+
// Turned about x, then y, then z (degrees), as an assembly's rotate
|
|
230
|
+
/** @type {(degrees: number[]) => number[]} */
|
|
231
|
+
export const turn = ([x, y, z]) => mul(rz(z), mul(ry(y), rx(x)));
|
|
232
|
+
// A frame from where it is, its z axis and the way its x axis points (default: along x, or y if z is along x)
|
|
233
|
+
/** @param {number[]} at @param {number[]} [axis] @param {number[]} [ref] @returns {number[]} */
|
|
234
|
+
export function frame(at, axis = [0, 0, 1], ref) {
|
|
235
|
+
const unit = (v) => { const l = Math.hypot(...v); if (!(l > 1e-12)) throw new Error('an anchor axis has no length'); return v.map((x) => x / l); };
|
|
236
|
+
const z = unit(axis), dot = (u, v) => u[0] * v[0] + u[1] * v[1] + u[2] * v[2], cross = (u, v) => [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
|
|
237
|
+
let r = ref || (Math.abs(z[0]) > 0.9 ? [0, 1, 0] : [1, 0, 0]);
|
|
238
|
+
const x = unit(r.map((v, k) => v - dot(r, z) * z[k])), y = cross(z, x);
|
|
239
|
+
return [x[0], y[0], z[0], at[0], x[1], y[1], z[1], at[1], x[2], y[2], z[2], at[2]];
|
|
240
|
+
}
|
|
241
|
+
// The turn that takes z to v, the shortest way
|
|
242
|
+
function zTo(v) {
|
|
243
|
+
const l = Math.hypot(...v), [x, y, z] = v.map((c) => c / l), c = z;
|
|
244
|
+
if (c < -1 + 1e-9) return rx(180);
|
|
245
|
+
const k = 1 / (1 + c); // Rodrigues, about z × v = (-y, x, 0)
|
|
246
|
+
return [1 - x * x * k, -x * y * k, x, 0, -x * y * k, 1 - y * y * k, y, 0, -x, -y, c, 0];
|
|
247
|
+
}
|
|
248
|
+
// Along a polyline (distance s, kept within it): where, with z along the segment there
|
|
249
|
+
function along(points, s) {
|
|
250
|
+
let left = Math.max(0, s);
|
|
251
|
+
for (let i = 1; i < points.length; i++) {
|
|
252
|
+
const a = points[i - 1], b = points[i], d = [b[0] - a[0], b[1] - a[1], b[2] - a[2]], l = Math.hypot(...d);
|
|
253
|
+
if (left <= l || i === points.length - 1) { const f = l ? Math.min(left, l) / l : 0, m = zTo(l ? d : [0, 0, 1]); m[3] = a[0] + d[0] * f; m[7] = a[1] + d[1] * f; m[11] = a[2] + d[2] * f; return m; }
|
|
254
|
+
left -= l;
|
|
255
|
+
}
|
|
256
|
+
return [...I3];
|
|
257
|
+
}
|
|
258
|
+
/** @type {(points: number[][]) => number} */
|
|
259
|
+
export const pathLength = (points) => points.slice(1).reduce((t, b, i) => t + Math.hypot(b[0] - points[i][0], b[1] - points[i][1], b[2] - points[i][2]), 0);
|
|
260
|
+
// What a joint does at its values: the child's anchor, in the parent's anchor frame
|
|
261
|
+
/** @param {{ id: string, type: string, path?: number[][] }} j @param {number[]} v @returns {number[]} */
|
|
262
|
+
export function jointMatrix(j, v) {
|
|
263
|
+
switch (j.type) {
|
|
264
|
+
case 'fixed': return [...I3];
|
|
265
|
+
case 'revolute': return rz(v[0]);
|
|
266
|
+
case 'prismatic': return tz(v[0]);
|
|
267
|
+
case 'cylindrical': return mul(tz(v[1]), rz(v[0]));
|
|
268
|
+
case 'ball': return turn(v);
|
|
269
|
+
case 'path': return along(j.path, v[0]);
|
|
270
|
+
default: throw new Error(`joint ${j.id}: no joint type "${j.type}" (${Object.keys(DOFS).join(', ')})`);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
// Every joint's values: each at its default, then the pose's, then the joints that follow another
|
|
274
|
+
// pose: a name in motion.poses, or { joint: value }; values: [number] per joint, by id
|
|
275
|
+
/** @param {{ joints: any[], poses?: Record<string, Record<string, number | number[]>>, pose?: string }} motion @param {string | Record<string, number | number[]> | null} [pose] @returns {Record<string, number[]>} */
|
|
276
|
+
export function jointValues(motion, pose) {
|
|
277
|
+
const set = typeof pose === 'string' ? motion.poses?.[pose] : pose || (motion.pose ? motion.poses?.[motion.pose] : {});
|
|
278
|
+
if (typeof pose === 'string' && !set) throw new Error(`no pose "${pose}" (poses: ${Object.keys(motion.poses || {}).join(', ') || 'none'})`);
|
|
279
|
+
const out = {};
|
|
280
|
+
for (const j of motion.joints) {
|
|
281
|
+
const given = set?.[j.id];
|
|
282
|
+
out[j.id] = given == null ? j.dofs.map((d) => d[2]) : [].concat(given).map(Number);
|
|
283
|
+
if (out[j.id].length !== j.dofs.length) throw new Error(`joint ${j.id} (${j.type}) takes ${j.dofs.length} value${j.dofs.length === 1 ? '' : 's'}`);
|
|
284
|
+
}
|
|
285
|
+
const done = new Set(), follow = (j, seen = []) => {
|
|
286
|
+
if (!j.follow || done.has(j.id)) return out[j.id];
|
|
287
|
+
if (seen.includes(j.id)) throw new Error(`joints follow each other round: ${[...seen, j.id].join(' → ')}`);
|
|
288
|
+
const [lead, ratio = 1, offset = 0] = j.follow, l = motion.joints.find((x) => x.id === lead);
|
|
289
|
+
if (!l) throw new Error(`joint ${j.id} follows "${lead}", which isn't a joint`);
|
|
290
|
+
out[j.id] = follow(l, [...seen, j.id]).map((x) => x * ratio + offset).slice(0, j.dofs.length);
|
|
291
|
+
done.add(j.id); return out[j.id];
|
|
292
|
+
};
|
|
293
|
+
for (const j of motion.joints) follow(j);
|
|
294
|
+
return out;
|
|
295
|
+
}
|
|
296
|
+
// Where every item is at these values (jointValues): [12 numbers] per item, a joint's child from its parent
|
|
297
|
+
/** @param {{ items: any[][], joints: any[] }} motion @param {Record<string, number[]>} values @returns {number[][]} */
|
|
298
|
+
export function placeItems(motion, values) {
|
|
299
|
+
const by = new Map(motion.joints.map((j) => [j.child, j])), out = [];
|
|
300
|
+
const at = (i, seen = []) => {
|
|
301
|
+
if (out[i]) return out[i];
|
|
302
|
+
if (i < 0) return I3;
|
|
303
|
+
if (seen.includes(i)) throw new Error(`joints go round in a loop: ${[...seen, i].map((k) => motion.items[k][0]).join(' → ')} (join the loop's last pair with a loops check instead)`);
|
|
304
|
+
const j = by.get(i), item = motion.items[i];
|
|
305
|
+
if (!j) { if (item.length < 13) throw new Error(`item ${item[0]} has no place and no joint`); return (out[i] = item.slice(1, 13)); }
|
|
306
|
+
return (out[i] = mul(mul(mul(at(j.parent, [...seen, i]), j.a), jointMatrix(j, values[j.id])), inv(j.b)));
|
|
307
|
+
};
|
|
308
|
+
motion.items.forEach((_, i) => at(i));
|
|
309
|
+
return out;
|
|
310
|
+
}
|
|
146
311
|
|
|
147
312
|
// ---------- files ----------
|
|
148
313
|
// cap@0.6.0.stl; with what was picked, if not everything: staggered-cap-2-4.3mf
|
|
149
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}`;
|
|
150
315
|
|
|
151
316
|
// Which parts a file holds: all the printed ones (references are only there to check a fit), or the indices picked
|
|
152
|
-
|
|
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'));
|
|
153
319
|
|
|
154
320
|
// Binary STL (mm): the parts picked, as one mesh, each part mended (mesh) as for 3MF.
|
|
155
321
|
// fromSTL(bytes) -> triangles [[[x, y, z] ×3], …] from an STL file, binary or text (ASCII). Units are as the file has
|
|
@@ -174,7 +340,7 @@ export function fromSTL(bytes) {
|
|
|
174
340
|
}
|
|
175
341
|
|
|
176
342
|
// generator: the name the file says made it (rulecad by default)
|
|
177
|
-
/** 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} */
|
|
178
344
|
export function stl(m, keep, { generator = 'rulecad' } = {}) {
|
|
179
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);
|
|
180
346
|
const head = `${generator} ${m.src || m.title || ''}`.slice(0, 80);
|
|
@@ -195,7 +361,7 @@ export const thingOf = (name) => { const bits = String(name).split('.'); return
|
|
|
195
361
|
|
|
196
362
|
// 3MF of the parts picked, in Bambu Studio's layout (bambu3mf): one object per printed thing, its parts on their AMS
|
|
197
363
|
// slots (parts' sixth field; slot 1 without one).
|
|
198
|
-
/** 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>} */
|
|
199
365
|
export async function threemf(m, keep, { generator = 'rulecad' } = {}) {
|
|
200
366
|
const things = new Map();
|
|
201
367
|
for (const x of chosen(m, keep)) {
|
|
@@ -313,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
|
|
|
313
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"';
|
|
314
480
|
|
|
315
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) */
|
|
316
|
-
export async function bambu3mf(objects, { centre = [128, 128], generator = 'rulecad', date } = {}) {
|
|
482
|
+
export async function bambu3mf(objects, { centre = [128, 128], generator = 'rulecad', date, title } = {}) {
|
|
317
483
|
const files = {}, rels = [], resources = [], build = [], settings = [], instances = [];
|
|
318
484
|
let id = 0;
|
|
319
485
|
objects.forEach((o, n) => {
|
|
@@ -334,7 +500,7 @@ export async function bambu3mf(objects, { centre = [128, 128], generator = 'rule
|
|
|
334
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`],
|
|
335
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`],
|
|
336
502
|
['3D/_rels/3dmodel.model.rels', `${xml}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n ${rels.join('\n ')}\n</Relationships>\n`],
|
|
337
|
-
['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`],
|
|
338
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`],
|
|
339
505
|
...Object.entries(files),
|
|
340
506
|
]);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/model-link",
|
|
3
|
-
"version": "0.1
|
|
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": {
|