@rulecad/cad 0.7.55 → 0.7.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -344,10 +344,16 @@ other items' variables, so a keycap can sit exactly where its slot meets the swi
344
344
  - A fit with `*` applies to every copy: `{ "a": "plate", "b": "key-*.switch.bottom", … }`. With `*` on both sides,
345
345
  each copy is checked against every other copy near it: `{ "a": "key-*.cap", "b": "key-*.cap", "min": 0.5 }`. Repeated fits are reported
346
346
  together: the worst case, and how many of the copies are in range.
347
- - **Holes fits** follow a board's mounting holes into what they screw into: `{ "holes": "pcb.board", "into":
348
- "case.body", "depth": "m2.insert_length" }`. Each screw's path must be clear for `depth` mm and solid within `ring`
349
- mm of it (default: the hole's diameter) half way down. A gap fit can't see this: a board that rests on its bosses
350
- passes even when the bosses are in the wrong place. `"direction": "up"` for screws from below.
347
+ - **Screws** join parts with a `fasten` (the next section), which knows the screw: it follows each one through the
348
+ holes as drawn, chooses its length, and puts it on the shopping list. A gap fit can't see holes: a board that rests on
349
+ its bosses passes even when the bosses are in the wrong place. The older **holes fit** follows a board's mounting
350
+ holes into what they screw into, without the screw: `{ "holes": "pcb.board", "into": "case.body", "depth":
351
+ "m2.insert_length" }`, each path clear for `depth` mm and solid within `ring` mm of it (default: the hole's diameter)
352
+ half way down, `"direction": "up"` for screws from below. Where a holes fit and a fit that `fastens` join the same two
353
+ items, `cad check` says the fasten that would stand for both, with the entry to paste (`fasten.suggest`, a note), and
354
+ `cad add fasten <project>/<assembly> --from-fits` puts it in their place (below). A `fasten` with `"holes": "pcb.board"` holds a
355
+ board's holes to its thread's clearance hole as the fab drills it, with nothing added for a printer (EXAMPLES,
356
+ chapter 6).
351
357
  - `requires` pins versions (`^` same major, at least this version, 0.x included, since a minor release never breaks a
352
358
  fit here; `~` same minor); an item can use a release: `"object": "keycap@0.2.1"`, or a variant: `"keycap:oem-r3"`.
353
359
  - The check names any `estimate` rule an assembly relies on, through its positions or its objects, so guesses get
@@ -372,7 +378,10 @@ ends in. The screws' places are given one of two ways: `at`, an anchor on each s
372
378
  centre line, the anchor's axis along the screw), or `holes`, a part whose own round holes are the places (for a
373
379
  circuit board, its mounting holes). `nut` (`true`, `hex`, `square` or `lock`) says a nut holds the screw where the
374
380
  last part does not; `washer` puts a plain washer under the head; `length` gives the length where the name has none;
375
- `torque` gives the tightening torque in N m. Add one with `cad add fasten <project>/<assembly> --screw "M3 cap"
381
+ `torque` gives the tightening torque in N m. A screw across a yoke or a split clamp ends in the part under its head:
382
+ name that part first in `through` and again as `into` (`"through": ["fork", "block"], "into": "fork", "nut": true`),
383
+ and place each screw with `at`, an anchor whose axis points from the head into the part. Along the axis, the part's
384
+ first stretch of material is the side under the head, and the rest is the far side. Add one with `cad add fasten <project>/<assembly> --screw "M3 cap"
376
385
  --through bracket --into base --at bracket.h1,bracket.h2`.
377
386
 
378
387
  Nothing about the holes is declared. Each part is read as drawn: along the screw's axis the mesh is sliced, and the
@@ -385,7 +394,7 @@ starts and stops. From that the check says:
385
394
  | `fasten.clearance` | Each part passed through has a clearance hole for the thread as drawn on this printer, between the close and the loose figure; it says what the hole measures and what it should be |
386
395
  | `fasten.end` | The far end is a pilot, a hole to tap, a thread drawn to print, an insert's hole or a nut's seat of this thread (a pocket on the far face, or a slot across the screw partway along it, as `v.fixings.nutTrap` cuts), or a clearance hole with `nut`; into a motor, one of its own threaded mounting holes |
387
396
  | `fasten.length` | The length chosen where none is given: the shortest sold length that fits the stack as measured (into a motor, the longest that stops short of the end of its thread). A given length is checked for reaching the far end, bottoming out in a blind hole (1 mm is kept at the tip) and standing more than a diameter proud |
388
- | `fasten.engagement` | The thread engaged at the far end against the rule for what it is in: the thread's `pilot_depth` or the engagement rule for the project's material, an insert's length, a nut's height. A short one names the length or the depth that would do |
397
+ | `fasten.engagement` | The thread engaged at the far end against the rule for what it is in: the thread's `pilot_depth` or the engagement rule for the project's material, an insert's length, a nut's height; into a motor, its own thread's depth, and at least one diameter (`engagement.steel`, as `motor.mount` holds it). A short one names the length or the depth that would do |
389
398
  | `fasten.seat` | The head (or its washer) has a flat seat as wide as itself and square to the screw, read under the head from the part; a countersunk head has a countersink of its angle. It says the force and torque the seat takes on the project's material, and with `torque` holds the pressure against the material's strength and names the washer that would bring it within |
