@rulecad/cad 0.7.53 → 0.7.55

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
@@ -21,6 +21,10 @@ variable says which rule it comes from. Follow these steps; they're what makes a
21
21
  - When a part must fit something whose model exists (a maker's CAD, a model site), measure that model:
22
22
  `npx cad measure <file> --rules <name> --source <url> --licence "…"`. Look at the drawing in `.preview/measure/`,
23
23
  then rename the draft rules for what they are and say in each `rule` what the feature does.
24
+ - For a beam (an aluminium extrusion) the kit has no profile for, measure the maker's model or a DXF of its section:
25
+ `npx cad measure <beam.stl|section.dxf> --profile <name> --source <url> --licence "…"`. It writes a draft profile
26
+ set and the section's outline into this workspace's `rules/`. Look at the drawing, check the slot figures against
27
+ the maker's sheet, and never copy the outline out of the workspace: it is the maker's shape.
24
28
  - Model it from those rules, then `npx cad match <project>/<object> <file>`: report the worst places with their numbers,
25
29
  and look at the sections picture. A deliberate clearance shows as an even offset; anything else is a finding.
26
30
  - Don't copy the shape of a model whose licence is non-commercial, no-derivatives or share-alike into a design under
package/README.md CHANGED
@@ -43,6 +43,7 @@ npx cad compare keyboard/keycap dsa legend-f # two variants (or releases) si
43
43
  npx cad import-kle layout.json keyboard/mine # a layout from keyboard-layout-editor.com, into layouts/
44
44
  npx cad clone <github link to a .kicad_pcb> sea_picro # a published board's circuit, into rules/, to redraw by rules
45
45
  npx cad measure cover.3mf --rules cover # a model from elsewhere, measured into draft rules
46
+ npx cad measure beam.stl --profile profile-2020-mine # a beam's profile from its maker's model or a DXF of its section
46
47
  npx cad match legion-go/rail cover.3mf # how closely a design matches that model, both ways
47
48
  ```
48
49
 
@@ -164,6 +165,10 @@ own copy anywhere and name it in `viewUrl`.
164
165
  (`rules/m3.json`) before the kit's, the project's printer and (for what a thread is in) its material, so a design
165
166
  types no diameter and passes none. `cad check` lists what each call drew and the rule it rests on (`hole.drawn`,
166
167
  `counterbore.drawn`, ...). A design may also import `@rulecad/fixings` itself: then it reads the kit's sets only.
168
+ - `v.frames`: beams and profiles (`@rulecad/frames`): `profileModel` for a profile's figures, slots and faces
169
+ (`v.frames.profileModel('2020-misumi-hfs5').slots['slot-6-misumi'].opening`, to draw a tab that drops into a slot),
170
+ `slotModel`, `beamModel`, `beam` and `outline`. A profile measured into this workspace's `rules/` (`cad measure
171
+ --profile`) is read before the kit's, with its outline. In an assembly a beam is an item (see Beams).
167
172
  - `v.gears`: gears (`@rulecad/gears`): `spur`, `rack` and `internal` as shapes, from a module and teeth, each with its
168
173
  model (`gearModel`, `rackModel`, `internalModel`) and `printable(model, printer, width)`. Drawn flat: the axis up z,
169
174
  the first tooth on +x, the face on the bed. Two gears in an assembly mesh with a joint's `mesh` (see Joints).
@@ -253,6 +258,26 @@ faces) show up as an even offset: set `--tol` above them.
253
258
  A model's licence limits what you make from it, not what you learn: measurements are facts, but a non-commercial or
254
259
  share-alike model's shape shouldn't be copied into a design under another licence. `measure` warns about those.
255
260
 
261
+ **A beam's profile from its maker's model.** `cad measure <beam.stl|beam.3mf|section.dxf> --profile <name>` reads an
262
+ aluminium extrusion's section and writes it as a profile rule set, for a beam the kit has no set for:
263
+
264
+ ```sh
265
+ npx cad measure hfs5-2020.stl --profile profile-2020-mine --source https://example.com/hfs5-2020 --licence "the maker's terms"
266
+ ```
267
+
268
+ | It does | How |
269
+ |---|---|
270
+ | Takes the section | From a model: across its longest axis (or `--along y`), in the middle of the longest stretch that keeps one cross-section. From a DXF: its LINE, LWPOLYLINE (with bulges), ARC and CIRCLE entities, joined into closed loops; inches, centimetres and metres are turned into mm. A SPLINE, an ELLIPSE or a block is refused by name: export the section as lines and arcs |
271
+ | Finds each slot | On every face: the opening at its narrowest, the lip's thickness at its tip, the width under the lips, the depth, the floor's width and the flanks' angle, and a V mouth (`track_width`, `track_angle`) where there is one. An opening with no room under lips is told as a groove, or as the channel of a C section |
272
+ | Finds the bores | Round holes at the middles of the cells are the profile's bores; other round holes and hollows are listed, and stay in the outline |
273
+ | Names the slot family | The known family (the kit's, or your workspace's) whose opening, lip, width and depth are all within `--tol` (0.1 mm) of what was found; where none is, a new family is drafted as `rules/slot-<opening>-<name>.json` |
274
+ | Writes | `rules/<name>.json`, a draft profile with every figure `derived` and carrying the source and licence; `rules/outlines/<name>.json`, the section itself; `.preview/measure/<name>-profile.svg` (and `.png`), the section with each slot and bore marked and listed, to check against the bar in hand |
275
+
276
+ Then `cad rules check <name>` and `cad rules draw <name>`, which use the measured outline in place of a drawn one, and
277
+ add what a model cannot say: the maker, the alloy, a material set for its mass, the thread its bore taps to. The
278
+ outline is the model's shape, so it goes into your own workspace and nowhere else: the kit publishes no maker's
279
+ outline, and under a non-commercial, no-derivatives or share-alike licence the command says to keep it there.
280
+
256
281
  ## Assemblies
257
282
 
258
283
  `projects/<project>/assemblies/<name>.json` places objects together. Positions are expressions over rules and the
@@ -481,6 +506,54 @@ An item can be a motor instead of a printed object: `{ "id": "drive", "motor": {
481
506
  - `cad preview --check` of an assembly with a motor writes `<assembly>-check.png`: the same six views, with a label at each joint the motor's torque passes through (what reaches it, and at the loaded joint the margin and whether it holds unpowered). The rest view never carries them.
482
507
  - `cad preview` of an assembly with a motor draws each one at work beside the picture, as SVG: `<assembly>-<motor>-curve.svg`, its torque against speed at the output with the load and the working speed marked, and `<assembly>-<motor>-train.svg`, the torque from its shaft through each stage to the joint with the load, against what the load needs there, and whether it holds with the power on and off. The numbers are the check's.
483
508
 
509
+ ### Beams
510
+
511
+ An item can be a beam, a length of an aluminium extrusion, a tube or a bar from `@rulecad/frames`:
512
+
513
+ ```json
514
+ { "id": "x1", "beam": { "profile": "2020-misumi-hfs5", "length": 300 }, "from": [0, 0, 0], "to": [300, 0, 0], "roll": 0 }
515
+ ```
516
+
517
+ - `"profile"` names the profile (`2020-misumi-hfs5`, `profile-4040-item-8`, or a set in this workspace's `rules/`).
518
+ `"length"` is mm from end `a` to end `b`, a number or an expression (`"x1.length"`). Placed by its ends, the length
519
+ may be left out: it is the distance from `from` to `to`, and a length that disagrees with them is refused with both.
520
+ `"material"` names a material set in place of the profile's alloy. `"printed": true` is for printed beams, a later
521
+ release: it is refused by name for now.
522
+ - Placed by its ends, end `a` is at `from` and end `b` at `to`; at roll 0 its top faces up (+z), or +y when it stands
523
+ upright, and `"roll"` turns it about its own axis, in degrees. Or place it with `at` and `rotate` as any item, in its
524
+ own frame: end `a` at the origin, the beam up +z, its top +y. The face names and a picture are in the
525
+ `@rulecad/frames` README ("Face names in an assembly").
526
+ - A beam is bought: drawn faint, never on a plate, on `cad list` by profile and length (`2 × profile-2020-misumi-hfs5
527
+ x 300 mm a beam 150 g each`, weighed by the maker's mass per metre where the sheet gives one), and in the overlap
528
+ check by its envelope, a plain box. `cad check` says each beam's mass beside the sheet's, and warns of a length
529
+ longer than the profile is sold in. Its numbers are values: `x1.length`, `x1.width`, `x1.height`, `x1.mass`.
530
+ - `"ops"` lists the operations on it, each placed by an address on the beam and dimensioned from end `a`: `cut`,
531
+ `mitre`, `tap`, `access`, `drill`, `counterbore`, `pocket`, `notch` and `deburr`. `{ "op": "tap", "at": "a", "thread":
532
+ "M5" }` taps end a's bore; `{ "op": "access", "at": "top@-10", "thread": "M5" }` drills a hole for an M5 screw's key 10
533
+ mm from end b; `{ "op": "mitre", "at": "b", "angle": 45, "about": "top" }` mitres end b, the length then measured on
534
+ the long side. Numbers may be expressions. Each is cut into the beam's solid (a mitre into its envelope too), and
535
+ `cad check` reports its findings as `beam.op` (a hole into a slot's lips or across a tapped thread, a tap deeper than
536
+ the bore, a hole too near an end) and thread engagement in the alloy. What each takes is in the `@rulecad/frames`
537
+ README ("Operations").
538
+ - `cad add beam <project>/<assembly> --id x1 --profile 2020-misumi-hfs5 --from 0,0,0 --to 300,0,0 [--roll 90]` adds one.
539
+
540
+ Every beam has addresses, taken wherever an anchor is: an item's `at`, a joint's `parent` or `child`, a `loop`, a
541
+ fit's `a` or `b`, a fit's `access`, and a load's `at`.
542
+
543
+ | Address | Where |
544
+ |---|---|
545
+ | `x1.a`, `x1.b` | The middle of each end, its z out of the end |
546
+ | `x1.a.1`, `x1.b.2` | A bore in an end |
547
+ | `x1.top`, `x1.top.2` | A face's first and second place (a slot, or the face where it is closed), at the middle of the beam |
548
+ | `x1.top@120`, `x1.top@-20`, `x1.top@50%` | 120 mm from end `a`, 20 mm from end `b`, half way along |
549
+ | `x1.top.2@120` | The second slot of a face that has more than one |
550
+
551
+ A face's anchor has its z out of the face and its x along the beam toward `b`. An item placed at an address
552
+ (`{ "id": "plate", "object": "plate", "at": "x1.top@50%" }`) puts its own origin there, its z out of the face and its
553
+ x along the beam, turned by its `rotate` in that frame; it moves with the beam. A distance past either end is refused
554
+ with the beam's length: `"top@320" is past the end of profile-2020-misumi-hfs5 x 300: it is 300 mm long`. In a fit, an
555
+ address stands for the faces near it, as `item@anchor` does (`"within"`, 10 mm by default).
556
+
484
557
  ### Building it
485
558
 
486
559
  Once an assembly is checked, these say how to make it. They all read the assembly itself, so they can't disagree with it.
@@ -488,8 +561,10 @@ Once an assembly is checked, these say how to make it. They all read the assembl
488
561
  - `cad order <project>/<assembly>`: the order it goes together in, each step with the part and the fasteners named from its `fastens` notes (`"fastener": "M3x12", "count": 2` on a fit puts them on the shopping list and the step). A `fasten` names its screws on the step where its parts are both there, with the key that turns them and how tight: its `torque`, or the most the seat under the head takes (`2. bracket goes on: bracket fastened to base (2 × M3x10 cap) with a 2.5 mm hex key, to 0.33 N m at most (what the seat takes)`); `--json` gives each as `{ fit, fastener, count, key, tighten: { torque, given } }`, and the build page shows the same. `--preview` writes a picture of each step to `.preview/`: what's there, and the new part held off along the way it goes on. The order is found by taking the assembly apart, so a part goes in after what it's fastened into, a bearing before its shaft, and a nut trapped by a wall before the neighbour that traps it. A part goes on along a straight line that clears everything already there; which line comes from the part as drawn.
489
562
  - `assembly.order` is `cad check`'s finding on it: a part no order can reach fails by name, and a part sealed inside another too. A fit can say where a screw is driven from with `"access": "<item>.<anchor>"`, the anchor's z pointing out along the screw: whatever stands on that line goes on after the screw, and if it has to go on first the screw can't be reached at all. Works on an assembly's own items; a component (an assembly used as an item) goes on as one step.
490
563
  - `cad plates <project>/<assembly>`: every printed part laid out on beds, in its print orientation (as it's drawn), grouped by filament so each plate is one colour change, spaced by the first layer's rule (the printer's `print_gap` plus twice its `foot`, up to whole lines; `--gap` for your own). They're written as `kind: "plate"` assemblies called `<assembly>-<filament>-<n>` and checked as prints; `cad export` makes each one's 3MF. Each plate remembers what's on it by its build's hash (`"packed"` in its file): a changed part re-packs only its plate, so the other plates keep their files untouched, and a part too big for the bed is said by name (`plate.bed`).
564
+ - `cad list <project>/<assembly>` lists the beams' **cut list** after the bought parts: each mark (beams that are the same, one profile, length and set of operations, share a mark, A, B, C), its count, grams each and work, then each profile's lengths to cut, the bars to buy in the lengths it is sold in, and the cuts on each bar in order with its offcut. Every cut takes the saw's 3 mm kerf and each bar's first end is trimmed 10 mm (`CUT_DEFAULTS` in `@rulecad/frames`, each with its source); the packing is first-fit decreasing. `cad check` adds the cut list's findings (`frame.cut`): a beam longer than any length sold fails, two lengths nearer than the cut tolerance can hold apart warn, and beams of one mark are reminded to be cut against one stop. Each beam's mark is in its label in the preview and the link (`x1: mark A, profile-2020-misumi-hfs5 x 300 mm`).
565
+ - `cad beams <project>/<assembly>`: a cut-and-drill sheet for each mark, written to `exports/<project>/<assembly>.beam-<mark>.svg`, in mm so it prints to scale at 100%: the section at end a with each face named and the taps marked, a view of each face with work on it (that face up, end a on the left), every operation dimensioned from end a to 0.1 mm, and the operations in order, each tap with its thread and depth. The build page lists the sheets with the cut list.
491
566
  - `cad wires <project>/<assembly>`: the wiring sheet, printed and written to `exports/<project>/<assembly>.wiring.md` (`cad machine` writes it too): each wire's length through every pose with its service loop, gauge, colour, connectors and board pins. Wires also show faint along their routes in `cad preview` and in the link, moving with the joints, and are never parts: no overlap check sees them.
492
- - `cad link` for such an assembly (or one with a `fasten`) carries the rest of the project with the model. A **Build** button on the page opens, beside it, the shopping list, the plates drawn on their beds, the wiring sheet, the assembly steps (each shows the model at that step) and the machine's settings. The Rules panel lists **predicted against measured**: the ledger `cad measured` writes, each with its ratio, and what the checks predict that nobody has measured yet.
567
+ - `cad link` for such an assembly (or one with a `fasten`) carries the rest of the project with the model. A **Build** button on the page opens, beside it, the shopping list, the beams' cut list and their sheets, the plates drawn on their beds, the wiring sheet, the assembly steps (each shows the model at that step) and the machine's settings. The Rules panel lists **predicted against measured**: the ledger `cad measured` writes, each with its ratio, and what the checks predict that nobody has measured yet.
493
568
  - A link for an assembly with a `task` lets the page move the machine: see "Things that move" in the viewer's README. It carries the newest step file `cad plot` wrote for this assembly (`--steps <file>` for another, `--no-steps` for none). A step file for other joints is refused by name.
494
569
 
495
570
  ## Optimised parts
package/bin/cad.mjs CHANGED
@@ -24,7 +24,7 @@ import { setVariables, addToAssembly, parseValue } from '../lib/edit.mjs';
24
24
  import { setAt } from '../lib/jsonedit.mjs';
25
25
  import { threemf, slotOf } from '../lib/threemf.mjs';
26
26
  import { liveView } from '../lib/live.mjs';
27
- import { checkSets, drawSet, draftSet } from '../lib/sheet.mjs';
27
+ import { checkSets, drawSet, draftSet, draftPart, draftParts } from '../lib/sheet.mjs';
28
28
  import { filaments, slots, linkTo, objectModel, assemblyModel, VIEW } from '../lib/links.mjs';
29
29
 
30
30
  // What the print file asks of the AMS: which filament each kind of part prints in
@@ -50,9 +50,10 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
50
50
  cad rules check [set …] rule sets held to what makes them traceable (exit 1 on a failure) [--json]
51
51
  cad rules draw <set> a dimension drawing of what a set says a part mounts by, <set>.svg, to compare with its datasheet [--out file]
52
52
  cad rules draft <name> --from <file.pdf> the figures in a datasheet's text, into rules/<name>.json for you to name and check (all kind estimate)
53
+ cad rules draft profile|slot|slot_nut <name> every field a beam's profile, a slot family or a slot nut has, to fill from its sheet
53
54
  cad values <project>/<object> [names…] the object's variables, resolved [--json]
54
55
  cad set <project>/<object> name=value … change variables, keeping the file's layout [--unit, --rule, --label, --new to add one]
55
- cad add fit|joint|item|loop|pose <project>/<assembly> --a … --b … --min … add to an assembly, keeping its layout
56
+ cad add fit|joint|item|beam|loop|pose <project>/<assembly> --a … --b … --min … add to an assembly, keeping its layout
56
57
  cad add fasten <project>/<assembly> --screw "M3 cap" --through bracket --into base --at bracket.h1,bracket.h2
57
58
  a screwed joint (or --holes bracket.body for the part's own holes) [--nut [hex|square|lock]]
58
59
  [--washer] [--length 12] [--torque 0.5] [--note …]
@@ -91,7 +92,8 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
91
92
  .preview/, and any stroke refused [--calibrate: the calibration drawing] [--tol 0.1] [--json]
92
93
  cad order <project>/<assembly> the order it goes together in, each step with its fasteners [--preview: an exploded picture of each step in .preview/]
93
94
  cad plates <project>/<assembly> every printed part on beds, by filament, spaced by the first-layer rule: written as plate assemblies and checked; a changed part re-packs only its plate [--gap mm] [--json]
94
- cad list <project>/<assembly> what it takes to build: bought parts by set, every screw, nut and insert in packs, wire, printed parts in grams
95
+ cad list <project>/<assembly> what it takes to build: bought parts by set, the beams' cut list and bars to buy, every screw, nut and insert in packs, wire, printed parts in grams
96
+ cad beams <project>/<assembly> a cut-and-drill sheet for each mark of beam (beams that are the same share one), to scale, written to exports/ [--json]
95
97
  cad wires <project>/<assembly> the wiring sheet: each wire's length, gauge and ends, written to exports/ [--out wiring.md]
96
98
  cad measured <project>/<assembly> <name>=<value> … a measurement, where the estimate was: a rule (x1c.press=0.08) or a
97
99
  check's prediction (task.accuracy=0.8): says what moved, and keeps a ledger of predicted
@@ -99,10 +101,17 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
99
101
  [--table: what the assembly still assumes, as Markdown; --out MEASURE.md: kept in that file]
100
102
  The fixings coupon's rules need no --rule: x1c.pilot_m4, x1c.insert_m3 (and _petg for one
101
103
  plastic), x1c.nut_fit, x1c.nut_slip, x1c.thread_gap, x1c.thread_flank (45 or 60)
104
+ The slot coupon's need no --rule: x1c.slot_fit, x1c.printed_slot_fit; a slot measured by
105
+ caliper goes in your copy of its set (slot-8.opening=8.1), checked as a slot
102
106
  cad measure <model.stl|3mf> a model from elsewhere, measured: size, the stretches along its length with the same
103
107
  cross-section, and each section's shape, with a drawing in .preview/measure/
104
108
  [--along x|y|z] [--at 10,50: sections there too] [--line 0.6,2.5;4.6,2.5: where lines
105
109
  along it are inside] [--rules <name> --source <url> --licence "…": draft rules]
110
+ cad measure <beam.stl|3mf|section.dxf> --profile <name> a beam's profile from a model of it, or a DXF of its
111
+ section: its outline to rules/outlines/<name>.json, its slots (opening, lip, width,
112
+ depth) and bores as a draft profile set, each slot matched to a known slot family or
113
+ drafted as a new one, and a drawing of what was found [--source <url> --licence "…"]
114
+ [--tol 0.1: how close a slot must be to a family, mm] [--along x|y|z] [--force]
106
115
  cad match <project>/<object> <model.stl|3mf> how closely the design matches a model: both ways, signed, with the
107
116
  worst places and sections through them [--tol 0.2 (default: the printer's fit)]
108
117
  [--place "rz90 t1,2,3": how to lay the model over the design, else it is fitted]
@@ -123,15 +132,15 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
123
132
 
124
133
  // Every command and option there is: a misspelt one is refused by name, not passed over
125
134
  const COMMANDS = ['new', 'import-kle', 'clone', 'agents', 'trust', 'rules', 'values', 'set', 'add', 'why', 'check', 'preview', 'animate', 'optimise', 'optimize', 'export',
126
- 'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'measured', 'list', 'wires', 'machine', 'plot', 'plates', 'order', 'match', 'variants', 'compare', 'help'];
135
+ 'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'measured', 'list', 'beams', 'wires', 'machine', 'plot', 'plates', 'order', 'match', 'variants', 'compare', 'help'];
127
136
  const OPTIONS = ['table', 'calibrate', 'check', 'turns', 'preview', 'gap', 'no-steps', 'all', 'along', 'at', 'bump', 'depth', 'dry-run', 'explode', 'force', 'fresh', 'json', 'licence', 'license', 'long', 'm', 'material', 'md', 'name', 'new',
128
- 'no-models', 'no-pictures', 'no-rules', 'note', 'open', 'part', 'place', 'pose', 'progress', 'push', 'result', 'rules', 'samples', 'set', 'short', 'source', 'steps',
137
+ 'no-models', 'no-pictures', 'no-rules', 'note', 'open', 'part', 'place', 'pose', 'profile', 'progress', 'push', 'result', 'rules', 'samples', 'set', 'short', 'source', 'steps',
129
138
  'sweep', 'tol', 'trailer', 'ttl', 'version', 'watch', 'line',
130
139
  'unit', 'rule', 'label', 'from', 'out', // cad set, cad rules
131
- 'a', 'b', 'min', 'max', 'poses', 'id', 'type', 'parent', 'child', 'follow', 'value', 'ratio', 'object', 'assembly', 'variant', 'rotate', // cad add
140
+ 'a', 'b', 'min', 'max', 'poses', 'id', 'type', 'parent', 'child', 'follow', 'value', 'ratio', 'object', 'assembly', 'variant', 'rotate', 'to', 'roll', // cad add
132
141
  'screw', 'through', 'into', 'holes', 'nut', 'washer', 'length', 'torque']; // cad add fasten
133
142
  // What a command takes, where that isn't <project>/<object>
134
- const USAGE = { add: 'fit|joint|item|loop|pose|fasten <project>/<assembly> --key value …', why: '<project>/<object>.<variable>', set: '<project>/<object> name=value …',
143
+ const USAGE = { add: 'fit|joint|item|beam|loop|pose|fasten <project>/<assembly> --key value …', why: '<project>/<object>.<variable>', set: '<project>/<object> name=value …',
135
144
  optimise: '<project>/<problem>', optimize: '<project>/<problem>', history: '<project>[/<object>]', release: '<project>[/<object>] -m "what changed"',
136
145
  diff: '<project>/<object> <from> [<to>]', compare: '<project>/<object> <a> <b>', match: '<project>/<object> <model.stl|model.3mf>', clone: '<board.kicad_pcb | GitHub link> <name>' };
137
146
 
@@ -338,24 +347,36 @@ async function analyses(b, d, tag) {
338
347
  // cad rules check / draw / draft: rule sets themselves, not a design's use of them
339
348
  function ruleSheets(what, names) {
340
349
  if (what === 'check') {
341
- const results = checkSets(names), bad = results.filter((r) => r.findings.length);
350
+ // a set fails on a finding of level fail; a warning or a note is said and the set still passes
351
+ const results = checkSets(names), fails = (r) => r.findings.filter((x) => x.level === 'fail').length, bad = results.filter(fails), noted = results.filter((r) => r.findings.length && !fails(r));
342
352
  if (opt('json')) console.log(JSON.stringify(results.map((r) => ({ name: r.name, findings: r.findings })), null, 2));
343
353
  else {
344
- for (const r of bad) { console.log(`${r.name}: ${r.findings.length} to fix`); for (const x of r.findings) console.log(` FAIL ${x.text} (${x.code})`); }
345
- console.log(`${results.length - bad.length} of ${results.length} rule sets pass`);
354
+ for (const r of results.filter((x) => x.findings.length)) { console.log(`${r.name}: ${fails(r) ? `${fails(r)} to fix` : `passes, ${r.findings.length} to know`}`); for (const x of r.findings) console.log(` ${{ fail: 'FAIL', warn: 'WARN', info: 'NOTE' }[x.level] ?? 'FAIL'} ${x.text} (${x.code})`); }
355
+ console.log(`${results.length - bad.length} of ${results.length} rule sets pass${noted.length ? ` (${noted.length} with something to know)` : ''}`);
346
356
  }
347
357
  process.exitCode = bad.length ? 1 : 0;
348
358
  return;
349
359
  }
350
360
  const name = names[0];
351
- if (!name) throw new Error(`usage: cad rules ${what} <set>${what === 'draft' ? ' --from <file.pdf>' : ''}`);
361
+ if (!name) throw new Error(`usage: cad rules ${what} <set>${what === 'draft' ? ` --from <file.pdf>, or cad rules draft ${draftParts().join('|')} <name>` : ''}`);
352
362
  if (what === 'draw') { const to = opt('out') || `${name}.svg`; fs.writeFileSync(to, drawSet(name)); return console.log(`drew ${to}: compare it with the datasheet`); }
353
- if (!opt('from')) throw new Error('usage: cad rules draft <name> --from <file.pdf>');
363
+ const save = (as, set) => {
364
+ const to = path.join(paths.rules ? paths.rules() : path.join(WS, 'rules'), `${as}.json`);
365
+ if (fs.existsSync(to) && !opt('force')) throw new Error(`${path.relative(WS, to)} already exists (--force replaces it)`);
366
+ fs.mkdirSync(path.dirname(to), { recursive: true }); fs.writeFileSync(to, JSON.stringify(set, null, 2) + '\n');
367
+ return to;
368
+ };
369
+ // cad rules draft profile <name>: every field of the vocabulary for that part, to fill from a sheet
370
+ if (draftParts().includes(name) && !opt('from')) {
371
+ const part = name, as = names[1];
372
+ if (!as) throw new Error(`usage: cad rules draft ${part} <name>`);
373
+ const to = save(as, draftPart(part, as));
374
+ return console.log(`a draft ${part.replace('_', ' ')} in ${path.relative(WS, to)}, every figure an estimate: fill it from the maker's sheet (source, page, date), then cad rules check ${as} and cad rules draw ${as}`);
375
+ }
376
+ if (!opt('from')) throw new Error(`usage: cad rules draft <name> --from <file.pdf>, or cad rules draft ${draftParts().join('|')} <name>`);
354
377
  const { set, found } = draftSet(name, opt('from'));
355
378
  if (!found) return console.log(`no figures in ${opt('from')}'s text: it's probably a picture of a drawing, so read it by eye and write rules/${name}.json by hand`);
356
- const to = path.join(paths.rules ? paths.rules() : path.join(WS, 'rules'), `${name}.json`);
357
- if (fs.existsSync(to) && !opt('force')) throw new Error(`${path.relative(WS, to)} already exists (--force replaces it)`);
358
- fs.mkdirSync(path.dirname(to), { recursive: true }); fs.writeFileSync(to, JSON.stringify(set, null, 2) + '\n');
379
+ const to = save(name, set);
359
380
  return console.log(`${found} figures in ${path.relative(WS, to)}, every one an estimate: name them from the vocabulary, check them against the datasheet, then cad rules check ${name}`);
360
381
  }
361
382
 
@@ -422,7 +443,12 @@ async function main() {
422
443
  if (cmd === 'clone') return cloneBoard(ref, pos[2], { source: opt('source'), licence: opt('licence') || opt('license'), force: !!opt('force'), noModels: !!opt('no-models') });
423
444
  if (cmd === 'status') return status(ref);
424
445
  if (cmd === 'measure') {
425
- if (!ref) throw new Error('usage: cad measure <model.stl|model.3mf> [--along x] [--at 10,50] [--line 0.6,2.5] [--rules <name>]');
446
+ if (!ref) throw new Error('usage: cad measure <model.stl|model.3mf> [--along x] [--at 10,50] [--line 0.6,2.5] [--rules <name>], or cad measure <beam.stl|3mf|section.dxf> --profile <name>');
447
+ if (opt('profile')) {
448
+ const { measureProfile } = await import('../lib/profilemeasure.mjs');
449
+ return measureProfile(ref, { profile: opt('profile'), along: opt('along'), tol: opt('tol') && opt('tol') !== true ? opt('tol') : undefined, source: opt('source'), licence: opt('licence') || opt('license'), force: !!opt('force'), pictures: !opt('no-pictures') });
450
+ }
451
+ if (/\.dxf$/i.test(ref)) throw new Error('a DXF is a drawing of a section, not a model: cad measure <section.dxf> --profile <name> reads a beam\'s profile from it');
426
452
  const list = (k) => (opt(k) && opt(k) !== true ? String(opt(k)).split(k === 'line' ? ';' : ',').filter(Boolean) : []);
427
453
  return measure(ref, { along: opt('along'), at: list('at'), line: list('line'), rules: opt('rules'), source: opt('source'), licence: opt('licence') || opt('license'), force: !!opt('force'), pictures: !opt('no-pictures') });
428
454
  }
@@ -431,7 +457,7 @@ async function main() {
431
457
  if (cmd === 'variants') return variants(locate(ref));
432
458
  if (cmd === 'compare') return compareVariants(locate(ref), pos[2], pos[3]);
433
459
  if (cmd === 'measured') return measuredCommand(ref);
434
- if (cmd === 'list' || cmd === 'wires') return listCommand(cmd, ref);
460
+ if (cmd === 'list' || cmd === 'wires' || cmd === 'beams') return listCommand(cmd, ref);
435
461
  if (cmd === 'machine' || cmd === 'plot') return machineCommand(cmd, ref);
436
462
  if (cmd === 'plates' || cmd === 'order') return platesCommand(cmd, ref);
437
463
  if (cmd === 'history') return history(ref);
@@ -572,10 +598,15 @@ async function editAssembly(what, ref) {
572
598
  const list = (k) => (typeof opt(k) === 'string' ? opt(k).split(',').map((x) => parseValue(x.trim())) : undefined);
573
599
  const pick = (keys) => Object.fromEntries(keys.map((k) => [k, typeof opt(k) === 'string' ? parseValue(opt(k)) : undefined]).filter(([, v]) => v !== undefined));
574
600
  const text = (keys) => Object.fromEntries(keys.filter((k) => typeof opt(k) === 'string').map((k) => [k, String(opt(k))]));
601
+ // (an item's at is a point, 1,2,3, or an address on a beam: --at x1.top@50%)
602
+ const at = () => (typeof opt('at') !== 'string' ? {} : /^[a-z][\w-]*\./i.test(opt('at')) ? { at: String(opt('at')) } : { at: list('at') });
575
603
  let entry;
576
604
  if (what === 'fit') entry = { ...text(['a', 'b']), ...pick(['min', 'max']), ...(list('poses') ? { poses: list('poses').map(String) } : {}), ...text(['note', 'label']) };
577
605
  else if (what === 'joint') entry = { ...text(['id', 'type', 'parent', 'child', 'label', 'follow']), ...pick(['min', 'max', 'value', 'ratio']) };
578
- else if (what === 'item') entry = { ...text(['id', 'object', 'assembly', 'variant']), ...(list('at') ? { at: list('at') } : {}), ...(list('rotate') ? { rotate: list('rotate') } : {}),
606
+ else if (what === 'beam') {
607
+ if (typeof opt('profile') !== 'string') throw new Error('usage: cad add beam <project>/<assembly> --id x1 --profile 2020-misumi-hfs5 --from 0,0,0 --to 300,0,0 [--roll 90] [--length 300] [--material al6063-t5], or --length 300 --at 0,0,0 --rotate 0,90,0');
608
+ entry = { ...text(['id']), beam: { profile: String(opt('profile')), ...pick(['length']), ...text(['material']) }, ...(list('from') ? { from: list('from') } : {}), ...(list('to') ? { to: list('to') } : {}), ...pick(['roll']), ...at(), ...(list('rotate') ? { rotate: list('rotate') } : {}) };
609
+ } else if (what === 'item') entry = { ...text(['id', 'object', 'assembly', 'variant']), ...at(), ...(list('rotate') ? { rotate: list('rotate') } : {}),
579
610
  ...(typeof opt('set') === 'string' ? { set: Object.fromEntries(sets() && Object.entries(sets()).map(([k, v]) => [k, parseValue(v)])) } : {}) };
580
611
  else if (what === 'loop') entry = text(['a', 'b', 'label']);
581
612
  else if (what === 'fasten') { // --screw "M3 cap" --through bracket --into base --at bracket.h1,bracket.h2 | --holes bracket.body [--nut [hex] --washer --length 12 --torque 0.5 --note …]
@@ -586,8 +617,8 @@ async function editAssembly(what, ref) {
586
617
  const pairs = positional().slice(3);
587
618
  if (typeof opt('name') !== 'string' || !pairs.length) throw new Error('usage: cad add pose <project>/<assembly> --name open hinge=90 [joint=value …]');
588
619
  entry = { name: opt('name'), values: Object.fromEntries(pairs.map((p) => { const [k, v] = p.split('='); return [k.trim(), v.includes(',') ? v.split(',').map(parseValue) : parseValue(v)]; })) };
589
- } else throw new Error('usage: cad add fit|joint|item|loop|pose|fasten <project>/<assembly> --key value …');
590
- const r = addToAssembly(ref, what, entry);
620
+ } else throw new Error('usage: cad add fit|joint|item|beam|loop|pose|fasten <project>/<assembly> --key value …');
621
+ const r = addToAssembly(ref, what === 'beam' ? 'item' : what, entry);
591
622
  if (opt('json')) return console.log(JSON.stringify({ ...r, added: entry }));
592
623
  console.log(`added ${/^[aeiou]/.test(what) ? "an" : "a"} ${what} to ${path.relative(WS, r.file)}`);
593
624
  }
@@ -1003,6 +1034,13 @@ async function listCommand(what, ref) {
1003
1034
  const { shoppingList, listText } = await import('../lib/list.mjs'), l = shoppingList(s);
1004
1035
  return console.log(opt('json') ? JSON.stringify(l, null, 2) : listText(ref, l));
1005
1036
  }
1037
+ if (what === 'beams') {
1038
+ const { writeBeamSheets } = await import('../lib/beams.mjs'), sheets = writeBeamSheets(s);
1039
+ if (opt('json')) return console.log(JSON.stringify(sheets.map((x) => ({ ...x, file: path.relative(WS, x.file) })), null, 2));
1040
+ if (!sheets.length) return console.log(`${ref} has no beams`);
1041
+ for (const x of sheets) say(` mark ${x.mark} (${x.items.join(', ')}), 1:${x.scale}: ${path.relative(WS, x.file)}`);
1042
+ return;
1043
+ }
1006
1044
  const { wiresFor } = await import('../lib/assembly.mjs'), { wiringSheet } = await import('../lib/wires.mjs'), rows = wiresFor(s);
1007
1045
  if (opt('json')) return console.log(JSON.stringify(rows.map(({ route, ...r }) => r), null, 2));
1008
1046
  if (!rows.length) return console.log(`${ref} has no "wires"`);
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 "bought"`);
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);
@@ -267,6 +273,11 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
267
273
  }
268
274
  // A fit with * applies to every copy: "key-*.switch.bottom" becomes one fit for key-0-0, key-0-1, …
269
275
  // With * on both sides, each copy is checked against all the others: { "a": "key-*.cap", "b": "key-*.cap" }
276
+ // 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
277
+ const beamIds = new Set(placed.filter(([it]) => it.beam).map(([, c]) => c.id));
278
+ for (const x of a.fits || []) for (const n of [x.a, x.b, x.access].flat()) {
279
+ 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}`}`);
280
+ }
270
281
  for (let x of a.fits || []) {
271
282
  if (x.seat != null && x.min == null) x = { ...x, min: -1000 }; // a seat presses, so the pair may overlap
272
283
  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 +349,42 @@ function motionOf(a, placed, num, ref) {
338
349
  // An anchor: { item (index, -1 the world), frame (12 numbers, in the item's own frame) }
339
350
  const anchor = (spec, what) => {
340
351
  if (spec && typeof spec === 'object') return { item: spec.item ? where(spec.item, what) : -1, frame: frameOf(spec, num) };
341
- const bits = String(spec).split('.'), name = bits.pop(), [id, ...inside] = bits;
342
- if (!id || !name) throw new Error(`${what}: name an anchor as <item>.<anchor> (got "${spec}")`);
352
+ const bits = String(spec).split('.'), id = bits[0];
353
+ if (bits.length < 2 || !id || !bits.at(-1)) throw new Error(`${what}: name an anchor as <item>.<anchor> (got "${spec}")`);
343
354
  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 (const n of inside) { // into a component: its item's place there
346
- const sub = src.sub?.items.find((x) => x.id === n);
347
- if (!sub) throw new Error(`${what}: ${id} has no item "${n}"`);
355
+ let src = placed[k][1].src, pre = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0], i = 1;
356
+ for (; i < bits.length - 1 && !src.beam; i++) { // into a component: its item's place there
357
+ const n = bits[i], sub = src.sub?.items.find((x) => x.id === n);
358
+ if (!sub) throw new Error(`${what}: ${bits.slice(0, i).join('.')} has no item "${n}"`);
348
359
  pre = mul(pre, rows(sub.m));
349
- src = sub.sub ? { sub: sub.sub } : { b: sub.built, objName: sub.objName };
360
+ src = sub.sub ? { sub: sub.sub } : { b: sub.built, objName: sub.objName, beam: sub.beam };
350
361
  }
362
+ // 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)
363
+ if (src.beam) return { item: k, frame: mul(pre, beamAddress(src.beam, bits.slice(i).join('.'), `${what}: ${bits.slice(0, i).join('.')}`)) };
364
+ const name = bits[i];
351
365
  const anchors = src.b?.object.anchors || {};
352
366
  if (!anchors[name]) throw new Error(`${what}: ${src.objName || id} has no anchor "${name}" (anchors: ${Object.keys(anchors).join(', ') || 'none'})`);
353
367
  return { item: k, frame: mul(pre, frameOf(anchors[name], evalIn(src.b.values, `${src.objName} anchor ${name}`))) };
354
368
  };
355
369
  const joints = [], children = new Set();
356
- for (const j of a.joints || []) {
370
+ // 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
371
+ // 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
372
+ const atAddress = placed.map(([it]) => it).filter((it, k, all) => typeof it.at === 'string' && all.indexOf(it) === k).map((it) => {
373
+ 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]`);
374
+ 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`);
375
+ return { id: `${it.id}@`, type: 'fixed', parent: it.at, child: { item: it.id, at: [0, 0, 0], ...(it.rotate ? { rotate: it.rotate } : {}) }, at: true };
376
+ });
377
+ for (const j of [...atAddress, ...(a.joints || [])]) {
357
378
  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)}`);
379
+ 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
380
  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);
381
+ 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);
382
+ 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
383
  if (c.item < 0) throw new Error(`${what}: its child must be an item`);
362
- 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)`);
384
+ if (j.at && p.item === c.item) throw new Error(`item ${j.child.item}: at "${j.parent}" is on the item itself`);
385
+ 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
386
  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 repeat`);
387
+ 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
388
  children.add(c.item);
366
389
  const path = j.type === 'path' ? (j.path || []).map((pt) => pt.map(num)) : undefined;
367
390
  if (path && path.length < 2) throw new Error(`${what}: a path joint needs "path": two points or more`);
@@ -374,7 +397,7 @@ function motionOf(a, placed, num, ref) {
374
397
  if (mn > mx) throw new Error(`${what}: min ${mn} is above max ${mx}`);
375
398
  return [mn, mx, val[i] != null ? num(val[i]) : Math.min(mx, Math.max(mn, 0))];
376
399
  });
377
- joints.push({ id: j.id, type: j.type, parent: p.item, child: c.item, a: p.frame, b: c.frame, dofs,
400
+ 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
401
  ...(j.label ? { label: j.label } : {}), ...(path ? { path } : {}), ...(j.cone != null ? { cone: num(j.cone) } : {}),
379
402
  ...(j.follow ? { follow: [j.follow, j.ratio != null ? num(j.ratio) : 1, j.offset != null ? num(j.offset) : 0] } : {}),
380
403
  ...(j.mesh ? { meshSpec: j.mesh } : {}), ...(j.brake ? { brake: j.brake } : {}) });
@@ -386,6 +409,8 @@ function motionOf(a, placed, num, ref) {
386
409
  }
387
410
  const items = placed.map(([it, c], k) => {
388
411
  if (children.has(k)) return [c.id];
412
+ const ends = it.beam ? beamPlace(it, num) : null; // a beam by its ends (lib/beams.mjs)
413
+ if (ends) return [c.id, ...ends];
389
414
  const base = (it.at || [0, 0, 0]).map(num), rot = (it.rotate || [0, 0, 0]).map((r) => num(r) * deg);
390
415
  // A repeated item turns as a whole about its at: each copy's offset turns with it (keys on a tilted plate)
391
416
  return [c.id, ...rows(translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create()))).transforms)];
@@ -403,9 +428,10 @@ function motionOf(a, placed, num, ref) {
403
428
  const marks = placed.flatMap(([, c], k) => Object.entries(c.src?.b?.object.anchors || {}).map(([name, spec]) => {
404
429
  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
430
  })).filter(Boolean);
431
+ // address(name): any anchor by name, a beam's addresses too (x1.top@120), as { item, frame }: for fits and the build order
406
432
  // 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
433
  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) };
434
+ 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
435
  }
410
436
 
411
437
  // A pair measured from its drawn teeth (@rulecad/gears contact: backlash, transmission error, interference), kept in
@@ -664,6 +690,14 @@ function gearMeshes(joints, items, num) {
664
690
  }
665
691
 
666
692
  // Where each item's anchors are in a pose: [{ id: 'keyboard@pivot', item, at: [x, y, z] }]
693
+ // Where an address is in the world, at these joint values: { id (its item), at, frame }, or null where it is not an
694
+ // address on a beam (x1.top@120, x1.a.1). A beam's address it does not have is refused by name.
695
+ export function addressAt(s, n, values = s.jointValues) {
696
+ const id = String(n).split('.')[0], it = s.items.find((x) => x.id === id);
697
+ if (!it?.beam || !String(n).includes('.') || !s.motion?.address) return null;
698
+ const r = s.motion.address(n), W = mul(placeItems(s.motion, values)[r.item], r.frame);
699
+ return { id, at: [W[3], W[7], W[11]], frame: W };
700
+ }
667
701
  export function anchorsAt(s, values = s.jointValues) {
668
702
  const worlds = placeItems(s.motion, values);
669
703
  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 +737,12 @@ async function measurer() {
703
737
  const OVERLAPS = paths.cache('overlaps.json');
704
738
  let remembered = null, fresh = 0;
705
739
  function pairOverlap(pa, pb) {
706
- if (!pa.hash || !pb.hash) return overlap(pa.geometry, pb.geometry);
740
+ const solidOf = (p) => p.collide ?? p.geometry; // (a beam by its envelope: lib/beams.mjs)
741
+ if (!pa.hash || !pb.hash) return overlap(solidOf(pa), solidOf(pb));
707
742
  remembered ||= (() => { try { return JSON.parse(host.readText(OVERLAPS)); } catch { return {}; } })();
708
743
  const at = (p) => `${p.hash}@${Array.from(p.m || []).map((x) => Math.round(x * 1e6) / 1e6).join(',')}`;
709
744
  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.geometry, pb.geometry); fresh++; }
745
+ if (!(k in remembered)) { remembered[k] = overlap(solidOf(pa), solidOf(pb)); fresh++; }
711
746
  return remembered[k];
712
747
  }
713
748
  function saveOverlaps() {
@@ -761,11 +796,13 @@ export function checkAssembly(s) {
761
796
  // A fit names parts (keyboard, key-0-0.cap), or the faces of an item near one of its anchors (keyboard@pivot, within
762
797
  // "within" mm, 10 by default): the pocket round a pivot, not the whole case
763
798
  const marks = anchorsAt(s), within = (x) => (x.within != null ? x.num(x.within) : 10);
799
+ // A beam's address in a fit (x1.top@120): the faces near that point, as near an anchor
800
+ const addressMark = (n) => { const r = addressAt(s, n); return r && { id: n, item: r.id, at: r.at }; };
764
801
  const near = (p, mark, r) => ({ ...p, polygons: p.polygons.filter((f) => distanceToFace(mark.at, f) <= r) });
765
802
  const pickIn = (n, x) => {
766
803
  if (Array.isArray(n)) return n.flatMap((m) => pickIn(m, x));
767
- if (!n.includes('@')) return s.parts.filter((p) => named(p, n));
768
- const mark = marks.find((m) => m.id === n);
804
+ 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)
805
+ const mark = marks.find((m) => m.id === n) ?? addressMark(n);
769
806
  if (!mark) return [];
770
807
  return s.parts.filter((p) => named(p, mark.item)).map((p) => near(p, mark, within(x))).filter((p) => p.polygons.length);
771
808
  };
@@ -871,7 +908,7 @@ export function checkAssembly(s) {
871
908
  // nowhere else: a ring gear resting on its case turns with the planets; a pawl resting on its post walks off it.
872
909
  if (s.motion.joints.some((j) => j.type !== 'fixed')) {
873
910
  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)]);
911
+ 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
912
  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
913
  const placed = new Set(s.objects.filter((o) => !o.unplaced && o.role !== 'reference').map((o) => top(o.id)));
877
914
  const loose = ids.filter((id) => !held.has(id) && placed.has(id));
@@ -889,6 +926,7 @@ export function checkAssembly(s) {
889
926
  }
890
927
  if (s.a.fasten?.length && fastening) fastening.fastenChecks(s, f, { placeItems });
891
928
  boughtFindings(s, f);
929
+ beamFindings(s, f);
892
930
  massFinding(s, f);
893
931
  runningChecks(s, f, { axisOf, placeItems, jointValues, mul });
894
932
  if (s.wires?.length) wireChecks(s, f, { placeItems, jointValues, mul });