any2orca 0.12.1 → 0.14.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +7 -2
  3. package/dist/archive/meshPaint.d.ts +25 -0
  4. package/dist/archive/meshPaint.js +136 -0
  5. package/dist/archive/objectWorldBboxXY.d.ts +19 -1
  6. package/dist/archive/objectWorldBboxXY.js +32 -8
  7. package/dist/archive/paintColor.d.ts +21 -0
  8. package/dist/archive/paintColor.js +88 -0
  9. package/dist/archive/plateFilaments.d.ts +65 -0
  10. package/dist/archive/plateFilaments.js +363 -0
  11. package/dist/cli/commands/convert.d.ts +10 -0
  12. package/dist/cli/commands/convert.js +83 -19
  13. package/dist/cli/commands/inspect.d.ts +17 -0
  14. package/dist/cli/commands/inspect.js +75 -0
  15. package/dist/cli/main.js +43 -1
  16. package/dist/cli/surface.d.ts +29 -0
  17. package/dist/cli/surface.js +6 -0
  18. package/dist/engine/carrySourceLayerHeight.js +2 -2
  19. package/dist/engine/runConvertPipeline.d.ts +9 -2
  20. package/dist/engine/runConvertPipeline.js +24 -6
  21. package/dist/explain/filamentNotes.d.ts +17 -1
  22. package/dist/explain/filamentNotes.js +28 -12
  23. package/dist/explain/notes.d.ts +40 -0
  24. package/dist/explain/notes.js +74 -0
  25. package/dist/explain/plateNotes.d.ts +32 -0
  26. package/dist/explain/plateNotes.js +89 -0
  27. package/dist/index.d.ts +8 -1
  28. package/dist/index.js +4 -1
  29. package/dist/inspect.d.ts +9 -1
  30. package/dist/inspect.js +2 -1
  31. package/dist/problemReport.d.ts +68 -0
  32. package/dist/problemReport.js +312 -0
  33. package/dist/profiles.d.ts +12 -0
  34. package/dist/profiles.js +18 -1
  35. package/dist/project.d.ts +31 -8
  36. package/dist/project.js +91 -48
  37. package/dist/sources/bambuFamily.js +6 -1
  38. package/dist/sources/prusa/prusa.js +6 -1
  39. package/dist/sources/reader.d.ts +6 -0
  40. package/dist/version.js +1 -1
  41. package/package.json +2 -2
