bambu-printer-mcp 1.1.50 → 1.1.52

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 (54) hide show
  1. package/README.md +33 -8
  2. package/dist/ams-mapping.d.ts +19 -0
  3. package/dist/ams-mapping.js +49 -0
  4. package/dist/bambu-network-bridge.d.ts +86 -9
  5. package/dist/bambu-network-bridge.js +284 -4
  6. package/dist/control-reply.d.ts +21 -0
  7. package/dist/control-reply.js +44 -0
  8. package/dist/counterpart/info.js +1 -0
  9. package/dist/counterpart/route.d.ts +37 -0
  10. package/dist/counterpart/route.js +78 -0
  11. package/dist/counterpart/schemas.d.ts +4 -0
  12. package/dist/counterpart/schemas.js +1 -0
  13. package/dist/design-guidance.d.ts +26 -0
  14. package/dist/design-guidance.js +177 -0
  15. package/dist/fusion-mcp-bridge.d.ts +8 -4
  16. package/dist/fusion-mcp-bridge.js +36 -10
  17. package/dist/index.js +219 -54
  18. package/dist/printers/bambu.d.ts +38 -13
  19. package/dist/printers/bambu.js +204 -69
  20. package/dist/printers/camera-sources.d.ts +8 -0
  21. package/dist/printers/camera-sources.js +66 -0
  22. package/dist/printers/camera-stream.d.ts +65 -0
  23. package/dist/printers/camera-stream.js +227 -0
  24. package/dist/printers/camera-tools.d.ts +192 -0
  25. package/dist/printers/camera-tools.js +29 -0
  26. package/dist/printers/camera-wire.d.ts +7 -0
  27. package/dist/printers/camera-wire.js +40 -0
  28. package/dist/safety/print-file.d.ts +3 -0
  29. package/dist/safety/print-file.js +11 -2
  30. package/dist/safety/printer-state.d.ts +7 -0
  31. package/dist/safety/printer-state.js +11 -1
  32. package/dist/slicer/layer-pauses.d.ts +47 -0
  33. package/dist/slicer/layer-pauses.js +130 -0
  34. package/dist/stl/stl-manipulator.d.ts +40 -1
  35. package/dist/stl/stl-manipulator.js +253 -83
  36. package/package.json +2 -1
  37. package/src/ams-mapping.ts +52 -0
  38. package/src/bambu-network-bridge.ts +311 -8
  39. package/src/control-reply.ts +41 -0
  40. package/src/counterpart/info.ts +1 -0
  41. package/src/counterpart/route.ts +91 -0
  42. package/src/counterpart/schemas.ts +2 -0
  43. package/src/design-guidance.ts +188 -0
  44. package/src/fusion-mcp-bridge.ts +30 -10
  45. package/src/index.ts +213 -57
  46. package/src/printers/bambu.ts +194 -60
  47. package/src/printers/camera-sources.ts +53 -0
  48. package/src/printers/camera-stream.ts +165 -0
  49. package/src/printers/camera-tools.ts +29 -0
  50. package/src/printers/camera-wire.ts +39 -0
  51. package/src/safety/print-file.ts +12 -2
  52. package/src/safety/printer-state.ts +11 -1
  53. package/src/slicer/layer-pauses.ts +143 -0
  54. package/src/stl/stl-manipulator.ts +298 -93
