bambu-printer-mcp 1.1.96 → 1.1.97

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 (46) hide show
  1. package/dist/cad/contracts.js +7 -5
  2. package/dist/cad-engine.js +1 -0
  3. package/dist/counterpart/info.js +1 -0
  4. package/dist/counterpart/make-3mf.d.ts +1 -0
  5. package/dist/counterpart/make-3mf.js +37 -5
  6. package/dist/counterpart/model-plates.d.ts +2 -0
  7. package/dist/counterpart/model-plates.js +3 -0
  8. package/dist/counterpart/part-meshes.d.ts +114 -0
  9. package/dist/counterpart/part-meshes.js +323 -0
  10. package/dist/counterpart/plate-filaments.d.ts +3 -0
  11. package/dist/counterpart/plate-filaments.js +31 -10
  12. package/dist/counterpart/remote.js +1 -0
  13. package/dist/counterpart/schemas.d.ts +10 -0
  14. package/dist/counterpart/schemas.js +2 -0
  15. package/dist/design-app-setup.d.ts +9 -0
  16. package/dist/design-app-setup.js +5 -2
  17. package/dist/design-guidance.d.ts +3 -3
  18. package/dist/design-guidance.js +8 -4
  19. package/dist/index.js +37 -6
  20. package/dist/refusal.d.ts +15 -1
  21. package/dist/refusal.js +19 -1
  22. package/dist/slicer/floating-regions.d.ts +54 -0
  23. package/dist/slicer/floating-regions.js +198 -0
  24. package/dist/slicer/profile-flatten.js +4 -0
  25. package/dist/tool-annotations.js +2 -0
  26. package/package.json +2 -2
  27. package/src/cad/contracts.ts +7 -5
  28. package/src/cad/project3mf.py +9 -4
  29. package/src/cad/scan_measure.py +207 -0
  30. package/src/cad/scan_touchup.py +4 -1
  31. package/src/cad/worker.py +2 -1
  32. package/src/cad-engine.ts +1 -0
  33. package/src/counterpart/info.ts +1 -0
  34. package/src/counterpart/make-3mf.ts +33 -7
  35. package/src/counterpart/model-plates.ts +4 -0
  36. package/src/counterpart/part-meshes.ts +304 -0
  37. package/src/counterpart/plate-filaments.ts +25 -9
  38. package/src/counterpart/remote.ts +1 -0
  39. package/src/counterpart/schemas.ts +4 -0
  40. package/src/design-app-setup.ts +7 -2
  41. package/src/design-guidance.ts +8 -4
  42. package/src/index.ts +38 -6
  43. package/src/refusal.ts +19 -1
  44. package/src/slicer/floating-regions.ts +187 -0
  45. package/src/slicer/profile-flatten.ts +3 -0
  46. package/src/tool-annotations.ts +2 -0
