@rulecad/cad 0.7.32 → 0.7.34

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/EXAMPLES.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [The tutorial](TUTORIAL.md) ends with a wall hook checked against its screw. These examples carry on from there, one
4
4
  for each thing the [README](README.md) describes after that: parts, variants and releases, joints and poses, a model
5
- from elsewhere, an optimised part, a board, and a mechanism printed flat. Each is a few files and the commands to run
5
+ from elsewhere, an optimised part, a board, a mechanism printed flat, and gears. Each is a few files and the commands to run
6
6
  them. The tests write every file here and run every command, so what you read is what works.
7
7
 
8
8
  They start from a workspace `npm create rulecad my-designs` makes, as the tutorial does, and run in order: later
@@ -384,3 +384,138 @@ npx cad animate home/flick
384
384
  `animate` writes the sequence as an animated SVG in `.preview/`, the leaf drawn bent, and a page that plays it with
385
385
  the force on each step. The launcher in `examples/bench/projects/launcher` is the same idea at full size: a flooded
386
386
  frame, catches, a trigger, and a shot.
387
+
388
+ ## 8. Gears: a focus slider on a rack and pinion
389
+
390
+ A slide for a phone or a small camera, moved by a knob: a pinion turns, and a rack carries the slide along. The gears
391
+ come from `v.gears` (`@rulecad/gears`), drawn from their module and teeth; the assembly says which gear drives which,
392
+ and the check works out the rest.
393
+
394
+ The pinion has 14 teeth. Fewer than 17 at the standard 20° are undercut, so it is drawn with a profile shift of 0.2,
395
+ which `@rulecad/gears` names when it refuses one without (`give a profile shift of at least 0.19`). One turn of the knob
396
+ moves the slide π × 14 × 1 = 43.98 mm.
397
+
398
+ ```json projects/home/objects/pinion.json
399
+ {
400
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
401
+ "name": "pinion",
402
+ "title": "Focus knob and pinion",
403
+ "version": "0.1.0",
404
+ "uses": ["x1c"],
405
+ "anchors": { "axis": { "at": [0, 0, 0], "axis": [0, 0, 1] } },
406
+ "variables": {
407
+ "module": { "value": 1, "unit": "mm", "rule": "Tooth size: 3.6 lines across a tooth at the pitch circle on the X1C" },
408
+ "teeth": { "value": 14, "rule": "Few teeth for a fine travel a turn" },
409
+ "shift": { "value": 0.2, "rule": "Profile shift: 14 teeth at 20° need at least 0.19, or they are undercut" },
410
+ "width": { "value": "x1c.layer * 30", "unit": "mm", "rule": "Face width, thirty layers" },
411
+ "bore": { "value": 3.2, "unit": "mm", "rule": "An M3 screw as its axle, 0.2 mm clear" },
412
+ "knob": { "value": 5.5, "unit": "mm", "rule": "The knob's radius, inside the teeth's roots" },
413
+ "grip": { "value": "x1c.layer * 40", "unit": "mm", "rule": "The knob's height, forty layers" }
414
+ }
415
+ }
416
+ ```
417
+
418
+ ```js projects/home/objects/pinion.js
419
+ // A pinion with a knob on top: the gear's face on the bed, the knob printed on it.
420
+ import jscad from '@jscad/modeling'
421
+ const { cylinder } = jscad.primitives
422
+ const { union, subtract } = jscad.booleans
423
+
424
+ export function main (v) {
425
+ const gear = v.gears.spur({ module: v.module, teeth: v.teeth, shift: v.shift, width: v.width, bore: v.bore })
426
+ const knob = cylinder({ radius: v.knob, height: v.grip, center: [0, 0, v.width + v.grip / 2] })
427
+ const hole = cylinder({ radius: v.bore / 2, height: v.grip, center: [0, 0, v.width + v.grip / 2] })
428
+ return union(gear, subtract(knob, hole))
429
+ }
430
+ ```
431
+
432
+ ```json projects/home/objects/rack.json
433
+ {
434
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
435
+ "name": "rack",
436
+ "title": "Slide rack",
437
+ "version": "0.1.0",
438
+ "uses": ["x1c"],
439
+ "anchors": { "slide": { "at": [0, 0, 0], "axis": [1, 0, 0] } },
440
+ "variables": {
441
+ "module": { "value": 1, "unit": "mm", "rule": "The pinion's module: gears that mesh share it" },
442
+ "teeth": { "value": 24, "rule": "Long enough for 60 mm of travel" },
443
+ "width": { "value": "x1c.layer * 30", "unit": "mm", "rule": "The pinion's face width" },
444
+ "back": { "value": "x1c.line * 10", "unit": "mm", "rule": "Bar under the teeth: ten lines" }
445
+ }
446
+ }
447
+ ```
448
+
449
+ ```js projects/home/objects/rack.js
450
+ // The rack: along x, its teeth up +y, its pitch line on y = 0.
451
+ export function main (v) {
452
+ return v.gears.rack({ module: v.module, teeth: v.teeth, width: v.width, height: v.back })
453
+ }
454
+ ```
455
+
456
+ ```json projects/home/objects/rail.json
457
+ {
458
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
459
+ "name": "rail",
460
+ "title": "Slide base",
461
+ "version": "0.1.0",
462
+ "uses": ["x1c"],
463
+ "anchors": {
464
+ "axle": { "at": [0, "centre", "thick"], "axis": [0, 0, 1] },
465
+ "track": { "at": ["start", 0, "thick"], "axis": [1, 0, 0] }
466
+ },
467
+ "variables": {
468
+ "centre": { "value": 7.2, "unit": "mm", "rule": "The pinion's axle above the rack's pitch line: its pitch radius and its shift, m z / 2 + x m" },
469
+ "length": { "value": 140, "unit": "mm", "rule": "Room for the rack's whole travel" },
470
+ "start": { "value": -37.7, "unit": "mm", "rule": "The rack's middle under the knob at rest: half its 24 teeth, 12 × π" },
471
+ "wide": { "value": 40, "unit": "mm", "rule": "Under the rack and the knob" },
472
+ "thick": { "value": "x1c.layer * 15", "unit": "mm", "rule": "Fifteen layers" }
473
+ }
474
+ }
475
+ ```
476
+
477
+ ```js projects/home/objects/rail.js
478
+ // The base: a plate under the rack's travel and the knob, the axle above the rack.
479
+ import jscad from '@jscad/modeling'
480
+
481
+ export function main (v) {
482
+ return jscad.primitives.cuboid({ size: [v.length, v.wide, v.thick], center: [0, v.wide / 4, v.thick / 2] })
483
+ }
484
+ ```
485
+
486
+ The assembly: the knob turns on the base's axle, and the rack slides along its track, its middle under the knob at
487
+ rest, so half a turn either way (±22 mm) keeps the pinion on its teeth. The slide's joint doesn't say
488
+ how far it moves for a turn of the knob: its `mesh` says which joint drives it, and the gears' module and teeth (read
489
+ from the parts, so they can't disagree). The check works out the travel a turn and the phase that puts a tooth in a
490
+ gap, and says whether the axle is where the gears need it.
491
+
492
+ ```json projects/home/assemblies/slider.json
493
+ {
494
+ "title": "Focus slider",
495
+ "kind": "fit",
496
+ "items": [
497
+ { "id": "rail", "object": "rail" },
498
+ { "id": "pinion", "object": "pinion" },
499
+ { "id": "rack", "object": "rack" }
500
+ ],
501
+ "joints": [
502
+ { "id": "knob", "type": "revolute", "parent": "rail.axle", "child": "pinion.axis", "min": -180, "max": 180, "label": "Knob" },
503
+ { "id": "slide", "type": "prismatic", "parent": "rail.track", "child": "rack.slide", "min": -100, "max": 100,
504
+ "mesh": { "with": "knob", "module": "pinion.module", "teeth": ["pinion.teeth", "rack.teeth"], "shift": ["pinion.shift", 0] } }
505
+ ],
506
+ "poses": { "home": { "knob": 0 }, "out": { "knob": 150 } }
507
+ }
508
+ ```
509
+
510
+ ```sh
511
+ npx cad check home/slider
512
+ npx cad check home/slider --sweep --steps 12
513
+ ```
514
+
515
+ The check says `knob drives slide: 43.98 mm of rack a turn`, the contact ratio, and that the axle is where the gears
516
+ need it (`centre distance 7.2 mm, as they need`). Set the base's `centre` to 7 and it fails: the teeth would jam. The
517
+ sweep turns the knob from −180° to 180° with the rack following, and names any teeth that touch on the way. The link
518
+ carries the knob as a slider, with the rack moving with it: `npx cad link home/slider --md`.
519
+
520
+ To see the gears' geometry, `@rulecad/gears/diagram` draws a pair the way a textbook does: pitch and base circles,
521
+ the line of action and the path of contact.
package/README.md CHANGED
@@ -153,6 +153,9 @@ own copy anywhere and name it in `viewUrl`.
153
153
  `notchHinge`, `bistable`, `livingHinge` as shapes, each with a `<name>Model(shape, { E })` giving its stiffness and the