390
399
  | `fasten.access` | A key or driver reaches the head along its axis, in the build pose: a cylinder as wide as the key across its corners, as long as its long arm (both from the `hexkey` set, ISO 2936; a hexagon head's socket adds `hexkey.socket_wall`, an estimate), clear of every other part. A part over the head that goes on after the screw passes, with the step it goes on at: `cad order` puts it after. One that must be there first (it comes earlier in the order, it is one of the joined parts, or it is no step at all) fails by name with how far over the head it is; where a ball-end key tilted up to `hexkey.ball_end_tilt` (25°) clears it, it warns instead |
391
400
  | `fasten.load` | With `loads` or a motor's torque on the joint: what it holds up (the parts left with no other way to the first item, their masses, the loads hung on them, under the assembly's `gravity`, and the torque of a motor among them), shared between the screws as a group (`screwGroup` of `@rulecad/fixings`: shear by distance from the centroid, pull by a plane through it). The screw that takes the most is held against its proof load, the thread it is in against stripping, and the clamp against slipping, at its preload (`screwLoad`); the margin is how many times the load it holds, and under 2 it warns. With no `torque`, it says the torque that leaves the thread twice the load, within the seat, and `cad order` tightens to that. It names the estimates it rests on (the nut factor, a plastic's shear strength, the friction) |
@@ -397,9 +406,19 @@ part they sit in through every pose, and carried in links. `cad list` counts the
397
406
  step. A `fasten` holds its parts as a fit with `"fastens": true` does and lines their holes up as a holes fit does;
398
407
  both older forms still work, and an assembly with no `fasten` checks as before.
399
408
 
409
+ **From the older forms.** A holes fit and a fit with `"fastens": true` between the same two items said apart what one
410
+ `fasten` says, and neither knew the screw. `cad check` names the pair in a note (`fasten.suggest`) with the entry to
411
+ paste: `{ "screw": "M2 cap", "through": ["pcb.board"], "into": "case.body", "holes": "pcb.board" }`. The screw is
412
+ read from the fit's `fastener` (`M2x6`), else from a thread set the holes fit's `depth` names (`m2.insert_length`),
413
+ else from the board's holes as drawn: the largest metric thread narrower than the narrowest hole. `cad add fasten
414
+ <project>/<assembly> --from-fits` writes it in their place: the holes fit goes, the fit that fastens keeps its gap
415
+ range (`min`, `max`) with `fastens`, `fastener` and `count` taken off, or goes too where it had no range. `--screw "M2x8
416
+ countersunk"` gives another screw. Screws driven from below (`"direction": "up"`) are left for you to write.
417
+
400
418
  `cad list` counts every fixing (`fasten.count`): each screw, nut, washer and insert a `fasten` placed (a component's
401
419
  too), a motor's mounting screws where a fit that `fastens` holds it (as many as its holes, at the length its mount
402
- works out for the plate as drawn, taken to a length sold), and a fit that names its `fastener` by hand. They are
420
+ works out for the plate as drawn, taken to a length sold), and a fit that names its `fastener` by hand (pins, a clip:
421
+ anything that is not a screw, since a screw is a `fasten`'s, which knows its length). They are
403
422
  summed by name, which is the thread, length and head (`12 × M3x8 cap`), each with its mass (an estimate from its
404
423
  outline, from `@rulecad/fixings`) and the line's, and rounded up to whole packs of `packs.pack` (10, an estimate:
405
424
  set your own in `rules/packs.json`) with the spares said. `--json` gives each line as `{ fastener, qty, kind,
@@ -469,8 +488,8 @@ then y, then z, as `rotate` does.
469
488
  (`planetary.phase`: planets go every 360° / n, and (S + R) / n is whole). `planetary()` in `@rulecad/gears` finds
470
489
  teeth for a ratio.
471
490
  - **What holds each part:** in an assembly that moves, every part but the first turns or slides on a joint, or is
472
- fastened to the first through fits with `"fastens": true` (the pins, screws or press that do it, named in the fit's
473
- note): `{ "a": "ring", "b": "case", "fastens": true, "note": "Two push pins" }`. A part only placed somewhere is
491
+ fastened to the first: by a `fasten` where screws do it, or by a fit with `"fastens": true` where pins, a press or a
492
+ clip do (named in the fit's note): `{ "a": "ring", "b": "case", "fastens": true, "note": "Two push pins" }`. A part only placed somewhere is
474
493
  said (`assembly.loose`): a ring gear resting on its case would turn with its planets.
475
494
  - **Onto a shaft:** `{ "a": "arm", "b": "crank", "engage": "arm.thick" }` checks that a part slid onto a shaft, a pin or a
476
495
  peg goes that far onto it along the joint between them (`fit.engage`), not just against its end: an arm resting on
@@ -500,7 +519,7 @@ An item can be a motor instead of a printed object: `{ "id": "drive", "motor": {
500
519
  - A compound planetary is a `planetary` with `"output": { "ring", "planet", "teeth" }`: a second ring on the planets' second step, following them in phase.
501
520
  - `motor.torque`: what reaches the joint through the gears, against the load: a fail under 1 times, a warning under the margin. It says what its figures rest on. `motor.speed`: how fast it moves and how long its range takes. Stages pass on `stageEfficiency` of the power (0.95 a mesh, an estimate).
502
521
  - `motor.holds`: with the power on (holding torque, or stall torque) and off (detent torque, a built-in gearbox's friction, a worm that locks, gears under 50% efficient, or `"brake": "a ratchet and pawl"` on the joint). Dropping with the power off is a warning: it may be what you want.
503
- - `motor.mount`: the part a motor is fastened to (a `fastens` fit), read as drawn: how thick it is at the screw holes against the screws' size, and the screws' bearing on the plastic under the motor's full torque. Then the whole part bent, by FE on the part as drawn (cubes, two across the plate at the screws): the motor's weight at its centre, along `gravity` in the pose it's checked in, and its full torque (the larger of its working and holding torque), both carried into the plate where the screws clamp it. The part is held at the joint that carries it, if one does; else where it meets the printed parts it's fastened to that sit below it; failing both, on its lowest face. It reports how far the shaft's tip moves (against the driven joint's seat, where that is on the same part, since the two move together), against the printer's `fit` clearance (or the motor's `"deflection"` in mm), and the peak stress against the material's `strength`; under 2 times either fails, and says what fixes it: the plate thickness that would do (bending goes with its cube), ribs, or how much stiffer a material would have to be. Cells this coarse read a plate 10 to 20% stiff, and a cell's stress is read at its centre, so the peak is scaled up to the surface; it's an estimate, said as one. Kept in `.cache/mount`.
522
+ - `motor.mount`: the part a motor is fastened to (a `fasten` into the motor, or a fit that `fastens`), read as drawn: how thick it is at the screw holes against the screws' size, the screws' engagement in the motor's tapped holes (the screws as bought: their length past the plate, held to the motor's `mount_hole_depth`, at least one diameter, `engagement.steel`, or it fails; a motor item's `"screw"` may name a whole screw, `"M3x8 cap"`, to check that one), and the screws' bearing on the plastic under the motor's full torque. Its screws are counted in `cad list` and `cad order` (at the length sold that stays in the motor's thread, with the key that turns them). Then the whole part bent, by FE on the part as drawn (cubes, two across the plate at the screws): the motor's weight at its centre, along `gravity` in the pose it's checked in, and its full torque (the larger of its working and holding torque), both carried into the plate where the screws clamp it. The part is held at the joint that carries it, if one does; else where it meets the printed parts it's fastened to that sit below it; failing both, on its lowest face. It reports how far the shaft's tip moves (against the driven joint's seat, where that is on the same part, since the two move together), against the printer's `fit` clearance (or the motor's `"deflection"` in mm), and the peak stress against the material's `strength`; under 2 times either fails, and says what fixes it: the plate thickness that would do (bending goes with its cube), ribs, or how much stiffer a material would have to be. Cells this coarse read a plate 10 to 20% stiff, and a cell's stress is read at its centre, so the peak is scaled up to the surface; it's an estimate, said as one. Kept in `.cache/mount`.
504
523
  - `motor.heat`: the motor's case against the softening point of the material the project prints in. Too hot says the current to set the driver to.
505
524
  - A `"shaft": true` fit (or `"press"`) between a motor and what it drives reads the bore from the part as drawn: that it's on the shaft (`shaft.seat`), that its flat is there (`shaft.flat`; the shaft turns to meet it, so where the flat faces doesn't matter), how much of the flat it grips (`shaft.grip`), and, pressed on, the hoop stress in the hub (`shaft.hoop`).
506
525
  - `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.
@@ -558,7 +577,7 @@ address stands for the faces near it, as `item@anchor` does (`"within"`, 10 mm b
558
577
 
559
578
  Once an assembly is checked, these say how to make it. They all read the assembly itself, so they can't disagree with it.
560
579
 
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.
580
+ - `cad order <project>/<assembly>`: the order it goes together in, each step with the part and what fastens it. 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. What is not a screw (pins, a clip) is named on a fit that fastens: `"fastener": "push pin", "count": 2` puts it on the shopping list and the step. `--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.
562
581
  - `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.
563
582
  - `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
583
  - `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`).
package/TUTORIAL.md CHANGED
@@ -73,7 +73,7 @@ npx cad new home/hook
73
73
  ```
74
74
 
75
75
  That makes `projects/home/objects/hook.json` and `hook.js` from a template. Replace the `.json` with the hook's
76
- variables. The screw's sizes come from the `m4` rule set, which is copied into `rules/` the first time it is used:
76
+ variables. The screw's hole comes from the shape below, which asks `v.fixings` for it by the screw's thread:
77
77
 
78
78
  ```json projects/home/objects/hook.json
