bambu-printer-mcp 1.1.90 → 1.1.92

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 (86) hide show
  1. package/CONTRIBUTORS.md +2 -0
  2. package/README.md +48 -3
  3. package/dist/bambu-native.js +1 -1
  4. package/dist/cad/contracts.js +16 -7
  5. package/dist/cad/examples.d.ts +2 -1
  6. package/dist/cad/examples.js +13 -10
  7. package/dist/cad/serial.d.ts +1 -1
  8. package/dist/cad/serial.js +4 -6
  9. package/dist/cad-engine.js +17 -12
  10. package/dist/counterpart/flight-record.d.ts +155 -0
  11. package/dist/counterpart/flight-record.js +831 -0
  12. package/dist/counterpart/flight-tools.d.ts +213 -0
  13. package/dist/counterpart/flight-tools.js +232 -0
  14. package/dist/counterpart/fresh-frame.d.ts +16 -0
  15. package/dist/counterpart/fresh-frame.js +26 -0
  16. package/dist/counterpart/make-3mf.js +1 -4
  17. package/dist/counterpart/physical-evidence.d.ts +70 -0
  18. package/dist/counterpart/physical-evidence.js +103 -0
  19. package/dist/counterpart/print-geometry.d.ts +13 -0
  20. package/dist/counterpart/print-geometry.js +181 -0
  21. package/dist/counterpart/remote.js +2 -0
  22. package/dist/counterpart/schemas.d.ts +32 -0
  23. package/dist/counterpart/schemas.js +2 -0
  24. package/dist/counterpart/visual-evidence.d.ts +38 -0
  25. package/dist/counterpart/visual-evidence.js +155 -0
  26. package/dist/index.js +63 -24
  27. package/dist/printers/bambu.d.ts +15 -2
  28. package/dist/printers/bambu.js +64 -12
  29. package/dist/safety/limits.d.ts +6 -0
  30. package/dist/safety/limits.js +8 -0
  31. package/dist/safety/print-file.js +2 -2
  32. package/dist/safety/print-preview.d.ts +2 -0
  33. package/dist/safety/print-preview.js +1 -1
  34. package/dist/safety/printer-state.d.ts +4 -0
  35. package/dist/safety/printer-state.js +14 -1
  36. package/dist/slicer/3mf-xml.d.ts +7 -0
  37. package/dist/slicer/3mf-xml.js +61 -0
  38. package/dist/stl/stl-manipulator.js +5 -2
  39. package/dist/studio-print-options.d.ts +9 -0
  40. package/dist/studio-print-options.js +34 -2
  41. package/dist/tool-annotations.js +2 -0
  42. package/package.json +2 -1
  43. package/src/bambu-native.ts +1 -1
  44. package/src/cad/contracts.ts +17 -7
  45. package/src/cad/examples/bag_clip.py +1 -0
  46. package/src/cad/examples/bistable_clicker.py +1 -0
  47. package/src/cad/examples/broom_grip.py +61 -0
  48. package/src/cad/examples/cable_clip.py +1 -0
  49. package/src/cad/examples/chainmail.py +1 -0
  50. package/src/cad/examples/desk_clamp_hook.py +91 -0
  51. package/src/cad/examples/desk_edge_cable_holder.py +55 -0
  52. package/src/cad/examples/drawer_divider.py +56 -0
  53. package/src/cad/examples/hinged_box.py +1 -0
  54. package/src/cad/examples/knurled_knob.py +1 -0
  55. package/src/cad/examples/loft_handle.py +1 -0
  56. package/src/cad/examples/organizer_tray.py +41 -0
  57. package/src/cad/examples/phone_stand.py +1 -0
  58. package/src/cad/examples/plant_pot.py +53 -0
  59. package/src/cad/examples/shelf_bracket.py +53 -0
  60. package/src/cad/examples/swept_hook.py +1 -0
  61. package/src/cad/examples/threaded_jar.py +1 -0
  62. package/src/cad/examples/trigger_capo.py +1 -0
  63. package/src/cad/examples/wall_hook.py +1 -0
  64. package/src/cad/examples.ts +13 -10
  65. package/src/cad/geometry.py +6 -0
  66. package/src/cad/serial.ts +4 -6
  67. package/src/cad-engine.ts +9 -3
  68. package/src/counterpart/flight-record.ts +984 -0
  69. package/src/counterpart/flight-tools.ts +282 -0
  70. package/src/counterpart/fresh-frame.ts +45 -0
  71. package/src/counterpart/make-3mf.ts +1 -5
  72. package/src/counterpart/physical-evidence.ts +185 -0
  73. package/src/counterpart/print-geometry.ts +192 -0
  74. package/src/counterpart/remote.ts +2 -0
  75. package/src/counterpart/schemas.ts +3 -0
  76. package/src/counterpart/visual-evidence.ts +212 -0
  77. package/src/index.ts +61 -21
  78. package/src/printers/bambu.ts +64 -10
  79. package/src/safety/limits.ts +8 -0
  80. package/src/safety/print-file.ts +2 -2
  81. package/src/safety/print-preview.ts +1 -1
  82. package/src/safety/printer-state.ts +13 -1
  83. package/src/slicer/3mf-xml.ts +52 -0
  84. package/src/stl/stl-manipulator.ts +4 -1
  85. package/src/studio-print-options.ts +33 -2
  86. package/src/tool-annotations.ts +2 -0