154
154
  strain at a travel, and `printable(shape, printer, material, model)` for how it prints. Drawn flat: bending along y,
155
155
  width up z, so a flexure bends within its layers.
156
+ - `v.gears`: gears (`@rulecad/gears`): `spur`, `rack` and `internal` as shapes, from a module and teeth, each with its
157
+ model (`gearModel`, `rackModel`, `internalModel`) and `printable(model, printer, width)`. Drawn flat: the axis up z,
158
+ the first tooth on +x, the face on the bed. Two gears in an assembly mesh with a joint's `mesh` (see Joints).
156
159
  - A rule set can also carry `"footprints"` (pad data from @rulecad/pcb's `fromKicad`, with its source), which a
157
160
  board's code reads as `v.parts.footprints.usb_c`.
158
161
  - `cad clone` writes a rule set with a `"circuit"`: a published board's parts, pads, nets, planes and outline, read
@@ -265,8 +268,9 @@ other items' variables, so a keycap can sit exactly where its slot meets the swi
265
268
  watertight; `npm install manifold-3d`) with `"engine": "manifold"` in the object's JSON or `CAD_ENGINE=manifold`.
266
269
  - **Sandbox:** a JSCAD design runs in a separate Node process under Node's permission model. Whatever it does, it
267
270
  can't write or delete files, start programs or workers, or load addons, and it reads only the workspace and the
