@rulecad/cad 0.8.0 → 0.10.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.
Files changed (102) hide show
  1. package/AGENTS.md +45 -16
  2. package/CHANGELOG.md +724 -0
  3. package/EXAMPLES.md +61 -54
  4. package/README.md +376 -98
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2664 -541
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1883 -435
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/cache-file.mjs +105 -0
  15. package/lib/carried.mjs +201 -0
  16. package/lib/clone.mjs +194 -42
  17. package/lib/code-text.mjs +28 -0
  18. package/lib/design-imports.mjs +127 -0
  19. package/lib/design.mjs +871 -147
  20. package/lib/designshapes.mjs +142 -0
  21. package/lib/drive.mjs +187 -63
  22. package/lib/edit.mjs +922 -192
  23. package/lib/errors.mjs +16 -3
  24. package/lib/estimates.mjs +51 -0
  25. package/lib/explain.mjs +62 -13
  26. package/lib/fasten.mjs +2708 -507
  27. package/lib/fe-key.mjs +29 -0
  28. package/lib/fittings.mjs +721 -122
  29. package/lib/fixings.mjs +38 -13
  30. package/lib/framebuild.mjs +790 -175
  31. package/lib/framecheck.mjs +1901 -368
  32. package/lib/framegen.mjs +108 -22
  33. package/lib/frameheat.mjs +225 -42
  34. package/lib/frameprint.mjs +513 -108
  35. package/lib/frames.mjs +86 -18
  36. package/lib/framesize.mjs +719 -120
  37. package/lib/frametip.mjs +235 -0
  38. package/lib/gait.mjs +135 -23
  39. package/lib/grip.mjs +62 -13
  40. package/lib/guides.mjs +1403 -230
  41. package/lib/host.mjs +129 -23
  42. package/lib/inplace.mjs +171 -36
  43. package/lib/jigs.mjs +360 -78
  44. package/lib/joins.mjs +697 -118
  45. package/lib/jsonedit.mjs +88 -26
  46. package/lib/kept.mjs +84 -0
  47. package/lib/kit.mjs +439 -69
  48. package/lib/layout.mjs +2 -1
  49. package/lib/links.mjs +149 -42
  50. package/lib/list.mjs +334 -64
  51. package/lib/live-guard.mjs +68 -0
  52. package/lib/live-shape.mjs +96 -24
  53. package/lib/live.mjs +189 -59
  54. package/lib/loads.mjs +597 -136
  55. package/lib/machine.mjs +372 -74
  56. package/lib/magnets.mjs +162 -44
  57. package/lib/measured.mjs +1080 -117
  58. package/lib/mesh.mjs +526 -119
  59. package/lib/meshcmd.mjs +215 -60
  60. package/lib/motors.mjs +1002 -214
  61. package/lib/motorsvg.mjs +114 -32
  62. package/lib/names.mjs +18 -1
  63. package/lib/optimise.mjs +991 -287
  64. package/lib/order.mjs +515 -114
  65. package/lib/panels.mjs +482 -94
  66. package/lib/parts.mjs +81 -23
  67. package/lib/pins.mjs +163 -44
  68. package/lib/plates.mjs +223 -35
  69. package/lib/player.mjs +37 -9
  70. package/lib/power.mjs +64 -13
  71. package/lib/preview.mjs +83 -16
  72. package/lib/profilemeasure.mjs +572 -129
  73. package/lib/rules.mjs +17 -6
  74. package/lib/sandbox-hooks.mjs +179 -27
  75. package/lib/sandbox-lock.mjs +225 -0
  76. package/lib/sandbox-preload.mjs +2 -2
  77. package/lib/sandbox-run.mjs +122 -25
  78. package/lib/sandbox.mjs +667 -75
  79. package/lib/schema.mjs +42 -11
  80. package/lib/seats.mjs +227 -49
  81. package/lib/services.mjs +261 -52
  82. package/lib/sheet.mjs +963 -179
  83. package/lib/slotnuts.mjs +213 -34
  84. package/lib/targets/gist.mjs +4 -1
  85. package/lib/targets.mjs +22 -4
  86. package/lib/task.mjs +376 -79
  87. package/lib/versions.mjs +285 -39
  88. package/lib/wires.mjs +228 -45
  89. package/lib/workspace.mjs +200 -14
  90. package/package.json +19 -19
  91. package/schemas/assembly.schema.json +2 -2
  92. package/schemas/project.schema.json +6 -0
  93. package/templates/coupons/MEASURE.md +109 -0
  94. package/templates/coupons/assemblies/fixings-test.json +20 -0
  95. package/templates/coupons/assemblies/slot-test.json +11 -0
  96. package/templates/coupons/objects/fixings-coupon.js +88 -0
  97. package/templates/coupons/objects/fixings-coupon.json +26 -0
  98. package/templates/coupons/objects/holds-coupon.js +130 -0
  99. package/templates/coupons/objects/holds-coupon.json +42 -0
  100. package/templates/coupons/objects/slot-coupon.js +89 -0
  101. package/templates/coupons/objects/slot-coupon.json +29 -0
  102. package/templates/coupons/project.json +10 -0
