@rulecad/shapes 0.4.9 → 0.5.0

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/CHANGELOG.md CHANGED
@@ -4,6 +4,21 @@ What changed in each release, for someone upgrading a workspace. A **printed siz
4
4
  print (a hole's diameter, a seat's depth, a part's outline). Each release says whether any printed size moved, and
5
5
  why.
6
6
 
7
+ ## 0.5.0: an unused name removed; needs Node 22.13 or later, the version the kit is tested on
8
+
9
+ ### Changed
10
+
11
+ - A name the code never used is gone. No printed size moves, and nothing a design or a check does changes.
12
+
13
+ - @rulecad/shapes now states Node 22.13 or later in its `engines`, the same lowest Node as every rulecad package, and
14
+ the tests run on exactly Node 22.13.0 as well as the newest Node 24. Node 20 reached the end of its support on 30
15
+ April 2026, and the kit's packages stated five different lowest versions, some of them too low: on Node 20.6 to 20.9
16
+ `cad` stopped at start-up with "Unexpected token 'with'", and on Node 22.0 to 22.12 every `cad` command that runs a
17
+ design stops, because the sandbox designs run in cannot start there. npm gave no warning at install for either.
18
+
19
+ Upgrading: on a Node older than 22.13, npm now warns at install that this package needs Node 22.13; install Node 22.13
20
+ or later (24 recommended). Nothing else changes, and no printed size moves.
21
+
7
22
  ## 0.4.9: swept parts as regions
8
23
  ### Added
9
24
 
package/enclosure.mjs CHANGED
@@ -14,27 +14,54 @@
14
14
  // vents({ count, width, pitch, length, depth }) slots side by side along x, centred, each length long in z
15
15
  import jscad from '@jscad/modeling';
16
16
 
17
- const { polygon, roundedRectangle, rectangle, cuboid } = jscad.primitives, { extrudeLinear } = jscad.extrusions;
18
- const { translate, rotateX, rotateY } = jscad.transforms, { subtract, union } = jscad.booleans, { hull } = jscad.hulls;
17
+ const { polygon, roundedRectangle, rectangle, cuboid } = jscad.primitives,
18
+ { extrudeLinear } = jscad.extrusions;
19
+ const { translate, rotateX, rotateY } = jscad.transforms,
20
+ { subtract, union } = jscad.booleans,
21
+ { hull } = jscad.hulls;
19
22
  const THIN = 1e-3; // the height of a slice that hulls join into slopes
20
23
 
21
24
  /** A rectangle with rounded or cut corners, centred on 0. @returns {object} geom2 */
22
25
  export function outline(w, h, { round = 0, bevel = 0, segments = 32 } = {}) {
23
26
  if (!(w > 0) || !(h > 0)) throw new Error(`outline: ${w} × ${h} mm is not a shape`); // (NaN and missing too)
24
- if (round > 0) return roundedRectangle({ size: [w, h], roundRadius: Math.min(round, w / 2 - THIN, h / 2 - THIN), segments });
25
- if (bevel > 0) { const b = Math.min(bevel, w / 2, h / 2); return polygon({ points: [[-w / 2 + b, -h / 2], [w / 2 - b, -h / 2], [w / 2, -h / 2 + b], [w / 2, h / 2 - b], [w / 2 - b, h / 2], [-w / 2 + b, h / 2], [-w / 2, h / 2 - b], [-w / 2, -h / 2 + b]] }); }
27
+ if (round > 0)
28
+ return roundedRectangle({ size: [w, h], roundRadius: Math.min(round, w / 2 - THIN, h / 2 - THIN), segments });
29
+ if (bevel > 0) {
30
+ const b = Math.min(bevel, w / 2, h / 2);
31
+ return polygon({
32
+ points: [
33
+ [-w / 2 + b, -h / 2],
34
+ [w / 2 - b, -h / 2],
35
+ [w / 2, -h / 2 + b],
36
+ [w / 2, h / 2 - b],
37
+ [w / 2 - b, h / 2],
38
+ [-w / 2 + b, h / 2],
39
+ [-w / 2, h / 2 - b],
40
+ [-w / 2, -h / 2 + b],
41
+ ],
42
+ });
43
+ }
26
44
  return rectangle({ size: [w, h] });
27
45
  }
28
46
 
29
47
  // The outline moved in by d all round: a rounded corner keeps its centre, a cut corner its angle
30
- const inset = (o, d) => ({ ...o, width: o.width - d * 2, height: o.height - d * 2, round: o.round ? Math.max(o.round - d, 0) : 0, bevel: o.bevel ? Math.max(o.bevel - d * (2 - Math.SQRT2), 0) : 0 });
31
- const slice = (o, d, z0, z1 = z0 + THIN) => translate([0, 0, z0], extrudeLinear({ height: z1 - z0 }, outline(o.width - d * 2, o.height - d * 2, inset(o, d))));
48
+ const inset = (o, d) => ({
49
+ ...o,
50
+ width: o.width - d * 2,
51
+ height: o.height - d * 2,
52
+ round: o.round ? Math.max(o.round - d, 0) : 0,
53
+ bevel: o.bevel ? Math.max(o.bevel - d * (2 - Math.SQRT2), 0) : 0,
54
+ });
55
+ const slice = (o, d, z0, z1 = z0 + THIN) =>
56
+ translate([0, 0, z0], extrudeLinear({ height: z1 - z0 }, outline(o.width - d * 2, o.height - d * 2, inset(o, d))));
32
57
 
33
58
  /** A block on an outline, its lower and upper edges sloped in at 45 degrees by bottom and top. @returns {object} geom3 */
34
59
  export function slab({ width, height, depth, round = 0, bevel = 0, bottom = 0, top = 0, segments = 32 }) {
35
- for (const [k, v] of Object.entries({ width, height, depth })) if (!(typeof v === 'number' && v > 0)) throw new Error(`slab: ${k} is a size above 0 mm (got ${v})`);
60
+ for (const [k, v] of Object.entries({ width, height, depth }))
61
+ if (!(typeof v === 'number' && v > 0)) throw new Error(`slab: ${k} is a size above 0 mm (got ${v})`);
36
62
  const o = { width, height, round, bevel, segments };
37
- if (bottom + top >= depth) throw new Error(`slab: slopes of ${bottom} and ${top} mm need more than ${depth} mm of depth`);
63
+ if (bottom + top >= depth)
64
+ throw new Error(`slab: slopes of ${bottom} and ${top} mm need more than ${depth} mm of depth`);
38
65
  if (!bottom && !top) return slice(o, 0, 0, depth);
39
66
  return hull(slice(o, bottom, 0), slice(o, 0, bottom, depth - top), slice(o, top, depth - THIN));
40
67
  }
@@ -42,7 +69,10 @@ export function slab({ width, height, depth, round = 0, bevel = 0, bottom = 0, t
42
69
  /** A slab hollowed from floor up, open at the top; the walls wall thick. @returns {object} geom3 */
43
70
  export function shell({ wall, floor, ...o }) {
44
71
  const room = inset({ ...o, round: o.round || 0, bevel: o.bevel || 0 }, wall);
45
- return subtract(slab(o), translate([0, 0, floor], extrudeLinear({ height: o.depth }, outline(room.width, room.height, room))));
72
+ return subtract(
73
+ slab(o),
74
+ translate([0, 0, floor], extrudeLinear({ height: o.depth }, outline(room.width, room.height, room))),
75
+ );
46
76
  }
47
77
 
48
78
  /**
@@ -53,32 +83,54 @@ export function lid({ width, height, round = 0, bevel = 0, thick, edge = 0, wall
53
83
  const o = { width, height, round, bevel, segments };
54
84
  const plate = slab({ ...o, depth: thick, bottom: edge });
55
85
  if (!lip) return plate;
56
- const out = inset(o, wall + fit), hole = inset(o, wall + fit + ring);
86
+ const out = inset(o, wall + fit),
87
+ hole = inset(o, wall + fit + ring);
57
88
  const band = subtract(outline(out.width, out.height, out), outline(hole.width, hole.height, hole));
58
89
  return union(plate, translate([0, 0, thick], extrudeLinear({ height: lip }, band)));
59
90
  }
60
91
 
61
92
  /** A dovetail rail's profile (gap 0) or the slot that takes it (gap > 0), rising from y = 0, flanks at 45 degrees. */
62
93
  export function dovetail({ base, height, gap = 0 }) {
63
- const b = base / 2 + gap, t = b + height + (gap ? gap : 0), y = height + gap;
64
- return polygon({ points: [[-b, gap ? -1 : 0], [b, gap ? -1 : 0], [b, 0], [t, y], [-t, y], [-b, 0]] });
94
+ const b = base / 2 + gap,
95
+ t = b + height + (gap ? gap : 0),
96
+ y = height + gap;
97
+ return polygon({
98
+ points: [
99
+ [-b, gap ? -1 : 0],
100
+ [b, gap ? -1 : 0],
101
+ [b, 0],
102
+ [t, y],
103
+ [-t, y],
104
+ [-b, 0],
105
+ ],
106
+ });
65
107
  }
66
108
 
67
109
  /** A box [x0, x1] × [y0, y1] × [z0, z1] with a 45 degree gabled roof above z1, its ridge along axis ('x' or 'y'). */
68
110
  export function gabled([x0, x1], [y0, y1], [z0, z1], axis = 'y') {
69
- const box = (a0, a1, b0, b1, c0, c1) => translate([(a0 + a1) / 2, (b0 + b1) / 2, (c0 + c1) / 2], cuboid({ size: [a1 - a0, b1 - b0, c1 - c0] }));
70
- const half = axis === 'y' ? (x1 - x0) / 2 : (y1 - y0) / 2, mx = (x0 + x1) / 2, my = (y0 + y1) / 2;
71
- const ridge = axis === 'y' ? box(mx - THIN, mx + THIN, y0, y1, z1, z1 + half) : box(x0, x1, my - THIN, my + THIN, z1, z1 + half);
111
+ const box = (a0, a1, b0, b1, c0, c1) =>
112
+ translate([(a0 + a1) / 2, (b0 + b1) / 2, (c0 + c1) / 2], cuboid({ size: [a1 - a0, b1 - b0, c1 - c0] }));
113
+ const half = axis === 'y' ? (x1 - x0) / 2 : (y1 - y0) / 2,
114
+ mx = (x0 + x1) / 2,
115
+ my = (y0 + y1) / 2;
116
+ const ridge =
117
+ axis === 'y' ? box(mx - THIN, mx + THIN, y0, y1, z1, z1 + half) : box(x0, x1, my - THIN, my + THIN, z1, z1 + half);
72
118
  return hull(box(x0, x1, y0, y1, z0, z1), ridge);
73
119
  }
74
120
 
75
121
  /** A square hole size wide turned 45 degrees about axis, through length, centred on 0. */
76
122
  export function diamond(size, axis = 'y', length = 10) {
77
123
  const a = size / Math.SQRT2;
78
- return axis === 'y' ? rotateY(Math.PI / 4, cuboid({ size: [a, length, a] })) : rotateX(Math.PI / 4, cuboid({ size: [length, a, a] }));
124
+ return axis === 'y'
125
+ ? rotateY(Math.PI / 4, cuboid({ size: [a, length, a] }))
126
+ : rotateX(Math.PI / 4, cuboid({ size: [length, a, a] }));
79
127
  }
80
128
 
81
129
  /** Vent slots side by side along x, centred on 0: count of them, width wide, pitch apart, length long in z, depth in y. */
82
130
  export function vents({ count, width, pitch, length, depth }) {
83
- return union(...Array.from({ length: count }, (_, i) => translate([(i - (count - 1) / 2) * pitch, 0, 0], cuboid({ size: [width, depth, length] }))));
131
+ return union(
132
+ ...Array.from({ length: count }, (_, i) =>
133
+ translate([(i - (count - 1) / 2) * pitch, 0, 0], cuboid({ size: [width, depth, length] })),
134
+ ),
135
+ );
84
136
  }
package/features.mjs CHANGED
@@ -17,16 +17,24 @@
17
17
  // printer's bridge, a wider one rises at 45° each side to a flat that wide (height is the square part)
18
18
  import jscad from '@jscad/modeling';
19
19
 
20
- const { cylinder, cylinderElliptic, cuboid } = jscad.primitives, { translate, rotateX, rotateY, rotateZ } = jscad.transforms;
21
- const { hull } = jscad.hulls, { union } = jscad.booleans;
20
+ const { cylinder, cylinderElliptic, cuboid } = jscad.primitives,
21
+ { translate, rotateX, rotateY, rotateZ } = jscad.transforms;
22
+ const { hull } = jscad.hulls,
23
+ { union } = jscad.booleans;
22
24
  const TINY = 1e-3; // a slice's thickness, where a hull comes to a point
23
25
  const OUT = 0.1; // how far a cutter starts outside the face it enters by, so no faces lie on each other
24
26
  const EDGE = 0.05; // a ridge's width: a sharp point, without the slivers a vanishing one leaves
25
27
 
26
28
  // A cutter drawn going down from z = 0 (into = -z), turned to go along `into` from the origin, then moved to `at`
27
29
  function along(g, into, at = [0, 0, 0]) {
28
- const turn = { '-z': (x) => x, '+z': (x) => rotateX(Math.PI, x), '+x': (x) => rotateY(-Math.PI / 2, x), '-x': (x) => rotateY(Math.PI / 2, x),
29
- '+y': (x) => rotateX(Math.PI / 2, x), '-y': (x) => rotateX(-Math.PI / 2, x) }[into];
30
+ const turn = {
31
+ '-z': (x) => x,
32
+ '+z': (x) => rotateX(Math.PI, x),
33
+ '+x': (x) => rotateY(-Math.PI / 2, x),
34
+ '-x': (x) => rotateY(Math.PI / 2, x),
35
+ '+y': (x) => rotateX(Math.PI / 2, x),
36
+ '-y': (x) => rotateX(-Math.PI / 2, x),
37
+ }[into];
30
38
  if (!turn) throw new Error(`into must be +x, -x, +y, -y, +z or -z (got ${into})`);
31
39
  return translate(at, turn(g));
32
40
  }
@@ -37,27 +45,48 @@ const across = (into) => into in UP;
37
45
  // A round cutter from z = z0 down to z1, and its 45° ridge on the up side (r(z) the radius at each end)
38
46
  function tear(r0, r1, z0, z1, up) {
39
47
  // The ridge: a thin square turned 45° about the cutter's axis, its far corner at r√2, so the roof meets it at 45°
40
- const ridge = (r, z) => translate([up[0] * (r * Math.SQRT2 - EDGE / Math.SQRT2), up[1] * (r * Math.SQRT2 - EDGE / Math.SQRT2), z], rotateZ(Math.PI / 4, cuboid({ size: [EDGE, EDGE, TINY] })));
41
- const round = r0 === r1 ? translate([0, 0, (z0 + z1) / 2], cylinder({ radius: r0, height: Math.abs(z0 - z1), segments: 48 }))
42
- : translate([0, 0, (z0 + z1) / 2], cylinderElliptic({ height: Math.abs(z0 - z1), startRadius: [r1, r1], endRadius: [r0, r0], segments: 48 }));
48
+ const ridge = (r, z) =>
49
+ translate(
50
+ [up[0] * (r * Math.SQRT2 - EDGE / Math.SQRT2), up[1] * (r * Math.SQRT2 - EDGE / Math.SQRT2), z],
51
+ rotateZ(Math.PI / 4, cuboid({ size: [EDGE, EDGE, TINY] })),
52
+ );
53
+ const round =
54
+ r0 === r1
55
+ ? translate([0, 0, (z0 + z1) / 2], cylinder({ radius: r0, height: Math.abs(z0 - z1), segments: 48 }))
56
+ : translate(
57
+ [0, 0, (z0 + z1) / 2],
58
+ cylinderElliptic({ height: Math.abs(z0 - z1), startRadius: [r1, r1], endRadius: [r0, r0], segments: 48 }),
59
+ );
43
60
  return up ? hull(round, ridge(r0, z0), ridge(r1, z1)) : round;
44
61
  }
45
62
 
46
-
47
63
  // Sizes are lengths above 0: a feature given 0 or less (or nothing) says so by name, rather than drawing garbage
48
- function sizes(what, o) { for (const [k, v] of Object.entries(o)) if (!(typeof v === 'number' && v > 0)) throw new Error(`${what}: ${k} is a size above 0 mm (got ${v})`); }
64
+ function sizes(what, o) {
65
+ for (const [k, v] of Object.entries(o))
66
+ if (!(typeof v === 'number' && v > 0)) throw new Error(`${what}: ${k} is a size above 0 mm (got ${v})`);
67
+ }
49
68
 
50
69
  /** A flat-head screw's hole and 90° countersink, the head flush with the face at `at`. */
51
70
  export function countersink({ hole, head, length, at = [0, 0, 0], into = '-z', teardrop = across(into) }) {
52
71
  sizes('countersink', { hole, head, length });
53
- const up = teardrop ? UP[into] : null, cone = (head - hole) / 2;
54
- return along(union(tear(head / 2, head / 2, OUT, 0, up), tear(head / 2, hole / 2, 0, -cone, up), tear(hole / 2, hole / 2, -cone / 2, -length, up)), into, at); // overlapping, not touching: clean seams
72
+ const up = teardrop ? UP[into] : null,
73
+ cone = (head - hole) / 2;
74
+ return along(
75
+ union(
76
+ tear(head / 2, head / 2, OUT, 0, up),
77
+ tear(head / 2, hole / 2, 0, -cone, up),
78
+ tear(hole / 2, hole / 2, -cone / 2, -length, up),
79
+ ),
80
+ into,
81
+ at,
82
+ ); // overlapping, not touching: clean seams
55
83
  }
56
84
 
57
85
  /** A round hole across a part, with a 45° roof so it prints without support. */
58
86
  export function teardropHole({ d, length, at = [0, 0, 0], into = '+x', through = false }) {
59
87
  sizes('teardropHole', { d, length });
60
- if (!across(into)) throw new Error('teardropHole goes across a part: into ±x or ±y (a hole up or down is a plain cylinder)');
88
+ if (!across(into))
89
+ throw new Error('teardropHole goes across a part: into ±x or ±y (a hole up or down is a plain cylinder)');
61
90
  // through: out past the far face as it starts out past the near one, so a hole exactly as long as its wall leaves no
62
91
  // skin of faces lying on each other
63
92
  return along(tear(d / 2, d / 2, OUT, -length - (through ? OUT : 0), UP[into]), into, at);
@@ -73,28 +102,50 @@ export function nutPocket({ flats, height, hole, at = [0, 0, 0], into = '-z' })
73
102
  if (into !== '+z') return along(hex(pocket), into, at);
74
103
  // Going up from the bed face: a 45° hexagonal roof from the corners to the hole, so nothing spans
75
104
  const rise = corner - hole / 2;
76
- const roof = translate([0, 0, -height - rise / 2], cylinderElliptic({ height: rise, startRadius: [hole / 2, hole / 2], endRadius: [corner, corner], segments: 6 }));
105
+ const roof = translate(
106
+ [0, 0, -height - rise / 2],
107
+ cylinderElliptic({ height: rise, startRadius: [hole / 2, hole / 2], endRadius: [corner, corner], segments: 6 }),
108
+ );
77
109
  return along(union(pocket, roof), into, at);
78
110
  }
79
111
 
80
112
  /** Half-round crush ribs on a pocket's wall, for a press fit that takes a range of sizes. To add to the part. */
81
113
  export function crushRibs({ at, into, z, radius, protrude }) {
82
114
  sizes('crushRibs', { radius, protrude });
83
- return union(...at.map(([x, y], i) => {
84
- const [nx, ny] = into[i] || into[0], back = radius - protrude;
85
- return translate([x - nx * back, y - ny * back, (z[0] + z[1]) / 2], cylinder({ radius, height: z[1] - z[0], segments: 24 }));
86
- }));
115
+ return union(
116
+ ...at.map(([x, y], i) => {
117
+ const [nx, ny] = into[i] || into[0],
118
+ back = radius - protrude;
119
+ return translate(
120
+ [x - nx * back, y - ny * back, (z[0] + z[1]) / 2],
121
+ cylinder({ radius, height: z[1] - z[0], segments: 24 }),
122
+ );
123
+ }),
124
+ );
87
125
  }
88
126
 
89
127
  /** A square-cornered opening through an upright wall, centred on at (a cable's plug, a switch). */
90
128
  export function wallOpening({ width, height, depth, at = [0, 0, 0], into = '-y', bridge }) {
91
129
  sizes('wallOpening', { width, height, depth });
92
130
  if (!across(into)) throw new Error('wallOpening goes through an upright wall: into ±x or ±y');
93
- const long = depth + OUT, w = into.endsWith('x') ? [long, width, height] : [width, long, height], dir = into[0] === '+' ? 1 : -1;
94
- const off = into.endsWith('x') ? [dir * (depth - OUT) / 2, 0, 0] : [0, dir * (depth - OUT) / 2, 0];
131
+ const long = depth + OUT,
132
+ w = into.endsWith('x') ? [long, width, height] : [width, long, height],
133
+ dir = into[0] === '+' ? 1 : -1;
134
+ const off = into.endsWith('x') ? [(dir * (depth - OUT)) / 2, 0, 0] : [0, (dir * (depth - OUT)) / 2, 0];
95
135
  const box = cuboid({ size: w });
96
- if (bridge == null || width <= bridge) return translate(at.map((a, k) => a + off[k]), box);
136
+ if (bridge == null || width <= bridge)
137
+ return translate(
138
+ at.map((a, k) => a + off[k]),
139
+ box,
140
+ );
97
141
  // Wider than the printer bridges: the top rises at 45° each side to a flat as wide as it can span
98
- const rise = (width - bridge) / 2, top = translate([0, 0, height / 2 + rise], cuboid({ size: into.endsWith('x') ? [long, bridge, TINY] : [bridge, long, TINY] }));
99
- return translate(at.map((a, k) => a + off[k]), hull(box, top));
142
+ const rise = (width - bridge) / 2,
143
+ top = translate(
144
+ [0, 0, height / 2 + rise],
145
+ cuboid({ size: into.endsWith('x') ? [long, bridge, TINY] : [bridge, long, TINY] }),
146
+ );
147
+ return translate(
148
+ at.map((a, k) => a + off[k]),
149
+ hull(box, top),
150
+ );
100
151
  }
package/ops.mjs CHANGED
@@ -17,30 +17,64 @@ export async function ops(engine = 'jscad') {
17
17
  const stats = { ops: 0, fallbacks: 0 };
18
18
  const { union, subtract, intersect } = jscad.booleans;
19
19
  // (the gap between two solids needs Manifold: JSCAD has no distance query, so it says so by name)
20
- const noGap = () => { throw Object.assign(new Error('gap needs the manifold engine: ops(\'manifold\'), with manifold-3d installed'), { code: 'engine.gap' }); };
21
- if (engine === 'jscad') return { engine, stats, union: (...a) => (stats.ops++, union(...flat(a))), subtract: (...a) => (stats.ops++, subtract(...flat(a))), intersect: (...a) => (stats.ops++, intersect(...flat(a))), gap: noGap };
20
+ const noGap = () => {
21
+ throw Object.assign(new Error("gap needs the manifold engine: ops('manifold'), with manifold-3d installed"), {
22
+ code: 'engine.gap',
23
+ });
24
+ };
25
+ if (engine === 'jscad')
26
+ return {
27
+ engine,
28
+ stats,
29
+ union: (...a) => (stats.ops++, union(...flat(a))),
30
+ subtract: (...a) => (stats.ops++, subtract(...flat(a))),
31
+ intersect: (...a) => (stats.ops++, intersect(...flat(a))),
32
+ gap: noGap,
33
+ };
22
34
  if (engine !== 'manifold') throw new Error(`no boolean engine "${engine}" (jscad or manifold)`);
23
35
  let wasm;
24
- try { wasm = await (await import('manifold-3d')).default(); } catch (e) {
25
- throw Object.assign(new Error('the manifold engine needs manifold-3d: npm install manifold-3d (in the workspace)'), { code: 'engine.missing', cause: e });
36
+ try {
37
+ wasm = await (await import('manifold-3d')).default();
38
+ } catch (e) {
39
+ throw Object.assign(
40
+ new Error('the manifold engine needs manifold-3d: npm install manifold-3d (in the workspace)'),
41
+ { code: 'engine.missing', cause: e },
42
+ );
26
43
  }
27
44
  wasm.setup();
28
45
  const { Manifold, Mesh } = wasm;
29
46
  // JSCAD → Manifold: the shape's faces as triangles, corners shared where they meet
30
47
  const toManifold = (g) => {
31
- const verts = [], tris = [], index = new Map();
32
- const at = (v) => { const k = `${v[0]},${v[1]},${v[2]}`; if (!index.has(k)) { index.set(k, verts.length / 3); verts.push(v[0], v[1], v[2]); } return index.get(k); };
33
- for (const p of geom3.toPolygons(g)) { const ids = p.vertices.map(at); for (let i = 1; i < ids.length - 1; i++) tris.push(ids[0], ids[i], ids[i + 1]); }
48
+ const verts = [],
49
+ tris = [],
50
+ index = new Map();
51
+ const at = (v) => {
52
+ const k = `${v[0]},${v[1]},${v[2]}`;
53
+ if (!index.has(k)) {
54
+ index.set(k, verts.length / 3);
55
+ verts.push(v[0], v[1], v[2]);
56
+ }
57
+ return index.get(k);
58
+ };
59
+ for (const p of geom3.toPolygons(g)) {
60
+ const ids = p.vertices.map(at);
61
+ for (let i = 1; i < ids.length - 1; i++) tris.push(ids[0], ids[i], ids[i + 1]);
62
+ }
34
63
  const mesh = new Mesh({ numProp: 3, vertProperties: new Float32Array(verts), triVerts: new Uint32Array(tris) });
35
64
  mesh.merge();
36
65
  const m = new Manifold(mesh);
37
- if (m.status() !== 'NoError') { m.delete(); throw new Error(`not a closed solid (${m.status()})`); }
66
+ if (m.status() !== 'NoError') {
67
+ m.delete();
68
+ throw new Error(`not a closed solid (${m.status()})`);
69
+ }
38
70
  return m;
39
71
  };
40
72
  // Manifold → JSCAD: its triangles as faces
41
73
  const toGeom = (m) => {
42
- const { vertProperties: v, triVerts: t, numProp: n } = m.getMesh(), polys = [];
43
- for (let i = 0; i < t.length; i += 3) polys.push(poly3.create([t[i], t[i + 1], t[i + 2]].map((k) => [v[k * n], v[k * n + 1], v[k * n + 2]])));
74
+ const { vertProperties: v, triVerts: t, numProp: n } = m.getMesh(),
75
+ polys = [];
76
+ for (let i = 0; i < t.length; i += 3)
77
+ polys.push(poly3.create([t[i], t[i + 1], t[i + 2]].map((k) => [v[k * n], v[k * n + 1], v[k * n + 2]])));
44
78
  return geom3.create(polys);
45
79
  };
46
80
  const run = (name, jscadOp, list) => {
@@ -50,22 +84,48 @@ export async function ops(engine = 'jscad') {
50
84
  let made = [];
51
85
  try {
52
86
  made = shapes.map(toManifold);
53
- const out = name === 'union' ? Manifold.union(made) : name === 'intersect' ? Manifold.intersection(made)
54
- : made.slice(1).reduce((a, b) => { const r = a.subtract(b); if (a !== made[0]) a.delete(); return r; }, made[0]);
87
+ const out =
88
+ name === 'union'
89
+ ? Manifold.union(made)
90
+ : name === 'intersect'
91
+ ? Manifold.intersection(made)
92
+ : made.slice(1).reduce((a, b) => {
93
+ const r = a.subtract(b);
94
+ if (a !== made[0]) a.delete();
95
+ return r;
96
+ }, made[0]);
55
97
  const g = toGeom(out);
56
98
  if (!made.includes(out)) out.delete();
57
99
  return g;
58
100
  } catch {
59
101
  stats.fallbacks++;
60
102
  return jscadOp(...shapes);
61
- } finally { for (const m of made) m.delete(); }
103
+ } finally {
104
+ for (const m of made) m.delete();
105
+ }
62
106
  };
63
107
  // The least distance between two solids' surfaces, by Manifold's minGap, up to `within` mm (beyond it, within is
64
108
  // returned: nothing nearer). 0 when they touch or cross.
65
109
  const gap = (a, b, within = 1) => {
66
- if (!(typeof within === 'number' && within > 0)) throw new Error(`gap: within is how far to look, in mm above 0 (got ${JSON.stringify(within)})`);
67
- let ma = null, mb = null;
68
- try { ma = toManifold(a); mb = toManifold(b); return Math.max(0, ma.minGap(mb, within)); } finally { ma?.delete(); mb?.delete(); }
110
+ if (!(typeof within === 'number' && within > 0))
111
+ throw new Error(`gap: within is how far to look, in mm above 0 (got ${JSON.stringify(within)})`);
112
+ let ma = null,
113
+ mb = null;
114
+ try {
115
+ ma = toManifold(a);
116
+ mb = toManifold(b);
117
+ return Math.max(0, ma.minGap(mb, within));
118
+ } finally {
119
+ ma?.delete();
120
+ mb?.delete();
121
+ }
122
+ };
123
+ return {
124
+ engine,
125
+ stats,
126
+ union: (...a) => run('union', union, a),
127
+ subtract: (...a) => run('subtract', subtract, a),
128
+ intersect: (...a) => run('intersect', intersect, a),
129
+ gap,
69
130
  };
70
- return { engine, stats, union: (...a) => run('union', union, a), subtract: (...a) => run('subtract', subtract, a), intersect: (...a) => run('intersect', intersect, a), gap };
71
131
  }
package/optimised.mjs CHANGED
@@ -9,8 +9,11 @@
9
9
  // mesh is big: pass v.ops, with the object's engine set to manifold
10
10
  import jscad from '@jscad/modeling';
11
11
 
12
- const { geom2 } = jscad.geometries, { circle, rectangle, polygon, polyhedron, cuboid, cylinder, sphere } = jscad.primitives, { union, subtract } = jscad.booleans;
13
- const { rotateX, rotateY, rotateZ, translate } = jscad.transforms, { hull } = jscad.hulls;
12
+ const { geom2 } = jscad.geometries,
13
+ { circle, rectangle, polygon, polyhedron, cuboid, cylinder, sphere } = jscad.primitives,
14
+ { union, subtract } = jscad.booleans;
15
+ const { rotateX, rotateY, rotateZ, translate } = jscad.transforms,
16
+ { hull } = jscad.hulls;
14
17
 
15
18
  /**
16
19
  * Closed loops (solid on the left) as one JSCAD 2D shape.
@@ -44,7 +47,8 @@ export function regionShape(r, segments = 48) {
44
47
  */
45
48
  export function optimisedOutline(result, { segments = 48 } = {}) {
46
49
  let shape = fromOutlines(result.outlines);
47
- const keep = result.regions.keep.map((r) => regionShape(r, segments)).filter(Boolean), avoid = result.regions.avoid.map((r) => regionShape(r, segments)).filter(Boolean);
50
+ const keep = result.regions.keep.map((r) => regionShape(r, segments)).filter(Boolean),
51
+ avoid = result.regions.avoid.map((r) => regionShape(r, segments)).filter(Boolean);
48
52
  if (keep.length) shape = union(shape, ...keep);
49
53
  if (avoid.length) shape = subtract(shape, ...avoid);
50
54
  return shape;
@@ -60,8 +64,13 @@ export function solidRegion(r, segments = 48) {
60
64
  if (r.part || r.triangles) return null;
61
65
  if (r.size) return cuboid({ center: r.at, size: r.size });
62
66
  if (r.length != null) {
63
- const c = cylinder({ radius: r.r, height: r.length, segments }), axis = r.axis || 'z', ax = 'xyz'.indexOf(axis);
64
- const turned = translate(r.at, axis === 'x' ? rotateY(Math.PI / 2, c) : axis === 'y' ? rotateZ(Math.PI / 2, rotateY(Math.PI / 2, c)) : c);
67
+ const c = cylinder({ radius: r.r, height: r.length, segments }),
68
+ axis = r.axis || 'z',
69
+ ax = 'xyz'.indexOf(axis);
70
+ const turned = translate(
71
+ r.at,
72
+ axis === 'x' ? rotateY(Math.PI / 2, c) : axis === 'y' ? rotateZ(Math.PI / 2, rotateY(Math.PI / 2, c)) : c,
73
+ );
65
74
  // A teardrop (across the axis): the cylinder hulled with a thin ridge r√2 from its axis, below it (a boss) or
66
75
  // above it (a hole), so that side is 45°
67
76
  // The ridge: a thin slice of a square turned 45° about the axis at each end, its far corner a little past r√2: a
@@ -69,9 +78,17 @@ export function solidRegion(r, segments = 48) {
69
78
  // flatter than 45°
70
79
  const pa = r.teardrop ? 'xyz'.indexOf(r.teardrop[1]) : -1;
71
80
  if (pa < 0 || pa === ax) return turned;
72
- const edge = 0.05, slice = 1e-3, reach = (r.teardrop[0] === '-' ? -1 : 1) * (r.r * Math.SQRT2 / Math.cos(Math.PI / segments) - edge / Math.SQRT2);
73
- const square = [0, 1, 2].map((a) => (a === ax ? slice : edge)), spin = [rotateX, rotateY, rotateZ][ax];
74
- const end = (along) => translate(r.at.map((x, a) => x + (a === pa ? reach : 0) + (a === ax ? along : 0)), spin(Math.PI / 4, cuboid({ size: square })));
81
+ const edge = 0.05,
82
+ slice = 1e-3,
83
+ reach =
84
+ (r.teardrop[0] === '-' ? -1 : 1) * ((r.r * Math.SQRT2) / Math.cos(Math.PI / segments) - edge / Math.SQRT2);
85
+ const square = [0, 1, 2].map((a) => (a === ax ? slice : edge)),
86
+ spin = [rotateX, rotateY, rotateZ][ax];
87
+ const end = (along) =>
88
+ translate(
89
+ r.at.map((x, a) => x + (a === pa ? reach : 0) + (a === ax ? along : 0)),
90
+ spin(Math.PI / 4, cuboid({ size: square })),
91
+ );
75
92
  return hull(turned, end((slice - r.length) / 2), end((r.length - slice) / 2));
76
93
  }
77
94
  return sphere({ center: r.at, radius: r.r, segments });
@@ -85,7 +102,8 @@ export function solidRegion(r, segments = 48) {
85
102
  export function optimisedSolid(result, { ops, segments = 48 } = {}) {
86
103
  const o = ops || { union, subtract };
87
104
  let solid = polyhedron({ points: result.mesh.vertices, faces: result.mesh.faces, orientation: 'outward' });
88
- const keep = result.regions.keep.map((r) => solidRegion(r, segments)).filter(Boolean), avoid = result.regions.avoid.map((r) => solidRegion(r, segments)).filter(Boolean);
105
+ const keep = result.regions.keep.map((r) => solidRegion(r, segments)).filter(Boolean),
106
+ avoid = result.regions.avoid.map((r) => solidRegion(r, segments)).filter(Boolean);
89
107
  if (keep.length) solid = o.union(solid, ...keep);
90
108
  if (avoid.length) solid = o.subtract(solid, ...avoid);
91
109
  return solid;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/shapes",
3
- "version": "0.4.9",
3
+ "version": "0.5.0",
4
4
  "description": "Shape helpers for printed JSCAD designs: text that prints cleanly, anchors on a face, clean local cuts, and enclosure pieces (shells, lids, rails, print-safe holes).",
5
5
  "type": "module",
6
6
  "exports": {
@@ -8,21 +8,12 @@
8
8
  "default": "./shapes.mjs"
9
9
  },
10
10
  "files": [
11
- "shapes.mjs",
12
- "shapes.d.mts",
13
- "enclosure.mjs",
14
- "enclosure.d.mts",
11
+ "*.mjs",
12
+ "*.d.mts",
15
13
  "README.md",
16
14
  "CHANGELOG.md",
17
15
  "LICENSE",
18
- "features.mjs",
19
- "features.d.mts",
20
- "seats.mjs",
21
- "seats.d.mts",
22
- "ops.mjs",
23
- "ops.d.mts",
24
- "optimised.mjs",
25
- "optimised.d.mts"
16
+ "!test.mjs"
26
17
  ],
27
18
  "license": "MIT",
28
19
  "keywords": [
@@ -33,7 +24,7 @@
33
24
  "cad"
34
25
  ],
35
26
  "engines": {
36
- "node": ">=20"
27
+ "node": ">=22.13"
37
28
  },
38
29
  "sideEffects": false,
39
30
  "repository": {
@@ -49,7 +40,7 @@
49
40
  "test": "node --test"
50
41
  },
51
42
  "dependencies": {
52
- "@rulecad/variables": "^0.3.0"
43
+ "@rulecad/variables": "^0.4.0"
53
44
  },
54
45
  "peerDependencies": {
55
46
  "@jscad/modeling": "^2.12.0",
package/seats.d.mts CHANGED
@@ -42,7 +42,7 @@ export function bearingSeat(bearing: {
42
42
  bore: number;
43
43
  outer_diameter: number;
44
44
  width: number;
45
- }, { fit, lip, relief, through, into, lead, printer, at }?: {
45
+ }, { fit, lip, relief, through, into, lead, printer, at, }?: {
46
46
  fit?: "press" | "slip" | number;
47
47
  lip?: number;
48
48
  relief?: number;
package/seats.mjs CHANGED
@@ -10,34 +10,70 @@
10
10
  // clipGroove(shaft, { width, depth, at }) a ring to subtract from a printed shaft, stood up: flat below, sloped above
11
11
  import jscad from '@jscad/modeling';
12
12
 
13
- const { cylinder, cylinderElliptic, cuboid, polygon } = jscad.primitives, { translate, rotateX, rotateY, rotateZ } = jscad.transforms;
14
- const { hull } = jscad.hulls, { union } = jscad.booleans, { extrudeRotate } = jscad.extrusions;
15
- const OUT = 0.1, TINY = 1e-3, EDGE = 0.05, SEGMENTS = 64;
13
+ const { cylinder, cylinderElliptic, cuboid, polygon } = jscad.primitives,
14
+ { translate, rotateX, rotateY, rotateZ } = jscad.transforms;
15
+ const { hull } = jscad.hulls,
16
+ { union } = jscad.booleans,
17
+ { extrudeRotate } = jscad.extrusions;
18
+ const OUT = 0.1,
19
+ TINY = 1e-3,
20
+ EDGE = 0.05,
21
+ SEGMENTS = 64;
16
22
  const UP = { '+x': [1, 0], '-x': [-1, 0], '+y': [0, 1], '-y': [0, -1] };
17
23
 
18
24
  function along(g, into, at = [0, 0, 0]) {
19
- const turn = { '-z': (x) => x, '+z': (x) => rotateX(Math.PI, x), '+x': (x) => rotateY(-Math.PI / 2, x), '-x': (x) => rotateY(Math.PI / 2, x),
20
- '+y': (x) => rotateX(Math.PI / 2, x), '-y': (x) => rotateX(-Math.PI / 2, x) }[into];
25
+ const turn = {
26
+ '-z': (x) => x,
27
+ '+z': (x) => rotateX(Math.PI, x),
28
+ '+x': (x) => rotateY(-Math.PI / 2, x),
29
+ '-x': (x) => rotateY(Math.PI / 2, x),
30
+ '+y': (x) => rotateX(Math.PI / 2, x),
31
+ '-y': (x) => rotateX(-Math.PI / 2, x),
32
+ }[into];
21
33
  if (!turn) throw new Error(`into must be +x, -x, +y, -y, +z or -z (got ${into})`);
22
34
  return translate(at, turn(g));
23
35
  }
24
- function size(what, name, v, { zero = false } = {}) { if (!(typeof v === 'number' && Number.isFinite(v) && (zero ? v >= 0 : v > 0))) throw new Error(`${what}: ${name} is a size ${zero ? 'of 0 mm or more' : 'above 0 mm'} (got ${v})`); return v; }
36
+ function size(what, name, v, { zero = false } = {}) {
37
+ if (!(typeof v === 'number' && Number.isFinite(v) && (zero ? v >= 0 : v > 0)))
38
+ throw new Error(`${what}: ${name} is a size ${zero ? 'of 0 mm or more' : 'above 0 mm'} (got ${v})`);
39
+ return v;
40
+ }
25
41
  // A round cutter from z0 down to z1 (radius r0 to r1), with a 45° ridge on the up side when it goes across a part
26
42
  function tear(r0, r1, z0, z1, up) {
27
- const ridge = (r, z) => translate([up[0] * (r * Math.SQRT2 - EDGE / Math.SQRT2), up[1] * (r * Math.SQRT2 - EDGE / Math.SQRT2), z], rotateZ(Math.PI / 4, cuboid({ size: [EDGE, EDGE, TINY] })));
28
- const round = r0 === r1 ? translate([0, 0, (z0 + z1) / 2], cylinder({ radius: r0, height: Math.abs(z0 - z1), segments: SEGMENTS }))
29
- : translate([0, 0, (z0 + z1) / 2], cylinderElliptic({ height: Math.abs(z0 - z1), startRadius: [r1, r1], endRadius: [r0, r0], segments: SEGMENTS }));
43
+ const ridge = (r, z) =>
44
+ translate(
45
+ [up[0] * (r * Math.SQRT2 - EDGE / Math.SQRT2), up[1] * (r * Math.SQRT2 - EDGE / Math.SQRT2), z],
46
+ rotateZ(Math.PI / 4, cuboid({ size: [EDGE, EDGE, TINY] })),
47
+ );
48
+ const round =
49
+ r0 === r1
50
+ ? translate([0, 0, (z0 + z1) / 2], cylinder({ radius: r0, height: Math.abs(z0 - z1), segments: SEGMENTS }))
51
+ : translate(
52
+ [0, 0, (z0 + z1) / 2],
53
+ cylinderElliptic({
54
+ height: Math.abs(z0 - z1),
55
+ startRadius: [r1, r1],
56
+ endRadius: [r0, r0],
57
+ segments: SEGMENTS,
58
+ }),
59
+ );
30
60
  return up ? hull(round, ridge(r0, z0), ridge(r1, z1)) : round;
31
61
  }
32
62
  function printerOf(what, p) {
33
- if (!p || typeof p !== 'object') throw new Error(`${what}: give the printer's rules ({ printer: v.x1c }): the fit is theirs, so there are no numbers here`);
63
+ if (!p || typeof p !== 'object')
64
+ throw new Error(
65
+ `${what}: give the printer's rules ({ printer: v.x1c }): the fit is theirs, so there are no numbers here`,
66
+ );
34
67
  return p;
35
68
  }
36
69
  const FITS = ['press', 'slip'];
37
70
  function bearingOf(what, b) {
38
- if (!b || typeof b !== 'object') throw new Error(`${what}: give the bearing's rules ({ bore, outer_diameter, width }), not ${b}`);
39
- const outer = b.outer_diameter ?? b.outer, bore = size(what, 'bore', b.bore);
40
- if (!(size(what, 'outer_diameter', outer) > bore)) throw new Error(`${what}: the outer diameter (${outer}) is above the bore (${bore})`);
71
+ if (!b || typeof b !== 'object')
72
+ throw new Error(`${what}: give the bearing's rules ({ bore, outer_diameter, width }), not ${b}`);
73
+ const outer = b.outer_diameter ?? b.outer,
74
+ bore = size(what, 'bore', b.bore);
75
+ if (!(size(what, 'outer_diameter', outer) > bore))
76
+ throw new Error(`${what}: the outer diameter (${outer}) is above the bore (${bore})`);
41
77
  return { bore, outer, width: size(what, 'width', b.width) };
42
78
  }
43
79
 
@@ -52,17 +88,32 @@ function bearingOf(what, b) {
52
88
  * pocket: the diameter as drawn; relief: the diameter past the ledge; clearance: what's left across it once printed (below 0, a press)
53
89
  */
54
90
  export function seatSize(bearing, { fit = 'press', lip, printer } = {}) {
55
- const what = 'bearingSeat', b = bearingOf(what, bearing), p = printerOf(what, printer), comp = size(what, 'printer.hole_comp', p.hole_comp, { zero: true });
91
+ const what = 'bearingSeat',
92
+ b = bearingOf(what, bearing),
93
+ p = printerOf(what, printer),
94
+ comp = size(what, 'printer.hole_comp', p.hole_comp, { zero: true });
56
95
  let clearance;
57
96
  if (typeof fit === 'number') clearance = fit;
58
97
  else if (fit === 'press') clearance = -size(what, 'printer.press', p.press, { zero: true });
59
98
  else if (fit === 'slip') clearance = size(what, 'printer.slip', p.slip, { zero: true });
60
99
  else throw new Error(`${what}: fit is ${FITS.join(' or ')}, or a clearance in mm (got ${fit})`);
61
- const radial = (b.outer - b.bore) / 2, ledge = lip ?? radial / 4;
100
+ const radial = (b.outer - b.bore) / 2,
101
+ ledge = lip ?? radial / 4;
62
102
  size(what, 'lip', ledge);
63
- if (ledge > radial / 2) throw new Error(`${what}: a lip of ${ledge} mm reaches the inner race (the races are ${radial} mm deep together: ${radial / 2} mm at most)`);
103
+ if (ledge > radial / 2)
104
+ throw new Error(
105
+ `${what}: a lip of ${ledge} mm reaches the inner race (the races are ${radial} mm deep together: ${radial / 2} mm at most)`,
106
+ );
64
107
  const pocket = b.outer + comp + clearance;
65
- return { pocket: +pocket.toFixed(4), depth: b.width, relief: +(pocket - 2 * ledge).toFixed(4), lip: ledge, fit, clearance, comp };
108
+ return {
109
+ pocket: +pocket.toFixed(4),
110
+ depth: b.width,
111
+ relief: +(pocket - 2 * ledge).toFixed(4),
112
+ lip: ledge,
113
+ fit,
114
+ clearance,
115
+ comp,
116
+ };
66
117
  }
67
118
 
68
119
  /**
@@ -74,18 +125,61 @@ export function seatSize(bearing, { fit = 'press', lip, printer } = {}) {
74
125
  * relief: how far past the ledge (mm); through: run the relief out of the far face; lead: the lead-in chamfer at the mouth (none across a part, where its top half would overhang)
75
126
  * @returns {object} a JSCAD geom3 to subtract, with .seat holding seatSize's numbers
76
127
  */
77
- export function bearingSeat(bearing, { fit = 'press', lip, relief = 1, through = false, into = '-z', lead = UP[into] ? 0 : 0.4, printer, at = [0, 0, 0] } = {}) {
78
- const what = 'bearingSeat', s = seatSize(bearing, { fit, lip, printer });
79
- size(what, 'relief', relief); size(what, 'lead', lead, { zero: true });
80
- const R = s.pocket / 2, r = s.relief / 2, up = UP[into] ?? null, D = s.depth, past = D + relief + (through ? OUT : 0);
81
- if (up) { // across a part, a teardrop's roof on each step
128
+ export function bearingSeat(
129
+ bearing,
130
+ {
131
+ fit = 'press',
132
+ lip,
133
+ relief = 1,
134
+ through = false,
135
+ into = '-z',
136
+ lead = UP[into] ? 0 : 0.4,
137
+ printer,
138
+ at = [0, 0, 0],
139
+ } = {},
140
+ ) {
141
+ const what = 'bearingSeat',
142
+ s = seatSize(bearing, { fit, lip, printer });
143
+ size(what, 'relief', relief);
144
+ size(what, 'lead', lead, { zero: true });
145
+ const R = s.pocket / 2,
146
+ r = s.relief / 2,
147
+ up = UP[into] ?? null,
148
+ D = s.depth,
149
+ past = D + relief + (through ? OUT : 0);
150
+ if (up) {
151
+ // across a part, a teardrop's roof on each step
82
152
  const cuts = [tear(R, R, lead ? 0 : OUT, -D, up), tear(r, r, -D + EDGE, -past, up)];
83
153
  if (lead) cuts.push(tear(R + lead, R, 0, -lead, up), tear(R + lead, R + lead, OUT, 0, up));
84
154
  return Object.assign(along(union(cuts), into, at), { seat: s });
85
155
  }
86
156
  // Going up or down, one profile turned about the axis: no seams between the steps for a boolean to leak at
87
- const mouth = lead ? [[R + lead, OUT], [R + lead, 0], [R, -lead]] : [[R, OUT]], z0 = -D, floor = through ? Math.min(-past, -D - R) - OUT : -past;
88
- const inner = into === '+z' ? (through ? [[R, z0], [r, z0 - (R - r)], [r, floor]] : [[R, z0], [TINY, z0 - (R - TINY)]]) : [[R, z0], [r, z0], [r, -past]];
157
+ const mouth = lead
158
+ ? [
159
+ [R + lead, OUT],
160
+ [R + lead, 0],
161
+ [R, -lead],
162
+ ]
163
+ : [[R, OUT]],
164
+ z0 = -D,
165
+ floor = through ? Math.min(-past, -D - R) - OUT : -past;
166
+ const inner =
167
+ into === '+z'
168
+ ? through
169
+ ? [
170
+ [R, z0],
171
+ [r, z0 - (R - r)],
172
+ [r, floor],
173
+ ]
174
+ : [
175
+ [R, z0],
176
+ [TINY, z0 - (R - TINY)],
177
+ ]
178
+ : [
179
+ [R, z0],
180
+ [r, z0],
181
+ [r, -past],
182
+ ];
89
183
  const pts = [[0, OUT], ...mouth, ...inner, [0, inner.at(-1)[1]]].reverse();
90
184
  const turned = extrudeRotate({ segments: SEGMENTS }, polygon({ points: pts }));
91
185
  const g = along(turned, into, at);
@@ -99,8 +193,23 @@ export function bearingSeat(bearing, { fit = 'press', lip, relief = 1, through =
99
193
  * @type {Record<'slide' | 'press', { value: number, unit: string, rule: string, kind: string, source: string, checked: string }>}
100
194
  */
101
195
  export const SHAFT_FITS = {
102
- slide: { value: 0.05, unit: 'mm', rule: 'Gap each side of a shaft in its bore, with the printed hole\'s shrinkage allowed for, so it slides on and no more: a 5 mm D-shaft slides comfortably in a bore drawn 5.2 mm (0.05 each side and hole_comp 0.1), is tight in 5.1 mm and will not go in 5.0 mm', kind: 'measured', source: 'fit bar row 2, examples/bench/projects/benchmarks/MEASURE.md row 3, PLA on the X1C', checked: '2026-11-10' },
103
- press: { value: -0.02, unit: 'mm', rule: 'Each side of a shaft in a press-fit bore as printed: a hair tight, 0.8% strain on a 5 mm shaft, well inside what PLA stretches to before it cracks. A D flat does the driving. A bore drawn 5.06 mm for a 5 mm shaft falls between the fit bar\'s 5.1 mm (tight) and 5.0 mm (too tight)', kind: 'estimate', source: 'A reasoned guess, between the fit bar\'s tight and too tight bores (examples/bench/projects/benchmarks/MEASURE.md row 3); not yet pressed and turned under load', checked: '2026-11-10' }
196
+ slide: {
197
+ value: 0.05,
198
+ unit: 'mm',
199
+ rule: "Gap each side of a shaft in its bore, with the printed hole's shrinkage allowed for, so it slides on and no more: a 5 mm D-shaft slides comfortably in a bore drawn 5.2 mm (0.05 each side and hole_comp 0.1), is tight in 5.1 mm and will not go in 5.0 mm",
200
+ kind: 'measured',
201
+ source: 'fit bar row 2, examples/bench/projects/benchmarks/MEASURE.md row 3, PLA on the X1C',
202
+ checked: '2026-11-10',
203
+ },
204
+ press: {
205
+ value: -0.02,
206
+ unit: 'mm',
207
+ rule: "Each side of a shaft in a press-fit bore as printed: a hair tight, 0.8% strain on a 5 mm shaft, well inside what PLA stretches to before it cracks. A D flat does the driving. A bore drawn 5.06 mm for a 5 mm shaft falls between the fit bar's 5.1 mm (tight) and 5.0 mm (too tight)",
208
+ kind: 'estimate',
209
+ source:
210
+ "A reasoned guess, between the fit bar's tight and too tight bores (examples/bench/projects/benchmarks/MEASURE.md row 3); not yet pressed and turned under load",
211
+ checked: '2026-11-10',
212
+ },
104
213
  };
105
214
  const SHAFT_FIT_NAMES = ['slide', 'press', 'run'];
106
215
 
@@ -122,16 +231,31 @@ export function shaftBore(shaft, { fit = 'slide', across, printer, what = 'shaft
122
231
  size(what, 'shaft', shaft);
123
232
  // hole_comp may be below 0 here, for a printer whose holes come out large: motors' bore has always taken one
124
233
  const comp = p.hole_comp;
125
- if (!(typeof comp === 'number' && Number.isFinite(comp))) throw new Error(`${what}: printer.hole_comp is a number of mm, how much smaller across a printed hole comes out (got ${comp})`);
234
+ if (!(typeof comp === 'number' && Number.isFinite(comp)))
235
+ throw new Error(
236
+ `${what}: printer.hole_comp is a number of mm, how much smaller across a printed hole comes out (got ${comp})`,
237
+ );
126
238
  let each, kind;
127
- if (typeof fit === 'number') { if (!Number.isFinite(fit) || 2 * fit + comp <= -shaft) throw new Error(`${what}: a fit of ${fit} mm each side${comp < 0 ? ` and hole_comp ${comp}` : ''} leaves no bore for a ${shaft} mm shaft`); each = fit; kind = 'given'; }
128
- else if (fit === 'run') { each = size(what, 'printer.fit', p.fit); kind = 'derived'; }
129
- else if (typeof fit === 'string' && Object.hasOwn(SHAFT_FITS, fit)) { each = SHAFT_FITS[fit].value; kind = SHAFT_FITS[fit].kind; }
130
- else throw new Error(`${what}: fit is ${SHAFT_FIT_NAMES.join(', ')}, or a gap each side in mm (got ${fit})`);
239
+ if (typeof fit === 'number') {
240
+ if (!Number.isFinite(fit) || 2 * fit + comp <= -shaft)
241
+ throw new Error(
242
+ `${what}: a fit of ${fit} mm each side${comp < 0 ? ` and hole_comp ${comp}` : ''} leaves no bore for a ${shaft} mm shaft`,
243
+ );
244
+ each = fit;
245
+ kind = 'given';
246
+ } else if (fit === 'run') {
247
+ each = size(what, 'printer.fit', p.fit);
248
+ kind = 'derived';
249
+ } else if (typeof fit === 'string' && Object.hasOwn(SHAFT_FITS, fit)) {
250
+ each = SHAFT_FITS[fit].value;
251
+ kind = SHAFT_FITS[fit].kind;
252
+ } else throw new Error(`${what}: fit is ${SHAFT_FIT_NAMES.join(', ')}, or a gap each side in mm (got ${fit})`);
131
253
  const out = { diameter: +(shaft + 2 * each + comp).toFixed(4), each, comp, fit, kind };
132
- if (!(out.diameter > 0)) throw new Error(`${what}: hole_comp ${comp} leaves no bore for a ${shaft} mm shaft at ${fit}`);
254
+ if (!(out.diameter > 0))
255
+ throw new Error(`${what}: hole_comp ${comp} leaves no bore for a ${shaft} mm shaft at ${fit}`);
133
256
  if (across != null) {
134
- if (size(what, 'across', across) > shaft) throw new Error(`${what}: across the flat (${across}) is at most the shaft's diameter, ${shaft} mm`);
257
+ if (size(what, 'across', across) > shaft)
258
+ throw new Error(`${what}: across the flat (${across}) is at most the shaft's diameter, ${shaft} mm`);
135
259
  out.across = +(across + 2 * each + comp).toFixed(4);
136
260
  }
137
261
  return out;
@@ -147,17 +271,45 @@ export function shaftBore(shaft, { fit = 'slide', across, printer, what = 'shaft
147
271
  * side in mm, the same as a number for fit
148
272
  * @returns {object} a JSCAD geom3, with .bore the diameter as drawn and .clearance each side
149
273
  */
150
- export function plainBearing(shaft, { fit, clearance, length, wall, through = false, printer, at = [0, 0, 0], into = '-z', what = 'plainBearing' } = {}) {
274
+ export function plainBearing(
275
+ shaft,
276
+ { fit, clearance, length, wall, through = false, printer, at = [0, 0, 0], into = '-z', what = 'plainBearing' } = {},
277
+ ) {
151
278
  printerOf(what, printer);
152
- size(what, 'shaft', shaft); size(what, 'length', length);
153
- if (clearance != null && fit != null) throw new Error(`${what}: give fit or clearance, not both: a clearance is a fit in mm each side`);
279
+ size(what, 'shaft', shaft);
280
+ size(what, 'length', length);
281
+ if (clearance != null && fit != null)
282
+ throw new Error(`${what}: give fit or clearance, not both: a clearance is a fit in mm each side`);
154
283
  if (clearance != null) size(what, 'clearance', clearance);
155
- const b = shaftBore(shaft, { fit: clearance ?? fit ?? 'run', printer, what }), bore = b.diameter, gap = b.each;
156
- if (wall == null) return Object.assign(along(tear(bore / 2, bore / 2, OUT, -length - (through ? OUT : 0), UP[into] ?? null), into, at), { bore, clearance: gap, fit: b.fit, kind: b.kind });
284
+ const b = shaftBore(shaft, { fit: clearance ?? fit ?? 'run', printer, what }),
285
+ bore = b.diameter,
286
+ gap = b.each;
287
+ if (wall == null)
288
+ return Object.assign(
289
+ along(tear(bore / 2, bore / 2, OUT, -length - (through ? OUT : 0), UP[into] ?? null), into, at),
290
+ { bore, clearance: gap, fit: b.fit, kind: b.kind },
291
+ );
157
292
  size(what, 'wall', wall);
158
- if (UP[into]) throw new Error(`${what}: a bush with a wall prints standing up (into +z or -z): a tube on its side wouldn't print round. Bore across a part with no wall instead`);
159
- const outer = bore / 2 + wall, inner = bore / 2, chamfer = Math.min(0.4, wall / 2);
160
- const g = extrudeRotate({ segments: SEGMENTS }, polygon({ points: [[inner + chamfer, 0], [outer - chamfer, 0], [outer, chamfer], [outer, length], [inner, length], [inner, chamfer]] }));
293
+ if (UP[into])
294
+ throw new Error(
295
+ `${what}: a bush with a wall prints standing up (into +z or -z): a tube on its side wouldn't print round. Bore across a part with no wall instead`,
296
+ );
297
+ const outer = bore / 2 + wall,
298
+ inner = bore / 2,
299
+ chamfer = Math.min(0.4, wall / 2);
300
+ const g = extrudeRotate(
301
+ { segments: SEGMENTS },
302
+ polygon({
303
+ points: [
304
+ [inner + chamfer, 0],
305
+ [outer - chamfer, 0],
306
+ [outer, chamfer],
307
+ [outer, length],
308
+ [inner, length],
309
+ [inner, chamfer],
310
+ ],
311
+ }),
312
+ );
161
313
  return Object.assign(translate(at, g), { bore, clearance: gap, fit: b.fit, kind: b.kind });
162
314
  }
163
315
 
@@ -169,12 +321,31 @@ export function plainBearing(shaft, { fit, clearance, length, wall, through = fa
169
321
  * @returns {object} a JSCAD geom3 to add
170
322
  */
171
323
  export function shaftShoulder(shaft, { shoulder, height, at = [0, 0, 0] } = {}) {
172
- const what = 'shaftShoulder', a = size(what, 'shaft', shaft) / 2, b = size(what, 'shoulder', shoulder) / 2;
324
+ const what = 'shaftShoulder',
325
+ a = size(what, 'shaft', shaft) / 2,
326
+ b = size(what, 'shoulder', shoulder) / 2;
173
327
  size(what, 'height', height);
174
328
  if (b <= a) throw new Error(`${what}: the shoulder (${shoulder}) stands proud of the shaft (${shaft})`);
175
- if (height < b - a) throw new Error(`${what}: a ${shoulder} mm collar on a ${shaft} mm shaft is ${b - a} mm of 45° underside, and ${height} mm isn't enough to draw it`);
329
+ if (height < b - a)
330
+ throw new Error(
331
+ `${what}: a ${shoulder} mm collar on a ${shaft} mm shaft is ${b - a} mm of 45° underside, and ${height} mm isn't enough to draw it`,
332
+ );
176
333
  // the solid runs in to the axis, so it joins the shaft whatever the shaft is drawn as
177
- return translate(at, extrudeRotate({ segments: SEGMENTS }, polygon({ points: [[0, -height], [a - TINY, -height], [b, -height + (b - a) + TINY], [b, 0], [0, 0]] })));
334
+ return translate(
335
+ at,
336
+ extrudeRotate(
337
+ { segments: SEGMENTS },
338
+ polygon({
339
+ points: [
340
+ [0, -height],
341
+ [a - TINY, -height],
342
+ [b, -height + (b - a) + TINY],
343
+ [b, 0],
344
+ [0, 0],
345
+ ],
346
+ }),
347
+ ),
348
+ );
178
349
  }
179
350
 
180
351
  /**
@@ -185,13 +356,28 @@ export function shaftShoulder(shaft, { shoulder, height, at = [0, 0, 0] } = {})
185
356
  * @returns {object} a JSCAD geom3 to subtract, with .root the diameter at the groove's root
186
357
  */
187
358
  export function clipGroove(shaft, { width, depth, at = [0, 0, 0] } = {}) {
188
- const what = 'clipGroove', R = size(what, 'shaft', shaft) / 2;
189
- size(what, 'width', width); size(what, 'depth', depth);
190
- if (depth >= R / 2) throw new Error(`${what}: a groove ${depth} mm deep leaves too little of a ${shaft} mm shaft (under ${R / 2} mm)`);
191
- const r = R - depth, over = R + 1, rise = 1.2 * (over - r);
359
+ const what = 'clipGroove',
360
+ R = size(what, 'shaft', shaft) / 2;
361
+ size(what, 'width', width);
362
+ size(what, 'depth', depth);
363
+ if (depth >= R / 2)
364
+ throw new Error(`${what}: a groove ${depth} mm deep leaves too little of a ${shaft} mm shaft (under ${R / 2} mm)`);
365
+ const r = R - depth,
366
+ over = R + 1,
367
+ rise = 1.2 * (over - r);
192
368
  // The upper face is a little steeper than 45° (a slope of exactly the limit is an overhang by a hair, sliced). The
193
369
  // cutter's outside runs 1 mm past the shaft, with its slope carried on so the face is one line
194
- const g = extrudeRotate({ segments: SEGMENTS }, polygon({ points: [[r, 0], [over, 0], [over, width + rise], [r, width]] }));
370
+ const g = extrudeRotate(
371
+ { segments: SEGMENTS },
372
+ polygon({
373
+ points: [
374
+ [r, 0],
375
+ [over, 0],
376
+ [over, width + rise],
377
+ [r, width],
378
+ ],
379
+ }),
380
+ );
195
381
  return Object.assign(translate(at, g), { root: 2 * r });
196
382
  }
197
383
 
@@ -202,10 +388,26 @@ export function clipGroove(shaft, { width, depth, at = [0, 0, 0] } = {}) {
202
388
  * @param {{ fit?: 'press' | 'slip' | number, clearance?: number, through?: boolean, printer: object, at?: number[], into?: string }} o clearance: round the rod, each side
203
389
  * @returns {object} a JSCAD geom3 to subtract, with .pocket the diameter as drawn
204
390
  */
205
- export function lm8uuPocket(bearing, { fit = 'press', clearance = 1, through = false, printer, at = [0, 0, 0], into = '-z' } = {}) {
206
- const what = 'lm8uuPocket', p = printerOf(what, printer), L = size(what, 'length', bearing?.length), s = seatSize({ bore: bearing?.bore, outer_diameter: bearing?.outer_diameter, width: L }, { fit, printer: p, lip: 0.01 }), up = UP[into] ?? null, R = s.pocket / 2, rod = bearing.bore / 2 + clearance;
391
+ export function lm8uuPocket(
392
+ bearing,
393
+ { fit = 'press', clearance = 1, through = false, printer, at = [0, 0, 0], into = '-z' } = {},
394
+ ) {
395
+ const what = 'lm8uuPocket',
396
+ p = printerOf(what, printer),
397
+ L = size(what, 'length', bearing?.length),
398
+ s = seatSize(
399
+ { bore: bearing?.bore, outer_diameter: bearing?.outer_diameter, width: L },
400
+ { fit, printer: p, lip: 0.01 },
401
+ ),
402
+ up = UP[into] ?? null,
403
+ R = s.pocket / 2,
404
+ rod = bearing.bore / 2 + clearance;
207
405
  const cuts = [tear(R, R, OUT, -L, up)];
208
- if (into === '+z') { const rise = R - rod; cuts.push(tear(R, rod, -L, -L - rise)); cuts.push(tear(rod, rod, -L - rise / 2, -(L + rise + (through ? OUT : 2)))); } else cuts.push(tear(rod, rod, -L + EDGE, -(L + 2 + (through ? OUT : 0)), up));
406
+ if (into === '+z') {
407
+ const rise = R - rod;
408
+ cuts.push(tear(R, rod, -L, -L - rise));
409
+ cuts.push(tear(rod, rod, -L - rise / 2, -(L + rise + (through ? OUT : 2))));
410
+ } else cuts.push(tear(rod, rod, -L + EDGE, -(L + 2 + (through ? OUT : 0)), up));
209
411
  return Object.assign(along(union(cuts), into, at), { pocket: s.pocket, clearance: s.clearance });
210
412
  }
211
413
 
@@ -214,7 +416,10 @@ export function lm8uuPocket(bearing, { fit = 'press', clearance = 1, through = f
214
416
  function screwHole(what, given, part, comp) {
215
417
  if (given != null) return size(what, 'hole', given);
216
418
  const own = part.hole_diameter ?? part.mount_hole_diameter;
217
- if (own == null) throw new Error(`${what}: give the screws' hole as drawn ({ hole: fixings.holeModel('M3', { printer }).diameter }), or the part's own hole_diameter: there is no screw size here`);
419
+ if (own == null)
420
+ throw new Error(
421
+ `${what}: give the screws' hole as drawn ({ hole: fixings.holeModel('M3', { printer }).diameter }), or the part's own hole_diameter: there is no screw size here`,
422
+ );
218
423
  return size(what, 'hole_diameter', own) + comp;
219
424
  }
220
425
 
@@ -232,11 +437,32 @@ function screwHole(what, given, part, comp) {
232
437
  * @returns {object} a JSCAD geom3 to subtract, with .flange and .body the diameters as drawn, and .hole the screws' holes as drawn
233
438
  */
234
439
  export function nutTrap(nut, { fit, hole: hole_, printer, at = [0, 0, 0], depth } = {}) {
235
- const what = 'nutTrap', p = printerOf(what, printer), comp = size(what, 'printer.hole_comp', p.hole_comp, { zero: true }), gap = fit ?? 2 * size(what, 'printer.fit', p.fit), flange = size(what, 'flange_diameter', nut?.flange_diameter), body = size(what, 'body_diameter', nut.body_diameter), length = size(what, 'length', nut.length), circle = size(what, 'hole_circle', nut.hole_circle), n = size(what, 'hole_count', nut.hole_count);
440
+ const what = 'nutTrap',
441
+ p = printerOf(what, printer),
442
+ comp = size(what, 'printer.hole_comp', p.hole_comp, { zero: true }),
443
+ gap = fit ?? 2 * size(what, 'printer.fit', p.fit),
444
+ flange = size(what, 'flange_diameter', nut?.flange_diameter),
445
+ body = size(what, 'body_diameter', nut.body_diameter),
446
+ length = size(what, 'length', nut.length),
447
+ circle = size(what, 'hole_circle', nut.hole_circle),
448
+ n = size(what, 'hole_count', nut.hole_count);
236
449
  const hole = screwHole(what, hole_, nut, comp);
237
- const t = nut.flange_thickness ?? nut.flange_width ?? 3.5, D = depth ?? length, r = (body + comp + gap) / 2, R = (flange + comp + gap) / 2;
238
- if (circle / 2 + (hole - comp) / 2 > R + 0.01 || circle / 2 - (hole - comp) / 2 < r) throw new Error(`nutTrap: holes on a ${circle} mm circle don't fall between the ${body} mm body and the ${flange} mm flange`);
239
- const cuts = [tear(R, R, OUT, -t), tear(r, r, -t + EDGE, -D - OUT)], holes = Array.from({ length: n }, (_, i) => { const a = (i * 2 * Math.PI) / n; return translate([(circle / 2) * Math.cos(a), (circle / 2) * Math.sin(a), 0], tear(hole / 2, hole / 2, 0, -D - OUT)); });
450
+ const t = nut.flange_thickness ?? nut.flange_width ?? 3.5,
451
+ D = depth ?? length,
452
+ r = (body + comp + gap) / 2,
453
+ R = (flange + comp + gap) / 2;
454
+ if (circle / 2 + (hole - comp) / 2 > R + 0.01 || circle / 2 - (hole - comp) / 2 < r)
455
+ throw new Error(
456
+ `nutTrap: holes on a ${circle} mm circle don't fall between the ${body} mm body and the ${flange} mm flange`,
457
+ );
458
+ const cuts = [tear(R, R, OUT, -t), tear(r, r, -t + EDGE, -D - OUT)],
459
+ holes = Array.from({ length: n }, (_, i) => {
460
+ const a = (i * 2 * Math.PI) / n;
461
+ return translate(
462
+ [(circle / 2) * Math.cos(a), (circle / 2) * Math.sin(a), 0],
463
+ tear(hole / 2, hole / 2, 0, -D - OUT),
464
+ );
465
+ });
240
466
  return Object.assign(translate(at, union(...cuts, ...holes)), { flange: 2 * R, body: 2 * r, hole });
241
467
  }
242
468
 
@@ -248,8 +474,19 @@ export function nutTrap(nut, { fit, hole: hole_, printer, at = [0, 0, 0], depth
248
474
  * fit: as shaftBore (default slide); run, for an idler that turns on its axle
249
475
  * @returns {object} a JSCAD geom3 to subtract, with .bore the diameter as drawn and .clearance each side
250
476
  */
251
- export function pulleyBore(pulley, { length, fit = 'slide', printer, at = [0, 0, 0], into = '-z', through = false } = {}) {
252
- return plainBearing(size('pulleyBore', 'bore', pulley?.bore), { length, fit, printer, at, into, through, what: 'pulleyBore' });
477
+ export function pulleyBore(
478
+ pulley,
479
+ { length, fit = 'slide', printer, at = [0, 0, 0], into = '-z', through = false } = {},
480
+ ) {
481
+ return plainBearing(size('pulleyBore', 'bore', pulley?.bore), {
482
+ length,
483
+ fit,
484
+ printer,
485
+ at,
486
+ into,
487
+ through,
488
+ what: 'pulleyBore',
489
+ });
253
490
  }
254
491
 
255
492
  /**
@@ -259,9 +496,22 @@ export function pulleyBore(pulley, { length, fit = 'slide', printer, at = [0, 0,
259
496
  * @returns {object} a JSCAD geom3 to add, x along the belt, z up
260
497
  */
261
498
  export function beltClamp(belt, { length, height, wall, at = [0, 0, 0] } = {}) {
262
- const what = 'beltClamp', pitch = size(what, 'pitch', belt?.pitch), width = size(what, 'width', belt.width);
263
- size(what, 'length', length); size(what, 'height', height); size(what, 'wall', wall);
264
- const count = Math.floor(length / pitch), base = translate([0, 0, height / 2], cuboid({ size: [length, width + 2 * wall, height] })), teeth = [], tooth = pitch * 0.45;
265
- for (let i = 0; i < count; i++) teeth.push(translate([-length / 2 + pitch * (i + 0.5), 0, height + 0.375], cuboid({ size: [tooth, width + 2 * wall, 0.75] })));
499
+ const what = 'beltClamp',
500
+ pitch = size(what, 'pitch', belt?.pitch),
501
+ width = size(what, 'width', belt.width);
502
+ size(what, 'length', length);
503
+ size(what, 'height', height);
504
+ size(what, 'wall', wall);
505
+ const count = Math.floor(length / pitch),
506
+ base = translate([0, 0, height / 2], cuboid({ size: [length, width + 2 * wall, height] })),
507
+ teeth = [],
508
+ tooth = pitch * 0.45;
509
+ for (let i = 0; i < count; i++)
510
+ teeth.push(
511
+ translate(
512
+ [-length / 2 + pitch * (i + 0.5), 0, height + 0.375],
513
+ cuboid({ size: [tooth, width + 2 * wall, 0.75] }),
514
+ ),
515
+ );
266
516
  return translate(at, union(base, ...teeth));
267
517
  }
package/shapes.mjs CHANGED
@@ -10,15 +10,32 @@
10
10
  import jscad from '@jscad/modeling';
11
11
  import { ANCHORS } from '@rulecad/variables';
12
12
 
13
- const { vectorText } = jscad.text, { path2 } = jscad.geometries, { expand } = jscad.expansions, { circle } = jscad.primitives;
14
- const { union, subtract } = jscad.booleans, { translate, scale } = jscad.transforms, { measureBoundingBox } = jscad.measurements;
13
+ const { vectorText } = jscad.text,
14
+ { path2 } = jscad.geometries,
15
+ { expand } = jscad.expansions,
16
+ { circle } = jscad.primitives;
17
+ const { union, subtract } = jscad.booleans,
18
+ { scale } = jscad.transforms,
19
+ { measureBoundingBox } = jscad.measurements;
15
20
 
16
21
  // Arrows the font doesn't have, as lines in a box height tall: a shaft and a head, pointing up, then turned
17
22
  const ARROWS = { '↑': 0, '→': -90, '↓': 180, '←': 90 };
18
23
  function arrow(char, height) {
19
- const h = height / 2, head = height * 0.35, turn = (ARROWS[char] * Math.PI) / 180;
24
+ const h = height / 2,
25
+ head = height * 0.35,
26
+ turn = (ARROWS[char] * Math.PI) / 180;
20
27
  const r = ([x, y]) => [x * Math.cos(turn) - y * Math.sin(turn), x * Math.sin(turn) + y * Math.cos(turn)];
21
- return [[[0, -h], [0, h]], [[-head, h - head], [0, h], [head, h - head]]].map((l) => l.map(r));
28
+ return [
29
+ [
30
+ [0, -h],
31
+ [0, h],
32
+ ],
33
+ [
34
+ [-head, h - head],
35
+ [0, h],
36
+ [head, h - head],
37
+ ],
38
+ ].map((l) => l.map(r));
22
39
  }
23
40
 
24
41
  /**
@@ -28,15 +45,23 @@ function arrow(char, height) {
28
45
  */
29
46
  export function text({ text: input, height, stroke, segments = 8 }) {
30
47
  if (!input) throw new Error('text: nothing to write');
31
- if (!(height > 0) || !(stroke > 0)) throw new Error(`text: height and stroke are sizes above 0 mm (got ${height} and ${stroke})`);
32
- if (input in ARROWS) return union(...arrow(input, height).map((l) => expand({ delta: stroke / 2, corners: 'round', segments }, path2.fromPoints({}, l))));
48
+ if (!(height > 0) || !(stroke > 0))
49
+ throw new Error(`text: height and stroke are sizes above 0 mm (got ${height} and ${stroke})`);
50
+ if (input in ARROWS)
51
+ return union(
52
+ ...arrow(input, height).map((l) =>
53
+ expand({ delta: stroke / 2, corners: 'round', segments }, path2.fromPoints({}, l)),
54
+ ),
55
+ );
33
56
  // One scale for every legend: a capital H is height tall, so a dash or a full stop stays small. Then centre the text
34
57
  // on its own outline, and thicken the lines (after scaling, so the stroke is exactly as wide as asked)
35
58
  const capital = measureBoundingBox(path2.fromPoints({}, vectorText({ height, input: 'H' }).flat()));
36
59
  const k = height / (capital[1][1] - capital[0][1] || 1);
37
60
  // The text in runs between arrows, each run as the font draws it, set one after another; each arrow drawn in a
38
61
  // capital's box between them (the font has none)
39
- const lines = [], gap = (capital[1][0] - capital[0][0]) * 0.3, mid = (capital[0][1] + capital[1][1]) / 2;
62
+ const lines = [],
63
+ gap = (capital[1][0] - capital[0][0]) * 0.3,
64
+ mid = (capital[0][1] + capital[1][1]) / 2;
40
65
  let x = 0;
41
66
  for (const run of input.split(/([↑→↓←])/).filter(Boolean)) {
42
67
  if (run in ARROWS) {
@@ -46,29 +71,42 @@ export function text({ text: input, height, stroke, segments = 8 }) {
46
71
  continue;
47
72
  }
48
73
  const drawn = vectorText({ height, input: run }).filter((l) => l.length > 1);
49
- if (!drawn.length) { x += gap * 2; continue; } // (spaces)
50
- const [lo, hi] = measureBoundingBox(path2.fromPoints({}, drawn.flat())), lead = run.match(/^ */)[0].length;
74
+ if (!drawn.length) {
75
+ x += gap * 2;
76
+ continue;
77
+ } // (spaces)
78
+ const [lo, hi] = measureBoundingBox(path2.fromPoints({}, drawn.flat())),
79
+ lead = run.match(/^ */)[0].length;
51
80
  const at = x + lead * gap * 2 - lo[0];
52
81
  lines.push(...drawn.map((l) => l.map(([lx, ly]) => [lx + at, ly])));
53
- x = at + hi[0] + gap + (run.match(/ *$/)[0].length) * gap * 2;
82
+ x = at + hi[0] + gap + run.match(/ *$/)[0].length * gap * 2;
54
83
  }
55
84
  if (!lines.length) throw new Error(`text: the font has none of "${input}"`);
56
85
  const [lo, hi] = measureBoundingBox(path2.fromPoints({}, lines.flat()));
57
- const cx = (lo[0] + hi[0]) / 2, cy = (lo[1] + hi[1]) / 2;
86
+ const cx = (lo[0] + hi[0]) / 2,
87
+ cy = (lo[1] + hi[1]) / 2;
58
88
  // Each line, scaled; points closer than half a stroke are dropped (thickening them would fold the outline over itself),
59
89
  // and a line smaller than the stroke (a full stop's tiny loop) becomes a round dot
60
- const strokes = lines.map((l) => {
61
- const pts = l.map(([x, y]) => [(x - cx) * k, (y - cy) * k]), kept = [pts[0]];
62
- for (const p of pts.slice(1)) if (Math.hypot(p[0] - kept.at(-1)[0], p[1] - kept.at(-1)[1]) >= stroke / 2) kept.push(p);
63
- const span = Math.max(...[0, 1].map((i) => Math.max(...pts.map((p) => p[i])) - Math.min(...pts.map((p) => p[i]))));
64
- if (kept.length < 2 || span < stroke) {
65
- const c = [0, 1].map((i) => (Math.max(...pts.map((p) => p[i])) + Math.min(...pts.map((p) => p[i]))) / 2);
66
- return circle({ center: c, radius: Math.max(stroke * 0.75, (span + stroke) / 2), segments: segments * 2 });
67
- }
68
- // Each straight piece thickened on its own, then joined: thickening a whole line folds over itself at sharp turns
69
- // (the point of an M), which leaves holes
70
- return kept.slice(1).map((p, i) => expand({ delta: stroke / 2, corners: 'round', segments }, path2.fromPoints({}, [kept[i], p])));
71
- }).flat();
90
+ const strokes = lines
91
+ .map((l) => {
92
+ const pts = l.map(([x, y]) => [(x - cx) * k, (y - cy) * k]),
93
+ kept = [pts[0]];
94
+ for (const p of pts.slice(1))
95
+ if (Math.hypot(p[0] - kept.at(-1)[0], p[1] - kept.at(-1)[1]) >= stroke / 2) kept.push(p);
96
+ const span = Math.max(
97
+ ...[0, 1].map((i) => Math.max(...pts.map((p) => p[i])) - Math.min(...pts.map((p) => p[i]))),
98
+ );
99
+ if (kept.length < 2 || span < stroke) {
100
+ const c = [0, 1].map((i) => (Math.max(...pts.map((p) => p[i])) + Math.min(...pts.map((p) => p[i]))) / 2);
101
+ return circle({ center: c, radius: Math.max(stroke * 0.75, (span + stroke) / 2), segments: segments * 2 });
102
+ }
103
+ // Each straight piece thickened on its own, then joined: thickening a whole line folds over itself at sharp turns
104
+ // (the point of an M), which leaves holes
105
+ return kept
106
+ .slice(1)
107
+ .map((p, i) => expand({ delta: stroke / 2, corners: 'round', segments }, path2.fromPoints({}, [kept[i], p])));
108
+ })
109
+ .flat();
72
110
  return strokes.length > 1 ? union(...strokes) : strokes[0];
73
111
  }
74
112
 
@@ -80,8 +118,9 @@ export function text({ text: input, height, stroke, segments = 8 }) {
80
118
  */
81
119
  export function anchor({ width, depth }, [w, d], at = 'mc') {
82
120
  if (!ANCHORS.includes(at)) throw new Error(`anchor: one of ${ANCHORS.join(', ')} (got "${at}")`);
83
- const col = { l: -1, c: 0, r: 1 }[at[1]], row = { t: 1, m: 0, b: -1 }[at[0]];
84
- return [col * Math.max(width - w, 0) / 2, row * Math.max(depth - d, 0) / 2];
121
+ const col = { l: -1, c: 0, r: 1 }[at[1]],
122
+ row = { t: 1, m: 0, b: -1 }[at[0]];
123
+ return [(col * Math.max(width - w, 0)) / 2, (row * Math.max(depth - d, 0)) / 2];
85
124
  }
86
125
 
87
126
  // cut(a, b): a with b taken out, touching only a's faces near b. JSCAD's subtract splits every face of a along the
@@ -89,23 +128,44 @@ export function anchor({ width, depth }, [w, d], at = 'mc') {
89
128
  // above). Here the faces clear of b's box pass through unchanged, and only the rest are cut.
90
129
  /** a with b taken out, cutting only a's faces near b. @param {object} a JSCAD geom3 @param {object} b JSCAD geom3 @param {number} [margin] @returns {object} */
91
130
  export function cut(a, b, margin = 0.05) {
92
- const { geom3 } = jscad.geometries, [lo, hi] = measureBoundingBox(b);
93
- const near = [], far = [];
131
+ const { geom3 } = jscad.geometries,
132
+ [lo, hi] = measureBoundingBox(b);
133
+ const near = [],
134
+ far = [];
94
135
  for (const p of geom3.toPolygons(a)) {
95
- const vs = p.vertices, clear = [0, 1, 2].some((k) => Math.max(...vs.map((v) => v[k])) < lo[k] - margin || Math.min(...vs.map((v) => v[k])) > hi[k] + margin);
136
+ const vs = p.vertices,
137
+ clear = [0, 1, 2].some(
138
+ (k) => Math.max(...vs.map((v) => v[k])) < lo[k] - margin || Math.min(...vs.map((v) => v[k])) > hi[k] + margin,
139
+ );
96
140
  (clear ? far : near).push(p);
97
141
  }
98
- if (!near.length) { // nothing of a's surface near b: b is clear of a, or wholly inside it (a cavity), which only a whole subtract makes
142
+ if (!near.length) {
143
+ // nothing of a's surface near b: b is clear of a, or wholly inside it (a cavity), which only a whole subtract makes
99
144
  const [alo, ahi] = measureBoundingBox(a);
100
145
  return [0, 1, 2].every((k) => lo[k] > alo[k] && hi[k] < ahi[k]) ? subtract(a, b) : a;
101
146
  }
102
147
  return geom3.create([...far, ...geom3.toPolygons(subtract(geom3.create(near), b))]);
103
148
  }
104
149
 
105
- export const size = (g) => { const [lo, hi] = measureBoundingBox(g); return [hi[0] - lo[0], hi[1] - lo[1]]; };
150
+ export const size = (g) => {
151
+ const [lo, hi] = measureBoundingBox(g);
152
+ return [hi[0] - lo[0], hi[1] - lo[1]];
153
+ };
106
154
  export { scale };
107
155
  export { outline, slab, shell, lid, dovetail, gabled, diamond, vents } from './enclosure.mjs';
108
156
  export { countersink, teardropHole, nutPocket, crushRibs, wallOpening } from './features.mjs';
109
- export { seatSize, bearingSeat, shaftBore, SHAFT_FITS, plainBearing, shaftShoulder, clipGroove, lm8uuPocket, nutTrap, pulleyBore, beltClamp } from './seats.mjs';
157
+ export {
158
+ seatSize,
159
+ bearingSeat,
160
+ shaftBore,
161
+ SHAFT_FITS,
162
+ plainBearing,
163
+ shaftShoulder,
164
+ clipGroove,
165
+ lm8uuPocket,
166
+ nutTrap,
167
+ pulleyBore,
168
+ beltClamp,
169
+ } from './seats.mjs';
110
170
  export { ops } from './ops.mjs';
111
171
  export { fromOutlines, regionShape, optimisedOutline, solidRegion, optimisedSolid } from './optimised.mjs';