268
- packages designs use. To keep it to making shapes it may import only `@jscad/modeling`, `@rulecad/shapes`,
269
- `@rulecad/flexures` and files in its own project (no `node:` modules), `fetch` and its kin are gone, and it is
271
+ packages designs use, by their real paths (a `node_modules` link spelled through another link, as macOS spells its
272
+ temporary folders through `/tmp` and `/var`, is refused by name: make the link with the real path). To keep it to making shapes it may import only `@jscad/modeling`, `@rulecad/shapes`,
273
+ `@rulecad/flexures`, `@rulecad/gears` and files in its own project (no `node:` modules), `fetch` and its kin are gone, and it is
270
274
  started with none of your environment (no tokens). Those shut the ordinary roads to the network, not every one:
271
275
  before Node 25 the permission model doesn't cover the network, so a design written to get round them might still
272
276
  reach it. Run only designs you trust. It gets its values as data and returns its parts; what it prints
@@ -356,6 +360,15 @@ then y, then z, as `rotate` does.
356
360
  from 0 to its length.
357
361
  - **Followers:** `"follow": "lid"` gives a joint another joint's values, times `ratio` (default 1), plus `offset`. Use
358
362
  it for the second hinge of a pair, or for gears.
363
+ - **Gears:** `"mesh": { "with": "drive", "module": "pinion.module", "teeth": ["pinion.teeth", "wheel.teeth"] }` on a
364
+ revolute makes its gear follow the gear on the joint `with` names, at the ratio of their teeth and in phase: a tooth
365
+ of one sits in a gap of the other at every angle. On a prismatic it is a rack under a pinion (mm a turn); `"ring":
366
+ true` makes it a ring gear round its pinion. `shift` ([the driver's, this one's]), `pressureAngle` and `backlash` are
367
+ as `@rulecad/gears` takes them. Each gear is drawn as `v.gears` draws it (axis up its z, first tooth on +x; a rack
368
+ along its x, teeth up +y) and its joint is anchored at its centre, along its axis. The check gives the ratio, the
369
+ contact ratio and the centre distance (`mesh.centre`: closer than the gears need jams them, further adds backlash),
370
+ each placed between the two axes; `--sweep` turns the train and looks for teeth that touch. Both gears' axes sit on
371
+ one part, or on parts held still: a planet on a turning carrier is not yet a mesh.
359
372
  - **Loops:** each item has one joint to its parent. Where parts join in a ring (two links between the same two
360
373
  parts), let joints place every part, then name the meeting that closes the ring in `loops`. The check measures it
361
374
  in every pose: `"loops": [{ "a": "link_l.top", "b": "mount_l.axis", "label": "Left pivot lines up" }]`. Its anchors
package/lib/assembly.mjs CHANGED
@@ -29,6 +29,7 @@ import { bounds } from '@rulecad/printcheck';
29
29
  import { closest, closestAt, inside, distanceToFace } from '@rulecad/fit';
30
30
  import { keys as keyCentres, readLayout, hasLayout } from './layout.mjs';
31
31
  import { DOFS, frame, turn, mul, pathLength, jointValues, placeItems, jointMatrix } from '@rulecad/model-link';
32
+ import { gearModel, internalModel, rackModel, mesh as meshOf, phase, rackPhase } from '@rulecad/gears';
32
33
 
33
34
  export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