@@ -0,0 +1,61 @@
1
+ /** XML output boundary for 3MF metadata; no printer calls or geometry/G-code changes. */
2
+ import fs from "node:fs/promises";
3
+ import { randomUUID } from "node:crypto";
4
+ import { SaxesParser } from "saxes";
5
+ import { readSafe3mfArchive } from "../safety/archive.js";
6
+ /** Encode text for a quoted XML attribute, preserving whitespace through XML parsing. */
7
+ export function xmlAttribute(value) {
8
+ const entities = { "&": "&amp;", '"': "&quot;", "'": "&apos;", "<": "&lt;", ">": "&gt;", "\t": "&#9;", "\n": "&#10;", "\r": "&#13;" };
9
+ return value.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, "").replace(/[&"'<>\t\r\n]/g, char => entities[char]);
10
+ }
11
+ const parses = (xml) => {
12
+ try {
13
+ let root;
14
+ const parser = new SaxesParser();
15
+ parser.on("error", error => { throw error; });
16
+ parser.on("opentag", node => { root ?? (root = node.name); });
17
+ parser.write(xml).close();
18
+ return root === "config";
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ };
24
+ /** Studio 02.08.02.61 bbs_3mf.cpp writes object opt_serialize values without XML escaping.
25
+ * Only repair its single-line key/value metadata form. Unexpected malformed XML fails closed. */
26
+ export async function escapedModelSettings(xml) {
27
+ if (Buffer.byteLength(xml) > 16 * 1024 * 1024)
28
+ throw Error("3MF model settings exceed the 16 MiB XML limit.");
29
+ if (await parses(xml))
30
+ return xml;
31
+ const lines = xml.split(/(?<=\n)/);
32
+ for (let i = 0; i < lines.length; i++) {
33
+ const match = /^([ \t]*<metadata\s+key="[\w.:-]+"\s+value=")(.*)("\s*\/>[ \t]*\r?\n?)$/.exec(lines[i]);
34
+ if (!match || await parses('<config>' + lines[i] + '</config>'))
35
+ continue;
36
+ lines[i] = match[1] + xmlAttribute(match[2]) + match[3];
37
+ }
38
+ const repaired = lines.join('');
39
+ if (!await parses(repaired))
40
+ throw Error("Slicer produced malformed Metadata/model_settings.config; no safe attribute repair is available.");
41
+ return repaired;
42
+ }
43
+ /** Normalize only a newly produced/restored slice, before caching or handing it to the client. */
44
+ export async function normalize3mfMetadata(filePath) {
45
+ const { zip } = await readSafe3mfArchive(filePath);
46
+ const entry = zip.file('Metadata/model_settings.config');
47
+ if (!entry)
48
+ return;
49
+ const original = await entry.async('string'), repaired = await escapedModelSettings(original);
50
+ if (repaired === original)
51
+ return;
52
+ zip.file(entry.name, repaired);
53
+ const staged = filePath + '.' + randomUUID() + '.xml-tmp';
54
+ try {
55
+ await fs.writeFile(staged, await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' }), { flag: 'wx', mode: 0o600 });
56
+ await fs.rename(staged, filePath);
57
+ }
58
+ finally {
59
+ await fs.rm(staged, { force: true }).catch(() => { });
60
+ }
61
+ }
@@ -1,3 +1,4 @@
1
+ import { normalize3mfMetadata } from "../slicer/3mf-xml.js";
1
2
  import { customGcodesWithPauses, layerTops, machinePauseGcode, pausedLayers, readPlateGcode, readProjectCustomGcodes } from "../slicer/layer-pauses.js";
2
3
  import * as THREE from 'three';
3
4
  import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js';
@@ -1732,11 +1733,13 @@ export class STLManipulator extends EventEmitter {
1732
1733
  if (typeof slicerResult?.return_code === "number" && slicerResult.return_code !== 0) {
1733
1734
  throw new SlicerRunError(`Slicer failed: the slicer exited with code 0, but its result.json reports return_code ${slicerResult.return_code}.`, slicerResult);
1734
1735
  }
1735
- if (cacheKey && !restored && fs.existsSync(outputFilePath))
1736
- await keepSlice(cacheKey, cacheRun);
1737
1736
  if (!fs.existsSync(outputFilePath)) {
1738
1737
  throw new SlicerRunError(`Slicer finished but output file not found: ${outputFilePath}`, slicerResult);
1739
1738
  }
1739
+ if (/\.3mf$/i.test(outputFilePath))
1740
+ await normalize3mfMetadata(outputFilePath);
1741
+ if (cacheKey && !restored)
1742
+ await keepSlice(cacheKey, cacheRun);
1740
1743
  if (progressCallback)
1741
1744
  progressCallback(100, "Slicing completed successfully");
1742
1745
  this.emit('operationComplete', {
@@ -55,3 +55,12 @@ export declare function usedNozzleCount(inspection: {
55
55
  usedFilamentPositions: number[];
56
56
  filamentNozzleIndices?: Array<number | undefined>;
57
57
  }): number | undefined;
58
+ /** Report only verified direct-wire fields. A task boolean is not an SDK mode.
59
+ * null means this route does not transmit that option, not off/auto/unknown hardware state. */
60
+ export declare function directPrintOptionReport(caller: CallerPrintOptions, resolved: StudioPrintOptions, packet: Record<string, unknown>): {
61
+ warning?: string | undefined;
62
+ requested: CallerPrintOptions;
63
+ resolved: StudioPrintOptions;
64
+ transmitted: Record<string, number | boolean | null>;
65
+ unsupported: string[];
66
+ };
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The print options Bambu Studio's Send dialog sends, resolved the way it
3
- * resolves them, so every print route sends what Bambu's own Print button
4
- * would. Source: Bambu Studio v02.08.02.61 (commit 926a7192574b), the version
3
+ * resolves them, for the vendor SDK. Direct routes report which options their verified
4
+ * wire format can carry; this does not establish SDK packet equivalence. Source: Bambu Studio v02.08.02.61 (commit 926a7192574b), the version
5
5
  * the hidden-HMS and stage tables are pinned to:
6
6
  *
7
7
  * - SelectMachine.cpp:3344-3356 `set_print_config(bed_type,
@@ -177,3 +177,35 @@ export function usedNozzleCount(inspection) {
177
177
  const nozzles = inspection.usedFilamentPositions.map(position => inspection.filamentNozzleIndices?.[position]).filter((value) => Number.isInteger(value));
178
178
  return nozzles.length === inspection.usedFilamentPositions.length && nozzles.length ? new Set(nozzles).size : undefined;
179
179
  }
180
+ /** Report only verified direct-wire fields. A task boolean is not an SDK mode.
181
+ * null means this route does not transmit that option, not off/auto/unknown hardware state. */
182
+ export function directPrintOptionReport(caller, resolved, packet) {
183
+ const fields = {
184
+ bedLeveling: ["task_bed_leveling", "bed_leveling"],
185
+ flowCalibration: ["task_flow_cali", "flow_cali"],
186
+ vibrationCalibration: ["task_vibration_cali", "vibration_cali"],
187
+ layerInspect: ["task_layer_inspect", "layer_inspect"],
188
+ autoBedLeveling: ["auto_bed_leveling", "auto_bed_leveling"],
189
+ autoFlowCali: ["auto_flow_cali", "auto_flow_cali"],
190
+ autoOffsetCali: ["auto_offset_cali", "nozzle_offset_cali"],
191
+ extruderCaliManualMode: ["extruder_cali_manual_mode", "extrude_cali_manual_mode"],
192
+ };
193
+ const requested = {};
194
+ const transmitted = {};
195
+ const unsupported = [];
196
+ for (const key of Object.keys(fields)) {
197
+ const [sdk, wire] = fields[key];
198
+ if (caller[key] !== undefined)
199
+ Object.assign(requested, { [key]: caller[key] });
200
+ const value = packet[wire];
201
+ transmitted[sdk] = typeof value === "boolean" || typeof value === "number" ? value : null;
202
+ if (caller[key] !== undefined && transmitted[sdk] === null)
203
+ unsupported.push(key);
204
+ }
205
+ const omitted = Object.keys(transmitted).filter(key => transmitted[key] === null);
206
+ const warning = omitted.length
207
+ ? `Direct print options not transmitted: ${omitted.join(", ")}. Task booleans are not equivalent to Studio integer modes.` +
208
+ (unsupported.length ? ` Requested overrides unsupported by this route: ${unsupported.join(", ")}. Use a vendor bridge/native route that supports these options if required.` : "")
209
+ : undefined;
210
+ return { requested, resolved, transmitted, unsupported, ...(warning ? { warning } : {}) };
211
+ }
@@ -24,6 +24,8 @@ export const TOOL_ANNOTATIONS = {
24
24
  resolve_3mf_ams_slots: READ_OUTSIDE, // reads the live AMS inventory
25
25
  list_printer_files: READ_OUTSIDE,
26
26
  counterpart_print_progress: READ_OUTSIDE,
27
+ counterpart_print_record: READ_LOCAL,
28
+ counterpart_print_assess: hints(false, false, true, false),
27
29
  counterpart_discover_printers: READ_OUTSIDE, // listens for the printers' own SSDP announcements
28
30
  counterpart_propose_filaments: READ_OUTSIDE, // reads the live AMS inventory
29
31
  // connect: true starts the bridge agent, which writes its configuration and device identity and can replace certificates.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.90",
3
+ "version": "1.1.92",
4
4
  "description": "MCP server for Bambu Lab 3D printers with STL manipulation, slicing, and print management",
5
5
  "main": "dist/index.js",
6
6
  "repository": {
@@ -55,6 +55,7 @@
55
55
  "jszip": "^3.10.2",
56
56
  "mqtt": "^5.16.1",
57
57
  "patch-package": "8.0.1",
58
+ "saxes": "^6.0.0",
58
59
  "sharp": "0.35.5",
59
60
  "three": "^0.173.0",
60
61
  "xml2js": "^0.6.2"
@@ -221,7 +221,7 @@ function isRegularFile(file: string): boolean {
221
221
  */
222
222
  function resolveNativeInstall(): NativeInstall {
223
223
  if (!isBambuNativePlatform()) {
224
- throw new Error("Bambu native X2D transport requires macOS or x86-64 Linux and Bambu's networking plug-in.");
224
+ throw new Error("Bambu native transport requires macOS or x86-64 Linux and Bambu's networking plug-in.");
225
225
  }
226
226
  const helper = resolveNativeHelper();
227
227
  if (process.platform !== "linux") return { helper, env: {} };
@@ -113,7 +113,7 @@ export const CAD_TOOLS = [
113
113
  {
114
114
  name: "cad_run",
115
115
  description:
116
- "Build parametric CAD headlessly in OS confinement. Read cad_design first: declare literal P = {...} and build() returning a build123d Shape. Supply script OR script_path; parameters overrides saved named values in one call before derived dimensions. Calls wait for the environment’s exclusive execution slot up to their own deadline and report queue_wait_ms. Each call creates a private immutable subfolder under allowed output_dir, never overwriting previous artifacts. The saved .py and .parameters.json are the recovery checkpoint even after cancellation. Returns independently measured geometry, STL/STEP, six orthographic renders, a perspective view and a contact sheet, the closest approach between every pair of solids (bodies), problems, and what was checked and not checked; valid means only that the exported geometry is sound, never that the part fits, holds, moves or prints.",
116
+ "Build parametric CAD headlessly in OS confinement. Read cad_design first: declare literal P = {...} and build() returning a build123d Shape. Supply script OR script_path; parameters overrides saved named values in one call before derived dimensions. Calls wait for the environment’s exclusive execution slot up to their own deadline and report queue_wait_ms. Each call creates a private immutable subfolder under allowed output_dir, never overwriting previous artifacts. The saved .py and .parameters.json are the recovery checkpoint even after cancellation. Returns independently measured geometry, STL/STEP, six orthographic renders, a perspective view and a contact sheet (with next: read the perspective view before the next change), the closest approach between every pair of solids (bodies), problems, what was checked and not checked, and printed: whatever the script wrote with print(), capped at 4000 characters, so a design can report a number it computed; valid means only that the exported geometry is sound, never that the part fits, holds, moves or prints.",
117
117
  inputSchema: {
118
118
  type: "object" as const,
119
119
  properties: {
@@ -225,6 +225,12 @@ export const CAD_TOOLS = [
225
225
  checked: { type: "array", items: { type: "string" } },
226
226
  not_checked: { type: "array", items: { type: "string" } },
227
227
  renders: { type: "object", additionalProperties: { type: "string" } },
228
+ next: { type: "string", description: "What to do before the next change: look at the perspective render." },
229
+ printed: {
230
+ type: "string",
231
+ description:
232
+ "The script's own print() output from this run, capped at 4000 characters (build.log keeps the rest). The script's words, not a measurement by the engine.",
233
+ },
228
234
  seconds: { type: "number" },
229
235
  },
230
236
  [
@@ -251,7 +257,7 @@ export const CAD_TOOLS = [
251
257
  {
252
258
  name: "cad_examples",
253
259
  description:
254
- "The code engine's cookbook: worked build123d designs from simple to complex, each modelled on the best bought version of the thing, with its concept, published sizes and script. Without arguments, lists them (name, title, the pattern each shows, the product it is modelled on). With name, returns that example's record and full script to adapt. Read-only; starts no process.",
260
+ "The code engine's cookbook: worked build123d designs from simple to complex, each modelled on the best bought version of the thing, with its concept, published sizes and script. Without arguments, lists them by purpose (name, title, use_for: the requests it suits, the pattern it shows, the product it is modelled on): choose by use_for before choosing a mechanism. With name, returns that example's record and full script to adapt. Read-only; starts no process.",
255
261
  inputSchema: {
256
262
  type: "object" as const,
257
263
  properties: {
@@ -271,15 +277,17 @@ export const CAD_TOOLS = [
271
277
  properties: {
272
278
  name: { type: "string" },
273
279
  title: { type: "string" },
280
+ use_for: { type: "string" },
274
281
  pattern: { type: "string" },
275
282
  modelled_on: { type: "string" },
276
283
  },
277
- required: ["name", "title", "pattern"],
284
+ required: ["name", "title", "use_for", "pattern"],
278
285
  },
279
286
  },
280
287
  usage: { type: "string" },
281
288
  name: { type: "string" },
282
289
  title: { type: "string" },
290
+ use_for: { type: "string" },
283
291
  pattern: { type: "string" },
284
292
  modelled_on: { type: "string" },
285
293
  published_sizes: { type: "string" },
@@ -293,7 +301,7 @@ export const CAD_TOOLS = [
293
301
  {
294
302
  name: "cad_check_fit",
295
303
  description:
296
- "Check two allowed watertight manifold STL meshes in millimetres. Applies only the explicit rigid transform to reference: XYZ rotation in degrees about the origin, then translation. Never silently scales a scan. Reports Boolean interference volume and minimum surface gap (zero on contact/intersection), plus a clearance verdict; intentional support contact also has zero gap. Fails rather than guessing for open meshes or excessive triangle workload.",
304
+ "Check two allowed watertight manifold STL meshes in millimetres. Applies only the explicit rigid transform to reference: XYZ rotation in degrees about the origin, then translation. Never silently scales a scan. Reports Boolean interference volume and minimum surface gap (zero on contact/intersection), plus a clearance verdict; intentional support contact also has zero gap. Like cad_run, a call waits for the environment's exclusive execution slot up to its timeout_ms and reports queue_wait_ms, so several checks may be sent at once. Fails rather than guessing for open meshes or excessive triangle workload.",
297
305
  inputSchema: {
298
306
  type: "object" as const,
299
307
  properties: {
@@ -341,6 +349,7 @@ export const CAD_TOOLS = [
341
349
  outputSchema: output(
342
350
  {
343
351
  units: { type: "string", const: "mm" },
352
+ queue_wait_ms: { type: "integer" },
344
353
  interference_volume_mm3: { type: "number" },
345
354
  minimum_gap_mm: { type: "number" },
346
355
  clearance_mm: { type: "number" },
@@ -365,9 +374,10 @@ export const CAD_DESIGN_PROMPT = {
365
374
  description:
366
375
  "MCP-owned rules for headless build123d designs and one-call parameter revisions.",
367
376
  text: `Use code-CAD for dimensioned functional designs and parameter edits. Build in millimetres with build123d 0.13.0; the MCP owns the Python environment, execution, export, validation and rendering. Check cad_status and use cad_setup with install: true when needed. No Blender, Fusion, network or printer access is available to your script.
368
- Form first: build the product's shape, not a profile pushed up. Before any geometry, write the concept in a few lines: the bought product you are following, its mechanism, the load path, the print orientation and why. build123d has loft (through sections of different shape), sweep (a section along a path or a Helix), revolve, fillet, chamfer, offset and shell as well as extrude; use the one the product's surface calls for: lofted where a hand closes round it, revolved where it turns, swept where it runs like a bent rod or a thread, filleted where two surfaces meet under load. Extrude a flat profile only for something that really is a plate or a lever, or for a print-in-place mechanism or spring that must lie in the layers, and say that reason in the result. Choose the print orientation after the form: split a part, turn it or accept a modest support before flattening its design.
369
- Worked examples: cad_examples lists this engine's cookbook (each modelled on a bought product, with its concept, published sizes and script) and returns one script by name. When the request works like one of these, read that example first and adapt its pattern, never its sizes:
377
+ A new design starts from the product, in this order. First, name two or three products a person would buy for this request (search when you are not sure what is sold) and say which one the design follows. Second, choose from the cookbook by purpose: the list below says what each example is for (cad_examples with no name returns it with each one's pattern and product). Read the example whose use is nearest the request, with cad_examples and its name, before deciding anything else, and adapt its form and pattern, never its sizes. Third, and only then, choose the mechanism (a clamp, screw, spring, hinge or snap) and read a second example for it if you need one. A mechanism chosen before the product gives a bracket with the mechanism bolted on.
378
+ The cookbook, by what each example is for:
370
379
  ${cadExampleLines()}
380
+ Form first: build the product's shape, not a profile pushed up. Before any geometry, write the concept as the script's opening docstring, the way every cookbook example does: what it is, then "Modelled on:" the bought product you named, its mechanism, the load path, the print orientation and why. A script whose header names no product was designed from the mechanism. build123d has loft (through sections of different shape), sweep (a section along a path or a Helix), revolve, fillet, chamfer, offset and shell as well as extrude; use the one the product's surface calls for: lofted where a hand closes round it, revolved where it turns, swept where it runs like a bent rod or a thread, filleted where two surfaces meet under load. Extrude a flat profile only for something that really is a plate or a lever, or for a print-in-place mechanism or spring that must lie in the layers, and say that reason in the result. Choose the print orientation after the form: split a part, turn it or accept a modest support before flattening its design.
371
381
  What the cookbook taught about this engine: return several bodies as Compound([a, b]); bodies that touch or overlap come back invalid, so leave a real gap (0.2 mm or more) or union them, and check that solid_count equals the bodies you intend (for a print-in-place mechanism that count is the first evidence nothing fused). fillet() often fails on the edges of an outline unioned from many curves, where chamfer() usually succeeds: fillet or chamfer simple bodies before the booleans that complicate them, and when a chamfer fails too, apply it to the plain body and union the details on afterwards. Do not round a sketch by growing and shrinking it with offset(): the solid looks right and its STEP comes back with no solids (the step_solids check fails). A whole Sphere() exports open at its poles: trim them (Sphere(r) & Box(2 * r, 2 * r, 2 * r - 0.1)). One fillet of the same radius over every edge of a box can export open: fillet in two passes with different radii. A model with moving parts takes a pose parameter: the assembled pose to judge it, the print plate to make it.
372
382
  Declare exactly one top-level P = {...} dictionary of JSON-compatible literal named parameters. Put every functional dimension in P; derive geometry from P. Define build() to return a build123d Shape or Compound of disjoint solid parts. When a design has separate bodies (print-in-place parts, a captive wheel, links of a fabric), return Compound(children=[...]) with a label on each body: cad_run then checks that each labelled body is exactly one solid, so a piece cut off one body cannot hide behind two bodies fused into one. Near pairs of solids are screened and, where the screen cannot clear them, measured exactly against P["print_in_place_clearance_mm"] when you declare it, else 0.3 mm. If the bodies are shown assembled rather than printed in place (a shaft in its hole at a fit clearance), set P["print_in_place"] = False: only touching or overlap is then a problem. Export in print orientation with the plate at Z = 0: a solid below it, or above it with nothing under it that reaches it, is a problem. Do not put construction or exports in a __main__ block: cad_run calls build() and exports the result. Imports, functions and derived P entries are fine. Parameters are applied to the literal defaults before derived expressions execute. For solid designs without inputs, the script and parameters file alone reconstruct it. For input-dependent designs, declare inputs as an array of {name, path} files: cad_run snapshots only those allowed files, exposes INPUTS[alias] to your script, and saves an inputs manifest. Retain the snapshots too for recovery; subsequent script_path edits reuse them unless inputs is explicitly supplied. No other personal files are readable. For a mesh-only experiment use mode: "mesh" and return a trimesh.Trimesh from build(); it exports and checks STL plus the same renders, with step: null and an explicit reason. It does not manufacture a fake parametric STEP or promise scan-cleanup capability.
373
383
  Call cad_run with script, output_dir and a plain name. It saves <name>.py and <name>.parameters.json before running, then exports <name>.stl and <name>.step in a fresh subfolder. For an edit, one cad_run with script_path pointing to the earlier .py, parameters containing just the changed dimension, output_dir and name regenerates it without resending the script. Existing parameter values are retained; unknown names and type changes are refused. A killed run can be retried from its checkpoint in a new workspace; mutations are never replayed automatically.
@@ -376,7 +386,7 @@ Fit reference workflow: return load_scan("scan", source_units="m", up_axis="y")
376
386
  Result selection and edits: set final: true only on the result you select. cad-result.json in each immediate run folder is protected from script writes and retains final, completed_at, lineage_id (source hash), full checks and artifact paths; clients can discover the latest completed final record after restart without rebuilding. Final is a selection marker, not a replacement for valid/checks. Queued calls may expire with cad-queue-timeout before dispatch; do not automatically replay. Unchanged declared files reuse a read-only content-addressed bundle under output_dir/.cad-inputs, preserving filenames and restricting reads to that bundle. Keep this shared cache with the saved runs.
377
387
  Mesh cleanup workflow: return a trimesh.Trimesh in mode: "mesh". Load the prepared mesh, fit needed geometry with NumPy/SciPy, rebuild regular sections/features with build123d or manifold3d CrossSection/extrusion/revolve, and combine meshes with manifold3d booleans. scikit-image supplies marching cubes for voxel/SDF work; Shapely supplies planar operations; Pillow supplies image/texture reads. Keep numeric choices in P and regenerate from declared inputs. Validate closure, winding, manifold status, dimensions and all six views using cad_run. What to regularise, infer, preserve or label comes from the caller's cleanup rules, not this engine prompt.
378
388
  Captured scan touch-up: t = scan_touchup(load_scan("scan", source_units="m", up_axis="y", ground=False), colour="colour", normal="normal", edge_mm=0.4) takes a textured capture (declare its OBJ, MTL and colour and normal map PNGs as inputs; pass the map aliases). It removes loose pieces and spikes, closes holes and refines to edge_mm without shrinking the body. t.regions() prints the colour regions (id, colour, area, size, flatness; 0 is the body) to build.log and saves regions.png in the run folder: read both, then name regions by id in the same scan and edge_mm. t.flatten(ids, shape="plane" or "curved"), t.bead(id, diameter_mm, proud_mm), t.cord(id, diameter_mm, proud_mm) (a cord follows its region's own curve) and t.seat(height_mm) record steps; return t.mesh(relief_gain=1.0), which adds the normal map's measured relief, applies the steps with manifold3d and prints its changes. Keep relief_gain at 1: a larger gain amplifies the map's noise, not stitches. When the caller's rules call for a textile's relief the scan missed (fabric, knit, crochet the photos show raised), t.texture_relief(height_mm, regions=None) raises its stitch pattern from the colour texture on the textile only (never flattened, beaded or corded regions); about 0.6 to 1.0 mm peak to peak prints visibly. It is off unless called: never for hard objects, printed graphics or labels.
379
- The result includes paths, millimetre bounds/size, mesh and STEP volumes, solid count, watertight/manifold/winding/STEP checks, bodies (closest approach between solids, contact with the print plate at Z = 0, labelled bodies that are not one solid), problems, checked and not_checked, six orthographic renders (front, back, left, right, top, bottom), a perspective view from the front right and above, and a contact sheet with the perspective view large beside the six. Fix every entry in problems before selecting a result; an empty problems list proves nothing listed in not_checked. Judge the form from the perspective view first: would a person recognise the product and want it? Then inspect all six; revise visible defects. A valid mesh or nominal parameter does not prove the requested dimension: measure the actual exported interfaces. Use cad_check_fit on a model and reference STL with an explicit rigid transform; report raw-scan interference and minimum gap. Calipers are authoritative but disagreement with a scan is unresolved measurement evidence, not permission to silently rescale it. Check assembly/insertion paths and actual articulated poses, not sums of local joint limits or reference points alone. Printing, clearance under load, supports and motion need separate evidence.
389
+ The result includes paths, millimetre bounds/size, mesh and STEP volumes, solid count, watertight/manifold/winding/STEP checks, bodies (closest approach between solids, contact with the print plate at Z = 0, labelled bodies that are not one solid), problems, checked and not_checked, six orthographic renders (front, back, left, right, top, bottom), a perspective view from the front right and above, and a contact sheet with the perspective view large beside the six. Fix every entry in problems before selecting a result; an empty problems list proves nothing listed in not_checked. After every cad_run, Read its perspective view (renders.perspective, as the result's next says) before the next cad_run or any other change: a run you have not looked at tells you nothing about the form. Judge the form from the perspective view first: would a person recognise the product and want it? Then inspect all six; revise visible defects. Before the final run, list what the views show is wrong against the bought product you named (for a scan, the object in its photos), and fix each one or report it. To get a number out of a design (a spring force, a strain, a clearance you derived), print() it in the script: the result returns it as printed, with no need to make a run fail. A valid mesh or nominal parameter does not prove the requested dimension: measure the actual exported interfaces. Use cad_check_fit on a model and reference STL with an explicit rigid transform; report raw-scan interference and minimum gap. Calipers are authoritative but disagreement with a scan is unresolved measurement evidence, not permission to silently rescale it. Check assembly/insertion paths and actual articulated poses, not sums of local joint limits or reference points alone. Printing, clearance under load, supports and motion need separate evidence.
380
390
  Fit, flexure and thread parameters: put each interface's nominal size, its source (measured, published, or assumed), the print correction, and the design fit in P as separate named values, so a fit report revises one number without resending the script. Model every dimension you claim: a parameter the geometry never uses (a wallet or case width that no cut or wall reads) is a defect; use it or remove it. Shape flexures so their bending lies in the layer plane of the exported print orientation, with the stroke, preload, and hard-stop gap as P values; build the stopped pose as well as the rest pose when checking. Model printed threads as explicit coarse geometry with the same pitch on both sides and clearance as a radial P offset; never scale a screw to clear its hole.
381
391
  Check insertion and articulated poses with cad_check_fit against each object state that matters (the bare product, the product in its case, and the case with its attachment as its own reference envelope), including the widest section on the way in. Report interference and minimum gap per state. In your summary, attach each "fits", "holds", and "prints without supports" claim to the check or slice number that shows it; a valid flag alone shows none of them. Apply fdm_design and fdm_slicing too. When a part meets a real object apply fdm_fit, and when it flexes, grips, snaps or springs apply fdm_flexures: if they were not attached, read them with the design_guidance tool before choosing that fit or spring. Never invoke a printer as part of constructing CAD.`,
382
392
  };
@@ -1,4 +1,5 @@
1
1
  """Bag-sealing clip: two hinged bars, ridge into groove, snap latch, printed in place
2
+ Use for: closing a bag of food or sealing film; any clip with two hinged bars and a latch
2
3
  Pattern: bar cross-section drawn in YZ and extruded along the bar; revolved waisted pin in a C-socket; ridge and its offset as the groove; modelled SHUT, then one bar swung open for printing
3
4
  Modelled on: Linden Sweden Twixit! bag clip (https://www.webstaurantstore.com/linden-sweden-411-8-twixit-blue-4-1-4-pastry-bag-clips-pack/534411.8.html); mechanism as in the hinged-bar clip patent US 4656697, Naslund (https://patents.google.com/patent/US4656697)
4
5
  Published sizes used: 108 mm (4 1/4 in) = overall length (retailer, https://www.webstaurantstore.com/linden-sweden-411-8-twixit-blue-4-1-4-pastry-bag-clips-pack/534411.8.html); nothing else is published, the other sizes are design choices
@@ -1,4 +1,5 @@
1
1
  """Pocket clicker: a bistable double curved beam in a closed frame
2
+ Use for: a fidget or clicker; any part that must snap between two stable positions
2
3
  Pattern: a computed 2D curve (cosine beam from a formula) made into a face, extruded flat with a filleted frame round it
3
4
  Modelled on: the double curved-beam bistable mechanism of Qiu, Lang and Slocum, "A curved-beam bistable mechanism", J. Microelectromechanical Systems 13(2), 2004, pp. 137-146 (https://manuscript.isc.ac/Inventory/49/950908.htm)
4
5
  Published sizes used: bistability ratio rise / thickness must exceed about 2.31 for a cosine beam clamped at both ends with its twisting mode blocked (Qiu, Lang and Slocum 2004, URL above); here rise / thickness = 3.0. All other sizes are design choices.
@@ -0,0 +1,61 @@
1
+ """Wall-mounted spring grip for a broom or mop handle (one screw, snap-in C with flared lips)
2
+ Use for: storing a broom, mop, rake, torch or any round handle or pipe 19 to 29 mm thick on a wall or inside a cupboard door; any snap-in spring clip that grips a round bar
3
+ Pattern: sweep one rounded section round the handle's axis for the C ring; pad and lip beads as simple bodies chamfered before they are joined; one countersunk screw through the seat, reached through the mouth
4
+ Modelled on: National Hardware spring grip clips for handles (https://www.doitbest.com/product/222143/national-rust-resistant-spring-grip-clip-hook-222143/); screw is SPAX 4.0 mm flat countersunk (https://www.ahlsell.se/en/products/mounting/wood-screw/wood-screw-spax/71333788---traskruv-tft-spax-svart-4.0x25h-200fp-eta-120114)
5
+ Published sizes used: 3/4 to 1 1/8 in (19 to 28.6 mm) = handle diameters the bought steel clip takes (retailer listing, first URL); 4.0 mm = screw thread, 8.0 mm = head diameter, 2.4 mm = head height (SPAX listing, second URL); ring, wall and mouth sizes are design choices
6
+ Concept: A clip on the wall that a broom handle is pushed into and pulled out of with one hand. Frame: the wall is the plane y = 0 and the mouth faces away from it, towards -y (the front view). The handle spreads two arms as it passes the mouth and they close behind it; the ring is made 1 mm smaller than the handle so it keeps squeezing and the broom does not slide down. The bought clip is spring steel; plastic arms must be longer and thicker to do the same job, so the ring wraps 230 degrees and the arms are 4 lines (1.68 mm) thick: opening the 20 mm mouth to a 25 mm handle strains them about 2 percent, and the script prints that figure for whatever sizes it is given. Round beads on the lips guide the handle in and are kind to its paint. The screw sits in the seat, where the handle covers it, and pulls the pad flat to the wall. It is printed with the C outline on the bed, the handle's axis upright, so the arms bend within their layers; printed lying on the pad they would split along a layer the first time. No supports. PETG (PLA arms creep open in a warm cupboard), 4 walls.
7
+ What makes this good: it is sized as a spring, not as a bracket, with the strain worked out in the script, and the one screw is hidden under the handle.
8
+ """
9
+ from math import acos, asin, degrees, radians
10
+
11
+ from build123d import *
12
+
13
+ P = {
14
+ "handle_d": 25.0, # the handle it grips (inside the published 19 to 28.6 mm range)
15
+ "squeeze": 1.0, # ring is this much smaller than the handle, so it grips
16
+ "mouth": 20.0, # gap between the beads, 80% of the handle
17
+ "arm_t": 1.68, # ring wall: 4 lines of 0.42, thin enough to spring
18
+ "bead_r": 1.6, # round bead on the end of each arm: lead-in outside, retaining bump inside
19
+ "pad_over": 1.0, # the pad stands this far above the seat; lower leaves more arm free to bend
20
+ "height": 22.0, # along the handle = height off the bed as printed
21
+ "pad_w": 34.0, # wall pad width
22
+ "pad_t": 5.0, # wall to the seat; leaves 2.6 mm under the screw head
23
+ "screw_d": 4.0, # screw thread diameter (published)
24
+ "screw_head_d": 8.0, # head diameter (published)
25
+ "screw_head_h": 2.4, # head height (published)
26
+ "screw_clear": 0.5,
27
+ "edge": 0.8, # softening of the ring's, beads' and pad's edges
28
+ }
29
+
30
+
31
+ def build():
32
+ h, e = P["height"], P["edge"]
33
+ r_in = (P["handle_d"] - P["squeeze"]) / 2
34
+ r_mid = r_in + P["arm_t"] / 2
35
+ yc = P["pad_t"] + r_in # ring centre: the seat is pad_t from the wall
36
+ half = degrees(asin((P["mouth"] / 2 + P["bead_r"]) / r_mid)) # half the mouth angle: the beads end up `mouth` apart
37
+ up = (Align.CENTER, Align.CENTER, Align.MIN)
38
+
39
+ # each piece is a simple body with its own softened edges, then they are joined: an outline chamfered after the
40
+ # union fails here. The ring is one section swept round the handle's axis, open at the mouth.
41
+ arc = Pos(0, yc, h / 2) * CenterArc((0, 0), r_mid, 90 + half, 360 - 2 * half)
42
+ ring = sweep(Plane(arc @ 0, x_dir=(0, 0, 1), z_dir=arc % 0) * RectangleRounded(h, P["arm_t"], e), path=arc)
43
+ bead = Cylinder(P["bead_r"], h, align=up)
44
+ bead = chamfer(bead.edges(), e) # lead-in outside the arm, retaining bump inside it
45
+ pad_y = P["pad_t"] + P["pad_over"]
46
+ pad = Pos(0, pad_y / 2, 0) * Box(P["pad_w"], pad_y, h, align=up)
47
+ pad = fillet(pad.edges().filter_by(Axis.Z).filter_by_position(Axis.Y, 1, 99), 3.0) # round the two front corners in plan
48
+ pad = chamfer(pad.edges().group_by(Axis.Z)[0] + pad.edges().group_by(Axis.Z)[-1], e)
49
+ grip = ring + pad + [Pos(arc @ u) * Pos(0, 0, -h / 2) * bead for u in (0, 1)]
50
+ grip -= Pos(0, yc, 0) * Cylinder(r_in, h, align=up) # the seat, cleared through the pad
51
+
52
+ # the spring, worked out: each arm is a cantilever from where the ring leaves the pad round to its bead,
53
+ # and the handle pushes each bead out by half of (handle - mouth)
54
+ free = radians(180 - half) - acos((r_in - P["pad_over"]) / (r_in + P["arm_t"]))
55
+ strain = 1.5 * P["arm_t"] * (P["handle_d"] - P["mouth"]) / 2 / (r_mid * free) ** 2
56
+ print(f"arm strain while the handle passes the mouth: {100 * strain:.1f} % (keep to about 2 % for PETG)")
57
+
58
+ hole_r, head_r = (P["screw_d"] + P["screw_clear"]) / 2, (P["screw_head_d"] + P["screw_clear"]) / 2
59
+ screw = Cylinder(hole_r, 4 * P["pad_t"]) + Cone(hole_r, head_r, P["screw_head_h"], align=(Align.CENTER, Align.CENTER, Align.MAX)) \
60
+ + Cylinder(head_r, 6, align=(Align.CENTER, Align.CENTER, Align.MIN)) # head recess clear up into the seat
61
+ return Rot(0, 0, 180) * (grip - Pos(0, P["pad_t"], h / 2) * Rot(-90, 0, 0) * screw) # mouth towards the front view
@@ -1,4 +1,5 @@
1
1
  """Adhesive desk cable clip (single cable, snap-in C channel on a taped pad)
2
+ Use for: holding one cable, cord or charger lead on a desk, wall or bedside; any small stick-on snap-in clip
2
3
  Pattern: sweep a rounded (slot) section along an arc for the C ring + loft the pad up into it, fillet the lip tips
3
4
  Modelled on: 3M Command Clear Round Cord Clips 17017CLR (https://argo.webstaurantstore.com/3m-command-8482-7100027385-clear-round-cord-clips-pack/39917017CLRES.html)
4
5
  Published sizes used: 13/16 in (20.6 mm) = clip width, 1/2 in (12.7 mm) = clip depth (retailer, URL above); cable diameter, mouth and wall are design choices
@@ -1,4 +1,5 @@
1
1
  """Chainmail patch: rigid square links that pass through each other, printed in place
2
+ Use for: flexible printed fabric, a strap or a mat made of linked rigid pieces
2
3
  Pattern: one link made from a rounded ring with two box cuts (two bars stay on the bed, two become bridges), then copied on a grid as a Compound of separate solids
3
4
  Modelled on: NASA/JPL "space fabric" (https://www.jpl.nasa.gov/news/space-fabric-links-fashion-and-engineering) and Ed Nisley's printable chain mail (https://softsolder.com/2014/12/04/3d-printed-chain-mail-armor-cosplay-edition/)
4
5
  Published sizes used: 2.4 mm = bar width, 6 threads of 0.40 mm (maker, https://softsolder.com/2014/12/04/3d-printed-chain-mail-armor-cosplay-edition/); JPL publishes no sizes; the other sizes are design choices
@@ -0,0 +1,91 @@
1
+ """Clamp-on desk headphone hook (rounded S frame, printed thumbscrew, hook hanging under the desk)
2
+ Use for: hanging headphones, a bag or a cable coil from a desk, shelf or table edge without tape or screws; any clamp that grips a board 18 to 30 mm thick with a printed screw
3
+ Pattern: one rounded section swept along a filleted S path (top jaw, spine, lower jaw, drop, hook, tip); a boss for the nut thread; the screw and nut threads are one section on one helix, the nut's moved out by the fit; "pose" shows it clamped or on the plate
4
+ Modelled on: Brainwavz Hoist headphone hanger with adjustable clamp (https://brainwavzaudio.com/de/products/brainwavz-hoist-headphone-hanger-with-adjustable-clamp)
5
+ Published sizes used: 5 to 40 mm = desk thickness the bought clamp takes, 50 mm = its hanger width (maker's listing, URL above); this printed one is sized for 18 to 30 mm desks and every other size is a design choice
6
+ Concept: Hangs a headset under the desk edge with nothing stuck or screwed to the desk. 2 bodies: the frame and the thumbscrew. Frame as used: the desk edge is at x = 0 and the desk runs towards +x; the top jaw lies on the desk, the spine passes in front of the edge, the lower jaw runs back under the desk and carries the threaded boss, then the frame drops and comes forward again as the hook, with an upturned tip at the front so the headband lifts on and off from where you sit. The screw comes up through the boss and presses the underside of the desk, so one frame takes any desk from 18 to 30 mm; the headphones' weight pulls the frame down onto the top jaw, so the clamp only has to stop it sliding. The knob hangs in the hook's opening, above where the headband rests. The frame is printed on its side so every layer holds the whole S and no bend is a layer joint; its threaded hole then lies level, which a 4 mm pitch, 45 degree thread survives without supports. The screw prints standing on its knob. Stick felt on the top jaw and the screw tip. PETG or PLA, 4 walls.
7
+ What makes this good: the whole frame is a single swept bar with large bends, so it reads as a bent-steel hanger, not a bracket, and the load goes round the bends inside the layers.
8
+ """
9
+ from build123d import *
10
+
11
+ P = {
12
+ "pose": "plate", # "plate": as printed, frame on its side and screw on its knob; "assembled": clamped on desk_t, standing as used (the screw is then off the plate, which cad_run notes: that pose is for looking, not printing)
13
+ "desk_t": 25.0, # the desk it is shown clamped on (assembled pose only)
14
+ "opening": 32.0, # between the jaws; takes desks up to 30 mm with a felt pad
15
+ "min_desk": 18.0, # thinnest desk the screw still reaches
16
+ "reach": 46.0, # jaws over the desk, from the desk edge
17
+ "bar_t": 10.0, # frame bar thickness, in the bending direction
18
+ "width": 26.0, # frame width = what the headband rests on
19
+ "edge_r": 3.0, # rounding of the bar's four long edges
20
+ "bend_r": 13.0, # centreline radius of every bend
21
+ "drop": 84.0, # lower jaw down to the hook arm (centrelines): knob plus a padded headband
22
+ "hook_len": 60.0, # hook arm, back towards the desk edge
23
+ "tip_h": 24.0, # upturned tip, centreline rise
24
+ "boss_h": 18.0, # threaded length through the lower jaw and its boss (4.5 turns)
25
+ "boss_l": 28.0, # boss length along the jaw
26
+ "thread_d": 14.0, # screw outside diameter
27
+ "pitch": 4.0, # coarse, so it prints lying level in the frame
28
+ "thread_depth": 1.2, # 45 degree flanks
29
+ "crest": 0.8, # flat on the thread crest
30
+ "fit": 0.4, # radial clearance, screw to nut
31
+ "knob_d": 32.0,
32
+ "knob_h": 11.0,
33
+ "flutes": 8,
34
+ "gap_on_plate": 10.0, # frame to screw on the plate
35
+ "print_in_place": False, # two parts assembled by hand: only touching is a problem
36
+ }
37
+
38
+
39
+ def thread(root_r, crest_r, z0, length):
40
+ """A 45 degree trapezoid swept along a helix about Z, from z0. root_r > crest_r makes the nut's thread."""
41
+ depth = crest_r - root_r
42
+ half_root = P["crest"] / 2 + abs(depth)
43
+ bury = 0.3 if depth > 0 else -0.3 # the flanks run on into the wall: no section corner lies on the wall's surface
44
+ section = Polygon((root_r - bury, -half_root - 0.3), (crest_r, -P["crest"] / 2),
45
+ (crest_r, P["crest"] / 2), (root_r - bury, half_root + 0.3), align=None)
46
+ return Pos(0, 0, z0) * sweep(Plane.XZ * section, path=Helix(P["pitch"], length, (root_r + crest_r) / 2), is_frenet=True)
47
+
48
+
49
+ def build():
50
+ t, w, r = P["bar_t"], P["width"], P["bend_r"]
51
+ major, root = P["thread_d"] / 2, P["thread_d"] / 2 - P["thread_depth"]
52
+ low = -P["opening"] - t / 2 # lower jaw centreline; the desk top is y = 0
53
+ x_spine = -(r - t / 2) - t / 2 # the inside of the bend ends at the desk edge
54
+ x_screw = P["reach"] - P["boss_l"] / 2
55
+
56
+ # frame, drawn lying on the bed: X into the desk, Y up as used, Z across the width
57
+ path = Polyline((P["reach"], t / 2), (x_spine, t / 2), (x_spine, low), (P["reach"] + r, low),
58
+ (P["reach"] + r, low - P["drop"]), (P["reach"] + r - P["hook_len"], low - P["drop"]),
59
+ (P["reach"] + r - P["hook_len"], low - P["drop"] + P["tip_h"]))
60
+ path = Pos(0, 0, w / 2) * fillet(path.vertices(), r)
61
+ frame = sweep(Plane(path @ 0, x_dir=(0, 0, 1), z_dir=path % 0) * RectangleRounded(w, t, P["edge_r"]), path=path)
62
+ ends = [frame.faces().sort_by_distance(path @ u)[0] for u in (0, 1)]
63
+ frame = fillet(ends[0].edges() + ends[1].edges(), P["edge_r"] - 0.5) # soft jaw end and hook tip; a radius over edge_r exports open
64
+ boss = Pos(x_screw, -P["opening"] - P["boss_h"] / 2) * RectangleRounded(P["boss_l"], P["boss_h"], 5)
65
+ frame += extrude(boss, w)
66
+
67
+ # threads in the screw's own frame: axis Z, origin on the lower jaw's top face. Plain hole first, then the
68
+ # nut's thread added to its wall (a thread subtracted from the cutter does not cut)
69
+ z_nut = -P["boss_h"] + 2.5
70
+ to_frame = Pos(x_screw, -P["opening"], w / 2) * Rot(-90, 0, 0)
71
+ frame -= to_frame * Cylinder(major + P["fit"], 3 * P["boss_h"])
72
+ frame += to_frame * thread(major + P["fit"], root + P["fit"], z_nut, P["boss_h"] - 5)
73
+
74
+ # screw: fluted knob, threaded shank long enough for the thinnest desk, tip and thread ends cut to a chamfer
75
+ shank = P["boss_h"] + P["opening"] - P["min_desk"] + 4
76
+ kh = P["knob_h"]
77
+ knob = fillet(Cylinder(P["knob_d"] / 2, kh, align=(Align.CENTER, Align.CENTER, Align.MIN)).edges(), 2.0)
78
+ flute = Pos(P["knob_d"] / 2 + 1.5, 0, 0) * Cylinder(4.0, kh, align=(Align.CENTER, Align.CENTER, Align.MIN))
79
+ knob -= [Rot(0, 0, i * 360 / P["flutes"]) * flute for i in range(P["flutes"])]
80
+ # the envelope is wider than the thread (a surface shared with the crest breaks the cut) and chamfers the tip
81
+ envelope = chamfer(Cylinder(major + 0.6, shank + 1, align=(Align.CENTER, Align.CENTER, Align.MIN)).edges().group_by(Axis.Z)[-1], P["thread_depth"] + 1.2)
82
+ screw = knob + Pos(0, 0, kh - 1) * ((Cylinder(root, shank + 1, align=(Align.CENTER, Align.CENTER, Align.MIN))
83
+ + thread(root, major, 2.0, shank - 3)) & envelope)
84
+
85
+ if P["pose"] == "plate":
86
+ return Compound([frame, Pos(P["reach"] + r + P["knob_d"] / 2 + P["gap_on_plate"], 0, 0) * screw])
87
+ # assembled: tip on the underside of the desk; the turn that puts the screw's ridge in the nut's groove
88
+ lift = P["opening"] - P["desk_t"] - (kh + shank)
89
+ turn = 360 * (lift + kh + 1 - z_nut) / P["pitch"] + 180
90
+ used = Rot(90, 0, 0) * Compound([frame, to_frame * Pos(0, 0, lift) * Rot(0, 0, turn) * screw])
91
+ return Pos(0, 0, -used.bounding_box().min.Z) * used
@@ -0,0 +1,55 @@
1
+ """Stick-on desk-edge cable holder (five sprung slots in one small rail)
2
+ Use for: keeping several charging cables (USB-C, Lightning, earphone leads) side by side at a desk edge, bedside or shelf so the plugs do not fall behind; any multi-slot stick-on cable organiser
3
+ Pattern: a comb drawn in the plane its arms bend in: per slot, two tapered spring arms with round beads over a cradled seat, patterned along a base with rounded end blocks; extruded to the rail's depth and its outline chamfered
4
+ Modelled on: Orico CBS5 5-slot self-adhesive silicone desk cable holder (https://www.scom.hu/ORICO-CBS5-GY-Cable-Organizer-Grey)
5
+ Published sizes used: 96 x 20 x 12 mm = the bought holder's length, depth and height, for cables under 5 mm (retailer listing, URL above); this rigid one is shorter because its slots sit closer, and the slot sizes are design choices
6
+ Concept: A small rail taped to the desk top at its edge (or to the edge's front face) that parks five cables. Each cable is pushed down between two round beads into a seat a little bigger than itself: it slides freely, cannot lift out, and its plug is too big to pull back through, so the end stays on the desk. The bought one is soft silicone, which a printer cannot copy, so each slot has two thin arms that spring apart instead: 12 mm long and 3 lines thick at the tip, they let a 5 mm cable through the 3.2 mm mouth at about 1.6 percent strain, and the script prints that figure for whatever sizes it is given. It holds cables from 3.4 to 5.0 mm; a thinner one lifts out. The arms taper to the base so they bend along their length, not at the root, and the gaps beside them are what lets them move. This one is rightly an extrusion: it is printed standing on its front face, comb outline on the bed, so every arm bends within its layers and none can snap along a layer line; printed tape-face down the arms would be weak. No supports. PETG, 0.2 mm layers; 12.7 mm foam tape on the flat underside.
7
+ What makes this good: it is as small as the thing you buy (about 68 x 16 x 16 mm for five cables), with no clamp or screw, and the spring is drawn and printed in the plane it bends in.
8
+ """
9
+ from build123d import *
10
+
11
+ P = {
12
+ "slots": 5,
13
+ "cable_max": 5.0, # thickest cable it takes
14
+ "seat_clear": 0.4, # seat is this much bigger than cable_max so every cable slides
15
+ "mouth": 3.2, # gap between the beads; holds cables from about 3.4 mm
16
+ "arm_tip_t": 1.26, # arm thickness under the bead: 3 lines of 0.42
17
+ "arm_root_t": 1.7, # arm thickness at the base: the taper spreads the bending along the arm
18
+ "pitch": 10.6, # slot to slot
19
+ "base_t": 3.0, # base under the seats (the taped strip)
20
+ "cradle": 1.0, # the seat is sunk this far into the base
21
+ "height": 16.0, # underside to the top of the beads; taller means longer, easier arms
22
+ "depth": 16.0, # along the cable = height off the bed as printed; room for 12.7 mm tape
23
+ "end_w": 7.0, # solid block at each end
24
+ "relief": 1.4, # gap between the outer arms and the end blocks
25
+ "edge": 0.6, # chamfer round both faces of the comb: no sharp edge on a cable jacket
26
+ }
27
+
28
+
29
+ def build():
30
+ seat_r = (P["cable_max"] + P["seat_clear"]) / 2
31
+ h, tip, root_t = P["height"], P["arm_tip_t"], P["arm_root_t"]
32
+ bead_r = (seat_r + tip - P["mouth"] / 2) / 2 # the bead spans from the mouth to the arm's outer face
33
+ seat_y = P["base_t"] + seat_r - P["cradle"] # seat centre
34
+ half = (P["slots"] - 1) * P["pitch"] / 2 + seat_r + root_t + P["relief"] + P["end_w"]
35
+
36
+ comb = Pos(0, P["base_t"] / 2) * Rectangle(2 * half, P["base_t"])
37
+ for side in (-1, 1): # end blocks, outer corners rounded
38
+ block = Pos(side * (half - P["end_w"] / 2), h / 2) * Rectangle(P["end_w"], h)
39
+ comb += fillet(block.vertices().sort_by(Axis.X)[2 if side > 0 else 0:][:2], P["end_w"] * 0.45)
40
+ for i in range(P["slots"]):
41
+ x = (i - (P["slots"] - 1) / 2) * P["pitch"]
42
+ for side in (-1, 1): # one tapered arm and its bead; the inner face is straight
43
+ pts = [(side * seat_r, 0), (side * (seat_r + root_t), 0), (side * (seat_r + tip), h - bead_r), (side * seat_r, h - bead_r)]
44
+ arm = Polygon(*pts[::side], align=None) # anticlockwise on both sides, so every face extrudes up
45
+ comb += Pos(x, 0) * (arm + Pos(side * (P["mouth"] / 2 + bead_r), h - bead_r) * Circle(bead_r))
46
+ comb -= Pos(x, seat_y) * Circle(seat_r) # the cradle in the base
47
+
48
+ # the spring, worked out: each arm is a cantilever from the base to its bead, pushed out by half of (cable - mouth)
49
+ arm_len = h - bead_r - P["base_t"]
50
+ t_base = root_t - (root_t - tip) * P["base_t"] / (h - bead_r)
51
+ strain = 1.5 * t_base * (P["cable_max"] - P["mouth"]) / 2 / arm_len ** 2
52
+ print(f"arm strain while the thickest cable passes the mouth: {100 * strain:.1f} % (keep to about 2 % for PETG)")
53
+
54
+ rail = extrude(comb, P["depth"])
55
+ return chamfer(rail.edges().group_by(Axis.Z)[0] + rail.edges().group_by(Axis.Z)[-1], P["edge"])
@@ -0,0 +1,56 @@
1
+ """Interlocking drawer divider grid (slotted strips that cross in half-laps)
2
+ Use for: dividing a drawer, box or shelf into compartments for cutlery, tools, socks or stationery; any grid of flat strips that slot together; flat parts cut to a measured space
3
+ Pattern: one function makes a strip from its length and slot count; every strip is a flat plate with rounded corners and half-depth slots with a lead-in; the set is laid out on the plate from the drawer's inside sizes, and "pose" stands it up as the grid
4
+ Modelled on: slotted plastic drawer divider strips, as in the 2 in high clip-and-strip sets (https://www.med-supply.net/products/divider-strip-only-2-inch)
5
+ Published sizes used: 2 in (50.8 mm) high x 21 1/4 in long = a bought strip (retailer listing, URL above), which is cut to the drawer; these are printed to length, so the drawer's inside length, width and height are the person's measurements
6
+ Concept: A grid that drops into a drawer and makes compartments. The long strips have slots cut down from the top edge and the cross strips have slots cut up from the bottom edge, each to half the height, so they cross flush like an egg crate and hold each other upright; the drawer's walls stop the grid sliding. Strips are 1 mm shorter than the drawer so they go in without bowing its sides. The slot is the strip thickness plus 0.3 mm: a hand push fit that still comes apart. Each strip is a plate, so it is drawn flat and extruded to its thickness, and printed lying down: the layers then run the length of the strip and it cannot split along its slots. 6 lines (2.4 mm) thick is stiff enough at 45 mm high. Measure the drawer at the bottom, where it is narrowest. PLA or PETG, no supports; a drawer longer than the bed needs each long strip in two halves butted at a cross strip.
7
+ What makes this good: it is sized from the three numbers a person can measure, every strip comes from one function, and the slots, not glue, do the holding.
8
+ """
9
+ from build123d import *
10
+
11
+ P = {
12
+ "drawer_l": 240.0, # inside length of the drawer (the person's measurement)
13
+ "drawer_w": 150.0, # inside width
14
+ "height": 45.0, # strip height: a few mm under the drawer's inside height
15
+ "long_strips": 2, # strips running the length
16
+ "cross_strips": 3, # strips running the width
17
+ "t": 2.4, # strip thickness: 6 lines of 0.4
18
+ "fit": 0.3, # slot is this much wider than the strip
19
+ "end_gap": 1.0, # strips are this much shorter than the drawer
20
+ "corner_r": 4.0, # rounded top corners
21
+ "lead_in": 1.2, # flare at the mouth of each slot
22
+ "gap_on_plate": 4.0,
23
+ "pose": "plate", # "plate": every strip lying flat, as printed; "assembled": the grid standing as it sits in the drawer
24
+ "print_in_place": False, # assembled, the strips sit in each other's slots at the fit: only touching is a problem
25
+ }
26
+
27
+
28
+ def strip(length, slots, from_top):
29
+ """A flat strip lying on the bed, `slots` equally spaced half-depth slots cut from its top or bottom edge."""
30
+ h, w = P["height"], P["t"] + P["fit"]
31
+ plate = Rectangle(length, h)
32
+ plate = fillet(plate.vertices().group_by(Axis.Y)[-1], P["corner_r"]) # top corners only: the bottom sits square
33
+ edge = h / 2 if from_top else -h / 2
34
+ inward = -1 if from_top else 1
35
+ for i in range(slots):
36
+ x = length * (i + 1) / (slots + 1) - length / 2
37
+ cut = Pos(x, edge + inward * h / 4) * Rectangle(w, h / 2 + 0.6) # 0.3 past half way, so the laps seat fully
38
+ pts = [(x - w / 2 - P["lead_in"], edge), (x + w / 2 + P["lead_in"], edge), (x + w / 2, edge + inward * P["lead_in"] * 2),
39
+ (x - w / 2, edge + inward * P["lead_in"] * 2)]
40
+ plate -= cut + Polygon(*pts[::-inward], align=None)
41
+ return Pos(0, h / 2) * extrude(plate, P["t"])
42
+
43
+
44
+ def build():
45
+ long_l, cross_l = P["drawer_l"] - P["end_gap"], P["drawer_w"] - P["end_gap"]
46
+ parts = [strip(long_l, P["cross_strips"], True) for _ in range(P["long_strips"])]
47
+ parts += [strip(cross_l, P["long_strips"], False) for _ in range(P["cross_strips"])]
48
+ if P["pose"] == "plate":
49
+ step = P["height"] + P["gap_on_plate"]
50
+ return Compound([Pos(-(long_l - s.bounding_box().size.X) / 2, i * step, 0) * s for i, s in enumerate(parts)])
51
+ # assembled: stand each strip up (its Y becomes Z), long strips along X, cross strips along Y, each centred in its slot
52
+ up = Rot(90, 0, 0) * Pos(0, 0, -P["t"] / 2)
53
+ longs = [Pos(0, cross_l * (j + 1) / (P["long_strips"] + 1) - cross_l / 2, 0) * up * parts[j] for j in range(P["long_strips"])]
54
+ crosses = [Pos(long_l * (i + 1) / (P["cross_strips"] + 1) - long_l / 2, 0, 0) * Rot(0, 0, 90) * up * parts[P["long_strips"] + i]
55
+ for i in range(P["cross_strips"])]
56
+ return Compound(longs + crosses)