@rulecad/cad 0.3.4 → 0.4.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/AGENTS.md CHANGED
@@ -56,6 +56,9 @@ variable says which rule it comes from. Follow these steps; they're what makes a
56
56
  with ranges from rules. An overlap or gap outside its range is a finding: report it with the numbers, and never
57
57
  widen a range to make it pass without saying why.
58
58
  - Build bigger things from checked assemblies used as items, rather than placing their objects again.
59
+ - Things that move are one assembly with joints and poses, not a copy per position: give the objects anchors, join
60
+ them with joints, name the positions in `poses`, and run `cad check --sweep` to find where parts collide on the way.
61
+ See "Joints and poses" in the cad README.
59
62
  - A part is named in fits as `<item>.<part>`; an object that returns one unnamed shape has one part, `body`.
60
63
  - A gap fit can't tell whether holes line up. Where a board screws into a part, add a holes fit
61
64
  (`{ "holes": "pcb.board", "into": "case.body", "depth": "m2.insert_length" }`).
package/README.md CHANGED
@@ -254,6 +254,62 @@ other items' variables, so a keycap can sit exactly where its slot meets the swi
254
254
  - `check`, `preview` (`--explode` lifts each kind of object above the last: plate, switches, keycaps), `show`, `link` and, for plates, `export` all take
255
255
  `<project>/<assembly>`.
256
256
 
257
+ ### Joints and poses
258
+
259
+ Things that move (a lid, a hinged screen, a drawer, a ball head) are one assembly with joints, not one assembly per
260
+ position. An object names its **anchors** in its .json, as expressions over its own variables: a point, with an axis.
261
+
262
+ ```json
263
+ "anchors": { "pivot": { "at": ["width / 2", 0, "height"], "axis": [1, 0, 0] } }
264
+ ```
265
+
266
+ A **joint** ties an anchor on its child item to one on its parent item. At value 0 the two anchors lie together, and
267
+ the joint's value moves the child from there. A joint's child has no `at` or `rotate`: the joint places it.
268
+
269
+ ```json
270
+ "joints": [
271
+ { "id": "lid", "type": "revolute", "parent": "case.pivot", "child": "lid.pivot", "min": -180, "max": 0, "label": "Lid" },
272
+ { "id": "lid_r", "type": "revolute", "parent": "case.pivot_r", "child": "stay.pivot", "follow": "lid" }
273
+ ],
274
+ "poses": { "shut": { "lid": 0 }, "open": { "lid": -110 } }
275
+ ```
276
+
277
+ | Type | Values | For |
278
+ |---|---|---|
279
+ | `fixed` | none | a part bolted on in a set place |
280
+ | `revolute` | angle | hinges, pivots |
281
+ | `prismatic` | distance | straight rails, drawers |
282
+ | `cylindrical` | `[angle, distance]` | a pin that turns and slides in a slot |
283
+ | `ball` | `[x, y, z]` angles | ball joints; `"cone": 30` limits how far the child's axis may tip |
284
+ | `path` | distance | curved rails: `"path": [[x, y, z], …]`, a polyline in the parent anchor's frame, the child's axis along it |
285
+
286
+ Angles are in degrees about the anchor's z axis (its `axis`); distances are in mm along it. A `ball` turns about x,
287
+ then y, then z, as `rotate` does.
288
+
289
+ - **Anchors:** `<item>.<anchor>`, or `<item>.<component item>.<anchor>` inside a component. An anchor can also be
290
+ written in place, in the assembly's names: `{ "item": "case", "at": ["case.width", 0, 0], "axis": [0, 1, 0] }`.
291
+ Without an `item` it is in the world. `ref` sets which way the anchor's x axis points (what angle 0 means), or
292
+ `rotate` turns the anchor as `rotate` turns an item.
293
+ - **Limits:** `min`, `max` and `value` (the default) are numbers or expressions, one per value (`[…]` for two or
294
+ three). An angle with no limits goes from -180 to 180. A distance needs both limits, except on a path, which runs
295
+ from 0 to its length.
296
+ - **Followers:** `"follow": "lid"` gives a joint another joint's values, times `ratio` (default 1), plus `offset`. Use
297
+ it for the second hinge of a pair, or for gears.
298
+ - **Loops:** each item has one joint to its parent. Where parts join in a ring (two links between the same two
299
+ parts), let joints place every part, then name the meeting that closes the ring in `loops`. The check measures it
300
+ in every pose: `"loops": [{ "a": "link_l.top", "b": "mount_l.axis", "label": "Left pivot lines up" }]`. Its anchors
301
+ must meet within 0.01 mm (or `tolerance`), with their axes lined up.
302
+ - **Poses:** `"poses"` names sets of values. `"pose"` names the one that previews, links and the display show (by
303
+ default, the first). `cad check` checks every pose. What is the same in every pose is reported once; the rest is
304
+ reported under the pose's name. `--pose open` checks, previews, shows or links one pose. A fit that only makes
305
+ sense in some poses names them: `"poses": ["folded"]`.
306
+ - **Sweeps:** `cad check <project>/<assembly> --sweep` moves each joint that doesn't follow another through its
307
+ range (`--steps 24`, from the pose, the other joints held still). It names where parts collide or a loop comes
308
+ apart: "sweep lid, -180 to 0° in 24 steps: -180 to -165°: lid.body hits hinge.pin". `--sweep lid` sweeps one joint.
309
+ - **Links:** an assembly's link carries its joints. The page shows a slider for each joint, a button for each pose,
310
+ and a quick look for parts pushed into each other when you let a slider go. The quick look can miss parts that cross
311
+ without a corner going in, so `--sweep` is the real check.
312
+
257
313
  ## Boards