34
35
  export const isAssembly = (ref) => String(ref).includes('/') && host.exists(assemblyPath(ref.split('@')[0]));
@@ -334,7 +335,8 @@ function motionOf(a, placed, num, ref) {
334
335
  });
335
336
  joints.push({ id: j.id, type: j.type, parent: p.item, child: c.item, a: p.frame, b: c.frame, dofs,
336
337
  ...(j.label ? { label: j.label } : {}), ...(path ? { path } : {}), ...(j.cone != null ? { cone: num(j.cone) } : {}),
337
- ...(j.follow ? { follow: [j.follow, j.ratio != null ? num(j.ratio) : 1, j.offset != null ? num(j.offset) : 0] } : {}) });
338
+ ...(j.follow ? { follow: [j.follow, j.ratio != null ? num(j.ratio) : 1, j.offset != null ? num(j.offset) : 0] } : {}),
339
+ ...(j.mesh ? { meshSpec: j.mesh } : {}) });
338
340
  }
339
341
  for (const j of joints) if (j.follow) {
340
342
  const l = joints.find((x) => x.id === j.follow[0]);
@@ -347,6 +349,7 @@ function motionOf(a, placed, num, ref) {
347
349
  // A repeated item turns as a whole about its at: each copy's offset turns with it (keys on a tilted plate)
348
350
  return [c.id, ...rows(translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create()))).transforms)];
349
351
  });