@@ -0,0 +1,363 @@
1
+ // SPDX-License-Identifier: MIT
2
+ /**
3
+ * Which filaments each plate of a project uses, how, and between which heights.
4
+ *
5
+ * It follows the slicer's own rule for the filaments a print uses (Snapmaker Orca's `Print::object_extruders` and
6
+ * `support_material_extruders`, and the condition under which `ToolOrdering` applies layer tool changes): each part's
7
+ * filament, or its object's when the part sets none; the filaments painted on it; a filament set for a range of
8
+ * heights; the support and raft filaments where an object has supports; and a tool change at a layer, on a plate
9
+ * that otherwise prints with one filament.
10
+ *
11
+ * The heights are read from the model, not from a slice, so "the most filaments at the same height" is an estimate:
12
+ * a filament counts for the whole span between the lowest and the highest point it is used at.
13
+ *
14
+ * Everything read here comes from the file, which is untrusted: numbers are range-checked, lists are capped, and a
15
+ * file that names more than the caps allow is read up to them.
16
+ */
17
+ import { MODEL_SETTINGS_PATH, TOP_MODEL_PATH } from "./paths.js";
18
+ import { hasPaintAttribute, scanMeshPaint } from "./meshPaint.js";
19
+ import { xmlBlocks, xmlTags } from "./xmlBlocks.js";
20
+ /** How a plate uses a filament, in the order `uses` lists them. */
21
+ export const FILAMENT_USES = ["object", "part", "paint", "height-range", "support", "layer-change"];
22
+ const utf8Decoder = new TextDecoder("utf-8");
23
+ const LAYER_RANGES_PATH = "Metadata/layer_config_ranges.xml";
24
+ const CUSTOM_GCODE_PATH = "Metadata/custom_gcode_per_layer.xml";
25
+ /** Small settings files; a larger one isn't read. */
26
+ const MAX_AUX_BYTES = 16 * 1024 * 1024;
27
+ /** Far past any real project; bounds the lists a crafted file can make this read. */
28
+ const MAX_BLOCKS = 20_000;
29
+ const MAX_RANGES = 10_000;
30
+ const MAX_TOOL_CHANGES = 10_000;
31
+ /** A height in mm that a printer could have; anything else in the file isn't a height. */
32
+ const MAX_HEIGHT = 100_000;
33
+ /** The parts of a model that print with a filament: a negative part cuts, and a blocker or enforcer only steers supports. */
34
+ const PRINTING_SUBTYPES = new Set(["normal_part", "modifier_part"]);
35
+ /** The `key="..." value="..."` pairs of the `<metadata>` tags in `text`. */
36
+ function metadataValues(text) {
37
+ const values = new Map();
38
+ for (const { attrs } of xmlTags(text, "metadata")) {
39
+ const key = /(?:^|\s)key="([^"]{1,80})"/.exec(attrs)?.[1];
40
+ const value = /(?:^|\s)value="([^"]{0,200})"/.exec(attrs)?.[1];
41
+ if (key !== undefined && value !== undefined && !values.has(key))
42
+ values.set(key, value);
43
+ }
44
+ return values;
45
+ }
46
+ /** Each wanted object's own settings and its parts', from `model_settings.config`. */
47
+ function readObjectSettings(modelSettings, wanted) {
48
+ const byId = new Map();
49
+ let seen = 0;
50
+ for (const { attrs, body } of xmlBlocks(modelSettings, "object")) {
51
+ if (++seen > MAX_BLOCKS)
52
+ break;
53
+ const id = /(?:^|\s)id="(\d{1,9})"/.exec(attrs)?.[1];
54
+ if (id === undefined || !wanted.has(id) || byId.has(id))
55
+ continue;
56
+ const parts = [];
57
+ // The object's own settings are the metadata outside its parts.
58
+ const outside = [];
59
+ let copiedTo = 0;
60
+ for (const part of xmlBlocks(body, "part")) {
61
+ if (parts.length >= MAX_BLOCKS)
62
+ break;
63
+ outside.push(body.slice(copiedTo, part.bodyStart));
64
+ copiedTo = part.bodyEnd;
65
+ const partId = /(?:^|\s)id="(\d{1,9})"/.exec(part.attrs)?.[1];
66
+ if (partId === undefined)
67
+ continue;
68
+ parts.push({ id: partId, subtype: /(?:^|\s)subtype="([a-z_]{1,40})"/.exec(part.attrs)?.[1] ?? "normal_part", values: metadataValues(part.body) });
69
+ }
70
+ outside.push(body.slice(copiedTo));
71
+ byId.set(id, { values: metadataValues(outside.join("")), parts });
72
+ }
73
+ return byId;
74
+ }
75
+ /**
76
+ * The project's objects in the order the model builds them (its `<item>` list): the order the height ranges file
77
+ * numbers them in, from 1, as the slicer does when it loads one.
78
+ */
79
+ function buildOrder(topModel) {
80
+ const order = [];
81
+ const seen = new Set();
82
+ for (const { attrs } of xmlTags(topModel, "item")) {
83
+ const id = /(?:^|\s)objectid="(\d{1,9})"/.exec(attrs)?.[1];
84
+ if (id === undefined || seen.has(id))
85
+ continue;
86
+ seen.add(id);
87
+ order.push(id);
88
+ if (order.length >= MAX_BLOCKS)
89
+ break;
90
+ }
91
+ return order;
92
+ }
93
+ /** A filament number from a setting: a whole number from 0 (none set) up; anything else is 0. */
94
+ function filamentNumber(value) {
95
+ const text = Array.isArray(value) ? value[0] : value;
96
+ const n = typeof text === "number" ? text : typeof text === "string" && /^\d{1,6}$/.test(text.trim()) ? Number(text.trim()) : 0;
97
+ return Number.isInteger(n) && n > 0 ? n : 0;
98
+ }
99
+ function isOn(value) {
100
+ const text = typeof value === "string" ? value.trim().toLowerCase() : value;
101
+ return text === "1" || text === "true" || text === 1 || text === true;
102
+ }
103
+ function positiveNumber(value) {
104
+ const n = typeof value === "number" ? value : typeof value === "string" ? Number(value.trim()) : NaN;
105
+ return Number.isFinite(n) && n > 0 ? n : 0;
106
+ }
107
+ function height(value) {
108
+ // The slicer writes a height with all the digits a float has ("29.399999618530273").
109
+ if (value === undefined || !/^-?\d{1,7}(\.\d{1,25})?(e-?\d{1,3})?$/i.test(value.trim()))
110
+ return null;
111
+ const n = Number(value);
112
+ return Number.isFinite(n) && Math.abs(n) <= MAX_HEIGHT ? n : null;
113
+ }
114
+ /** Filament ranges set for a span of an object's height, by the object's position in the project (from 1). */
115
+ function readHeightRanges(xml) {
116
+ const ranges = new Map();
117
+ let count = 0;
118
+ for (const object of xmlBlocks(xml, "object")) {
119
+ const index = Number(/(?:^|\s)id="(\d{1,9})"/.exec(object.attrs)?.[1] ?? NaN);
120
+ if (!Number.isInteger(index))
121
+ continue;
122
+ for (const range of xmlBlocks(object.body, "range")) {
123
+ if (++count > MAX_RANGES)
124
+ return ranges;
125
+ const from = height(/(?:^|\s)min_z="([^"]{1,40})"/.exec(range.attrs)?.[1]);
126
+ const to = height(/(?:^|\s)max_z="([^"]{1,40})"/.exec(range.attrs)?.[1]);
127
+ if (from === null || to === null || to < from)
128
+ continue;
129
+ for (const option of xmlBlocks(range.body, "option")) {
130
+ if (!/(?:^|\s)opt_key="extruder"/.test(option.attrs))
131
+ continue;
132
+ const filament = filamentNumber(option.body);
133
+ if (filament > 0)
134
+ ranges.set(index, [...(ranges.get(index) ?? []), { filament, from, to }]);
135
+ }
136
+ }
137
+ }
138
+ return ranges;
139
+ }
140
+ /** Each plate's tool changes at a layer, lowest first, where the plate's changes are in the mode that applies them. */
141
+ function readToolChanges(xml) {
142
+ const byPlate = new Map();
143
+ let count = 0;
144
+ for (const plate of xmlBlocks(xml, "plate")) {
145
+ const id = Number(/<plate_info\s[^>]*?id="(\d{1,6})"/.exec(plate.body)?.[1] ?? NaN);
146
+ if (!Number.isInteger(id) || id < 1)
147
+ continue;
148
+ // The slicer applies them only in this mode (a plate that prints with one filament on a printer with several).
149
+ if (/<mode\s[^>]*?value="([^"]{1,40})"/.exec(plate.body)?.[1] !== "MultiAsSingle")
150
+ continue;
151
+ const changes = [];
152
+ for (const { attrs } of xmlTags(plate.body, "layer")) {
153
+ if (++count > MAX_TOOL_CHANGES)
154
+ break;
155
+ // Type 2 is a tool change; 0 is a color change by hand and 1 a pause, neither of which is a filament slot.
156
+ if (/(?:^|\s)type="([^"]{1,10})"/.exec(attrs)?.[1] !== "2")
157
+ continue;
158
+ const z = height(/(?:^|\s)top_z="([^"]{1,40})"/.exec(attrs)?.[1]);
159
+ const filament = filamentNumber(/(?:^|\s)extruder="([^"]{1,10})"/.exec(attrs)?.[1]);
160
+ if (z !== null && z >= 0 && filament > 0)
161
+ changes.push({ filament, z });
162
+ }
163
+ if (changes.length > 0)
164
+ byPlate.set(id, changes.sort((a, b) => a.z - b.z));
165
+ }
166
+ return byPlate;
167
+ }
168
+ /** How many filaments a project's settings have. */
169
+ export function filamentCountOf(projectSettings) {
170
+ const colors = projectSettings.filament_colour;
171
+ const names = projectSettings.filament_settings_id;
172
+ return Math.max(1, Array.isArray(colors) ? colors.length : 0, Array.isArray(names) ? names.length : 0);
173
+ }
174
+ /**
175
+ * The paint of every part whose model file has any: one pass over each such file. A painted filament number above
176
+ * `filamentCount` counts as no paint, as the slicer treats it.
177
+ */
178
+ export function readPartPaint(zipEntries, objects, partPlacements, filamentCount) {
179
+ const paintOf = new Map();
180
+ const requestsByFile = new Map();
181
+ const paintedFile = new Map();
182
+ for (const object of objects) {
183
+ for (const part of partPlacements?.get(object.id) ?? []) {
184
+ const file = part.path ?? TOP_MODEL_PATH;
185
+ const bytes = zipEntries[file];
186
+ if (!bytes)
187
+ continue;
188
+ if (!paintedFile.has(file))
189
+ paintedFile.set(file, hasPaintAttribute(bytes));
190
+ if (!paintedFile.get(file))
191
+ continue;
192
+ const result = { painted: new Map(), unpainted: false, triangles: 0 };
193
+ paintOf.set(part, result);
194
+ const { R, T } = part;
195
+ // The z row of `v * R + T` (transform.ts).
196
+ const request = { zOf: (x, y, z) => R[0][2] * x + R[1][2] * y + R[2][2] * z + T[2], result };
197
+ const byMesh = requestsByFile.get(file) ?? new Map();
198
+ byMesh.set(part.id, [...(byMesh.get(part.id) ?? []), request]);
199
+ requestsByFile.set(file, byMesh);
200
+ }
201
+ }
202
+ for (const [file, byMesh] of requestsByFile)
203
+ scanMeshPaint(zipEntries[file], byMesh, filamentCount);
204
+ return paintOf;
205
+ }
206
+ /**
207
+ * The most ranges that share a layer, with layers `layerHeight` thick from the plate up. A range counts for every
208
+ * layer it reaches into, so two that meet inside a layer share that layer, and two that meet exactly between layers
209
+ * (one part on top of another) don't; a range with no thickness, a painted top face, say, counts for the layer under it.
210
+ */
211
+ function mostAtOnce(ranges, layerHeight) {
212
+ /** A height in layers, snapped to a whole number when it is one but for rounding. */
213
+ const layers = (mm) => {
214
+ const q = mm / layerHeight;
215
+ return Math.abs(q - Math.round(q)) < 1e-6 ? Math.round(q) : q;
216
+ };
217
+ const events = [];
218
+ for (const { from, to } of ranges) {
219
+ let first = Math.floor(layers(from));
220
+ const end = Math.max(1, Math.ceil(layers(to)));
221
+ if (first >= end)
222
+ first = end - 1;
223
+ events.push([first, 1], [end, -1]);
224
+ }
225
+ // At the same layer an end comes before a start.
226
+ events.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
227
+ let open = 0;
228
+ let most = 0;
229
+ for (const [, change] of events) {
230
+ open += change;
231
+ if (open > most)
232
+ most = open;
233
+ }
234
+ return most;
235
+ }
236
+ const round = (mm) => Math.round(mm * 1000) / 1000;
237
+ /** Every plate's filaments; see the module comment for what counts and how the heights are read. */
238
+ export function readPlateFilaments(input) {
239
+ const { zipEntries, projectSettings, objects, paint: paintOf } = input;
240
+ const filamentCount = filamentCountOf(projectSettings);
241
+ /** The slicer prints a filament number the project doesn't have with filament 1. */
242
+ const existing = (filament) => (filament > filamentCount ? 1 : filament);
243
+ const layerHeight = positiveNumber(projectSettings.layer_height) || 0.2;
244
+ const modelSettingsBytes = zipEntries[MODEL_SETTINGS_PATH];
245
+ const modelSettings = modelSettingsBytes ? utf8Decoder.decode(modelSettingsBytes) : "";
246
+ const settingsById = readObjectSettings(modelSettings, new Set(objects.map((o) => o.id)));
247
+ const rangesBytes = zipEntries[LAYER_RANGES_PATH];
248
+ const heightRanges = rangesBytes && rangesBytes.length <= MAX_AUX_BYTES ? readHeightRanges(utf8Decoder.decode(rangesBytes)) : new Map();
249
+ // Read only for a project that has such ranges: the main model file can be large.
250
+ const topModelBytes = heightRanges.size > 0 ? zipEntries[TOP_MODEL_PATH] : undefined;
251
+ const order = topModelBytes ? buildOrder(utf8Decoder.decode(topModelBytes)) : [];
252
+ const customGcodeBytes = zipEntries[CUSTOM_GCODE_PATH];
253
+ const toolChanges = customGcodeBytes && customGcodeBytes.length <= MAX_AUX_BYTES ? readToolChanges(utf8Decoder.decode(customGcodeBytes)) : new Map();
254
+ const usesByPlate = new Map();
255
+ const topByPlate = new Map();
256
+ /** The filaments a plate's objects print with, supports aside: what decides whether its tool changes apply. */
257
+ const objectFilamentsByPlate = new Map();
258
+ for (const object of objects) {
259
+ const plate = object.plate ?? 1;
260
+ const uses = usesByPlate.get(plate) ?? [];
261
+ usesByPlate.set(plate, uses);
262
+ const objectFilaments = objectFilamentsByPlate.get(plate) ?? new Set();
263
+ objectFilamentsByPlate.set(plate, objectFilaments);
264
+ const add = (slot, use, from, to) => {
265
+ // A height that isn't known (no mesh found) counts from the plate up to where the object is known to end.
266
+ const low = Number.isFinite(from) ? Math.max(0, from) : 0;
267
+ const high = Number.isFinite(to) ? Math.max(low, to) : low;
268
+ uses.push({ slot, use, from: low, to: high });
269
+ if (use !== "support")
270
+ objectFilaments.add(slot);
271
+ };
272
+ const settings = settingsById.get(object.id);
273
+ const placements = input.partPlacements?.get(object.id) ?? [];
274
+ const objectFilament = filamentNumber(settings?.values.get("extruder"));
275
+ let objectTop = 0;
276
+ for (const p of placements)
277
+ if (Number.isFinite(p.zMax) && p.zMax > objectTop)
278
+ objectTop = p.zMax;
279
+ const setting = (key) => settings?.values.get(key) ?? projectSettings[key];
280
+ // Paint reaches all the way into a part unless a depth is set; with one, the inside prints with the part's own filament.
281
+ const paintDepthSet = positiveNumber(setting("mmu_segmented_region_max_width")) > 0;
282
+ // Parts: the settings file's list, or, for a part it doesn't name, the model's own.
283
+ const partSettings = new Map((settings?.parts ?? []).map((p) => [p.id, p]));
284
+ const placementById = new Map();
285
+ for (const p of placements)
286
+ if (!placementById.has(p.id))
287
+ placementById.set(p.id, p);
288
+ const partIds = settings && settings.parts.length > 0 ? settings.parts.map((p) => p.id) : placements.map((p) => p.id);
289
+ if (partIds.length === 0)
290
+ add(existing(objectFilament || 1), "object", 0, 0);
291
+ for (const partId of partIds) {
292
+ const part = partSettings.get(partId);
293
+ if (part && !PRINTING_SUBTYPES.has(part.subtype))
294
+ continue;
295
+ const placement = placementById.get(partId) ?? (placements.length === 1 && partIds.length === 1 ? placements[0] : undefined);
296
+ const from = placement ? placement.zMin : NaN;
297
+ const to = placement ? placement.zMax : objectTop;
298
+ const own = filamentNumber(part?.values.get("extruder"));
299
+ const paint = placement ? paintOf.get(placement) : undefined;
300
+ const found = paint !== undefined && paint.triangles > 0;
301
+ // A part painted all over prints none of its own filament.
302
+ if (!found || paint.unpainted || paintDepthSet)
303
+ add(existing(own || objectFilament || 1), own > 0 ? "part" : "object", from, to);
304
+ if (found && part?.subtype !== "modifier_part") {
305
+ for (const [filament, [zMin, zMax]] of paint.painted)
306
+ add(filament, "paint", Number.isNaN(zMin) ? from : zMin, Number.isNaN(zMax) ? to : zMax);
307
+ }
308
+ }
309
+ if (objectTop > (topByPlate.get(plate) ?? 0))
310
+ topByPlate.set(plate, objectTop);
311
+ // A filament set for a range of the object's height: the ranges file numbers objects in the order the model builds them.
312
+ const position = order.indexOf(object.id) + 1;
313
+ for (const range of position > 0 ? (heightRanges.get(position) ?? []) : [])
314
+ add(existing(range.filament), "height-range", range.from, Math.min(range.to, objectTop || range.to));
315
+ // Supports and raft, where the object has them; filament 0 is "whichever is printing", which adds none.
316
+ if (isOn(setting("enable_support")) || positiveNumber(setting("enforce_support_layers")) > 0 || positiveNumber(setting("raft_layers")) > 0) {
317
+ for (const key of ["support_filament", "support_interface_filament"]) {
318
+ const filament = filamentNumber(setting(key));
319
+ if (filament > 0)
320
+ add(existing(filament), "support", 0, objectTop);
321
+ }
322
+ }
323
+ }
324
+ // Tool changes at a layer, on a plate whose objects print with one filament of a project that has several.
325
+ for (const [plate, changes] of toolChanges) {
326
+ const uses = usesByPlate.get(plate);
327
+ const objectFilaments = objectFilamentsByPlate.get(plate);
328
+ if (!uses || !objectFilaments || objectFilaments.size !== 1 || filamentCount < 2)
329
+ continue;
330
+ const top = topByPlate.get(plate) ?? 0;
331
+ const first = changes[0].z;
332
+ // The plate's own filament prints up to the first change.
333
+ for (const use of uses)
334
+ if (use.use !== "support" && use.to > first)
335
+ use.to = Math.max(use.from, first);
336
+ changes.forEach((change, i) => {
337
+ const next = changes[i + 1]?.z ?? Math.max(top, change.z);
338
+ // The change takes effect with the layer that ends at its height.
339
+ uses.push({ slot: existing(change.filament), use: "layer-change", from: Math.max(0, change.z - layerHeight), to: Math.max(change.z, next) });
340
+ });
341
+ }
342
+ const plateCount = Math.min(MAX_BLOCKS, Math.max(1, input.plateCount, ...usesByPlate.keys()));
343
+ const plates = [];
344
+ for (let plate = 1; plate <= plateCount; plate++) {
345
+ const bySlot = new Map();
346
+ for (const use of usesByPlate.get(plate) ?? []) {
347
+ const known = bySlot.get(use.slot);
348
+ if (known) {
349
+ known.uses.add(use.use);
350
+ known.from = Math.min(known.from, use.from);
351
+ known.to = Math.max(known.to, use.to);
352
+ }
353
+ else {
354
+ bySlot.set(use.slot, { uses: new Set([use.use]), from: use.from, to: use.to });
355
+ }
356
+ }
357
+ const filaments = [...bySlot.entries()]
358
+ .sort((a, b) => a[0] - b[0])
359
+ .map(([slot, { uses, from, to }]) => ({ slot, uses: FILAMENT_USES.filter((u) => uses.has(u)), from: round(from), to: round(to) }));
360
+ plates.push({ plate, filaments, mostAtOnce: mostAtOnce(filaments, layerHeight) });
361
+ }
362
+ return plates;
363
+ }
@@ -1,4 +1,5 @@
1
1
  import type { MatchSource } from "../../schema.js";
