threemf_tools.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  1. """3MF file parsing utilities for filament tracking.
  2. This module provides functions to parse Bambu Lab 3MF files and extract
  3. per-layer filament usage data from the embedded G-code. This enables
  4. accurate partial usage reporting for multi-material prints.
  5. """
  6. import json
  7. import logging
  8. import math
  9. import re
  10. import zipfile
  11. from pathlib import Path
  12. import defusedxml.ElementTree as ET
  13. logger = logging.getLogger(__name__)
  14. # Default filament properties
  15. DEFAULT_FILAMENT_DIAMETER = 1.75 # mm
  16. DEFAULT_FILAMENT_DENSITY = 1.24 # g/cm³ (PLA)
  17. def parse_gcode_layer_filament_usage(gcode_content: str) -> dict[int, dict[int, float]]:
  18. """Parse G-code to extract per-layer, per-filament cumulative extrusion in mm.
  19. This function tracks filament extrusion across layers and tool changes,
  20. building a cumulative usage map that can be used to calculate partial
  21. usage at any layer.
  22. Args:
  23. gcode_content: The raw G-code content as a string
  24. Returns:
  25. A nested dictionary mapping layer numbers to filament usage:
  26. {layer: {filament_id: cumulative_mm}, ...}
  27. Example:
  28. {0: {0: 125.5}, 1: {0: 250.0, 1: 50.0}, 2: {0: 375.0, 1: 150.0}}
  29. This shows:
  30. - Layer 0: filament 0 used 125.5mm cumulative
  31. - Layer 1: filament 0 used 250mm cumulative, filament 1 used 50mm
  32. - Layer 2: filament 0 used 375mm cumulative, filament 1 used 150mm
  33. G-code commands parsed:
  34. - M73 L<layer>: Layer change marker
  35. - M620 S<filament>: Filament/tool change (S255 = unload)
  36. - G0/G1/G2/G3 E<amount>: Extrusion moves
  37. """
  38. layer_filaments: dict[int, dict[int, float]] = {}
  39. current_layer = 0
  40. active_filament: int | None = None
  41. cumulative_extrusion: dict[int, float] = {} # filament_id -> total mm
  42. for line in gcode_content.splitlines():
  43. line = line.strip()
  44. if not line:
  45. continue
  46. # Handle comments - skip but check for layer markers
  47. if line.startswith(";"):
  48. # Some slicers use comment-based layer markers
  49. # e.g., "; CHANGE_LAYER" or ";LAYER_CHANGE"
  50. continue
  51. # Split line into command and inline comment
  52. if ";" in line:
  53. line = line.split(";")[0].strip()
  54. # Extract command and parameters
  55. parts = line.split()
  56. if not parts:
  57. continue
  58. cmd = parts[0].upper()
  59. # Layer change: M73 L<layer>
  60. # Bambu printers use M73 with L parameter for layer indication
  61. if cmd == "M73":
  62. for part in parts[1:]:
  63. part_upper = part.upper()
  64. if part_upper.startswith("L"):
  65. try:
  66. new_layer = int(part[1:])
  67. # Save current state before layer change
  68. if cumulative_extrusion:
  69. layer_filaments[current_layer] = cumulative_extrusion.copy()
  70. current_layer = new_layer
  71. except ValueError:
  72. pass # Skip G-code lines with unparseable layer numbers
  73. # Filament change: M620 S<filament>
  74. # Bambu uses M620 for AMS filament switching
  75. # S255 means full unload (no active filament)
  76. elif cmd == "M620":
  77. for part in parts[1:]:
  78. part_upper = part.upper()
  79. if part_upper.startswith("S"):
  80. filament_str = part[1:]
  81. if filament_str == "255":
  82. # Full unload - no active filament
  83. active_filament = None
  84. else:
  85. try:
  86. # Extract digits (e.g., "0A" -> 0, "1" -> 1)
  87. match = re.match(r"(\d+)", filament_str)
  88. if match:
  89. active_filament = int(match.group(1))
  90. except (ValueError, AttributeError):
  91. pass # Skip unparseable filament switch commands
  92. # Extrusion moves: G0/G1/G2/G3 with E parameter
  93. # Only G1 typically has extrusion, but check all for safety
  94. elif cmd in ("G0", "G1", "G2", "G3"):
  95. if active_filament is None:
  96. continue
  97. for part in parts[1:]:
  98. part_upper = part.upper()
  99. if part_upper.startswith("E"):
  100. try:
  101. extrusion = float(part[1:])
  102. # Only count positive extrusion (not retractions)
  103. if extrusion > 0:
  104. current = cumulative_extrusion.get(active_filament, 0)
  105. cumulative_extrusion[active_filament] = current + extrusion
  106. except ValueError:
  107. pass # Skip G-code lines with unparseable extrusion values
  108. # Save final layer state
  109. if cumulative_extrusion:
  110. layer_filaments[current_layer] = cumulative_extrusion.copy()
  111. return layer_filaments
  112. def mm_to_grams(
  113. length_mm: float,
  114. diameter_mm: float = DEFAULT_FILAMENT_DIAMETER,
  115. density_g_cm3: float = DEFAULT_FILAMENT_DENSITY,
  116. ) -> float:
  117. """Convert filament length in mm to weight in grams.
  118. Uses the formula: mass = volume × density
  119. where volume = π × r² × length
  120. Args:
  121. length_mm: Length of filament in millimeters
  122. diameter_mm: Filament diameter in millimeters (default: 1.75)
  123. density_g_cm3: Material density in g/cm³ (default: 1.24 for PLA)
  124. Returns:
  125. Weight in grams
  126. """
  127. radius_cm = (diameter_mm / 2) / 10 # Convert mm to cm
  128. length_cm = length_mm / 10 # Convert mm to cm
  129. volume_cm3 = math.pi * radius_cm * radius_cm * length_cm
  130. return volume_cm3 * density_g_cm3
  131. def extract_layer_filament_usage_from_3mf(file_path: Path) -> dict[int, dict[int, float]] | None:
  132. """Extract per-layer filament usage from a 3MF file's embedded G-code.
  133. Args:
  134. file_path: Path to the 3MF file
  135. Returns:
  136. Dictionary mapping layers to filament usage, or None if parsing fails.
  137. Format: {layer: {filament_id: cumulative_mm}, ...}
  138. """
  139. try:
  140. with zipfile.ZipFile(file_path, "r") as zf:
  141. # Find G-code file(s) - usually plate_1.gcode or Metadata/plate_1.gcode
  142. gcode_files = [f for f in zf.namelist() if f.endswith(".gcode")]
  143. if not gcode_files:
  144. return None
  145. # Use the first G-code file (typically only one per 3MF export)
  146. gcode_path = gcode_files[0]
  147. gcode_content = zf.read(gcode_path).decode("utf-8", errors="ignore")
  148. return parse_gcode_layer_filament_usage(gcode_content)
  149. except Exception:
  150. return None
  151. def get_cumulative_usage_at_layer(
  152. layer_usage: dict[int, dict[int, float]],
  153. target_layer: int,
  154. ) -> dict[int, float]:
  155. """Get cumulative filament usage (in mm) up to and including target_layer.
  156. Args:
  157. layer_usage: The output from parse_gcode_layer_filament_usage()
  158. target_layer: The layer number to get usage for
  159. Returns:
  160. Dictionary of {filament_id: cumulative_mm} for each filament used
  161. up to target_layer. Returns empty dict if no data available.
  162. """
  163. if not layer_usage:
  164. return {}
  165. # Find the highest recorded layer <= target_layer
  166. # (we store snapshots at layer changes, so we need the closest one)
  167. relevant_layers = [layer for layer in layer_usage if layer <= target_layer]
  168. if not relevant_layers:
  169. return {}
  170. max_layer = max(relevant_layers)
  171. return layer_usage.get(max_layer, {})
  172. def extract_filament_properties_from_3mf(file_path: Path) -> dict[int, dict]:
  173. """Extract filament properties (density, diameter, type) from 3MF metadata.
  174. Args:
  175. file_path: Path to the 3MF file
  176. Returns:
  177. Dictionary mapping filament IDs to their properties:
  178. {filament_id: {"diameter": 1.75, "density": 1.24, "type": "PLA"}, ...}
  179. Note: filament_id is 1-based (matches slot_id in slice_info.config)
  180. """
  181. properties: dict[int, dict] = {}
  182. try:
  183. with zipfile.ZipFile(file_path, "r") as zf:
  184. # Try slice_info.config first for filament types
  185. if "Metadata/slice_info.config" in zf.namelist():
  186. content = zf.read("Metadata/slice_info.config").decode()
  187. root = ET.fromstring(content)
  188. for f in root.findall(".//filament"):
  189. try:
  190. # id is 1-based in slice_info.config
  191. fid = int(f.get("id", 0))
  192. properties[fid] = {
  193. "type": f.get("type", "PLA"),
  194. "diameter": DEFAULT_FILAMENT_DIAMETER,
  195. "density": DEFAULT_FILAMENT_DENSITY,
  196. }
  197. except ValueError:
  198. pass # Skip filament entries with unparseable IDs
  199. # Try project_settings.config for density values
  200. if "Metadata/project_settings.config" in zf.namelist():
  201. content = zf.read("Metadata/project_settings.config").decode()
  202. try:
  203. data = json.loads(content)
  204. densities = data.get("filament_density", [])
  205. for i, density in enumerate(densities):
  206. # project_settings uses 0-based indexing, convert to 1-based
  207. fid = i + 1
  208. if fid not in properties:
  209. properties[fid] = {
  210. "type": "",
  211. "diameter": DEFAULT_FILAMENT_DIAMETER,
  212. }
  213. try:
  214. properties[fid]["density"] = float(density)
  215. except (ValueError, TypeError):
  216. properties[fid]["density"] = DEFAULT_FILAMENT_DENSITY
  217. except json.JSONDecodeError:
  218. pass # Skip malformed project_settings.config JSON
  219. except Exception:
  220. pass # Return whatever properties were collected before the error
  221. return properties
  222. def _first_settings_id(value: object) -> str | None:
  223. """A ``*_settings_id`` value is usually a string, occasionally a list (one
  224. entry per extruder). Return the first non-empty string, else None."""
  225. if isinstance(value, str):
  226. return value.strip() or None
  227. if isinstance(value, list):
  228. for item in value:
  229. if isinstance(item, str) and item.strip():
  230. return item.strip()
  231. return None
  232. def extract_embedded_presets_from_3mf(zf: zipfile.ZipFile) -> dict[str, str | None]:
  233. """Read the printer / process preset names a 3MF project was prepared with.
  234. BambuStudio / OrcaSlicer write the chosen preset names into
  235. ``Metadata/project_settings.config`` (``printer_settings_id`` and
  236. ``print_settings_id``). The SliceModal uses them to default its printer
  237. and process dropdowns to what the file was sliced for (#1325) instead of
  238. blindly taking the first listed preset.
  239. Returns ``{"printer": <name|None>, "process": <name|None>}``. Every failure
  240. mode (missing config, malformed JSON, unexpected shape) yields ``None``
  241. values so the modal falls back to its own defaults.
  242. """
  243. result: dict[str, str | None] = {"printer": None, "process": None}
  244. try:
  245. if "Metadata/project_settings.config" not in zf.namelist():
  246. return result
  247. data = json.loads(zf.read("Metadata/project_settings.config").decode())
  248. except (KeyError, ValueError, OSError):
  249. return result
  250. if not isinstance(data, dict):
  251. return result
  252. result["printer"] = _first_settings_id(data.get("printer_settings_id"))
  253. result["process"] = _first_settings_id(data.get("print_settings_id"))
  254. return result
  255. def extract_nozzle_mapping_from_3mf(zf: zipfile.ZipFile) -> dict[int, int] | None:
  256. """Extract per-slot nozzle/extruder mapping from a 3MF file.
  257. On dual-nozzle printers (H2D, H2D Pro), each filament slot is assigned to a
  258. specific nozzle. The slicer may override user preferences when using "Auto For
  259. Flush" mode, so the actual assignment comes from slice_info.config group_id
  260. attributes, not from the user's filament_nozzle_map preference.
  261. Priority:
  262. 1. group_id on <filament> elements in slice_info.config (actual assignment)
  263. 2. filament_nozzle_map in project_settings.config (user preference fallback)
  264. Both are mapped through physical_extruder_map to get MQTT extruder IDs (0=right, 1=left).
  265. Args:
  266. zf: An open ZipFile of the 3MF archive
  267. Returns:
  268. Dictionary mapping {slot_id: extruder_id} for dual-nozzle files,
  269. or None if single-nozzle, missing data, or parse error.
  270. """
  271. try:
  272. if "Metadata/project_settings.config" not in zf.namelist():
  273. return None
  274. content = zf.read("Metadata/project_settings.config").decode()
  275. data = json.loads(content)
  276. physical_extruder_map = data.get("physical_extruder_map")
  277. if not physical_extruder_map or len(physical_extruder_map) <= 1:
  278. return None # Single-nozzle printer
  279. # Check if only one extruder is active.
  280. # If so, we can skip the mapping and just assign all slots to that extruder.
  281. # extruder_nozzle_stats format: ["Standard#0|High Flow#0", "Standard#1"]
  282. # Each entry = one extruder. Format: <NozzleVolumeType>#<count>[|...]
  283. # #N is the count of physical nozzles of that type (0 = none installed).
  284. # Types: Standard, High Flow, Hybrid, TPU High Flow
  285. active_extruders = []
  286. for stats_str in data.get("extruder_nozzle_stats") or []:
  287. nozzle_counts = [n.partition("#")[2] for n in stats_str.split("|")]
  288. active_extruders.append(1 if any(c not in ("0", "") for c in nozzle_counts) else 0)
  289. if sum(active_extruders) == 1:
  290. nozzle_mapping: dict[int, int] = {}
  291. active_idx = active_extruders.index(1)
  292. target_extruder = int(physical_extruder_map[active_idx])
  293. if "Metadata/slice_info.config" in zf.namelist():
  294. si_content = zf.read("Metadata/slice_info.config").decode()
  295. si_root = ET.fromstring(si_content)
  296. for filament_elem in si_root.findall(".//filament"):
  297. try:
  298. nozzle_mapping[int(filament_elem.get("id"))] = target_extruder
  299. except (ValueError, TypeError):
  300. pass
  301. return nozzle_mapping or None
  302. # Priority 1: Use group_id from slice_info filament elements.
  303. # This reflects the actual slicer assignment (respects "Auto For Flush").
  304. nozzle_mapping: dict[int, int] = {}
  305. if "Metadata/slice_info.config" in zf.namelist():
  306. si_content = zf.read("Metadata/slice_info.config").decode()
  307. si_root = ET.fromstring(si_content)
  308. for filament_elem in si_root.findall(".//filament"):
  309. group_id_str = filament_elem.get("group_id")
  310. filament_id_str = filament_elem.get("id")
  311. if group_id_str is not None and filament_id_str:
  312. try:
  313. group_id = int(group_id_str)
  314. slot_id = int(filament_id_str)
  315. if group_id < len(physical_extruder_map):
  316. nozzle_mapping[slot_id] = int(physical_extruder_map[group_id])
  317. except (ValueError, TypeError, IndexError):
  318. pass
  319. if nozzle_mapping:
  320. return nozzle_mapping
  321. # Priority 2: Fall back to filament_nozzle_map (user preference).
  322. # This is correct when the user manually assigned nozzles, but may be
  323. # wrong when the slicer overrides via "Auto For Flush".
  324. filament_nozzle_map = data.get("filament_nozzle_map")
  325. if not filament_nozzle_map:
  326. return None
  327. for i, slicer_ext_str in enumerate(filament_nozzle_map):
  328. slot_id = i + 1
  329. try:
  330. slicer_ext = int(slicer_ext_str)
  331. if slicer_ext < len(physical_extruder_map):
  332. nozzle_mapping[slot_id] = int(physical_extruder_map[slicer_ext])
  333. except (ValueError, TypeError, IndexError):
  334. pass
  335. return nozzle_mapping if nozzle_mapping else None
  336. except Exception:
  337. return None
  338. def extract_filament_usage_from_3mf(file_path: Path, plate_id: int | None = None) -> list[dict]:
  339. """Extract per-filament total usage from 3MF slice_info.config.
  340. This extracts the slicer-estimated total usage per filament slot,
  341. not the per-layer breakdown.
  342. Args:
  343. file_path: Path to the 3MF file
  344. plate_id: Optional plate index to filter for (for multi-plate files)
  345. Returns:
  346. List of filament usage dictionaries:
  347. [{"slot_id": 1, "used_g": 50.5, "type": "PLA", "color": "#FF0000"}, ...]
  348. """
  349. filament_usage = []
  350. try:
  351. with zipfile.ZipFile(file_path, "r") as zf:
  352. if "Metadata/slice_info.config" not in zf.namelist():
  353. return []
  354. content = zf.read("Metadata/slice_info.config").decode()
  355. root = ET.fromstring(content)
  356. if plate_id is not None:
  357. # Find the plate element with matching index
  358. for plate_elem in root.findall(".//plate"):
  359. plate_index = None
  360. for meta in plate_elem.findall("metadata"):
  361. if meta.get("key") == "index":
  362. try:
  363. plate_index = int(meta.get("value", "0"))
  364. except ValueError:
  365. pass
  366. break
  367. if plate_index == plate_id:
  368. for f in plate_elem.findall("filament"):
  369. filament_id = f.get("id")
  370. used_g = f.get("used_g", "0")
  371. try:
  372. used_amount = float(used_g)
  373. if filament_id:
  374. filament_usage.append(
  375. {
  376. "slot_id": int(filament_id),
  377. "used_g": used_amount,
  378. "type": f.get("type", ""),
  379. "color": f.get("color", ""),
  380. }
  381. )
  382. except (ValueError, TypeError):
  383. pass
  384. break
  385. else:
  386. # No plate_id specified - extract all filaments
  387. for f in root.findall(".//filament"):
  388. filament_id = f.get("id")
  389. used_g = f.get("used_g", "0")
  390. try:
  391. used_amount = float(used_g)
  392. if filament_id:
  393. filament_usage.append(
  394. {
  395. "slot_id": int(filament_id),
  396. "used_g": used_amount,
  397. "type": f.get("type", ""),
  398. "color": f.get("color", ""),
  399. }
  400. )
  401. except (ValueError, TypeError):
  402. pass # Skip filament entries with unparseable usage values
  403. except Exception:
  404. pass # Return whatever usage data was collected before the error
  405. return filament_usage
  406. def extract_bed_type_from_3mf(file_path: Path, plate_id: int | None = None) -> str | None:
  407. """Extract the build plate type (`curr_bed_type`) for a specific plate (#1281).
  408. ``archive.bed_type`` is captured at ingest time but is one value per archive
  409. (the first plate's `curr_bed_type` — see services/archive.py:235). For a
  410. multi-plate 3MF where different plates target different beds (e.g. a 40-plate
  411. file mixing PEI + Engineering), the archive-level value lies. When a queue
  412. item or print modal targets a specific plate, this re-reads the 3MF and
  413. returns that plate's actual bed type.
  414. Args:
  415. file_path: Path to the 3MF file
  416. plate_id: Plate index to filter for; if None, returns the first plate's
  417. ``curr_bed_type`` (matches the archive-level capture).
  418. Returns:
  419. Bed type string (e.g. "Textured PEI Plate"), or None if not found.
  420. """
  421. try:
  422. with zipfile.ZipFile(file_path, "r") as zf:
  423. if "Metadata/slice_info.config" not in zf.namelist():
  424. return None
  425. content = zf.read("Metadata/slice_info.config").decode()
  426. root = ET.fromstring(content)
  427. for plate_elem in root.findall(".//plate"):
  428. plate_index = None
  429. bed_value: str | None = None
  430. for meta in plate_elem.findall("metadata"):
  431. key = meta.get("key")
  432. if key == "index":
  433. try:
  434. plate_index = int(meta.get("value", "0"))
  435. except ValueError:
  436. pass # Skip plate with unparseable index
  437. elif key == "curr_bed_type" and meta.get("value"):
  438. bed_value = (meta.get("value") or "").strip()
  439. if plate_id is None:
  440. # First plate wins when no plate_id is requested.
  441. return bed_value
  442. if plate_index == plate_id:
  443. return bed_value
  444. except Exception:
  445. pass # Return None on any failure rather than raising — caller decides
  446. return None
  447. # Header values exposed as `{placeholder}` substitutions inside snippets.
  448. # Aliases let users write Prusa-style names (`{max_layer_z}`) that map onto
  449. # Bambu/Orca header keys (`max_z_height`).
  450. _HEADER_PLACEHOLDER_ALIASES = {
  451. "max_layer_z": "max_z_height",
  452. "max_print_height": "max_z_height",
  453. "total_layers": "total_layer_number",
  454. }
  455. _HEADER_KEY_RE = re.compile(r"^;\s*([^:]+?)\s*:\s*(.+?)\s*$")
  456. _PLACEHOLDER_RE = re.compile(r"\{([a-zA-Z_][a-zA-Z0-9_]*)\}")
  457. _START_GCODE_END_MARKER = "; MACHINE_START_GCODE_END"
  458. def _parse_3mf_gcode_header(content: str) -> dict[str, str]:
  459. """Parse the `; HEADER_BLOCK_START..END` block into a normalised dict.
  460. Keys are lowercased, ` [units]` suffixes stripped, and spaces converted
  461. to underscores so callers can look up `total_layer_number` regardless of
  462. whether the source line is `; total layer number: 80` or
  463. `; total filament length [mm] : 12155.34`.
  464. """
  465. header: dict[str, str] = {}
  466. in_header = False
  467. for raw_line in content.splitlines():
  468. line = raw_line.strip()
  469. if line == "; HEADER_BLOCK_START":
  470. in_header = True
  471. continue
  472. if line == "; HEADER_BLOCK_END":
  473. break
  474. if not in_header:
  475. continue
  476. m = _HEADER_KEY_RE.match(line)
  477. if not m:
  478. continue
  479. key, value = m.group(1), m.group(2)
  480. key = re.sub(r"\s*\[[^\]]*\]\s*$", "", key)
  481. key = key.strip().lower().replace(" ", "_")
  482. header[key] = value
  483. return header
  484. def _substitute_placeholders(snippet: str, header: dict[str, str]) -> str:
  485. """Replace `{var}` placeholders with header values, leaving unknowns intact."""
  486. def repl(m: re.Match) -> str:
  487. name = m.group(1)
  488. value = header.get(name)
  489. if value is None:
  490. alias = _HEADER_PLACEHOLDER_ALIASES.get(name)
  491. if alias is not None:
  492. value = header.get(alias)
  493. if value is None:
  494. logger.warning(
  495. "G-code injection: placeholder {%s} not found in 3MF header; leaving as-is",
  496. name,
  497. )
  498. return m.group(0)
  499. return value
  500. return _PLACEHOLDER_RE.sub(repl, snippet)
  501. def _inject_start_at_marker(content: str, snippet: str) -> str:
  502. """Insert snippet immediately before `; MACHINE_START_GCODE_END`.
  503. The marker sits at the bottom of the printer's startup block — bed heat,
  504. homing, and nozzle prime are already done, so injected snippets land in
  505. the same place a slicer-side custom-start-gcode would. Falls back to
  506. prepending if the marker isn't present (older files / non-Bambu slicers).
  507. """
  508. marker_idx = content.find(_START_GCODE_END_MARKER)
  509. if marker_idx == -1:
  510. logger.warning(
  511. "G-code injection: '%s' not found, prepending start snippet to whole file",
  512. _START_GCODE_END_MARKER,
  513. )
  514. return snippet.rstrip("\n") + "\n" + content
  515. line_start = content.rfind("\n", 0, marker_idx)
  516. line_start = 0 if line_start == -1 else line_start + 1
  517. return content[:line_start] + snippet.rstrip("\n") + "\n" + content[line_start:]
  518. def inject_gcode_into_3mf(
  519. source_path: Path,
  520. plate_id: int,
  521. start_gcode: str | None,
  522. end_gcode: str | None,
  523. ):
  524. """Create a temp copy of a 3MF with G-code injected at start/end.
  525. Snippets support `{placeholder}` substitution against values parsed from
  526. the 3MF G-code header block (e.g. `{max_layer_z}` → `16.00`). Start
  527. snippets are anchored to the `; MACHINE_START_GCODE_END` marker so they
  528. run after the printer's own startup (#422). End snippets are appended
  529. after the last line of the print.
  530. Args:
  531. source_path: Path to the original 3MF file.
  532. plate_id: Plate number (1-indexed) to inject into.
  533. start_gcode: G-code to insert after printer startup, or None.
  534. end_gcode: G-code to append, or None.
  535. Returns:
  536. Path to temp file with injected G-code, or None if injection failed.
  537. Caller is responsible for cleaning up the temp file.
  538. """
  539. import tempfile
  540. if not start_gcode and not end_gcode:
  541. return None
  542. try:
  543. # Find the target gcode file inside the 3MF
  544. with zipfile.ZipFile(source_path, "r") as zf:
  545. all_gcode = [f for f in zf.namelist() if f.endswith(".gcode")]
  546. if not all_gcode:
  547. return None
  548. # Try plate-specific gcode file first
  549. target_gcode = None
  550. plate_pattern = f"plate_{plate_id}.gcode"
  551. for f in all_gcode:
  552. if f.endswith(plate_pattern):
  553. target_gcode = f
  554. break
  555. # Fall back to first gcode file
  556. if target_gcode is None:
  557. target_gcode = all_gcode[0]
  558. # Read and modify gcode content
  559. gcode_content = zf.read(target_gcode).decode("utf-8", errors="ignore")
  560. header = _parse_3mf_gcode_header(gcode_content)
  561. if start_gcode:
  562. resolved = _substitute_placeholders(start_gcode, header)
  563. gcode_content = _inject_start_at_marker(gcode_content, resolved)
  564. if end_gcode:
  565. resolved = _substitute_placeholders(end_gcode, header)
  566. gcode_content = gcode_content.rstrip("\n") + "\n" + resolved + "\n"
  567. # Write modified 3MF to temp file
  568. with tempfile.NamedTemporaryFile(delete=False, suffix=".3mf") as tmp:
  569. tmp_path = Path(tmp.name)
  570. with zipfile.ZipFile(tmp_path, "w", zipfile.ZIP_DEFLATED) as zf_write:
  571. for item in zf.namelist():
  572. info = zf.getinfo(item)
  573. if item == target_gcode:
  574. zf_write.writestr(info, gcode_content.encode("utf-8"))
  575. else:
  576. zf_write.writestr(info, zf.read(item))
  577. return tmp_path
  578. except Exception:
  579. # Clean up temp file on error
  580. if "tmp_path" in locals() and tmp_path.exists():
  581. tmp_path.unlink(missing_ok=True)
  582. return None
  583. def extract_project_filaments_from_3mf(zf: zipfile.ZipFile) -> list[dict]:
  584. """Project-wide AMS slot config from ``Metadata/project_settings.config``.
  585. Returns one dict per configured AMS slot in slot order (1-indexed), with
  586. ``type`` and ``color`` populated from the project's ``filament_type`` and
  587. ``filament_colour`` arrays. ``used_grams`` / ``used_meters`` are 0 because
  588. project_settings carries the configuration, not per-print usage — the
  589. fields exist for shape compatibility with the slice_info-derived list.
  590. The SliceModal needs this on **unsliced** project files: slice_info.config
  591. is empty until Bambu Studio has actually sliced the project, but the user
  592. can still pick filament profiles for a slice we're about to perform.
  593. """
  594. if "Metadata/project_settings.config" not in zf.namelist():
  595. return []
  596. try:
  597. proj = json.loads(zf.read("Metadata/project_settings.config").decode())
  598. except (ValueError, OSError):
  599. return []
  600. if not isinstance(proj, dict):
  601. return []
  602. types_arr = proj.get("filament_type") or []
  603. colors_arr = proj.get("filament_colour") or []
  604. slot_count = max(
  605. len(types_arr) if isinstance(types_arr, list) else 0, len(colors_arr) if isinstance(colors_arr, list) else 0
  606. )
  607. out: list[dict] = []
  608. for i in range(slot_count):
  609. out.append(
  610. {
  611. "slot_id": i + 1,
  612. "type": types_arr[i] if i < len(types_arr) and isinstance(types_arr[i], str) else "",
  613. "color": colors_arr[i] if i < len(colors_arr) and isinstance(colors_arr[i], str) else "",
  614. "used_grams": 0,
  615. "used_meters": 0,
  616. }
  617. )
  618. return out
  619. _PAINT_COLOR_ATTR_RE = re.compile(rb'paint_color="([0-9A-Fa-f]+)"')
  620. # Painted-face quadtree leaves include both real filament assignments and
  621. # tiny edit artifacts (single-leaf accidents from "tried a colour, undid,
  622. # repainted with a different one"). The threshold's only job is dropping
  623. # accidents — anything the user spent meaningful effort on must survive.
  624. # 5% of an object's painted triangles is well below any 60/40 / 70/30 /
  625. # 33/33/33 split a real two- or three-colour print would hit, so all
  626. # intentional colours are kept; one-off single-leaf paints (typically
  627. # 0.1-1.5% in observed projects) are filtered. Note that this fallback
  628. # path runs ONLY when the preview-slice path can't reach the sidecar; in
  629. # the normal flow the slicer's own pruning produces the canonical list and
  630. # this threshold isn't reached.
  631. _PAINT_NOISE_THRESHOLD = 0.05
  632. def extract_plate_extruder_set_from_3mf(zf: zipfile.ZipFile, plate_id: int) -> set[int]:
  633. """Extruder/AMS slot indices (1-indexed) used by objects on ``plate_id``.
  634. Three sources are unioned because Bambu Studio splits per-object extruder
  635. info across THREE places depending on how the user assigned colours:
  636. 1. ``model_settings.config`` — top-level ``<metadata key="extruder">``
  637. on each ``<object>`` (the "default extruder" for the whole object).
  638. 2. ``model_settings.config`` — per-``<part>`` ``<metadata key="extruder">``
  639. overrides (used when the user split an object into multiple parts
  640. with distinct filaments).
  641. 3. ``3D/Objects/object_*.model`` — ``paint_color`` attributes on
  642. individual ``<triangle>`` elements (used when the user "painted" a
  643. face with a different filament). The encoding is a hex string where
  644. each nibble is a TriangleSelector tree node: ``0`` = unpainted leaf,
  645. ``F`` = branch (4 children follow), ``1``..``E`` = leaf painted with
  646. extruder N. We don't decode the tree — every leaf-paint nibble in
  647. the string IS the extruder number, so a flat scan over hex chars
  648. yields the correct set without recursive parsing.
  649. Without (3) the painted-face data is invisible: model_settings says
  650. every object on a multi-color plate uses extruder 1 by default but the
  651. actual print uses 3, 4, 12 etc. via face paint, so the SliceModal would
  652. render only one filament dropdown for what's clearly a multi-colour
  653. print (#1150 follow-up).
  654. """
  655. if "Metadata/model_settings.config" not in zf.namelist():
  656. return set()
  657. try:
  658. root = ET.fromstring(zf.read("Metadata/model_settings.config").decode())
  659. except (ET.ParseError, OSError):
  660. return set()
  661. # Pass 1: object → set of extruders from XML metadata (sources 1 + 2)
  662. # plus the per-object .model file path so we can later scan source 3.
  663. object_extruders: dict[str, set[int]] = {}
  664. object_model_paths: dict[str, list[str]] = {}
  665. for obj_elem in root.findall(".//object"):
  666. obj_id = obj_elem.get("id")
  667. if not obj_id:
  668. continue
  669. extruders: set[int] = set()
  670. top = obj_elem.find("metadata[@key='extruder']")
  671. if top is not None:
  672. try:
  673. v = int(top.get("value", "0"))
  674. if v > 0:
  675. extruders.add(v)
  676. except (ValueError, TypeError):
  677. pass
  678. for part_elem in obj_elem.findall(".//part"):
  679. part_ext = part_elem.find("metadata[@key='extruder']")
  680. if part_ext is None:
  681. continue
  682. try:
  683. v = int(part_ext.get("value", "0"))
  684. if v > 0:
  685. extruders.add(v)
  686. except (ValueError, TypeError):
  687. pass
  688. object_extruders[obj_id] = extruders
  689. # Pass 2: 3dmodel.model maps each <object id="N"> to its component
  690. # .model file path(s). Bambu wraps object IDs that match
  691. # model_settings.config IDs around <components><component
  692. # path="/3D/Objects/object_K.model" objectid="..." /></components>.
  693. # Strip xmlns prefixes on attributes so ElementTree can find them
  694. # without namespace gymnastics — `p:path` becomes `path` etc.
  695. if "3D/3dmodel.model" in zf.namelist():
  696. try:
  697. raw = zf.read("3D/3dmodel.model").decode()
  698. stripped = re.sub(r'xmlns:?\w*="[^"]*"', "", raw)
  699. stripped = re.sub(r"<(/?)\w+:", r"<\1", stripped)
  700. stripped = re.sub(r" \w+:(\w+=)", r" \1", stripped)
  701. model_root = ET.fromstring(stripped)
  702. for obj_elem in model_root.findall(".//object"):
  703. oid = obj_elem.get("id")
  704. if not oid:
  705. continue
  706. comps = obj_elem.find("components")
  707. if comps is None:
  708. continue
  709. paths = []
  710. for c in comps.findall("component"):
  711. p = c.get("path")
  712. if p:
  713. paths.append(p.lstrip("/"))
  714. if paths:
  715. object_model_paths[oid] = paths
  716. except (ET.ParseError, OSError):
  717. pass # No 3dmodel — paint scan just won't apply
  718. # Pass 3: scan paint_color attrs in each per-object .model file. Cache
  719. # by file path because two objects often share the same component tree.
  720. paint_cache: dict[str, set[int]] = {}
  721. def _scan_paint(path: str) -> set[int]:
  722. if path in paint_cache:
  723. return paint_cache[path]
  724. out: set[int] = set()
  725. if path not in zf.namelist():
  726. paint_cache[path] = out
  727. return out
  728. try:
  729. data = zf.read(path)
  730. except OSError:
  731. paint_cache[path] = out
  732. return out
  733. # Per-extruder triangle coverage. Each painted triangle may have
  734. # multiple leaf nibbles (the quadtree subdivides the face into
  735. # painted regions); we count one triangle per unique extruder per
  736. # match so the resulting fraction is "what share of painted
  737. # triangles include at least one leaf with extruder N". Noise from
  738. # one-off edit artifacts is filtered out at the threshold below.
  739. extruder_triangles: dict[int, int] = {}
  740. total_painted = 0
  741. for match in _PAINT_COLOR_ATTR_RE.finditer(data):
  742. total_painted += 1
  743. seen: set[int] = set()
  744. for ch in match.group(1):
  745. # Hex digit → 4-bit value. 0 = unpainted leaf, F = branch
  746. # (decoded recursively but children are encoded inline, so
  747. # we'll see them on later iterations). 1-E = leaf painted
  748. # with extruder N.
  749. if ch in b"123456789":
  750. seen.add(ch - 0x30)
  751. elif ch in b"ABCDEabcde":
  752. seen.add((ch & 0x4F) - 0x37)
  753. for e in seen:
  754. extruder_triangles[e] = extruder_triangles.get(e, 0) + 1
  755. if total_painted > 0:
  756. cutoff = max(1, int(total_painted * _PAINT_NOISE_THRESHOLD))
  757. for ext, count in extruder_triangles.items():
  758. if count >= cutoff:
  759. out.add(ext)
  760. paint_cache[path] = out
  761. return out
  762. # Walk plates — collect extruders for objects on the requested plate.
  763. used: set[int] = set()
  764. for plate_elem in root.findall(".//plate"):
  765. plater_id = None
  766. for meta in plate_elem.findall("metadata"):
  767. if meta.get("key") == "plater_id":
  768. try:
  769. plater_id = int(meta.get("value", ""))
  770. except (ValueError, TypeError):
  771. pass
  772. break
  773. if plater_id != plate_id:
  774. continue
  775. for inst in plate_elem.findall("model_instance"):
  776. for inst_meta in inst.findall("metadata"):
  777. if inst_meta.get("key") != "object_id":
  778. continue
  779. obj_id = inst_meta.get("value")
  780. if not obj_id:
  781. continue
  782. used.update(object_extruders.get(obj_id, set()))
  783. for path in object_model_paths.get(obj_id, []):
  784. used.update(_scan_paint(path))
  785. break
  786. return used