352
+ const meshes = gearMeshes(joints, items, num);
350
353
  const poses = Object.fromEntries(Object.entries(a.poses || {}).map(([n, set]) => [n, Object.fromEntries(Object.entries(set).filter(([id]) => !id.includes('.')).map(([id, v]) => {
351
354
  if (!joints.some((j) => j.id === id)) throw new Error(`pose ${n}: no joint "${id}"`);
352
355
  return [id, Array.isArray(v) ? v.map(num) : num(v)];
@@ -358,7 +361,76 @@ function motionOf(a, placed, num, ref) {
358
361
  const marks = placed.flatMap(([, c], k) => Object.entries(c.src?.b?.object.anchors || {}).map(([name, spec]) => {
359
362
  try { return { item: k, id: c.id, name, frame: frameOf(spec, evalIn(c.src.b.values, `${c.src.objName} anchor ${name}`)) }; } catch { return null; }
360
363
  })).filter(Boolean);
361
- return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref, marks };
364
+ return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref, marks, meshes };
365
+ }
366
+
367
+ // Gears that mesh: "mesh": { "with": <the driving joint>, "module", "teeth": [its, this one's], "shift"?, "ring"? } on
368
+ // a revolute (a gear, or a ring with "ring": true) or a prismatic (a rack). It becomes a follow: the ratio from the
369
+ // teeth, and the offset that puts a tooth in a gap, read from where the two gears are with their joints at 0. Each
370
+ // gear is drawn as @rulecad/gears draws it (its axis up its own z, its first tooth on +x; a rack along its x, teeth up
371
+ // +y, its first space at x = 0), and its joint turns it about its own axis. The centre distance is checked here, the
372
+ // rest of the meshing by --sweep.
373
+ function gearMeshes(joints, items, num) {
374
+ const out = [], list = (x) => (x == null ? [] : [].concat(x));
375
+ const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
376
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
377
+ const crossP = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
378
+ const along = (v, axis) => sub(v, axis.map((x) => x * dot(v, axis))), len = (v) => Math.hypot(...v);
379
+ const angleIn = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v)) / (Math.PI / 180); // v's angle from x0 about z, degrees
380
+ // Is an item held still relative to another: every joint between it and the world fixed (or no joint at all)?
381
+ const byChild = new Map(joints.map((j) => [j.child, j]));
382
+ const still = (i) => { for (let k = i, n = 0; k >= 0 && n < 99; n++) { const j = byChild.get(k); if (!j) return true; if (j.type !== 'fixed') return false; k = j.parent; } return true; };
383
+ for (const j of joints) {
384
+ if (!j.meshSpec) continue;
385
+ const spec = j.meshSpec, what = `joint ${j.id}: mesh`;
386
+ delete j.meshSpec;
387
+ if (j.follow) throw new Error(`${what}: a meshed joint follows its mate already: give mesh or follow, not both`);
388
+ const lead = joints.find((x) => x.id === spec.with);
389
+ if (!lead) throw new Error(`${what}: "with" names the driving joint (${joints.filter((x) => x !== j).map((x) => x.id).join(', ')}; got ${JSON.stringify(spec.with)})`);
390
+ if (lead.type !== 'revolute') throw new Error(`${what}: ${lead.id} is a ${lead.type}; the driver is a gear turning on a revolute`);
391
+ if (j.type !== 'revolute' && j.type !== 'prismatic') throw new Error(`${what}: a gear turns on a revolute, a rack slides on a prismatic (this is a ${j.type})`);
392
+ const kind = j.type === 'prismatic' ? 'rack' : spec.ring ? 'internal' : 'external';
393
+ if (!(lead.parent === j.parent || (still(lead.parent) && still(j.parent)))) throw new Error(`${what}: ${lead.id} and ${j.id} turn on parts that move apart (a planet on a carrier): a mesh needs both on one part, or both on parts held still`);
394
+ const teeth = list(spec.teeth).map(num), shift = list(spec.shift ?? [0, 0]).map(num);
395
+ if (teeth.length !== 2) throw new Error(`${what}: teeth is [the driver's, this one's] (got ${JSON.stringify(spec.teeth)})`);
396
+ const common = { module: num(spec.module), ...(spec.pressureAngle != null ? { pressureAngle: num(spec.pressureAngle) } : {}), ...(spec.backlash != null ? { backlash: num(spec.backlash) } : {}) };
397
+ let A, B;
398
+ try {
399
+ A = gearModel({ ...common, teeth: teeth[0], shift: shift[0] });
400
+ B = kind === 'rack' ? rackModel({ ...common, teeth: teeth[1] }) : (kind === 'internal' ? internalModel : gearModel)({ ...common, teeth: teeth[1], shift: shift[1] ?? 0 });
401
+ } catch (e) { throw new Error(`${what}: ${e.message}`); }
402
+ // Where the two gears are with their own joints at 0 (everything else as it stands by default)
403
+ const v = jointValues({ joints: joints.map((x) => (x.meshSpec ? { ...x, meshSpec: undefined } : x)), poses: {} }, {});
404
+ v[lead.id] = [0]; v[j.id] = [0];
405
+ const worlds = placeItems({ items, joints }, v), W1 = worlds[lead.child], W2 = worlds[j.child];
406
+ const axisOf = (jt) => { const P = mul(jt.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[jt.parent], jt.a); return { at: org(P), dir: col(P, 2) }; };
407
+ const O1 = org(W1), X1 = col(W1, 0), Z1 = col(W1, 2), ax1 = axisOf(lead);
408
+ // the driver turns about its own centre and axis, or its teeth wander
409
+ if (Math.abs(Math.abs(dot(ax1.dir, Z1)) - 1) > 1e-6 || len(along(sub(O1, ax1.at), ax1.dir)) > 1e-4) throw new Error(`${what}: ${lead.id} doesn't turn its gear about the gear's own centre and axis: anchor the gear's joint at its centre, along its axis`);
410
+ const result = { joint: j.id, with: lead.id, kind, findings: [], between: null };
411
+ if (kind === 'rack') {
412
+ const R0 = org(W2), U = col(W2, 0), Y = col(W2, 1), Zr = col(W2, 2), ax2 = axisOf(j);
413
+ const sTravel = Math.sign(dot(ax2.dir, U));
414
+ if (Math.abs(Math.abs(dot(ax2.dir, U)) - 1) > 1e-6) throw new Error(`${what}: ${j.id} doesn't slide the rack along its length (the rack's x)`);
415
+ if (Math.abs(Math.abs(dot(Z1, Zr)) - 1) > 1e-6) throw new Error(`${what}: the pinion's axis isn't across the rack (along the rack's z)`);
416
+ const s1 = Math.sign(dot(Z1, Zr)), rel = sub(O1, R0), at = dot(rel, U), height = dot(rel, Y);
417
+ const k = (Math.PI * A.pitch) / 360, g1 = angleIn(along(X1, Zr), U, Zr);
418
+ j.follow = [lead.id, sTravel * s1 * k, sTravel * (k * g1 + rackPhase(A, at))];
419
+ const m = meshOf(A, B, { centre: height });
420
+ result.findings = m.findings; result.between = [O1, [R0[0] + at * U[0], R0[1] + at * U[1], R0[2] + at * U[2]]]; result.text = m.text;
421
+ } else {
422
+ const O2 = org(W2), X2 = col(W2, 0), Z2 = col(W2, 2), ax2 = axisOf(j);
423
+ if (Math.abs(Math.abs(dot(ax2.dir, Z2)) - 1) > 1e-6 || len(along(sub(O2, ax2.at), ax2.dir)) > 1e-4) throw new Error(`${what}: ${j.id} doesn't turn its gear about the gear's own centre and axis: anchor the gear's joint at its centre, along its axis`);
424
+ if (Math.abs(Math.abs(dot(Z1, Z2)) - 1) > 1e-6) throw new Error(`${what}: ${lead.id} and ${j.id} turn about axes that aren't parallel (spur gears need parallel axes)`);
425
+ const s = Math.sign(dot(Z1, Z2)), d = along(sub(O2, O1), Z1), beta = angleIn(d, X1, Z1), g2 = angleIn(along(X2, Z1), X1, Z1);
426
+ const m = meshOf(A, B, { centre: len(d) });
427
+ // b's angle in the driver's frame is ratio × a's + phase; its joint measures about its own z (the other way when flipped)
428
+ j.follow = [lead.id, s * m.ratio, s * (phase(A, B, beta) - g2)];
429
+ result.findings = m.findings; result.between = [O1, O2]; result.text = m.text;
430
+ }
431
+ out.push(result);
432
+ }
433
+ return out;
362
434
  }
363
435
 
364
436
  // Where each item's anchors are in a pose: [{ id: 'keyboard@pivot', item, at: [x, y, z] }]
@@ -506,6 +578,14 @@ export function checkAssembly(s) {
506
578
  }
507
579
  if (outside.length) f('fail', `joints out of range: ${outside.join(', ')}`, `${outside.length} joints out of range`, { code: 'joint.range', refs: { joints: outside } });
508
580
  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'}`, { code: 'loop', values: { gap: l.gap, angle: l.angle }, refs: { label: l.label } });
581
+ // Gears: each mesh's centre distance and contact ratio, said between the two axes (the rest by --sweep)
582
+ for (const g of s.motion.meshes || []) {
583
+ f('info', `${g.with} drives ${g.joint}: ${g.text}`, null, { code: 'mesh.ratio', refs: { joints: [g.with, g.joint] } });
584
+ for (const x of g.findings) {
585
+ const mid = g.between[0].map((v, k) => (v + g.between[1][k]) / 2);
586
+ f(x.level, `${g.with} and ${g.joint}: ${x.text}`, x.level === 'pass' ? null : `${g.joint}: ${x.code.split('.')[1]}`, { code: x.code, at: mid, between: g.between, ...(x.values ? { values: x.values } : {}), refs: { joints: [g.with, g.joint] } });
587
+ }
588
+ }
509
589
  }
510
590
  // Plates print everything: no references
511
591
  if (s.a.kind === 'plate') {
package/lib/design.mjs CHANGED
@@ -32,6 +32,7 @@ import { readLayout, hasLayout, keys, width, depth } from './layout.mjs';
32
32
  import { optimised, forDesign } from './optimise.mjs';
33
33
  import * as shapes from '@rulecad/shapes';
34
34
  import * as flexures from '@rulecad/flexures';
35
+ import * as gears from '@rulecad/gears';
35
36
  import { engineId, packageVersion, materialise } from './versions.mjs';
36
37
  import { satisfies } from '@rulecad/versions';
37
38
 
@@ -125,11 +126,11 @@ const CACHE = paths.cache('builds'), CACHE_VERSION = 3;
125
126
  const source = (f) => fs.readFileSync(new URL(f, import.meta.url), 'utf8');
126
127
  // What every build is made with: this code, the shape helpers and JSCAD's version (an upgrade rebuilds everything);
127
128
  // boards also with the board engine (engineId: its code and tscircuit's version), loaded only for boards
128
- const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))), flexuresDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/flexures')));
129
+ 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')));
129
130
  // (every module of a helper package but its tests: they change nothing a design builds)