package/lib/meshcmd.mjs CHANGED
@@ -5,7 +5,23 @@ import { fmt } from './rules.mjs';
5
5
  import { WS, paths } from './workspace.mjs';
6
6
  import { picture, preview } from './preview.mjs';
7
7
  import {
8
- AXES, axisOf, planeAxes, readMesh, bounds, volume, section, profiles, spans, loops, parsePlacement, turn, align, deviation, worst, stats, limitingLicence,
8
+ AXES,
9
+ axisOf,
10
+ planeAxes,
11
+ readMesh,
12
+ bounds,
13
+ volume,
14
+ section,
15
+ profiles,
16
+ spans,
17
+ loops,
18
+ parsePlacement,
19
+ turn,
20
+ align,
21
+ deviation,
22
+ worst,
23
+ stats,
24
+ limitingLicence,
9
25
  } from './mesh.mjs';
10
26
 
11
27
  const f2 = (n) => fmt(Math.round(n * 100) / 100);
@@ -15,8 +31,15 @@ const today = () => new Date().toISOString().slice(0, 10);
15
31
 
16
32
  // Edges used by one face only: holes in the surface, which make inside and outside meaningless
17
33
  function openEdges(tris) {
18
- const k = (v) => v.map((x) => Math.round(x * 1e4)).join(','), count = new Map();
19
- for (const t of tris) for (let i = 0; i < 3; i++) { const a = k(t[i]), b = k(t[(i + 1) % 3]), e = a < b ? `${a}|${b}` : `${b}|${a}`; count.set(e, (count.get(e) || 0) + 1); }
34
+ const k = (v) => v.map((x) => Math.round(x * 1e4)).join(','),
35
+ count = new Map();
36
+ for (const t of tris)
37
+ for (let i = 0; i < 3; i++) {
38
+ const a = k(t[i]),
39
+ b = k(t[(i + 1) % 3]),
40
+ e = a < b ? `${a}|${b}` : `${b}|${a}`;
41
+ count.set(e, (count.get(e) || 0) + 1);
42
+ }
20
43
  return [...count.values()].filter((n) => n === 1).length;
21
44
  }
22
45
 
@@ -24,31 +47,46 @@ function openEdges(tris) {
24
47
 
25
48
  // panels: [{ title, layers: [{ segs, style: 'design' | 'reference' }], marks: [[u, w]] }], all in one scale
26
49
  function sectionsSvg(panels, { title, note, axis }) {
27
- const [u, w] = planeAxes(axis), W = 1800, H = 1200, head = 110, cols = Math.min(panels.length, 3), rows = Math.ceil(panels.length / cols);
28
- const pw = W / cols, ph = (H - head) / rows, pad = 70;
50
+ const [u, w] = planeAxes(axis),
51
+ W = 1800,
52
+ H = 1200,
53
+ head = 110,
54
+ cols = Math.min(panels.length, 3),
55
+ rows = Math.ceil(panels.length / cols);
56
+ const pw = W / cols,
57
+ ph = (H - head) / rows,
58
+ pad = 70;
29
59
  const all = panels.flatMap((p) => p.layers.flatMap((l) => l.segs.flat()));
30
60
  if (!all.length) return '';
31
- const lo = [Math.min(...all.map((p) => p[0])), Math.min(...all.map((p) => p[1]))], hi = [Math.max(...all.map((p) => p[0])), Math.max(...all.map((p) => p[1]))];
61
+ const lo = [Math.min(...all.map((p) => p[0])), Math.min(...all.map((p) => p[1]))],
62
+ hi = [Math.max(...all.map((p) => p[0])), Math.max(...all.map((p) => p[1]))];
32
63
  const s = Math.min((pw - pad * 2) / (hi[0] - lo[0] || 1), (ph - pad * 2) / (hi[1] - lo[1] || 1));
33
64
  const esc = (t) => String(t).replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]);
34
65
  let body = '';