79
79
  {
@@ -81,33 +81,37 @@ variables. The screw's sizes come from the `m4` rule set, which is copied into `
81
81
  "name": "hook",
82
82
  "title": "Wall hook",
83
83
  "version": "0.1.0",
84
- "uses": ["x1c", "m4"],
84
+ "uses": ["x1c"],
85
85
  "material": "PETG",
86
86
  "orientation": "On its side, so the layers run along the arm and it can't snap off across them.",
87
87
  "variables": {
88
88
  "width": { "value": 20, "unit": "mm", "rule": "Wide enough for a coat's loop", "label": "Width", "show": true, "tweak": { "min": 10, "max": 60 } },
89
89
  "plate": { "value": 50, "unit": "mm", "rule": "The back plate: room for a screw above the arm", "label": "Plate", "show": true },
90
90
  "reach": { "value": 30, "unit": "mm", "rule": "How far the arm stands out from the wall", "label": "Reach", "show": true, "tweak": { "min": 15, "max": 60 } },
91
- "thick": { "value": "x1c.line * 10", "unit": "mm", "rule": "Ten print lines: stiff enough for a coat" },
92
- "hole": { "value": "m4.clearance + x1c.hole_comp", "unit": "mm", "rule": "An M4 screw's clearance hole, widened for how holes print", "interface": true }
91
+ "thick": { "value": "x1c.line * 10", "unit": "mm", "rule": "Ten print lines: stiff enough for a coat" }
93
92
  }
94
93
  }
95
94
  ```
96
95
 
97
96
  Then the shape. `main(v)` gets the variables as `v`, with the rule sets (`v.x1c.line`), print-aware shapes
98
- (`v.shapes`) and booleans (`v.ops`). Z is up and the bed is z = 0: draw the part the way it will print.
97
+ (`v.shapes`), screws, nuts and inserts (`v.fixings`) and booleans (`v.ops`). Z is up and the bed is z = 0: draw the
98
+ part the way it will print.
99
+
100
+ `v.fixings.hole('M4', ...)` is a clearance hole for an M4 screw, sized from the `m4` rule set: 4.5 mm, the normal
101
+ clearance ISO 273 gives, plus the printer's `x1c.hole_comp` (0.1 mm), since a printed hole comes out small. Lying on
102
+ its side, it is drawn as a teardrop, so its roof needs no support. The check says what it was drawn to.
99
103
 
100
104
  ```js projects/home/objects/hook.js
101
- // A wall hook: a back plate with a screw hole, and an arm. It lies on its side to print (z is its width).
105
+ // A wall hook: a back plate with a hole for an M4 screw, and an arm. It lies on its side to print (z is its width).
102
106
  import jscad from '@jscad/modeling'
103
107
  const { cuboid } = jscad.primitives
104
108
 
105
109
  export function main (v) {
106
110
  const plate = cuboid({ size: [v.plate, v.thick, v.width], center: [0, v.thick / 2, v.width / 2] })
107
111
  const arm = cuboid({ size: [v.thick, v.reach, v.width], center: [(v.thick - v.plate) / 2, v.thick + v.reach / 2, v.width / 2] })
108
- // a hole across the part as it prints: a teardrop, so its roof needs no support. It is a line longer than the
109
- // plate is thick, so it comes out of the back cleanly
110
- const screw = v.shapes.teardropHole({ d: v.hole, length: v.thick + v.x1c.line, at: [v.plate / 2 / 2, v.thick, v.width / 2], into: '-y' })
112
+ // the screw's hole across the part as it prints, from the plate's face out through its back: v.fixings sizes it
113
+ // from the thread's rule set and draws it as a teardrop, so its roof needs no support
114
+ const screw = v.fixings.hole('M4', { depth: v.thick, at: [v.plate / 2 / 2, v.thick, v.width / 2], into: '-y' })
111
115
  return v.ops.subtract(v.ops.union(plate, arm), screw)
112
116
  }
113
117
  ```
@@ -129,7 +133,8 @@ The check names mistakes rather than drawing something else. The ones everyone m
129
133
  |---|---|
130
134
  | a number in the `.js`: `v.plate / 4` | `numbers in hook.js that should be variables: line 10: 4` |
131
135
  | a variable that isn't there: `v.thik` | `v.thik: the design has no variable "thik" (did you mean "thick"?)` |
132
- | a rule that isn't there: `m4.clearence` | `"m4.clearence": no rule "clearence" in m4 (hook.json: variables.hole.value)` |
136
+ | a rule that isn't there: `x1c.lien` | `"x1c.lien": no rule "lien" in x1c (hook.json: variables.thick.value)` |
137
+ | a thread that isn't there: `v.fixings.hole('M44', ...)` | `fixingModel: no thread "M44" (did you mean M4?)`, with the threads there are |
133
138
  | a misspelt key in the `.json`: `"lable"` | `variables.thick.lable: not allowed here (did you mean "label"?)` |
134
139
  | nothing returned from `main` | `main() returned no shape: return a JSCAD solid, or named parts` |
135
140
 
@@ -153,7 +158,6 @@ npx cad new home/screw
153
158
  "version": "0.1.0",
154
159
  "role": "reference",
155
160
  "variables": {
156
- "d": { "value": 4, "unit": "mm", "rule": "An M4 screw's thread", "interface": true },
157
161
  "length": { "value": 16, "unit": "mm", "rule": "Long enough to go through the plate into a wall plug" },
158
162
  "sides": { "value": 32, "rule": "Sides drawn round the shank" }
159
163
  }
@@ -161,11 +165,13 @@ npx cad new home/screw
161
165
  ```
162
166
 
163
167
  ```js projects/home/objects/screw.js
164
- // An M4 screw's shank, lying along y: something the hook fits, not something to print.
168
+ // An M4 screw's shank, lying along y: something the hook fits, not something to print. Its diameter is the thread's
169
+ // own, from the same rule set as the hook's hole.
165
170
  import jscad from '@jscad/modeling'
166
171
 
167
172
  export function main (v) {
168
- return jscad.transforms.rotateX(Math.PI / 2, jscad.primitives.cylinder({ radius: v.d / 2, height: v.length, segments: v.sides }))
173
+ const thread = v.fixings.fixingModel('M4')
174
+ return jscad.transforms.rotateX(Math.PI / 2, jscad.primitives.cylinder({ radius: thread.major / 2, height: v.length, segments: v.sides }))
169
175
  }
170
176
  ```
171
177
 
@@ -199,8 +205,12 @@ Hook on its screw (fit: hook 0.1.0, screw 0.1.0)
199
205
  ✓ The screw in its hole: closest gap 0.295 mm