130
131
  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('');
131
132
  const feaDir = path.dirname(createRequire(pathToFileURL(path.join(flexuresDir, 'package.json')).href).resolve('@rulecad/fea')); // (flexures' own, wherever npm put it)
132
- const own = source(import.meta.url) + helperSources(shapesDir) + helperSources(flexuresDir) + helperSources(feaDir) + packageVersion('@jscad/modeling'); // every shapes module, not just its entry
133
+ const own = source(import.meta.url) + helperSources(shapesDir) + helperSources(flexuresDir) + helperSources(gearsDir) + helperSources(feaDir) + packageVersion('@jscad/modeling'); // every shapes module, not just its entry
133
134
  // A lamina's slow stages (the physics, the flood's probe) are kept apart from the builds, keyed by the library's code
134
135
  // and their own inputs, so a build that changes only what comes after them (a strap, a check, a rule's words) has them
135
136
  // at once: .cache/stages/. A design in the sandbox can't write them, so the sandbox hands them back and the tool writes them
@@ -219,7 +220,7 @@ export async function build(d, set = {}, { mirror = false } = {}) {
219
220
  throw syntaxAt(located(e, d.js, 'design.run'), d);
220
221
  });
221
222
  if (typeof mod.main !== 'function') throw new Error(`${path.relative(WS, d.js)} has no exported main(v)`);
