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
@@ -27,20 +27,20 @@ const MAX_PARTS = 64;
27
27
  const MAX_FILAMENT = 64;
28
28
  const MAX_STL_BYTES = 256 * 1024 * 1024;
29
29
  const MAX_TOTAL_TRIANGLES = 5_000_000;
30
- const PART_KEYS = new Set(["stl_path", "name", "filament"]);
30
+ const PART_KEYS = new Set(["stl_path", "name", "filament", "color"]);
31
31
 
32
32
  export class Make3mfError extends Error {}
33
33
 
34
34
  const isFilament = (value: unknown): value is number => typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= MAX_FILAMENT;
35
35
 
36
36
  type Mesh = { vertices: Float32Array; indices: Uint32Array; triangles: number; min: number[]; max: number[] };
37
- type Part = { name: string; stlPath: string; filament: number; mesh: Mesh };
37
+ type Part = { name: string; stlPath: string; filament: number; mesh: Mesh; color?: string };
38
38
  export type Make3mfResult = {
39
39
  contract: typeof COUNTERPART_CONTRACT;
40
40
  path: string;
41
41
  objects: number;
42
42
  filaments: number;
43
- parts: { name: string; stl_path: string; filament: number; triangles: number }[];
43
+ parts: { name: string; stl_path: string; filament: number; triangles: number; color?: string }[];
44
44
  };
45
45
 
46
46
  function fail(message: string): never { throw new Make3mfError(message); }
@@ -251,8 +251,30 @@ async function publish(outPath: string, bytes: Buffer): Promise<void> {
251
251
  }
252
252
  }
253
253
 
254
+ /**
255
+ * The project's filament colours, filament 1 first, when the parts give one for every filament they use (#691): Bambu
256
+ * Studio and OrcaSlicer keep a project's colours in project_settings.config filament_colour, slice_stl keeps them per
257
+ * slot, and counterpart_part_meshes reads them back. Some colours but not all, or two for one filament, is refused.
258
+ */
259
+ function filamentColours(parts: Part[]): string[] | undefined {
260
+ if (!parts.some(part => part.color)) return undefined;
261
+ const colours: string[] = [];
262
+ for (const part of parts) {
263
+ if (!part.color) fail(`Give every part a color, or none: "${part.name}" has none.`);
264
+ const known = colours[part.filament - 1];
265
+ if (known && known !== part.color) fail(`Filament ${part.filament} has two colours (${known} and ${part.color}); parts on one filament share its colour.`);
266
+ colours[part.filament - 1] = part.color;
267
+ }
268
+ const missing = Array.from(colours, (colour, index) => colour ? undefined : index + 1).filter(Boolean);
269
+ if (missing.length) fail(`No part uses filament ${missing.join(", ")}, so it has no colour; number the filaments from 1 without gaps.`);
270
+ return colours;
271
+ }
272
+
254
273
  async function writeAssemblies(objects: Assembly[], outPath: string, application: string): Promise<void> {
255
274
  const zip = new JSZip();
275
+ const colours = filamentColours(objects.flatMap(object => object.parts));
276
+ // Only the colours: no process settings, so slice_stl still slices it with its own profiles.
277
+ if (colours) zip.file("Metadata/project_settings.config", JSON.stringify({ filament_colour: colours }, null, 2));
256
278
  zip.file("[Content_Types].xml", CONTENT_TYPES);
257
279
  zip.file("_rels/.rels", RELATIONSHIPS);
258
280
  zip.file("3D/3dmodel.model", modelXml(objects, plateTransforms(objects), application));
@@ -271,7 +293,9 @@ export async function makeCounterpart3mf(args: Record<string, unknown>): Promise
271
293
  const label = `parts[${index}]`;
272
294
  if (!value || typeof value !== "object" || Array.isArray(value)) fail(`${label} must be an object with stl_path and name.`);
273
295
  const entry = value as Record<string, unknown>;
274
- if (Object.keys(entry).some(key => !PART_KEYS.has(key))) fail(`${label} accepts only stl_path, name and filament.`);
296
+ if (Object.keys(entry).some(key => !PART_KEYS.has(key))) fail(`${label} accepts only stl_path, name, filament and color.`);
297
+ if (entry.color !== undefined && (typeof entry.color !== "string" || !/^#[0-9A-Fa-f]{6}$/.test(entry.color))) fail(`${label}.color must be a colour as #RRGGBB.`);
298
+ const color = typeof entry.color === "string" ? entry.color.toUpperCase() : undefined;
275
299
  const name = nonEmptyText(entry.name, `${label}.name`).trim();
276
300
  const stlPath = path.resolve(nonEmptyText(entry.stl_path, `${label}.stl_path`));
277
301
  if (path.extname(stlPath).toLowerCase() !== ".stl") fail(`${label}.stl_path must name an STL file.`);
@@ -280,7 +304,7 @@ export async function makeCounterpart3mf(args: Record<string, unknown>): Promise
280
304
  const mesh = await readMesh(await fs.realpath(stlPath).catch(() => fail(`${label}.stl_path does not exist.`)), `${label}.stl_path`);
281
305
  triangles += mesh.triangles;
282
306
  if (triangles > MAX_TOTAL_TRIANGLES) fail(`The parts have more than ${MAX_TOTAL_TRIANGLES} triangles in total; decimate them first.`);
283
- parts.push({ name, stlPath, filament, mesh });
307
+ parts.push({ name, stlPath, filament, mesh, ...(color ? { color } : {}) });
284
308
  }
285
309
  await writeAssemblies([{ name: path.basename(outPath, path.extname(outPath)), plate: 1, parts }], outPath, "bambu-printer-mcp counterpart_make_3mf");
286
310
  return {
@@ -288,7 +312,7 @@ export async function makeCounterpart3mf(args: Record<string, unknown>): Promise
288
312
  path: outPath,
289
313
  objects: 1,
290
314
  filaments: Math.max(...parts.map(part => part.filament)),
291
- parts: parts.map(part => ({ name: part.name, stl_path: part.stlPath, filament: part.filament, triangles: part.mesh.triangles })),
315
+ parts: parts.map(part => ({ name: part.name, stl_path: part.stlPath, filament: part.filament, triangles: part.mesh.triangles, ...(part.color ? { color: part.color } : {}) })),
292
316
  };
293
317
  }
294
318
 
@@ -392,7 +416,9 @@ export async function writeCadProject3mf(manifest: unknown, partsDir: string, in
392
416
  const parts: Part[] = [];
393
417
  for (const [at, part] of (entry.parts as Record<string, unknown>[]).entries()) {
394
418
  if (!isFilament(part?.filament)) fail(`objects[${index}].parts[${at}].filament must be from 1 to ${MAX_FILAMENT}.`);
395
- 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) fail(`objects[${index}].parts[${at}].color must be #RRGGBB.`);
421
+ parts.push({ name: text(part.name, "part name"), stlPath: "", filament: part.filament, mesh: await partMesh(part.stl, `objects[${index}].parts[${at}]`), ...(color ? { color } : {}) });
396
422
  }
397
423
  objects.push({ name: text(entry.name, "object name"), plate, parts });
398
424
  }