200
206
  ```
201
207
 
202
- Change `hole` in the hook to something too tight and the check fails with the number. That is the loop: rules, a
203
- shape from them, and a check against the thing it meets.
208
+ Ask `v.fixings` for an M3 hole in the hook and the check fails with the number: the M4 screw overlaps it. That is
209
+ the loop: rules, a shape from them, and a check against the thing it meets.
210
+
211
+ A screw that holds printed parts to each other gets more than a fit: a `fasten` says which parts it passes through
212
+ and what it ends in, and the check chooses its length, finds its holes, and puts it on the shopping list. The worked
213
+ examples screw a board into its case with one (chapter 6) and explain it in full in chapter 15.
204
214
 
205
215
  ## 7. Share it
206
216
 
package/bin/cad.mjs CHANGED
@@ -20,7 +20,7 @@ import { schemaFindings } from '../lib/schema.mjs';
20
20
  import { readJson } from '../lib/host.mjs';
21
21
  import { optimised, readProblem, analysePart, picture, problemFile } from '../lib/optimise.mjs';
22
22
  import { evaluate } from '../lib/rules.mjs';
23
- import { setVariables, addToAssembly, parseValue } from '../lib/edit.mjs';
23
+ import { setVariables, addToAssembly, fastenFromFitsEdit, 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';
@@ -47,7 +47,8 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
47
47
  cad agents AGENTS.md: how an AI agent should design in this workspace
48
48
  cad trust allow what this workspace's cad.config.json asks (no sandbox, its own targets)
49
49
  cad rules <project>/<object> every variable: value, the rule behind it, its source
50
- cad rules check [set …] rule sets held to what makes them traceable (exit 1 on a failure) [--json]
50
+ cad rules check [set …] rule sets held to what makes them traceable (exit 1 on a failure) [--json]; notes,
51
+ never failures: an alias in "interface", and what the kit's set has that your copy lacks
51
52
  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
53
  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
54
  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
@@ -57,6 +58,8 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
57
58
  cad add fasten <project>/<assembly> --screw "M3 cap" --through bracket --into base --at bracket.h1,bracket.h2
58
59
  a screwed joint (or --holes bracket.body for the part's own holes) [--nut [hex|square|lock]]
59
60
  [--washer] [--length 12] [--torque 0.5] [--note …]
61
+ cad add fasten <project>/<assembly> --from-fits a fasten in place of a holes fit and a fit that fastens the same parts
62
+ (the screw read from them, or --screw "M2 cap")
60
63
  cad why <project>/<object>.<name> what a value reads, down to the rules and their sources [--json] [--depth N]
61
64
  cad check <project>/<object> raw numbers in the design, then printability (exit 1 on a failure) [--json: findings as data]
62
65
  cad preview <project>/<object> six views as a PNG in .preview/ (prints the path); an assembly with a motor also gets
@@ -138,7 +141,7 @@ const OPTIONS = ['table', 'calibrate', 'check', 'turns', 'preview', 'gap', 'no-s
138
141
  'sweep', 'tol', 'trailer', 'ttl', 'version', 'watch', 'line',
139
142
  'unit', 'rule', 'label', 'from', 'out', // cad set, cad rules
140
143
  'a', 'b', 'min', 'max', 'poses', 'id', 'type', 'parent', 'child', 'follow', 'value', 'ratio', 'object', 'assembly', 'variant', 'rotate', 'to', 'roll', // cad add
141
- 'screw', 'through', 'into', 'holes', 'nut', 'washer', 'length', 'torque']; // cad add fasten
144
+ 'screw', 'through', 'into', 'holes', 'nut', 'washer', 'length', 'torque', 'from-fits']; // cad add fasten
142
145
  // What a command takes, where that isn't <project>/<object>
143
146
  const USAGE = { add: 'fit|joint|item|beam|loop|pose|fasten <project>/<assembly> --key value …', why: '<project>/<object>.<variable>', set: '<project>/<object> name=value …',
144
147
  optimise: '<project>/<problem>', optimize: '<project>/<problem>', history: '<project>[/<object>]', release: '<project>[/<object>] -m "what changed"',
@@ -147,7 +150,7 @@ const USAGE = { add: 'fit|joint|item|beam|loop|pose|fasten <project>/<assembly>
147
150
  const args = process.argv.slice(2);
148
151
  // Options that stand alone. Every other takes the value after it: --name value, or -m for one-letter names
149
152
  // (--sweep, --watch and --nut take one or not).
150
- const FLAGS = ['table', 'calibrate', 'check', 'preview', 'no-steps', 'all', 'dry-run', 'explode', 'force', 'fresh', 'json', 'long', 'md', 'new', 'no-models', 'no-pictures', 'no-rules', 'open', 'progress', 'push', 'short', 'washer'];
153
+ const FLAGS = ['table', 'calibrate', 'check', 'preview', 'no-steps', 'all', 'dry-run', 'explode', 'force', 'fresh', 'json', 'long', 'md', 'new', 'no-models', 'no-pictures', 'no-rules', 'open', 'progress', 'push', 'short', 'washer', 'from-fits'];
151
154
  const opt = (k) => {
152
155
  const i = args.findIndex((a) => a === `--${k}` || (k.length === 1 && a === `-${k}`));
153
156
  if (i < 0) return undefined;
@@ -349,9 +352,15 @@ function ruleSheets(what, names) {
349
352
  if (what === 'check') {
350
353
  // a set fails on a finding of level fail; a warning or a note is said and the set still passes
351
354
  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));
352
- if (opt('json')) console.log(JSON.stringify(results.map((r) => ({ name: r.name, findings: r.findings })), null, 2));
355
+ if (opt('json')) console.log(JSON.stringify(results.map((r) => ({ name: r.name, findings: r.findings, ...(r.notes ? { notes: r.notes } : {}) })), null, 2));
353
356
  else {
354
357
  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})`); }
358
+ // notes never fail: an alias names one line per set, what a copy lacks of the kit's set says it whole
359
+ for (const r of results.filter((x) => x.notes)) {
360
+ const alias = r.notes.filter((x) => x.code === 'rules.alias'), rest = r.notes.filter((x) => x.code !== 'rules.alias');
361
+ if (alias.length) console.log(`${r.name}: NOTE ${alias.map((x) => `${x.rule} is also read as ${x.values.alias}`).join(', ')} (rules.alias)`);
362
+ for (const x of rest) console.log(`${r.name}: NOTE ${x.text} (${x.code})`);
363
+ }
355
364
  console.log(`${results.length - bad.length} of ${results.length} rule sets pass${noted.length ? ` (${noted.length} with something to know)` : ''}`);
356
365
  }
357
366
  process.exitCode = bad.length ? 1 : 0;
@@ -609,6 +618,13 @@ async function editAssembly(what, ref) {
609
618
  } else if (what === 'item') entry = { ...text(['id', 'object', 'assembly', 'variant']), ...at(), ...(list('rotate') ? { rotate: list('rotate') } : {}),
610
619
  ...(typeof opt('set') === 'string' ? { set: Object.fromEntries(sets() && Object.entries(sets()).map(([k, v]) => [k, parseValue(v)])) } : {}) };
611
620
  else if (what === 'loop') entry = text(['a', 'b', 'label']);
621
+ else if (what === 'fasten' && opt('from-fits')) { // a holes fit and a fit that fastens, put as one fasten
622
+ const s = await buildAssembly(ref), { fastenFromFits } = await import('../lib/fasten.mjs');
623
+ const r = fastenFromFitsEdit(ref, fastenFromFits(s), { screw: typeof opt('screw') === 'string' ? opt('screw') : undefined });
624
+ if (opt('json')) return console.log(JSON.stringify(r));
625
+ for (const x of r.added) console.log(`added a fasten to ${path.relative(WS, r.file)} in place of its holes fit and its fit that fastens: ${JSON.stringify(x)}`);
626
+ return console.log(`check its screws: cad check ${ref}`);
627
+ }
612
628
  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 …]
613
629
  const names = (k) => (typeof opt(k) === 'string' ? opt(k).split(',').map((x) => x.trim()).filter(Boolean) : undefined);
614
630
  entry = { ...text(['screw']), through: names('through') ?? [], ...text(['into']), ...(names('at') ? { at: names('at') } : {}), ...text(['holes']), ...(opt('nut') ? { nut: opt('nut') === true ? true : String(opt('nut')) } : {}), ...(opt('washer') ? { washer: true } : {}), ...pick(['length', 'torque']), ...text(['note']) };
package/lib/assembly.mjs CHANGED
@@ -264,6 +264,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
264
264
  // Screwed joints: each screw followed through the parts as they stand, its hardware placed, and the joint counted as a
265
265
  // fit that fastens (what holds a part, what the order of assembly and the list read)
266
266
  let fastened = null;
267
+ if (a.fits?.some((x) => x.holes)) fastening ||= await import('./fasten.mjs'); // (a holes fit with a fit that fastens: the fasten that says both is suggested)
267
268
  if (a.fasten?.length && a.kind !== 'plate') {
268
269
  fastening ||= await import('./fasten.mjs');
269
270
  fastened = fastening.fastenOf({ a, project, parts, objects, motion, num }, worlds0, { access: pose === motion.pose });
@@ -925,6 +926,11 @@ export function checkAssembly(s) {
925
926
  }
926
927
  }