222
- const w = watch(values, { shapes, flexures, ops: await shapes.ops(booleans(object)), ...(pcb ? { pcb } : {}) }, optional);
223
+ const w = watch(values, { shapes, flexures, gears, ops: await shapes.ops(booleans(object)), ...(pcb ? { pcb } : {}) }, optional);
223
224
  read = w.read;
224
225
  let made;
225
226
  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 }); }
@@ -1,11 +1,11 @@
1
- // The sandbox's import hook: code in the design's project may import @jscad/modeling, @rulecad/shapes, @rulecad/flexures and files of
1
+ // The sandbox's import hook: code in the design's project may import @jscad/modeling, @rulecad/shapes, @rulecad/flexures, @rulecad/gears and files of
2
2
  // its own project, nothing else (no node: modules: no files, network or processes). The tool's own modules are free.
3
3
  import { builtinModules } from 'node:module';
4
4
 
5
5
  let project = '';
6
6
  export async function initialize(data) { project = data?.project || ''; }
7
7
 
8
- const ALLOWED = ['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures'];
8
+ const ALLOWED = ['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears'];
9
9
  const deny = (spec, why) => Object.assign(new Error(`designs can't import "${spec}": ${why}`), { code: 'design.sandbox' });
10
10
 
11
11
  // The same check, for in-thread hooks (synchronous) and worker hooks (async)
@@ -4,6 +4,7 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import * as shapes from '@rulecad/shapes';
6
6
  import * as flexures from '@rulecad/flexures';
7
+ import * as gears from '@rulecad/gears';
7
8
  import { named, faces, unpack, watch } from './parts.mjs';
8
9
  import { lineOf } from './errors.mjs';
9
10
 
@@ -27,11 +28,11 @@ console.log = console.info = console.debug = (...a) => console.error(...a);
27
28
  try {
28
29
  const mod = await import(js);
29
30
  if (typeof mod.main !== 'function') throw Object.assign(new Error('the design has no exported main(v)'), { code: 'design.main' });
30
- const { v, read } = watch(values, { shapes, flexures, ops: await shapes.ops(engine || 'jscad') }, optional);
31
+ const { v, read } = watch(values, { shapes, flexures, gears, ops: await shapes.ops(engine || 'jscad') }, optional);
31
32
  const { shapes: made, mechanism } = unpack(await mod.main(v));
32
33
  const parts = named(made, meta).map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) }));
33
34
  done({ parts, read: [...read], ...(mechanism ? { mechanism } : {}), ...(Object.keys(kept).length ? { stages: kept } : {}) });
34
35
  } catch (e) {
35
36
  const line = lineOf(e, js);
36
- done({ error: { message: e?.message || String(e), ...(line ? { line } : {}), ...(e?.name === 'SyntaxError' ? { syntax: true } : {}), code: e?.code && typeof e.code === 'string' && !/^ERR_/.test(e.code) ? e.code : e?.code === 'ERR_ACCESS_DENIED' ? 'design.sandbox' : 'design.run' } });
37
+ done({ error: { message: e?.message || String(e), ...(line ? { line } : {}), ...(e?.name === 'SyntaxError' ? { syntax: true } : {}), code: e?.code && typeof e.code === 'string' && !/^ERR_/.test(e.code) ? e.code : e?.code === 'ERR_ACCESS_DENIED' ? 'design.sandbox' : 'design.run', ...(e?.code === 'ERR_ACCESS_DENIED' && e.resource ? { resource: e.resource } : {}) } });
37
38
  }
package/lib/sandbox.mjs CHANGED
@@ -40,10 +40,22 @@ function readable() {
40
40
  // Every node_modules above the workspace and the tool (package lookups read their links), and where links lead
41
41
  const up = (dir) => { const out = []; for (let d = dir; ; d = path.dirname(d)) { out.push(path.join(d, 'node_modules')); if (path.dirname(d) === d) return out; } };
42
42
  const dirs = [WS, TOOL, ...[...up(WS), ...up(TOOL)].filter((d) => fs.existsSync(d)),
43
- ...['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/fea', '@rulecad/variables', 'manifold-3d'].flatMap((n) => [pkgDir(n, fromWs), pkgDir(n, fromTool)])];
43
+ ...['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@rulecad/fea', '@rulecad/variables', 'manifold-3d'].flatMap((n) => [pkgDir(n, fromWs), pkgDir(n, fromTool)])];
44
44
  return [...new Set(dirs.filter(Boolean).flatMap((d) => [d, real(d)]).filter(Boolean))];
45
45
  }
46
46
 