@@ -0,0 +1,130 @@
1
+ import fs from "node:fs";
2
+ import JSZip from "jszip";
3
+ /**
4
+ * Pause-at-layer for Bambu-compatible slicer CLIs ("Add pause" in Bambu Studio
5
+ * and OrcaSlicer). The slicer writes the machine's own machine_pause_gcode
6
+ * (M400 U1 on Bambu printers) before the chosen layer, so the printer pauses
7
+ * by itself there and waits for Resume; no remote command is involved.
8
+ *
9
+ * The CLI takes these as --load-custom-gcodes <json> (CustomGCode::Info). It
10
+ * does not apply the pauses a project 3MF already carries in
11
+ * Metadata/custom_gcode_per_print_z.xml, so those are read here and passed the
12
+ * same way. A pause's print_z must be the exact top of its layer: a height
13
+ * between layers lands on the layer below.
14
+ */
15
+ /** CustomGCode::Type, in the order bbs_3mf.cpp writes it as an integer. */
16
+ const CUSTOM_GCODE_TYPES = ["ColorChange", "PausePrint", "ToolChange", "Template", "Custom", "Unknown"];
17
+ /** 1-based layer numbers, as Bambu Studio's and OrcaSlicer's preview slider count them. */
18
+ export function parsePauseLayers(value) {
19
+ if (value === undefined || value === null || value === "")
20
+ return undefined;
21
+ const raw = Array.isArray(value) ? value : String(value).split(/[\s,;]+/).filter(Boolean);
22
+ const layers = raw.map(entry => Number(entry));
23
+ for (const layer of layers) {
24
+ if (!Number.isInteger(layer) || layer < 2) {
25
+ throw new Error(`pause_at_layers takes whole layer numbers of 2 or more (the printer cannot pause before layer 1), not ${JSON.stringify(value)}.`);
26
+ }
27
+ }
28
+ const unique = [...new Set(layers)].sort((a, b) => a - b);
29
+ return unique.length ? unique : undefined;
30
+ }
31
+ function xmlAttr(tag, name) {
32
+ const match = new RegExp(`\\b${name}="([^"]*)"`).exec(tag);
33
+ return match ? match[1].replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&") : undefined;
34
+ }
35
+ /**
36
+ * The custom G-codes (pauses, colour changes, ...) a project 3MF stores for
37
+ * one plate (1-based), as Bambu Studio and OrcaSlicer save them.
38
+ */
39
+ export async function readProjectCustomGcodes(threeMfPath, plate = 1) {
40
+ let zip;
41
+ try {
42
+ zip = await JSZip.loadAsync(await fs.promises.readFile(threeMfPath));
43
+ }
44
+ catch {
45
+ return undefined;
46
+ }
47
+ const file = zip.file(/^Metadata\/custom_gcode_per_print_z\.xml$/i)[0];
48
+ if (!file)
49
+ return undefined;
50
+ const xml = await file.async("string");
51
+ for (const block of xml.match(/<plate>[\s\S]*?<\/plate>/g) ?? []) {
52
+ const info = /<plate_info\b[^>]*>/.exec(block)?.[0];
53
+ if (Number(info ? xmlAttr(info, "id") : NaN) !== plate)
54
+ continue;
55
+ const gcodes = [];
56
+ for (const tag of block.match(/<layer\b[^>]*>/g) ?? []) {
57
+ const type = CUSTOM_GCODE_TYPES[Number(xmlAttr(tag, "type"))] ?? "Unknown";
58
+ const printZ = Number(xmlAttr(tag, "top_z"));
59
+ if (!Number.isFinite(printZ))
60
+ continue;
61
+ gcodes.push({
62
+ type,
63
+ print_z: printZ,
64
+ color: xmlAttr(tag, "color") ?? "",
65
+ extruder: Number(xmlAttr(tag, "extruder") ?? 1) || 1,
66
+ // Template and Custom keep their G-code text in "extra" (CustomGCode.hpp).
67
+ extra: xmlAttr(tag, "extra") ?? "",
68
+ });
69
+ }
70
+ const modeTag = /<mode\b[^>]*>/.exec(block)?.[0];
71
+ return { mode: (modeTag && xmlAttr(modeTag, "value")) || "SingleExtruder", gcodes };
72
+ }
73
+ return undefined;
74
+ }
75
+ /** The plate's G-code text inside a sliced 3MF. */
76
+ export async function readPlateGcode(threeMfPath, plate = 1) {
77
+ const zip = await JSZip.loadAsync(await fs.promises.readFile(threeMfPath));
78
+ const exact = zip.file(`Metadata/plate_${plate}.gcode`);
79
+ const file = exact ?? zip.file(/^Metadata\/plate_\d+\.gcode$/)[0];
80
+ return file ? file.async("string") : undefined;
81
+ }
82
+ /** Each layer's top Z in order, from the slicer's "; Z_HEIGHT:" markers. */
83
+ export function layerTops(gcode) {
84
+ const tops = [];
85
+ for (const match of gcode.matchAll(/^; Z_HEIGHT: ([0-9.]+)\s*$/gm))
86
+ tops.push(Number(match[1]));
87
+ return tops;
88
+ }
89
+ /**
90
+ * The 1-based layers whose block holds a pause: the slicer's "; PAUSE_PRINTING"
91
+ * marker or the machine's pause G-code on its own line.
92
+ */
93
+ export function pausedLayers(gcode, pauseGcode = "M400 U1") {
94
+ const lines = gcode.split(/\r?\n/);
95
+ const paused = new Set();
96
+ let layer = 0;
97
+ const pauseLine = pauseGcode.trim();
98
+ for (const line of lines) {
99
+ if (line.startsWith("; Z_HEIGHT:")) {
100
+ layer += 1;
101
+ continue;
102
+ }
103
+ if (layer === 0)
104
+ continue;
105
+ const trimmed = line.trim();
106
+ if (trimmed === "; PAUSE_PRINTING" || (pauseLine && trimmed === pauseLine))
107
+ paused.add(layer);
108
+ }
109
+ return [...paused].sort((a, b) => a - b);
110
+ }
111
+ /** The machine_pause_gcode a sliced file was made with (its config block), else Bambu's M400 U1. */
112
+ export function machinePauseGcode(gcode) {
113
+ const match = /^; machine_pause_gcode = (.*)$/m.exec(gcode);
114
+ const value = match?.[1]?.split("\\n")[0]?.trim();
115
+ return value || "M400 U1";
116
+ }
117
+ /** Project custom G-codes plus a pause before each requested layer, at that layer's exact top. */
118
+ export function customGcodesWithPauses(tops, layers, project) {
119
+ const total = tops.length;
120
+ const beyond = layers.filter(layer => layer > total);
121
+ if (beyond.length) {
122
+ throw new Error(`This print has ${total} layers, so it cannot pause before layer ${beyond.join(", ")}.`);
123
+ }
124
+ const pauses = layers.map(layer => ({ type: "PausePrint", print_z: tops[layer - 1], color: "", extruder: 1, extra: "" }));
125
+ const kept = (project?.gcodes ?? []).filter(item => !(item.type === "PausePrint" && pauses.some(p => Math.abs(p.print_z - item.print_z) < 1e-4)));
126
+ return {
127
+ mode: project?.mode || "SingleExtruder",
128
+ gcodes: [...kept, ...pauses].sort((a, b) => a.print_z - b.print_z),
129
+ };
130
+ }
@@ -51,6 +51,24 @@ export interface BambuSliceOptions {
51
51
  skipModifiedGcodes?: boolean;
52
52
  slicePlate?: number;
53
53
  processOverrides?: ProcessOverrides;
54
+ pauseAtLayers?: number[];
55
+ customGcodesFile?: string;
56
+ }
57
+ /** Bambu Studio's or OrcaSlicer's own result.json, parsed verbatim. */
58
+ export type SlicerResult = Record<string, unknown>;
59
+ /** A sliced file, with the slicer's own result.json when it wrote one. */
60
+ export type SliceOutput = {
61
+ path: string;
62
+ slicer_result?: SlicerResult;
63
+ };
64
+ /**
65
+ * A slicer failure that keeps the slicer's own result.json. The message starts
66
+ * with the slicer's own words (`slicerText`), when it gave any, then `detail`.
67
+ */
68
+ export declare class SlicerRunError extends Error {
69
+ readonly slicerResult?: SlicerResult | undefined;
70
+ readonly slicerText: string;
71
+ constructor(detail: string, slicerResult?: SlicerResult | undefined);
54
72
  }