258
314
 
259
315
  A circuit board is an object whose .json says `"engine": "pcb"`. Its `main(v)` returns a
package/bin/cad.mjs CHANGED
@@ -12,7 +12,7 @@ import { git, tags, bump, bigger, newer, compare, snapshot, materialise, files,
12
12
  import { check } from '@rulecad/printcheck';
13
13
  import { preview } from '../lib/preview.mjs';
14
14
  import { measure, match } from '../lib/meshcmd.mjs';
15
- import { isAssembly, buildAssembly, checkAssembly, shapes } from '../lib/assembly.mjs';
15
+ import { isAssembly, buildAssembly, checkAssembly, shapes, sweep } from '../lib/assembly.mjs';
16
16
  import { fromParts, fromShapes, encode, check as checkLink, expand } from '@rulecad/model-link';
17
17
  import { threemf, slotOf } from '../lib/threemf.mjs';
18
18
 
@@ -53,6 +53,9 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
53
53
  [--md: one labelled Markdown link, for chat (the page downloads any parts): short unless --long]
54
54
  [--short: the model's data in a secret GitHub Gist, so links are ~80 characters]
55
55
  [--no-rules: leave out the Rules panel's list of values and their sources]
56
+ Assemblies with joints: check checks every pose; --pose <name> picks one (check, preview, show, link)
57
+ [--sweep [joint]: move each joint (or one) through its range, looking for collisions]
58
+ [--steps 24: how many steps a sweep takes]
56
59
 
57
60
  cad status [project] each object's version, and whether it has changes since its last release
58
61
  cad release <project>/<object> -m "what changed" [--bump major|minor|patch] [--dry-run] [--push]
@@ -260,20 +263,28 @@ async function board(cmd, d, b, { title, version, tag }) {
260
263
 
261
264
  // ---------- assemblies ----------
262
265
  async function assembly(cmd, ref) {
263
- const s = await buildAssembly(ref), a = s.a, title = a.title || s.name;
266
+ const pose = typeof opt('pose') === 'string' ? opt('pose') : undefined;
267
+ const s = await buildAssembly(ref, [], {}, { pose }), a = s.a, title = `${a.title || s.name}${pose ? ` (${pose})` : ''}`;
264
268
  const versions = [...new Map(s.objects.map((o) => [o.objName, `${o.objName} ${o.version}`])).values()].join(', ');
265
269
  const rules = (ns) => Object.fromEntries(Object.keys(loadRuleSet(ns).rules).map((k) => [k, s.num(`${ns}.${k}`)]));
266
270
  const printed = s.parts.filter((p) => p.role !== 'reference');
267
271
 
268
272
  if (cmd === 'check') {
269
273
  console.log(`${title} (${a.kind || 'fit'}: ${versions})`);
270
- const findings = checkAssembly(s);
274
+ // Each pose (or the one asked for): what's the same in every pose is said once, the rest under the pose's name
275
+ const poses = pose ? [pose] : Object.keys(s.motion.poses);
276
+ let findings = checkAssembly(s);
277
+ if (poses.length > 1) {
278
+ const each = poses.map((p) => [p, checkAssembly(s.at(p))]), same = (x) => each.every(([, list]) => list.some((y) => y.text === x.text && y.level === x.level));
279
+ findings = [{ level: 'pass', text: `${poses.length} poses checked: ${poses.join(', ')}` }, ...each[0][1].filter(same), ...each.flatMap(([p, list]) => list.filter((x) => !same(x)).map((x) => ({ ...x, text: `${p}: ${x.text}`, ...(x.card ? { card: `${p}: ${x.card}` } : {}) })))];
280
+ }
281
+ if (opt('sweep')) findings.push(...sweep(s, { joint: typeof opt('sweep') === 'string' ? opt('sweep') : undefined, steps: Number(opt('steps')) || 24 }));
271
282
  if (a.kind === 'plate') findings.push(...check(printed.flatMap((p) => p.triangles), rules(printerOf(s.project)), { parts: printed }));
272
283
  process.exitCode = report(findings) ? 1 : 0;
273
284
  return;
274
285
  }
275
286
  if (cmd === 'preview') {
276
- const out = paths.preview(s.project, `${s.name}${opt('explode') ? '-exploded' : ''}.png`);
287
+ const out = paths.preview(s.project, `${s.name}${pose ? `-${pose}` : ''}${opt('explode') ? '-exploded' : ''}.png`);
277
288
  const size = (await import('@rulecad/printcheck')).bounds(s.triangles).size.map((n) => fmt(n)).join(' × ');
278
289
  const faint = [...new Set(s.parts.filter((p) => p.role !== 'part').map((p) => `${p.object || p.item}${p.role === 'support' ? ' supports' : ''}`))]; // each kind once
279
290
  await preview(s.parts, { title, meta: `${size} mm · ${versions}${faint.length ? ` · faint: ${faint.join(', ')}` : ''}`, out, explode: !!opt('explode') });
@@ -311,6 +322,7 @@ async function assembly(cmd, ref) {
311
322
  return placed.place.map(([i, ...m], n) => { const p = placed.shapes[i].part; return { shape: i, role: p.role, label: p.object || p.label, slot: slotOf(fil, p.filament), triangles: tri(placed.shapes[i].triangles), matrix: m, name: s.parts[n].name }; });
312
323
  })() : []),
313
324
  };
325
+ Object.assign(model, motionLink(s));
314
326
  const url = await linkTo(model);
315
327
  return { view: url, stl: `${url}&get=stl`, '3mf': `${url}&get=3mf`, src: model.src, size: url.length, title, version: '' };
316
328
  };
@@ -318,7 +330,7 @@ async function assembly(cmd, ref) {
318
330
  if (cmd === 'show') {
319
331
  // Each shape once, placed for every copy: nine keys cost one keycap in the mirror's link. Built with each object's
320
332
  // mirror settings (fewer segments), so the display gets a lighter mesh; checks and links use the real one
321
- const m = await buildAssembly(ref, [], {}, { mirror: true });
333
+ const m = await buildAssembly(ref, [], {}, { mirror: true, pose });
322
334
  const placed = shapes(m.parts.filter((p) => p.role !== 'support' && p.mirror !== false));
323
335
  // The card: what the checks found, one short line each
324
336
  const items = checkAssembly(s).filter((x) => x.card).slice(0, 6).map((x) => x.card);
@@ -329,6 +341,26 @@ async function assembly(cmd, ref) {
329
341
  throw new Error(`cad ${cmd} doesn't work on an assembly (check, preview, export, show, link do)`);
330
342
  }
331
343
 
344
+ // An assembly's joints, for the page's sliders: each part moves with its item (motion in @rulecad/model-link)
345
+ function motionLink(s) {
346
+ const mo = s.motion;
347
+ if (!mo.joints.length) return {};
348
+ const r = (x) => Number(x.toFixed(6)), names = mo.items.map((x) => x[0]);
349
+ const named = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`), allow = [];
350
+ const loose = s.fits.filter((x) => x.min != null && x.num(x.min) < 0);
351
+ s.parts.forEach((pa, i) => s.parts.forEach((pb, j) => {
352
+ if (j > i && pa.item !== pb.item && loose.some((x) => (named(pa, x.a) && named(pb, x.b)) || (named(pa, x.b) && named(pb, x.a)))) allow.push([i, j]);
353
+ }));
354
+ return { motion: {
355
+ items: mo.items.map(([n, ...m]) => [n, ...m.map(r)]),
356
+ joints: mo.joints.map(({ id, type, parent, child, a, b, dofs, label, follow, path, cone }) => ({ id, type, parent, child, a: a.map(r), b: b.map(r), dofs: dofs.map((d) => d.map(r)),
357
+ ...(label ? { label } : {}), ...(follow ? { follow } : {}), ...(path ? { path: path.map((p) => p.map(r)) } : {}), ...(cone != null ? { cone } : {}) })),
358
+ poses: mo.poses, ...(s.pose ? { pose: s.pose } : {}),
359
+ part: s.parts.map((p) => names.indexOf(p.item)),
360
+ ...(allow.length ? { allow } : {}),
361
+ } };
362
+ }
363
+
332
364
  // ---------- links ----------
333
365
  // The rules sheet a link carries, for the page's Rules panel: a row for each of an object's own values, then each rule
334
366
  // they use, as [group, name, value, unit, rule, expr, kind, source, checked] (group: the object, or the rule's set).
package/lib/assembly.mjs CHANGED
@@ -27,6 +27,7 @@ import { satisfies } from '@rulecad/versions';
27
27
  import { bounds } from '@rulecad/printcheck';
28
28
  import { closest, inside } from '@rulecad/fit';
29
29
  import { keys as keyCentres, readLayout, hasLayout } from './layout.mjs';
30
+ import { DOFS, frame, turn, mul, pathLength, jointValues, placeItems, jointMatrix } from '@rulecad/model-link';
30
31
 
31
32
  export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
32
33
  export const isAssembly = (ref) => String(ref).includes('/') && fs.existsSync(assemblyPath(ref.split('@')[0]));
@@ -90,7 +91,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
90
91
  const sub = it.assembly ? extra : {}; // a component's values go to its items: { cap: { units: 1.5 } }
91
92
  const key = JSON.stringify([it.object, it.variant, it.assembly, set, sub]);
92
93
  if (!built.has(key)) {
93
- if (it.assembly) built.set(key, { key, sub: await buildAssembly(`${project}/${it.assembly}`, [...stack, ref], sub, opts) });
94
+ if (it.assembly) built.set(key, { key, sub: await buildAssembly(`${project}/${it.assembly}`, [...stack, ref], sub, { ...opts, pose: undefined }) }); // a pose names the outer assembly's joints
94
95
  else {
95
96
  const [ref, named] = String(it.object).split(':'), [objName, pin] = ref.split('@'), variant = named || it.variant;
96
97
  const d = locate(`${project}/${objName}`), at = { ...(pin ? materialise(d, pin) : d), ...(variant ? { variant } : {}) };
@@ -143,46 +144,61 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
143
144
  placing.push([it, copies]);
144
145
  }
145
146
  // Then place them: every item is built by now, so a position can refer to any item, before or after it (a board
146
- // placed under the case's top, the case built with the board's Pico position)
147
+ // placed under the case's top, the case built with the board's Pico position). Each copy is an item of the motion:
148
+ // placed by at and rotate, or by the joint whose child it is.
149
+ const placed = []; // [it, copy], each a motion item, in order
147
150
  for (const [it, copies] of placing) {
148
151
  if (it.place === false) { // built only for its values ("place": false): a board a print plate's case is sized from
149
152
  for (const c of copies) if (!c.src.sub) objects.push({ id: c.id, objName: c.src.objName, version: c.src.version, built: c.src.b, role: c.src.role, unplaced: true });
150
153
  continue;
151
154
  }
152
- for (const c of copies) {
153
- const src = c.src, id = c.id, key = src.key;
154
- const base = (it.at || [0, 0, 0]).map(num), rot = (it.rotate || [0, 0, 0]).map((r) => num(r) * deg);
155
- // A repeated item turns as a whole about its at: each copy's offset turns with it (keys on a tilted plate)
155
+ for (const c of copies) { placed.push([it, c]); ids.push(c.id); }
156
+ }
157
+ const motion = motionOf(a, placed, num, ref);
158
+ for (const [it, c] of placed) {
159
+ const src = c.src, id = c.id;
160
+ if (src.sub) {
161
+ const sub = src.sub;
162
+ for (const o of sub.objects) objects.push({ ...o, id: `${id}.${o.id}` });
163
+ for (const x of sub.fits) fits.push({ ...x, a: `${id}.${x.a}`, b: `${id}.${x.b}`, label: x.label && `${x.label} (${id})` });
164
+ requires.push(...sub.requires);
165
+ for (const n of sub.seen) seen.add(n);
166
+ items.push({ ...it, id, sub, role: 'part' });
167
+ } else {
168
+ objects.push({ id, objName: src.objName, version: src.version, built: src.b, role: src.role });
169
+ items.push({ ...it, id, objName: src.objName, built: src.b, version: src.version, role: src.role });
170
+ }
171
+ }
172
+ // Every part, with its item where the joints put it at these values (jointValues)
173
+ const partsAt = (worlds) => {
174
+ const out = [];
175
+ placed.forEach(([, c], k) => {
176
+ const src = c.src, id = c.id, key = src.key, m = toMat4(worlds[k]);
177
+ items[k].m = m;
156
178
  // Faces are moved as they are, not re-triangulated in place: triangulating again after a move rounds differently
157
- const m = translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create()))).transforms;
158
179
  const move = (polys) => polys.map((poly) => poly.map((v) => jscad.maths.vec3.transform([0, 0, 0], v, m)));
159
- ids.push(id);
160
180
  if (src.sub) {
161
- const sub = src.sub;
162
- for (const p of sub.parts) {
181
+ for (const p of src.sub.parts) {
163
182
  if (p.role === 'support' && a.kind !== 'plate') continue;
164
- parts.push({ ...p, name: `${id}.${p.name}`, item: id, leaf: `${id}.${p.leaf}`, label: `${id} ${p.label}`,
183
+ out.push({ ...p, name: `${id}.${p.name}`, item: id, leaf: `${id}.${p.leaf}`, label: `${id} ${p.label}`,
165
184
  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) });
166
185
  }
167
- for (const o of sub.objects) objects.push({ ...o, id: `${id}.${o.id}` });
168
- for (const x of sub.fits) fits.push({ ...x, a: `${id}.${x.a}`, b: `${id}.${x.b}`, label: x.label && `${x.label} (${id})` });
169
- requires.push(...sub.requires);
170
- for (const n of sub.seen) seen.add(n);
171
- items.push({ ...it, id, sub, role: 'part' });
172
186
  } else {
173
- const { b } = src;
174
- for (const p of b.parts) {
187
+ for (const p of src.b.parts) {
175
188
  if (p.role === 'support' && a.kind !== 'plate') continue; // supports are snipped off before parts go together
176
- parts.push({ name: `${id}.${p.name}`, item: id, leaf: id, object: src.objName, role: src.role === 'reference' ? 'reference' : p.role, label: `${id}: ${p.label}`,
189
+ out.push({ name: `${id}.${p.name}`, item: id, leaf: id, object: src.objName, role: src.role === 'reference' ? 'reference' : p.role, label: `${id}: ${p.label}`,
177
190
  ...(p.filament ? { filament: p.filament } : {}), ...(p.mirror === false ? { mirror: false } : {}), part: p.name,
178
191
  geometry: transform(m, p.geometry), polygons: move(p.polygons), triangles: move(p.triangles),
179
- shape: `${key}:${p.name}`, hash: `${b.hash}:${p.name}`, local: p.polygons, localTriangles: p.triangles, m });
192
+ shape: `${key}:${p.name}`, hash: `${src.b.hash}:${p.name}`, local: p.polygons, localTriangles: p.triangles, m });
180
193
  }
181
- objects.push({ id, objName: src.objName, version: src.version, built: b, role: src.role });
182
- items.push({ ...it, id, objName: src.objName, built: b, version: src.version, role: src.role });
183
194
  }
184
- }
185
- }
195
+ });
196
+ return out;
197
+ };
198
+ 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'})`);
199
+ const pose = opts.pose ?? motion.pose;
200
+ const jv = jointValues(motion, pose);
201
+ parts.push(...partsAt(placeItems(motion, jv)));
186
202
  // A fit with * applies to every copy: "key-*.switch.bottom" becomes one fit for key-0-0, key-0-1, …
187
203
  // With * on both sides, each copy is checked against all the others: { "a": "key-*.cap", "b": "key-*.cap" }
188
204
  for (let x of a.fits || []) {
@@ -199,8 +215,115 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
199
215
  }
200
216
  for (const id of copies) { const swap = (n) => (n === star ? at(id, n) : n); fits.push({ ...x, a: swap(x.a), b: swap(x.b), num }); }
201
217
  }
202
- return { a, project, name, items, parts, objects, fits, requires, values, num, seen,
218
+ // at(pose): the same assembly in another pose (a name, or { joint: values }), nothing built again
219
+ const at = (p) => {
220
+ const v = jointValues(motion, p), moved = partsAt(placeItems(motion, v));
221
+ return { ...s, parts: moved, pose: typeof p === 'string' ? p : null, jointValues: v, polygons: moved.flatMap((x) => x.polygons), triangles: moved.flatMap((x) => x.triangles) };
222
+ };
223
+ const s = { a, project, name, items, parts, objects, fits, requires, values, num, seen, motion, pose: typeof pose === 'string' ? pose : null, jointValues: jv, at,
203
224
  polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles) };
225
+ return s;
226
+ }
227
+
228
+ // ---------- joints ----------
229
+ // "joints" move items against each other: a joint ties an anchor on its child item to one on its parent, and its
230
+ // values (an angle, a distance) move the child from there. A joint's child has no at or rotate: the joint places it.
231
+ // "joints": [{ "id": "hinge", "type": "revolute", "parent": "case.pivot", "child": "lid.pivot", "min": 0, "max": 180,
232
+ // "value": 90, "label": "Lid" }]
233
+ // Anchors are named in the object's .json ("anchors": { "pivot": { "at": ["width / 2", 0, "h"], "axis": [1, 0, 0] } },
234
+ // expressions over its own variables) and found as <item>.<anchor>, or <item>.<component item>.<anchor> into a
235
+ // component. Or written in place, in the assembly's names: { "item": "case", "at": […], "axis": […] } (no item: the
236
+ // world). An anchor is a point with axes: z along axis, x towards ref (optional), or turned by rotate as items are.
237
+ // At value 0 the two anchors lie together. Types, and what they take (angles in degrees, distances in mm, on z):
238
+ // fixed; revolute (angle); prismatic (distance: a straight rail); cylindrical ([angle, distance]: a pin in a slot);
239
+ // ball ([x, y, z] turns; "cone": how far z may tip); path (distance along "path": [[x, y, z], …], a polyline in the
240
+ // parent anchor's frame: a curved rail, the child's z along it).
241
+ // min, max and value are numbers or expressions, one per value ([…] for two or three). "follow": "hinge" gives a joint
242
+ // another's values (times "ratio", plus "offset"): the second hinge of a pair, gears. Items joined in a ring (two links
243
+ // between the same two parts) can't all be joints: join the ring's last pair with "loops" instead, which the check
244
+ // measures in every pose: [{ "a": "link_l.top", "b": "mount_l.axis", "label": "Left pivot lines up" }].
245
+ // "poses": { "open": { "hinge": 90 } } names sets of values, "pose" the one shown (default: the first); check checks
246
+ // every pose, and --sweep moves each joint through its range, looking for parts that collide.
247
+ const rows = (m) => [m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6], m[10], m[14]]; // JSCAD's mat4 is column-major
248
+ const toMat4 = (r) => [r[0], r[4], r[8], 0, r[1], r[5], r[9], 0, r[2], r[6], r[10], 0, r[3], r[7], r[11], 1];
249
+ export const LIMITS = { angle: [-180, 180] };
250
+ function motionOf(a, placed, num, ref) {
251
+ const { translate, rotate } = jscad.transforms, deg = Math.PI / 180;
252
+ const index = new Map(placed.map(([, c], k) => [c.id, k]));
253
+ const where = (n, what) => { if (!index.has(n)) throw new Error(`${what}: no item "${n}" (items: ${[...index.keys()].join(', ')})`); return index.get(n); };
254
+ const evalIn = (values, label) => (x) => evaluate(x, (n) => {
255
+ let v = values;
256
+ for (const k of n.split('.')) v = v?.[k];
257
+ if (typeof v !== 'number') throw new Error(`${label}: "${n}" isn't one of its numbers`);
258
+ return v;
259
+ });
260
+ const frameOf = (spec, ev) => {
261
+ const at = (spec.at || [0, 0, 0]).map(ev);
262
+ if (spec.rotate) { const m = turn(spec.rotate.map(ev)); m[3] = at[0]; m[7] = at[1]; m[11] = at[2]; return m; }
263
+ return frame(at, (spec.axis || [0, 0, 1]).map(ev), spec.ref && spec.ref.map(ev));
264
+ };
265
+ // An anchor: { item (index, -1 the world), frame (12 numbers, in the item's own frame) }
266
+ const anchor = (spec, what) => {
267
+ if (spec && typeof spec === 'object') return { item: spec.item ? where(spec.item, what) : -1, frame: frameOf(spec, num) };
268
+ const bits = String(spec).split('.'), name = bits.pop(), [id, ...inside] = bits;
269
+ if (!id || !name) throw new Error(`${what}: name an anchor as <item>.<anchor> (got "${spec}")`);
270
+ const k = where(id, what);
271
+ let src = placed[k][1].src, pre = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
272
+ for (const n of inside) { // into a component: its item's place there
273
+ const sub = src.sub?.items.find((x) => x.id === n);
274
+ if (!sub) throw new Error(`${what}: ${id} has no item "${n}"`);
275
+ pre = mul(pre, rows(sub.m));
276
+ src = sub.sub ? { sub: sub.sub } : { b: sub.built, objName: sub.objName };
277
+ }
278
+ const anchors = src.b?.object.anchors || {};
279
+ if (!anchors[name]) throw new Error(`${what}: ${src.objName || id} has no anchor "${name}" (anchors: ${Object.keys(anchors).join(', ') || 'none'})`);
280
+ return { item: k, frame: mul(pre, frameOf(anchors[name], evalIn(src.b.values, `${src.objName} anchor ${name}`))) };
281
+ };
282
+ const joints = [], children = new Set();
283
+ for (const j of a.joints || []) {
284
+ const what = `joint ${j.id}`;
285
+ if (!/^[a-z][\w-]*$/.test(j.id || '')) throw new Error(`each joint needs an id (letters, digits, - or _): got ${JSON.stringify(j.id)}`);
286
+ if (!Object.hasOwn(DOFS, j.type)) throw new Error(`${what}: type is one of ${Object.keys(DOFS).join(', ')} (got ${JSON.stringify(j.type)})`);
287
+ const p = j.parent == null ? { item: -1, frame: frame([0, 0, 0]) } : anchor(j.parent, what), c = anchor(j.child, what);
288
+ if (c.item < 0) throw new Error(`${what}: its child must be an item`);
289
+ if (children.has(c.item)) throw new Error(`${what}: ${placed[c.item][1].id} is already placed by another joint (two joints to one item make a ring: use loops)`);
290
+ const [it] = placed[c.item];
291
+ 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 repeat`);
292
+ children.add(c.item);
293
+ const path = j.type === 'path' ? (j.path || []).map((pt) => pt.map(num)) : undefined;
294
+ if (path && path.length < 2) throw new Error(`${what}: a path joint needs "path": two points or more`);
295
+ const kinds = DOFS[j.type], list = (x) => (x == null ? [] : [].concat(x));
296
+ const lo = list(j.min), hi = list(j.max), val = list(j.value);
297
+ const dofs = kinds.map((kind, i) => {
298
+ const range = j.type === 'path' ? [0, pathLength(path)] : kind === 'angle' ? LIMITS.angle : null;
299
+ const mn = lo[i] != null ? num(lo[i]) : range?.[0], mx = hi[i] != null ? num(hi[i]) : range?.[1];
300
+ if (mn == null || mx == null) throw new Error(`${what}: give its ${kind} a min and max`);
301
+ if (mn > mx) throw new Error(`${what}: min ${mn} is above max ${mx}`);
302
+ return [mn, mx, val[i] != null ? num(val[i]) : Math.min(mx, Math.max(mn, 0))];
303
+ });
304
+ joints.push({ id: j.id, type: j.type, parent: p.item, child: c.item, a: p.frame, b: c.frame, dofs,
305
+ ...(j.label ? { label: j.label } : {}), ...(path ? { path } : {}), ...(j.cone != null ? { cone: num(j.cone) } : {}),
306
+ ...(j.follow ? { follow: [j.follow, j.ratio != null ? num(j.ratio) : 1, j.offset != null ? num(j.offset) : 0] } : {}) });
307
+ }
308
+ for (const j of joints) if (j.follow) {
309
+ const l = joints.find((x) => x.id === j.follow[0]);
310
+ if (!l) throw new Error(`joint ${j.id}: follows "${j.follow[0]}", which isn't a joint (${joints.map((x) => x.id).join(', ')})`);
311
+ if (l.dofs.length !== j.dofs.length) throw new Error(`joint ${j.id} (${j.type}) takes ${j.dofs.length} values, but follows ${l.id} (${l.type}), which takes ${l.dofs.length}`);
312
+ }
313
+ const items = placed.map(([it, c], k) => {
314
+ if (children.has(k)) return [c.id];
315
+ const base = (it.at || [0, 0, 0]).map(num), rot = (it.rotate || [0, 0, 0]).map((r) => num(r) * deg);
316
+ // A repeated item turns as a whole about its at: each copy's offset turns with it (keys on a tilted plate)
317
+ return [c.id, ...rows(translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create()))).transforms)];
318
+ });
319
+ const poses = Object.fromEntries(Object.entries(a.poses || {}).map(([n, set]) => [n, Object.fromEntries(Object.entries(set).map(([id, v]) => {
320
+ if (!joints.some((j) => j.id === id)) throw new Error(`pose ${n}: no joint "${id}"`);
321
+ return [id, Array.isArray(v) ? v.map(num) : num(v)];
322
+ }))]));
323
+ if (a.pose && !poses[a.pose]) throw new Error(`pose "${a.pose}" isn't one of the poses (${Object.keys(poses).join(', ') || 'none'})`);
324
+ const loops = (a.loops || []).map((l, i) => ({ label: l.label || `${typeof l.a === 'string' ? l.a : 'anchor'} meets ${typeof l.b === 'string' ? l.b : 'anchor'}`,
325
+ a: anchor(l.a, `loop ${i + 1}`), b: anchor(l.b, `loop ${i + 1}`), tolerance: l.tolerance != null ? num(l.tolerance) : 0.01 }));
326
+ return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref };
204
327
  }