47
+ // A read the permission model refused, said with what to do. Node names the first path it may not read; when that is
48
+ // a link (macOS spells its temporary folders through /tmp and /var, both links into /private), the design's packages
49
+ // are reached through a node_modules link spelled through it, which the sandbox follows by its real path and may not.
50
+ function refused(e) {
51
+ if (e.code !== 'design.sandbox' || !e.resource) return e.message;
52
+ const res = e.resource, to = (() => { try { return fs.lstatSync(res).isSymbolicLink() ? fs.realpathSync(res) : null; } catch { return null; } })();
53
+ const trust = 'or trust the workspace ("sandbox": false in cad.config.json, then cad trust)';
54
+ return to
55
+ ? `the design's sandbox was refused ${res}, a link to ${to}: something the design loads is reached through it (a node_modules link spelled through ${res}, most likely). Make that link with its real path (ln -s "$(pwd -P)/node_modules"), ${trust}`
56
+ : `the design's sandbox was refused ${res}: a design may read only its workspace and the packages it uses. Keep what it needs inside the workspace, ${trust}`;
57
+ }
58
+
47
59
  /**
48
60
  * Run a design's main(values) in the sandbox: { parts, read } as the build makes them.
49
61
  * @param {{ js: string }} d the design @param {object} values @param {object} meta the .json's parts @param {'jscad' | 'manifold'} [engine] v.ops's booleans
@@ -69,7 +81,7 @@ export function runSandboxed(d, values, meta, engine = 'jscad', optional = [], s
69
81
  return reject(located(new Error(`the design's sandbox stopped: ${Buffer.concat(err).toString('utf8').trim().split('\n').slice(-3).join(' ') || 'no output'}`), d.js, 'design.sandbox'));
70
82
  }
71
83
  if (err.length) process.stderr.write(Buffer.concat(err)); // what the design printed
72
- if (r.error) return reject(located(Object.assign(new Error(r.error.message), { code: r.error.code, ...(r.error.line ? { line: r.error.line } : {}), ...(r.error.syntax ? { name: 'SyntaxError' } : {}) }), d.js, r.error.code || 'design.run'));
84
+ if (r.error) return reject(located(Object.assign(new Error(refused(r.error)), { code: r.error.code, ...(r.error.line ? { line: r.error.line } : {}), ...(r.error.syntax ? { name: 'SyntaxError' } : {}) }), d.js, r.error.code || 'design.run'));
73
85
  if (stages) for (const [k, text] of Object.entries(r.stages || {})) stages.put(k, text);
74
86
  resolve({ parts: r.parts.map(({ solid, ...p }) => ({ ...p, geometry: fromFaces(solid) })), read: new Set(r.read), mechanism: r.mechanism || null });
75
87
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.32",
3
+ "version": "0.7.34",
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": {
@@ -69,7 +69,8 @@
69
69
  "three": "^0.186.1",
70
70
  "@rulecad/fea": "^0.2.1",
71
71
  "@rulecad/topopt": "^0.3.0",
72
- "@rulecad/flexures": "^0.5.0"
72
+ "@rulecad/flexures": "^0.5.0",
73
+ "@rulecad/gears": "^0.1.0"
73
74
  },
74
75
  "peerDependencies": {
75
76
  "@rulecad/pcb": "^0.1.0 || ^0.2.0 || ^0.3.0 || ^0.4.0 || ^0.5.0"
@@ -100,7 +100,22 @@
100
100
  "ratio": { "$ref": "#/$defs/expr" },
101
101
  "offset": { "$ref": "#/$defs/values" },
102
102
  "path": { "type": "array", "items": { "$ref": "#/$defs/vec3" } },
103
- "cone": { "$ref": "#/$defs/expr" }
103
+ "cone": { "$ref": "#/$defs/expr" },
104
+ "mesh": {
105
+ "type": "object",
106
+ "description": "Gears: this joint's gear meshes with the gear on the joint named by with, which drives it",
107
+ "required": ["with", "module", "teeth"],
108
+ "additionalProperties": false,
109
+ "properties": {
110
+ "with": { "type": "string" },
111
+ "module": { "$ref": "#/$defs/expr" },
112
+ "teeth": { "type": "array", "minItems": 2, "maxItems": 2, "items": { "$ref": "#/$defs/expr" } },
113
+ "shift": { "type": "array", "minItems": 2, "maxItems": 2, "items": { "$ref": "#/$defs/expr" } },
114
+ "pressureAngle": { "$ref": "#/$defs/expr" },
115
+ "backlash": { "$ref": "#/$defs/expr" },
116
+ "ring": { "type": "boolean" }
117
+ }
118
+ }
104
119
  }
105
120
  },
106
121
  "loop": {