35
66
  panels.forEach((p, i) => {
36
- const ox = (i % cols) * pw, oy = head + Math.floor(i / cols) * ph;
37
- const X = (x) => ox + pw / 2 + (x - (lo[0] + hi[0]) / 2) * s, Y = (y) => oy + ph / 2 - (y - (lo[1] + hi[1]) / 2) * s;
67
+ const ox = (i % cols) * pw,
68
+ oy = head + Math.floor(i / cols) * ph;
69
+ const X = (x) => ox + pw / 2 + (x - (lo[0] + hi[0]) / 2) * s,
70
+ Y = (y) => oy + ph / 2 - (y - (lo[1] + hi[1]) / 2) * s;
38
71
  body += `<text x="${ox + 32}" y="${oy + 36}" class="h">${esc(p.title)}</text>`;
39
72
  // a 1 mm scale bar
40
73
  body += `<line x1="${ox + 32}" y1="${oy + ph - 30}" x2="${ox + 32 + s}" y2="${oy + ph - 30}" stroke="#8a8a8a" stroke-width="2"/><text x="${ox + 40 + s}" y="${oy + ph - 24}" class="m">1 mm</text>`;
41
74
  for (const l of p.layers) {
42
- const d = loops(l.segs).map((line) => `M${line.map(([a, b]) => `${X(a).toFixed(1)},${Y(b).toFixed(1)}`).join('L')}`).join('');
43
- body += l.style === 'reference'
44
- ? `<path d="${d}" fill="none" stroke="#b4b4b4" stroke-width="2" stroke-dasharray="7 5"/>`
45
- : `<path d="${d}" fill="#3a3a3a" fill-rule="evenodd" stroke="#ffffff" stroke-width="1.6"/>`;
75
+ const d = loops(l.segs)
76
+ .map((line) => `M${line.map(([a, b]) => `${X(a).toFixed(1)},${Y(b).toFixed(1)}`).join('L')}`)
77
+ .join('');
78
+ body +=
79
+ l.style === 'reference'
80
+ ? `<path d="${d}" fill="none" stroke="#b4b4b4" stroke-width="2" stroke-dasharray="7 5"/>`
81
+ : `<path d="${d}" fill="#3a3a3a" fill-rule="evenodd" stroke="#ffffff" stroke-width="1.6"/>`;
46
82
  }
47
- for (const [a, b] of p.marks || []) body += `<circle cx="${X(a)}" cy="${Y(b)}" r="9" fill="none" stroke="#ffffff" stroke-width="2"/>`;
83
+ for (const [a, b] of p.marks || [])
84
+ body += `<circle cx="${X(a)}" cy="${Y(b)}" r="9" fill="none" stroke="#ffffff" stroke-width="2"/>`;
48
85
  body += `<text x="${ox + 32}" y="${oy + 62}" class="m">${AXES[u]} across, ${AXES[w]} up</text>`;
49
86
  });
50
87
  const legend = panels.some((p) => p.layers.some((l) => l.style === 'reference'))
51
- ? `<rect x="1180" y="40" width="34" height="18" fill="#3a3a3a" stroke="#fff"/><text x="1226" y="55" class="m">design</text><line x1="1340" y1="49" x2="1380" y2="49" stroke="#b4b4b4" stroke-width="2" stroke-dasharray="7 5"/><text x="1392" y="55" class="m">reference</text><circle cx="1530" cy="49" r="9" fill="none" stroke="#fff" stroke-width="2"/><text x="1548" y="55" class="m">worst places</text>` : '';
88
+ ? `<rect x="1180" y="40" width="34" height="18" fill="#3a3a3a" stroke="#fff"/><text x="1226" y="55" class="m">design</text><line x1="1340" y1="49" x2="1380" y2="49" stroke="#b4b4b4" stroke-width="2" stroke-dasharray="7 5"/><text x="1392" y="55" class="m">reference</text><circle cx="1530" cy="49" r="9" fill="none" stroke="#fff" stroke-width="2"/><text x="1548" y="55" class="m">worst places</text>`
89
+ : '';
52
90
  return `<!doctype html><html><head><meta charset="utf-8"></head><body style="margin:0;background:#000"><svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">
53
91
  <style>text{font-family:-apple-system,Helvetica,Arial,sans-serif;fill:#fff}.t{font-size:30px}.n{font-size:21px;fill:#9a9a9a}.h{font-size:19px;letter-spacing:2px;fill:#9a9a9a}.m{font-size:17px;fill:#8a8a8a}</style>
54
92
  <rect width="${W}" height="${H}" fill="#000"/><text x="32" y="52" class="t">${esc(title)}</text><text x="32" y="86" class="n">${esc(note)}</text>${legend}${body}</svg></body></html>`;
