@rulecad/cad 0.7.53 → 0.7.56
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/AGENTS.md +20 -7
- package/CHANGELOG.md +108 -0
- package/EXAMPLES.md +579 -267
- package/README.md +106 -12
- package/TUTORIAL.md +25 -15
- package/bin/cad.mjs +79 -25
- package/lib/assembly.mjs +70 -26
- package/lib/beams.mjs +147 -0
- package/lib/bought.mjs +1 -1
- package/lib/buildpage.mjs +6 -3
- package/lib/design.mjs +13 -8
- package/lib/edit.mjs +26 -1
- package/lib/fasten.mjs +72 -15
- package/lib/frames.mjs +63 -0
- package/lib/jsonedit.mjs +19 -0
- package/lib/list.mjs +16 -9
- package/lib/measured.mjs +24 -4
- package/lib/motors.mjs +21 -10
- package/lib/order.mjs +5 -2
- package/lib/profilemeasure.mjs +278 -0
- package/lib/sandbox-hooks.mjs +2 -2
- package/lib/sandbox-run.mjs +3 -2
- package/lib/sandbox.mjs +8 -7
- package/lib/schema.mjs +4 -3
- package/lib/sheet.mjs +160 -4
- package/package.json +8 -6
- package/schemas/assembly.schema.json +37 -11
- package/schemas/object.schema.json +2 -2
- package/schemas/outline.schema.json +24 -0
package/lib/assembly.mjs
CHANGED
|
@@ -31,7 +31,7 @@ import { satisfies } from '@rulecad/versions';
|
|
|
31
31
|
import { bounds } from '@rulecad/printcheck';
|
|
32
32
|
import { closest, closestAt, inside, distanceToFace, overlapAt } from '@rulecad/fit';
|
|
33
33
|
import { keys as keyCentres, readLayout, hasLayout } from './layout.mjs';
|
|
34
|
-
import { DOFS, frame, turn, mul, pathLength, jointValues, placeItems, jointMatrix } from '@rulecad/model-link';
|
|
34
|
+
import { DOFS, frame, turn, mul, inv, pathLength, jointValues, placeItems, jointMatrix } from '@rulecad/model-link';
|
|
35
35
|
import { gearModel, internalModel, rackModel, mesh as meshOf, phase, rackPhase, contact, wormModel, wormMesh, bevelModel, bevelMesh, compoundEfficiency } from '@rulecad/gears';
|
|
36
36
|
import { ops as booleans } from '@rulecad/shapes';
|
|
37
37
|
import { motorBuilt, motorDrives, shaftFits, loadsOf, motorChecks, shaftFit, axisOf } from './motors.mjs';
|
|
@@ -46,6 +46,7 @@ import { gripChecks } from './grip.mjs';
|
|
|
46
46
|
import { gaitOf, gaitChecks, gaitSequence } from './gait.mjs';
|
|
47
47
|
import { boughtBuilt, boughtFindings, boughtSets } from './bought.mjs';
|
|
48
48
|
import { orderChecks } from './order.mjs';
|
|
49
|
+
import { beamBuilt, beamPlace, beamAddress, beamFindings, marksOf } from './beams.mjs';
|
|
49
50
|
let fastening = null; // lib/fasten.mjs, loaded with the first assembly that has a fasten: the rest start as fast as before
|
|
50
51
|
|
|
51
52
|
export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
|
|
@@ -110,6 +111,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
110
111
|
const built = new Map(); // each object or component is built once per set of values, however many copies are placed
|
|
111
112
|
const source = async (it, extra) => {
|
|
112
113
|
if (it.motor) { const key = JSON.stringify(['motor', it.id, it.motor]); if (!built.has(key)) built.set(key, motorBuilt(it.motor, num, it.id)); return built.get(key); }
|
|
114
|
+
if (it.beam) { const b = beamBuilt(it, num, it.id); if (!built.has(b.key)) built.set(b.key, b); return built.get(b.key); } // (lib/beams.mjs)
|
|
113
115
|
if (it.bought) {
|
|
114
116
|
const key = JSON.stringify(['bought', it.id, it.bought, it.variant, it.set]);
|
|
115
117
|
if (!built.has(key)) built.set(key, boughtSets().get(it.bought) === 'motor' ? motorBuilt({ model: it.bought }, num, it.id) : boughtBuilt(it.bought, it, num, it.id));
|
|
@@ -151,7 +153,8 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
151
153
|
let builtCount = 0;
|
|
152
154
|
for (const it of a.items || []) {
|
|
153
155
|
if (!/^[a-z][\w-]*$/.test(it.id || '')) throw new Error(`each item needs an id (letters, digits, - or _): got ${JSON.stringify(it.id)}`);
|
|
154
|
-
if ([it.object, it.assembly, it.motor, it.bought].filter(Boolean).length !== 1) throw new Error(`item ${it.id}: give one of "object", "assembly", "motor" or "
|
|
156
|
+
if ([it.object, it.assembly, it.motor, it.bought, it.beam].filter(Boolean).length !== 1) throw new Error(`item ${it.id}: give one of "object", "assembly", "motor", "bought" or "beam"`);
|
|
157
|
+
if (!it.beam && (it.to != null || it.roll != null)) throw new Error(`item ${it.id}: to and roll place a beam by its ends: place ${it.object || it.assembly || it.motor?.model || it.bought} with at and rotate`);
|
|
155
158
|
// Copies: one, a grid from repeat x/y, or a layout's keys. Each: { id, offset (from at), extra (values to set) }
|
|
156
159
|
const rx = it.repeat?.x, ry = it.repeat?.y, rl = it.repeat?.layout, copies = [];
|
|
157
160
|
if (rl) {
|
|
@@ -216,8 +219,8 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
216
219
|
for (const n of sub.seen) seen.add(n);
|
|
217
220
|
items.push({ ...it, id, sub, role: 'part' });
|
|
218
221
|
} else {
|
|
219
|
-
objects.push({ id, objName: src.objName, version: src.version, built: src.b, role: src.role, ...(src.set ? { set: src.set } : {}), ...(src.variant ? { variant: src.variant } : {}), ...(src.bought ? { bought: src.bought } : {}), ...(src.motor ? { motor: src.motor } : {}) });
|
|
220
|
-
items.push({ ...it, id, objName: src.objName, built: src.b, version: src.version, role: src.role });
|
|
222
|
+
objects.push({ id, objName: src.objName, version: src.version, built: src.b, role: src.role, ...(src.set ? { set: src.set } : {}), ...(src.variant ? { variant: src.variant } : {}), ...(src.bought ? { bought: src.bought } : {}), ...(src.motor ? { motor: src.motor } : {}), ...(src.beam ? { beam: src.beam } : {}) });
|
|
223
|
+
items.push({ ...it, id, objName: src.objName, built: src.b, version: src.version, role: src.role, ...(src.beam ? { beam: src.beam } : {}) });
|
|
221
224
|
}
|
|
222
225
|
}
|
|
223
226
|
// Every part, with its item where the joints put it at these values (jointValues); then the hardware of its fasten
|
|
@@ -234,15 +237,15 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
234
237
|
for (const p of src.sub.parts) {
|
|
235
238
|
if (p.role === 'support' && a.kind !== 'plate') continue;
|
|
236
239
|
out.push({ ...p, name: `${id}.${p.name}`, item: id, leaf: `${id}.${p.leaf}`, label: `${id} ${p.label}`,
|
|
237
|
-
geometry: transform(m, p.geometry), polygons: move(p.polygons), triangles: move(p.triangles), m: jscad.maths.mat4.multiply(jscad.maths.mat4.create(), m, p.m),
|
|
240
|
+
geometry: transform(m, p.geometry), polygons: move(p.polygons), triangles: move(p.triangles), ...(p.collide ? { collide: transform(m, p.collide) } : {}), m: jscad.maths.mat4.multiply(jscad.maths.mat4.create(), m, p.m),
|
|
238
241
|
...(p.hardware ? { moves: id, allow: p.allow.map((l) => `${id}.${l}`), lift: jscad.maths.vec3.transform([0, 0, 0], p.lift, [...m.slice(0, 12), 0, 0, 0, 1]) } : {}) }); // (a component's screws move with it)
|
|
239
242
|
}
|
|
240
243
|
} else {
|
|
241
244
|
for (const p of src.b.parts) {
|
|
242
245
|
if (p.role === 'support' && a.kind !== 'plate') continue; // supports are snipped off before parts go together
|
|
243
|
-
out.push({ name: `${id}.${p.name}`, item: id, leaf: id, object: src.objName, role: src.role === 'reference' ? 'reference' : p.role, label: `${id}: ${p.label}`,
|
|
246
|
+
out.push({ name: `${id}.${p.name}`, item: id, leaf: id, object: src.objName, role: src.role === 'reference' ? 'reference' : p.role, label: `${id}: ${marks.has(id) ? `mark ${marks.get(id)}, ` : ''}${p.label}`,
|
|
244
247
|
...(p.filament ? { filament: p.filament } : {}), ...(p.mirror === false ? { mirror: false } : {}), part: p.name,
|
|
245
|
-
geometry: transform(m, p.geometry), polygons: move(p.polygons), triangles: move(p.triangles),
|
|
248
|
+
geometry: transform(m, p.geometry), ...(p.collide ? { collide: transform(m, p.collide) } : {}), polygons: move(p.polygons), triangles: move(p.triangles),
|
|
246
249
|
shape: `${key}:${p.name}`, hash: `${src.b.hash}:${p.name}`, local: p.polygons, localTriangles: p.triangles, m });
|
|
247
250
|
}
|
|
248
251
|
}
|
|
@@ -251,6 +254,9 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
251
254
|
return out;
|
|
252
255
|
};
|
|
253
256
|
for (const x of a.fits || []) for (const p of x.poses || []) if (!motion.poses[p]) throw new Error(`fit ${x.note || x.label || `${x.a} / ${x.b}`}: no pose "${p}" (poses: ${Object.keys(motion.poses).join(', ') || 'none'})`);
|
|
257
|
+
// each beam's mark on the cut list and its sheet (beams that are the same share one), shown in its label
|
|
258
|
+
const marks = marksOf(objects);
|
|
259
|
+
for (const o of objects) if (marks.has(o.id)) o.mark = marks.get(o.id);
|
|
254
260
|
const pose = opts.pose ?? motion.pose;
|
|
255
261
|
const jv = jointValues(motion, pose);
|
|
256
262
|
const worlds0 = placeItems(motion, jv);
|
|
@@ -258,6 +264,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
258
264
|
// Screwed joints: each screw followed through the parts as they stand, its hardware placed, and the joint counted as a
|
|
259
265
|
// fit that fastens (what holds a part, what the order of assembly and the list read)
|
|
260
266
|
let fastened = null;
|
|
267
|
+
if (a.fits?.some((x) => x.holes)) fastening ||= await import('./fasten.mjs'); // (a holes fit with a fit that fastens: the fasten that says both is suggested)
|
|
261
268
|
if (a.fasten?.length && a.kind !== 'plate') {
|
|
262
269
|
fastening ||= await import('./fasten.mjs');
|
|
263
270
|
fastened = fastening.fastenOf({ a, project, parts, objects, motion, num }, worlds0, { access: pose === motion.pose });
|
|
@@ -267,6 +274,11 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
267
274
|
}
|
|
268
275
|
// A fit with * applies to every copy: "key-*.switch.bottom" becomes one fit for key-0-0, key-0-1, …
|
|
269
276
|
// With * on both sides, each copy is checked against all the others: { "a": "key-*.cap", "b": "key-*.cap" }
|
|
277
|
+
// A beam's address in a fit or an access is read now, so one past the beam's end is refused by name when it is built
|
|
278
|
+
const beamIds = new Set(placed.filter(([it]) => it.beam).map(([, c]) => c.id));
|
|
279
|
+
for (const x of a.fits || []) for (const n of [x.a, x.b, x.access].flat()) {
|
|
280
|
+
if (typeof n === 'string' && beamIds.has(n.split('.')[0]) && n.includes('.') && !/\.body$/.test(n)) motion.address(n, `fit ${x.note || x.label || `${x.a} / ${x.b}`}`);
|
|
281
|
+
}
|
|
270
282
|
for (let x of a.fits || []) {
|
|
271
283
|
if (x.seat != null && x.min == null) x = { ...x, min: -1000 }; // a seat presses, so the pair may overlap
|
|
272
284
|
if (x.holes) x = { ...x, a: x.holes, b: x.into }; // a holes fit: a board's holes (a) over what its screws go into (b)
|
|
@@ -338,30 +350,42 @@ function motionOf(a, placed, num, ref) {
|
|
|
338
350
|
// An anchor: { item (index, -1 the world), frame (12 numbers, in the item's own frame) }
|
|
339
351
|
const anchor = (spec, what) => {
|
|
340
352
|
if (spec && typeof spec === 'object') return { item: spec.item ? where(spec.item, what) : -1, frame: frameOf(spec, num) };
|
|
341
|
-
const bits = String(spec).split('.'),
|
|
342
|
-
if (!id || !
|
|
353
|
+
const bits = String(spec).split('.'), id = bits[0];
|
|
354
|
+
if (bits.length < 2 || !id || !bits.at(-1)) throw new Error(`${what}: name an anchor as <item>.<anchor> (got "${spec}")`);
|
|
343
355
|
const k = where(id, what);
|
|
344
|
-
let src = placed[k][1].src, pre = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
|
|
345
|
-
for (
|
|
346
|
-
const sub = src.sub?.items.find((x) => x.id === n);
|
|
347
|
-
if (!sub) throw new Error(`${what}: ${
|
|
356
|
+
let src = placed[k][1].src, pre = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0], i = 1;
|
|
357
|
+
for (; i < bits.length - 1 && !src.beam; i++) { // into a component: its item's place there
|
|
358
|
+
const n = bits[i], sub = src.sub?.items.find((x) => x.id === n);
|
|
359
|
+
if (!sub) throw new Error(`${what}: ${bits.slice(0, i).join('.')} has no item "${n}"`);
|
|
348
360
|
pre = mul(pre, rows(sub.m));
|
|
349
|
-
src = sub.sub ? { sub: sub.sub } : { b: sub.built, objName: sub.objName };
|
|
361
|
+
src = sub.sub ? { sub: sub.sub } : { b: sub.built, objName: sub.objName, beam: sub.beam };
|
|
350
362
|
}
|
|
363
|
+
// A beam's address, the rest of the name: an end (a, b), an end's bore (a.1), a face with a distance (top.2@120)
|
|
364
|
+
if (src.beam) return { item: k, frame: mul(pre, beamAddress(src.beam, bits.slice(i).join('.'), `${what}: ${bits.slice(0, i).join('.')}`)) };
|
|
365
|
+
const name = bits[i];
|
|
351
366
|
const anchors = src.b?.object.anchors || {};
|
|
352
367
|
if (!anchors[name]) throw new Error(`${what}: ${src.objName || id} has no anchor "${name}" (anchors: ${Object.keys(anchors).join(', ') || 'none'})`);
|
|
353
368
|
return { item: k, frame: mul(pre, frameOf(anchors[name], evalIn(src.b.values, `${src.objName} anchor ${name}`))) };
|
|
354
369
|
};
|
|
355
370
|
const joints = [], children = new Set();
|
|
356
|
-
|
|
371
|
+
// An item at an address ("at": "x1.top@50%") is held there as by a fixed joint: its own origin on the anchor, its z
|
|
372
|
+
// out of the face and its x along the beam toward end b, turned by its rotate in that frame; it moves with the beam
|
|
373
|
+
const atAddress = placed.map(([it]) => it).filter((it, k, all) => typeof it.at === 'string' && all.indexOf(it) === k).map((it) => {
|
|
374
|
+
if (it.repeat) throw new Error(`item ${it.id}: an item at an address ("${it.at}") is one copy: place a repeat with at [x, y, z]`);
|
|
375
|
+
if (it.beam) throw new Error(`item ${it.id}: a beam is placed by its ends (from, to) or at a point [x, y, z], not at an address`);
|
|
376
|
+
return { id: `${it.id}@`, type: 'fixed', parent: it.at, child: { item: it.id, at: [0, 0, 0], ...(it.rotate ? { rotate: it.rotate } : {}) }, at: true };
|
|
377
|
+
});
|
|
378
|
+
for (const j of [...atAddress, ...(a.joints || [])]) {
|
|
357
379
|
const what = `joint ${j.id}`;
|
|
358
|
-
if (!/^[a-z][\w-]*$/.test(j.id || '')) throw new Error(`each joint needs an id (letters, digits, - or _): got ${JSON.stringify(j.id)}`);
|
|
380
|
+
if (!j.at && !/^[a-z][\w-]*$/.test(j.id || '')) throw new Error(`each joint needs an id (letters, digits, - or _): got ${JSON.stringify(j.id)}`);
|
|
359
381
|
if (!Object.hasOwn(DOFS, j.type)) throw new Error(`${what}: type is one of ${Object.keys(DOFS).join(', ')} (got ${JSON.stringify(j.type)})`);
|
|
360
|
-
const p = j.parent == null ? { item: -1, frame: frame([0, 0, 0]) } : anchor(j.parent, what), c = anchor(j.child, what);
|
|
382
|
+
const p = j.parent == null ? { item: -1, frame: frame([0, 0, 0]) } : anchor(j.parent, j.at ? `item ${j.child.item}: at` : what), c = anchor(j.child, what);
|
|
383
|
+
if (j.at) c.frame = inv(c.frame); // (the item turned by its rotate in the anchor's frame: the joint's child anchor is that turn undone)
|
|
361
384
|
if (c.item < 0) throw new Error(`${what}: its child must be an item`);
|
|
362
|
-
if (
|
|
385
|
+
if (j.at && p.item === c.item) throw new Error(`item ${j.child.item}: at "${j.parent}" is on the item itself`);
|
|
386
|
+
if (children.has(c.item)) throw new Error(`${what}: ${placed[c.item][1].id} is already placed by ${joints.find((x) => x.child === c.item)?.at ? `its at (${placed[c.item][0].at})` : 'another joint'} (two joints to one item make a ring: use loops)`);
|
|
363
387
|
const [it] = placed[c.item];
|
|
364
|
-
if (it.at || it.rotate || it.repeat) throw new Error(`${what}: ${it.id} is placed by the joint, so it can't have at, rotate or
|
|
388
|
+
if (!j.at && (it.at || it.rotate || it.repeat || it.from != null && it.beam)) throw new Error(`${what}: ${it.id} is placed by the joint, so it can't have at, rotate, repeat${it.beam ? ', or from and to' : ''}`);
|
|
365
389
|
children.add(c.item);
|
|
366
390
|
const path = j.type === 'path' ? (j.path || []).map((pt) => pt.map(num)) : undefined;
|
|
367
391
|
if (path && path.length < 2) throw new Error(`${what}: a path joint needs "path": two points or more`);
|
|
@@ -374,7 +398,7 @@ function motionOf(a, placed, num, ref) {
|
|
|
374
398
|
if (mn > mx) throw new Error(`${what}: min ${mn} is above max ${mx}`);
|
|
375
399
|
return [mn, mx, val[i] != null ? num(val[i]) : Math.min(mx, Math.max(mn, 0))];
|
|
376
400
|
});
|
|
377
|
-
joints.push({ id: j.id, type: j.type, parent: p.item, child: c.item, a: p.frame, b: c.frame, dofs,
|
|
401
|
+
joints.push({ id: j.id, type: j.type, parent: p.item, child: c.item, a: p.frame, b: c.frame, dofs, ...(j.at ? { at: true } : {}),
|
|
378
402
|
...(j.label ? { label: j.label } : {}), ...(path ? { path } : {}), ...(j.cone != null ? { cone: num(j.cone) } : {}),
|
|
379
403
|
...(j.follow ? { follow: [j.follow, j.ratio != null ? num(j.ratio) : 1, j.offset != null ? num(j.offset) : 0] } : {}),
|
|
380
404
|
...(j.mesh ? { meshSpec: j.mesh } : {}), ...(j.brake ? { brake: j.brake } : {}) });
|
|
@@ -386,6 +410,8 @@ function motionOf(a, placed, num, ref) {
|
|
|
386
410
|
}
|
|
387
411
|
const items = placed.map(([it, c], k) => {
|
|
388
412
|
if (children.has(k)) return [c.id];
|
|
413
|
+
const ends = it.beam ? beamPlace(it, num) : null; // a beam by its ends (lib/beams.mjs)
|
|
414
|
+
if (ends) return [c.id, ...ends];
|
|
389
415
|
const base = (it.at || [0, 0, 0]).map(num), rot = (it.rotate || [0, 0, 0]).map((r) => num(r) * deg);
|
|
390
416
|
// A repeated item turns as a whole about its at: each copy's offset turns with it (keys on a tilted plate)
|
|
391
417
|
return [c.id, ...rows(translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create()))).transforms)];
|
|
@@ -403,9 +429,10 @@ function motionOf(a, placed, num, ref) {
|
|
|
403
429
|
const marks = placed.flatMap(([, c], k) => Object.entries(c.src?.b?.object.anchors || {}).map(([name, spec]) => {
|
|
404
430
|
try { return { item: k, id: c.id, name, frame: frameOf(spec, evalIn(c.src.b.values, `${c.src.objName} anchor ${name}`)) }; } catch { return null; }
|
|
405
431
|
})).filter(Boolean);
|
|
432
|
+
// address(name): any anchor by name, a beam's addresses too (x1.top@120), as { item, frame }: for fits and the build order
|
|
406
433
|
// Where each screw of a fasten goes, where it says so with anchors: a point on its axis, the anchor's z along it
|
|
407
434
|
const fasten = (a.fasten || []).map((x, i) => (Array.isArray(x.at) ? x.at : []).map((n) => ({ ...anchor(n, `fasten ${i + 1}`), name: typeof n === 'string' ? n : null })));
|
|
408
|
-
return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref, marks, meshes, drives, loads, fasten, gravity: (a.gravity || [0, 0, -1]).map(num) };
|
|
435
|
+
return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref, marks, meshes, drives, loads, fasten, gravity: (a.gravity || [0, 0, -1]).map(num), address: (n, what = 'address') => anchor(n, what) };
|
|
409
436
|
}
|
|
410
437
|
|
|
411
438
|
// A pair measured from its drawn teeth (@rulecad/gears contact: backlash, transmission error, interference), kept in
|
|
@@ -664,6 +691,14 @@ function gearMeshes(joints, items, num) {
|
|
|
664
691
|
}
|
|
665
692
|
|
|
666
693
|
// Where each item's anchors are in a pose: [{ id: 'keyboard@pivot', item, at: [x, y, z] }]
|
|
694
|
+
// Where an address is in the world, at these joint values: { id (its item), at, frame }, or null where it is not an
|
|
695
|
+
// address on a beam (x1.top@120, x1.a.1). A beam's address it does not have is refused by name.
|
|
696
|
+
export function addressAt(s, n, values = s.jointValues) {
|
|
697
|
+
const id = String(n).split('.')[0], it = s.items.find((x) => x.id === id);
|
|
698
|
+
if (!it?.beam || !String(n).includes('.') || !s.motion?.address) return null;
|
|
699
|
+
const r = s.motion.address(n), W = mul(placeItems(s.motion, values)[r.item], r.frame);
|
|
700
|
+
return { id, at: [W[3], W[7], W[11]], frame: W };
|
|
701
|
+
}
|
|
667
702
|
export function anchorsAt(s, values = s.jointValues) {
|
|
668
703
|
const worlds = placeItems(s.motion, values);
|
|
669
704
|
return (s.motion.marks || []).map((m) => { const w = mul(worlds[m.item], m.frame); return { id: `${m.id}@${m.name}`, item: m.id, at: [w[3], w[7], w[11]] }; });
|
|
@@ -703,11 +738,12 @@ async function measurer() {
|
|
|
703
738
|
const OVERLAPS = paths.cache('overlaps.json');
|
|
704
739
|
let remembered = null, fresh = 0;
|
|
705
740
|
function pairOverlap(pa, pb) {
|
|
706
|
-
|
|
741
|
+
const solidOf = (p) => p.collide ?? p.geometry; // (a beam by its envelope: lib/beams.mjs)
|
|
742
|
+
if (!pa.hash || !pb.hash) return overlap(solidOf(pa), solidOf(pb));
|
|
707
743
|
remembered ||= (() => { try { return JSON.parse(host.readText(OVERLAPS)); } catch { return {}; } })();
|
|
708
744
|
const at = (p) => `${p.hash}@${Array.from(p.m || []).map((x) => Math.round(x * 1e6) / 1e6).join(',')}`;
|
|
709
745
|
const [x, y] = [at(pa), at(pb)].sort(), k = crypto.createHash('sha1').update(`crossing+${solid ? 'manifold' : 'jscad'}|${x}|${y}`).digest('hex');
|
|
710
|
-
if (!(k in remembered)) { remembered[k] = overlap(pa
|
|
746
|
+
if (!(k in remembered)) { remembered[k] = overlap(solidOf(pa), solidOf(pb)); fresh++; }
|
|
711
747
|
return remembered[k];
|
|
712
748
|
}
|
|
713
749
|
function saveOverlaps() {
|
|
@@ -761,11 +797,13 @@ export function checkAssembly(s) {
|
|
|
761
797
|
// A fit names parts (keyboard, key-0-0.cap), or the faces of an item near one of its anchors (keyboard@pivot, within
|
|
762
798
|
// "within" mm, 10 by default): the pocket round a pivot, not the whole case
|
|
763
799
|
const marks = anchorsAt(s), within = (x) => (x.within != null ? x.num(x.within) : 10);
|
|
800
|
+
// A beam's address in a fit (x1.top@120): the faces near that point, as near an anchor
|
|
801
|
+
const addressMark = (n) => { const r = addressAt(s, n); return r && { id: n, item: r.id, at: r.at }; };
|
|
764
802
|
const near = (p, mark, r) => ({ ...p, polygons: p.polygons.filter((f) => distanceToFace(mark.at, f) <= r) });
|
|
765
803
|
const pickIn = (n, x) => {
|
|
766
804
|
if (Array.isArray(n)) return n.flatMap((m) => pickIn(m, x));
|
|
767
|
-
if (!n.includes('@'))
|
|
768
|
-
const mark = marks.find((m) => m.id === n);
|
|
805
|
+
if (!n.includes('@')) { const ps = s.parts.filter((p) => named(p, n)); if (ps.length) return ps; } // (else a beam's end or face: x1.a, x1.top)
|
|
806
|
+
const mark = marks.find((m) => m.id === n) ?? addressMark(n);
|
|
769
807
|
if (!mark) return [];
|
|
770
808
|
return s.parts.filter((p) => named(p, mark.item)).map((p) => near(p, mark, within(x))).filter((p) => p.polygons.length);
|
|
771
809
|
};
|
|
@@ -871,7 +909,7 @@ export function checkAssembly(s) {
|
|
|
871
909
|
// nowhere else: a ring gear resting on its case turns with the planets; a pawl resting on its post walks off it.
|
|
872
910
|
if (s.motion.joints.some((j) => j.type !== 'fixed')) {
|
|
873
911
|
const ids = s.motion.items.map((x) => x[0]), top = (n) => String(n).split(/[.@]/)[0];
|
|
874
|
-
const held = new Set([ids[0], ...s.motion.joints.map((j) => ids[j.child])]), links = s.fits.filter((x) => x.fastens).map((x) => [top(x.a), top(x.b)]);
|
|
912
|
+
const held = new Set([ids[0], ...s.motion.joints.filter((j) => !j.at).map((j) => ids[j.child])]), links = s.fits.filter((x) => x.fastens).map((x) => [top(x.a), top(x.b)]);
|
|
875
913
|
for (let grew = true; grew;) { grew = false; for (const [a, b] of links) { if (held.has(a) && !held.has(b)) { held.add(b); grew = true; } if (held.has(b) && !held.has(a)) { held.add(a); grew = true; } } }
|
|
876
914
|
const placed = new Set(s.objects.filter((o) => !o.unplaced && o.role !== 'reference').map((o) => top(o.id)));
|
|
877
915
|
const loose = ids.filter((id) => !held.has(id) && placed.has(id));
|
|
@@ -888,7 +926,13 @@ export function checkAssembly(s) {
|
|
|
888
926
|
}
|
|
889
927
|
}
|
|
890
928
|
if (s.a.fasten?.length && fastening) fastening.fastenChecks(s, f, { placeItems });
|
|
929
|
+
// A holes fit and a fit that fastens the same two items: one fasten says both, and knows the screw
|
|
930
|
+
if (fastening) for (const g of fastening.fastenFromFits(s)) {
|
|
931
|
+
f('info', `${g.label} and the fit that fastens ${g.pair[0]} to ${g.pair[1]} are one screwed joint: a fasten says both and knows the screw (its holes, length, thread engaged, the seat under its head and the key that turns it). In place of the two, add to "fasten": ${JSON.stringify(g.fasten)}${g.screw ? '' : ' (with the screw it takes: no thread was found in the fits or the holes)'}, or run cad add fasten ${s.project}/${s.name} --from-fits`,
|
|
932
|
+
null, { code: 'fasten.suggest', refs: { fits: [g.holes, g.fastens], items: g.pair, paste: g.fasten } });
|
|
933
|
+
}
|
|
891
934
|
boughtFindings(s, f);
|
|
935
|
+
beamFindings(s, f);
|
|
892
936
|
massFinding(s, f);
|
|
893
937
|
runningChecks(s, f, { axisOf, placeItems, jointValues, mul });
|
|
894
938
|
if (s.wires?.length) wireChecks(s, f, { placeItems, jointValues, mul });
|
package/lib/beams.mjs
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
// Beams in assemblies (@rulecad/frames).
|
|
2
|
+
//
|
|
3
|
+
// A beam item is a length of a profile: { "id": "x1", "beam": { "profile": "2020-misumi-hfs5", "length": 300 },
|
|
4
|
+
// "from": [0, 0, 0], "to": [300, 0, 0], "roll": 0 }, or placed with at and rotate as any item is. It is bought, so it is
|
|
5
|
+
// drawn faint (a reference), goes on cad list by profile and length, and is in the overlap check by its envelope.
|
|
6
|
+
// Its frame is the beam's own: end a at z = 0, end b at z = length, top +y, front -x. Placed by its ends, its z runs
|
|
7
|
+
// from to to, and at roll 0 its top faces up (+z), or +y when it stands upright (within 0.1° of z); roll turns it
|
|
8
|
+
// about its own axis, a toward b, right-handed.
|
|
9
|
+
// Its addresses are anchors (lib/assembly.mjs reads them through beamAnchor): x1.a, x1.b, x1.a.1, x1.top, x1.top@120,
|
|
10
|
+
// x1.top@-20, x1.top@50%, x1.top.2@120.
|
|
11
|
+
// Its operations ("ops": cut, mitre, tap, access, drill, counterbore, pocket, notch, deburr) are @rulecad/frames': each
|
|
12
|
+
// is cut into its preview, a mitre into its envelope too, and their findings (beam.op) are the beam's.
|
|
13
|
+
import * as frames from '@rulecad/frames';
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { beamModel, beam, beamAnchor, cutList, beamMarks, beamSheet } from '@rulecad/frames';
|
|
17
|
+
import { frame } from '@rulecad/model-link';
|
|
18
|
+
import { RULE_DIRS, paths } from './workspace.mjs';
|
|
19
|
+
import { named } from './parts.mjs';
|
|
20
|
+
import { referenceBuilt } from './bought.mjs';
|
|
21
|
+
import { framesContext as contextIn, givenFor } from './frames.mjs';
|
|
22
|
+
|
|
23
|
+
const KEYS = ['profile', 'length', 'printed', 'material', 'ops'];
|
|
24
|
+
const OP_NUMBERS = ['angle', 'depth', 'diameter', 'length', 'radius'];
|
|
25
|
+
const shown = (v) => (v === undefined ? 'nothing' : JSON.stringify(v));
|
|
26
|
+
const mm = (x) => String(+Number(x).toFixed(2));
|
|
27
|
+
const strip = (e) => String(e?.message ?? e).replace(/^(beamModel|beamAnchor|profileModel|beam): /, '');
|
|
28
|
+
/** This workspace's frames sets (lib/frames.mjs framesContext over its rules/) */
|
|
29
|
+
export const framesContext = () => contextIn(RULE_DIRS[0]);
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The beam an item names, its length worked out: { model, length }. A length may be an expression; left out, it is the
|
|
33
|
+
* distance from from to to. Refused by name: an unknown key, no profile, a printed beam (a later release), a length
|
|
34
|
+
* that disagrees with its ends, ends and at both given.
|
|
35
|
+
* @param {object} it the item @param {(x: any) => number} num the assembly's expressions @param {object} [context] framesContext()'s
|
|
36
|
+
*/
|
|
37
|
+
export function beamOf(it, num, context = framesContext()) {
|
|
38
|
+
const what = `item ${it.id}`, b = it.beam;
|
|
39
|
+
if (!b || typeof b !== 'object' || Array.isArray(b)) throw new Error(`${what}: beam is { "profile", "length", "material" } (got ${shown(b)})`);
|
|
40
|
+
for (const k of Object.keys(b)) if (!KEYS.includes(k)) throw new Error(`${what}: a beam has no "${k}": it takes ${KEYS.join(', ')}`);
|
|
41
|
+
if (typeof b.profile !== 'string' || !b.profile) throw new Error(`${what}: beam.profile names a profile, such as 2020-misumi-hfs5 (got ${shown(b.profile)})`);
|
|
42
|
+
if (b.printed != null && typeof b.printed !== 'boolean') throw new Error(`${what}: beam.printed is true or false (got ${shown(b.printed)})`);
|
|
43
|
+
if (b.printed) throw new Error(`${what}: a printed beam ("printed": true) is a later release${b.ops?.length ? ', and its ops become features of the print then' : ''}: leave printed out for a bought beam of ${b.profile}`);
|
|
44
|
+
if (b.ops != null && !Array.isArray(b.ops)) throw new Error(`${what}: beam.ops is a list of operations, [{ "op": "tap", "at": "a" }] (got ${shown(b.ops)})`);
|
|
45
|
+
// an operation's numbers may be expressions, as a length is
|
|
46
|
+
const ops = (b.ops ?? []).map((o) => (o && typeof o === 'object' && !Array.isArray(o) ? Object.fromEntries(Object.entries(o).map(([k, v]) => [k, OP_NUMBERS.includes(k) && v != null ? num(v) : k === 'size' && Array.isArray(v) ? v.map(num) : v])) : o));
|
|
47
|
+
if (b.material != null && typeof b.material !== 'string') throw new Error(`${what}: beam.material is a material set's name, such as al6063-t5 (got ${shown(b.material)})`);
|
|
48
|
+
const ends = it.from != null || it.to != null;
|
|
49
|
+
if (ends && (it.from == null || it.to == null)) throw new Error(`${what}: a beam placed by its ends gives both: from (end a) and to (end b)`);
|
|
50
|
+
if (ends && (it.at != null || it.rotate != null)) throw new Error(`${what}: a beam is placed by its ends (from, to, roll) or by at and rotate, not both`);
|
|
51
|
+
if (!ends && it.roll != null) throw new Error(`${what}: roll turns a beam placed by its ends: give from and to, or turn it with rotate`);
|
|
52
|
+
if (ends && it.repeat) throw new Error(`${what}: a beam placed by its ends is one beam: give each its own item, or place it with at and repeat`);
|
|
53
|
+
for (const k of ['from', 'to']) if (ends && !(Array.isArray(it[k]) && it[k].length === 3)) throw new Error(`${what}: ${k} is a point, [x, y, z] (got ${shown(it[k])})`);
|
|
54
|
+
const span = ends ? Math.hypot(...[0, 1, 2].map((i) => num(it.to[i]) - num(it.from[i]))) : null;
|
|
55
|
+
if (b.length == null && span == null) throw new Error(`${what}: give the beam a length, or place it by its ends (from and to) so the length is theirs`);
|
|
56
|
+
const length = b.length != null ? num(b.length) : span;
|
|
57
|
+
if (!(Number.isFinite(length) && length > 0)) throw new Error(`${what}: a beam's length is above 0 mm (got ${shown(b.length ?? length)}${b.length == null ? ': its ends are at one point' : ''})`);
|
|
58
|
+
if (span != null && Math.abs(span - length) > 1e-3) throw new Error(`${what}: its length is ${mm(length)} mm, and its ends are ${mm(span)} mm apart: leave the length out, or move an end`);
|
|
59
|
+
const given = givenFor(context, b.profile);
|
|
60
|
+
let model;
|
|
61
|
+
try {
|
|
62
|
+
model = beamModel(frames.profileModel(b.profile, {}, given), { length, ...(b.material ? { material: b.material } : {}), ...(ops.length ? { ops } : {}), given });
|
|
63
|
+
} catch (e) { throw new Error(`${what}: ${strip(e)}`); }
|
|
64
|
+
return { model, length };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Where a beam placed by its ends goes: its frame as 12 numbers by rows (z from end a to end b, top up, turned by roll),
|
|
69
|
+
* or null for a beam placed by at and rotate.
|
|
70
|
+
* @param {object} it @param {(x: any) => number} num @returns {number[] | null}
|
|
71
|
+
*/
|
|
72
|
+
export function beamPlace(it, num) {
|
|
73
|
+
if (it.from == null) return null;
|
|
74
|
+
const a = it.from.map(num), b = it.to.map(num), z = b.map((v, k) => v - a[k]), l = Math.hypot(...z), u = z.map((v) => v / l);
|
|
75
|
+
const up = Math.abs(u[2]) > Math.cos(0.1 * Math.PI / 180) ? [0, 1, 0] : [0, 0, 1], d = up[0] * u[0] + up[1] * u[1] + up[2] * u[2];
|
|
76
|
+
const yl = up.map((v, k) => v - d * u[k]), n = Math.hypot(...yl), y = yl.map((v) => v / n);
|
|
77
|
+
const x = [y[1] * u[2] - y[2] * u[1], y[2] * u[0] - y[0] * u[2], y[0] * u[1] - y[1] * u[0]]; // y × z
|
|
78
|
+
const r = (it.roll != null ? num(it.roll) : 0) * Math.PI / 180, c = Math.cos(r), s = Math.sin(r);
|
|
79
|
+
return frame(a, u, x.map((v, k) => c * v + s * y[k]));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* An item with "beam", built as a bought reference: its preview solid as the part, its envelope for the overlap check,
|
|
84
|
+
* its named anchors (ends, end bores, faces at mid-length) for joints and fits, and its figures as values (x1.length).
|
|
85
|
+
* @param {object} it @param {(x: any) => number} num @param {string} id
|
|
86
|
+
*/
|
|
87
|
+
export function beamBuilt(it, num, id, context = framesContext()) {
|
|
88
|
+
const { model: m, length } = beamOf(it, num, context);
|
|
89
|
+
const meta = { body: { label: `${m.profile.name} x ${mm(length)} mm` } };
|
|
90
|
+
const parts = named({ body: beam(m) }, meta), link = named({ body: beam(m, { display: 'link' }) }, meta)[0];
|
|
91
|
+
parts[0].collide = link.geometry; // (the overlap check measures the envelope: light, and a beam's slots hold nothing else)
|
|
92
|
+
const anchors = Object.fromEntries(Object.entries(m.anchors).map(([k, a]) => [k, { at: a.origin, axis: a.axis, ref: a.ref }]));
|
|
93
|
+
const values = { length, width: m.profile.width, height: m.profile.height, area: m.area, ...(m.mass != null ? { mass: m.mass } : {}) };
|
|
94
|
+
const entries = Object.entries(m.profile.figures).filter(([, f]) => typeof f?.value === 'number').map(([k, f]) => ({ name: `${m.profile.name}.${k}`, value: f.value, unit: f.unit, rule: f.rule, kind: f.kind, source: f.source, checked: f.checked, set: m.profile.name }));
|
|
95
|
+
const grams = m.weight.sheet ?? m.mass; // (weighed by the sheet where it gives a mass per metre: a light section's drawn outline can be 10 to 20% heavy)
|
|
96
|
+
return referenceBuilt({ id, key: 'beam', objName: `beam:${m.profile.name}`, name: m.profile.name, parts, anchors, entries, values,
|
|
97
|
+
extra: { beam: m, bought: { set: m.profile.name, variant: null, part: 'beam', mass: grams != null ? grams / 1000 : null, length } } });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* An anchor on a beam by its address (a, b, a.1, top, top@120, top@-20, top@50%, top.2@120), as a frame of 12 numbers in
|
|
102
|
+
* the beam's own frame. Past the beam's end, or a name it does not have: refused by name, with its length.
|
|
103
|
+
* @param {object} m the beam's model @param {string} address what follows the item's id @param {string} what who asks
|
|
104
|
+
*/
|
|
105
|
+
export function beamAddress(m, address, what) {
|
|
106
|
+
let a;
|
|
107
|
+
try { a = beamAnchor(m, address); } catch (e) { throw new Error(`${what}: ${strip(e)}`); }
|
|
108
|
+
return frame(a.origin, a.axis, a.ref);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The assembly's beams, nested ones too, as { id, beam } for @rulecad/frames' cut list. @param {object} s a built assembly */
|
|
112
|
+
export const beamsIn = (s) => s.objects.filter((o) => o.beam && !o.unplaced).map((o) => ({ id: o.id, beam: o.beam }));
|
|
113
|
+
|
|
114
|
+
/** Each beam's mark: beams that are the same share one (A, B, ...), as the cut list and the sheets name them. @returns {Map<string, string>} item to mark */
|
|
115
|
+
export function marksOf(objects) {
|
|
116
|
+
const list = objects.filter((o) => o.beam && !o.unplaced), out = new Map();
|
|
117
|
+
if (list.length) for (const m of beamMarks(list.map((o) => ({ id: o.id, beam: o.beam })))) for (const id of m.items) out.set(id, m.mark);
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The cut list of an assembly's beams (frames' cutList), or null where it has none. @param {object} s a built assembly */
|
|
122
|
+
export function cutListOf(s) { const b = beamsIn(s); return b.length ? cutList(b) : null; }
|
|
123
|
+
|
|
124
|
+
/** The cut list as the list and the build page keep it: no beam models, the numbers and words only. */
|
|
125
|
+
export const cutListData = (c) => c && { marks: c.marks.map(({ beam, ...m }) => m), stock: c.stock, totals: c.totals, rules: Object.fromEntries(Object.entries(c.rules).map(([k, r]) => [k, { value: r.value, unit: r.unit, kind: r.kind }])) };
|
|
126
|
+
|
|
127
|
+
/** The sheet files cad beams writes for an assembly, by mark: exports/<project>/<assembly>.beam-<mark>.svg */
|
|
128
|
+
export const sheetFile = (s, mark) => paths.exports(s.project, `${s.name}.beam-${mark}.svg`);
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* One cut-and-drill sheet per mark, written to exports/<project>/<assembly>.beam-<mark>.svg, old sheets of this
|
|
132
|
+
* assembly removed. @param {object} s a built assembly @returns {{ mark: string, file: string, items: string[], scale: number }[]}
|
|
133
|
+
*/
|
|
134
|
+
export function writeBeamSheets(s) {
|
|
135
|
+
const c = cutListOf(s), dir = paths.exports(s.project), base = `${s.name}.beam-`;
|
|
136
|
+
if (fs.existsSync(dir)) for (const f of fs.readdirSync(dir)) if (f.startsWith(base) && f.endsWith('.svg')) fs.rmSync(path.join(dir, f));
|
|
137
|
+
if (!c) return [];
|
|
138
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
139
|
+
return c.marks.map((m) => { const sh = beamSheet(m.beam, { mark: m.mark, items: m.items, grams: m.grams }), file = sheetFile(s, m.mark); fs.writeFileSync(file, sh.svg); return { mark: m.mark, file, items: m.items, scale: sh.scale }; });
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Each beam's own findings (its mass beside the sheet's, its length beside the stock's), named by item; and the cut list's (frame.cut). */
|
|
143
|
+
export function beamFindings(s, f) {
|
|
144
|
+
for (const o of s.objects) if (o.beam && !o.unplaced) for (const x of o.beam.findings) f(x.level, `${o.id}: ${x.text}`, null, { code: x.code, ...(x.values ? { values: x.values } : {}), refs: { item: o.id, profile: o.beam.profile.name, length: o.beam.length, ...(x.rule ? { rule: x.rule } : {}) } });
|
|
145
|
+
const c = cutListOf(s);
|
|
146
|
+
if (c) for (const x of c.findings) f(x.level, x.text, null, { code: x.code, ...(x.values ? { values: x.values } : {}), refs: x.refs });
|
|
147
|
+
}
|
package/lib/bought.mjs
CHANGED
|
@@ -101,5 +101,5 @@ export function boughtBuilt(spec, it, num, id) {
|
|
|
101
101
|
|
|
102
102
|
// One line in the check for each bought item, so the shopping list and the wiring can read it
|
|
103
103
|
export function boughtFindings(s, f) {
|
|
104
|
-
for (const o of s.objects) if (o.bought) f('info', `${o.id}: ${o.bought.set}${o.bought.variant ? ` (${o.bought.variant})` : ''}, a ${o.bought.part}`, null, { code: 'bought.item', refs: { item: o.id, set: o.bought.set, variant: o.bought.variant, part: o.bought.part } });
|
|
104
|
+
for (const o of s.objects) if (o.bought) f('info', `${o.id}: ${o.bought.set}${o.bought.variant ? ` (${o.bought.variant})` : ''}${o.bought.length != null ? ` x ${Number(o.bought.length.toFixed(2))} mm` : ''}, a ${o.bought.part}`, null, { code: 'bought.item', refs: { item: o.id, set: o.bought.set, variant: o.bought.variant, part: o.bought.part, ...(o.bought.length != null ? { length: o.bought.length } : {}) } });
|
|
105
105
|
}
|
package/lib/buildpage.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// What a machine's model link adds to the model, all read from the same assembly the checks read: the task (the pen, the
|
|
2
|
-
// plane, the margins' figures), a step file, the wires' routes, and the build page (shopping list
|
|
3
|
-
// assembly steps, machine settings).
|
|
2
|
+
// plane, the margins' figures), a step file, the wires' routes, and the build page (shopping list with the beams' cut
|
|
3
|
+
// list, each beam's cut-and-drill sheet, plates, wiring sheet, assembly steps, machine settings).
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import { sheetFrame } from '@rulecad/robots';
|
|
@@ -10,6 +10,7 @@ import { host } from './host.mjs';
|
|
|
10
10
|
import { accuracyOf, sample, chainOf } from './task.mjs';
|
|
11
11
|
import { machineOf } from './machine.mjs';
|
|
12
12
|
import { shoppingList } from './list.mjs';
|
|
13
|
+
import { cutListOf, sheetFile } from './beams.mjs';
|
|
13
14
|
import { wiresFor, wireRoutesOf } from './assembly.mjs';
|
|
14
15
|
import { orderOf, isBuilt } from './order.mjs';
|
|
15
16
|
import { platesOf } from './plates.mjs';
|
|
@@ -61,7 +62,9 @@ export async function buildData(s) {
|
|
|
61
62
|
const plates = await guard(() => platesOf(s).then(({ bed, gap, plates: p, findings }) => ({ bed, gap, plates: p, findings })));
|
|
62
63
|
const order = isBuilt(s) ? await guard(() => orderOf(s)) : null;
|
|
63
64
|
const machine = s.task ? await guard(() => machineOf(s)) : null;
|
|
64
|
-
|
|
65
|
+
// each mark's cut-and-drill sheet, by its file in the exports (cad beams writes them), and whether it is there yet
|
|
66
|
+
const beams = await guard(() => { const c = cutListOf(s); return c ? { sheets: c.marks.map((m) => ({ mark: m.mark, items: m.items, file: ['exports', s.project, path.basename(sheetFile(s, m.mark))].join('/'), written: fs.existsSync(sheetFile(s, m.mark)) })) } : null; });
|
|
67
|
+
return { build: { list, wires, plates, order, machine, beams } };
|
|
65
68
|
}
|
|
66
69
|
|
|
67
70
|
// The ledger, in the rules sheet's own rows: each prediction the bench can measure, the measurement once it's in
|
package/lib/design.mjs
CHANGED
|
@@ -34,6 +34,7 @@ import * as shapes from '@rulecad/shapes';
|
|
|
34
34
|
import * as flexures from '@rulecad/flexures';
|
|
35
35
|
import * as gears from '@rulecad/gears';
|
|
36
36
|
import * as motors from '@rulecad/motors';
|
|
37
|
+
import { designFrames, framesContext } from './frames.mjs';
|
|
37
38
|
import { resolve as resolveWith } from '@rulecad/variables';
|
|
38
39
|
import { engineId, packageVersion, materialise } from './versions.mjs';
|
|
39
40
|
import { satisfies } from '@rulecad/versions';
|
|
@@ -128,12 +129,12 @@ const CACHE = paths.cache('builds'), CACHE_VERSION = 3;
|
|
|
128
129
|
const source = (f) => fs.readFileSync(new URL(f, import.meta.url), 'utf8');
|
|
129
130
|
// What every build is made with: this code, the shape helpers and JSCAD's version (an upgrade rebuilds everything);
|
|
130
131
|
// boards also with the board engine (engineId: its code and tscircuit's version), loaded only for boards
|
|
131
|
-
const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))), flexuresDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/flexures'))), gearsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))), motorsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/motors'))), fixingsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/fixings')));
|
|
132
|
+
const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))), flexuresDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/flexures'))), gearsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))), motorsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/motors'))), framesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/frames'))), fixingsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/fixings')));
|
|
132
133
|
// (every module of a helper package but its tests: they change nothing a design builds)
|
|
133
134
|
const helperSources = (dir) => fs.readdirSync(dir).filter((f) => f.endsWith('.mjs') && f !== 'test.mjs').sort().map((f) => source(pathToFileURL(path.join(dir, f)).href)).join('');
|
|
134
135
|
const feaDir = path.dirname(createRequire(pathToFileURL(path.join(flexuresDir, 'package.json')).href).resolve('@rulecad/fea')); // (flexures' own, wherever npm put it)
|
|
135
136
|
// (as one digest, so each build's key hashes a line and not a megabyte of source)
|
|
136
|
-
const own = crypto.createHash('sha256').update(source(import.meta.url) + source('./fixings.mjs') + helperSources(shapesDir) + helperSources(flexuresDir) + helperSources(gearsDir) + helperSources(motorsDir) + helperSources(fixingsDir) + helperSources(feaDir) + packageVersion('@jscad/modeling')).digest('hex'); // every shapes module, not just its entry
|
|
137
|
+
const own = crypto.createHash('sha256').update(source(import.meta.url) + source('./fixings.mjs') + source('./frames.mjs') + helperSources(framesDir) + helperSources(shapesDir) + helperSources(flexuresDir) + helperSources(gearsDir) + helperSources(motorsDir) + helperSources(fixingsDir) + helperSources(feaDir) + packageVersion('@jscad/modeling')).digest('hex'); // every shapes module, not just its entry
|
|
137
138
|
// A lamina's slow stages (the physics, the flood's probe) are kept apart from the builds, keyed by the library's code
|
|
138
139
|
// and their own inputs, so a build that changes only what comes after them (a strap, a check, a rule's words) has them
|
|
139
140
|
// at once: .cache/stages/. A design in the sandbox can't write them, so the sandbox hands them back and the tool writes them
|
|
@@ -220,7 +221,9 @@ export async function build(d, set = {}, { mirror = false } = {}) {
|
|
|
220
221
|
// label, a note or the version change nothing it builds, so they aren't in the key
|
|
221
222
|
const ruleText = [...(object.uses || []).map((u) => JSON.stringify(sets[u] || loadRuleSet(u))), JSON.stringify(refs.extra)];
|
|
222
223
|
const reads = { values, parts: object.parts, engine: object.engine, mirror: object.mirror };
|
|
223
|
-
|
|
224
|
+
// (v.frames reads the workspace's own profile sets: a build is made from them too, lib/frames.mjs)
|
|
225
|
+
const framed = framesContext(RULE_DIRS[0]);
|
|
226
|
+
const key = crypto.createHash('sha256').update(JSON.stringify([CACHE_VERSION, own, framed.hash, object.engine === 'pcb' ? engineId() : booleans(object), host.readText(d.js), reads, ruleText, files, Object.values(problems).map((p) => p.hash), set, display])).digest('hex');
|
|
224
227
|
const hit = path.join(CACHE, `${key}.json`);
|
|
225
228
|
// (a build that called v.fixings is also made from the workspace's thread sets, its printer and material: it holds
|
|
226
229
|
// while those stand, and is known by them too, so what is kept by a build's hash, an overlap, follows a changed pilot)
|
|
@@ -238,10 +241,10 @@ export async function build(d, set = {}, { mirror = false } = {}) {
|
|
|
238
241
|
// A JSCAD design runs in a sandbox (sandbox.mjs: another process that can't write files, start programs or reach
|
|
239
242
|
// the network) unless the workspace trusts its designs; a board design runs here, with the board engine
|
|
240
243
|
const pcb = object.engine === 'pcb' ? await pcbEngine() : null;
|
|
241
|
-
let parts, board = null, read, mechanism = null, fixings = null;
|
|
244
|
+
let parts, board = null, read, mechanism = null, fixings = null, mounted = false;
|
|
242
245
|
const optional = Object.keys(object.mirror || {}); // inputs only the on-screen copy has: main may ask for them when they aren't there
|
|
243
246
|
const stages = stageStore();
|
|
244
|
-
if (!pcb && sandboxed() && host.name === 'node') ({ parts, read, mechanism, fixings } = await runSandboxed(d, values, object.parts || {}, booleans(object), optional, stages, fixed().context).catch((e) => { throw syntaxAt(e, d); }));
|
|
247
|
+
if (!pcb && sandboxed() && host.name === 'node') ({ parts, read, mechanism, fixings } = await runSandboxed(d, values, object.parts || {}, booleans(object), optional, stages, { frames: framed, fixings: fixed().context }).catch((e) => { throw syntaxAt(e, d); }));
|
|
245
248
|
else {
|
|
246
249
|
flexures.laminaCache(stages);
|
|
247
250
|
const mod = await host.loadModule(d.js).catch((e) => { // a fresh copy after each edit
|
|
@@ -252,7 +255,9 @@ export async function build(d, set = {}, { mirror = false } = {}) {
|
|
|
252
255
|
});
|
|
253
256
|
if (typeof mod.main !== 'function') throw new Error(`${path.relative(WS, d.js)} has no exported main(v)`);
|
|
254
257
|
const ops = await shapes.ops(booleans(object)), df = (await import('./fixings.mjs')).designFixings({ ...fixed().context, ops }); // (loaded when a design is run here: the sandbox's runner has its own)
|
|
255
|
-
|
|
258
|
+
// v.pcb.mount('M2', ...) reads the workspace's thread sets, as v.fixings does: such a build is known by them too
|
|
259
|
+
const engine = pcb ? { ...pcb, mount: (thread, x, y, o = {}) => { mounted = true; return pcb.mount(thread, x, y, { sets: fixed().context.sets, ...o }); } } : null;
|
|
260
|
+
const w = watch(values, { shapes, flexures, gears, motors, frames: designFrames(framed), fixings: df.fixings, ops, ...(engine ? { pcb: engine } : {}) }, optional);
|
|
256
261
|
read = w.read;
|
|
257
262
|
let made;
|
|
258
263
|
try { ({ shapes: made, mechanism } = unpack(await mod.main(w.v))); } catch (e) { throw Object.assign(located(e, d.js, 'design.run'), { line: lineOf(e, pathToFileURL(d.js).href) || undefined }); }
|
|
@@ -274,9 +279,9 @@ export async function build(d, set = {}, { mirror = false } = {}) {
|
|
|
274
279
|
for (const e of entries) if (read.has(e.name)) e.used = true;
|
|
275
280
|
try {
|
|
276
281
|
prune();
|
|
277
|
-
host.writeText(hit, JSON.stringify({ used: entries.filter((e) => e.used).map((e) => e.name), parts: parts.map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) })), ...(board || {}), ...(mechanism ? { mechanism } : {}), ...(fixings ? { fixed: fixed().hash, fixings } : {}) }));
|
|
282
|
+
host.writeText(hit, JSON.stringify({ used: entries.filter((e) => e.used).map((e) => e.name), parts: parts.map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) })), ...(board || {}), ...(mechanism ? { mechanism } : {}), ...(fixings || mounted ? { fixed: fixed().hash } : {}), ...(fixings ? { fixings } : {}) }));
|
|
278
283
|
} catch {} // a cache that can't be written is only slower
|
|
279
|
-
return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash: known(fixings ? fixed().hash : null), ...(fixings ? { fixings } : {}), ...(board || {}), ...(mechanism ? { mechanism } : {}) };
|
|
284
|
+
return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash: known(fixings || mounted ? fixed().hash : null), ...(fixings ? { fixings } : {}), ...(board || {}), ...(mechanism ? { mechanism } : {}) };
|
|
280
285
|
}
|
|
281
286
|
|
|
282
287
|
// A cache keeps its most recently used files, about `keep` of them (an old version's builds go first)
|
package/lib/edit.mjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// its schema, and an object's variables must still resolve. Used by cad set and cad add; a program can call them too.
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import path from 'node:path';
|
|
6
|
-
import { setAt, appendAt, getAt } from './jsonedit.mjs';
|
|
6
|
+
import { setAt, appendAt, getAt, removeAt } from './jsonedit.mjs';
|
|
7
7
|
import { validate, schema } from './schema.mjs';
|
|
8
8
|
import { CadError } from './errors.mjs';
|
|
9
9
|
import { paths } from './workspace.mjs';
|
|
@@ -97,3 +97,28 @@ export function addToAssembly(ref, what, entry) {
|
|
|
97
97
|
write(file, text, 'assembly');
|
|
98
98
|
return { file };
|
|
99
99
|
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Put a fasten in place of each holes fit and the fit that fastens the same two items (as lib/fasten.mjs's fastenFromFits
|
|
103
|
+
* finds them): the holes fit goes, the fit that fastens goes too, or keeps its gap range (min, max) with "fastens",
|
|
104
|
+
* "fastener" and "count" taken off, and the fasten is added. A screw given replaces the one found.
|
|
105
|
+
* @param {string} ref project/assembly @param {{ fasten: object, holes: number, fastens: number }[]} found @param {{ screw?: string }} [options]
|
|
106
|
+
* @returns {{ file: string, added: object[] }}
|
|
107
|
+
*/
|
|
108
|
+
export function fastenFromFitsEdit(ref, found, { screw } = {}) {
|
|
109
|
+
const file = assemblyFile(ref);
|
|
110
|
+
if (!found.length) throw new CadError('edit.nothing', `${ref} has no holes fit with a fit that fastens the same two items (and no fasten for them yet): nothing to put a fasten in place of`, { file });
|
|
111
|
+
let text = fs.readFileSync(file, 'utf8');
|
|
112
|
+
const fits = getAt(text, ['fits']), drop = new Set(), trim = new Set();
|
|
113
|
+
for (const g of found) { drop.add(g.holes); (fits[g.fastens].min != null || fits[g.fastens].max != null ? trim : drop).add(g.fastens); }
|
|
114
|
+
// last first, so the places of the others hold
|
|
115
|
+
for (const i of [...new Set([...drop, ...trim])].sort((a, b) => b - a)) {
|
|
116
|
+
if (drop.has(i)) { text = removeAt(text, ['fits', i]); continue; }
|
|
117
|
+
for (const k of ['count', 'fastener', 'fastens']) if (getAt(text, ['fits', i, k]) !== undefined) text = removeAt(text, ['fits', i, k]);
|
|
118
|
+
}
|
|
119
|
+
if (getAt(text, ['fasten']) === undefined) text = setAt(text, ['fasten'], []);
|
|
120
|
+
const added = found.map((g) => ({ ...g.fasten, ...(screw ? { screw } : {}) }));
|
|
121
|
+
for (const x of added) text = appendAt(text, ['fasten'], x);
|
|
122
|
+
write(file, text, 'assembly');
|
|
123
|
+
return { file, added };
|
|
124
|
+
}
|