927
928
  if (s.a.fasten?.length && fastening) fastening.fastenChecks(s, f, { placeItems });
929
+ // A holes fit and a fit that fastens the same two items: one fasten says both, and knows the screw
930
+ if (fastening) for (const g of fastening.fastenFromFits(s)) {
931
+ f('info', `${g.label} and the fit that fastens ${g.pair[0]} to ${g.pair[1]} are one screwed joint: a fasten says both and knows the screw (its holes, length, thread engaged, the seat under its head and the key that turns it). In place of the two, add to "fasten": ${JSON.stringify(g.fasten)}${g.screw ? '' : ' (with the screw it takes: no thread was found in the fits or the holes)'}, or run cad add fasten ${s.project}/${s.name} --from-fits`,
932
+ null, { code: 'fasten.suggest', refs: { fits: [g.holes, g.fastens], items: g.pair, paste: g.fasten } });
933
+ }
928
934
  boughtFindings(s, f);
929
935
  beamFindings(s, f);
930
936
  massFinding(s, f);
package/lib/design.mjs CHANGED
@@ -241,7 +241,7 @@ export async function build(d, set = {}, { mirror = false } = {}) {
241
241
  // A JSCAD design runs in a sandbox (sandbox.mjs: another process that can't write files, start programs or reach
242
242
  // the network) unless the workspace trusts its designs; a board design runs here, with the board engine
243
243
  const pcb = object.engine === 'pcb' ? await pcbEngine() : null;
244
- let parts, board = null, read, mechanism = null, fixings = null;
244
+ let parts, board = null, read, mechanism = null, fixings = null, mounted = false;
245
245
  const optional = Object.keys(object.mirror || {}); // inputs only the on-screen copy has: main may ask for them when they aren't there
246
246
  const stages = stageStore();
247
247
  if (!pcb && sandboxed() && host.name === 'node') ({ parts, read, mechanism, fixings } = await runSandboxed(d, values, object.parts || {}, booleans(object), optional, stages, { frames: framed, fixings: fixed().context }).catch((e) => { throw syntaxAt(e, d); }));
@@ -255,7 +255,9 @@ export async function build(d, set = {}, { mirror = false } = {}) {
255
255
  });
256
256
  if (typeof mod.main !== 'function') throw new Error(`${path.relative(WS, d.js)} has no exported main(v)`);
257
257
  const ops = await shapes.ops(booleans(object)), df = (await import('./fixings.mjs')).designFixings({ ...fixed().context, ops }); // (loaded when a design is run here: the sandbox's runner has its own)
258
- const w = watch(values, { shapes, flexures, gears, motors, frames: designFrames(framed), fixings: df.fixings, ops, ...(pcb ? { pcb } : {}) }, optional);
258
+ // v.pcb.mount('M2', ...) reads the workspace's thread sets, as v.fixings does: such a build is known by them too
259
+ const engine = pcb ? { ...pcb, mount: (thread, x, y, o = {}) => { mounted = true; return pcb.mount(thread, x, y, { sets: fixed().context.sets, ...o }); } } : null;
260
+ const w = watch(values, { shapes, flexures, gears, motors, frames: designFrames(framed), fixings: df.fixings, ops, ...(engine ? { pcb: engine } : {}) }, optional);
259
261
  read = w.read;
260
262
  let made;
261
263
  try { ({ shapes: made, mechanism } = unpack(await mod.main(w.v))); } catch (e) { throw Object.assign(located(e, d.js, 'design.run'), { line: lineOf(e, pathToFileURL(d.js).href) || undefined }); }
@@ -277,9 +279,9 @@ export async function build(d, set = {}, { mirror = false } = {}) {
277
279
  for (const e of entries) if (read.has(e.name)) e.used = true;
278
280
  try {
279
281
  prune();
280
- host.writeText(hit, JSON.stringify({ used: entries.filter((e) => e.used).map((e) => e.name), parts: parts.map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) })), ...(board || {}), ...(mechanism ? { mechanism } : {}), ...(fixings ? { fixed: fixed().hash, fixings } : {}) }));
282
+ host.writeText(hit, JSON.stringify({ used: entries.filter((e) => e.used).map((e) => e.name), parts: parts.map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) })), ...(board || {}), ...(mechanism ? { mechanism } : {}), ...(fixings || mounted ? { fixed: fixed().hash } : {}), ...(fixings ? { fixings } : {}) }));
281
283
  } catch {} // a cache that can't be written is only slower
282
- return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash: known(fixings ? fixed().hash : null), ...(fixings ? { fixings } : {}), ...(board || {}), ...(mechanism ? { mechanism } : {}) };
284
+ return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash: known(fixings || mounted ? fixed().hash : null), ...(fixings ? { fixings } : {}), ...(board || {}), ...(mechanism ? { mechanism } : {}) };
283
285
  }
284
286
 
285
287
  // A cache keeps its most recently used files, about `keep` of them (an old version's builds go first)
package/lib/edit.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  // its schema, and an object's variables must still resolve. Used by cad set and cad add; a program can call them too.
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
- import { setAt, appendAt, getAt } from './jsonedit.mjs';
6
+ import { setAt, appendAt, getAt, removeAt } from './jsonedit.mjs';
7
7
  import { validate, schema } from './schema.mjs';
8
8
  import { CadError } from './errors.mjs';
9
9
  import { paths } from './workspace.mjs';
@@ -97,3 +97,28 @@ export function addToAssembly(ref, what, entry) {
97
97
  write(file, text, 'assembly');
98
98
  return { file };
99
99
  }
100
+
101
+ /**
102
+ * Put a fasten in place of each holes fit and the fit that fastens the same two items (as lib/fasten.mjs's fastenFromFits
103
+ * finds them): the holes fit goes, the fit that fastens goes too, or keeps its gap range (min, max) with "fastens",
104
+ * "fastener" and "count" taken off, and the fasten is added. A screw given replaces the one found.
105
+ * @param {string} ref project/assembly @param {{ fasten: object, holes: number, fastens: number }[]} found @param {{ screw?: string }} [options]
106
+ * @returns {{ file: string, added: object[] }}
107
+ */
108
+ export function fastenFromFitsEdit(ref, found, { screw } = {}) {
109
+ const file = assemblyFile(ref);
110
+ if (!found.length) throw new CadError('edit.nothing', `${ref} has no holes fit with a fit that fastens the same two items (and no fasten for them yet): nothing to put a fasten in place of`, { file });
111
+ let text = fs.readFileSync(file, 'utf8');
112
+ const fits = getAt(text, ['fits']), drop = new Set(), trim = new Set();
113
+ for (const g of found) { drop.add(g.holes); (fits[g.fastens].min != null || fits[g.fastens].max != null ? trim : drop).add(g.fastens); }
114
+ // last first, so the places of the others hold
115
+ for (const i of [...new Set([...drop, ...trim])].sort((a, b) => b - a)) {
116
+ if (drop.has(i)) { text = removeAt(text, ['fits', i]); continue; }
117
+ for (const k of ['count', 'fastener', 'fastens']) if (getAt(text, ['fits', i, k]) !== undefined) text = removeAt(text, ['fits', i, k]);
118
+ }
119
+ if (getAt(text, ['fasten']) === undefined) text = setAt(text, ['fasten'], []);
120
+ const added = found.map((g) => ({ ...g.fasten, ...(screw ? { screw } : {}) }));
121
+ for (const x of added) text = appendAt(text, ['fasten'], x);
122
+ write(file, text, 'assembly');
123
+ return { file, added };
124
+ }
package/lib/fasten.mjs CHANGED
@@ -11,7 +11,7 @@
11
11
  // as reference parts (hardware, below): faint, checked for overlap, and carried into previews and links.
12
12
  import crypto from 'node:crypto';