205
328
 
206
329
  // keyCentres(layout): each key's centre, from lib/layout.mjs (kept under this name for older callers)
@@ -263,6 +386,7 @@ export function checkAssembly(s) {
263
386
  const pick = (n) => (Array.isArray(n) ? n.flatMap(pick) : s.parts.filter((p) => named(p, n)));
264
387
  const groups = new Map();
265
388
  for (const x of s.fits) {
389
+ if (x.poses && !x.poses.includes(s.pose)) continue; // a fit for some poses only: the folded screen over the keys
266
390
  if (x.holes) { holesFit(x); continue; }
267
391
  const A = pick(x.a), key = x.note || `${x.a} / ${x.b}`;
268
392
  const lo = x.min != null ? x.num(x.min) : -Infinity, hi = x.max != null ? x.num(x.max) : Infinity;
@@ -308,6 +432,17 @@ export function checkAssembly(s) {
308
432
  f(misses.length ? 'fail' : 'pass', misses.length ? `${label}: ${misses.join('; ')}` : `${label}: ${holes.length} of ${holes.length} holes clear for ${mm(depth)} mm, with material around each`,
309
433
  `${label}: ${misses.length ? `${misses.length} of ${holes.length} miss` : `${holes.length} of ${holes.length} line up`}`);
310
434
  }
435
+ // Joints: every value in its range (a ball's tip within its cone), and every loop closed
436
+ if (s.motion?.joints.length) {
437
+ const outside = [];
438
+ for (const j of s.motion.joints) {
439
+ const v = s.jointValues[j.id];
440
+ j.dofs.forEach(([lo, hi], i) => { if (v[i] < lo - 1e-9 || v[i] > hi + 1e-9) outside.push(`${j.id} ${mm(v[i])} (${mm(lo)} to ${mm(hi)})`); });
441
+ if (j.cone != null) { const tip = Math.acos(Math.min(1, jointMatrix(j, v)[10])) / (Math.PI / 180); if (tip > j.cone + 1e-9) outside.push(`${j.id} tips ${mm(tip)}° (cone ${mm(j.cone)}°)`); }
442
+ }
443
+ if (outside.length) f('fail', `joints out of range: ${outside.join(', ')}`, `${outside.length} joints out of range`);
444
+ for (const l of loopGaps(s)) f(l.ok ? 'pass' : 'fail', `${l.label}: ${l.ok ? 'closed' : 'apart'} (${mm(l.gap)} mm, axes ${mm(l.angle)}° apart)`, `${l.label}: ${l.ok ? 'closed' : 'apart'}`);
445
+ }
311
446
  // Plates print everything: no references
312
447
  if (s.a.kind === 'plate') {
313
448
  const refs = s.objects.filter((o) => o.role === 'reference' && !o.unplaced); // an unplaced item only lends its numbers
@@ -322,6 +457,58 @@ export function checkAssembly(s) {
322
457
  return out;
323
458
  }
324
459
 
460
+ // Each loop at the assembly's pose: how far apart its two anchors are (mm), and their axes (degrees, either way round)
461
+ export function loopGaps(s) {
462
+ const worlds = placeItems(s.motion, s.jointValues), I = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
463
+ return s.motion.loops.map((l) => {
464
+ const A = mul(l.a.item < 0 ? I : worlds[l.a.item], l.a.frame), B = mul(l.b.item < 0 ? I : worlds[l.b.item], l.b.frame);
465
+ const gap = Math.hypot(A[3] - B[3], A[7] - B[7], A[11] - B[11]), dot = Math.abs(A[2] * B[2] + A[6] * B[6] + A[10] * B[10]);
466
+ const angle = Math.acos(Math.min(1, dot)) / (Math.PI / 180);
467
+ return { label: l.label, gap, angle, ok: gap <= l.tolerance && angle <= 0.05 };
468
+ });
469
+ }
470
+
471
+ // Pairs of parts that overlap, as checkAssembly finds them (fits with a negative min allowed): [[a, b, mm³]]
472
+ function clashesOf(s, named) {
473
+ const allowed = (a, b) => s.fits.some((x) => x.min != null && x.num(x.min) < 0 && ((named(a, x.a) && named(b, x.b)) || (named(a, x.b) && named(b, x.a))));
474
+ const boxes = s.parts.map((p) => bounds(p.triangles)), out = [];
475
+ for (let i = 0; i < s.parts.length; i++) for (let j = i + 1; j < s.parts.length; j++) {
476
+ const pa = s.parts[i], pb = s.parts[j], A = boxes[i], B = boxes[j];
477
+ if (pa.leaf === pb.leaf || ![0, 1, 2].every((k) => A.lo[k] <= B.hi[k] + 1e-6 && B.lo[k] <= A.hi[k] + 1e-6) || allowed(pa, pb)) continue;
478
+ const v = pairOverlap(pa, pb);
479
+ if (v > 0.01) out.push([pa.name, pb.name, v]);
480
+ }
481
+ return out;
482
+ }
483
+ const isNamed = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`);
484
+
485
+ // sweep(s, { joint, steps }) -> findings: each free joint (or the one named) moved through its range, the others held
486
+ // at the assembly's pose, looking for parts that collide and loops that come apart on the way
487
+ export function sweep(s, { joint, steps = 24 } = {}) {
488
+ const out = [], f = (level, text, card) => out.push({ level, text, ...(card && { card }) }), mm = (n) => `${Number(n.toFixed(2))}`;
489
+ const free = s.motion.joints.filter((j) => !j.follow && j.dofs.length && (!joint || j.id === joint));
490
+ if (joint && !free.length) throw new Error(`no joint "${joint}" to sweep (${s.motion.joints.filter((j) => !j.follow && j.dofs.length).map((j) => j.id).join(', ') || 'none'})`);
491
+ const base = s.jointValues;
492
+ for (const j of free) j.dofs.forEach(([lo, hi], d) => {
493
+ const unit = DOFS[j.type][d] === 'angle' ? '°' : ' mm', name = `${j.id}${j.dofs.length > 1 ? ` ${'xyz'[d] && j.type === 'ball' ? 'xyz'[d] : DOFS[j.type][d]}` : ''}`;
494
+ const bad = []; // [value, what]
495
+ for (let i = 0; i <= steps; i++) {
496
+ const v = lo + ((hi - lo) * i) / steps, set = { ...base, [j.id]: base[j.id].map((x, k) => (k === d ? v : x)) };
497
+ const t = s.at(Object.fromEntries(Object.entries(set).filter(([id]) => !s.motion.joints.find((x) => x.id === id).follow)));
498
+ const what = [...clashesOf(t, isNamed).map(([a, b]) => `${a} hits ${b}`), ...loopGaps(t).filter((l) => !l.ok).map((l) => `${l.label} apart by ${mm(l.gap)} mm`)];
499
+ if (what.length) bad.push([v, what]);
500
+ }
501
+ const ranges = []; // runs of steps in a row that collide
502
+ for (const [v, what] of bad) { const r = ranges[ranges.length - 1]; if (r && Math.abs(v - r.to - (hi - lo) / steps) < 1e-9) { r.to = v; r.what = [...new Set([...r.what, ...what])]; } else ranges.push({ from: v, to: v, what }); }
503
+ const span = `${mm(lo)} to ${mm(hi)}${unit}`;
504
+ if (!ranges.length) f('pass', `sweep ${name}, ${span} in ${steps} steps: nothing collides`, `${name}: clear ${span}`);
505
+ else f('fail', `sweep ${name}, ${span} in ${steps} steps: ${ranges.map((r) => `${r.from === r.to ? `at ${mm(r.from)}` : `${mm(r.from)} to ${mm(r.to)}`}${unit.trim()}: ${r.what.slice(0, 3).join('; ')}${r.what.length > 3 ? `; and ${r.what.length - 3} more` : ''}`).join(' | ')}`,
506
+ `${name}: collides ${ranges.map((r) => (r.from === r.to ? mm(r.from) : `${mm(r.from)}-${mm(r.to)}`)).join(', ')}${unit.trim()}`);
507
+ });
508
+ saveOverlaps();
509
+ return out;
510
+ }
511
+
325
512
  // shapes(parts) -> { shapes: [{ part, polygons, triangles }], place: [[shape index, 12 numbers], …] }
326
513
  // Each distinct shape once, then where each copy goes: a 3 × 4 transform by rows (x' = a·x + b·y + c·z + d, …).
327
514
  export function shapes(parts) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.3.4",
3
+ "version": "0.4.1",
4
4
  "description": "The cad command: JSCAD designs from traceable rules, checked for printing and fit, versioned by what fits, shared as links and exported as Bambu 3MF.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -47,7 +47,7 @@
47
47
  "@rulecad/keyboard-layout": "^0.1.2",
48
48
  "@rulecad/printcheck": "^0.1.0",
49
49
  "@rulecad/fit": "^0.2.0",
50
- "@rulecad/model-link": "^0.1.5",
50
+ "@rulecad/model-link": "^0.2.0",
51
51
  "@rulecad/versions": "^0.1.0",
52
52
  "@rulecad/shapes": "^0.2.0",
53
53
  "@rulecad/rules": "^0.2.0",