@@ -41,6 +41,8 @@ export interface ModelPlate {
41
41
  build_items: number[];
42
42
  /** Each model part of this plate's objects once, with the filament it prints in (counterpart/1; see PlatePart). */
43
43
  parts: PlatePart[];
44
+ /** How many more parts the plate has beyond the 1000 listed, when it has more. */
45
+ parts_truncated?: number;
44
46
  /** The plate's own preview from the file (Metadata/plate_N.png), when asked for and present. */
45
47
  thumbnail_png_base64?: string;
46
48
  }
@@ -164,6 +166,8 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
164
166
  if (geometry) {
165
167
  plate.build_items = filaments.buildItems.get(plate.index + 1) ?? [];
166
168
  plate.parts = filaments.parts.get(plate.index + 1) ?? [];
169
+ const truncated = filaments.partsTruncated.get(plate.index + 1);
170
+ if (truncated) plate.parts_truncated = truncated;
167
171
  }
168
172
  }
169
173
  result.project_filaments = filaments.project;
@@ -0,0 +1,304 @@
1
+ /**
2
+ * counterpart_part_meshes (counterpart/1, scan-to-make #691 and #845): one STL per printable part of any 3MF, in its
3
+ * filament's colour, so a client can draw a multi-colour design part by part, or show a designer's published 3MF in
4
+ * AR, without reading 3MF itself.
5
+ *
6
+ * Plates, parts and filaments come from list_3mf_plates (model-plates.ts), so both tools agree on what a part is and
7
+ * which filament it prints with. Each part is written in the 3MF's build frame, in millimetres: its component
8
+ * transforms and its build item's transform applied, and the root model's unit converted, so the parts line up when drawn
9
+ * together. Only bounded model text is read; nothing in the file is run. Shared by bambu-printer-mcp and
10
+ * mcp-3D-printer-server.
11
+ */
12
+ import fs from "node:fs/promises";
13
+ import path from "node:path";
14
+ import type JSZip from "jszip";
15
+ import { readSafe3mfArchive } from "../safety/archive.js";
16
+ import { listModelPlates } from "./model-plates.js";
17
+ import { COUNTERPART_CONTRACT } from "./schemas.js";
18
+
19
+ const MAX_MODEL_BYTES = 64 * 1024 * 1024;
20
+ const MAX_TOTAL_BYTES = 256 * 1024 * 1024;
21
+ const MAX_DEPTH = 8;
22
+ /** All the STLs one call writes, together: about 200 MB of binary STL. Parts beyond it are listed in skipped. */
23
+ export const MAX_TOTAL_TRIANGLES = 4_000_000;
24
+ const ROOT = "3D/3dmodel.model";
25
+ const UNITS: Record<string, number> = { micron: 0.001, millimeter: 1, centimeter: 10, inch: 25.4, foot: 304.8, meter: 1000 };
26
+
27
+ export class PartMeshesError extends Error {}
28
+ function fail(message: string): never { throw new PartMeshesError(message); }
29
+
30
+ export interface PartMesh {
31
+ id: string;
32
+ name: string;
33
+ plate?: number;
34
+ color?: string;
35
+ filament?: number;
36
+ painted?: true;
37
+ stl_path: string;
38
+ triangles: number;
39
+ size_mm: [number, number, number];
40
+ }
41
+ export interface PartMeshes {
42
+ contract: typeof COUNTERPART_CONTRACT;
43
+ units: "mm";
44
+ folder: string;
45
+ parts: PartMesh[];
46
+ skipped?: { id: string; name: string; reason: string }[];
47
+ }
48
+
49
+ /** A 3MF transform ("m00 m01 m02 m10 m11 m12 m20 m21 m22 m30 m31 m32", row vectors) as 12 numbers; identity when absent. */
50
+ function matrix(value: string | undefined): number[] {
51
+ const identity = [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0];
52
+ if (!value) return identity;
53
+ const numbers = value.trim().split(/\s+/).map(Number);
54
+ return numbers.length === 12 && numbers.every(Number.isFinite) ? numbers : fail(`A transform in the 3MF is malformed: "${value.slice(0, 80)}".`);
55
+ }
56
+ /** First a, then b (p' = (p a) b). */
57
+ function compose(a: number[], b: number[]): number[] {
58
+ const out = new Array<number>(12);
59
+ for (let r = 0; r < 4; r++) for (let c = 0; c < 3; c++)
60
+ out[r * 3 + c] = a[r * 3] * b[c] + a[r * 3 + 1] * b[3 + c] + a[r * 3 + 2] * b[6 + c] + (r === 3 ? b[9 + c] : 0);
61
+ return out;
62
+ }
63
+
64
+ type ModelFile = { scale: number; objects: Map<string, string> };
65
+
66
+ /** The model files, read once each within the byte budgets. */
67
+ function modelReader(zip: JSZip) {
68
+ const files = new Map<string, ModelFile | string>();
69
+ let total = 0;
70
+ return async (name: string): Promise<ModelFile | string> => {
71
+ const known = files.get(name);
72
+ if (known !== undefined) return known;
73
+ const file = zip.file(name);
74
+ let result: ModelFile | string;
75
+ if (!file) result = `the model part ${name} is missing from the file`;
76
+ else {
77
+ const bytes = await file.async("nodebuffer");
78
+ total += bytes.length;
79
+ if (bytes.length > MAX_MODEL_BYTES) result = `its model part ${name} is larger than ${MAX_MODEL_BYTES / 1024 / 1024} MiB`;
80
+ else if (total > MAX_TOTAL_BYTES) result = `the 3MF's model parts are larger than ${MAX_TOTAL_BYTES / 1024 / 1024} MiB in all`;
81
+ else {
82
+ const text = bytes.toString("utf8");
83
+ const unit = /<(?:\w+:)?model\b[^>]*\bunit="(\w+)"/.exec(text)?.[1] ?? "millimeter";
84
+ const objects = new Map<string, string>();
85
+ // An <object .../> closes itself: its (empty) body never runs on into the next object's.
86
+ for (const object of text.matchAll(/<(?:\w+:)?object\b([^>]*?)(?:\/>|>([\s\S]*?)<\/(?:\w+:)?object>)/g)) {
87
+ const id = /\bid="(\d+)"/.exec(object[1])?.[1];
88
+ if (id) objects.set(id, object[2] ?? "");
89
+ }
90
+ // Only the root model's unit counts (3MF core spec); a model part's own is read and ignored.
91
+ result = { scale: UNITS[unit] ?? (name === ROOT ? fail(`The 3MF's unit "${unit}" is not one the 3MF standard defines.`) : 1), objects };
92
+ }
93
+ }
94
+ files.set(name, result);
95
+ return result;
96
+ };
97
+ }
98
+
99
+ type ParsedMesh = { vertices: Float64Array; corners: Uint32Array } | string;
100
+ /** Each mesh object parsed once, however many copies and components place it. */
101
+ const parsed = new WeakMap<ModelFile, Map<string, ParsedMesh>>();
102
+ function parseMesh(model: ModelFile, file: string, id: string, mesh: string): ParsedMesh {
103
+ let cache = parsed.get(model);
104
+ if (!cache) parsed.set(model, cache = new Map());
105
+ const known = cache.get(id);
106
+ if (known) return known;
107
+ let result: ParsedMesh;
108
+ const vertices: number[] = [];
109
+ for (const v of mesh.matchAll(/<(?:\w+:)?vertex\b([^>]*)\/?>/g)) {
110
+ const x = Number(/\bx="([^"]+)"/.exec(v[1])?.[1]), y = Number(/\by="([^"]+)"/.exec(v[1])?.[1]), z = Number(/\bz="([^"]+)"/.exec(v[1])?.[1]);
111
+ vertices.push(x, y, z);
112
+ }
113
+ const count = vertices.length / 3;
114
+ const corners: number[] = [];
115
+ if (!vertices.every(Number.isFinite)) result = `a vertex of object ${id} in ${file} is not a number`;
116
+ else {
117
+ result = { vertices: Float64Array.from(vertices), corners: new Uint32Array() };
118
+ for (const tri of mesh.matchAll(/<(?:\w+:)?triangle\b([^>]*)\/?>/g)) {
119
+ const c = ["v1", "v2", "v3"].map(key => Number(new RegExp(`\\b${key}="(\\d+)"`).exec(tri[1])?.[1]));
120
+ if (!c.every(k => Number.isInteger(k) && k >= 0 && k < count)) { result = `a triangle of object ${id} in ${file} names a vertex it doesn't have`; break; }
121
+ corners.push(c[0], c[1], c[2]);
122
+ }
123
+ if (typeof result !== "string") result.corners = Uint32Array.from(corners);
124
+ }
125
+ cache.set(id, result);
126
+ return result;
127
+ }
128
+
129
+ /** An object's triangles in the build frame: its own mesh, or its components' meshes, each through its transform. */
130
+ async function collect(read: ReturnType<typeof modelReader>, file: string, id: string, transform: number[], out: number[], budget: number, depth = 0): Promise<string | undefined> {
131
+ if (depth > MAX_DEPTH) return "its components nest too deeply";
132
+ const model = await read(file);
133
+ if (typeof model === "string") return model;
134
+ const body = model.objects.get(id);
135
+ if (body === undefined) return `object ${id} is missing from ${file}`;
136
+ const mesh = /<(?:\w+:)?mesh\b[^>]*>([\s\S]*?)<\/(?:\w+:)?mesh>/.exec(body)?.[1];
137
+ if (mesh) {
138
+ const parsedMesh = parseMesh(model, file, id, mesh);
139
+ if (typeof parsedMesh === "string") return parsedMesh;
140
+ const t = transform, v = parsedMesh.vertices, corners = parsedMesh.corners;
141
+ // Checked before each mesh is expanded: nested components placing one mesh many times stop here, not in memory.
142
+ if (out.length / 9 + corners.length / 3 > budget) return `it has more triangles than this call's remaining ${Math.max(0, Math.floor(budget))} of ${MAX_TOTAL_TRIANGLES}`;
143
+ // A mirroring placement (negative determinant) turns the surface inside out: each triangle's winding is reversed.
144
+ const mirrored = t[0] * (t[4] * t[8] - t[5] * t[7]) - t[1] * (t[3] * t[8] - t[5] * t[6]) + t[2] * (t[3] * t[7] - t[4] * t[6]) < 0;
145
+ for (let i = 0; i < corners.length; i += 3) for (const k of mirrored ? [0, 2, 1] : [0, 1, 2]) {
146
+ const c = corners[i + k];
147
+ const x = v[c * 3], y = v[c * 3 + 1], z = v[c * 3 + 2];
148
+ out.push(x * t[0] + y * t[3] + z * t[6] + t[9], x * t[1] + y * t[4] + z * t[7] + t[10], x * t[2] + y * t[5] + z * t[8] + t[11]);
149
+ }
150
+ return undefined;
151
+ }
152
+ for (const component of body.matchAll(/<(?:\w+:)?component\b([^>]*)\/?>/g)) {
153
+ const child = /\bobjectid="(\d+)"/.exec(component[1])?.[1];
154
+ if (!child) continue;
155
+ const childFile = /\b(?:\w+:)?path="\/?([^"]+)"/.exec(component[1])?.[1] ?? file;
156
+ const problem = await collect(read, childFile, child, compose(matrix(/\btransform="([^"]+)"/.exec(component[1])?.[1]), transform), out, budget, depth + 1);
157
+ if (problem) return problem;
158
+ }
159
+ return undefined;
160
+ }
161
+
162
+ /** A binary STL of a flat triangle list, with each facet's normal. */
163
+ function stl(values: number[]): Buffer {
164
+ const count = values.length / 9;
165
+ const buffer = Buffer.alloc(84 + count * 50);
166
+ buffer.write("counterpart_part_meshes", 0, "ascii");
167
+ buffer.writeUInt32LE(count, 80);
168
+ for (let i = 0; i < count; i++) {
169
+ const p = values.slice(i * 9, i * 9 + 9); // nine numbers: cheap beside the file write
170
+ const u = [p[3] - p[0], p[4] - p[1], p[5] - p[2]], v = [p[6] - p[0], p[7] - p[1], p[8] - p[2]];
171
+ const n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
172
+ const length = Math.hypot(n[0], n[1], n[2]) || 1;
173
+ const at = 84 + i * 50;
174
+ n.forEach((value, k) => buffer.writeFloatLE(value / length, at + k * 4));
175
+ p.forEach((value, k) => buffer.writeFloatLE(value, at + 12 + k * 4));
176
+ }
177
+ return buffer;
178
+ }
179
+
180
+ const slug = (name: string) => name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "part";
181
+
182
+ /** A new folder inside out_dir, named after the 3MF; nothing that exists is reused or overwritten. */
183
+ async function newFolder(outDir: string, base: string): Promise<string> {
184
+ const parent = await fs.realpath(outDir).catch(() => fail("out_dir must be an existing folder."));
185
+ if (!(await fs.stat(parent)).isDirectory()) fail("out_dir must be an existing folder.");
186
+ for (let n = 1; n <= 1000; n++) {
187
+ const folder = path.join(parent, `${slug(base)}-parts-${n}`);
188
+ try { await fs.mkdir(folder); return folder; } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
189
+ }
190
+ return fail("out_dir already holds 1000 part folders for this 3MF; choose another out_dir.");
191
+ }
192
+
193
+ export async function partMeshes(args: Record<string, unknown>): Promise<PartMeshes> {
194
+ if (Object.keys(args).some(key => key !== "three_mf_path" && key !== "out_dir")) fail("counterpart_part_meshes accepts only three_mf_path and out_dir.");
195
+ if (typeof args.three_mf_path !== "string" || !args.three_mf_path.trim()) fail("three_mf_path must name a 3MF file.");
196
+ if (typeof args.out_dir !== "string" || !args.out_dir.trim()) fail("out_dir must name an existing folder.");
197
+ const source = path.resolve(args.three_mf_path);
198
+ const plates = await listModelPlates(source);
199
+ const { zip } = await readSafe3mfArchive(source);
200
+ const settings = await zip.file("Metadata/model_settings.config")?.async("string") ?? "";
201
+ const hasPlates = /<plate\b/.test(settings);
202
+ const colours = new Map(plates.project_filaments.flatMap(f => f.colour && /^#[0-9A-Fa-f]{6}/.test(f.colour) ? [[f.index, f.colour.slice(0, 7).toUpperCase()]] : []));
203
+ const read = modelReader(zip);
204
+ const root = await read(ROOT);
205
+ if (typeof root === "string") fail(`This 3MF has no model to draw: ${root}.`);
206
+ const rootScale = (root as ModelFile).scale;
207
+ const items = [...(await zip.file(ROOT)!.async("string")).matchAll(/<(?:\w+:)?item\b([^>]*)\/?>/g)].map(item => item[1]);
208
+ if (!plates.plates.some(plate => plate.parts.length)) fail("This 3MF has no printable part to draw.");
209
+
210
+ const folder = await newFolder(args.out_dir, path.basename(source, path.extname(source)));
211
+ const parts: PartMesh[] = [];
212
+ const skipped: NonNullable<PartMeshes["skipped"]> = [];
213
+ let written = 0;
214
+ try {
215
+ for (const plate of plates.plates) if (plate.parts_truncated)
216
+ skipped.push({ id: `plate ${plate.index + 1}`, name: plate.name, reason: `${plate.parts_truncated} more parts beyond the first 1000 on this plate were not read` });
217
+ for (const plate of plates.plates) for (const itemIndex of plate.build_items) {
218
+ const item = items[itemIndex];
219
+ if (!item || /\bprintable="(?:0|false)"/.test(item)) continue;
220
+ const objectId = /\bobjectid="(\d+)"/.exec(item)?.[1];
221
+ for (const part of plate.parts.filter(p => String(p.build_object_id) === objectId)) {
222
+ const file = part.path?.replace(/^\//, "") ?? ROOT;
223
+ // Each place the object puts this mesh: itself, or every component that names it (one mesh placed twice is two
224
+ // parts on the plate, like a plain 3MF's pair of wheels).
225
+ // Object ids are local to each model file: only a part in the root model with the build object's own id is that
226
+ // object's own mesh (Codex review, #169).
227
+ const placements: (string | undefined)[] = String(part.object_id) === objectId && file === ROOT ? [undefined]
228
+ : [...((root as ModelFile).objects.get(objectId ?? "") ?? "").matchAll(/<(?:\w+:)?component\b([^>]*)\/?>/g)]
229
+ .map(match => match[1]).filter(attrs => /\bobjectid="(\d+)"/.exec(attrs)?.[1] === String(part.object_id)
230
+ && (/\b(?:\w+:)?path="\/?([^"]+)"/.exec(attrs)?.[1] ?? ROOT) === file);
231
+ if (!placements.length) { skipped.push({ id: `${itemIndex + 1}/${part.object_id}`, name: part.name, reason: `its component is missing from object ${objectId}` }); continue; }
232
+ for (const [copy, component] of placements.entries()) {
233
+ const id = copy ? `${itemIndex + 1}/${part.object_id}/${copy + 1}` : `${itemIndex + 1}/${part.object_id}`;
234
+ const triangles: number[] = [];
235
+ let problem: string | undefined;
236
+ try {
237
+ const placed = matrix(/\btransform="([^"]+)"/.exec(item)?.[1]);
238
+ const budget = MAX_TOTAL_TRIANGLES - written;
239
+ problem = component === undefined ? await collect(read, ROOT, objectId!, placed, triangles, budget)
240
+ : await collect(read, file, String(part.object_id), compose(matrix(/\btransform="([^"]+)"/.exec(component)?.[1]), placed), triangles, budget);
241
+ } catch (error) {
242
+ // A malformed transform spoils this part only: it is listed with why, and the others are still written.
243
+ if (!(error instanceof PartMeshesError)) throw error;
244
+ problem = error.message;
245
+ }
246
+ if (!problem && !triangles.length) problem = "it has no triangles";
247
+ // The root model's unit covers every model part and transform in the package (3MF core spec, 3.4).
248
+ if (rootScale !== 1) for (let i = 0; i < triangles.length; i++) triangles[i] *= rootScale;
249
+ if (problem) { skipped.push({ id, name: part.name, reason: problem }); continue; }
250
+ written += triangles.length / 9;
251
+ const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
252
+ for (let i = 0; i < triangles.length; i++) { min[i % 3] = Math.min(min[i % 3], triangles[i]); max[i % 3] = Math.max(max[i % 3], triangles[i]); }
253
+ const stlPath = path.join(folder, `${parts.length + 1}-${slug(part.name)}.stl`);
254
+ await fs.writeFile(stlPath, stl(triangles), { flag: "wx" });
255
+ const colour = colours.get(part.filament);
256
+ parts.push({
257
+ id, name: part.name,
258
+ ...(hasPlates ? { plate: plate.index + 1 } : {}),
259
+ ...(colour ? { color: colour } : {}),
260
+ filament: part.filament,
261
+ ...(part.painted ? { painted: true as const } : {}),
262
+ stl_path: stlPath,
263
+ triangles: triangles.length / 9,
264
+ size_mm: [0, 1, 2].map(k => Math.round((max[k] - min[k]) * 1000) / 1000) as [number, number, number],
265
+ });
266
+ }
267
+ }
268
+ }
269
+ } catch (error) {
270
+ // Nothing half-written is left behind.
271
+ await fs.rm(folder, { recursive: true, force: true }).catch(() => {});
272
+ throw error;
273
+ }
274
+ return { contract: COUNTERPART_CONTRACT, units: "mm", folder, parts, ...(skipped.length ? { skipped } : {}) };
275
+ }
276
+
277
+ export const PART_MESHES_OUTPUT_SCHEMA = {
278
+ type: "object" as const,
279
+ properties: {
280
+ contract: { type: "string", const: COUNTERPART_CONTRACT },
281
+ units: { type: "string", const: "mm" },
282
+ folder: { type: "string", description: "The new folder the STLs were written in." },
283
+ parts: {
284
+ type: "array",
285
+ items: {
286
+ type: "object",
287
+ properties: {
288
+ id: { type: "string", description: "<build item, from 1>/<part's object id>, with /<n> for its second and later placements as a component: stable for the same file; a key, not to be parsed." },
289
+ name: { type: "string" },
290
+ plate: { type: "integer", minimum: 1, description: "Plate number from 1 (list_3mf_plates index + 1); absent without plate metadata." },
291
+ color: { type: "string", pattern: "^#[0-9A-F]{6}$", description: "The filament's colour as the 3MF declares it; absent when it declares none." },
292
+ filament: { type: "integer", minimum: 1 },
293
+ painted: { type: "boolean", const: true, description: "Slicer painting recolours some facets; color is the base filament's." },
294
+ stl_path: { type: "string" },
295
+ triangles: { type: "integer", minimum: 1 },
296
+ size_mm: { type: "array", items: { type: "number" }, minItems: 3, maxItems: 3 },
297
+ },
298
+ required: ["id", "name", "stl_path", "triangles", "size_mm"],
299
+ },
300
+ },
301
+ skipped: { type: "array", items: { type: "object", properties: { id: { type: "string" }, name: { type: "string" }, reason: { type: "string" } }, required: ["id", "name", "reason"] } },
302
+ },
303
+ required: ["contract", "units", "folder", "parts"],
304
+ };
@@ -50,6 +50,8 @@ export interface PlatePart {
50
50
  name: string;
51
51
  filament: number;
52
52
  painted?: true;
53
+ /** How many times the object places this mesh as a component, when more than once (a plain 3MF's wheels). */
54
+ components?: number;
53
55
  }
54
56
 
55
57
  const MAX_TEXT_BYTES = 8 * 1024 * 1024;
@@ -202,7 +204,7 @@ export interface PlateLayout {
202
204
  * 3D/3dmodel.model text.
203
205
  */
204
206
  export async function plateFilaments(zip: JSZip, settings: string, model: string, plates: PlateLayout[], limits: PaintLimits = PAINT_LIMITS)
205
- : Promise<{ plates: Map<number, PlateFilament[]>; incomplete: Set<number>; project: PlateFilament[]; buildItems: Map<number, number[]>; parts: Map<number, PlatePart[]> }> {
207
+ : Promise<{ plates: Map<number, PlateFilament[]>; incomplete: Set<number>; project: PlateFilament[]; buildItems: Map<number, number[]>; parts: Map<number, PlatePart[]>; partsTruncated: Map<number, number> }> {
206
208
  const text = async (name: string) => {
207
209
  const file = zip.file(name);
208
210
  if (!file) return "";
@@ -224,17 +226,27 @@ export async function plateFilaments(zip: JSZip, settings: string, model: string
224
226
  const components = new Map<string, Map<string, string>>();
225
227
  // Root objects that are meshes themselves (a plain 3MF): their own id is the part.
226
228
  const rootMeshes = new Set<string>();
227
- for (const object of model.matchAll(/<(?:\w+:)?object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/(?:\w+:)?object>/g)) {
228
- if (/<(?:\w+:)?mesh[\s>]/.test(object[2])) rootMeshes.add(object[1]);
229
+ // How often each root object places each component mesh, and the root model's own object names (a plain 3MF's).
230
+ const componentCounts = new Map<string, Map<string, number>>();
231
+ const modelNames = new Map<string, string>();
232
+ // An <object .../> closes itself: its (empty) body never runs on into the next object's.
233
+ for (const object of model.matchAll(/<(?:\w+:)?object\b([^>]*?)(?:\/>|>([\s\S]*?)<\/(?:\w+:)?object>)/g)) {
234
+ const objectId = /\bid="(\d+)"/.exec(object[1])?.[1];
235
+ if (!objectId) continue;
236
+ const body = object[2] ?? "";
237
+ const named = /\bname="([^"]*)"/.exec(object[1])?.[1];
238
+ if (named) modelNames.set(objectId, words(named));
239
+ if (/<(?:\w+:)?mesh[\s>]/.test(body)) rootMeshes.add(objectId);
229
240
  const parts = new Map<string, string>();
230
- for (const component of object[2].matchAll(/<(?:\w+:)?component\b([^>]*)\/?>/g)) {
241
+ const counts = new Map<string, number>();
242
+ for (const component of body.matchAll(/<(?:\w+:)?component\b([^>]*)\/?>/g)) {
231
243
  const path = /\b(?:\w+:)?path="\/?([^"]+)"/.exec(component[1])?.[1];
232
244
  const id = /\bobjectid="(\d+)"/.exec(component[1])?.[1];
233
245
  // Studio keys a component by (path, objectid); one without p:path names a mesh object in the root model
234
246
  // itself, keyed by the root's empty path (bbs_3mf.cpp:4131-4148, 3891).
235
- if (id) parts.set(id, path || "3D/3dmodel.model");
247
+ if (id) { parts.set(id, path || "3D/3dmodel.model"); counts.set(id, (counts.get(id) ?? 0) + 1); }
236
248
  }
237
- if (parts.size) components.set(object[1], parts);
249
+ if (parts.size) { components.set(objectId, parts); componentCounts.set(objectId, counts); }
238
250
  }
239
251
  // Model object order (1-based in layer_config_ranges.xml): the build items' order, as Studio creates the objects.
240
252
  const buildItems = [...model.matchAll(/<(?:\w+:)?item\b([^>]*)\/?>/g)].map(item => item[1]);
@@ -290,6 +302,7 @@ export async function plateFilaments(zip: JSZip, settings: string, model: string
290
302
  const result = new Map<number, PlateFilament[]>();
291
303
  const plateItems = new Map<number, number[]>();
292
304
  const plateParts = new Map<number, PlatePart[]>();
305
+ const partsTruncated = new Map<number, number>();
293
306
  const itemObject = buildItems.map(item => /\bobjectid="(\d+)"/.exec(item)?.[1]);
294
307
  // The plate's copies as root build items (0-based, in build order): a copy is its object's instance_id-th item.
295
308
  const plateItemsOf = (plate: PlateLayout) => {
@@ -314,8 +327,10 @@ export async function plateFilaments(zip: JSZip, settings: string, model: string
314
327
  const entry = (id: string, name: string, filament: number) => {
315
328
  const path = meshes?.get(id) ?? (id === objectId && rootMeshes.has(objectId) ? ROOT_MODEL : undefined);
316
329
  const paint = path ? painting.get(`${path}#${id}`) : undefined;
317
- drawn.push({ object_id: Number(id), build_object_id: Number(objectId), ...(path && path !== "3D/3dmodel.model" ? { path: `/${path}` } : {}), name,
318
- filament: valid(filament) ? filament : 1, ...(paint?.states.size ? { painted: true as const } : {}) });
330
+ const placed = componentCounts.get(objectId)?.get(id) ?? 1;
331
+ drawn.push({ object_id: Number(id), build_object_id: Number(objectId), ...(path && path !== "3D/3dmodel.model" ? { path: `/${path}` } : {}),
332
+ name: name || modelNames.get(id) || modelNames.get(objectId) || "",
333
+ filament: valid(filament) ? filament : 1, ...(paint?.states.size ? { painted: true as const } : {}), ...(placed > 1 ? { components: placed } : {}) });
319
334
  };
320
335
  if (object?.parts.length) {
321
336
  for (const part of object.parts) if (part.subtype === "normal_part" && /^\d+$/.test(part.id))
@@ -324,6 +339,7 @@ export async function plateFilaments(zip: JSZip, settings: string, model: string
324
339
  else if (rootMeshes.has(objectId)) entry(objectId, object?.name ?? "", objectFilament);
325
340
  }
326
341
  plateParts.set(plate.number, drawn.slice(0, 1000));
342
+ if (drawn.length > 1000) partsTruncated.set(plate.number, drawn.length - 1000);
327
343
 
328
344
  const used = new Map<number, string | undefined>();
329
345
  const add = (index: number | undefined, name?: string) => {
@@ -418,5 +434,5 @@ export async function plateFilaments(zip: JSZip, settings: string, model: string
418
434
  result.set(plate.number, [...used.entries()].sort((a, b) => a[0] - b[0]).map(([index, name]) => describe(index, project, name)));
419
435
  }
420
436
  // Every filament the project declares, used on a plate or not: slice_stl takes one profile per declared filament.
421
- return { plates: result, incomplete, project: Array.from({ length: declared }, (_, i) => describe(i + 1, project)), buildItems: plateItems, parts: plateParts };
437
+ return { plates: result, incomplete, project: Array.from({ length: declared }, (_, i) => describe(i + 1, project)), buildItems: plateItems, parts: plateParts, partsTruncated };
422
438
  }
@@ -58,6 +58,7 @@ export const REMOTE_SCOPES: Readonly<Record<string, RemoteScope>> = {
58
58
  slice_stl: "design",
59
59
  lay_flat: "design",
60
60
  counterpart_make_3mf: "design",
61
+ counterpart_part_meshes: "design",
61
62
  // control
62
63
  bambu_connect_import_file: "control",
63
64
  camera_stream_start: "control",
@@ -41,6 +41,8 @@ export type PrinterInfo = {
41
41
  pause: boolean; resume: boolean; cancel: boolean; print3mf: boolean; gcode: boolean;
42
42
  /** What slice_stl can apply with this server's slicer (the same field in mcp-3D-printer-server). */
43
43
  slicing?: { supports: boolean; copies: boolean; orient: boolean };
44
+ /** counterpart_part_meshes is here: one STL per printable part of any 3MF, with its filament's colour (#691, #845). */
45
+ partMeshes?: boolean;
44
46
  };
45
47
  };
46
48
 
@@ -80,6 +82,7 @@ export const PRINTER_INFO_OUTPUT_SCHEMA = {
80
82
  camera: { type: "string", enum: ["bambu-tcp", "rtsp", "http-snapshot", "none"] },
81
83
  cameraStream: { type: "boolean" },
82
84
  diagnostics: { type: "boolean", description: "counterpart_diagnostics is available." },
85
+ partMeshes: { type: "boolean", description: "counterpart_part_meshes is available." },
83
86
  filaments: { type: "string", enum: ["ams", "single", "none"] },
84
87
  pause: { type: "boolean" },
85
88
  resume: { type: "boolean" },
@@ -164,6 +167,7 @@ export const MAKE_3MF_OUTPUT_SCHEMA = {
164
167
  stl_path: { type: "string" },
165
168
  filament: { type: "integer", minimum: 1 },
166
169
  triangles: { type: "integer", minimum: 1 },
170
+ color: { type: "string", pattern: "^#[0-9A-F]{6}$" },
167
171
  },
168
172
  required: ["name", "stl_path", "filament", "triangles"],
169
173
  },
@@ -169,6 +169,8 @@ export type BlenderSetupReport = {
169
169
  target_problem?: "not-installed" | "several-modules";
170
170
  /** What the person can do, in plain words, when the add-on can't be checked or updated here (reason, target_problem). */
171
171
  message?: string;
172
+ /** not-configured: the server settings that connect Blender, for a setup screen or a log; never shown as the message. */
173
+ settings?: string[];
172
174
  /** The installed file's protocol is what the package expects. */
173
175
  current?: boolean;
174
176
  /** Set by update. */
@@ -179,7 +181,8 @@ export type BlenderSetupReport = {
179
181
  type Installer = { command: string; packageSpec: string; packageName: string };
180
182
 
181
183
  const UNSUPPORTED_MESSAGES: Record<NonNullable<BlenderSetupReport["reason"]>, string> = {
182
- "not-configured": "This printer MCP has no Blender bridge configured (BLENDER_MCP_COMMAND and BLENDER_MCP_ARGS). Set it up for MCP for Blender, then check again.",
184
+ // Shown as it is to a new tester (scan-to-make #851): plain words; the settings it needs are in `settings`.
185
+ "not-configured": "Blender isn't connected to your printer software yet. Scan cleanup can use it once it is; printing never needs it.",
183
186
  "custom-command": "This Blender bridge uses its own command, so its add-on is updated with that bridge's installer.",
184
187
  "custom-package": "This Blender bridge uses its own package, so its add-on is updated with that bridge's installer.",
185
188
  };
@@ -249,7 +252,8 @@ export class BlenderAddonSetup {
249
252
  const installer = configuredInstaller(this.env);
250
253
  const { host, port } = blenderAddress(this.env);
251
254
  const listening = await this.system.listening(host, port);
252
- if ("reason" in installer) return { supported: false, reason: installer.reason, listening, message: UNSUPPORTED_MESSAGES[installer.reason] };
255
+ if ("reason" in installer) return { supported: false, reason: installer.reason, listening, message: UNSUPPORTED_MESSAGES[installer.reason],
256
+ ...(installer.reason === "not-configured" ? { settings: ["BLENDER_MCP_COMMAND", "BLENDER_MCP_ARGS"] } : {}) };
253
257
  let live: BlenderAddonHandshake | null | undefined, liveError: string | undefined;
254
258
  if (listening) {
255
259
  try { live = (await this.handshake()) ?? null; }
@@ -320,6 +324,7 @@ export const BLENDER_SETUP_OUTPUT_SCHEMA = {
320
324
  properties: {
321
325
  supported: { type: "boolean", description: "The configured bridge is the upstream MCP for Blender package run with uvx, so this tool can check and update its add-on." },
322
326
  reason: { type: "string", enum: ["not-configured", "custom-command", "custom-package"] },
327
+ settings: { type: "array", items: { type: "string" }, description: "not-configured: the server settings that connect Blender (BLENDER_MCP_COMMAND, BLENDER_MCP_ARGS)." },
323
328
  package: { type: "string", description: "The package as BLENDER_MCP_ARGS names it." },
324
329
  package_version: { type: "string" },
325
330
  expected_protocol: { type: "integer", description: "The add-on protocol the package needs." },