@@ -60,66 +98,118 @@ function sectionsSvg(panels, { title, note, axis }) {
60
98
  // writes the profiles' drawing, and draft rules when asked
61
99
  export async function measure(file, o = {}) {
62
100
  if (!fs.existsSync(file)) throw new Error(`no file ${file}`);
63
- const tris = readMesh(file), B = bounds(tris);
64
- const axis = o.along ? axisOf(o.along) : B.size.indexOf(Math.max(...B.size)), [u, w] = planeAxes(axis), A = AXES[axis];
101
+ const tris = readMesh(file),
102
+ B = bounds(tris);
103
+ const axis = o.along ? axisOf(o.along) : B.size.indexOf(Math.max(...B.size)),
104
+ [u, w] = planeAxes(axis),
105
+ A = AXES[axis];
65
106
  const name = path.basename(file).replace(/\.[^.]+$/, '');
66
107
  const open = openEdges(tris);
67
- console.log(`${path.basename(file)}: ${tris.length} triangles${open ? `, ${open} open edges (not a closed solid: inside and outside are guesses)` : ', a closed solid'}`);
68
- console.log(` size ${B.size.map(f2).join(' × ')} mm: ${AXES.map((a, i) => `${a} ${range([B.min[i], B.max[i]])}`).join(', ')}; volume ${fmt(Math.round(volume(tris) / 10) / 100)} cm³`);
69
- if (o.licence && limitingLicence(o.licence)) console.log(` ! licence "${o.licence}" limits reuse: measurements are facts, but don't copy the model's shape into a design under another licence`);
108
+ console.log(
109
+ `${path.basename(file)}: ${tris.length} triangles${open ? `, ${open} open edges (not a closed solid: inside and outside are guesses)` : ', a closed solid'}`,
110
+ );
111
+ console.log(
112
+ ` size ${B.size.map(f2).join(' × ')} mm: ${AXES.map((a, i) => `${a} ${range([B.min[i], B.max[i]])}`).join(', ')}; volume ${fmt(Math.round(volume(tris) / 10) / 100)} cm³`,
113
+ );
114
+ if (o.licence && limitingLicence(o.licence))
115
+ console.log(
116
+ ` ! licence "${o.licence}" limits reuse: measurements are facts, but don't copy the model's shape into a design under another licence`,
117
+ );
70
118
 
71
119
  // Stretches along the axis with the same cross-section, and the distinct shapes among them
72
- const runs = profiles(tris, axis), shapes = [];
120
+ const runs = profiles(tris, axis),
121
+ shapes = [];
73
122
  for (const r of runs) {
74
123
  if (r.shape === undefined) continue;
75
124
  if (!shapes[r.shape]) shapes[r.shape] = { ...r, first: r };
76
125
  r.shape = letter(r.shape);
77
126
  }
78
- console.log(`\n along ${A}: ${runs.length} stretches, ${shapes.length} distinct cross-sections (positions from ${A} = ${f2(B.min[axis])})`);
127
+ console.log(
128
+ `\n along ${A}: ${runs.length} stretches, ${shapes.length} distinct cross-sections (positions from ${A} = ${f2(B.min[axis])})`,
129
+ );
79
130
  for (const r of runs) {
80
- const len = r.to - r.from, at = `${f2(r.from)}..${f2(r.to)}`.padEnd(16);
81
- console.log(` ${at} ${`(${f2(len)})`.padEnd(9)} ${r.varies ? 'changing: a taper, slope or curve' : r.empty ? 'empty' : `section ${r.shape}`}`);
131
+ const len = r.to - r.from,
132
+ at = `${f2(r.from)}..${f2(r.to)}`.padEnd(16);
133
+ console.log(
134
+ ` ${at} ${`(${f2(len)})`.padEnd(9)} ${r.varies ? 'changing: a taper, slope or curve' : r.empty ? 'empty' : `section ${r.shape}`}`,
135
+ );
82
136
  }
83
137
  for (const [i, s] of shapes.entries()) {
84
- console.log(`\n section ${letter(i)}: ${AXES[u]} ${range(s.extent.across)} (${f2(s.extent.across[1] - s.extent.across[0])} wide), ${AXES[w]} ${range(s.extent.up)} (${f2(s.extent.up[1] - s.extent.up[0])} high)${s.curved ? ', with sloped or curved sides' : ''}`);
138
+ console.log(
139
+ `\n section ${letter(i)}: ${AXES[u]} ${range(s.extent.across)} (${f2(s.extent.across[1] - s.extent.across[0])} wide), ${AXES[w]} ${range(s.extent.up)} (${f2(s.extent.up[1] - s.extent.up[0])} high)${s.curved ? ', with sloped or curved sides' : ''}`,
140
+ );
85
141
  for (const b of s.bands) {
86
142
  const pieces = (x) => x.map(range).join(' + ');
87
- const how = b.straight ? pieces(b.widest) : `${pieces(b.bottom)} at the bottom, ${pieces(b.top)} at the top, widest ${pieces(b.widest)}`;
88
- console.log(` ${AXES[w]} ${range([b.from, b.to])}`.padEnd(24) + (b.pieces ? `${b.pieces} piece${b.pieces === 1 ? '' : 's'} at ${AXES[u]} ${how}` : 'nothing (a gap under material above)'));
143
+ const how = b.straight
144
+ ? pieces(b.widest)
145
+ : `${pieces(b.bottom)} at the bottom, ${pieces(b.top)} at the top, widest ${pieces(b.widest)}`;
146
+ console.log(
147
+ ` ${AXES[w]} ${range([b.from, b.to])}`.padEnd(24) +
148
+ (b.pieces
149
+ ? `${b.pieces} piece${b.pieces === 1 ? '' : 's'} at ${AXES[u]} ${how}`
150
+ : 'nothing (a gap under material above)'),
151
+ );
89
152
  }
90
153
  }
91
154
 
92
155
  // Lines along the axis: where they are inside
93
- const lines = (o.line || []).map((t) => { const p = String(t).split(',').map(Number); if (p.length !== 2 || p.some(Number.isNaN)) throw new Error(`--line ${t}: two numbers, ${AXES[u]},${AXES[w]}`); return p; });
156
+ const lines = (o.line || []).map((t) => {
157
+ const p = String(t).split(',').map(Number);
158
+ if (p.length !== 2 || p.some(Number.isNaN)) throw new Error(`--line ${t}: two numbers, ${AXES[u]},${AXES[w]}`);
159
+ return p;
160
+ });
94
161
  const found = lines.map((p) => ({ p, inside: spans(tris, axis, p) }));
95
- for (const l of found) console.log(`\n along ${A} at ${AXES[u]} ${f2(l.p[0])}, ${AXES[w]} ${f2(l.p[1])}: inside ${l.inside.map(range).join(', ') || 'nowhere'}`);
162
+ for (const l of found)
163
+ console.log(
164
+ `\n along ${A} at ${AXES[u]} ${f2(l.p[0])}, ${AXES[w]} ${f2(l.p[1])}: inside ${l.inside.map(range).join(', ') || 'nowhere'}`,
165
+ );
96
166
 
97
167
  // The drawing: each distinct section, and any asked for
98
- const panels = shapes.map((s, i) => ({ title: `SECTION ${letter(i)} · ${A} ${f2(s.first.from)}..${f2(s.first.to)}`, layers: [{ segs: s.first.segs, style: 'design' }] }));
99
- for (const at of (o.at || []).map(Number)) panels.push({ title: `${A} = ${f2(at)}`, layers: [{ segs: section(tris, axis, at), style: 'design' }] });
168
+ const panels = shapes.map((s, i) => ({
169
+ title: `SECTION ${letter(i)} · ${A} ${f2(s.first.from)}..${f2(s.first.to)}`,
170
+ layers: [{ segs: s.first.segs, style: 'design' }],
171
+ }));
172
+ for (const at of (o.at || []).map(Number))
173
+ panels.push({ title: `${A} = ${f2(at)}`, layers: [{ segs: section(tris, axis, at), style: 'design' }] });
100
174
  if (panels.length && o.pictures !== false) {
101
175
  const out = paths.preview('measure', `${name}.png`);
102
- await picture(sectionsSvg(panels.slice(0, 9), { title: `${path.basename(file)}: sections across ${A}`, note: `${B.size.map(f2).join(' × ')} mm · ${runs.length} stretches along ${A}`, axis }), out);
176
+ await picture(
177
+ sectionsSvg(panels.slice(0, 9), {
178
+ title: `${path.basename(file)}: sections across ${A}`,
179
+ note: `${B.size.map(f2).join(' × ')} mm · ${runs.length} stretches along ${A}`,
180
+ axis,
181
+ }),
182
+ out,
183
+ );
103
184
  console.log(`\n drawing: ${out}`);
104
185
  }
105
186
 
106
- if (o.rules) writeDraft({ o, name, file, B, axis, runs, shapes, found });
187
+ if (o.rules) writeDraft({ o, file, B, axis, runs, shapes, found });
107
188
  }
108
189
 
109
190
  // Draft rules from a measurement: kind derived, every value traced to the file (and its source and licence). Names are
110
191
  // placeholders (stretch2_from, sectionB_w): rename them for what they are before a design uses them.
111
- function writeDraft({ o, name, file, B, axis, runs, shapes, found }) {
192
+ function writeDraft({ o, file, B, axis, runs, shapes, found }) {
112
193
  const set = String(o.rules);
113
194
  if (!/^[a-z][a-z0-9_]*$/.test(set)) throw new Error('--rules <name>: lower case, digits and _ (a rule set name)');
114
195
  const to = path.join(WS, 'rules', `${set}.json`);
115
196
  if (fs.existsSync(to) && !o.force) throw new Error(`rules/${set}.json already exists (--force to replace it)`);
116
- const [u, w] = planeAxes(axis), A = AXES[axis], base = B.min[axis];
117
- const src = o.source || path.basename(file), extra = { kind: 'derived', source: src, ...(o.licence ? { licence: o.licence } : {}), checked: today() };
197
+ const [u, w] = planeAxes(axis),
198
+ A = AXES[axis],
199
+ base = B.min[axis];
200
+ const src = o.source || path.basename(file),
201
+ extra = { kind: 'derived', source: src, ...(o.licence ? { licence: o.licence } : {}), checked: today() };
118
202
  const rules = {};
119
- const add = (k, v, rule) => { rules[k] = { value: Math.round(v * 100) / 100, unit: 'mm', rule, ...extra }; };
203
+ const add = (k, v, rule) => {
204
+ rules[k] = { value: Math.round(v * 100) / 100, unit: 'mm', rule, ...extra };
205
+ };
120
206
  AXES.forEach((a, i) => add(`size_${a}`, B.size[i], `Overall size in ${a}`));
121
207
  runs.forEach((r, i) => {
122
- add(`stretch${i + 1}_from`, r.from - base, `Stretch ${i + 1} (${r.varies ? 'changing' : `section ${r.shape}`}) starts, from the model's lowest ${A}`);
208
+ add(
209
+ `stretch${i + 1}_from`,
210
+ r.from - base,
211
+ `Stretch ${i + 1} (${r.varies ? 'changing' : `section ${r.shape}`}) starts, from the model's lowest ${A}`,
212
+ );
123
213
  add(`stretch${i + 1}_len`, r.to - r.from, `Stretch ${i + 1} length along ${A}`);
124
214
  });
125
215
  shapes.forEach((s, i) => {
@@ -128,19 +218,37 @@ function writeDraft({ o, name, file, B, axis, runs, shapes, found }) {
128
218
  add(`section${L}_h`, s.extent.up[1] - s.extent.up[0], `Section ${L}: height in ${AXES[w]}`);
129
219
  s.bands.forEach((b, j) => {
130
220
  const at = `section${L}_band${j + 1}`;
131
- add(`${at}_at`, b.from - s.extent.up[0], `Section ${L}, band ${j + 1} (${b.pieces} piece${b.pieces === 1 ? '' : 's'}): its bottom, from the section's lowest ${AXES[w]}`);
221
+ add(
222
+ `${at}_at`,
223
+ b.from - s.extent.up[0],
224
+ `Section ${L}, band ${j + 1} (${b.pieces} piece${b.pieces === 1 ? '' : 's'}): its bottom, from the section's lowest ${AXES[w]}`,
225
+ );
132
226
  add(`${at}_h`, b.to - b.from, `Section ${L}, band ${j + 1}: its height`);
133
- b.widest.forEach(([p, q], k) => add(`${at}_piece${k + 1}_w`, q - p, `Section ${L}, band ${j + 1}, piece ${k + 1}: widest, from ${AXES[u]} ${f2(p)}`));
227
+ b.widest.forEach(([p, q], k) =>
228
+ add(
229
+ `${at}_piece${k + 1}_w`,
230
+ q - p,
231
+ `Section ${L}, band ${j + 1}, piece ${k + 1}: widest, from ${AXES[u]} ${f2(p)}`,
232
+ ),
233
+ );
134
234
  });
135
235
  });
136
- found.forEach((l, i) => l.inside.forEach(([a, b], j) => {
137
- add(`line${i + 1}_${j + 1}_from`, a - base, `Along ${A} at ${AXES[u]} ${f2(l.p[0])}, ${AXES[w]} ${f2(l.p[1])}: inside from (from the lowest ${A})`);
138
- add(`line${i + 1}_${j + 1}_to`, b - base, 'Inside to');
139
- }));
236
+ found.forEach((l, i) =>
237
+ l.inside.forEach(([a, b], j) => {
238
+ add(
239
+ `line${i + 1}_${j + 1}_from`,
240
+ a - base,
241
+ `Along ${A} at ${AXES[u]} ${f2(l.p[0])}, ${AXES[w]} ${f2(l.p[1])}: inside from (from the lowest ${A})`,
242
+ );
243
+ add(`line${i + 1}_${j + 1}_to`, b - base, 'Inside to');
244
+ }),
245
+ );
140
246
  const doc = `Measured from ${path.basename(file)} by cad measure (along ${A}). kind derived: read off someone else's model, so check it against the real thing; rename the placeholder names before a design uses them.${o.licence ? ` The model's licence: ${o.licence}.` : ''}`;
141
247
  fs.mkdirSync(path.dirname(to), { recursive: true });
142
248
  fs.writeFileSync(to, `${JSON.stringify({ _doc: doc, name: set, rules }, null, 2)}\n`);
143
- console.log(`\n draft rules: ${path.relative(process.cwd(), to)} (${Object.keys(rules).length} values, kind derived: rename them for what they are)`);
249
+ console.log(
250
+ `\n draft rules: ${path.relative(process.cwd(), to)} (${Object.keys(rules).length} values, kind derived: rename them for what they are)`,
251
+ );
144
252
  }
145
253
 
146
254
  // ---- cad match ----
@@ -149,40 +257,77 @@ function writeDraft({ o, name, file, B, axis, runs, shapes, found }) {
149
257
  export async function match(b, d, file, { place, tol, samples = 20000, at = [], title, tag = '', pictures = true }) {
150
258
  if (!fs.existsSync(file)) throw new Error(`no file ${file}`);
151
259
  const fan = (polys) => polys.flatMap((p) => p.slice(1, -1).map((_, i) => [p[0], p[i + 1], p[i + 2]]));
152
- const parts = b.parts.filter((p) => p.role !== 'support'), design = fan(parts.flatMap((p) => p.triangles));
260
+ const parts = b.parts.filter((p) => p.role !== 'support'),
261
+ design = fan(parts.flatMap((p) => p.triangles));
262
+ if (!design.length)
263
+ throw new Error(`${title} has no triangles to hold against ${path.basename(file)}: it draws nothing`);
153
264
  const ref = readMesh(file);
154
265
  const placed = place ? { ...parsePlacement(place), name: place, score: null } : align(ref, design);
155
266
  const R = turn(ref, placed.M, placed.shift);
156
267
  const words = (p) => `${p.name === 'none' ? '' : `${p.name} `}t${p.shift.map(f2).join(',')}`.trim();
157
268
  console.log(`${title} against ${path.basename(file)}`);
158
- console.log(` placed ${place ? 'as asked' : 'by fitting it to the design'}: ${words(placed)}${place ? '' : ` (pin it with --place "${words(placed)}")`}`);
159
- if (openEdges(ref)) console.log(` ! the reference has ${openEdges(ref)} open edges: inside and outside are guesses near them`);
269
+ console.log(
270
+ ` placed ${place ? 'as asked' : 'by fitting it to the design'}: ${words(placed)}${place ? '' : ` (pin it with --place "${words(placed)}")`}`,
271
+ );
272
+ if (openEdges(ref))
273
+ console.log(` ! the reference has ${openEdges(ref)} open edges: inside and outside are guesses near them`);
160
274
 
161
- const D = deviation(design, R, { samples }), Rv = deviation(R, design, { samples });
162
- const sd = stats(D), sr = stats(Rv);
275
+ const D = deviation(design, R, { samples }),
276
+ Rv = deviation(R, design, { samples });
277
+ const sd = stats(D),
278
+ sr = stats(Rv);
163
279
  const level = (s) => (s.max <= tol ? 'pass' : s.p95 <= tol ? 'warn' : 'fail');
164
280
  const mark = { pass: '✓', warn: '!', fail: '✗' };
165
281
  const side = (x) => (x < 0 ? 'inside' : 'outside');
166
- console.log(` ${mark[level(sd)]} the design's surface: 95% within ${f2(sd.p95)} mm of the reference, ${f2(sd.max)} at most (mean ${f2(sd.mean)}; on average ${f2(Math.abs(sd.signed))} mm ${side(sd.signed)} it)`);
167
- console.log(` ${mark[level(sr)]} the reference's surface: 95% within ${f2(sr.p95)} mm of the design, ${f2(sr.max)} at most (mean ${f2(sr.mean)})`);
168
- console.log(` tolerance ${f2(tol)} mm${place ? '' : ''}: ✓ everything within it, ! only the worst 5% past it, ✗ more than that`);
282
+ console.log(
283
+ ` ${mark[level(sd)]} the design's surface: 95% within ${f2(sd.p95)} mm of the reference, ${f2(sd.max)} at most (mean ${f2(sd.mean)}; on average ${f2(Math.abs(sd.signed))} mm ${side(sd.signed)} it)`,
284
+ );
285
+ console.log(
286
+ ` ${mark[level(sr)]} the reference's surface: 95% within ${f2(sr.p95)} mm of the design, ${f2(sr.max)} at most (mean ${f2(sr.mean)})`,
287
+ );
288
+ console.log(
289
+ ` tolerance ${f2(tol)} mm${place ? '' : ''}: ✓ everything within it, ! only the worst 5% past it, ✗ more than that`,
290
+ );
169
291
 
170
- const wd = worst(D.filter((x) => Math.abs(x.d) > tol)), wr = worst(Rv.filter((x) => Math.abs(x.d) > tol));
292
+ const wd = worst(D.filter((x) => Math.abs(x.d) > tol)),
293
+ wr = worst(Rv.filter((x) => Math.abs(x.d) > tol));
171
294
  const where = (p) => AXES.map((a, i) => `${a} ${f2(p[i])}`).join(' ');
172
- if (wd.length) { console.log(' where the design is off:'); for (const x of wd) console.log(` ${where(x.p)}: ${f2(Math.abs(x.d))} mm ${x.d > 0 ? 'outside the reference (extra material)' : 'inside the reference (material missing, or clearance)'}`); }
173
- if (wr.length) { console.log(' where the reference has what the design lacks, or lacks what it has:'); for (const x of wr) console.log(` ${where(x.p)}: the reference is ${f2(Math.abs(x.d))} mm ${x.d > 0 ? 'outside the design (material the design lacks)' : 'inside the design (the design has extra here)'}`); }
295
+ if (wd.length) {
296
+ console.log(' where the design is off:');
297
+ for (const x of wd)
298
+ console.log(
299
+ ` ${where(x.p)}: ${f2(Math.abs(x.d))} mm ${x.d > 0 ? 'outside the reference (extra material)' : 'inside the reference (material missing, or clearance)'}`,
300
+ );
301
+ }
302
+ if (wr.length) {
303
+ console.log(' where the reference has what the design lacks, or lacks what it has:');
304
+ for (const x of wr)
305
+ console.log(
306
+ ` ${where(x.p)}: the reference is ${f2(Math.abs(x.d))} mm ${x.d > 0 ? 'outside the design (material the design lacks)' : 'inside the design (the design has extra here)'}`,
307
+ );
308
+ }
174
309
 
175
310
  // Along the longest axis: the worst deviation in each eighth, to see where it goes wrong
176
- const DB = bounds(design), axis = DB.size.indexOf(Math.max(...DB.size)), lo = DB.min[axis], len = DB.size[axis] || 1;
311
+ const DB = bounds(design),
312
+ axis = DB.size.indexOf(Math.max(...DB.size)),
313
+ lo = DB.min[axis],
314
+ len = DB.size[axis] || 1;
177
315
  const bins = Array(8).fill(0);
178
- for (const x of [...D, ...Rv]) { const i = Math.min(7, Math.max(0, Math.floor(((x.p[axis] - lo) / len) * 8))); bins[i] = Math.max(bins[i], Math.abs(x.d)); }
316
+ for (const x of [...D, ...Rv]) {
317
+ const i = Math.min(7, Math.max(0, Math.floor(((x.p[axis] - lo) / len) * 8)));
318
+ bins[i] = Math.max(bins[i], Math.abs(x.d));
319
+ }
179
320
  console.log(` worst in each eighth along ${AXES[axis]}: ${bins.map(f2).join(' · ')} mm`);
180
321
 
181
322
  const ok = level(sd) !== 'fail' && level(sr) !== 'fail';
182
323
  if (!pictures) return ok;
183
324
  // Pictures: the reference over the design, and sections through the worst places (and any asked for)
184
325
  const out = paths.preview(d.project, `${d.name}${tag}-match.png`);
185
- await preview([...parts, { name: 'reference', role: 'reference', label: 'reference', triangles: R }], { title: `${title}: match`, meta: `reference ${path.basename(file)} · faint lines`, out });
326
+ await preview([...parts, { name: 'reference', role: 'reference', label: 'reference', triangles: R }], {
327
+ title: `${title}: match`,
328
+ meta: `reference ${path.basename(file)} · faint lines`,
329
+ out,
330
+ });
186
331
  // Sections at the places asked for, then through the worst places: just inside the ends (a cut on an end face is
187
332
  // empty), and at least 1 mm apart
188
333
  const cuts = [];
@@ -194,11 +339,21 @@ export async function match(b, d, file, { place, tol, samples = 20000, at = [],
194
339
  const [u, w] = planeAxes(axis);
195
340
  const panels = cuts.map((c) => ({
196
341
  title: `${AXES[axis].toUpperCase()} = ${f2(c)}`,
197
- layers: [{ segs: section(design, axis, c), style: 'design' }, { segs: section(R, axis, c), style: 'reference' }],
342
+ layers: [
343
+ { segs: section(design, axis, c), style: 'design' },
344
+ { segs: section(R, axis, c), style: 'reference' },
345
+ ],
198
346
  marks: [...wd, ...wr].filter((x) => Math.abs(x.p[axis] - c) < 0.5).map((x) => [x.p[u], x.p[w]]),
199
347
  }));
200
348
  const sOut = paths.preview(d.project, `${d.name}${tag}-match-sections.png`);
201
- await picture(sectionsSvg(panels, { title: `${title} against ${path.basename(file)}`, note: `sections across ${AXES[axis]} · tolerance ${f2(tol)} mm · 95% within ${f2(Math.max(sd.p95, sr.p95))}, worst ${f2(Math.max(sd.max, sr.max))}`, axis }), sOut);
349
+ await picture(
350
+ sectionsSvg(panels, {
351
+ title: `${title} against ${path.basename(file)}`,
352
+ note: `sections across ${AXES[axis]} · tolerance ${f2(tol)} mm · 95% within ${f2(Math.max(sd.p95, sr.p95))}, worst ${f2(Math.max(sd.max, sr.max))}`,
353
+ axis,
354
+ }),
355
+ sOut,
356
+ );
202
357
  console.log(` pictures: ${out}\n ${sOut}`);
203
358
  return ok;
204
359
  }