@@ -376,21 +376,23 @@ export const CAD_DESIGN_PROMPT = {
376
376
  title: "Parametric code-CAD design",
377
377
  description: "MCP-owned rules for headless build123d designs and one-call parameter revisions.",
378
378
  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.
379
- 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.
380
- Then state the purpose as data, before any geometry: a literal PURPOSE = {...} beside P (cad_run reads it from the source; parameters cannot change it). "for": what it is for in the person's words (who uses it, where, doing what); "modelled_on": the bought product; "holds": [{"body": name, "mass_g": grams}] for what it carries; "mounts": [{"body": name, "by": "tape", "rests", "screw", "clamp", "hook" or "other"}] for each surface that takes the load; "user": [x, y, z], the eye of the person who uses it, in mm in the use() frame, when it shows them something; optional "jolt_g", "press_n", "reach_mm", "material" and "faces": {"body": name, "within_deg": 25}. Its words add requirements whatever you list: a holder, hook, stand, dock, mount, rack, bracket, cradle or organizer must name what it holds and what it mounts to; anything in a vehicle takes jolts of at least 1.5 g in every direction; a phone, tablet or screen it holds must face the user's eye within 25 degrees. Then define use() beside build(): return Compound(children=[...]) of the part as it is used, Z up and gravity along -Z, with each held object at its real size and pose labelled "held:<body>" and each surface it meets as a solid slab where it really is (a dash face at its real angle, a desk's underside, a wall) labelled "world:<body>", all touching the part where they really touch. cad_run computes the loads at each mount from that geometry (gravity on the part and what it holds, the jolts, a hand pressing the held object), checks tape against 3M VHB's published stresses and that a resting part neither tips, lifts nor slides, checks that a held screen faces the user, draws renders.use (from the user's eye when given) and reports it all in purpose. final: true is recorded only when ready is true; until then the result lists final_refused. A run that is not the design itself (a part exported only for cad_check_fit, a reference, a diagnostic) is a check: pass role: "check" to every cad_run that is not the design itself, so it is never mistaken for the model (it is never final and evaluates no PURPOSE). Every valid run that is not final carries draft_reasons, saying why. When a requirement fails, change the design the way the bought products solve it (a joint that aims it, a broader pad, a wider or heavier base), never the purpose.
379
+ Build early, in pieces. The first cad_run is a rough but complete model within your first few turns: each main body at about its size and place, in simple shapes. Then add one body, mechanism or detail per run, read what the run returns, and go on. Never write a whole multi-part script in your head, and never plan the full design in one long thought before the first run: build, look, then add. A wrong first guess costs one quick run; a long plan that was never built costs many minutes and is still unchecked. Every check below still applies; each runs as soon as the geometry it checks exists, not before the first build. Call cad_run once at a time: the engine runs one call at a time, so parallel calls only queue.
380
+ A new design starts from the product, and each step before the first run is a sentence, not a study. First, name two or three products a person would buy for this request (search only 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 one example whose use is nearest the request, with cad_examples and its name, 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.
381
+ State the purpose as data in the first build, as a short first version, and complete it as the design grows: a literal PURPOSE = {...} beside P (cad_run reads it from the source; parameters cannot change it). "for": what it is for in the person's words (who uses it, where, doing what); "modelled_on": the bought product; "holds": [{"body": name, "mass_g": grams}] for what it carries; "mounts": [{"body": name, "by": "tape", "rests", "screw", "clamp", "hook" or "other"}] for each surface that takes the load; "user": [x, y, z], the eye of the person who uses it, in mm in the use() frame, when it shows them something; optional "jolt_g", "press_n", "reach_mm", "material" and "faces": {"body": name, "within_deg": 25}. Its words add requirements whatever you list: a holder, hook, stand, dock, mount, rack, bracket, cradle or organizer must name what it holds and what it mounts to; anything in a vehicle takes jolts of at least 1.5 g in every direction; a phone, tablet or screen it holds must face the user's eye within 25 degrees. Add use() beside build() once the main bodies exist, by the second or third run: return Compound(children=[...]) of the part as it is used, Z up and gravity along -Z, with each held object at its real size and pose labelled "held:<body>" and each surface it meets as a solid slab where it really is (a dash face at its real angle, a desk's underside, a wall) labelled "world:<body>", all touching the part where they really touch. cad_run computes the loads at each mount from that geometry (gravity on the part and what it holds, the jolts, a hand pressing the held object), checks tape against 3M VHB's published stresses and that a resting part neither tips, lifts nor slides, checks that a held screen faces the user, draws renders.use (from the user's eye when given) and reports it all in purpose. final: true is recorded only when ready is true; until then the result lists final_refused. A run that is not the design itself (a part exported only for cad_check_fit, a reference, a diagnostic) is a check: pass role: "check" to every cad_run that is not the design itself, so it is never mistaken for the model (it is never final and evaluates no PURPOSE). Every valid run that is not final carries draft_reasons, saying why. When a requirement fails, change the design the way the bought products solve it (a joint that aims it, a broader pad, a wider or heavier base), never the purpose.
381
382
  The cookbook, by what each example is for:
382
383
  ${cadExampleLines()}
383
- 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.
384
+ Form first: build the product's shape, not a profile pushed up. Write the concept in a few lines as the first build'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; correct it as the design firms up. 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.
384
385
  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.
385
386
  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.
386
387
  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.
387
388
  Captured mesh preparation: load_scan(name, source_units="m" or "mm", up_axis="x"|"-x"|"y"|"-y"|"z"|"-z", ground=True) is provided to build(). Name must be a declared input. Declare source units and the object's usage-up axis explicitly: the helper converts metres to millimetres, applies a rigid up-axis rotation and translates the lowest Z to zero; it never guesses scale or fits to calipers. Geometry/texture references must be declared inputs too; snapshots preserve distinct original filenames. Exports must be millimetres, Z up, in the orientation the object is used.
389
+ Measure a scan once, before designing from it: one check run (role: "check", mode: "mesh") whose build() is r = measure_scan(load_scan("scan", source_units="m", up_axis="y")); return r["mesh"]. It keeps the scan's main piece, removes the turntable or support it stands on (fitted even when tilted) and any floating pieces, and prints scan_measure: size_mm in the object's own frame (long side on x, across on y, height on z), profile (its length and depth at ten heights), what it removed, and scan-measure.png in the run folder (silhouettes seen from -y, +x and above, ticks every 10 mm); the returned mesh is the object alone in the scan's x and y, standing at z = 0. Read both and design from those numbers instead of writing measuring scripts of your own. When support_removed is set, check it against the photos: if the cut piece is the object's own base rather than a turntable, design from its uncut_size_mm. They carry the scan's accuracy: calipers or published sizes win where they exist.
388
390
  Fit reference workflow: return load_scan("scan", source_units="m", up_axis="y") from build() in mode: "mesh" to export an unchanged, prepared reference STL for cad_check_fit. Declare every linked OBJ/MTL/texture asset. If you crop, simplify, fill, or otherwise alter this reference, report exactly what you excluded/changed and that the fit check proves only that reduced reference in the stated pose. A fit check against a scan is information; it must never resize or override an interface specified by measured dimensions. Keep those measured interfaces and report the discrepancy.
389
391
  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.
390
392
  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.
391
- Multi-colour 3MF projects: build() may return project_3mf() instead of a shape. A new project: p = project_3mf(); p.add_part(shape, name="Lid", filament=2, object="Box", plate=1) for each part (parts that share object= are one object, printed as one piece; plates from 1), in solid mode with build123d shapes (the checks fuse each object's parts) or mode: "mesh" with trimesh parts. Editing a designer's 3MF: declare it as an input and p = project_3mf("kit") in mode: "mesh"; p.objects lists its objects (name, id, plate; p.object(id or unique name)) and their parts (name, id, filament, painted, mesh: a trimesh in the object's frame); p.add_part(shape, name=..., filament=..., object="Body") adds a part in that object's frame, p.replace_part(part, mesh) swaps a part's mesh (its painting goes with the old mesh) and p.set_part(part, name=..., filament=...) renames or recolours one; everything else in the file (print settings, painting, plates, other parts) is kept. cad_run writes <name>.3mf beside the STL and returns three_mf and three_mf_project (each plate's parts and filaments, read back from the file); slice it with slice_stl, never by rebuilding it from the STL.
393
+ Multi-colour 3MF projects: build() may return project_3mf() instead of a shape. A new project: p = project_3mf(); p.add_part(shape, name="Lid", filament=2, color="#1A1A1A", object="Box", plate=1) for each part (parts that share object= are one object, printed as one piece; plates from 1; color, given for every part or none, declares each filament's colour in the 3MF), in solid mode with build123d shapes (the checks fuse each object's parts) or mode: "mesh" with trimesh parts. Editing a designer's 3MF: declare it as an input and p = project_3mf("kit") in mode: "mesh"; p.objects lists its objects (name, id, plate; p.object(id or unique name)) and their parts (name, id, filament, painted, mesh: a trimesh in the object's frame); p.add_part(shape, name=..., filament=..., object="Body") adds a part in that object's frame, p.replace_part(part, mesh) swaps a part's mesh (its painting goes with the old mesh) and p.set_part(part, name=..., filament=...) renames or recolours one; everything else in the file (print settings, painting, plates, other parts) is kept. cad_run writes <name>.3mf beside the STL and returns three_mf and three_mf_project (each plate's parts and filaments, read back from the file); slice it with slice_stl, never by rebuilding it from the STL. A design in several colours gets them from the same run as the model: build() returns project_3mf() with one add_part per colour body, so one cad_run builds the shape once and writes the STL and the 3MF together. Never re-run the whole script once per colour to export each colour's STL: that repeats the full build for every colour.
392
394
  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.
393
395
  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.
394
396
  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.
395
- 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.`,
397
+ Once the bodies it involves exist, 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.`,
396
398
  };
@@ -367,6 +367,7 @@ export class CadEngine {
367
367
  "worker.py",
368
368
  "geometry.py",
369
369
  "scan_touchup.py",
370
+ "scan_measure.py",
370
371
  "project3mf.py",
371
372
  "purpose.py",
372
373
  "process.ts",
@@ -44,6 +44,7 @@ export function bambuPrinterInfo(options) {
44
44
  camera: model && TCP_CAMERA_MODELS.has(model) ? "bambu-tcp" : model && RTSP_CAMERA_MODELS.has(model) ? "rtsp" : "none",
45
45
  cameraStream: !!model && (TCP_CAMERA_MODELS.has(model) || RTSP_CAMERA_MODELS.has(model)),
46
46
  diagnostics: true,
47
+ partMeshes: true,
47
48
  filaments: "ams",
48
49
  pause: true,
49
50
  resume: true,
@@ -11,6 +11,7 @@ export type Make3mfResult = {
11
11
  stl_path: string;
12
12
  filament: number;
13
13
  triangles: number;
14
+ color?: string;
14
15
  }[];
15
16
  };
16
17
  export declare function makeCounterpart3mf(args: Record<string, unknown>): Promise<Make3mfResult>;
@@ -26,7 +26,7 @@ const MAX_PARTS = 64;
26
26
  const MAX_FILAMENT = 64;
27
27
  const MAX_STL_BYTES = 256 * 1024 * 1024;
28
28
  const MAX_TOTAL_TRIANGLES = 5000000;
29
- const PART_KEYS = new Set(["stl_path", "name", "filament"]);
29
+ const PART_KEYS = new Set(["stl_path", "name", "filament", "color"]);
30
30
  export class Make3mfError extends Error {
31
31
  }
32
32
  const isFilament = (value) => typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= MAX_FILAMENT;
@@ -237,8 +237,34 @@ async function publish(outPath, bytes) {
237
237
  await fs.rm(staged, { force: true }).catch(() => { });
238
238
  }
239
239
  }
240
+ /**
241
+ * The project's filament colours, filament 1 first, when the parts give one for every filament they use (#691): Bambu
242
+ * Studio and OrcaSlicer keep a project's colours in project_settings.config filament_colour, slice_stl keeps them per
243
+ * slot, and counterpart_part_meshes reads them back. Some colours but not all, or two for one filament, is refused.
244
+ */
245
+ function filamentColours(parts) {
246
+ if (!parts.some(part => part.color))
247
+ return undefined;
248
+ const colours = [];
249
+ for (const part of parts) {
250
+ if (!part.color)
251
+ fail(`Give every part a color, or none: "${part.name}" has none.`);
252
+ const known = colours[part.filament - 1];
253
+ if (known && known !== part.color)
254
+ fail(`Filament ${part.filament} has two colours (${known} and ${part.color}); parts on one filament share its colour.`);
255
+ colours[part.filament - 1] = part.color;
256
+ }
257
+ const missing = Array.from(colours, (colour, index) => colour ? undefined : index + 1).filter(Boolean);
258
+ if (missing.length)
259
+ fail(`No part uses filament ${missing.join(", ")}, so it has no colour; number the filaments from 1 without gaps.`);
260
+ return colours;
261
+ }
240
262
  async function writeAssemblies(objects, outPath, application) {
241
263
  const zip = new JSZip();
264
+ const colours = filamentColours(objects.flatMap(object => object.parts));
265
+ // Only the colours: no process settings, so slice_stl still slices it with its own profiles.
266
+ if (colours)
267
+ zip.file("Metadata/project_settings.config", JSON.stringify({ filament_colour: colours }, null, 2));
242
268
  zip.file("[Content_Types].xml", CONTENT_TYPES);
243
269
  zip.file("_rels/.rels", RELATIONSHIPS);
244
270
  zip.file("3D/3dmodel.model", modelXml(objects, plateTransforms(objects), application));
@@ -259,7 +285,10 @@ export async function makeCounterpart3mf(args) {
259
285
  fail(`${label} must be an object with stl_path and name.`);
260
286
  const entry = value;
261
287
  if (Object.keys(entry).some(key => !PART_KEYS.has(key)))
262
- fail(`${label} accepts only stl_path, name and filament.`);
288
+ fail(`${label} accepts only stl_path, name, filament and color.`);
289
+ if (entry.color !== undefined && (typeof entry.color !== "string" || !/^#[0-9A-Fa-f]{6}$/.test(entry.color)))
290
+ fail(`${label}.color must be a colour as #RRGGBB.`);
291
+ const color = typeof entry.color === "string" ? entry.color.toUpperCase() : undefined;
263
292
  const name = nonEmptyText(entry.name, `${label}.name`).trim();
264
293
  const stlPath = path.resolve(nonEmptyText(entry.stl_path, `${label}.stl_path`));
265
294
  if (path.extname(stlPath).toLowerCase() !== ".stl")
@@ -271,7 +300,7 @@ export async function makeCounterpart3mf(args) {
271
300
  triangles += mesh.triangles;
272
301
  if (triangles > MAX_TOTAL_TRIANGLES)
273
302
  fail(`The parts have more than ${MAX_TOTAL_TRIANGLES} triangles in total; decimate them first.`);
274
- parts.push({ name, stlPath, filament, mesh });
303
+ parts.push({ name, stlPath, filament, mesh, ...(color ? { color } : {}) });
275
304
  }
276
305
  await writeAssemblies([{ name: path.basename(outPath, path.extname(outPath)), plate: 1, parts }], outPath, "bambu-printer-mcp counterpart_make_3mf");
277
306
  return {
@@ -279,7 +308,7 @@ export async function makeCounterpart3mf(args) {
279
308
  path: outPath,
280
309
  objects: 1,
281
310
  filaments: Math.max(...parts.map(part => part.filament)),
282
- parts: parts.map(part => ({ name: part.name, stl_path: part.stlPath, filament: part.filament, triangles: part.mesh.triangles })),
311
+ parts: parts.map(part => ({ name: part.name, stl_path: part.stlPath, filament: part.filament, triangles: part.mesh.triangles, ...(part.color ? { color: part.color } : {}) })),
283
312
  };
284
313
  }
285
314
  // --- cad_run 3MF projects (project_3mf in a design script) --------------------------------------------------------
@@ -387,7 +416,10 @@ export async function writeCadProject3mf(manifest, partsDir, inputs, outPath) {
387
416
  for (const [at, part] of entry.parts.entries()) {
388
417
  if (!isFilament(part?.filament))
389
418
  fail(`objects[${index}].parts[${at}].filament must be from 1 to ${MAX_FILAMENT}.`);
390
- parts.push({ name: text(part.name, "part name"), stlPath: "", filament: part.filament, mesh: await partMesh(part.stl, `objects[${index}].parts[${at}]`) });
419
+ const color = typeof part.color === "string" && /^#[0-9A-F]{6}$/.test(part.color) ? part.color : undefined;
420
+ if (part.color !== undefined && !color)
421
+ fail(`objects[${index}].parts[${at}].color must be #RRGGBB.`);
422
+ parts.push({ name: text(part.name, "part name"), stlPath: "", filament: part.filament, mesh: await partMesh(part.stl, `objects[${index}].parts[${at}]`), ...(color ? { color } : {}) });
391
423
  }
392
424
  objects.push({ name: text(entry.name, "object name"), plate, parts });
393
425
  }
@@ -33,6 +33,8 @@ export interface ModelPlate {
33
33
  build_items: number[];
34
34
  /** Each model part of this plate's objects once, with the filament it prints in (counterpart/1; see PlatePart). */
35
35
  parts: PlatePart[];
36
+ /** How many more parts the plate has beyond the 1000 listed, when it has more. */
37
+ parts_truncated?: number;
36
38
  /** The plate's own preview from the file (Metadata/plate_N.png), when asked for and present. */
37
39
  thumbnail_png_base64?: string;
38
40
  }
@@ -127,6 +127,9 @@ export async function listModelPlates(filePath, options = {}) {
127
127
  if (geometry) {
128
128
  plate.build_items = filaments.buildItems.get(plate.index + 1) ?? [];
129
129
  plate.parts = filaments.parts.get(plate.index + 1) ?? [];
130
+ const truncated = filaments.partsTruncated.get(plate.index + 1);
131
+ if (truncated)
132
+ plate.parts_truncated = truncated;
130
133
  }
131
134
  }
132
135
  result.project_filaments = filaments.project;
@@ -0,0 +1,114 @@
1
+ import { COUNTERPART_CONTRACT } from "./schemas.js";
2
+ /** All the STLs one call writes, together: about 200 MB of binary STL. Parts beyond it are listed in skipped. */
3
+ export declare const MAX_TOTAL_TRIANGLES = 4000000;
4
+ export declare class PartMeshesError extends Error {
5
+ }
6
+ export interface PartMesh {
7
+ id: string;
8
+ name: string;
9
+ plate?: number;
10
+ color?: string;
11
+ filament?: number;
12
+ painted?: true;
13
+ stl_path: string;
14
+ triangles: number;
15
+ size_mm: [number, number, number];
16
+ }
17
+ export interface PartMeshes {
18
+ contract: typeof COUNTERPART_CONTRACT;
19
+ units: "mm";
20
+ folder: string;
21
+ parts: PartMesh[];
22
+ skipped?: {
23
+ id: string;
24
+ name: string;
25
+ reason: string;
26
+ }[];
27
+ }
28
+ export declare function partMeshes(args: Record<string, unknown>): Promise<PartMeshes>;
29
+ export declare const PART_MESHES_OUTPUT_SCHEMA: {
30
+ type: "object";
31
+ properties: {
32
+ contract: {
33
+ type: string;
34
+ const: string;
35
+ };
36
+ units: {
37
+ type: string;
38
+ const: string;
39
+ };
40
+ folder: {
41
+ type: string;
42
+ description: string;
43
+ };
44
+ parts: {
45
+ type: string;
46
+ items: {
47
+ type: string;
48
+ properties: {
49
+ id: {
50
+ type: string;
51
+ description: string;
52
+ };
53
+ name: {
54
+ type: string;
55
+ };
56
+ plate: {
57
+ type: string;
58
+ minimum: number;
59
+ description: string;
60
+ };
61
+ color: {
62
+ type: string;
63
+ pattern: string;
64
+ description: string;
65
+ };
66
+ filament: {
67
+ type: string;
68
+ minimum: number;
69
+ };
70
+ painted: {
71
+ type: string;
72
+ const: boolean;
73
+ description: string;
74
+ };
75
+ stl_path: {
76
+ type: string;
77
+ };
78
+ triangles: {
79
+ type: string;
80
+ minimum: number;
81
+ };
82
+ size_mm: {
83
+ type: string;
84
+ items: {
85
+ type: string;
86
+ };
87
+ minItems: number;
88
+ maxItems: number;
89
+ };
90
+ };
91
+ required: string[];
92
+ };
93
+ };
94
+ skipped: {
95
+ type: string;
96
+ items: {
97
+ type: string;
98
+ properties: {
99
+ id: {
100
+ type: string;
101
+ };
102
+ name: {
103
+ type: string;
104
+ };
105
+ reason: {
106
+ type: string;
107
+ };
108
+ };
109
+ required: string[];
110
+ };
111
+ };
112
+ };
113
+ required: string[];
114
+ };