any2orca 0.5.0 → 0.7.0

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.
@@ -22,7 +22,8 @@ import { parseItemPositions } from "../../archive/parseItemPositions.js";
22
22
  import { MODEL_SETTINGS_PATH, PROJECT_SETTINGS_PATH, TOP_MODEL_PATH } from "../../archive/paths.js";
23
23
  import { xmlBlocks } from "../../archive/xmlBlocks.js";
24
24
  import { convertObjectOverrides, convertPrusaSettings } from "./convertSettings.js";
25
- import { parsePrusaIni } from "./ini.js";
25
+ import { parsePrusaIni, splitStringList } from "./ini.js";
26
+ import { bedIndexOf, parseBedShape } from "./beds.js";
26
27
  import { parsePrusaModelConfig } from "./modelConfig.js";
27
28
  import { splitMultiPartObjects } from "./splitParts.js";
28
29
  const utf8Decoder = new TextDecoder("utf-8");
@@ -100,43 +101,55 @@ export function adaptPrusaModel(text) {
100
101
  export function convertCustomGcodes(prusaXml) {
101
102
  if (!/<custom_gcodes_per_print_z[\s>]/.test(prusaXml))
102
103
  return null;
103
- const layers = [];
104
+ // PrusaSlicer 2.9 writes one block per bed, side by side, each with its bed_idx; older files have one block.
105
+ const plates = [];
104
106
  let colorChanges = 0;
105
- for (const m of prusaXml.matchAll(/<code\s+([^>]*?)\/>/g)) {
106
- if (layers.length >= MAX_CUSTOM_GCODES)
107
- break;
108
- const attrs = m[1];
109
- const attr = (name) => {
110
- const found = new RegExp(`\\b${name}="([^"]*)"`).exec(attrs);
111
- return found ? decodeXml(found[1]) : null;
112
- };
113
- const printZ = attr("print_z");
114
- if (printZ === null || !/^\d+(\.\d+)?$/.test(printZ))
115
- continue;
116
- const sourceType = attr("type") ?? "";
117
- if (!/^[0-4]$/.test(sourceType))
118
- continue;
119
- const extruder = attr("extruder") ?? "1";
120
- if (!/^\d{1,3}$/.test(extruder))
121
- continue;
122
- const color = (attr("color") ?? "").slice(0, 32);
123
- let extra = (attr("extra") ?? "").slice(0, 4000);
124
- // 0 is a color change: a pause (1) in Snapmaker Orca, where the U1 pauses with M600 for the swap.
125
- let type = sourceType;
126
- if (sourceType === "0") {
127
- type = "1";
128
- extra = color ? `Color change to ${color}` : "Color change";
129
- colorChanges++;
107
+ let total = 0;
108
+ // One pass over the blocks (xmlBlocks): a lazy pattern would rescan the file for every opener without a closer.
109
+ for (const block of xmlBlocks(prusaXml, "custom_gcodes_per_print_z")) {
110
+ const bedIndex = Number(/\bbed_idx="(\d{1,2})"/.exec(block.attrs)?.[1] ?? "0");
111
+ const body = block.body;
112
+ const layers = [];
113
+ for (const m of body.matchAll(/<code\s+([^>]*?)\/>/g)) {
114
+ if (total >= MAX_CUSTOM_GCODES)
115
+ break;
116
+ total++;
117
+ const attrs = m[1];
118
+ const attr = (name) => {
119
+ const found = new RegExp(`\\b${name}="([^"]*)"`).exec(attrs);
120
+ return found ? decodeXml(found[1]) : null;
121
+ };
122
+ const printZ = attr("print_z");
123
+ if (printZ === null || !/^\d+(\.\d+)?$/.test(printZ))
124
+ continue;
125
+ const sourceType = attr("type") ?? "";
126
+ if (!/^[0-4]$/.test(sourceType))
127
+ continue;
128
+ const extruder = attr("extruder") ?? "1";
129
+ if (!/^\d{1,3}$/.test(extruder))
130
+ continue;
131
+ const color = (attr("color") ?? "").slice(0, 32);
132
+ let extra = (attr("extra") ?? "").slice(0, 4000);
133
+ // 0 is a color change: a pause (1) in Snapmaker Orca, where the U1 pauses with M600 for the swap.
134
+ let type = sourceType;
135
+ if (sourceType === "0") {
136
+ type = "1";
137
+ extra = color ? `Color change to ${color}` : "Color change";
138
+ colorChanges++;
139
+ }
140
+ // 4 is custom G-code, the only kind whose text is the creator's own.
141
+ const gcode = type === "4" ? (attr("gcode") ?? extra).slice(0, 4000) : type === "2" ? "tool_change" : "";
142
+ layers.push(`<layer top_z="${printZ}" type="${type}" extruder="${extruder}" color="${xmlAttr(color)}" extra="${xmlAttr(extra)}" gcode="${xmlAttr(gcode)}"/>`);
130
143
  }
131
- // 4 is custom G-code, the only kind whose text is the creator's own.
132
- const gcode = type === "4" ? (attr("gcode") ?? extra).slice(0, 4000) : type === "2" ? "tool_change" : "";
133
- layers.push(`<layer top_z="${printZ}" type="${type}" extruder="${extruder}" color="${xmlAttr(color)}" extra="${xmlAttr(extra)}" gcode="${xmlAttr(gcode)}"/>`);
144
+ if (layers.length === 0)
145
+ continue;
146
+ const mode = /<mode\s+value="(SingleExtruder|MultiAsSingle|MultiExtruder)"/.exec(body)?.[1] ?? "SingleExtruder";
147
+ plates.push(["<plate>", `<plate_info id="${bedIndex + 1}"/>`, ...layers, `<mode value="${mode}"/>`, "</plate>"].join("\n"));
134
148
  }
135
- if (layers.length === 0)
149
+ if (plates.length === 0)
136
150
  return null;
137
- const mode = /<mode\s+value="(SingleExtruder|MultiAsSingle|MultiExtruder)"/.exec(prusaXml)?.[1] ?? "SingleExtruder";
138
151
  return {
139
- xml: ['<?xml version="1.0" encoding="utf-8"?>', "<custom_gcodes_per_layer>", "<plate>", '<plate_info id="1"/>', ...layers, `<mode value="${mode}"/>`, "</plate>", "</custom_gcodes_per_layer>", ""].join("\n"),
152
+ xml: ['<?xml version="1.0" encoding="utf-8"?>', "<custom_gcodes_per_layer>", ...plates, "</custom_gcodes_per_layer>", ""].join("\n"),
140
153
  colorChanges,
141
154
  };
142
155
  }
@@ -174,6 +187,10 @@ export function componentIds(topModelText) {
174
187
  }
175
188
  return out;
176
189
  }
190
+ const compareVersions = (a, b) => {
191
+ const [x, y] = [a.split(".").map(Number), b.split(".").map(Number)];
192
+ return x[0] - y[0] || x[1] - y[1] || x[2] - y[2];
193
+ };
177
194
  /** The filament an object prints with: its own, else its only part's; 0 is the default (filament 1). */
178
195
  function objectFilament(object) {
179
196
  if (object.extruder > 0)
@@ -210,9 +227,10 @@ export function partsOf(object, components, split, depth = 0) {
210
227
  * Bambu's `model_settings.config`: each object with its name, filament and settings, its parts, and one plate holding
211
228
  * every instance.
212
229
  */
213
- export function buildModelSettings(ini, objects, instanceCounts, parts) {
230
+ export function buildModelSettings(ini, objects, instanceCounts, parts, plateOf = () => 1) {
214
231
  const lines = ['<?xml version="1.0" encoding="UTF-8"?>', "<config>"];
215
- const instances = [];
232
+ /** Each plate's `<model_instance>` blocks, by plate number. */
233
+ const plates = new Map();
216
234
  for (const object of objects) {
217
235
  const filament = objectFilament(object);
218
236
  const name = object.name || `Object ${object.id}`;
@@ -233,11 +251,18 @@ export function buildModelSettings(ini, objects, instanceCounts, parts) {
233
251
  }
234
252
  lines.push(" </object>");
235
253
  const count = instanceCounts.get(object.id) ?? 1;
254
+ const instances = plates.get(plateOf(object.id)) ?? [];
236
255
  for (let i = 0; i < count; i++) {
237
256
  instances.push(" <model_instance>", ` <metadata key="object_id" value="${object.id}"/>`, ` <metadata key="instance_id" value="${i}"/>`, ` <metadata key="identify_id" value="${object.id * 100 + i}"/>`, " </model_instance>");
238
257
  }
258
+ plates.set(plateOf(object.id), instances);
259
+ }
260
+ // Plates in order, every number up to the highest used, so a plate's number is its position (as the Bambu family's are).
261
+ const highest = Math.max(1, ...plates.keys());
262
+ for (let plate = 1; plate <= highest; plate++) {
263
+ lines.push(" <plate>", ` <metadata key="plater_id" value="${plate}"/>`, ' <metadata key="plater_name" value=""/>', ' <metadata key="locked" value="false"/>', ...(plates.get(plate) ?? []), " </plate>");
239
264
  }
240
- lines.push(" <plate>", ' <metadata key="plater_id" value="1"/>', ' <metadata key="plater_name" value=""/>', ' <metadata key="locked" value="false"/>', ...instances, " </plate>", "</config>", "");
265
+ lines.push("</config>", "");
241
266
  return lines.join("\n");
242
267
  }
243
268
  export const prusaReader = {
@@ -291,11 +316,30 @@ export const prusaReader = {
291
316
  // A wrapper object (an older PrusaSlicer's extra instance) has no config entry of its own: the mesh object's serves.
292
317
  const configFor = (id) => byId.get(id) ?? components.get(id)?.map((c) => byId.get(c)).find((o) => o !== undefined);
293
318
  const partFileCache = new Map();
319
+ // PrusaSlicer 2.9 can place objects on several beds, virtual copies of the printer's bed on a grid; each becomes a
320
+ // plate. An older project has one bed. An object on no bed (off every one) stays on plate 1, with a warning.
321
+ const version = ini.version ? (/^\d+\.\d+\.\d+/.exec(ini.version)?.[0] ?? null) : null;
322
+ const severalBeds = version !== null && compareVersions(version, "2.9.0") >= 0;
323
+ const bed = severalBeds ? parseBedShape(ini.settings.get("bed_shape")) : null;
324
+ const plateOf = new Map();
294
325
  const objects = Object.entries(itemPositions).map(([id, fallbackXy]) => {
295
326
  const bbox = objectWorldBboxXY(id, modelText, partFileCache, zipEntries);
296
327
  const name = configFor(Number(id))?.name;
297
- return { id, ...(name ? { name } : {}), plate: 1, ...(bbox ? { bbox } : { bbox: null, fallbackXy }) };
328
+ let plate = 1;
329
+ if (bed) {
330
+ const box = bbox ?? [fallbackXy[0], fallbackXy[0], fallbackXy[1], fallbackXy[1]];
331
+ const index = bedIndexOf(box, bed);
332
+ if (index === null)
333
+ warnings.push(` WARN: "${name ?? id}" sits on none of PrusaSlicer's beds (off every bed); it's put on plate 1.`);
334
+ else
335
+ plate = index + 1;
336
+ }
337
+ plateOf.set(Number(id), plate);
338
+ return { id, ...(name ? { name } : {}), plate, ...(bbox ? { bbox } : { bbox: null, fallbackXy }) };
298
339
  });
340
+ const plateCount = new Set(plateOf.values()).size;
341
+ if (plateCount > 1)
342
+ warnings.push(` note: the project's ${plateCount} beds become ${plateCount} plates.`);
299
343
  // Objects the model file places, in its order; the per-object config may name objects that aren't placed.
300
344
  const placed = objects.map((o) => {
301
345
  const config = configFor(Number(o.id));
@@ -309,7 +353,7 @@ export const prusaReader = {
309
353
  }
310
354
  const model = adaptPrusaModel(modelText);
311
355
  entries[TOP_MODEL_PATH] = model.text === topModelText ? topModelBytes : utf8Encoder.encode(model.text);
312
- entries[MODEL_SETTINGS_PATH] = utf8Encoder.encode(buildModelSettings(ini, placed, instanceCounts, (object) => partsOf(object, components, split.parts)));
356
+ entries[MODEL_SETTINGS_PATH] = utf8Encoder.encode(buildModelSettings(ini, placed, instanceCounts, (object) => partsOf(object, components, split.parts), (id) => plateOf.get(id) ?? 1));
313
357
  const customGcodeBytes = zipEntries[PRUSA_CUSTOM_GCODE_PATH];
314
358
  if (customGcodeBytes && customGcodeBytes.length <= MAX_AUX_BYTES) {
315
359
  const orca = convertCustomGcodes(utf8Decoder.decode(customGcodeBytes));
@@ -329,8 +373,20 @@ export const prusaReader = {
329
373
  if (zipEntries[PRUSA_LAYER_RANGES_PATH]) {
330
374
  warnings.push(" WARN: this project's layer-range settings (settings for a range of heights of an object) aren't carried yet.");
331
375
  }
376
+ const printerNotes = ini.settings.get("printer_notes") ?? "";
332
377
  return {
333
378
  source: "prusaslicer",
379
+ prusa: {
380
+ version,
381
+ settings: ini.settings,
382
+ targets: converted.targets,
383
+ presets: {
384
+ print: ini.settings.get("print_settings_id") ?? "",
385
+ printer: ini.settings.get("printer_settings_id") ?? "",
386
+ filaments: splitStringList(ini.raw.get("filament_settings_id") ?? ""),
387
+ },
388
+ vendorKeyword: /\bPRINTER_VENDOR_([A-Z0-9]{1,20})\b/.exec(printerNotes)?.[1] ?? null,
389
+ },
334
390
  zipEntries: entries,
335
391
  request: { projectSettings: converted.settings, objects },
336
392
  warnings,
@@ -12,9 +12,30 @@
12
12
  import type { ConvertRequest } from "../schema.js";
13
13
  /** The slicer family a project came from. */
14
14
  export type SourceFormat = "bambu-family" | "prusaslicer";
15
+ /**
16
+ * What a PrusaSlicer project keeps for the step that needs profile data
17
+ * (`convert()`, once the catalog is loaded): the project's settings in
18
+ * PrusaSlicer's own keys and value forms, which Snapmaker Orca keys each
19
+ * wrote, and the preset names it recorded.
20
+ */
21
+ export interface PrusaProjectInfo {
22
+ /** The PrusaSlicer version that saved the project ("2.9.6"), from the settings file's first line; null when unreadable. */
23
+ version: string | null;
24
+ settings: ReadonlyMap<string, string>;
25
+ targets: ReadonlyMap<string, readonly string[]>;
26
+ presets: {
27
+ print: string;
28
+ printer: string;
29
+ filaments: readonly string[];
30
+ };
31
+ /** The vendor keyword from `printer_notes` ("PRUSA3D"), when the printer profile names one. */
32
+ vendorKeyword: string | null;
33
+ }
15
34
  export interface ParsedProject {
16
35
  /** Which reader read the file. */
17
36
  source: SourceFormat;
37
+ /** Present for a PrusaSlicer project. */
38
+ prusa?: PrusaProjectInfo;
18
39
  /** The full decompressed source zip, kept for applyConvertResponse's final reassembly. */
19
40
  zipEntries: Record<string, Uint8Array>;
20
41
  /** The conversion request payload. */
package/dist/stamp.d.ts CHANGED
@@ -24,8 +24,8 @@ export declare const OutputStampSchema: z.ZodObject<{
24
24
  profileId: z.ZodString;
25
25
  source: z.ZodOptional<z.ZodObject<{
26
26
  format: z.ZodEnum<{
27
- "bambu-family": "bambu-family";
28
27
  prusaslicer: "prusaslicer";
28
+ "bambu-family": "bambu-family";
29
29
  }>;
30
30
  slicerVersion: z.ZodOptional<z.ZodString>;
31
31
  }, z.core.$strict>>;
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.5.0";
1
+ export declare const VERSION = "0.7.0";
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  // Written by scripts/sync-version.mjs from package.json; a test checks they match.
3
- export const VERSION = "0.5.0";
3
+ export const VERSION = "0.7.0";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "any2orca",
3
- "version": "0.5.0",
4
- "outputAffecting": "the stamp in every converted file now records the source format and slicer version",
3
+ "version": "0.7.0",
4
+ "outputAffecting": "a PrusaSlicer conversion carries only the print settings the creator changed; converted PrusaSlicer files change, Bambu-family files don't",
5
5
  "description": "Convert Bambu Studio, Creality Print, Anycubic Slicer Next, ElegooSlicer and Flash Studio 3MF projects for the Snapmaker U1 (Snapmaker Orca), entirely on your own machine. Library, CLI and Web Worker in one package.",
6
6
  "keywords": [
7
7
  "3mf",
@@ -65,7 +65,7 @@
65
65
  "docs": "typedoc"
66
66
  },
67
67
  "dependencies": {
68
- "any2orca-profiles": "0.2.0",
68
+ "any2orca-profiles": "0.3.0",
69
69
  "fflate": "0.8.3",
70
70
  "zod": "4.6.7"
71
71
  },