13
13
  import path from 'node:path';
14
- import { fixingsFor, DEFAULTS, screwGroup } from '@rulecad/fixings';
14
+ import { fixingsFor, DEFAULTS, screwGroup, parseName, threads } from '@rulecad/fixings';
15
15
  import { placeItems, jointValues } from '@rulecad/model-link';
16
16
  import { massesOf } from './loads.mjs';
17
17
  import { mountTorque } from './motors.mjs';
@@ -293,10 +293,11 @@ function fixingsOf(project) {
293
293
  if (bound.get(project)?.hash !== hash) bound.set(project, { hash, F: fixingsFor({ ...(Object.keys(context.sets).length ? { sets: context.sets } : {}), ...(context.printer ? { printer: context.printer } : {}) }), material: context.material, printer: context.printer?.name ?? 'x1c' });
294
294
  return bound.get(project);
295
295
  }
296
- // A piece of hardware as a part's shape, made once for each name: the light solid of @rulecad/fixings, its faces, a hash
296
+ // A piece of hardware as a part's shape, made once for each name: the light solid of @rulecad/fixings, its faces, a hash.
297
+ // m is a model (a screw) or a thread's name (a nut, a washer, an insert), so a thread's name is the key as it is
297
298
  const shapes = new Map();
298
299
  function shapeOf(F, kind, m, o) {
299
- const key = `${kind}:${m.name}:${JSON.stringify(o)}`;
300
+ const key = `${kind}:${typeof m === 'string' ? m : m.name}:${JSON.stringify(o)}`;
300
301
  if (!shapes.has(key)) {
301
302
  const g = F[kind](m, o), [p] = named({ body: g }, { body: { label: g.model.name } });
302
303
  shapes.set(key, { geometry: p.geometry, polygons: p.polygons, triangles: p.triangles, model: g.model, hash: `fixing:${crypto.createHash('sha256').update(JSON.stringify([key, p.polygons])).digest('hex').slice(0, 16)}` });
@@ -344,6 +345,9 @@ export function fastenOf(s, worlds, opts = {}) {
344
345
  if (!Array.isArray(through)) throw new Error(`${what}: "through" lists the parts the screw passes, in order from under its head (["bracket"])`);
345
346
  if (typeof x.into !== 'string' || !x.into) throw new Error(`${what}: "into" names the part the screw ends in`);
346
347
  const members = [...through, x.into].map((n) => { const ps = pick(n); if (!ps.length) throw new Error(`${what}: no part "${n}" (items: ${ids.join(', ')})`); return { name: n, parts: ps }; });
348
+ // A yoke (a screw through one cheek, what lies between, into the other) or a split clamp (across its own slot)
349
+ const yoke = through.length > 0 && through[0] === x.into;
350
+ if (yoke && x.holes != null) throw new Error(`${what}: a screw that ends in ${x.into}, the part under its head, is placed with "at": an anchor on each screw's axis, pointing from the head into the part`);
347
351
  if ((x.at == null) === (x.holes == null)) throw new Error(`${what}: give "at" (an anchor for each screw: ["${top(through[0] ?? x.into)}.h1"]) or "holes" (a part whose holes are the screws' places), one of the two`);
348
352
  if (x.nut != null && x.nut !== false && x.nut !== true && !NUTS.includes(x.nut)) throw new Error(`${what}: "nut" is true (a hexagon nut) or ${NUTS.join(', ')} (got ${JSON.stringify(x.nut)}): a slot nut comes with a frame's beam`);
349
353
  const wantNut = x.nut === true ? 'hex' : x.nut || null;
@@ -404,19 +408,31 @@ export function fastenOf(s, worlds, opts = {}) {
404
408
  try { const e = F.engagement(fx, { depth: 1, material: name }); return { name, cls: e.class, known: true }; } catch { return { name, cls: p.role === 'reference' ? null : 'plastic', known: false }; }
405
409
  };
406
410
  const drawn = (kind) => { try { return F.holeModel(fx, { kind }); } catch { return null; } };
407
- const clr = { close: drawn('close'), normal: drawn('clearance'), loose: drawn('loose') }, sizeTol = FASTEN.size.value;
411
+ const clr = { close: drawn('close'), normal: drawn('clearance'), loose: drawn('loose') }, clrOf = clr, sizeTol = FASTEN.size.value;
412
+ // A circuit board's holes are drilled by its fab, not printed: held to the thread's clearance holes as they stand
413
+ const drilled = (n) => (typeof fx.figures[n]?.value === 'number' ? { diameter: fx.figures[n].value, nominal: fx.figures[n].value, comp: 0, basis: { rule: `${fx.set}.${n}` } } : null);
414
+ const clrDrilled = { close: drilled('clearance_close'), normal: drilled('clearance'), loose: drilled('clearance_loose') };
415
+ const isBoard = (m) => m.parts.some((p) => s.objects.find((o) => o.id === p.leaf)?.built?.circuit);
408
416
 
409
417
  axes.forEach((ax, i) => {
410
418
  const sc = { index: i, name: ax.name, found: {}, hardware: [] }, say = (code, level, text, values) => { (sc.found[code] ||= []).push({ level, text, ...(values ? { values } : {}) }); };
411
419
  rel.screws.push(sc);
412
- // Which way the screw goes: from the part under its head towards the part it ends in (a set screw: against its anchor)
413
- const raw = members.map((m) => reach(along(m.parts, ax.O, ax.D, R, false)));
420
+ // Which way the screw goes: from the part under its head towards the part it ends in (a set screw: against its anchor).
421
+ // A yoke or a split clamp ends the screw in the part under its head: its first stretch of material from the head is
422
+ // that side, the rest the far side, and the anchor's axis says the way (from the head into the part)
423
+ const side = (j, segs) => {
424
+ if (!yoke || (j !== 0 && j !== members.length - 1)) return segs;
425
+ const on = (seg) => seg.solid || seg.hole, i = segs.findIndex(on); let e = i;
426
+ while (e >= 0 && e < segs.length && on(segs[e])) e++;
427
+ return i < 0 ? segs : j === 0 ? segs.slice(0, e) : segs.slice(e);
428
+ };
429
+ const raw = members.map((m, j) => reach(side(j, along(m.parts, ax.O, ax.D, R, false))));
414
430
  const missing = members.filter((_, j) => !raw[j]);
415
431
  sc.at = ax.O; sc.between = [ax.O, ax.O];
416
- if (missing.length) return say('fasten.holes', 'fail', `${missing.map((m) => m.name).join(' and ')} ${missing.length > 1 ? 'are' : 'is'} nowhere on the screw's axis (nothing of ${missing.length > 1 ? 'them' : 'it'} within ${mm(R)} mm of it): the parts are not where the joint needs them`);
417
- const mid = (r) => (r[0] + r[1]) / 2, flip = members.length > 1 ? mid(raw.at(-1)) < mid(raw[0]) : true;
432
+ if (missing.length) return say('fasten.holes', 'fail', `${missing.map((m) => m.name).join(' and ')} ${missing.length > 1 ? 'are' : 'is'} nowhere on the screw's axis (nothing of ${missing.length > 1 ? 'them' : 'it'} within ${mm(R)} mm of it)${yoke ? `: a screw that ends in ${x.into}, the part under its head, goes through one side of it and into the other, along its anchor's axis` : ': the parts are not where the joint needs them'}`);
433
+ const mid = (r) => (r[0] + r[1]) / 2, flip = yoke ? false : members.length > 1 ? mid(raw.at(-1)) < mid(raw[0]) : true;
418
434
  const D = flip ? ax.D.map((c) => -c) : ax.D, O = ax.O, at = (z) => add(O, D, z);
419
- const runs = members.map((m) => ({ ...m, segs: along(m.parts, O, ax.D, R, flip) }));
435
+ const runs = members.map((m, j) => ({ ...m, segs: side(j, along(m.parts, O, ax.D, R, flip)) }));
420
436
  for (const r of runs) r.reach = reach(r.segs);
421
437
  const order = runs.slice(1).find((r, j) => mid(r.reach) < mid(runs[j].reach));
422
438
  if (order) return say('fasten.holes', 'fail', `${order.name} lies before ${runs[runs.indexOf(order) - 1].name} along the screw: "through" lists the parts in order from under the head, and "into" comes last`);
@@ -458,7 +474,7 @@ export function fastenOf(s, worlds, opts = {}) {
458
474
  if (!holes.length) { say('fasten.holes', 'fail', `${r.name} has no hole on the screw's axis`); bad = true; continue; }
459
475
  const narrow = holes.reduce((m, seg) => (size(seg) < size(m) ? seg : m), holes[0]), d = size(narrow);
460
476
  for (const seg of holes) { const o = offAxis(seg); if (o != null && o > worst) worst = o; if (o != null && o > FASTEN.align.value) { say('fasten.holes', 'fail', `${r.name}'s hole is ${mm(o)} mm off the screw's axis: the holes do not line up`, { distance: r3(o) }); bad = true; break; } }
461
- cl.push({ name: r.name, d, free: 2 * Math.min(narrow.a.free, narrow.b.free) });
477
+ cl.push({ name: r.name, d, free: 2 * Math.min(narrow.a.free, narrow.b.free), board: isBoard(r) });
462
478
  }
463
479
  // The far end: the hole in the last part, from its mouth
464
480
  const first = B.segs.find((seg) => seg.solid || seg.hole);
@@ -494,11 +510,12 @@ export function fastenOf(s, worlds, opts = {}) {
494
510
  if (cl.length) {
495
511
  if (!clr.normal) say('fasten.clearance', 'info', `${fx.thread} has no clearance hole in its rule set (${fx.set}): the holes it passes are not held to one`);
496
512
  else for (const c of cl) {
513
+ const clr = c.board && clrDrilled.normal ? clrDrilled : clrOf, as = c.board && clrDrilled.normal ? 'as drilled' : 'as drawn';
497
514
  const lo = (clr.close ?? clr.normal).diameter, hi = (clr.loose ?? clr.normal).diameter, want = clr.normal, basis = `${want.basis.rule} ${mm(want.nominal)} mm${want.comp ? ` and ${printer}.hole_comp ${mm(want.comp)} mm` : ''}`;
498
515
  const values = { diameter: r3(c.d), wanted: want.diameter, least: lo, most: hi };
499
- if (c.d < lo - sizeTol) say('fasten.clearance', 'fail', `${c.name}'s hole measures ${mm(c.d)} mm where ${an(fx.thread)} ${fx.thread} screw passes through: a clearance hole should be ${mm(want.diameter)} mm as drawn (${basis}), ${mm(lo)} mm at the closest`, values);
500
- else if (c.d > hi + sizeTol) say('fasten.clearance', 'warn', `${c.name}'s hole measures ${mm(c.d)} mm, wider than the loosest clearance hole for ${fx.thread}, ${mm(hi)} mm as drawn: the screw does not place the part, and the head has less to sit on (${mm(want.diameter)} mm is the normal hole)`, values);
501
- else say('fasten.clearance', 'pass', `${c.name}'s hole measures ${mm(c.d)} mm, ${an(fx.thread)} ${fx.thread} clearance hole as drawn (${Math.abs(c.d - want.diameter) <= sizeTol ? basis : `between the close ${mm(lo)} mm and the loose ${mm(hi)} mm; the normal hole is ${mm(want.diameter)} mm`})`, values);
516
+ if (c.d < lo - sizeTol) say('fasten.clearance', 'fail', `${c.name}'s hole measures ${mm(c.d)} mm where ${an(fx.thread)} ${fx.thread} screw passes through: a clearance hole should be ${mm(want.diameter)} mm ${as} (${basis}), ${mm(lo)} mm at the closest`, values);
517
+ else if (c.d > hi + sizeTol) say('fasten.clearance', 'warn', `${c.name}'s hole measures ${mm(c.d)} mm, wider than the loosest clearance hole for ${fx.thread}, ${mm(hi)} mm ${as}: the screw does not place the part, and the head has less to sit on (${mm(want.diameter)} mm is the normal hole)`, values);
518
+ else say('fasten.clearance', 'pass', `${c.name}'s hole measures ${mm(c.d)} mm, ${an(fx.thread)} ${fx.thread} clearance hole ${as} (${Math.abs(c.d - want.diameter) <= sizeTol ? basis : `between the close ${mm(lo)} mm and the loose ${mm(hi)} mm; the normal hole is ${mm(want.diameter)} mm`})`, values);
502
519
  }
503
520
  }
504
521
  if (!end) return;
@@ -581,9 +598,14 @@ export function fastenOf(s, worlds, opts = {}) {
581
598
  }
582
599
 
583
600
  // fasten.engagement: thread engaged at the far end, against the rule for what it is in
584
- if (end.motor && form !== 'set') { const e = Math.max(0, Math.min(inEnd, end.depth)); say('fasten.engagement', 'pass', `${mm(e)} mm of ${x.into}'s own thread, ${mm(+(e / fx.pitch).toFixed(1))} turns of its ${mm(end.depth)} mm: a bought part's thread, held to its depth and to no engagement rule`, { engaged: r3(e), depth: end.depth, turns: +(e / fx.pitch).toFixed(1) }); }
601
+ if (end.motor && form !== 'set') { // a bought part's thread: held to its depth, and to the least engagement any metal is given (engagement.steel), as motor.mount is
602
+ const e = Math.max(0, Math.min(inEnd, end.depth)), least = r3(F.engagement(fx, { depth: 1, material: 'steel' }).need), turns = +(e / fx.pitch).toFixed(1), values = { engaged: r3(e), depth: end.depth, turns, least };
603
+ if (e >= least - EPS) say('fasten.engagement', 'pass', `${mm(e)} mm of ${x.into}'s own thread, ${mm(turns)} turns of its ${mm(end.depth)} mm: a bought part's thread, held to its depth and to the ${mm(least)} mm engagement.steel gives any metal`, values);
604
+ else say('fasten.engagement', 'fail', `${mm(e)} mm of ${x.into}'s own thread, ${mm(turns)} turns of its ${mm(end.depth)} mm: less than the ${mm(least)} mm engagement.steel gives any metal, so the thread strips before the screw holds. A longer screw, or a counterbore to sink its head`, values);
605
+ }
585
606
  else if (end.kind && need != null && form !== 'set') {
586
- const engaged = Math.max(0, Math.min(inEnd, avail)), ok = engaged >= need - EPS, values = { engaged: r3(engaged), need: r3(need), turns: +(engaged / fx.pitch).toFixed(1) };
607
+ // (held to the micron it is said in: the length was chosen from the stack rounded to the micron)
608
+ const engaged = Math.max(0, Math.min(inEnd, avail)), ok = r3(engaged) >= need - EPS, values = { engaged: r3(engaged), need: r3(need), turns: +(engaged / fx.pitch).toFixed(1) };
587
609
  const what2 = end.kind === 'nut' ? `its ${end.nut.model.name}, ${mm(avail)} mm high` : end.kind === 'insert' ? `the insert, ${mm(avail)} mm long` : `${intoMat.name ? `${intoMat.name}${intoMat.cls && intoMat.known ? ` (a${intoMat.cls === 'aluminium' ? 'n' : ''} ${intoMat.cls})` : ''}` : end.kind === 'pilot' ? 'plastic' : x.into}`;
588
610
  const rule = end.kind === 'nut' ? 'a nut wants its whole height engaged' : end.kind === 'insert' ? `fixings.insert_engagement asks a diameter of thread or the whole insert, ${mm(need)} mm` : end.kind === 'pilot' && fx.figures.pilot_depth ? `${fx.set}.pilot_depth asks ${mm(need)} mm` : `engagement.${end.kind === 'pilot' ? 'plastic' : intoMat.cls ?? 'plastic'} asks ${mm(need / fx.major)} diameters, ${mm(need)} mm`;
589
611
  if (ok) say('fasten.engagement', 'pass', `${mm(engaged)} mm of thread in ${what2}, ${mm(values.turns)} turns: ${rule}`, values);
@@ -822,3 +844,38 @@ export function fastenChecks(s, f, { placeItems }) {
822
844
  loadSays(s, f, rel, lead);
823
845
  }
824
846
  }
847
+
848
+ // ---------- the older forms, said as one fasten ----------
849
+ // A holes fit and a fit that fastens the same two items say apart what a fasten says at once. The screw is read from the
850
+ // fit's fastener ("M2x6"), else a thread set the holes fit's depth names (m2.insert_length), else the board's mounting
851
+ // holes as drawn: the largest metric thread narrower than the narrowest of them.
852
+ const metric = (t) => { const m = /^M(\d+(?:\.\d+)?)$/.exec(t); return m ? Number(m[1]) : null; };
853
+ function screwFrom(h, fit, s) {
854
+ try { const n = fit.fastener && parseName(String(fit.fastener)); if (n && (n.item === 'screw' || n.item === 'thread')) return `${n.thread}${n.length != null ? `x${n.length}` : ''} ${n.head ?? 'cap'}`; } catch {} // (a fastener in words, "Two push pins", names no thread)
855
+ let sets = {}; try { sets = fixingsContext({ project: s.project, dir: paths.project(s.project) }).context.sets; } catch {}
856
+ const known = threads({ sets }), set = /\b[mM](\d+(?:_\d+)?)\.\w/.exec([h.depth, h.ring].filter((x) => typeof x === 'string').join(' '));
857
+ if (set) { const t = `M${set[1].replace('_', '.')}`; if (known.includes(t)) return `${t} cap`; }
858
+ const board = s.objects.find((o) => o.id === top(h.holes))?.built, ds = (board?.circuit || []).filter((e) => e.type === 'pcb_hole' && !e.pcb_component_id).map((e) => e.hole_diameter).filter((d) => d > 0);
859
+ if (!ds.length) return null;
860
+ const d = Math.min(...ds), fit1 = known.filter((t) => metric(t) != null && metric(t) < d).sort((a, b) => metric(b) - metric(a))[0];
861
+ return fit1 ? `${fit1} cap` : null;
862
+ }
863
+
864
+ /**
865
+ * The fasten that would stand for each holes fit whose two items a fit that fastens also joins, and that no fasten
866
+ * names yet: the entry to paste, and where the two fits are in "fits".
867
+ * @param {{ a: object, project: string, objects: object[] }} s a built assembly
868
+ * @returns {{ fasten: object, holes: number, fastens: number, pair: string[], label: string, screw: string | null }[]}
869
+ */
870
+ export function fastenFromFits(s) {
871
+ const fits = s.a.fits || [], out = [], named = new Set((s.a.fasten || []).flatMap((x) => [...(x.through || []), x.into].map(top)));
872
+ fits.forEach((h, i) => {
873
+ if (!h.holes || !h.into || h.direction === 'up') return; // (screws from below: through and into the other way round, said by hand)
874
+ const pair = [top(h.holes), top(h.into)], same = (x) => typeof x.a === 'string' && typeof x.b === 'string' && [top(x.a), top(x.b)].sort().join() === [...pair].sort().join();
875
+ const k = fits.findIndex((x) => x.fastens && !x.holes && same(x));
876
+ if (k < 0 || pair.every((n) => named.has(n))) return;
877
+ const screw = screwFrom(h, fits[k], s), note = h.label || h.note || fits[k].note;
878
+ out.push({ fasten: { screw: screw ?? 'M3 cap', through: [h.holes], into: h.into, holes: h.holes, ...(note ? { note } : {}) }, holes: i, fastens: k, pair, label: h.label || `${h.holes} into ${h.into}`, screw });
879
+ });
880
+ return out;
881
+ }
package/lib/jsonedit.mjs CHANGED
@@ -88,3 +88,22 @@ function insert(text, s, key, value) {
88
88
  const after = last.end;
89
89
  return multi ? `${text.slice(0, after)},${eol}${indent}${piece}${text.slice(after)}` : `${text.slice(0, after)}, ${piece}${text.slice(after)}`;
90
90
  }
91
+
92
+ /**
93
+ * Remove the value at a path: a key from its object, or an entry from its array, with the comma and the line it was on.
94
+ * @param {string} text @param {(string | number)[]} path @returns {string}
95
+ */
96
+ export function removeAt(text, path) {
97
+ const s = find(text, path);
98
+ if (!s || !path.length) throw Object.assign(new Error(`no ${path.join('.') || 'value'} to remove`), { code: 'edit.path' });
99
+ const parent = find(text, path.slice(0, -1)), all = spans(text);
100
+ const members = all.filter((x) => x.path.length === path.length && same(x.path.slice(0, -1), parent.path)).sort((a, b) => a.start - b.start);
101
+ const keyed = text[parent.start] === '{';
102
+ // where a member starts: at its key in an object (the last "key" before its value), else at its value
103
+ const startOf = (m) => (keyed ? text.lastIndexOf(JSON.stringify(m.path.at(-1)), m.start) : m.start);
104
+ const k = members.findIndex((m) => same(m.path, path));
105
+ if (members.length === 1) return `${text.slice(0, parent.start + 1)}${text.slice(parent.end - 1)}`; // the only one: {} or []
106
+ // not the first: from the end of the one before (its comma, the line break) to this one's end; the first: to the next one's start
107
+ if (k > 0) return text.slice(0, members[k - 1].end) + text.slice(s.end);
108
+ return text.slice(0, startOf(s)) + text.slice(startOf(members[1]));
109
+ }
package/lib/list.mjs CHANGED
@@ -50,8 +50,8 @@ export function shoppingList(s) {
50
50
  const add = (name, n, from, more = {}) => { const line = fasteners.get(name) ?? { fastener: name, qty: 0, from: [], ...more }; line.qty += n; if (!line.from.includes(from)) line.from.push(from); fasteners.set(name, line); };
51
51
  for (const p of s.parts) if (p.hardware) { const h = p.hardware; add(h.name, 1, h.from ?? h.name, { kind: h.kind, thread: h.thread ?? null, length: h.length ?? null, head: h.head ?? null, grams: h.grams ?? null }); }
52
52
  for (const m of motorScrews(s, { placeItems, jointValues })) {
53
- let grams = null; try { grams = screwModel(m.thread, { length: m.length, head: 'cap', anyLength: true }).mass; } catch {}
54
- add(`${m.thread}x${m.length} cap`, m.count, `${m.item} on ${m.other} (its mount, a fit that fastens)`, { kind: 'screw', thread: m.thread, length: m.length, head: 'cap', grams });
53
+ let grams = null; try { grams = screwModel(m.thread, { length: m.length, head: m.head, anyLength: true }).mass; } catch {}
54
+ add(m.name, m.count, `${m.item} on ${m.other} (its mount, a fit that fastens)`, { kind: 'screw', thread: m.thread, length: m.length, head: m.head, grams });
55
55
  }
56
56
  for (const x of s.fits) if (x.fastener && x.fasten == null) add(x.fastener, x.count != null ? x.num(x.count) : 1, x.note || `${x.a} / ${x.b}`);
57
57
  // Rounded up to whole packs (packs.pack), the spares said