55
73
  export declare class STLManipulator extends EventEmitter {
56
74
  private tempDir;
@@ -172,6 +190,13 @@ export declare class STLManipulator extends EventEmitter {
172
190
  * @returns Path to the generated G-code or sliced 3MF file
173
191
  */
174
192
  sliceSTL(stlFilePath: string, slicerType: SlicerType, slicerPath: string, slicerProfile?: string, progressCallback?: ProgressCallback, printerPreset?: string, bambuOptions?: BambuSliceOptions): Promise<string>;
193
+ /**
194
+ * sliceSTL with the Bambu-compatible CLI's own result.json, parsed verbatim.
195
+ * A failure throws SlicerRunError, whose message starts with the slicer's
196
+ * error_string and plate warnings.
197
+ */
198
+ sliceSTLWithResult(stlFilePath: string, slicerType: SlicerType, slicerPath: string, slicerProfile?: string, progressCallback?: ProgressCallback, printerPreset?: string, bambuOptions?: BambuSliceOptions): Promise<SliceOutput>;
199
+ private sliceSTLOnce;
175
200
  /**
176
201
  * Enhanced version of confirmTemperatures with better error handling
177
202
  * @param gcodePath Path to the G-code file
@@ -207,7 +232,21 @@ export declare class STLManipulator extends EventEmitter {
207
232
  */
208
233
  centerModel(stlFilePath: string, progressCallback?: ProgressCallback): Promise<string>;
209
234
  /**
210
- * Rotate the model so its largest flat face lies on the XY plane (Z=0).
235
+ * Rotate the model so a face rests on the bed, in the pose with the least
236
+ * part and support material per mm² of bed contact, then move it down to
237
+ * Z=0. Returns the new file's path, or the input path when no pose qualifies.
211
238
  */
212
239
  layFlat(stlFilePath: string, progressCallback?: ProgressCallback): Promise<string>;
240
+ /**
241
+ * layFlat with its outcome. A pose qualifies only when some face, turned to
242
+ * face down, lies on the rotated mesh's lowest plane; `laid_flat` is false
243
+ * and the model is unchanged when none does.
244
+ */
245
+ layFlatWithResult(stlFilePath: string, progressCallback?: ProgressCallback): Promise<LayFlatResult>;
213
246
  }
247
+ export type LayFlatResult = {
248
+ /** The laid-flat STL, or the unchanged input when `laid_flat` is false. */
249
+ path: string;
250
+ laid_flat: boolean;
251
+ message: string;
252
+ };
@@ -1,3 +1,4 @@
1
+ import { customGcodesWithPauses, layerTops, machinePauseGcode, pausedLayers, readPlateGcode, readProjectCustomGcodes } from "../slicer/layer-pauses.js";
1
2
  import * as THREE from 'three';
2
3
  import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js';
3
4
  import { STLExporter } from 'three/examples/jsm/exporters/STLExporter.js';
@@ -113,6 +114,45 @@ const PROFILE_METADATA_KEYS = new Set([
113
114
  'name', 'type', 'from', 'inherits', 'instantiation', 'setting_id', 'version', 'is_custom_defined',
114
115
  'compatible_printers', 'compatible_printers_condition', 'compatible_prints', 'compatible_prints_condition',
115
116
  ]);
117
+ /**
118
+ * A slicer failure that keeps the slicer's own result.json. The message starts
119
+ * with the slicer's own words (`slicerText`), when it gave any, then `detail`.
120
+ */
121
+ export class SlicerRunError extends Error {
122
+ constructor(detail, slicerResult) {
123
+ const slicerText = slicerResult ? slicerResultText(slicerResult) : "";
124
+ super(slicerText ? `${slicerText}\n${detail}` : detail);
125
+ this.slicerResult = slicerResult;
126
+ this.name = "SlicerRunError";
127
+ this.slicerText = slicerText;
128
+ }
129
+ }
130
+ /**
131
+ * The result.json this run wrote. Bambu Studio 02.08.02.61 writes it on macOS
132
+ * for successes and failures alike; an older file must not describe this run.
133
+ */
134
+ function readCliResult(cli) {
135
+ try {
136
+ if (fs.statSync(cli.resultPath).mtimeMs < cli.startedAt)
137
+ return undefined;
138
+ const result = JSON.parse(fs.readFileSync(cli.resultPath, "utf8"));
139
+ return result && typeof result === "object" && !Array.isArray(result) ? result : undefined;
140
+ }
141
+ catch {
142
+ return undefined;
143
+ }
144
+ }
145
+ /**
146
+ * The slicer's own words: its error_string when it reports a failing
147
+ * return_code (not "Success."), then each plate's warning_message.
148
+ */
149
+ function slicerResultText(result) {
150
+ const plates = Array.isArray(result.sliced_plates) ? result.sliced_plates : [];
151
+ return [
152
+ result.return_code === 0 ? undefined : result.error_string,
153
+ ...plates.map(plate => plate && typeof plate === "object" ? plate.warning_message : undefined),
154
+ ].filter((text) => typeof text === "string" && text.trim() !== "").map(text => text.trim()).join("\n");
155
+ }
116
156
  function describeSlicerFailure(error, stdout, stderr, cli) {
117
157
  const status = typeof error.signal === "string" && error.signal
118
158
  ? `crashed with ${error.signal}`
@@ -122,7 +162,7 @@ function describeSlicerFailure(error, stdout, stderr, cli) {
122
162
  return `Slicer failed: the slicer ${status}${reason ? ` (${reason})` : ""}. ${error.message.trim()}${output ? `\nSlicer output: ${output}` : ""}`;
123
163
  }
124
164
  // Bambu Studio and OrcaSlicer CLI errors (libslic3r/Utils.hpp). The process
125
- // exits with the low byte of the code; on Linux result.json names the error.
165
+ // exits with the low byte of the code; result.json names the error.
126
166
  const BAMBU_CLI_ERRORS = {
127
167
  [-2]: "invalid parameters to the slicer",
128
168
  [-3]: "input files not found",
@@ -145,16 +185,9 @@ const BAMBU_CLI_ERRORS = {
145
185
  [-102]: "G-code in an unprintable area",
146
186
  };
147
187
  function bambuCliFailureReason(exitCode, cli) {
148
- try {
149
- if (fs.statSync(cli.resultPath).mtimeMs >= cli.startedAt) {
150
- const result = JSON.parse(fs.readFileSync(cli.resultPath, "utf8"));
151
- if (typeof result.error_string === "string" && result.error_string.trim()) {
152
- return `${result.error_string.trim()} [${result.return_code}]`;
153
- }
154
- }
155
- }
156
- catch {
157
- // result.json is written only on Linux and only for handled errors.
188
+ const result = readCliResult(cli);
189
+ if (typeof result?.error_string === "string" && result.error_string.trim()) {
190
+ return `${result.error_string.trim()} [${result.return_code}]`;
158
191
  }
159
192
  if (typeof exitCode !== "number")
160
193
  return undefined;
@@ -1305,6 +1338,56 @@ export class STLManipulator extends EventEmitter {
1305
1338
  * @returns Path to the generated G-code or sliced 3MF file
1306
1339
  */
1307
1340
  async sliceSTL(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, bambuOptions) {
1341
+ return (await this.sliceSTLWithResult(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, bambuOptions)).path;
1342
+ }
1343
+ /**
1344
+ * sliceSTL with the Bambu-compatible CLI's own result.json, parsed verbatim.
1345
+ * A failure throws SlicerRunError, whose message starts with the slicer's
1346
+ * error_string and plate warnings.
1347
+ */
1348
+ async sliceSTLWithResult(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, bambuOptions) {
1349
+ const once = (options) => this.sliceSTLOnce(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, options);
1350
+ const layers = bambuOptions?.pauseAtLayers?.length ? bambuOptions.pauseAtLayers : undefined;
1351
+ const cli = slicerType === 'bambustudio' || slicerType === 'orcaslicer' || slicerType === 'orcaslicer-bambulab';
1352
+ const plate = bambuOptions?.slicePlate && bambuOptions.slicePlate > 0 ? bambuOptions.slicePlate : 1;
1353
+ // The CLI drops a project's own pauses and colour changes; carry them over.
1354
+ const project = cli && /\.3mf$/i.test(stlFilePath) ? await readProjectCustomGcodes(stlFilePath, plate) : undefined;
1355
+ if (!layers && !project?.gcodes.length)
1356
+ return once(bambuOptions);
1357
+ if (layers && !cli) {
1358
+ throw new Error(`Pausing at a layer needs the Bambu Studio or OrcaSlicer CLI, not ${slicerType}.`);
1359
+ }
1360
+ const customGcodesFile = path.join(this.tempDir, `custom-gcodes-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);
1361
+ try {
1362
+ let tops = [];
1363
+ if (layers) {
1364
+ // A pause sits at its layer's exact top Z; learn the tops from a slice without pauses.
1365
+ if (progressCallback)
1366
+ progressCallback(10, `Finding layer heights for the pause before layer ${layers.join(", ")}`);
1367
+ const plain = await once({ ...bambuOptions, pauseAtLayers: undefined, customGcodesFile: undefined });
1368
+ const gcode = await readPlateGcode(plain.path, plate);
1369
+ if (!gcode)
1370
+ throw new Error('The slicer wrote no plate G-code, so the pause layers cannot be placed.');
1371
+ tops = layerTops(gcode);
1372
+ }
1373
+ const info = layers ? customGcodesWithPauses(tops, layers, project) : project;
1374
+ await fs.promises.writeFile(customGcodesFile, JSON.stringify(info));
1375
+ const result = await once({ ...bambuOptions, customGcodesFile });
1376
+ if (layers) {
1377
+ const gcode = await readPlateGcode(result.path, plate);
1378
+ const placed = gcode ? pausedLayers(gcode, machinePauseGcode(gcode)) : [];
1379
+ const missing = layers.filter(layer => !placed.includes(layer));
1380
+ if (!gcode || missing.length || layerTops(gcode).length !== tops.length) {
1381
+ throw new Error(`The slicer did not place the pause before layer ${(missing.length ? missing : layers).join(", ")}. Nothing was sent to the printer.`);
1382
+ }
1383
+ }
1384
+ return result;
1385
+ }
1386
+ finally {
1387
+ await fs.promises.rm(customGcodesFile, { force: true });
1388
+ }
1389
+ }
1390
+ async sliceSTLOnce(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, bambuOptions) {
1308
1391
  const operationId = this.generateOperationId();
1309
1392
  this.activeOperations.set(operationId, true);
1310
1393
  if (slicerType !== 'orca-slicer-api' && isPathLikeExecutable(slicerPath) && !fs.existsSync(slicerPath)) {
@@ -1453,8 +1536,8 @@ export class STLManipulator extends EventEmitter {
1453
1536
  throw new Error("OrcaSlicer's CLI crashes when scale above 1, rotate_x or rotate_y moves a 3MF object below the bed while arranging. " +
1454
1537
  "Set arrange to false, or apply the transform in the slicer and export the project.");
1455
1538
  }
1456
- if (orcaCli && !is3mf && bambuOptions?.repetitions !== undefined && bambuOptions.cloneObjects) {
1457
- throw new Error("Use either repetitions or clone_objects for an STL with OrcaSlicer, not both.");
1539
+ if (!is3mf && bambuOptions?.repetitions !== undefined && bambuOptions.cloneObjects) {
1540
+ throw new Error("Use either repetitions or clone_objects for an STL, not both.");
1458
1541
  }
1459
1542
  const inputPath = meshTransform ? await this.transformMeshForCli(stlFilePath, bambuOptions) : stlFilePath;
1460
1543
  if (inputPath !== stlFilePath)
@@ -1494,8 +1577,9 @@ export class STLManipulator extends EventEmitter {
1494
1577
  if (bambuOptions?.arrange !== undefined)
1495
1578
  args.push('--arrange', bambuOptions.arrange ? '1' : '0');
1496
1579
  if (bambuOptions?.repetitions !== undefined) {
1497
- // OrcaSlicer counts copies of a single loaded STL with --clone-objects.
1498
- if (orcaCli && !is3mf)
1580
+ // Both Bambu Studio and Orca count STL copies with --clone-objects.
1581
+ // --repetitions > 1 requires a selected existing plate and rejects --slice 0.
1582
+ if (!is3mf)
1499
1583
  args.push('--clone-objects', String(bambuOptions.repetitions));
1500
1584
  else
1501
1585
  args.push('--repetitions', String(bambuOptions.repetitions));
@@ -1520,6 +1604,8 @@ export class STLManipulator extends EventEmitter {
1520
1604
  }
1521
1605
  if (bambuOptions?.loadFilamentIds)
1522
1606
  args.push('--load-filament-ids', bambuOptions.loadFilamentIds);
1607
+ if (bambuOptions?.customGcodesFile)
1608
+ args.push('--load-custom-gcodes', path.resolve(bambuOptions.customGcodesFile));
1523
1609
  args.push(path.resolve(inputPath));
1524
1610
  // Override outputFilePath for bambustudio since it produces 3MF, not gcode
1525
1611
  outputFilePath = bambuOutputPath;
@@ -1538,7 +1624,8 @@ export class STLManipulator extends EventEmitter {
1538
1624
  if (error) {
1539
1625
  console.error(`Slicer Error: ${error.message}`);
1540
1626
  console.error(`Slicer Stderr: ${stderr}`);
1541
- reject(new Error(describeSlicerFailure(error, stdout, stderr, cliResult)));
1627
+ const slicerResult = cliResult ? readCliResult(cliResult) : undefined;
1628
+ reject(new SlicerRunError(describeSlicerFailure(error, stdout, stderr, cliResult), slicerResult));
1542
1629
  }
1543
1630
  else {
1544
1631
  console.error(`Slicer Stdout: ${stdout}`);
@@ -1573,8 +1660,16 @@ export class STLManipulator extends EventEmitter {
1573
1660
  // This check might be redundant if the promise rejected on kill, but good safety
1574
1661
  throw new Error("Slicing operation cancelled after process finished");
1575
1662
  }
1663
+ const slicerResult = cliResult ? readCliResult(cliResult) : undefined;
1664
+ if (cliResult && !slicerResult) {
1665
+ // Older or Linux CLIs may write result.json only for handled errors.
1666
+ console.error(`${slicerType} wrote no result.json for this slice, so its own checks are not available.`);
1667
+ }
1668
+ if (typeof slicerResult?.return_code === "number" && slicerResult.return_code !== 0) {
1669
+ throw new SlicerRunError(`Slicer failed: the slicer exited with code 0, but its result.json reports return_code ${slicerResult.return_code}.`, slicerResult);
1670
+ }
1576
1671
  if (!fs.existsSync(outputFilePath)) {
1577
- throw new Error(`Slicer finished but output file not found: ${outputFilePath}`);
1672
+ throw new SlicerRunError(`Slicer finished but output file not found: ${outputFilePath}`, slicerResult);
1578
1673
  }
1579
1674
  if (progressCallback)
1580
1675
  progressCallback(100, "Slicing completed successfully");
@@ -1584,7 +1679,7 @@ export class STLManipulator extends EventEmitter {
1584
1679
  success: true,
1585
1680
  output: outputFilePath
1586
1681
  });
1587
- return outputFilePath;
1682
+ return slicerResult ? { path: outputFilePath, slicer_result: slicerResult } : { path: outputFilePath };
1588
1683
  }
1589
1684
  catch (error) {
1590
1685
  console.error(`Slicing failed for ${stlFilePath}:`, error);
@@ -1774,9 +1869,19 @@ export class STLManipulator extends EventEmitter {
1774
1869
  }
1775
1870
  }
1776
1871
  /**
1777
- * Rotate the model so its largest flat face lies on the XY plane (Z=0).
1872
+ * Rotate the model so a face rests on the bed, in the pose with the least
1873
+ * part and support material per mm² of bed contact, then move it down to
1874
+ * Z=0. Returns the new file's path, or the input path when no pose qualifies.
1778
1875
  */
1779
1876
  async layFlat(stlFilePath, progressCallback) {
1877
+ return (await this.layFlatWithResult(stlFilePath, progressCallback)).path;
1878
+ }
1879
+ /**
1880
+ * layFlat with its outcome. A pose qualifies only when some face, turned to
1881
+ * face down, lies on the rotated mesh's lowest plane; `laid_flat` is false
1882
+ * and the model is unchanged when none does.
1883
+ */
1884
+ async layFlatWithResult(stlFilePath, progressCallback) {
1780
1885
  const operationId = this.generateOperationId();
1781
1886
  this.activeOperations.set(operationId, true);
1782
1887
  try {
@@ -1790,91 +1895,96 @@ export class STLManipulator extends EventEmitter {
1790
1895
  const positionAttribute = geometry.getAttribute('position');
1791
1896
  if (!positionAttribute)
1792
1897
  throw new Error("Geometry has no position attribute.");
1793
- const faces = [];
1898
+ const faceCount = Math.floor(positionAttribute.count / 3);
1899
+ if (faceCount === 0)
1900
+ throw new Error("No faces found in geometry.");
1901
+ const mesh = {
1902
+ positions: new Float64Array(faceCount * 9),
1903
+ normals: new Float64Array(faceCount * 3),
1904
+ areas: new Float64Array(faceCount),
1905
+ volume: 0,
1906
+ };
1907
+ const center = new THREE.Vector3();
1908
+ boundingBox.getCenter(center);
1794
1909
  const vA = new THREE.Vector3();
1795
1910
  const vB = new THREE.Vector3();
1796
1911
  const vC = new THREE.Vector3();
1797
- const faceNormal = new THREE.Vector3();
1798
1912
  const cb = new THREE.Vector3(), ab = new THREE.Vector3();
1799
- // Iterate through faces (triangles)
1800
- for (let i = 0; i < positionAttribute.count; i += 3) {
1801
- vA.fromBufferAttribute(positionAttribute, i);
1802
- vB.fromBufferAttribute(positionAttribute, i + 1);
1803
- vC.fromBufferAttribute(positionAttribute, i + 2);
1804
- // Calculate face normal
1913
+ const fromA = new THREE.Vector3(), fromB = new THREE.Vector3(), fromC = new THREE.Vector3();
1914
+ for (let face = 0; face < faceCount; face++) {
1915
+ vA.fromBufferAttribute(positionAttribute, face * 3);
1916
+ vB.fromBufferAttribute(positionAttribute, face * 3 + 1);
1917
+ vC.fromBufferAttribute(positionAttribute, face * 3 + 2);
1918
+ vA.toArray(mesh.positions, face * 9);
1919
+ vB.toArray(mesh.positions, face * 9 + 3);
1920
+ vC.toArray(mesh.positions, face * 9 + 6);
1921
+ // Signed tetrahedron volumes about the center sum to the enclosed volume.
1922
+ fromA.subVectors(vA, center);
1923
+ fromB.subVectors(vB, center);
1924
+ fromC.subVectors(vC, center);
1925
+ mesh.volume += fromA.dot(fromB.cross(fromC)) / 6;
1926
+ // The cross product's direction is the outward normal; half its length is the area.
1805
1927
  cb.subVectors(vC, vB);
1806
1928
  ab.subVectors(vA, vB);
1807
1929
  cb.cross(ab);
1808
- faceNormal.copy(cb).normalize();
1809
- // Calculate face area (using cross product magnitude / 2)
1810
- const area = cb.length() / 2;
1811
- faces.push({
1812
- normal: faceNormal.clone(),
1813
- area: area,
1814
- vertices: [vA.clone(), vB.clone(), vC.clone()] // Store vertices if needed for center calculation
1815
- });
1930
+ mesh.areas[face] = cb.length() / 2;
1931
+ cb.normalize().toArray(mesh.normals, face * 3);
1816
1932
  }
1817
- if (faces.length === 0)
1818
- throw new Error("No faces found in geometry.");
1933
+ mesh.volume = Math.abs(mesh.volume);
1819
1934
  if (!this.activeOperations.get(operationId))
1820
1935
  throw new Error("Operation cancelled");
1821
1936
  if (progressCallback)
1822
1937
  progressCallback(65, "Grouping faces by normal...");
1823
1938
  // Group faces by similar normal vectors (tolerance for floating point errors)
1824
- const normalGroups = new Map();
1939
+ const normalGroups = [];
1825
1940
  const tolerance = 1e-5;
1826
- for (const face of faces) {
1827
- let foundGroup = false;
1828
- for (const [key, group] of normalGroups.entries()) {
1829
- if (face.normal.distanceToSquared(group.representativeNormal) < tolerance) {
1830
- group.totalArea += face.area;
1831
- // Optional: Average the normal? For now, just use the first one.
1832
- foundGroup = true;
1833
- break;
1834
- }
1835
- }
1836
- if (!foundGroup) {
1837
- const key = `${face.normal.x.toFixed(5)},${face.normal.y.toFixed(5)},${face.normal.z.toFixed(5)}`;
1838
- if (!normalGroups.has(key)) { // Ensure unique key even if floats slightly differ after toFixed
1839
- normalGroups.set(key, { totalArea: face.area, representativeNormal: face.normal });
1840
- }
1841
- }
1941
+ const faceNormal = new THREE.Vector3();
1942
+ for (let face = 0; face < faceCount; face++) {
1943
+ if (!(mesh.areas[face] > 0))
1944
+ continue;
1945
+ faceNormal.fromArray(mesh.normals, face * 3);
1946
+ const group = normalGroups.find(candidate => faceNormal.distanceToSquared(candidate.representativeNormal) < tolerance);
1947
+ if (group)
1948
+ group.totalArea += mesh.areas[face];
1949
+ else
1950
+ normalGroups.push({ totalArea: mesh.areas[face], representativeNormal: faceNormal.clone() });
1842
1951
  }
1843
- if (normalGroups.size === 0)
1844
- throw new Error("Could not group faces by normal.");
1845
1952
  if (!this.activeOperations.get(operationId))
1846
1953
  throw new Error("Operation cancelled");
1847
1954
  if (progressCallback)
1848
- progressCallback(75, "Finding largest flat surface...");
1849
- // Include already-horizontal faces: excluding Z-aligned normals can
1850
- // stand a flat model on its edge, including on a repeated layFlat call.
1851
- let largestArea = 0;
1852
- let targetNormal = null;
1853
- const downVector = new THREE.Vector3(0, 0, -1); // Target normal (pointing down)
1854
- // Faces are grouped by direction, so a part whose flat faces are all
1855
- // horizontal has equal up- and down-facing areas. On a tie, keep the
1856
- // face that already points down so a seated part is not flipped.
1857
- for (const group of normalGroups.values()) {
1858
- const tied = targetNormal !== null && Math.abs(group.totalArea - largestArea) <= largestArea * 1e-6;
1859
- if (tied ? group.representativeNormal.z < targetNormal.z : group.totalArea > largestArea) {
1860
- largestArea = group.totalArea;
1861
- targetNormal = group.representativeNormal;
1862
- }
1955
+ progressCallback(75, "Finding the pose that rests on the bed...");
1956
+ // Candidate directions to turn down: the largest face groups, plus the
1957
+ // model's own axes so a part with a domed side can be flipped exactly.
1958
+ const candidates = normalGroups
1959
+ .sort((a, b) => b.totalArea - a.totalArea)
1960
+ .slice(0, LAY_FLAT_MAX_GROUP_CANDIDATES)
1961
+ .map(group => group.representativeNormal);
1962
+ for (const axis of [[0, 0, -1], [0, 0, 1], [1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0]]) {
1963
+ const normal = new THREE.Vector3(axis[0], axis[1], axis[2]);
1964
+ if (!candidates.some(candidate => candidate.distanceToSquared(normal) < tolerance))
1965
+ candidates.push(normal);
1966
+ }
1967
+ let best = null;
1968
+ for (const normal of candidates) {
1969
+ const pose = evaluateLayFlatPose(mesh, normal);
1970
+ if (pose && (!best || isBetterLayFlatPose(pose, best)))
1971
+ best = pose;
1863
1972
  }
1864
- if (!targetNormal) {
1865
- // Only a mesh without any face area reaches this.
1866
- console.warn("Could not find a suitable large flat face to lay down. No changes made.");
1867
- this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: stlFilePath, message: "No suitable flat face found." });
1868
- return stlFilePath;
1973
+ if (!best) {
1974
+ const message = "No face lies on the model's lowest plane in any candidate orientation, so the model is unchanged.";
1975
+ console.error(`lay_flat: ${message}`);
1976
+ this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: stlFilePath, message });
1977
+ return { path: stlFilePath, laid_flat: false, message };
1869
1978
  }
1870
1979
  if (progressCallback)
1871
1980
  progressCallback(80, "Calculating rotation...");
1872
- // Calculate the rotation needed to align targetNormal with downVector
1873
- const quaternion = new THREE.Quaternion().setFromUnitVectors(targetNormal, downVector);
1874
- const rotationMatrix = new THREE.Matrix4().makeRotationFromQuaternion(quaternion);
1981
+ // Turn the chosen normal to face straight down. Turning +Z down rotates
1982
+ // half a turn about X, which keeps the model's X layout.
1983
+ const downVector = new THREE.Vector3(0, 0, -1);
1984
+ const rotationMatrix = best.normal.dot(downVector) < -1 + 1e-9
1985
+ ? new THREE.Matrix4().makeRotationX(Math.PI)
1986
+ : new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(best.normal, downVector));
1875
1987
  // Rotate around the model's center
1876
- const center = new THREE.Vector3();
1877
- boundingBox.getCenter(center);
1878
1988
  const toOriginMatrix = new THREE.Matrix4().makeTranslation(-center.x, -center.y, -center.z);
1879
1989
  const fromOriginMatrix = new THREE.Matrix4().makeTranslation(center.x, center.y, center.z);
1880
1990
  // Apply rotation
@@ -1892,8 +2002,9 @@ export class STLManipulator extends EventEmitter {
1892
2002
  const outputFileName = path.basename(stlFilePath, '.stl') + '_flat.stl';
1893
2003
  const outputFilePath = path.join(this.tempDir, outputFileName);
1894
2004
  await this.saveSTL(geometry, outputFilePath, progressCallback); // 90-100% progress
1895
- this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: outputFilePath });
1896
- return outputFilePath;
2005
+ const message = `Rests on ${best.contactArea.toFixed(1)} mm² of bed contact; overhangs more than 45° from vertical need about ${best.supportVolume.toFixed(0)} mm³ of support.`;
2006
+ this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: outputFilePath, message });
2007
+ return { path: outputFilePath, laid_flat: true, message };
1897
2008
  }
1898
2009
  catch (error) {
1899
2010
  this.emit('operationError', { operationId, type: 'layFlat', error: error instanceof Error ? error.message : String(error) });
@@ -1904,3 +2015,62 @@ export class STLManipulator extends EventEmitter {
1904
2015
  }
1905
2016
  }
1906
2017
  }
2018
+ const LAY_FLAT_MAX_GROUP_CANDIDATES = 64;
2019
+ /** Faces tilted more than 45° from vertical overhang and need support. */
2020
+ const LAY_FLAT_OVERHANG_COS = Math.SQRT1_2 + 1e-6;
2021
+ /**
2022
+ * Score turning `normal` to face the bed. The bed is the mesh's lowest plane in
2023
+ * that pose, its support plane. Faces lying on it, within 0.5% of the model's
2024
+ * height there (at most 0.2 mm), are bed contact. Overhanging faces above it
2025
+ * need support up from the bed: their projected area times their height.
2026
+ * Returns null when no face lies on the bed: turning that normal down would
2027
+ * rest the model on an edge or a point, not a face.
2028
+ */
2029
+ function evaluateLayFlatPose(mesh, normal) {
2030
+ const { positions, normals, areas } = mesh;
2031
+ const nx = normal.x, ny = normal.y, nz = normal.z;
2032
+ // Distance along the normal grows toward the bed: the bed is at its maximum.
2033
+ let bed = -Infinity, top = Infinity;
2034
+ for (let index = 0; index < positions.length; index += 3) {
2035
+ const along = positions[index] * nx + positions[index + 1] * ny + positions[index + 2] * nz;
2036
+ if (along > bed)
2037
+ bed = along;
2038
+ if (along < top)
2039
+ top = along;
2040
+ }
2041
+ const tolerance = Math.min(0.2, Math.max(0.005 * (bed - top), 1e-4));
2042
+ let contactArea = 0;
2043
+ let supportVolume = 0;
2044
+ for (let face = 0; face < areas.length; face++) {
2045
+ const facing = normals[face * 3] * nx + normals[face * 3 + 1] * ny + normals[face * 3 + 2] * nz;
2046
+ if (!(facing > 0))
2047
+ continue;
2048
+ const base = face * 9;
2049
+ let heightSum = 0, heightMax = 0;
2050
+ for (let corner = base; corner < base + 9; corner += 3) {
2051
+ const height = bed - (positions[corner] * nx + positions[corner + 1] * ny + positions[corner + 2] * nz);
2052
+ heightSum += height;
2053
+ if (height > heightMax)
2054
+ heightMax = height;
2055
+ }
2056
+ if (heightMax <= tolerance)
2057
+ contactArea += areas[face];
2058
+ else if (facing > LAY_FLAT_OVERHANG_COS)
2059
+ supportVolume += areas[face] * facing * (heightSum / 3);
2060
+ }
2061
+ if (!(contactArea > 0))
2062
+ return null;
2063
+ return { normal, contactArea, supportVolume, stackHeight: (mesh.volume + supportVolume) / contactArea };
2064
+ }
2065
+ /**
2066
+ * Prefer the pose with the lowest stack height, then the larger contact. On a
2067
+ * tie, keep the face that already points down so a seated part is not flipped.
2068
+ */
2069
+ function isBetterLayFlatPose(pose, best) {
2070
+ const same = (a, b) => Math.abs(a - b) <= 1e-9 + 1e-6 * Math.max(Math.abs(a), Math.abs(b));
2071
+ if (!same(pose.stackHeight, best.stackHeight))
2072
+ return pose.stackHeight < best.stackHeight;
2073
+ if (!same(pose.contactArea, best.contactArea))
2074
+ return pose.contactArea > best.contactArea;
2075
+ return pose.normal.z < best.normal.z;
2076
+ }