design_settings.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. """Carry a 3MF designer's own process tweaks across a re-slice (#2622).
  2. A MakerWorld model is often published with deliberate deviations from the stock
  3. Bambu process preset — 5 walls, 100% infill, a 0.1mm first layer. Re-slicing that
  4. file for a different printer used to drop every one of them: ``--load-settings``
  5. is authoritative, so the picked process preset wins over the 3MF's embedded
  6. ``Metadata/project_settings.config``.
  7. We do not have to *compute* what the designer changed. BambuStudio already did,
  8. and wrote the answer into the file:
  9. different_settings_to_system = [
  10. "enable_support;inner_wall_speed;sparse_infill_density;...", # [0] process
  11. "filament_change_length;filament_prime_volume", # [1..N] filaments
  12. "machine_start_gcode;bed_custom_model;...", # [-1] printer
  13. ]
  14. The array is ``1 + len(filament_settings_id) + 1`` long — verified against real
  15. files at 2, 3 and 4 filament slots. Index 0 is exactly the set of process keys
  16. that differ from the system preset, which is the reporter's step 1 for free: no
  17. baseline resolution, no shipping BBL profiles into Bambuddy, and no new endpoint
  18. on the slicer sidecar (which exposes bundled presets by name only, with no way to
  19. flatten one).
  20. Delivery is the mechanism ``_patch_process_support_settings`` already proved in
  21. #1881: write the values into the process JSON that goes out as ``--load-settings``.
  22. For a "standard" preset pick that JSON is a ``{inherits: …}`` stub, so the keys we
  23. write are the *child* in the inherits chain and win over the flattened parent.
  24. Not every key is safe to carry, though. Real files put ``inner_wall_speed``,
  25. ``outer_wall_speed`` and ``prime_tower_max_speed`` in that list — values tuned for
  26. the designer's machine that can be plain wrong, or out of range, on the target.
  27. Those are classified :data:`PRINTER_COUPLED` and offered unticked; the caller
  28. decides. Nothing is applied that the caller did not ask for by name.
  29. """
  30. from __future__ import annotations
  31. import json
  32. import logging
  33. import zipfile
  34. from io import BytesIO
  35. from typing import Any, NamedTuple
  36. logger = logging.getLogger(__name__)
  37. _PROJECT_SETTINGS = "Metadata/project_settings.config"
  38. class DesignOverride(NamedTuple):
  39. """One process setting the designer changed away from the system preset."""
  40. key: str
  41. value: Any
  42. printer_coupled: bool
  43. # Process keys whose sane value depends on the machine, not on the design intent.
  44. # The designer picked these for *their* printer's kinematics, chamber and hotend;
  45. # carrying them onto another model risks a slice that is merely slower/uglier —
  46. # or a hard range-validation reject from the CLI, which is how the very first
  47. # slicer spike died. Offered, but never pre-selected.
  48. #
  49. # Matching is by exact key OR by suffix/substring rule below, because Bambu's
  50. # process schema has dozens of per-feature speed keys and an exhaustive literal
  51. # list would rot on every slicer release.
  52. _PRINTER_COUPLED_EXACT: frozenset[str] = frozenset(
  53. {
  54. "default_acceleration",
  55. "independent_support_layer_height",
  56. "precise_z_height",
  57. "travel_acceleration",
  58. "enable_wrapping_detection",
  59. }
  60. )
  61. # Substring rules for the families that are always machine-coupled. Kept
  62. # deliberately narrow: "speed", "acceleration"/"accel" and "jerk" are the
  63. # kinematic families, "fan"/"temperature" follow the hotend and chamber, and
  64. # "prime_tower" follows the target's toolchange hardware.
  65. _PRINTER_COUPLED_SUBSTRINGS: tuple[str, ...] = (
  66. # Prime-tower geometry (and whether there is one at all) follows the target's
  67. # extruder count and bed, not the design — a real file carries five of these.
  68. "prime_tower",
  69. "_speed",
  70. "speed_",
  71. "acceleration",
  72. "_accel",
  73. "jerk",
  74. "fan_speed",
  75. "_temperature",
  76. "temperature_",
  77. )
  78. def is_printer_coupled(key: str) -> bool:
  79. """Whether carrying this process key across printer models is risky."""
  80. if key in _PRINTER_COUPLED_EXACT:
  81. return True
  82. lowered = key.lower()
  83. return any(token in lowered for token in _PRINTER_COUPLED_SUBSTRINGS)
  84. def _split_changed_keys(entry: Any) -> list[str]:
  85. """Parse one ``different_settings_to_system`` entry into its key names."""
  86. if not isinstance(entry, str):
  87. return []
  88. return [part.strip() for part in entry.split(";") if part.strip()]
  89. def extract_design_process_overrides(zip_bytes: bytes) -> list[DesignOverride]:
  90. """Process settings the 3MF's designer changed away from the system preset.
  91. Returns an empty list for anything that is not a BambuStudio-style 3MF
  92. carrying both ``project_settings.config`` and a well-formed
  93. ``different_settings_to_system`` — including OrcaSlicer files and older
  94. exports that predate the field. Callers treat empty as "nothing to offer",
  95. which is the pre-feature behaviour.
  96. """
  97. try:
  98. with zipfile.ZipFile(BytesIO(zip_bytes), "r") as zf:
  99. if _PROJECT_SETTINGS not in zf.namelist():
  100. return []
  101. config = json.loads(zf.read(_PROJECT_SETTINGS).decode("utf-8"))
  102. except (zipfile.BadZipFile, json.JSONDecodeError, UnicodeDecodeError, OSError, KeyError):
  103. return []
  104. return overrides_from_config(config)
  105. def overrides_from_config(config: Any) -> list[DesignOverride]:
  106. """``extract_design_process_overrides`` on an already-parsed config dict."""
  107. if not isinstance(config, dict):
  108. return []
  109. changed = config.get("different_settings_to_system")
  110. if not isinstance(changed, list) or not changed:
  111. return []
  112. # Sanity-check the layout before trusting index 0. The array should be
  113. # [process, *filaments, printer]; a file whose length disagrees with its own
  114. # filament count is one we do not understand, and guessing there could carry
  115. # printer G-code into the process slot.
  116. filaments = config.get("filament_settings_id")
  117. if isinstance(filaments, list) and len(changed) != len(filaments) + 2:
  118. logger.debug(
  119. "3MF different_settings_to_system has %d entries for %d filaments "
  120. "(expected %d) — skipping design-settings carry-over",
  121. len(changed),
  122. len(filaments),
  123. len(filaments) + 2,
  124. )
  125. return []
  126. overrides: list[DesignOverride] = []
  127. # Index 0 is the process slot — see the layout in the module docstring. The
  128. # length check above is what earns the right to index it blindly.
  129. for key in _split_changed_keys(changed[0]):
  130. if key not in config:
  131. # Listed as changed but absent from the flattened config — nothing
  132. # to carry. Seen with keys the slicer renamed between versions.
  133. continue
  134. overrides.append(DesignOverride(key=key, value=config[key], printer_coupled=is_printer_coupled(key)))
  135. overrides.sort(key=lambda o: o.key)
  136. return overrides
  137. def apply_design_overrides(process_json: str, overrides: list[DesignOverride], selected_keys: list[str]) -> str:
  138. """Write the selected designer values into the outgoing process JSON.
  139. ``selected_keys`` is authoritative — a key the caller did not name is not
  140. applied even when it is present in ``overrides``. Returns ``process_json``
  141. unchanged when nothing is selected or the JSON is unparseable, so a bad
  142. input degrades to a plain profile slice rather than failing it.
  143. """
  144. if not selected_keys or not overrides:
  145. return process_json
  146. wanted = set(selected_keys)
  147. by_key = {o.key: o.value for o in overrides if o.key in wanted}
  148. if not by_key:
  149. return process_json
  150. try:
  151. process_cfg = json.loads(process_json)
  152. except json.JSONDecodeError:
  153. return process_json
  154. if not isinstance(process_cfg, dict):
  155. return process_json
  156. process_cfg.update(by_key)
  157. logger.info("Carrying %d design setting(s) onto the picked process preset: %s", len(by_key), sorted(by_key))
  158. return json.dumps(process_cfg)