2
+ import { type ConvertReport } from "../../project.js";
2
3
  import type { ProfileCatalog } from "../../profiles.js";
3
4
  import type { Preset } from "../../presets/preset.js";
4
5
  import type { AboveStockChoice } from "../../engine/aboveStock.js";
@@ -25,6 +26,8 @@ export interface ConvertOptions {
25
26
  explain?: boolean;
26
27
  /** --explain-json: also write it, with every settings difference, as <output>.what-changed.json. */
27
28
  explainJson?: boolean;
29
+ /** --report: after each file, print a problem report to copy into a bug report (no file name, object names or paths). */
30
+ report?: boolean;
28
31
  outDir?: string;
29
32
  archiveDir?: string;
30
33
  suffix: string;
@@ -36,6 +39,11 @@ export interface ConvertOptions {
36
39
  logger: Logger;
37
40
  stats?: StatsReporter;
38
41
  }
42
+ /** The lines around a problem report, so the whole of it is easy to find and copy. */
43
+ export declare const REPORT_START = "----- any2orca problem report: copy from the next line -----";
44
+ export declare const REPORT_END = "----- end of the report -----";
45
+ /** Where a problem report goes: the project's bug report form. */
46
+ export declare const BUG_REPORT_URL = "https://github.com/KuzuriAo/any2orca/issues/new?template=bug_report.yml";
39
47
  export interface ConvertRunSummary {
40
48
  converted: number;
41
49
  failed: number;
@@ -58,6 +66,8 @@ export declare function shouldSkipExisting(outPath: string, skipExisting: boolea
58
66
  * gets nothing here.
59
67
  */
60
68
  export declare function matchWarningLine(matchSource: MatchSource, profileIdLabel: string): string | null;
69
+ /** One line per plate that has objects: the filaments it uses, and how many it needs at the same height when that is fewer. */
70
+ export declare function plateFilamentLines(report: Pick<ConvertReport, "plateFilaments">): string[];
61
71
  /**
62
72
  * Whether retrying this exact file could give a different result. A
63
73
  * conversion is deterministic, so a problem with the file itself is
@@ -2,12 +2,17 @@
2
2
  import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { basename, dirname, extname, join, resolve } from "node:path";
4
4
  import { Any2orcaError } from "../../errors.js";
5
- import { filamentNotes } from "../../explain/filamentNotes.js";
6
5
  import { formatWhatChanged } from "../../explain/whatChanged.js";
7
6
  import { openProject, unwrapBundle } from "../../project.js";
7
+ import { problemReport } from "../../problemReport.js";
8
8
  import { archiveOriginal } from "../archiveMove.js";
9
9
  import { describeFsError, isSamePath } from "../sameFile.js";
10
10
  import { computeFingerprint, loadStateFile, saveStateFile } from "../watchState.js";
11
+ /** The lines around a problem report, so the whole of it is easy to find and copy. */
12
+ export const REPORT_START = "----- any2orca problem report: copy from the next line -----";
13
+ export const REPORT_END = "----- end of the report -----";
14
+ /** Where a problem report goes: the project's bug report form. */
15
+ export const BUG_REPORT_URL = "https://github.com/KuzuriAo/any2orca/issues/new?template=bug_report.yml";
11
16
  /** An error as the CLI prints it. A project over the size limit gets the CLI's own way to raise it, not the library's. */
12
17
  function errorText(err) {
13
18
  if (err instanceof Any2orcaError && err.code === "too_large") {
@@ -52,6 +57,16 @@ export function matchWarningLine(matchSource, profileIdLabel) {
52
57
  }
53
58
  return null;
54
59
  }
60
+ /** One line per plate that has objects: the filaments it uses, and how many it needs at the same height when that is fewer. */
61
+ export function plateFilamentLines(report) {
62
+ return (report.plateFilaments ?? [])
63
+ .filter((p) => p.filaments.length > 0)
64
+ .map((p) => {
65
+ const slots = p.filaments.map((f) => f.slot);
66
+ const atOnce = p.mostAtOnce < slots.length ? `, ${p.mostAtOnce} at the same height` : "";
67
+ return `plate ${p.plate}: filament${slots.length === 1 ? "" : "s"} ${slots.join(", ")}${atOnce}`;
68
+ });
69
+ }
55
70
  function logReport(report, verbose, logger) {
56
71
  if (report.profileMatch) {
57
72
  const line = matchWarningLine(report.profileMatch.matchSource, report.profile.id);
@@ -70,17 +85,17 @@ function logReport(report, verbose, logger) {
70
85
  for (const c of report.preset.changes)
71
86
  logger.log(` preset: ${c.key} ${c.stock} -> ${c.yours}${c.aboveStock ? " (above stock)" : ""}`);
72
87
  }
73
- // The same sentences the web app shows (filamentNotes).
74
- for (const note of filamentNotes(report))
75
- logger.log(` note: ${note}`);
76
- for (const w of report.warnings)
77
- logger.log(` warning: ${w}`);
88
+ // The same sentences the web app shows, in the same order, each with its topic.
89
+ for (const note of report.notes)
90
+ logger.log(` note [${note.topic}]: ${note.text}`);
78
91
  if (report.retiredProfile)
79
92
  logger.log(' note: run "any2orca profiles" for the current list.');
80
93
  if (verbose) {
81
94
  for (const f of report.filaments) {
82
95
  logger.log(` filament ${f.slot}: ${f.color} ${f.type} ${f.outputName || "(no preset name)"}${f.outputName !== f.sourceName ? ` (was ${f.sourceName || "unnamed"})` : ""}`);
83
96
  }
97
+ for (const line of plateFilamentLines(report))
98
+ logger.log(` ${line}`);
84
99
  for (const line of report.log)
85
100
  logger.log(` log: ${line}`);
86
101
  }
@@ -115,7 +130,46 @@ async function convertOne(entryName, bytes, defaultDir, originalInputPath, optio
115
130
  logger.log(`${options.dryRun ? "[dry-run] " : ""}${entryName}: skipped (already exists at ${outPath})`);
116
131
  return;
117
132
  }
118
- const project = openProject(bytes, { maxUnpackedBytes: options.maxUnpackedBytes });
133
+ // --report: what was converted and what came of it, printed between two lines so it is easy to copy whole.
134
+ let inspection;
135
+ let stage = "opening";
136
+ const printReport = (outcome) => {
137
+ if (!options.report)
138
+ return;
139
+ const text = problemReport({
140
+ app: "any2orca command line",
141
+ ...(inspection ? { inspection } : {}),
142
+ ...outcome,
143
+ ...(outcome.error !== undefined ? { stage } : {}),
144
+ catalog: options.catalog,
145
+ options: {
146
+ nozzle: options.nozzle,
147
+ snapmakerOrcaVersion: options.catalog.index.slicer.version,
148
+ ...(options.profile ? { profileId: options.profile } : {}),
149
+ ...(options.filamentCompliance ? { filamentComplianceMode: options.filamentCompliance } : {}),
150
+ ...(options.highFlow ? { highFlowHotends: options.highFlow } : {}),
151
+ hardenedNozzles: options.hardenedNozzle === true,
152
+ stamp: !options.noStamp,
153
+ preset: options.preset !== undefined,
154
+ ...(options.aboveStock ? { aboveStock: { keep: options.aboveStock.keep ?? [], stock: options.aboveStock.stock ?? [] } } : {}),
155
+ },
156
+ });
157
+ logger.log(REPORT_START);
158
+ for (const line of text.split("\n"))
159
+ logger.log(line);
160
+ logger.log(REPORT_END);
161
+ logger.log(`Paste it into a bug report: ${BUG_REPORT_URL}`);
162
+ };
163
+ let project;
164
+ try {
165
+ project = openProject(bytes, { maxUnpackedBytes: options.maxUnpackedBytes });
166
+ if (options.report && !options.dryRun)
167
+ inspection = project.inspect();
168
+ }
169
+ catch (err) {
170
+ printReport({ error: err });
171
+ throw err;
172
+ }
119
173
  if (options.dryRun) {
120
174
  logger.log(`[dry-run] ${entryName}`);
121
175
  if (options.preset) {
@@ -136,18 +190,27 @@ async function convertOne(entryName, bytes, defaultDir, originalInputPath, optio
136
190
  written.set(outPath, originalInputPath);
137
191
  return;
138
192
  }
139
- const { output, report } = await project.convert({
140
- profiles: options.catalog,
141
- nozzle: options.nozzle,
142
- ...(options.profile ? { profileId: options.profile } : {}),
143
- ...(options.preset ? { preset: options.preset } : {}),
144
- ...(options.aboveStock ? { aboveStock: options.aboveStock } : {}),
145
- ...(options.filamentCompliance ? { filamentComplianceMode: options.filamentCompliance } : {}),
146
- ...(options.highFlow ? { highFlowHotends: options.highFlow } : {}),
147
- ...(options.hardenedNozzle ? { hardenedNozzles: true } : {}),
148
- ...(options.noStamp ? { stamp: false } : {}),
149
- ...(options.explainJson ? { explain: true } : {}),
150
- });
193
+ let converted;
194
+ try {
195
+ converted = await project.convert({
196
+ profiles: options.catalog,
197
+ nozzle: options.nozzle,
198
+ ...(options.profile ? { profileId: options.profile } : {}),
199
+ ...(options.preset ? { preset: options.preset } : {}),
200
+ ...(options.aboveStock ? { aboveStock: options.aboveStock } : {}),
201
+ ...(options.filamentCompliance ? { filamentComplianceMode: options.filamentCompliance } : {}),
202
+ ...(options.highFlow ? { highFlowHotends: options.highFlow } : {}),
203
+ ...(options.hardenedNozzle ? { hardenedNozzles: true } : {}),
204
+ ...(options.noStamp ? { stamp: false } : {}),
205
+ ...(options.explainJson ? { explain: true } : {}),
206
+ ...(options.report ? { onProgress: (reached) => void (stage = reached) } : {}),
207
+ });
208
+ }
209
+ catch (err) {
210
+ printReport({ error: err });
211
+ throw err;
212
+ }
213
+ const { output, report } = converted;
151
214
  // The result line comes first, so in a batch each file's notes sit under its own name.
152
215
  const replaced = existsSync(outPath);
153
216
  writeFileSync(outPath, output);
@@ -162,6 +225,7 @@ async function convertOne(entryName, bytes, defaultDir, originalInputPath, optio
162
225
  writeFileSync(jsonPath, `${JSON.stringify(report.whatChanged, null, 2)}\n`);
163
226
  logger.log(` what changed: ${jsonPath}`);
164
227
  }
228
+ printReport({ report });
165
229
  await options.stats?.afterConversion(report, project.inspect());
166
230
  }
167
231
  /** State tracking is on for repeated or resumable runs (--watch, --archive-dir, --skip-existing), never for --dry-run. */
@@ -0,0 +1,17 @@
1
+ import type { Inspection } from "../../inspect.js";
2
+ export interface InspectCommandOptions {
3
+ file: string;
4
+ /** --json: the whole reading as JSON instead of text. */
5
+ json: boolean;
6
+ /** --max-unpacked: the most the project may unpack to, in bytes (default 2 GB). */
7
+ maxUnpackedBytes?: number;
8
+ }
9
+ /** The name and version of `--json`'s output; the version goes up only when a field's meaning changes or one goes away. */
10
+ export declare const INSPECT_JSON_FORMAT: {
11
+ readonly format: "any2orca-inspect";
12
+ readonly version: 1;
13
+ };
14
+ /** The reading as the lines `inspect` prints. */
15
+ export declare function inspectionLines(name: string, inspection: Inspection): string[];
16
+ /** Reads the project and prints what it holds. Throws for a file that can't be read; the caller reports it. */
17
+ export declare function runInspect(options: InspectCommandOptions, out: (line: string) => void): number;
@@ -0,0 +1,75 @@
1
+ // SPDX-License-Identifier: MIT
2
+ /**
3
+ * `any2orca inspect <file>`: what a project holds, read the way a conversion reads it, without converting:
4
+ * the slicer and printer it was saved for, its filaments, and each plate's objects and the filaments it uses.
5
+ */
6
+ import { readFileSync } from "node:fs";
7
+ import { basename } from "node:path";
8
+ import { formatSize } from "../../archive/safeUnzip.js";
9
+ import { cleanWarnings, inspect } from "../../project.js";
10
+ import { formatTable } from "../table.js";
11
+ /** The name and version of `--json`'s output; the version goes up only when a field's meaning changes or one goes away. */
12
+ export const INSPECT_JSON_FORMAT = { format: "any2orca-inspect", version: 1 };
13
+ const USES = {
14
+ object: "objects",
15
+ part: "parts",
16
+ paint: "paint",
17
+ "height-range": "a height range",
18
+ support: "supports",
19
+ "layer-change": "a tool change at a layer",
20
+ };
21
+ /** The reading as the lines `inspect` prints. */
22
+ export function inspectionLines(name, inspection) {
23
+ const lines = [name];
24
+ const facts = [];
25
+ const fact = (label, value) => {
26
+ if (value)
27
+ facts.push([` ${label}`, value]);
28
+ };
29
+ fact("Printer", inspection.printerModel ? `${inspection.printerModel}${inspection.sourceVendor !== "other" ? ` (${inspection.sourceVendor})` : ""}` : null);
30
+ fact("Slicer version", inspection.slicerVersion);
31
+ fact("Process preset", inspection.sourcePresetName);
32
+ const sizes = inspection.nozzleDiameters ?? [];
33
+ fact("Nozzle", sizes.length > 0 ? `${sizes.join(", ")} mm` : inspection.nozzleDiameter ? `${inspection.nozzleDiameter} mm` : null);
34
+ fact("Layer height", inspection.layerHeight !== null ? `${inspection.layerHeight} mm` : null);
35
+ fact("Size", `${formatSize(inspection.unpackedBytes)} unpacked`);
36
+ const plateCount = inspection.plateCount ?? inspection.plates.length;
37
+ fact("Plates", `${plateCount}${inspection.plates.length < plateCount ? ` (${inspection.plates.length} with objects)` : ""}`);
38
+ fact("Objects", String(inspection.objects.length));
39
+ lines.push(formatTable(facts));
40
+ lines.push("", ` Filaments (${inspection.filaments.length})`);
41
+ if (inspection.filaments.length > 0) {
42
+ lines.push(formatTable(inspection.filaments.map((f) => [` ${f.slot}`, f.color, f.type, f.presetName || "(no preset name)", f.colorName ? `${f.colorName.name}` : ""])).replace(/[ \t]+$/gm, ""));
43
+ }
44
+ const plates = (inspection.plateFilaments ?? []).filter((p) => p.filaments.length > 0);
45
+ if (plates.length > 0) {
46
+ lines.push("", " Plates");
47
+ for (const plate of plates) {
48
+ const objects = inspection.objects.filter((o) => (o.plate ?? 1) === plate.plate).length;
49
+ const slots = plate.filaments.map((f) => f.slot);
50
+ const atOnce = plate.mostAtOnce < slots.length ? `, ${plate.mostAtOnce} at the same height` : "";
51
+ lines.push(` Plate ${plate.plate}: ${objects} object${objects === 1 ? "" : "s"}, filament${slots.length === 1 ? "" : "s"} ${slots.join(", ")}${atOnce}`);
52
+ for (const use of plate.filaments) {
53
+ lines.push(` ${use.slot}: ${use.uses.map((u) => USES[u] ?? u).join(", ")}, ${use.from} to ${use.to} mm`);
54
+ }
55
+ }
56
+ }
57
+ const notes = cleanWarnings(inspection.warnings);
58
+ if (notes.length > 0) {
59
+ lines.push("", " Notes");
60
+ for (const note of notes)
61
+ lines.push(` ${note}`);
62
+ }
63
+ return lines;
64
+ }
65
+ /** Reads the project and prints what it holds. Throws for a file that can't be read; the caller reports it. */
66
+ export function runInspect(options, out) {
67
+ const inspection = inspect(new Uint8Array(readFileSync(options.file)), { maxUnpackedBytes: options.maxUnpackedBytes });
68
+ const name = basename(options.file);
69
+ if (options.json)
70
+ out(JSON.stringify({ ...INSPECT_JSON_FORMAT, file: name, inspection }, null, 2));
71
+ else
72
+ for (const line of inspectionLines(name, inspection))
73
+ out(line);
74
+ return 0;
75
+ }