bambu-printer-mcp 1.1.49 → 1.1.51

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.
@@ -12,6 +12,7 @@ import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, d
12
12
  import { describeHmsKey, hiddenHmsKeys, hiddenHmsNotices, reportedHmsKey, unchippedNozzles, validatePrinterState, manualHeatingRequirements, type PrinterStateRequirements } from "../safety/printer-state.js";
13
13
  import { withPrinterOperation, withPrintSnapshot, uniquePrintName, normalizedRemotePath, cancelPendingPrinterOperations } from "../safety/artifact.js";
14
14
  import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "./camera-models.js";
15
+ import { resolveStudioPrintOptions, usedNozzleCount, type CallerPrintOptions } from "../studio-print-options.js";
15
16
  import { Client as FTPClient } from "basic-ftp";
16
17
  import * as mqtt from "mqtt";
17
18
  import {
@@ -46,6 +47,35 @@ function loadClientCreds(): { cert: Buffer; key: Buffer } | null {
46
47
  const CLIENT_CREDS = loadClientCreds();
47
48
 
48
49
  const COMMAND_SETTLE_MS = 300;
50
+ /** How long a stop waits for the printer's MQTT PUBACK before its client is closed (BAMBU_STOP_ACK_MS for tests). */
51
+ const stopAckMs = () => { const value = Number(process.env.BAMBU_STOP_ACK_MS); return Number.isInteger(value) && value > 0 ? value : 10_000; };
52
+
53
+ /**
54
+ * Publish JSON exactly as Bambu Studio's MachineObject::publish_json does
55
+ * (DeviceManager.cpp:2462): the given message on device/<serial>/request at the
56
+ * given QoS. With QoS 1 it resolves on the printer's PUBACK. bambu-node's own
57
+ * publish has no QoS (MQTT.js defaults to 0).
58
+ */
59
+ function publishStudioJson(client: BambuClient, message: Record<string, any>, qos: 0 | 1): Promise<void> {
60
+ const mqttClient = (client as any).mqttClient;
61
+ const serial = (client as any).config?.serialNumber;
62
+ if (!mqttClient || typeof mqttClient.publish !== "function" || typeof serial !== "string") return client.publish(message);
63
+ return new Promise((resolve, reject) => {
64
+ mqttClient.publish(`device/${serial}/request`, JSON.stringify(message), { qos }, (error?: Error) => {
65
+ if (error) reject(new Error(`Error publishing to device/${serial}/request: ${error.message}`));
66
+ else resolve();
67
+ });
68
+ });
69
+ }
70
+
71
+ /**
72
+ * Bambu Studio's stop, MachineObject::command_task_abort (DeviceManager.cpp:1418-1426):
73
+ * {"print":{"command":"stop","param":"","sequence_id":"<n>"}} at QoS 1. bambu-node's
74
+ * UpdateStateCommand sends no param, at QoS 0.
75
+ */
76
+ const studioStopCommand = {
77
+ invoke: (client: BambuClient) => publishStudioJson(client, { print: { command: "stop", param: "", sequence_id: String(Date.now()) } }, 1),
78
+ };
49
79
  /** A cached report older than this may be refreshed once with PushAll; see readProgressReport. */
50
80
  const STALE_REPORT_MS = 300_000;
51
81
  /** HMS 0500-0500-0001-0007: firmware 01.08.05+ rejected an unsigned MQTT command. */
@@ -114,6 +144,11 @@ interface BambuPrintOptionsInternal {
114
144
  flowCalibration?: boolean;
115
145
  vibrationCalibration?: boolean;
116
146
  layerInspect?: boolean;
147
+ /** Explicit Studio option values (0 off, 1 on, 2 auto); see studio-print-options.ts. */
148
+ autoBedLeveling?: number;
149
+ autoFlowCali?: number;
150
+ autoOffsetCali?: number;
151
+ extruderCaliManualMode?: number;
117
152
  timelapse?: boolean;
118
153
  amsMapping?: number[];
119
154
  /**
@@ -988,6 +1023,13 @@ export class BambuImplementation {
988
1023
  model, nozzleDiameters: options.nozzleDiameters, plateIndex: options.plateIndex ?? 0, bedType: options.bedType,
989
1024
  });
990
1025
  const resumeFile = await checkedFile(inspection, options.filePath);
1026
+ // The options Bambu Studio's Send dialog would send; explicit ones win.
1027
+ const studio = resolveStudioPrintOptions(model, {
1028
+ bedLeveling: options.bedLeveling, flowCalibration: options.flowCalibration,
1029
+ vibrationCalibration: options.vibrationCalibration, layerInspect: options.layerInspect,
1030
+ autoBedLeveling: options.autoBedLeveling, autoFlowCali: options.autoFlowCali,
1031
+ autoOffsetCali: options.autoOffsetCali, extruderCaliManualMode: options.extruderCaliManualMode,
1032
+ } satisfies CallerPrintOptions, { usedNozzles: usedNozzleCount(inspection) });
991
1033
  const projectMetadata = await this.resolveProjectFileMetadata(
992
1034
  options.filePath,
993
1035
  options.plateIndex,
@@ -1160,16 +1202,21 @@ export class BambuImplementation {
1160
1202
  md5,
1161
1203
  bed_type: options.bedType || "auto",
1162
1204
  timelapse: b(options.timelapse),
1163
- bed_leveling: b(options.bedLeveling ?? true),
1164
- auto_bed_leveling: 1,
1165
- flow_cali: b(options.flowCalibration ?? false),
1166
- vibration_cali: b(options.vibrationCalibration ?? true),
1167
- layer_inspect: b(options.layerInspect ?? false),
1205
+ bed_leveling: b(studio.task_bed_leveling),
1206
+ auto_bed_leveling: studio.auto_bed_leveling,
1207
+ // No verified project_file field requests automatic flow calibration
1208
+ // (Studio's PrintParams auto_flow_cali reaches the printer through the
1209
+ // plug-in, whose MQTT form is not public), so "auto" sends 0 as before,
1210
+ // and extrude_cali_flag keeps its existing 0. The bridge and native
1211
+ // routes carry auto_flow_cali.
1212
+ flow_cali: b(studio.task_flow_cali),
1213
+ vibration_cali: b(studio.task_vibration_cali),
1214
+ layer_inspect: b(studio.task_layer_inspect),
1168
1215
  use_ams: options.useAMS !== false,
1169
1216
  cfg: "0",
1170
1217
  extrude_cali_flag: 0,
1171
- extrude_cali_manual_mode: 0,
1172
- nozzle_offset_cali: 2,
1218
+ extrude_cali_manual_mode: studio.extruder_cali_manual_mode,
1219
+ nozzle_offset_cali: studio.auto_offset_cali,
1173
1220
  subtask_name: subtaskName,
1174
1221
  profile_id: "0",
1175
1222
  project_id: submissionId,
@@ -1187,10 +1234,10 @@ export class BambuImplementation {
1187
1234
  url: projectUrl,
1188
1235
  subtask_name: subtaskName,
1189
1236
  md5,
1190
- flow_cali: options.flowCalibration ?? true,
1191
- layer_inspect: options.layerInspect ?? true,
1192
- vibration_cali: options.vibrationCalibration ?? true,
1193
- bed_leveling: options.bedLeveling ?? true,
1237
+ flow_cali: studio.task_flow_cali,
1238
+ layer_inspect: studio.task_layer_inspect,
1239
+ vibration_cali: studio.task_vibration_cali,
1240
+ bed_leveling: studio.task_bed_leveling,
1194
1241
  bed_type: options.bedType || "textured_plate",
1195
1242
  timelapse: options.timelapse ?? false,
1196
1243
  use_ams: options.useAMS !== false,
@@ -1234,9 +1281,17 @@ export class BambuImplementation {
1234
1281
 
1235
1282
  try {
1236
1283
  if (dispatch) return await dispatch();
1237
- else await invokeWithoutAck(printer!, new UpdateStateCommand({ state: "stop" }));
1284
+ // A stop with no PUBACK must not stay queued in MQTT.js and reach a later job.
1285
+ const ackMs = stopAckMs();
1286
+ const deadline = new AbortController();
1287
+ const timer = setTimeout(() => deadline.abort(Object.assign(new Error("stop not acknowledged"), { name: "TimeoutError" })), ackMs);
1288
+ try { await this.invokeEmergencyCommand(printer!, studioStopCommand, deadline.signal); }
1289
+ catch (error) {
1290
+ if ((error as Error)?.name === "TimeoutError") throw new Error(`The printer did not acknowledge the stop within ${ackMs / 1000} s; its MQTT client was closed so the stop cannot be sent late. Check the printer.`);
1291
+ throw error;
1292
+ } finally { clearTimeout(timer); }
1238
1293
  this.checkedJobs.delete(`${host}\n${serial}`);
1239
- return { status: "success", message: "Cancel command sent successfully." };
1294
+ return { status: "success", message: "Stop sent and acknowledged by the printer (MQTT QoS 1), as Bambu Studio sends it. Check get_printer_status to confirm the job stopped." };
1240
1295
  } catch (error) {
1241
1296
  throw new Error(`Failed to cancel print: ${(error as Error).message}`);
1242
1297
  }
@@ -1275,8 +1330,8 @@ export class BambuImplementation {
1275
1330
  signal?.throwIfAborted();
1276
1331
  const printer = await this.getPrinter(host, serial, token);
1277
1332
  signal?.throwIfAborted();
1278
- await this.invokeEmergencyCommand(printer, new UpdateStateCommand({ state: "stop" }), signal);
1279
- return { status: "success", message: "Cancel command sent over MQTT." };
1333
+ await this.invokeEmergencyCommand(printer, studioStopCommand, signal);
1334
+ return { status: "success", message: "Stop sent over MQTT and acknowledged by the printer (QoS 1)." };
1280
1335
  }
1281
1336
 
1282
1337
  /** Raw MQTT heater-off; switching off needs no material or model declaration. */
@@ -209,9 +209,55 @@ const PROFILE_METADATA_KEYS = new Set([
209
209
  * segfaults with no output), so name the signal or exit code and add the end
210
210
  * of stdout instead.
211
211
  */
212
- /** Where a Bambu-style CLI records its error on Linux, and when this run started. */
212
+ /** Where a Bambu-style CLI writes result.json, and when this run started. */
213
213
  type CliResultSource = { resultPath: string; startedAt: number };
214
214
 
215
+ /** Bambu Studio's or OrcaSlicer's own result.json, parsed verbatim. */
216
+ export type SlicerResult = Record<string, unknown>;
217
+
218
+ /** A sliced file, with the slicer's own result.json when it wrote one. */
219
+ export type SliceOutput = { path: string; slicer_result?: SlicerResult };
220
+
221
+ /**
222
+ * A slicer failure that keeps the slicer's own result.json. The message starts
223
+ * with the slicer's own words (`slicerText`), when it gave any, then `detail`.
224
+ */
225
+ export class SlicerRunError extends Error {
226
+ readonly slicerText: string;
227
+ constructor(detail: string, readonly slicerResult?: SlicerResult) {
228
+ const slicerText = slicerResult ? slicerResultText(slicerResult) : "";
229
+ super(slicerText ? `${slicerText}\n${detail}` : detail);
230
+ this.name = "SlicerRunError";
231
+ this.slicerText = slicerText;
232
+ }
233
+ }
234
+
235
+ /**
236
+ * The result.json this run wrote. Bambu Studio 02.08.02.61 writes it on macOS
237
+ * for successes and failures alike; an older file must not describe this run.
238
+ */
239
+ function readCliResult(cli: CliResultSource): SlicerResult | undefined {
240
+ try {
241
+ if (fs.statSync(cli.resultPath).mtimeMs < cli.startedAt) return undefined;
242
+ const result: unknown = JSON.parse(fs.readFileSync(cli.resultPath, "utf8"));
243
+ return result && typeof result === "object" && !Array.isArray(result) ? result as SlicerResult : undefined;
244
+ } catch {
245
+ return undefined;
246
+ }
247
+ }
248
+
249
+ /**
250
+ * The slicer's own words: its error_string when it reports a failing
251
+ * return_code (not "Success."), then each plate's warning_message.
252
+ */
253
+ function slicerResultText(result: SlicerResult): string {
254
+ const plates = Array.isArray(result.sliced_plates) ? result.sliced_plates : [];
255
+ return [
256
+ result.return_code === 0 ? undefined : result.error_string,
257
+ ...plates.map(plate => plate && typeof plate === "object" ? (plate as Record<string, unknown>).warning_message : undefined),
258
+ ].filter((text): text is string => typeof text === "string" && text.trim() !== "").map(text => text.trim()).join("\n");
259
+ }
260
+
215
261
  function describeSlicerFailure(
216
262
  error: { message: string; code?: unknown; signal?: unknown },
217
263
  stdout: string,
@@ -227,7 +273,7 @@ function describeSlicerFailure(
227
273
  }
228
274
 
229
275
  // Bambu Studio and OrcaSlicer CLI errors (libslic3r/Utils.hpp). The process
230
- // exits with the low byte of the code; on Linux result.json names the error.
276
+ // exits with the low byte of the code; result.json names the error.
231
277
  const BAMBU_CLI_ERRORS: Record<number, string> = {
232
278
  [-2]: "invalid parameters to the slicer",
233
279
  [-3]: "input files not found",
@@ -251,15 +297,9 @@ const BAMBU_CLI_ERRORS: Record<number, string> = {
251
297
  };
252
298
 
253
299
  function bambuCliFailureReason(exitCode: unknown, cli: CliResultSource): string | undefined {
254
- try {
255
- if (fs.statSync(cli.resultPath).mtimeMs >= cli.startedAt) {
256
- const result = JSON.parse(fs.readFileSync(cli.resultPath, "utf8"));
257
- if (typeof result.error_string === "string" && result.error_string.trim()) {
258
- return `${result.error_string.trim()} [${result.return_code}]`;
259
- }
260
- }
261
- } catch {
262
- // result.json is written only on Linux and only for handled errors.
300
+ const result = readCliResult(cli);
301
+ if (typeof result?.error_string === "string" && result.error_string.trim()) {
302
+ return `${result.error_string.trim()} [${result.return_code}]`;
263
303
  }
264
304
  if (typeof exitCode !== "number") return undefined;
265
305
  const code = Object.keys(BAMBU_CLI_ERRORS).map(Number).find(value => (value & 0xff) === exitCode);
@@ -1684,6 +1724,23 @@ export class STLManipulator extends EventEmitter {
1684
1724
  printerPreset?: string,
1685
1725
  bambuOptions?: BambuSliceOptions
1686
1726
  ): Promise<string> {
1727
+ return (await this.sliceSTLWithResult(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, bambuOptions)).path;
1728
+ }
1729
+
1730
+ /**
1731
+ * sliceSTL with the Bambu-compatible CLI's own result.json, parsed verbatim.
1732
+ * A failure throws SlicerRunError, whose message starts with the slicer's
1733
+ * error_string and plate warnings.
1734
+ */
1735
+ async sliceSTLWithResult(
1736
+ stlFilePath: string,
1737
+ slicerType: SlicerType,
1738
+ slicerPath: string,
1739
+ slicerProfile?: string,
1740
+ progressCallback?: ProgressCallback,
1741
+ printerPreset?: string,
1742
+ bambuOptions?: BambuSliceOptions
1743
+ ): Promise<SliceOutput> {
1687
1744
  const operationId = this.generateOperationId();
1688
1745
  this.activeOperations.set(operationId, true);
1689
1746
 
@@ -1920,7 +1977,8 @@ export class STLManipulator extends EventEmitter {
1920
1977
  if (error) {
1921
1978
  console.error(`Slicer Error: ${error.message}`);
1922
1979
  console.error(`Slicer Stderr: ${stderr}`);
1923
- reject(new Error(describeSlicerFailure(error, stdout, stderr, cliResult)));
1980
+ const slicerResult = cliResult ? readCliResult(cliResult) : undefined;
1981
+ reject(new SlicerRunError(describeSlicerFailure(error, stdout, stderr, cliResult), slicerResult));
1924
1982
  } else {
1925
1983
  console.error(`Slicer Stdout: ${stdout}`);
1926
1984
  if (stderr) {
@@ -1959,8 +2017,17 @@ export class STLManipulator extends EventEmitter {
1959
2017
  throw new Error("Slicing operation cancelled after process finished");
1960
2018
  }
1961
2019
 
2020
+ const slicerResult = cliResult ? readCliResult(cliResult) : undefined;
2021
+ if (cliResult && !slicerResult) {
2022
+ // Older or Linux CLIs may write result.json only for handled errors.
2023
+ console.error(`${slicerType} wrote no result.json for this slice, so its own checks are not available.`);
2024
+ }
2025
+ if (typeof slicerResult?.return_code === "number" && slicerResult.return_code !== 0) {
2026
+ throw new SlicerRunError(`Slicer failed: the slicer exited with code 0, but its result.json reports return_code ${slicerResult.return_code}.`, slicerResult);
2027
+ }
2028
+
1962
2029
  if (!fs.existsSync(outputFilePath)) {
1963
- throw new Error(`Slicer finished but output file not found: ${outputFilePath}`);
2030
+ throw new SlicerRunError(`Slicer finished but output file not found: ${outputFilePath}`, slicerResult);
1964
2031
  }
1965
2032
 
1966
2033
  if (progressCallback) progressCallback(100, "Slicing completed successfully");
@@ -1972,7 +2039,7 @@ export class STLManipulator extends EventEmitter {
1972
2039
  output: outputFilePath
1973
2040
  });
1974
2041
 
1975
- return outputFilePath;
2042
+ return slicerResult ? { path: outputFilePath, slicer_result: slicerResult } : { path: outputFilePath };
1976
2043
  } catch (error) {
1977
2044
  console.error(`Slicing failed for ${stlFilePath}:`, error);
1978
2045
  this.emit('operationError', {
@@ -2200,12 +2267,26 @@ export class STLManipulator extends EventEmitter {
2200
2267
  }
2201
2268
 
2202
2269
  /**
2203
- * Rotate the model so its largest flat face lies on the XY plane (Z=0).
2270
+ * Rotate the model so a face rests on the bed, in the pose with the least
2271
+ * part and support material per mm² of bed contact, then move it down to
2272
+ * Z=0. Returns the new file's path, or the input path when no pose qualifies.
2204
2273
  */
2205
2274
  async layFlat(
2206
2275
  stlFilePath: string,
2207
2276
  progressCallback?: ProgressCallback
2208
2277
  ): Promise<string> {
2278
+ return (await this.layFlatWithResult(stlFilePath, progressCallback)).path;
2279
+ }
2280
+
2281
+ /**
2282
+ * layFlat with its outcome. A pose qualifies only when some face, turned to
2283
+ * face down, lies on the rotated mesh's lowest plane; `laid_flat` is false
2284
+ * and the model is unchanged when none does.
2285
+ */
2286
+ async layFlatWithResult(
2287
+ stlFilePath: string,
2288
+ progressCallback?: ProgressCallback
2289
+ ): Promise<LayFlatResult> {
2209
2290
  const operationId = this.generateOperationId();
2210
2291
  this.activeOperations.set(operationId, true);
2211
2292
 
@@ -2220,100 +2301,98 @@ export class STLManipulator extends EventEmitter {
2220
2301
  const positionAttribute = geometry.getAttribute('position');
2221
2302
  if (!positionAttribute) throw new Error("Geometry has no position attribute.");
2222
2303
 
2223
- const faces: { normal: THREE.Vector3; area: number; vertices: THREE.Vector3[] }[] = [];
2304
+ const faceCount = Math.floor(positionAttribute.count / 3);
2305
+ if (faceCount === 0) throw new Error("No faces found in geometry.");
2306
+ const mesh: LayFlatMesh = {
2307
+ positions: new Float64Array(faceCount * 9),
2308
+ normals: new Float64Array(faceCount * 3),
2309
+ areas: new Float64Array(faceCount),
2310
+ volume: 0,
2311
+ };
2312
+ const center = new THREE.Vector3();
2313
+ boundingBox.getCenter(center);
2224
2314
  const vA = new THREE.Vector3();
2225
2315
  const vB = new THREE.Vector3();
2226
2316
  const vC = new THREE.Vector3();
2227
- const faceNormal = new THREE.Vector3();
2228
2317
  const cb = new THREE.Vector3(), ab = new THREE.Vector3();
2229
-
2230
- // Iterate through faces (triangles)
2231
- for (let i = 0; i < positionAttribute.count; i += 3) {
2232
- vA.fromBufferAttribute(positionAttribute, i);
2233
- vB.fromBufferAttribute(positionAttribute, i + 1);
2234
- vC.fromBufferAttribute(positionAttribute, i + 2);
2235
-
2236
- // Calculate face normal
2318
+ const fromA = new THREE.Vector3(), fromB = new THREE.Vector3(), fromC = new THREE.Vector3();
2319
+
2320
+ for (let face = 0; face < faceCount; face++) {
2321
+ vA.fromBufferAttribute(positionAttribute, face * 3);
2322
+ vB.fromBufferAttribute(positionAttribute, face * 3 + 1);
2323
+ vC.fromBufferAttribute(positionAttribute, face * 3 + 2);
2324
+ vA.toArray(mesh.positions, face * 9);
2325
+ vB.toArray(mesh.positions, face * 9 + 3);
2326
+ vC.toArray(mesh.positions, face * 9 + 6);
2327
+ // Signed tetrahedron volumes about the center sum to the enclosed volume.
2328
+ fromA.subVectors(vA, center);
2329
+ fromB.subVectors(vB, center);
2330
+ fromC.subVectors(vC, center);
2331
+ mesh.volume += fromA.dot(fromB.cross(fromC)) / 6;
2332
+
2333
+ // The cross product's direction is the outward normal; half its length is the area.
2237
2334
  cb.subVectors(vC, vB);
2238
2335
  ab.subVectors(vA, vB);
2239
2336
  cb.cross(ab);
2240
- faceNormal.copy(cb).normalize();
2241
-
2242
- // Calculate face area (using cross product magnitude / 2)
2243
- const area = cb.length() / 2;
2244
-
2245
- faces.push({
2246
- normal: faceNormal.clone(),
2247
- area: area,
2248
- vertices: [vA.clone(), vB.clone(), vC.clone()] // Store vertices if needed for center calculation
2249
- });
2337
+ mesh.areas[face] = cb.length() / 2;
2338
+ cb.normalize().toArray(mesh.normals, face * 3);
2250
2339
  }
2251
2340
 
2252
- if (faces.length === 0) throw new Error("No faces found in geometry.");
2341
+ mesh.volume = Math.abs(mesh.volume);
2253
2342
 
2254
2343
  if (!this.activeOperations.get(operationId)) throw new Error("Operation cancelled");
2255
2344
  if (progressCallback) progressCallback(65, "Grouping faces by normal...");
2256
2345
 
2257
2346
  // Group faces by similar normal vectors (tolerance for floating point errors)
2258
- const normalGroups: Map<string, { totalArea: number; representativeNormal: THREE.Vector3 }> = new Map();
2259
- const tolerance = 1e-5;
2260
-
2261
- for (const face of faces) {
2262
- let foundGroup = false;
2263
- for (const [key, group] of normalGroups.entries()) {
2264
- if (face.normal.distanceToSquared(group.representativeNormal) < tolerance) {
2265
- group.totalArea += face.area;
2266
- // Optional: Average the normal? For now, just use the first one.
2267
- foundGroup = true;
2268
- break;
2269
- }
2270
- }
2271
- if (!foundGroup) {
2272
- const key = `${face.normal.x.toFixed(5)},${face.normal.y.toFixed(5)},${face.normal.z.toFixed(5)}`;
2273
- if (!normalGroups.has(key)) { // Ensure unique key even if floats slightly differ after toFixed
2274
- normalGroups.set(key, { totalArea: face.area, representativeNormal: face.normal });
2275
- }
2276
- }
2347
+ const normalGroups: { totalArea: number; representativeNormal: THREE.Vector3 }[] = [];
2348
+ const tolerance = 1e-5;
2349
+ const faceNormal = new THREE.Vector3();
2350
+
2351
+ for (let face = 0; face < faceCount; face++) {
2352
+ if (!(mesh.areas[face] > 0)) continue;
2353
+ faceNormal.fromArray(mesh.normals, face * 3);
2354
+ const group = normalGroups.find(candidate => faceNormal.distanceToSquared(candidate.representativeNormal) < tolerance);
2355
+ if (group) group.totalArea += mesh.areas[face];
2356
+ else normalGroups.push({ totalArea: mesh.areas[face], representativeNormal: faceNormal.clone() });
2277
2357
  }
2278
-
2279
- if (normalGroups.size === 0) throw new Error("Could not group faces by normal.");
2280
2358
 
2281
2359
  if (!this.activeOperations.get(operationId)) throw new Error("Operation cancelled");
2282
- if (progressCallback) progressCallback(75, "Finding largest flat surface...");
2283
-
2284
- // Include already-horizontal faces: excluding Z-aligned normals can
2285
- // stand a flat model on its edge, including on a repeated layFlat call.
2286
- let largestArea = 0;
2287
- let targetNormal: THREE.Vector3 | null = null;
2288
- const downVector = new THREE.Vector3(0, 0, -1); // Target normal (pointing down)
2289
-
2290
- // Faces are grouped by direction, so a part whose flat faces are all
2291
- // horizontal has equal up- and down-facing areas. On a tie, keep the
2292
- // face that already points down so a seated part is not flipped.
2293
- for (const group of normalGroups.values()) {
2294
- const tied = targetNormal !== null && Math.abs(group.totalArea - largestArea) <= largestArea * 1e-6;
2295
- if (tied ? group.representativeNormal.z < targetNormal!.z : group.totalArea > largestArea) {
2296
- largestArea = group.totalArea;
2297
- targetNormal = group.representativeNormal;
2298
- }
2360
+ if (progressCallback) progressCallback(75, "Finding the pose that rests on the bed...");
2361
+
2362
+ // Candidate directions to turn down: the largest face groups, plus the
2363
+ // model's own axes so a part with a domed side can be flipped exactly.
2364
+ const candidates = normalGroups
2365
+ .sort((a, b) => b.totalArea - a.totalArea)
2366
+ .slice(0, LAY_FLAT_MAX_GROUP_CANDIDATES)
2367
+ .map(group => group.representativeNormal);
2368
+ for (const axis of [[0, 0, -1], [0, 0, 1], [1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0]]) {
2369
+ const normal = new THREE.Vector3(axis[0], axis[1], axis[2]);
2370
+ if (!candidates.some(candidate => candidate.distanceToSquared(normal) < tolerance)) candidates.push(normal);
2299
2371
  }
2300
2372
 
2301
- if (!targetNormal) {
2302
- // Only a mesh without any face area reaches this.
2303
- console.warn("Could not find a suitable large flat face to lay down. No changes made.");
2304
- this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: stlFilePath, message: "No suitable flat face found." });
2305
- return stlFilePath;
2373
+ let best: LayFlatPose | null = null;
2374
+ for (const normal of candidates) {
2375
+ const pose = evaluateLayFlatPose(mesh, normal);
2376
+ if (pose && (!best || isBetterLayFlatPose(pose, best))) best = pose;
2306
2377
  }
2307
-
2378
+
2379
+ if (!best) {
2380
+ const message = "No face lies on the model's lowest plane in any candidate orientation, so the model is unchanged.";
2381
+ console.error(`lay_flat: ${message}`);
2382
+ this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: stlFilePath, message });
2383
+ return { path: stlFilePath, laid_flat: false, message };
2384
+ }
2385
+
2308
2386
  if (progressCallback) progressCallback(80, "Calculating rotation...");
2309
-
2310
- // Calculate the rotation needed to align targetNormal with downVector
2311
- const quaternion = new THREE.Quaternion().setFromUnitVectors(targetNormal, downVector);
2312
- const rotationMatrix = new THREE.Matrix4().makeRotationFromQuaternion(quaternion);
2387
+
2388
+ // Turn the chosen normal to face straight down. Turning +Z down rotates
2389
+ // half a turn about X, which keeps the model's X layout.
2390
+ const downVector = new THREE.Vector3(0, 0, -1);
2391
+ const rotationMatrix = best.normal.dot(downVector) < -1 + 1e-9
2392
+ ? new THREE.Matrix4().makeRotationX(Math.PI)
2393
+ : new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(best.normal, downVector));
2313
2394
 
2314
2395
  // Rotate around the model's center
2315
- const center = new THREE.Vector3();
2316
- boundingBox.getCenter(center);
2317
2396
  const toOriginMatrix = new THREE.Matrix4().makeTranslation(-center.x, -center.y, -center.z);
2318
2397
  const fromOriginMatrix = new THREE.Matrix4().makeTranslation(center.x, center.y, center.z);
2319
2398
 
@@ -2336,8 +2415,9 @@ export class STLManipulator extends EventEmitter {
2336
2415
 
2337
2416
  await this.saveSTL(geometry, outputFilePath, progressCallback); // 90-100% progress
2338
2417
 
2339
- this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: outputFilePath });
2340
- return outputFilePath;
2418
+ 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.`;
2419
+ this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: outputFilePath, message });
2420
+ return { path: outputFilePath, laid_flat: true, message };
2341
2421
 
2342
2422
  } catch (error) {
2343
2423
  this.emit('operationError', { operationId, type: 'layFlat', error: error instanceof Error ? error.message : String(error) });
@@ -2347,3 +2427,75 @@ export class STLManipulator extends EventEmitter {
2347
2427
  }
2348
2428
  }
2349
2429
  }
2430
+
2431
+ export type LayFlatResult = {
2432
+ /** The laid-flat STL, or the unchanged input when `laid_flat` is false. */
2433
+ path: string;
2434
+ laid_flat: boolean;
2435
+ message: string;
2436
+ };
2437
+
2438
+ /** Face corners (9 per face), outward unit normals (3 per face), areas, and the enclosed volume. */
2439
+ type LayFlatMesh = { positions: Float64Array; normals: Float64Array; areas: Float64Array; volume: number };
2440
+
2441
+ /**
2442
+ * A direction to turn down, with the bed contact and support it gives.
2443
+ * `stackHeight` is the part and support volume over the contact area: the mean
2444
+ * height of material standing on each mm² of bed. Standing a long part on its
2445
+ * end, or resting a part on a fin under a wide cap, makes it tall.
2446
+ */
2447
+ type LayFlatPose = { normal: THREE.Vector3; contactArea: number; supportVolume: number; stackHeight: number };
2448
+
2449
+ const LAY_FLAT_MAX_GROUP_CANDIDATES = 64;
2450
+ /** Faces tilted more than 45° from vertical overhang and need support. */
2451
+ const LAY_FLAT_OVERHANG_COS = Math.SQRT1_2 + 1e-6;
2452
+
2453
+ /**
2454
+ * Score turning `normal` to face the bed. The bed is the mesh's lowest plane in
2455
+ * that pose, its support plane. Faces lying on it, within 0.5% of the model's
2456
+ * height there (at most 0.2 mm), are bed contact. Overhanging faces above it
2457
+ * need support up from the bed: their projected area times their height.
2458
+ * Returns null when no face lies on the bed: turning that normal down would
2459
+ * rest the model on an edge or a point, not a face.
2460
+ */
2461
+ function evaluateLayFlatPose(mesh: LayFlatMesh, normal: THREE.Vector3): LayFlatPose | null {
2462
+ const { positions, normals, areas } = mesh;
2463
+ const nx = normal.x, ny = normal.y, nz = normal.z;
2464
+ // Distance along the normal grows toward the bed: the bed is at its maximum.
2465
+ let bed = -Infinity, top = Infinity;
2466
+ for (let index = 0; index < positions.length; index += 3) {
2467
+ const along = positions[index] * nx + positions[index + 1] * ny + positions[index + 2] * nz;
2468
+ if (along > bed) bed = along;
2469
+ if (along < top) top = along;
2470
+ }
2471
+ const tolerance = Math.min(0.2, Math.max(0.005 * (bed - top), 1e-4));
2472
+
2473
+ let contactArea = 0;
2474
+ let supportVolume = 0;
2475
+ for (let face = 0; face < areas.length; face++) {
2476
+ const facing = normals[face * 3] * nx + normals[face * 3 + 1] * ny + normals[face * 3 + 2] * nz;
2477
+ if (!(facing > 0)) continue;
2478
+ const base = face * 9;
2479
+ let heightSum = 0, heightMax = 0;
2480
+ for (let corner = base; corner < base + 9; corner += 3) {
2481
+ const height = bed - (positions[corner] * nx + positions[corner + 1] * ny + positions[corner + 2] * nz);
2482
+ heightSum += height;
2483
+ if (height > heightMax) heightMax = height;
2484
+ }
2485
+ if (heightMax <= tolerance) contactArea += areas[face];
2486
+ else if (facing > LAY_FLAT_OVERHANG_COS) supportVolume += areas[face] * facing * (heightSum / 3);
2487
+ }
2488
+ if (!(contactArea > 0)) return null;
2489
+ return { normal, contactArea, supportVolume, stackHeight: (mesh.volume + supportVolume) / contactArea };
2490
+ }
2491
+
2492
+ /**
2493
+ * Prefer the pose with the lowest stack height, then the larger contact. On a
2494
+ * tie, keep the face that already points down so a seated part is not flipped.
2495
+ */
2496
+ function isBetterLayFlatPose(pose: LayFlatPose, best: LayFlatPose): boolean {
2497
+ const same = (a: number, b: number) => Math.abs(a - b) <= 1e-9 + 1e-6 * Math.max(Math.abs(a), Math.abs(b));
2498
+ if (!same(pose.stackHeight, best.stackHeight)) return pose.stackHeight < best.stackHeight;
2499
+ if (!same(pose.contactArea, best.contactArea)) return pose.contactArea > best.contactArea;
2500
+ return pose.normal.z < best.normal.z;
2501
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * HMS and print-error text from the user's own Bambu Studio download, for
3
+ * codes the tables bundled at the pinned Studio tag lack (it bundles no P1,
4
+ * X1 or A1 table). Bambu Studio downloads hms_en_<serial prefix>.json and
5
+ * hms_en.json into an hms folder next to BambuStudio.conf; this reads them
6
+ * read-only and returns Bambu's text unchanged, with no advice added. The
7
+ * files are Bambu's and are never copied or redistributed.
8
+ */
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import { studioConfigPath } from "./studio-print-options.js";
12
+
13
+ type Table = { hms: Map<string, string>; error: Map<string, string> };
14
+ const cache = new Map<string, { mtimeMs: number; size: number; table: Table | undefined }>();
15
+
16
+ function entries(value: unknown): Map<string, string> {
17
+ const map = new Map<string, string>();
18
+ if (!Array.isArray(value)) return map;
19
+ for (const entry of value) {
20
+ const code = typeof entry?.ecode === "string" ? entry.ecode.trim().toUpperCase() : "";
21
+ const text = typeof entry?.intro === "string" ? entry.intro.trim() : "";
22
+ if (/^[0-9A-F]{8}([0-9A-F]{8})?$/.test(code) && text) map.set(code, text);
23
+ }
24
+ return map;
25
+ }
26
+
27
+ function load(file: string): Table | undefined {
28
+ let stat: fs.Stats;
29
+ try { stat = fs.statSync(file); } catch { return undefined; }
30
+ if (!stat.isFile() || stat.size > 32 * 1024 * 1024) return undefined;
31
+ const cached = cache.get(file);
32
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached.table;
33
+ let table: Table | undefined;
34
+ try {
35
+ const data = JSON.parse(fs.readFileSync(file, "utf8"))?.data;
36
+ table = { hms: entries(data?.device_hms?.en), error: entries(data?.device_error?.en) };
37
+ } catch { table = undefined; }
38
+ cache.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, table });
39
+ return table;
40
+ }
41
+
42
+ /** Bambu Studio's downloaded text for a 16-hex HMS code or an 8-hex print_error code, by serial prefix, else from hms_en.json. */
43
+ export function studioDownloadedText(kind: "hms" | "error", code: string, serial: string): string | undefined {
44
+ const config = studioConfigPath();
45
+ if (!config) return undefined;
46
+ const directory = path.join(path.dirname(config), "hms");
47
+ const prefix = serial.trim().toUpperCase().slice(0, 3);
48
+ const files = [...(/^[0-9A-Z]{3}$/.test(prefix) ? [`hms_en_${prefix}.json`] : []), "hms_en.json"];
49
+ for (const name of files) {
50
+ const text = load(path.join(directory, name))?.[kind].get(code.toUpperCase());
51
+ if (text) return text;
52
+ }
53
+ return undefined;
54
+ }