@rulecad/model-link 0.3.2 → 0.3.3
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 +7 -3
- package/model-link.mjs +83 -17
- package/package.json +1 -1
package/model-link.d.mts
CHANGED
|
@@ -95,9 +95,12 @@ export function stl(m: Model, keep?: Set<number> | ((part: any[], index: number)
|
|
|
95
95
|
export function threemf(m: Model, keep?: Set<number> | ((part: any[], index: number) => boolean), { generator }?: {
|
|
96
96
|
generator?: string;
|
|
97
97
|
}): Promise<Uint8Array>;
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
98
|
+
/** @param {Triangle[]} tris @param {{ budget: number }} [work] @returns {{ verts: number[][], tris: number[][] }} */
|
|
99
|
+
export function mesh(tris: Triangle[], work?: {
|
|
100
|
+
budget: number;
|
|
101
|
+
}): {
|
|
102
|
+
verts: number[][];
|
|
103
|
+
tris: number[][];
|
|
101
104
|
};
|
|
102
105
|
/** @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) */
|
|
103
106
|
export function bambu3mf(objects: {
|
|
@@ -154,6 +157,7 @@ export const turn: (degrees: number[]) => number[];
|
|
|
154
157
|
/** @type {(points: number[][]) => number} */
|
|
155
158
|
export const pathLength: (points: number[][]) => number;
|
|
156
159
|
export function filename(m: any, ext: any, picked?: string): string;
|
|
160
|
+
export function fabName(name: any): string;
|
|
157
161
|
export function thingOf(name: any): string;
|
|
158
162
|
/**
|
|
159
163
|
* corners in mm, counter-clockwise seen from outside, Z up
|
package/model-link.mjs
CHANGED
|
@@ -141,7 +141,13 @@ function problems(m) {
|
|
|
141
141
|
if (m.steps != null && !stepsOk(m.steps)) return ['broken step file'];
|
|
142
142
|
if (m.wires != null && !wiresOk(m.wires)) return ['broken wires'];
|
|
143
143
|
if (m.build != null && !plain(m.build)) return ['broken build page'];
|
|
144
|
+
if (m.show != null && m.show !== 'built') return ['broken show'];
|
|
144
145
|
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'];
|
|
146
|
+
// parts may share triangles, but all of them together are held to the link's limit: a short list of parts each
|
|
147
|
+
// naming every triangle would otherwise make the file writers write (and mend) the model hundreds of times over.
|
|
148
|
+
// The list itself is held to an assembly's limit on places: a long list of empty parts made the 3MF writer write
|
|
149
|
+
// hundreds of megabytes of part names for nothing.
|
|
150
|
+
if (m.parts != null && (m.parts.length > LIMITS.places || m.parts.reduce((n, x) => n + x[4], 0) > LIMITS.triangles)) return ['model too big for a link'];
|
|
145
151
|
return [];
|
|
146
152
|
}
|
|
147
153
|
|
|
@@ -182,6 +188,7 @@ function motionOk(mo, places) {
|
|
|
182
188
|
// point] | null], stroke matching a block's.
|
|
183
189
|
// wires: [[id, [[item (index, -1 fixed), x, y, z], …]]], routes drawn faint, moving with their items; never parts.
|
|
184
190
|
// build: the build page's content, read as text and numbers (the shopping list, plates, wiring, steps, settings).
|
|
191
|
+
// show (optional): 'built', an assembly shown as the thing built: its references drawn solid, as its parts are.
|
|
185
192
|
const INT = 2 ** 31;
|
|
186
193
|
const int = (x) => Number.isInteger(x) && Math.abs(x) < INT;
|
|
187
194
|
const text = (x) => typeof x === 'string' && x.length <= LIMITS.text;
|
|
@@ -398,6 +405,11 @@ export function placeItems(motion, values) {
|
|
|
398
405
|
// cap@0.6.0.stl; with what was picked, if not everything: staggered-cap-2-4.3mf
|
|
399
406
|
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}`;
|
|
400
407
|
|
|
408
|
+
// A fab zip's name as JLCPCB's upload takes it: letters, digits, _ and - before .zip, and none of the words it refuses
|
|
409
|
+
// (eval, copy, convert, confirm). So module@0.7.1-fab.zip is saved as module-v0_7_1-fab.zip
|
|
410
|
+
export const fabName = (name) => `${String(name).replace(/\.zip$/i, '').replace(/@/g, '-v').replace(/[^A-Za-z0-9_-]+/g, '_')
|
|
411
|
+
.replace(/eval|copy|convert|confirm/gi, (w) => `${w[0]}_${w.slice(1)}`).replace(/^[_-]+|[_-]+$/g, '') || 'board-fab'}.zip`;
|
|
412
|
+
|
|
401
413
|
// Which parts a file holds: all the printed ones (references are only there to check a fit), or the indices picked
|
|
402
414
|
// keep: which parts, as a Set of their places in partsOf(m), or a function of each part and its place
|
|
403
415
|
const chosen = (m, keep) => partsOf(m).filter((x, i) => (keep ? (typeof keep === 'function' ? keep(x, i) : keep.has(i)) : x[1] !== 'reference'));
|
|
@@ -428,7 +440,8 @@ export function fromSTL(bytes) {
|
|
|
428
440
|
// generator: the name the file says made it (rulecad by default)
|
|
429
441
|
/** 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} */
|
|
430
442
|
export function stl(m, keep, { generator = 'rulecad' } = {}) {
|
|
431
|
-
const
|
|
443
|
+
const picked = chosen(m, keep), work = { budget: 2e6 + 100 * picked.reduce((n, x) => n + x[4], 0) }; // one mend budget for the file
|
|
444
|
+
const tris = picked.flatMap((x) => { const { verts, tris: t } = mesh(triangles(m, x), work); return t.map((ids) => ids.map((i) => verts[i])); }), buf = new ArrayBuffer(84 + 50 * tris.length), dv = new DataView(buf);
|
|
432
445
|
const head = `${generator} ${m.src || m.title || ''}`.slice(0, 80);
|
|
433
446
|
for (let i = 0; i < head.length; i++) dv.setUint8(i, head.charCodeAt(i) & 0x7f);
|
|
434
447
|
dv.setUint32(80, tris.length, true);
|
|
@@ -480,7 +493,10 @@ const num = (x) => String(Number(x.toFixed(5)));
|
|
|
480
493
|
// and its repair can fill a legend's letters with sheets. So a triangle with a loose corner lying along its open edge is
|
|
481
494
|
// split there, one corner at a time until none is left, and any pinhole still open (a loop of open edges less than a
|
|
482
495
|
// millimetre round) is closed with a fan. Each part comes out as one closed body per piece (a keycap; each letter).
|
|
483
|
-
|
|
496
|
+
// work: a mend budget shared by the parts of one file ({ budget }, spent as it goes), so a file of many parts cannot
|
|
497
|
+
// spend a budget for each (stl, threemf and bambu3mf pass one); on its own a part gets a budget sized from it.
|
|
498
|
+
/** @param {Triangle[]} tris @param {{ budget: number }} [work] @returns {{ verts: number[][], tris: number[][] }} */
|
|
499
|
+
export function mesh(tris, work) {
|
|
484
500
|
const MERGE = 1e-3, verts = [], index = new Map(), out = [];
|
|
485
501
|
const key = (v) => v.map((c) => Math.round(c / MERGE)).join(',');
|
|
486
502
|
const at = (v) => { // the same corner as one already seen within MERGE (it may sit across a rounding boundary)
|
|
@@ -495,30 +511,78 @@ export function mesh(tris) {
|
|
|
495
511
|
const area2 = (ids) => { const [a, b, c] = ids.map((i) => verts[i]); return Math.hypot(...cross(sub(b, a), sub(c, a))); };
|
|
496
512
|
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); }
|
|
497
513
|
|
|
498
|
-
// Mend: split a triangle at a loose corner lying along its open edge, one corner at a time, until none is left
|
|
514
|
+
// Mend: split a triangle at a loose corner lying along its open edge, one corner at a time, until none is left.
|
|
515
|
+
// The loose corners are filed in 1 mm cells. Each open edge takes the cheapest of three searches: every cell of its
|
|
516
|
+
// box (a short or square-on edge), only the cells its line passes through and their neighbours (a long slanted edge:
|
|
517
|
+
// a corner within TOL of the line is at most one cell off it, so the work grows with the edge's length), or a plain
|
|
518
|
+
// look at every loose corner (few loose corners). (It always searched the box, which grows with the cube of a slanted
|
|
519
|
+
// edge's length: a short link holding one long diagonal triangle froze the writers for minutes.) All three find the
|
|
520
|
+
// same corner: the nearest the line, ties going to the corner first in cell order, as the box search always did.
|
|
521
|
+
// The searches share a work budget sized from the mesh, cells and corners looked at across all passes, so a mesh
|
|
522
|
+
// made to be slow (thousands of long open edges among thousands of loose corners) cannot freeze the writers: once
|
|
523
|
+
// it is spent, the edges left are not mended and are written as they are.
|
|
499
524
|
const TOL = 2e-3, CELL = 1, cell = (x) => Math.floor(x / CELL);
|
|
525
|
+
let budget = work ? work.budget : 2e6 + 100 * out.length; // cells and corners looked at, across all passes
|
|
500
526
|
for (let pass = 0; pass < 50; pass++) {
|
|
501
527
|
const edges = new Set(); for (const [a, b, c] of out) edges.add(`${a},${b}`).add(`${b},${c}`).add(`${c},${a}`);
|
|
502
528
|
const isOpen = (a, b) => !edges.has(`${b},${a}`), loose = new Set();
|
|
503
529
|
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);
|
|
504
530
|
if (!loose.size) break;
|
|
505
|
-
const grid = new Map();
|
|
506
|
-
for (const i of
|
|
531
|
+
const grid = new Map(), rank = new Map(), looseList = [...loose];
|
|
532
|
+
for (const i of looseList) { const k = verts[i].map(cell).join(','); if (!grid.has(k)) grid.set(k, []); rank.set(i, rank.size); grid.get(k).push(i); }
|
|
533
|
+
// Which of two corners the box search met first: the lower cell (x, then y, then z), then the one filed first
|
|
534
|
+
const before = (i, j) => {
|
|
535
|
+
for (let k = 0; k < 3; k++) { const ci = cell(verts[i][k]), cj = cell(verts[j][k]); if (ci !== cj) return ci < cj; }
|
|
536
|
+
return rank.get(i) < rank.get(j);
|
|
537
|
+
};
|
|
507
538
|
// The loose corner along a -> b nearest the line, if any
|
|
508
539
|
const along = (a, b) => {
|
|
509
|
-
const p = verts[a],
|
|
510
|
-
|
|
511
|
-
let best = null;
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
540
|
+
const p = verts[a], q = verts[b], d = sub(q, p), len = Math.sqrt(dot(d, d));
|
|
541
|
+
if (!(len * len < Infinity)) return null; // corners too far apart to measure (or not numbers): every corner looked on the line
|
|
542
|
+
let best = null, spent = false;
|
|
543
|
+
const consider = (i) => {
|
|
544
|
+
if (i === a || i === b) return;
|
|
545
|
+
const w = sub(verts[i], p), t = dot(w, d) / (len * len);
|
|
546
|
+
if (t * len < TOL || (1 - t) * len < TOL) return;
|
|
547
|
+
const off = Math.hypot(...cross(w, d)) / len;
|
|
548
|
+
if (off < TOL && (!best || off < best[1] || (off === best[1] && before(i, best[0])))) best = [i, off];
|
|
549
|
+
};
|
|
550
|
+
const from = p.map(cell), to = q.map(cell), steps = [0, 1, 2].reduce((s, k) => s + Math.abs(to[k] - from[k]), 0);
|
|
551
|
+
const lo = [0, 1, 2].map((k) => cell(Math.min(p[k], q[k]) - TOL)), hi = [0, 1, 2].map((k) => cell(Math.max(p[k], q[k]) + TOL));
|
|
552
|
+
const box = (hi[0] - lo[0] + 1) * (hi[1] - lo[1] + 1) * (hi[2] - lo[2] + 1), walk = 27 * (steps + 1);
|
|
553
|
+
const cost = Math.min(box, walk, looseList.length);
|
|
554
|
+
if (cost > budget) return null; // the budget is spent: this edge is left open
|
|
555
|
+
budget -= cost;
|
|
556
|
+
if (cost === looseList.length && cost < box && cost < walk) { for (const i of looseList) consider(i); return best; }
|
|
557
|
+
// The grid searches pay for each corner they find in a cell too: many loose corners packed in a few cells would
|
|
558
|
+
// otherwise cost every edge there all of them, with only its cells counted (a few kilobytes of tiny triangles in
|
|
559
|
+
// one cell froze the writers). If the budget runs out part way, the edge is left open.
|
|
560
|
+
const meet = (list) => { for (const i of list) { if (--budget < 0) { spent = true; return; } consider(i); } };
|
|
561
|
+
if (box <= walk) { // a short or square-on edge: its box is fewer cells than the walk
|
|
562
|
+
for (let x = lo[0]; x <= hi[0] && !spent; x++) for (let y = lo[1]; y <= hi[1] && !spent; y++) for (let z = lo[2]; z <= hi[2] && !spent; z++) meet(grid.get(`${x},${y},${z}`) || []);
|
|
563
|
+
return spent ? null : best;
|
|
564
|
+
}
|
|
565
|
+
// Walk the cells the segment passes through (a 3D grid walk), looking in each and its 26 neighbours once
|
|
566
|
+
const seen = new Set(), look = (c) => {
|
|
567
|
+
for (let dx = -1; dx <= 1; dx++) for (let dy = -1; dy <= 1; dy++) for (let dz = -1; dz <= 1; dz++) {
|
|
568
|
+
const k = `${c[0] + dx},${c[1] + dy},${c[2] + dz}`;
|
|
569
|
+
if (seen.has(k)) continue;
|
|
570
|
+
seen.add(k);
|
|
571
|
+
if (!spent) meet(grid.get(k) || []);
|
|
519
572
|
}
|
|
573
|
+
};
|
|
574
|
+
const c = [...from], step = d.map(Math.sign);
|
|
575
|
+
const tMax = [0, 1, 2].map((k) => (d[k] ? ((c[k] + (d[k] > 0 ? 1 : 0)) * CELL - p[k]) / d[k] : Infinity));
|
|
576
|
+
const tDelta = [0, 1, 2].map((k) => (d[k] ? CELL / Math.abs(d[k]) : Infinity));
|
|
577
|
+
look(c);
|
|
578
|
+
for (let n = 0; n < steps; n++) {
|
|
579
|
+
const k = tMax[0] <= tMax[1] ? (tMax[0] <= tMax[2] ? 0 : 2) : (tMax[1] <= tMax[2] ? 1 : 2);
|
|
580
|
+
if (c[k] === to[k]) { tMax[k] = Infinity; n--; continue; } // rounding: this axis is already at the end cell
|
|
581
|
+
c[k] += step[k]; tMax[k] += tDelta[k];
|
|
582
|
+
look(c);
|
|
520
583
|
}
|
|
521
|
-
|
|
584
|
+
look(to);
|
|
585
|
+
return spent ? null : best;
|
|
522
586
|
};
|
|
523
587
|
let split = 0;
|
|
524
588
|
const n = out.length;
|
|
@@ -537,6 +601,7 @@ export function mesh(tris) {
|
|
|
537
601
|
}
|
|
538
602
|
if (!split) break;
|
|
539
603
|
}
|
|
604
|
+
if (work) work.budget = budget;
|
|
540
605
|
// What's left are pinholes: a sliver face the booleans lost, a loop of open edges a fraction of a millimetre round.
|
|
541
606
|
// Close each with a fan.
|
|
542
607
|
const kept = out.filter((ids) => area2(ids) > 1e-9), edges = new Set();
|
|
@@ -567,11 +632,12 @@ const NS = 'xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02" xm
|
|
|
567
632
|
/** @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) */
|
|
568
633
|
export async function bambu3mf(objects, { centre = [128, 128], generator = 'rulecad', date, title } = {}) {
|
|
569
634
|
const files = {}, rels = [], resources = [], build = [], settings = [], instances = [];
|
|
635
|
+
const work = { budget: 2e6 + 100 * objects.reduce((n, o) => n + o.parts.reduce((k, p) => k + p.triangles.length, 0), 0) }; // one mend budget for the file
|
|
570
636
|
let id = 0;
|
|
571
637
|
objects.forEach((o, n) => {
|
|
572
638
|
const path = `/3D/Objects/object_${n + 1}.model`, parts = o.parts.map((p) => ({ ...p, id: ++id }));
|
|
573
639
|
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`
|
|
574
|
-
+ 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';
|
|
640
|
+
+ parts.map((p) => ` <object id="${p.id}" p:UUID="${uuid(p.id, 1)}" type="model">${meshXml(mesh(p.triangles, work))}</object>\n`).join('') + ' </resources>\n <build/>\n</model>\n';
|
|
575
641
|
rels.push(`<Relationship Target="${path}" Id="rel-${n + 1}" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/>`);
|
|
576
642
|
const parent = 100000 + n + 1;
|
|
577
643
|
resources.push(` <object id="${parent}" p:UUID="${uuid(n + 1, 0)}" type="model">\n <components>\n`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/model-link",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.3",
|
|
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": {
|