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
@@ -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';
@@ -162,7 +163,7 @@ function configuredBambuProfileDirs(): string[] {
162
163
  // Bambu-compatible slicer CLI flags exposed via the slice_stl tool
163
164
  export interface BambuSliceOptions {
164
165
  uptodate?: boolean; // --uptodate: update 3MF configs to latest presets
165
- repetitions?: number; // --repetitions N: print N copies
166
+ repetitions?: number; // STL: --clone-objects N; 3MF: --repetitions N on the selected plate
166
167
  orient?: boolean; // --orient 1: auto-orient for printability
167
168
  arrange?: boolean; // --arrange 1: auto-arrange objects on plate
168
169
  ensureOnBed?: boolean; // --ensure-on-bed: lift floating models onto bed
@@ -184,6 +185,8 @@ export interface BambuSliceOptions {
184
185
  skipModifiedGcodes?: boolean;// --skip-modified-gcodes: ignore stale custom gcodes
185
186
  slicePlate?: number; // --slice N: which plate (default: 0 = all)
186
187
  processOverrides?: ProcessOverrides; // layer_height / wall_loops / sparse_infill_density over the resolved process preset
188
+ pauseAtLayers?: number[]; // pause before each 1-based layer (the slicer's "Add pause"); Bambu-compatible CLIs only
189
+ customGcodesFile?: string; // --load-custom-gcodes <json>: set by sliceSTLWithResult, not by callers
187
190
  }
188
191
 
189
192
  interface BambuSettingsBundle {
@@ -209,9 +212,55 @@ const PROFILE_METADATA_KEYS = new Set([
209
212
  * segfaults with no output), so name the signal or exit code and add the end
210
213
  * of stdout instead.
211
214
  */
212
- /** Where a Bambu-style CLI records its error on Linux, and when this run started. */
215
+ /** Where a Bambu-style CLI writes result.json, and when this run started. */
213
216
  type CliResultSource = { resultPath: string; startedAt: number };
214
217
 
218
+ /** Bambu Studio's or OrcaSlicer's own result.json, parsed verbatim. */
219
+ export type SlicerResult = Record<string, unknown>;
220
+
221
+ /** A sliced file, with the slicer's own result.json when it wrote one. */
222
+ export type SliceOutput = { path: string; slicer_result?: SlicerResult };
223
+
224
+ /**
225
+ * A slicer failure that keeps the slicer's own result.json. The message starts
226
+ * with the slicer's own words (`slicerText`), when it gave any, then `detail`.
227
+ */
228
+ export class SlicerRunError extends Error {
229
+ readonly slicerText: string;
230
+ constructor(detail: string, readonly slicerResult?: SlicerResult) {
231
+ const slicerText = slicerResult ? slicerResultText(slicerResult) : "";
232
+ super(slicerText ? `${slicerText}\n${detail}` : detail);
233
+ this.name = "SlicerRunError";
234
+ this.slicerText = slicerText;
235
+ }
236
+ }
237
+
238
+ /**
239
+ * The result.json this run wrote. Bambu Studio 02.08.02.61 writes it on macOS
240
+ * for successes and failures alike; an older file must not describe this run.
241
+ */
242
+ function readCliResult(cli: CliResultSource): SlicerResult | undefined {
243
+ try {
244
+ if (fs.statSync(cli.resultPath).mtimeMs < cli.startedAt) return undefined;
245
+ const result: unknown = JSON.parse(fs.readFileSync(cli.resultPath, "utf8"));
246
+ return result && typeof result === "object" && !Array.isArray(result) ? result as SlicerResult : undefined;
247
+ } catch {
248
+ return undefined;
249
+ }
250
+ }
251
+
252
+ /**
253
+ * The slicer's own words: its error_string when it reports a failing
254
+ * return_code (not "Success."), then each plate's warning_message.
255
+ */
256
+ function slicerResultText(result: SlicerResult): string {
257
+ const plates = Array.isArray(result.sliced_plates) ? result.sliced_plates : [];
258
+ return [
259
+ result.return_code === 0 ? undefined : result.error_string,
260
+ ...plates.map(plate => plate && typeof plate === "object" ? (plate as Record<string, unknown>).warning_message : undefined),
261
+ ].filter((text): text is string => typeof text === "string" && text.trim() !== "").map(text => text.trim()).join("\n");
262
+ }
263
+
215
264
  function describeSlicerFailure(
216
265
  error: { message: string; code?: unknown; signal?: unknown },
217
266
  stdout: string,
@@ -227,7 +276,7 @@ function describeSlicerFailure(
227
276
  }
228
277
 
229
278
  // 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.
279
+ // exits with the low byte of the code; result.json names the error.
231
280
  const BAMBU_CLI_ERRORS: Record<number, string> = {
232
281
  [-2]: "invalid parameters to the slicer",
233
282
  [-3]: "input files not found",
@@ -251,15 +300,9 @@ const BAMBU_CLI_ERRORS: Record<number, string> = {
251
300
  };
252
301
 
253
302
  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.
303
+ const result = readCliResult(cli);
304
+ if (typeof result?.error_string === "string" && result.error_string.trim()) {
305
+ return `${result.error_string.trim()} [${result.return_code}]`;
263
306
  }
264
307
  if (typeof exitCode !== "number") return undefined;
265
308
  const code = Object.keys(BAMBU_CLI_ERRORS).map(Number).find(value => (value & 0xff) === exitCode);
@@ -1684,6 +1727,71 @@ export class STLManipulator extends EventEmitter {
1684
1727
  printerPreset?: string,
1685
1728
  bambuOptions?: BambuSliceOptions
1686
1729
  ): Promise<string> {
1730
+ return (await this.sliceSTLWithResult(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, bambuOptions)).path;
1731
+ }
1732
+
1733
+ /**
1734
+ * sliceSTL with the Bambu-compatible CLI's own result.json, parsed verbatim.
1735
+ * A failure throws SlicerRunError, whose message starts with the slicer's
1736
+ * error_string and plate warnings.
1737
+ */
1738
+ async sliceSTLWithResult(
1739
+ stlFilePath: string,
1740
+ slicerType: SlicerType,
1741
+ slicerPath: string,
1742
+ slicerProfile?: string,
1743
+ progressCallback?: ProgressCallback,
1744
+ printerPreset?: string,
1745
+ bambuOptions?: BambuSliceOptions
1746
+ ): Promise<SliceOutput> {
1747
+ const once = (options?: BambuSliceOptions) =>
1748
+ this.sliceSTLOnce(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, options);
1749
+ const layers = bambuOptions?.pauseAtLayers?.length ? bambuOptions.pauseAtLayers : undefined;
1750
+ const cli = slicerType === 'bambustudio' || slicerType === 'orcaslicer' || slicerType === 'orcaslicer-bambulab';
1751
+ const plate = bambuOptions?.slicePlate && bambuOptions.slicePlate > 0 ? bambuOptions.slicePlate : 1;
1752
+ // The CLI drops a project's own pauses and colour changes; carry them over.
1753
+ const project = cli && /\.3mf$/i.test(stlFilePath) ? await readProjectCustomGcodes(stlFilePath, plate) : undefined;
1754
+ if (!layers && !project?.gcodes.length) return once(bambuOptions);
1755
+ if (layers && !cli) {
1756
+ throw new Error(`Pausing at a layer needs the Bambu Studio or OrcaSlicer CLI, not ${slicerType}.`);
1757
+ }
1758
+ const customGcodesFile = path.join(this.tempDir, `custom-gcodes-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);
1759
+ try {
1760
+ let tops: number[] = [];
1761
+ if (layers) {
1762
+ // A pause sits at its layer's exact top Z; learn the tops from a slice without pauses.
1763
+ if (progressCallback) progressCallback(10, `Finding layer heights for the pause before layer ${layers.join(", ")}`);
1764
+ const plain = await once({ ...bambuOptions, pauseAtLayers: undefined, customGcodesFile: undefined });
1765
+ const gcode = await readPlateGcode(plain.path, plate);
1766
+ if (!gcode) throw new Error('The slicer wrote no plate G-code, so the pause layers cannot be placed.');
1767
+ tops = layerTops(gcode);
1768
+ }
1769
+ const info = layers ? customGcodesWithPauses(tops, layers, project) : project!;
1770
+ await fs.promises.writeFile(customGcodesFile, JSON.stringify(info));
1771
+ const result = await once({ ...bambuOptions, customGcodesFile });
1772
+ if (layers) {
1773
+ const gcode = await readPlateGcode(result.path, plate);
1774
+ const placed = gcode ? pausedLayers(gcode, machinePauseGcode(gcode)) : [];
1775
+ const missing = layers.filter(layer => !placed.includes(layer));
1776
+ if (!gcode || missing.length || layerTops(gcode).length !== tops.length) {
1777
+ throw new Error(`The slicer did not place the pause before layer ${(missing.length ? missing : layers).join(", ")}. Nothing was sent to the printer.`);
1778
+ }
1779
+ }
1780
+ return result;
1781
+ } finally {
1782
+ await fs.promises.rm(customGcodesFile, { force: true });
1783
+ }
1784
+ }
1785
+
1786
+ private async sliceSTLOnce(
1787
+ stlFilePath: string,
1788
+ slicerType: SlicerType,
1789
+ slicerPath: string,
1790
+ slicerProfile?: string,
1791
+ progressCallback?: ProgressCallback,
1792
+ printerPreset?: string,
1793
+ bambuOptions?: BambuSliceOptions
1794
+ ): Promise<SliceOutput> {
1687
1795
  const operationId = this.generateOperationId();
1688
1796
  this.activeOperations.set(operationId, true);
1689
1797
 
@@ -1849,8 +1957,8 @@ export class STLManipulator extends EventEmitter {
1849
1957
  "Set arrange to false, or apply the transform in the slicer and export the project."
1850
1958
  );
1851
1959
  }
1852
- if (orcaCli && !is3mf && bambuOptions?.repetitions !== undefined && bambuOptions.cloneObjects) {
1853
- throw new Error("Use either repetitions or clone_objects for an STL with OrcaSlicer, not both.");
1960
+ if (!is3mf && bambuOptions?.repetitions !== undefined && bambuOptions.cloneObjects) {
1961
+ throw new Error("Use either repetitions or clone_objects for an STL, not both.");
1854
1962
  }
1855
1963
  const inputPath = meshTransform ? await this.transformMeshForCli(stlFilePath, bambuOptions!) : stlFilePath;
1856
1964
  if (inputPath !== stlFilePath) temporaryFiles.push(inputPath);
@@ -1882,8 +1990,9 @@ export class STLManipulator extends EventEmitter {
1882
1990
  if (bambuOptions?.orient !== undefined) args.push('--orient', bambuOptions.orient ? '1' : '0');
1883
1991
  if (bambuOptions?.arrange !== undefined) args.push('--arrange', bambuOptions.arrange ? '1' : '0');
1884
1992
  if (bambuOptions?.repetitions !== undefined) {
1885
- // OrcaSlicer counts copies of a single loaded STL with --clone-objects.
1886
- if (orcaCli && !is3mf) args.push('--clone-objects', String(bambuOptions.repetitions));
1993
+ // Both Bambu Studio and Orca count STL copies with --clone-objects.
1994
+ // --repetitions > 1 requires a selected existing plate and rejects --slice 0.
1995
+ if (!is3mf) args.push('--clone-objects', String(bambuOptions.repetitions));
1887
1996
  else args.push('--repetitions', String(bambuOptions.repetitions));
1888
1997
  }
1889
1998
  if (!meshTransform) {
@@ -1899,6 +2008,7 @@ export class STLManipulator extends EventEmitter {
1899
2008
  args.push('--load-defaultfila');
1900
2009
  }
1901
2010
  if (bambuOptions?.loadFilamentIds) args.push('--load-filament-ids', bambuOptions.loadFilamentIds);
2011
+ if (bambuOptions?.customGcodesFile) args.push('--load-custom-gcodes', path.resolve(bambuOptions.customGcodesFile));
1902
2012
 
1903
2013
  args.push(path.resolve(inputPath));
1904
2014
  // Override outputFilePath for bambustudio since it produces 3MF, not gcode
@@ -1920,7 +2030,8 @@ export class STLManipulator extends EventEmitter {
1920
2030
  if (error) {
1921
2031
  console.error(`Slicer Error: ${error.message}`);
1922
2032
  console.error(`Slicer Stderr: ${stderr}`);
1923
- reject(new Error(describeSlicerFailure(error, stdout, stderr, cliResult)));
2033
+ const slicerResult = cliResult ? readCliResult(cliResult) : undefined;
2034
+ reject(new SlicerRunError(describeSlicerFailure(error, stdout, stderr, cliResult), slicerResult));
1924
2035
  } else {
1925
2036
  console.error(`Slicer Stdout: ${stdout}`);
1926
2037
  if (stderr) {
@@ -1959,8 +2070,17 @@ export class STLManipulator extends EventEmitter {
1959
2070
  throw new Error("Slicing operation cancelled after process finished");
1960
2071
  }
1961
2072
 
2073
+ const slicerResult = cliResult ? readCliResult(cliResult) : undefined;
2074
+ if (cliResult && !slicerResult) {
2075
+ // Older or Linux CLIs may write result.json only for handled errors.
2076
+ console.error(`${slicerType} wrote no result.json for this slice, so its own checks are not available.`);
2077
+ }
2078
+ if (typeof slicerResult?.return_code === "number" && slicerResult.return_code !== 0) {
2079
+ throw new SlicerRunError(`Slicer failed: the slicer exited with code 0, but its result.json reports return_code ${slicerResult.return_code}.`, slicerResult);
2080
+ }
2081
+
1962
2082
  if (!fs.existsSync(outputFilePath)) {
1963
- throw new Error(`Slicer finished but output file not found: ${outputFilePath}`);
2083
+ throw new SlicerRunError(`Slicer finished but output file not found: ${outputFilePath}`, slicerResult);
1964
2084
  }
1965
2085
 
1966
2086
  if (progressCallback) progressCallback(100, "Slicing completed successfully");
@@ -1972,7 +2092,7 @@ export class STLManipulator extends EventEmitter {
1972
2092
  output: outputFilePath
1973
2093
  });
1974
2094
 
1975
- return outputFilePath;
2095
+ return slicerResult ? { path: outputFilePath, slicer_result: slicerResult } : { path: outputFilePath };
1976
2096
  } catch (error) {
1977
2097
  console.error(`Slicing failed for ${stlFilePath}:`, error);
1978
2098
  this.emit('operationError', {
@@ -2200,12 +2320,26 @@ export class STLManipulator extends EventEmitter {
2200
2320
  }
2201
2321
 
2202
2322
  /**
2203
- * Rotate the model so its largest flat face lies on the XY plane (Z=0).
2323
+ * Rotate the model so a face rests on the bed, in the pose with the least
2324
+ * part and support material per mm² of bed contact, then move it down to
2325
+ * Z=0. Returns the new file's path, or the input path when no pose qualifies.
2204
2326
  */
2205
2327
  async layFlat(
2206
2328
  stlFilePath: string,
2207
2329
  progressCallback?: ProgressCallback
2208
2330
  ): Promise<string> {
2331
+ return (await this.layFlatWithResult(stlFilePath, progressCallback)).path;
2332
+ }
2333
+
2334
+ /**
2335
+ * layFlat with its outcome. A pose qualifies only when some face, turned to
2336
+ * face down, lies on the rotated mesh's lowest plane; `laid_flat` is false
2337
+ * and the model is unchanged when none does.
2338
+ */
2339
+ async layFlatWithResult(
2340
+ stlFilePath: string,
2341
+ progressCallback?: ProgressCallback
2342
+ ): Promise<LayFlatResult> {
2209
2343
  const operationId = this.generateOperationId();
2210
2344
  this.activeOperations.set(operationId, true);
2211
2345
 
@@ -2220,100 +2354,98 @@ export class STLManipulator extends EventEmitter {
2220
2354
  const positionAttribute = geometry.getAttribute('position');
2221
2355
  if (!positionAttribute) throw new Error("Geometry has no position attribute.");
2222
2356
 
2223
- const faces: { normal: THREE.Vector3; area: number; vertices: THREE.Vector3[] }[] = [];
2357
+ const faceCount = Math.floor(positionAttribute.count / 3);
2358
+ if (faceCount === 0) throw new Error("No faces found in geometry.");
2359
+ const mesh: LayFlatMesh = {
2360
+ positions: new Float64Array(faceCount * 9),
2361
+ normals: new Float64Array(faceCount * 3),
2362
+ areas: new Float64Array(faceCount),
2363
+ volume: 0,
2364
+ };
2365
+ const center = new THREE.Vector3();
2366
+ boundingBox.getCenter(center);
2224
2367
  const vA = new THREE.Vector3();
2225
2368
  const vB = new THREE.Vector3();
2226
2369
  const vC = new THREE.Vector3();
2227
- const faceNormal = new THREE.Vector3();
2228
2370
  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
2371
+ const fromA = new THREE.Vector3(), fromB = new THREE.Vector3(), fromC = new THREE.Vector3();
2372
+
2373
+ for (let face = 0; face < faceCount; face++) {
2374
+ vA.fromBufferAttribute(positionAttribute, face * 3);
2375
+ vB.fromBufferAttribute(positionAttribute, face * 3 + 1);
2376
+ vC.fromBufferAttribute(positionAttribute, face * 3 + 2);
2377
+ vA.toArray(mesh.positions, face * 9);
2378
+ vB.toArray(mesh.positions, face * 9 + 3);
2379
+ vC.toArray(mesh.positions, face * 9 + 6);
2380
+ // Signed tetrahedron volumes about the center sum to the enclosed volume.
2381
+ fromA.subVectors(vA, center);
2382
+ fromB.subVectors(vB, center);
2383
+ fromC.subVectors(vC, center);
2384
+ mesh.volume += fromA.dot(fromB.cross(fromC)) / 6;
2385
+
2386
+ // The cross product's direction is the outward normal; half its length is the area.
2237
2387
  cb.subVectors(vC, vB);
2238
2388
  ab.subVectors(vA, vB);
2239
2389
  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
- });
2390
+ mesh.areas[face] = cb.length() / 2;
2391
+ cb.normalize().toArray(mesh.normals, face * 3);
2250
2392
  }
2251
2393
 
2252
- if (faces.length === 0) throw new Error("No faces found in geometry.");
2394
+ mesh.volume = Math.abs(mesh.volume);
2253
2395
 
2254
2396
  if (!this.activeOperations.get(operationId)) throw new Error("Operation cancelled");
2255
2397
  if (progressCallback) progressCallback(65, "Grouping faces by normal...");
2256
2398
 
2257
2399
  // 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
- }
2400
+ const normalGroups: { totalArea: number; representativeNormal: THREE.Vector3 }[] = [];
2401
+ const tolerance = 1e-5;
2402
+ const faceNormal = new THREE.Vector3();
2403
+
2404
+ for (let face = 0; face < faceCount; face++) {
2405
+ if (!(mesh.areas[face] > 0)) continue;
2406
+ faceNormal.fromArray(mesh.normals, face * 3);
2407
+ const group = normalGroups.find(candidate => faceNormal.distanceToSquared(candidate.representativeNormal) < tolerance);
2408
+ if (group) group.totalArea += mesh.areas[face];
2409
+ else normalGroups.push({ totalArea: mesh.areas[face], representativeNormal: faceNormal.clone() });
2277
2410
  }
2278
-
2279
- if (normalGroups.size === 0) throw new Error("Could not group faces by normal.");
2280
2411
 
2281
2412
  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
- }
2413
+ if (progressCallback) progressCallback(75, "Finding the pose that rests on the bed...");
2414
+
2415
+ // Candidate directions to turn down: the largest face groups, plus the
2416
+ // model's own axes so a part with a domed side can be flipped exactly.
2417
+ const candidates = normalGroups
2418
+ .sort((a, b) => b.totalArea - a.totalArea)
2419
+ .slice(0, LAY_FLAT_MAX_GROUP_CANDIDATES)
2420
+ .map(group => group.representativeNormal);
2421
+ for (const axis of [[0, 0, -1], [0, 0, 1], [1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0]]) {
2422
+ const normal = new THREE.Vector3(axis[0], axis[1], axis[2]);
2423
+ if (!candidates.some(candidate => candidate.distanceToSquared(normal) < tolerance)) candidates.push(normal);
2299
2424
  }
2300
2425
 
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;
2426
+ let best: LayFlatPose | null = null;
2427
+ for (const normal of candidates) {
2428
+ const pose = evaluateLayFlatPose(mesh, normal);
2429
+ if (pose && (!best || isBetterLayFlatPose(pose, best))) best = pose;
2306
2430
  }
2307
-
2431
+
2432
+ if (!best) {
2433
+ const message = "No face lies on the model's lowest plane in any candidate orientation, so the model is unchanged.";
2434
+ console.error(`lay_flat: ${message}`);
2435
+ this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: stlFilePath, message });
2436
+ return { path: stlFilePath, laid_flat: false, message };
2437
+ }
2438
+
2308
2439
  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);
2440
+
2441
+ // Turn the chosen normal to face straight down. Turning +Z down rotates
2442
+ // half a turn about X, which keeps the model's X layout.
2443
+ const downVector = new THREE.Vector3(0, 0, -1);
2444
+ const rotationMatrix = best.normal.dot(downVector) < -1 + 1e-9
2445
+ ? new THREE.Matrix4().makeRotationX(Math.PI)
2446
+ : new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(best.normal, downVector));
2313
2447
 
2314
2448
  // Rotate around the model's center
2315
- const center = new THREE.Vector3();
2316
- boundingBox.getCenter(center);
2317
2449
  const toOriginMatrix = new THREE.Matrix4().makeTranslation(-center.x, -center.y, -center.z);
2318
2450
  const fromOriginMatrix = new THREE.Matrix4().makeTranslation(center.x, center.y, center.z);
2319
2451
 
@@ -2336,8 +2468,9 @@ export class STLManipulator extends EventEmitter {
2336
2468
 
2337
2469
  await this.saveSTL(geometry, outputFilePath, progressCallback); // 90-100% progress
2338
2470
 
2339
- this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: outputFilePath });
2340
- return outputFilePath;
2471
+ 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.`;
2472
+ this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: outputFilePath, message });
2473
+ return { path: outputFilePath, laid_flat: true, message };
2341
2474
 
2342
2475
  } catch (error) {
2343
2476
  this.emit('operationError', { operationId, type: 'layFlat', error: error instanceof Error ? error.message : String(error) });
@@ -2347,3 +2480,75 @@ export class STLManipulator extends EventEmitter {
2347
2480
  }
2348
2481
  }
2349
2482
  }
2483
+
2484
+ export type LayFlatResult = {
2485
+ /** The laid-flat STL, or the unchanged input when `laid_flat` is false. */
2486
+ path: string;
2487
+ laid_flat: boolean;
2488
+ message: string;
2489
+ };
2490
+
2491
+ /** Face corners (9 per face), outward unit normals (3 per face), areas, and the enclosed volume. */
2492
+ type LayFlatMesh = { positions: Float64Array; normals: Float64Array; areas: Float64Array; volume: number };
2493
+
2494
+ /**
2495
+ * A direction to turn down, with the bed contact and support it gives.
2496
+ * `stackHeight` is the part and support volume over the contact area: the mean
2497
+ * height of material standing on each mm² of bed. Standing a long part on its
2498
+ * end, or resting a part on a fin under a wide cap, makes it tall.
2499
+ */
2500
+ type LayFlatPose = { normal: THREE.Vector3; contactArea: number; supportVolume: number; stackHeight: number };
2501
+
2502
+ const LAY_FLAT_MAX_GROUP_CANDIDATES = 64;
2503
+ /** Faces tilted more than 45° from vertical overhang and need support. */
2504
+ const LAY_FLAT_OVERHANG_COS = Math.SQRT1_2 + 1e-6;
2505
+
2506
+ /**
2507
+ * Score turning `normal` to face the bed. The bed is the mesh's lowest plane in
2508
+ * that pose, its support plane. Faces lying on it, within 0.5% of the model's
2509
+ * height there (at most 0.2 mm), are bed contact. Overhanging faces above it
2510
+ * need support up from the bed: their projected area times their height.
2511
+ * Returns null when no face lies on the bed: turning that normal down would
2512
+ * rest the model on an edge or a point, not a face.
2513
+ */
2514
+ function evaluateLayFlatPose(mesh: LayFlatMesh, normal: THREE.Vector3): LayFlatPose | null {
2515
+ const { positions, normals, areas } = mesh;
2516
+ const nx = normal.x, ny = normal.y, nz = normal.z;
2517
+ // Distance along the normal grows toward the bed: the bed is at its maximum.
2518
+ let bed = -Infinity, top = Infinity;
2519
+ for (let index = 0; index < positions.length; index += 3) {
2520
+ const along = positions[index] * nx + positions[index + 1] * ny + positions[index + 2] * nz;
2521
+ if (along > bed) bed = along;
2522
+ if (along < top) top = along;
2523
+ }
2524
+ const tolerance = Math.min(0.2, Math.max(0.005 * (bed - top), 1e-4));
2525
+
2526
+ let contactArea = 0;
2527
+ let supportVolume = 0;
2528
+ for (let face = 0; face < areas.length; face++) {
2529
+ const facing = normals[face * 3] * nx + normals[face * 3 + 1] * ny + normals[face * 3 + 2] * nz;
2530
+ if (!(facing > 0)) continue;
2531
+ const base = face * 9;
2532
+ let heightSum = 0, heightMax = 0;
2533
+ for (let corner = base; corner < base + 9; corner += 3) {
2534
+ const height = bed - (positions[corner] * nx + positions[corner + 1] * ny + positions[corner + 2] * nz);
2535
+ heightSum += height;
2536
+ if (height > heightMax) heightMax = height;
2537
+ }
2538
+ if (heightMax <= tolerance) contactArea += areas[face];
2539
+ else if (facing > LAY_FLAT_OVERHANG_COS) supportVolume += areas[face] * facing * (heightSum / 3);
2540
+ }
2541
+ if (!(contactArea > 0)) return null;
2542
+ return { normal, contactArea, supportVolume, stackHeight: (mesh.volume + supportVolume) / contactArea };
2543
+ }
2544
+
2545
+ /**
2546
+ * Prefer the pose with the lowest stack height, then the larger contact. On a
2547
+ * tie, keep the face that already points down so a seated part is not flipped.
2548
+ */
2549
+ function isBetterLayFlatPose(pose: LayFlatPose, best: LayFlatPose): boolean {
2550
+ const same = (a: number, b: number) => Math.abs(a - b) <= 1e-9 + 1e-6 * Math.max(Math.abs(a), Math.abs(b));
2551
+ if (!same(pose.stackHeight, best.stackHeight)) return pose.stackHeight < best.stackHeight;
2552
+ if (!same(pose.contactArea, best.contactArea)) return pose.contactArea > best.contactArea;
2553
+ return pose.normal.z < best.normal.z;
2554
+ }