Compare commits

..
Author SHA1 Message Date
Ian Chua 7ed4095b20 fix: clang-tidy 2026-10-15 16:06:50 +08:00
Ian Chua ee1cc1b227 Merge branch 'feat/ams-parsing' into feat/generic-extruders-and-ams 2026-10-15 16:05:00 +08:00
Ian Chua 46096416cd Merge branch 'main' into feat/generic-n-extruders 2026-10-15 16:04:30 +08:00
Ian Chua 74fe2b7996 Merge branch 'main' into feat/generic-n-extruders 2026-10-15 14:45:26 +08:00
Ian Chua 38f649fc00 Merge branch 'main' into feat/ams-parsing 2026-10-15 14:42:59 +08:00
peachismomo 23f6771dcb fix: parse AFC lane data and non-bambu ams tray indices correctly 2026-10-11 20:11:47 +08:00
Ian Chua aebc0a2979 fix: change ams type when parsing AFC mmu 2026-10-09 18:27:14 +08:00
Ian Chua 6f0ec60d21 feat: update happy hare parsing 2026-10-08 21:26:00 +08:00
Ian Chua 8e43a2ac13 fix: center external spool 2026-10-08 21:19:00 +08:00
Ian Chua 6b366ad8a9 fix: sync_ams_list should drop placeholder filaments 2026-10-08 20:42:11 +08:00
Ian Chua 7d8261668e fix: use extruder count for bbl and m_nozzle_book for non bbl 2026-10-08 20:29:47 +08:00
Ian Chua 00127beffa fix: use multi-nozzle AMS layout for non-Bambu printers at any extruder count 2026-10-08 19:26:43 +08:00
Lam Wei Lun 927eb9922c Map slot id directly 2026-10-08 18:37:09 +08:00
Ian Chua 3d62769664 feat: expand filament parsing in MoonrakerPrinterAgent 2026-10-08 17:46:01 +08:00
Ian Chua e5e30ee0e8 fix: harden generic N-extruder device model and status/AMS UI, add N-toolhead ExtruderImage sizing, tests, and HLSD 2026-10-08 17:39:44 +08:00
Ian Chua 7515fb480f fix: remove dead code 2026-10-08 15:56:20 +08:00
Ian Chua acc1d6fd21 Merge branch 'main' into feat/generic-n-extruders 2026-10-08 14:49:50 +08:00
Ian Chua 6ca0fc5ef1 fix: clang-tidy 2026-10-07 19:33:58 +08:00
Ian Chua bcf7d078cd Merge branch 'main' into feat/generic-n-extruders 2026-10-07 19:25:52 +08:00
Ian Chua 15fc96fca7 Merge branch 'main' into feat/generic-n-extruders 2026-10-07 19:25:35 +08:00
Ian Chua 1fffda0533 chore: add tests and HLSD 2026-10-07 19:05:06 +08:00
Ian Chua 33e26a127e fix: warn when toolhead count differs from the selected printer preset's nozzle_diameter count 2026-10-07 18:40:41 +08:00
Ian Chua 6dd0cb9eba fix: harden generic N-extruder device paths 2026-10-07 18:30:49 +08:00
Ian Chua 9bf0fc2a8e test: reset virtual trays in the generic AMS tray index map case 2026-10-06 20:53:46 +08:00
Ian Chua 5bf6db95b3 fix: clang-tidy 2026-10-06 19:56:53 +08:00
Ian Chua 0feb87b417 feat: generic N extruders, multiple AMS and AMS slots 2026-10-06 19:22:10 +08:00
96 changed files with 9214 additions and 43505 deletions
+199
View File
@@ -0,0 +1,199 @@
# Multi-extruder and multi-AMS device control
`DeviceManager`/`MachineObject` model the toolheads, AMS units, and filament slots of a connected
printer and drive the device-control UI from that model. The model represents the counts as
device-reported runtime values rather than compile-time caps, so a printer with an arbitrary number
of toolheads, several AMS units, and a non-uniform number of slots per unit is handled by the same
code paths. The printer agent is responsible for translating its printer's state into the shared
JSON dialect this model consumes; the agent boundary is described in
[printer-agent.md](printer-agent.md), and this document describes the dialect and the model.
## Model layout
`MachineObject` owns the device subsystems that this document covers:
- `DevExtderSystem` — the toolheads (extruders) and their per-toolhead filament/temperature state.
- `DevFilaSystem` — the AMS units (`DevAms`) and their trays (`DevAmsTray`).
- `DevNozzleSystem` — the nozzles and, on rack printers, `DevNozzleRack`.
- `DevFilaSwitch` — a filament switch that can feed several AMS units to more than one extruder.
Each subsystem exposes its own count — `DevExtderSystem::GetTotalExtderCount()`,
`DevFilaSystem::GetAmsCount()`, `DevAms::GetSlotCount()` — and the rest of the application derives
its layout from those values rather than from fixed assumptions.
## Wire dialect
The dialect is the Bambu-shaped JSON that `DeviceManager` and `MachineObject` already consume. An
agent whose printer speaks something else is expected to translate into it; the agent is not free
to invent a new shape. Two representations coexist for extruders, and one for AMS/slots.
### Extruders
The generic representation is `print.device.extruder`, parsed by
`ExtderSystemParser::ParseV2_0` (`DevExtruderSystem.cpp`). It has a packed `state` integer and an
`info` array with one object per toolhead:
```text
device.extruder.state packed integer
bits 0..3 total extruder count
bits 4..7 current extruder id
bits 8..11 target extruder id
bits 12..14 switch state
bits 15..18 currently loading extruder id
bit 19 busy for loading
device.extruder.info[] one entry per toolhead
id extruder id
filam_bak array of backup-group bits
info bit 1 has filament, bit 2 buffer has filament, bit 3 nozzle present
temp bits 0..15 current temperature, bits 16..31 target temperature
spre slot_id bits 0..7, ams_id bits 8..15 (previous)
snow same packing (current)
star same packing (target)
stat bit 0..15 AMS status, bits 16..31 RFID status
hnow current nozzle id
```
The legacy single/dual representation is the pair of scalar fields `nozzle_temper` /
`nozzle_target_temper`, plus the `print.ams.tray_tar` / `tray_now` tray pointer, parsed by
`ExtderSystemParser::ParseV1_0`. That parser is a fallback and only fills the main extruder when the
reported toolhead count is one.
Physical extruder ids are fixed (`MAIN_EXTRUDER_ID = 0`, `DEPUTY_EXTRUDER_ID = 1`). Bambu printers
present the two toolheads as a left/right pair and invert the physical-to-logical mapping; generic
printers use the toolhead id itself as the logical id. `DevNozzle::GetLogicExtruderId()` /
`GetExtruderId()` centralise that distinction.
### AMS units and slots
AMS units arrive as `print.ams.ams[]` and are parsed by `DevFilaSystemParser::ParseV1_0`. Each unit
carries an `id` and an `info` bitfield:
```text
info bits 0..3 type: 0 dummy, 1 AMS, 2 AMS-Lite, 3 N3F, 4 N3S, 5 AMS-Lite-mixed (N9)
info bits 8..11 bound extruder id (0xE marks a switch-bound unit)
info bits 24..27 switch inlet when the unit is switch-bound
```
`DevAmsType` (`DevDefs.h`) enumerates the resulting unit kinds: `EXT_SPOOL`, `AMS`, `AMS_LITE`,
`N3F`, `N3S`, and the `AMS_LITE_MIXED` N9 variant. `AMS_LITE_MIXED` reports itself as `AMS_LITE` to
generic callers; code that needs the distinction uses `IsAmsLiteMixed()`.
A unit whose bound-extruder nibble is `0xE` is switch-bound: it is kept only when a `DevFilaSwitch`
is installed, in which case its extruder id is pinned to the main extruder and its binding set
becomes `{0, 1}`; otherwise the unit is dropped from the AMS list.
Each unit owns a map of `DevAmsTray` keyed by the tray id from the payload. The slot count is a
property of the unit kind and the reported trays:
- `AMS`, `AMS_LITE`, and `N3F` report four slots on Bambu printers, matching the firmware contract;
- `N3S` reports one slot;
- `EXT_SPOOL` and any non-Bambu unit report the number of trays actually present.
The tray ids are the payload's slot indices; they are expected to be unique, 0-based, and contiguous
within a unit, because the generic tray-index mapping below is cumulative.
Bulk/extended spools are carried by `print.vir_slot`, which `DeviceManager` parses into
`MachineObject::vt_slot`. Two ids are fixed: `VIRTUAL_TRAY_MAIN_ID = 255` (extruder 0) and
`VIRTUAL_TRAY_DEPUTY_ID = 254` (extruder 1); the id convention is `vt_id = 255 - extruder_id`, so
further extruders use 253, 252, … . The `vir_slot` parser recognises the 255/254 pair; the agent
filament descriptor path `DevFilaSystemParser::ParseAgentFilament` is the entry that stores a fuller
descending set in `vt_slot`.
## Mapping
Several subsystems relate AMS units, trays, and extruders, and more than one place derives a tray
index. The Bambu mapping path (`DevMappingUtil`) computes `ams_id * 4 + slot_id` and knows only the
Bambu unit kinds; `DevFilaSystem` provides the device model's own mapping below. The two agree for
Bambu units and diverge for a non-Bambu unit whose slot count is not four.
### AMS id to extruder id
`DevFilaSystem::GetExtruderIdByAmsId()` resolves an AMS id to the extruder it feeds:
- an AMS unit returns its bound extruder (`DevAms::GetExtruderId()`);
- a virtual tray returns `VIRTUAL_TRAY_MAIN_ID - vt_id`;
- Bambu's virtual AMS ids map to the main/deputy extruder.
A unit may be bound to more than one extruder when a `DevFilaSwitch` feeds it; the binding set
(`DevAms::m_binded_extruder_set`) and switch inlet are read by switch-aware code while the
single-extruder id stays pinned for legacy callers.
### Tray index
`DevFilaSystem::GetTrayIndexMap()` maps a global tray index to an `(ams_id, slot_id)` pair and is
used for backup-slot translation, calibration addressing, and the mapping popups.
- Bambu AMS: `ams_id * 4 + slot_id`; N3S: the AMS id; AMS-Lite-mixed (N9): `24 + slot_id`.
- Generic (non-Bambu): a running lane index — the count of trays in preceding units plus the slot
id. This depends on each unit's tray ids being 0-based and contiguous.
### Virtual-slot recognition
`devPrinterUtil::IsVirtualSlot()` decides whether an id denotes a virtual tray. On Bambu printers it
is the fixed pair `{255, 254}`. On generic printers it is the descending range
`[255 - count + 1, 255]`, where `count` is the selected printer preset's extruder count. The preset
is expected to match the connected device; when the two disagree the virtual range is wrong, which
is why a mismatch is reported rather than silently accepted.
## Device-control UI
The device-control widgets follow the same device-reported counts.
- `AMSModel` (`AMSItem.hpp`) mirrors `DevAmsType` numerically: `EXT_AMS`, `GENERIC_AMS`, `AMS_LITE`,
`N3F_AMS`, `N3S_AMS`. A plain `AMS` maps to `GENERIC_AMS`.
- On non-Bambu printers `use_generic_ams_layout()` routes `GENERIC_AMS` units through a variable-lane
rendering that draws one lane per reported tray; Bambu keeps its fixed four-slot rendering.
- `AMSControl` picks its layout by toolhead count, not vendor: `CreateAmsSingleNozzle` for one
toolhead, `CreateAmsDoubleNozzle` for two, and `CreateAmsMultiNozzle` (one preview and one AMS
simplebook per toolhead) for three or more. A two-toolhead generic printer therefore keeps the
legacy left/right presentation; that is deliberate.
- The status panel's `ExtruderImage` renders one per-toolhead state per nozzle and is resized to
`GetTotalExtderCount()`. Non-Bambu printers choose the active toolhead through
`m_generic_nozzle_selector` (shown when more than one toolhead exists); Bambu keeps its left/right
`m_nozzle_btn_panel`. Nozzle temperature controls are created on demand per toolhead.
## Constraints
- **Single dialect.** The agent translates its protocol into this JSON; the model does not learn
vendor protocols. Extending the model with a new unit kind or field means extending the dialect.
- **Agent-produced counts.** Toolhead, AMS, and slot counts come from the device payload. Nothing
caps them at two toolheads or four slots except the Bambu contract described above.
- **Extruder dialect invariants.** `device.extruder.state`'s count field must equal the length of
`info[]`, and `info[]` must be ordered by extruder id with `id` equal to the array index: the
parser places toolheads by array position while `GetExtderById()` indexes by id.
- **One filament road per toolhead.** Each toolhead renders a single AMS filament road rather than an
independent per-toolhead road state. A generic scaffold that allowed the latter was removed as
unused; the one-extruder-per-toolhead road is the intended model.
- **Preset/device agreement.** The generic layout and virtual-slot range derive their count from the
selected printer preset. A printer preset must therefore declare the same number of
`nozzle_diameter` entries as the device has toolheads. A mismatch is surfaced only as a log warning
(`StatusPanel::check_extruder_count_mismatch()`), deliberately log-only, because the sidebar and
extruder logic would otherwise silently disagree.
- **Bambu compatibility.** Bambu-specific presentation (left/right pair, fixed 4-slot units, fixed
virtual ids, physical/logical inversion) is preserved behind the vendor check. Generic paths do
not alter it.
- **Tray-index invariant.** The generic tray-index map is cumulative, so payload tray ids must be
unique, 0-based, and contiguous per unit. A malformed id is a producer error.
- **Protocol markers.** The dialect has no neutral equivalent for some Bambu state, so agents that
lack it send empty `print.cfg`, `print.fun`, `print.aux`, and `print.stat`. Their presence selects
the new-protocol parse path; they are compatibility markers, not feature switches.
## Main implementation locations
- [`DevExtruderSystem`](../../src/slic3r/GUI/DeviceCore/DevExtruderSystem.h) — toolhead model and the
`device.extruder` parser
- [`DevFilaSystem`](../../src/slic3r/GUI/DeviceCore/DevFilaSystem.h) — AMS/tray model, the AMS parser,
and the mapping helpers
- [`DevDefs.h`](../../src/slic3r/GUI/DeviceCore/DevDefs.h) — `DevAmsType`, extruder ids, and virtual
tray ids
- [`DeviceManager.cpp`](../../src/slic3r/GUI/DeviceManager.cpp) — message dispatch, `vir_slot`
parsing, and device state assembly
- [`AMSControl.cpp`](../../src/slic3r/GUI/Widgets/AMSControl.cpp) — per-toolhead AMS panes
(`CreateAmsMultiNozzle`) and the generic layout
- [`AMSItem.hpp`](../../src/slic3r/GUI/Widgets/AMSItem.hpp) — `AMSModel` and the variable-lane AMS
rendering
- [`StatusPanel.cpp`](../../src/slic3r/GUI/StatusPanel.cpp) — `ExtruderImage`, the toolhead selector,
and per-toolhead temperature controls
- [`MoonrakerPrinterAgent.cpp`](../../src/slic3r/Utils/MoonrakerPrinterAgent.cpp) — producer example
(AMS payload and the `device.extruder` encoding)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1 +1 @@
<?xml version="1.0" encoding="UTF-8"?><svg id="a" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 15"><rect x="1.5" y="3.5" width="12" height="8" rx="1" ry="1" style="fill:none; stroke:#fefefe; stroke-linecap:round; stroke-linejoin:round;"/><path d="M3,5h1v1h-1Z M5,5h1v1h-1Z M7,5h1v1h-1Z M9,5h1v1h-1Z M11,5h1v1h-1Z M4,7h1v1h-1Z M6,7h1v1h-1Z M8,7h1v1h-1Z M10,7h1v1h-1Z M5,9h5v1h-5Z" style="fill:#fefefe;"/></svg>
<?xml version="1.0" encoding="UTF-8"?><svg id="a" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 15"><rect x="7" y="12" width="1" height="1" style="fill:#fefefe;"/><path d="M4.5,5.5c0-1.71,1.43-3.09,3.16-3,1.62.08,2.84,1.54,2.84,3.17h0c0,.61-.25,1.2-.69,1.62l-2.31,2.24v.97" style="fill:none; stroke:#fefefe; stroke-linecap:round; stroke-linejoin:round;"/></svg>

Before

Width:  |  Height:  |  Size: 415 B

After

Width:  |  Height:  |  Size: 366 B

@@ -592,10 +592,6 @@
"name": "SUNLU PETG @base",
"sub_path": "filament/SUNLU/SUNLU PETG @base.json"
},
{
"name": "School House Spools PETG @base",
"sub_path": "filament/SchoolHouseSpools/School House Spools PETG @base.json"
},
{
"name": "eSUN PETG @base",
"sub_path": "filament/eSUN/eSUN PETG @base.json"
@@ -1100,10 +1096,6 @@
"name": "SUNLU Wood PLA @base",
"sub_path": "filament/SUNLU/SUNLU Wood PLA @base.json"
},
{
"name": "School House Spools PLA @base",
"sub_path": "filament/SchoolHouseSpools/School House Spools PLA @base.json"
},
{
"name": "Valment PLA @base",
"sub_path": "filament/Valment/Valment PLA @base.json"
@@ -2268,10 +2260,6 @@
"name": "SUNLU PETG @System",
"sub_path": "filament/SUNLU/SUNLU PETG @System.json"
},
{
"name": "School House Spools PETG @System",
"sub_path": "filament/SchoolHouseSpools/School House Spools PETG @System.json"
},
{
"name": "eSUN PETG @System",
"sub_path": "filament/eSUN/eSUN PETG @System.json"
@@ -3824,10 +3812,6 @@
"name": "SUNLU Wood PLA @System",
"sub_path": "filament/SUNLU/SUNLU Wood PLA @System.json"
},
{
"name": "School House Spools PLA @System",
"sub_path": "filament/SchoolHouseSpools/School House Spools PLA @System.json"
},
{
"name": "Valment PLA @System",
"sub_path": "filament/Valment/Valment PLA @System.json"
@@ -1,18 +0,0 @@
{
"type": "filament",
"name": "School House Spools PETG @System",
"inherits": "School House Spools PETG @base",
"from": "system",
"setting_id": "RSu2orfhR8ktT36h",
"instantiation": "true",
"filament_max_volumetric_speed": [
"13"
],
"filament_long_retractions_when_cut": [
"1"
],
"filament_retraction_distances_when_cut": [
"18"
],
"compatible_printers": []
}
@@ -1,80 +0,0 @@
{
"type": "filament",
"name": "School House Spools PETG @base",
"inherits": "fdm_filament_pet",
"from": "system",
"filament_id": "OFnaCGQ9",
"instantiation": "false",
"cool_plate_temp": [
"0"
],
"cool_plate_temp_initial_layer": [
"0"
],
"eng_plate_temp": [
"70"
],
"eng_plate_temp_initial_layer": [
"70"
],
"fan_cooling_layer_time": [
"30"
],
"fan_max_speed": [
"40"
],
"fan_min_speed": [
"10"
],
"filament_cost": [
"16.00"
],
"filament_density": [
"1.25"
],
"filament_flow_ratio": [
"0.95"
],
"filament_max_volumetric_speed": [
"8"
],
"filament_multitool_ramming_flow": [
"8"
],
"filament_vendor": [
"School House Spools"
],
"hot_plate_temp": [
"70"
],
"hot_plate_temp_initial_layer": [
"70"
],
"nozzle_temperature": [
"252"
],
"nozzle_temperature_initial_layer": [
"252"
],
"nozzle_temperature_range_high": [
"270"
],
"nozzle_temperature_range_low": [
"230"
],
"overhang_fan_speed": [
"90"
],
"overhang_fan_threshold": [
"10%"
],
"slow_down_layer_time": [
"12"
],
"textured_plate_temp": [
"70"
],
"textured_plate_temp_initial_layer": [
"70"
]
}
@@ -1,18 +0,0 @@
{
"type": "filament",
"name": "School House Spools PLA @System",
"inherits": "School House Spools PLA @base",
"from": "system",
"setting_id": "3rHJk6SVAvFzyHI0",
"instantiation": "true",
"filament_max_volumetric_speed": [
"21"
],
"filament_long_retractions_when_cut": [
"1"
],
"filament_retraction_distances_when_cut": [
"18"
],
"compatible_printers": []
}
@@ -1,35 +0,0 @@
{
"type": "filament",
"name": "School House Spools PLA @base",
"inherits": "fdm_filament_pla",
"from": "system",
"filament_id": "OFHzwmT9",
"instantiation": "false",
"filament_cost": [
"17.00"
],
"filament_density": [
"1.26"
],
"filament_flow_ratio": [
"0.98"
],
"filament_max_volumetric_speed": [
"12"
],
"filament_vendor": [
"School House Spools"
],
"filament_scarf_seam_type": [
"none"
],
"filament_scarf_height": [
"10%"
],
"filament_scarf_gap": [
"0%"
],
"filament_scarf_length": [
"10"
]
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "RatRig",
"version": "02.04.00.07",
"version": "02.04.00.06",
"force_update": "0",
"description": "RatRig configurations",
"machine_model_list": [
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -107,7 +107,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -107,7 +107,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -107,7 +107,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -106,7 +106,7 @@
"z_hop": [
"0.2"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single] TOTAL_LAYER_COUNT={total_layer_count} X0={first_layer_print_min[0]} Y0={first_layer_print_min[1]} X1={first_layer_print_max[0]} Y1={first_layer_print_max[1]}",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n_ON_LAYER_CHANGE LAYER={layer_num + 1}",
"change_filament_gcode": "M600",
@@ -131,7 +131,7 @@
"bed_exclude_area": [
"0x0"
],
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] EXTRUDER_OTHER_LAYER_TEMP=[nozzle_temperature] BED_TEMP=[bed_temperature_initial_layer_single]",
"machine_start_gcode": "START_PRINT EXTRUDER_TEMP=[nozzle_temperature_initial_layer] BED_TEMP=[bed_temperature_initial_layer_single]",
"machine_end_gcode": "END_PRINT",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_z]",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n",
-957
View File
@@ -1,957 +0,0 @@
# /// script
# requires-python = ">=3.12"
#
# [tool.orcaslicer.plugin]
# id = "preset-update-demo"
# name = "Preset Update Demo"
# description = "Edits any setting of the currently edited process, printer, or filament preset through the preset host API."
# author = "OrcaSlicer contributors"
# version = "0.2.0"
# type = "script"
# ///
"""Preset Update Demo — edit any setting of the current preset from a plugin window.
Install this file in the local ``orca_plugins`` directory, enable the plugin, then run
"Preset Update Demo" from the Plugins dialog. The window lists every setting of the
preset the matching settings tab is editing right now — process, printer, or filament —
with its current serialized value, and writes a value back through
``orca.host.preset.<type>.update(...)``.
Process and printer each have one edited preset, taken from
``current_process_preset()`` / ``current_printer_preset()``. Filament presets are
addressed by slot instead: the window reads one preset per slot from
``current_filament_presets()`` (slot numbers are one-based, matching Orca's labels),
shows the selected slot's preset, and writes through
``orca.host.preset.filament.update(slot, key, value)``.
Any assigned slot can be edited: the backend selects that slot's preset through Orca's
normal preset selection before it writes, so applying can switch the filament tab and Orca
may ask about unsaved changes first. Only an empty slot, whose mount resolves to no preset,
is unavailable — the window says so instead of offering an edit. A slot whose preset is not
the one the filament settings already have open gets an informational note that applying
will switch to it; it is never presented as a refusal. Two slots that mount the same preset
are one preset, so editing through either of them changes both; the window marks those
slots and says which they are.
Every row is one ``config_keys()`` entry carrying ``config_value(key)``.
What ``update()`` does, and what it does not:
* it runs the same validation and UI update path as editing the setting by hand, so
the change lands in the preset the tab is editing and is never written to disk here
— the preset shows as modified in OrcaSlicer once it differs from the saved one;
* it accepts only settings of that preset category. A key that belongs to another
category, or a value the setting would reject, raises an error and writes nothing;
* it is refused when the selected printer's technology does not use that tab (the
print and filament tabs do nothing under SLA), so this demo covers the three FFF
categories only;
* a setting whose page has not been built yet still runs its owning settings group's
checks and callbacks; behavior that requires an actual widget (such as widget-specific
parsing or clamping) only runs when the field exists;
* on a filament slot it selects that slot's preset first, so Orca may prompt about
unsaved changes in the filament tab before the value is written.
Values are OrcaSlicer's serialized config syntax — the same text a preset file stores —
so numbers are plain, percentages keep their ``%``, booleans are ``1``/``0``, choices use
the setting's internal key, and lists are semicolon-separated.
"""
import orca
# The three preset categories the main tabs edit. Each key is both the value the page
# sends and the attribute name on orca.host.preset that carries the matching editor.
KINDS = (
{"kind": "process", "label": "Process"},
{"kind": "printer", "label": "Printer"},
{"kind": "filament", "label": "Filament"},
)
KIND_KEYS = {item["kind"] for item in KINDS}
def _editor(kind):
"""The host.PresetEditor for a category (orca.host.preset.process / printer).
Filament is not reached through this helper: it is addressed by slot, so it calls
orca.host.preset.filament.update(slot, key, value) directly.
"""
return getattr(orca.host.preset, kind)
def _current_preset(bundle, kind):
"""The single preset the matching settings tab edits right now, as a host.Preset.
Only the process and printer categories have one such preset; filament presets are
addressed by slot instead (see _slot_presets).
"""
if kind == "process":
return bundle.current_process_preset()
return bundle.current_printer_preset()
def _slot_presets(bundle):
"""The filament preset mounted in each slot, in slot order; a slot may be None."""
return list(bundle.current_filament_presets())
def _preset_is_open(preset, edited):
"""Whether this slot's preset is the one the filament settings already have open.
A slot with an assigned preset can be edited either way: applying to another slot makes
the backend select that slot's preset first. This only distinguishes the slot that
switches nothing from the ones that will switch the filament tab.
"""
return preset is not None and preset.name == edited.name
def _filament_slots(presets, edited):
"""One entry per mounted slot: its one-based number, preset name, and open flag.
The number is the slot label Orca shows; the name is None for a slot that mounts no
preset, which is the only kind that cannot be edited.
"""
return [
{
"slot": index + 1,
"name": None if preset is None else preset.name,
"open": _preset_is_open(preset, edited),
}
for index, preset in enumerate(presets)
]
def _as_slot(value):
"""A requested slot as an int, or None when it is not a whole number."""
if isinstance(value, bool):
return None
if isinstance(value, int):
return value
if isinstance(value, float) and value.is_integer():
return int(value)
return None
def _clamp_slot(slot, count):
"""The slot to display: the requested one, kept inside the available range."""
if count <= 0:
return 0
number = _as_slot(slot)
if number is None or number < 1:
return 1
return number if number <= count else count
def _parse_slot(slot, count):
"""Validate a requested filament slot against the mounted slots (one-based)."""
if count == 0:
raise RuntimeError("No filament slots are mounted")
number = _as_slot(slot)
if number is None:
raise RuntimeError("A filament slot number is required")
if number < 1 or number > count:
raise RuntimeError("Filament slot %d is out of range (1-%d)" % (number, count))
return number
def _rows(preset):
"""Every setting of the preset, sorted by key, as [{k, v}].
config_value() returns None for a key the preset does not carry; the page shows
those as empty rather than "None".
"""
rows = []
for key in sorted(preset.config_keys()):
value = preset.config_value(key)
rows.append({"k": key, "v": "" if value is None else str(value)})
return rows
def _state(bundle, kind, slot, message="", error=""):
"""The payload the page renders: shown preset, rows, slots, result line."""
payload = {"command": "state", "kind": kind, "message": message, "error": error}
if kind == "filament":
presets = _slot_presets(bundle)
edited = bundle.filaments.edited_preset()
effective = _clamp_slot(slot, len(presets))
preset = None if effective == 0 else presets[effective - 1]
payload["slots"] = _filament_slots(presets, edited)
payload["slot"] = effective
# An empty slot has nothing to edit; any assigned slot is editable, and one that is
# not already open makes the backend select it first.
payload["assigned"] = preset is not None
payload["switches"] = preset is not None and not _preset_is_open(preset, edited)
payload["edited_name"] = edited.name
else:
preset = _current_preset(bundle, kind)
payload["preset"] = None if preset is None else {
"name": preset.name,
"is_dirty": bool(preset.is_dirty),
"is_system": bool(preset.is_system),
}
payload["rows"] = [] if preset is None else _rows(preset)
return payload
def _apply(kind, key, value, slot=None):
"""Set one setting of the preset the page is showing, through the host API.
A filament preset is addressed by slot number; process and printer each resolve
their single edited preset themselves, so no slot is passed to them.
"""
if kind == "filament":
orca.host.preset.filament.update(slot, key, value)
return
_editor(kind).update(key, value)
PAGE = r"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
:root {
--bg: var(--orca-bg, #fafafa);
--fg: var(--orca-fg, #1b1e23);
--muted: var(--orca-muted, #6b7280);
--border: var(--orca-border, #dadee3);
--accent: var(--orca-accent, #0e7c86);
--accent-fg: var(--orca-accent-fg, #ffffff);
--ui: var(--orca-font, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif);
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
--surface: rgba(127, 127, 127, .09);
}
@media (prefers-color-scheme: dark) {
:root {
--bg: var(--orca-bg, #23262a);
--fg: var(--orca-fg, #e6e8ea);
--muted: var(--orca-muted, #9aa1a9);
--border: var(--orca-border, #383c42);
}
}
* { box-sizing: border-box; }
html, body { height: 100%; }
body {
margin: 0; background: var(--bg); color: var(--fg);
font: 13px/1.45 var(--ui);
display: flex; flex-direction: column; overflow: hidden;
}
button { font: inherit; cursor: pointer; }
:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
/* header ------------------------------------------------------------- */
header {
flex: none; display: flex; align-items: center; gap: 10px;
padding: 9px 14px; border-bottom: 1px solid var(--border);
}
.logo { color: var(--accent); font-size: 15px; line-height: 1; }
h1 { margin: 0; font-size: 14px; font-weight: 650; letter-spacing: .01em; }
.seg {
display: flex; gap: 2px; margin-left: auto; padding: 2px;
border: 1px solid var(--border); border-radius: 9px; background: var(--surface);
}
.seg button {
border: 0; background: transparent; color: var(--muted);
padding: 4px 13px; border-radius: 7px;
transition: background .15s ease, color .15s ease;
}
.seg button:hover { color: var(--fg); }
.seg button[aria-pressed="true"] { background: var(--accent); color: var(--accent-fg); }
.iconbtn {
width: 28px; height: 28px; border: 1px solid var(--border); border-radius: 7px;
background: transparent; color: var(--fg); display: grid; place-items: center;
font-size: 13px; transition: background .15s ease;
}
.iconbtn:hover:enabled { background: var(--surface); }
.iconbtn:disabled { opacity: .5; }
/* preset bar --------------------------------------------------------- */
.presetbar {
flex: none; display: flex; align-items: center; gap: 8px;
padding: 7px 14px; border-bottom: 1px solid var(--border); font-size: 12px;
}
.presetbar .name {
font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
max-width: 60%;
}
.spacer { flex: 1; }
.tag {
border: 1px solid var(--border); color: var(--muted); border-radius: 999px;
padding: 1px 8px; font-size: 11px; white-space: nowrap;
}
.tag.on { border-color: transparent; background: var(--accent); color: var(--accent-fg); }
/* filament slots ----------------------------------------------------- */
.slotbar { flex: none; padding: 7px 14px 8px; border-bottom: 1px solid var(--border); }
.slotrow { display: flex; align-items: center; gap: 9px; min-width: 0; }
.slotlabel {
flex: none; font-size: 11px; letter-spacing: .06em; text-transform: uppercase;
color: var(--muted);
}
.slots { flex: 1; min-width: 0; display: flex; flex-wrap: wrap; gap: 6px;
max-height: 84px; overflow-y: auto; }
.chip {
display: inline-flex; align-items: center; gap: 6px; flex: none; max-width: 190px;
padding: 2px 10px 2px 3px; border: 1px solid var(--border); border-radius: 999px;
background: transparent; color: var(--fg);
transition: background .15s ease, color .15s ease, border-color .15s ease;
}
.chip:hover { background: var(--surface); }
.chip .n {
flex: none; min-width: 19px; height: 19px; padding: 0 4px; border-radius: 999px;
display: grid; place-items: center; background: var(--surface); color: var(--muted);
font-size: 11px; font-variant-numeric: tabular-nums;
}
/* the slot whose preset the filament settings already have open, so applying switches nothing */
.chip.open .n { box-shadow: inset 0 0 0 1px var(--accent); color: var(--fg); }
.chip .s {
min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
font-size: 11px; color: var(--muted);
}
.chip[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: var(--accent-fg); }
.chip[aria-pressed="true"] .n {
background: rgba(255, 255, 255, .22); color: var(--accent-fg); box-shadow: none;
}
.chip[aria-pressed="true"] .s { color: var(--accent-fg); }
/* a slot that mounts the preset the page is showing: editing either changes both */
.chip.linked::after {
content: ""; flex: none; width: 5px; height: 5px;
border-radius: 50%; background: var(--accent);
}
.slotnote {
margin-top: 7px; padding-left: 8px; border-left: 2px solid var(--accent);
font-size: 11px; line-height: 1.5; color: var(--muted);
}
.slotnote:empty { display: none; }
/* panes -------------------------------------------------------------- */
main { flex: 1; display: flex; min-height: 0; }
.list-pane {
flex: none; width: 45%; min-width: 250px; min-height: 0;
display: flex; flex-direction: column; border-right: 1px solid var(--border);
}
.search {
flex: none; display: flex; align-items: center; gap: 8px;
padding: 8px 10px; border-bottom: 1px solid var(--border);
}
.search input {
flex: 1; min-width: 0; font: inherit; color: var(--fg); background: var(--bg);
border: 1px solid var(--border); border-radius: 7px; padding: 4px 9px;
}
.rows { flex: 1; min-height: 0; overflow-y: auto; padding: 3px 0; }
.row {
display: flex; align-items: baseline; gap: 8px; width: 100%;
padding: 5px 10px; text-align: left; border: 0; border-left: 3px solid transparent;
background: transparent; color: var(--fg);
}
.row:hover { background: var(--surface); }
.row[aria-selected="true"] { background: var(--surface); border-left-color: var(--accent); }
.row .k {
flex: 1; min-width: 0; font-family: var(--mono); font-size: 12px;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.row .v {
flex: none; max-width: 40%; font-family: var(--mono); font-size: 11px;
color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.row .dot {
flex: none; align-self: center; width: 6px; height: 6px; border-radius: 50%;
background: var(--accent); visibility: hidden;
}
.row.changed .dot { visibility: visible; }
@keyframes flash {
0% { box-shadow: inset 0 0 0 2px var(--accent); }
100% { box-shadow: inset 0 0 0 2px transparent; }
}
.row.flash { animation: flash .7s ease-out; }
@media (prefers-reduced-motion: reduce) {
.row.flash { animation: none; }
}
.empty { color: var(--muted); padding: 14px 12px; }
.nil { font-style: italic; opacity: .75; }
/* editor ------------------------------------------------------------- */
.edit-pane {
flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 9px;
padding: 12px 14px; overflow-y: auto;
}
.edit-key { font-family: var(--mono); font-size: 13px; font-weight: 600; overflow-wrap: anywhere; }
.lbl { font-size: 11px; letter-spacing: .06em; text-transform: uppercase; color: var(--muted); }
.current {
margin: 0; max-height: 108px; overflow: auto;
font-family: var(--mono); font-size: 12px;
background: var(--surface); border: 1px solid var(--border); border-radius: 7px;
padding: 7px 10px; white-space: pre-wrap; overflow-wrap: anywhere;
}
textarea {
width: 100%; min-height: 74px; resize: vertical;
font-family: var(--mono); font-size: 12px; color: var(--fg); background: var(--bg);
border: 1px solid var(--border); border-radius: 7px; padding: 7px 10px;
}
.actions { display: flex; gap: 8px; align-items: center; }
button.primary {
padding: 5px 14px; border-radius: 7px; border: 1px solid var(--accent);
background: var(--accent); color: var(--accent-fg);
}
button.ghost {
padding: 5px 12px; border-radius: 7px; border: 1px solid var(--border);
background: transparent; color: var(--fg);
}
button.primary:disabled, button.ghost:disabled { opacity: .5; cursor: default; }
button.primary:hover:enabled { filter: brightness(1.08); }
button.ghost:hover:enabled { background: var(--surface); }
.notice {
padding: 8px 11px; border: 1px solid var(--border); border-left: 3px solid var(--accent);
border-radius: 7px; background: var(--surface);
font-size: 12px; line-height: 1.5; color: var(--muted);
}
.notice b { color: var(--fg); font-weight: 600; }
.notice:empty { display: none; }
.syntax {
margin-top: 2px; padding: 9px 11px; border: 1px solid var(--border);
border-left: 3px solid var(--accent); border-radius: 7px;
font-size: 12px; line-height: 1.55; color: var(--muted);
}
.syntax b { color: var(--fg); font-weight: 600; }
.syntax code { font-family: var(--mono); font-size: 11.5px; color: var(--fg); }
/* status ------------------------------------------------------------- */
footer {
flex: none; min-height: 30px; padding: 7px 14px;
border-top: 1px solid var(--border); font-size: 12px; color: var(--muted);
}
footer.ok { color: #0f8a5f; }
footer.err { color: #c8382c; }
</style>
</head>
<body>
<header>
<span class="logo">◈</span>
<h1>Preset update</h1>
<div class="seg" id="seg"></div>
<button class="iconbtn" id="refresh" title="Reload the current values">⟳</button>
<button class="iconbtn" id="close" title="Close">✕</button>
</header>
<div class="presetbar">
<span class="name" id="pname">Loading…</span>
<span id="ptag"></span>
<span class="spacer"></span>
<span class="tag" id="pcount">0 settings</span>
</div>
<div class="slotbar" id="slotbar" hidden>
<div class="slotrow">
<span class="slotlabel">Filament slots</span>
<div class="slots" id="slots"></div>
</div>
<div class="slotnote" id="slotnote"></div>
</div>
<main>
<section class="list-pane">
<div class="search">
<input id="q" type="search" placeholder="Search settings…" autocomplete="off" spellcheck="false">
<span class="tag" id="qcount">0</span>
</div>
<div class="rows" id="rows"></div>
</section>
<section class="edit-pane">
<div class="edit-key" id="ekey">Select a setting</div>
<div class="lbl">Current value</div>
<pre class="current" id="ecur">—</pre>
<label class="lbl" for="evalue">New value</label>
<textarea id="evalue" spellcheck="false" autocomplete="off"
placeholder="Serialized value" disabled></textarea>
<div class="notice" id="notice"></div>
<div class="actions">
<button class="primary" id="apply" disabled>Apply</button>
<button class="ghost" id="reset" disabled>Reset to current</button>
</div>
<div class="syntax">
<b>Values use OrcaSlicer's serialized config syntax</b> — the same text a preset
file stores. Numbers are plain (<code>0.2</code>, <code>3</code>) and percentages keep
their sign (<code>15%</code>). On/off is <code>1</code> or <code>0</code>. A choice uses
the setting's own key, e.g. <code>grid</code>. Lists are semicolon-separated
(<code>0.4;0.4;0.4</code>, or <code>"#FF0000";"#00FF00"</code>). Text keeps its
escapes, so a line break stays <code>\n</code>. A key that does not belong to this
preset, or a value the setting would reject, comes back as an error and writes
nothing. The edit lands in the preset the tab is editing and stays unsaved.
</div>
</section>
</main>
<footer id="status"></footer>
<script>
'use strict';
const SEG = [['process', 'Process'], ['printer', 'Printer'], ['filament', 'Filament']];
const IDLE = 'Edits apply to the preset shown here and stay unsaved until you save '
+ 'or export it.';
const S = {
kind: 'process',
slot: 1, // selected filament slot (one-based); ignored by the other kinds
slots: [], // [{slot, name, open}] from current_filament_presets()
preset: null,
rows: [],
selected: null,
changed: {}, // "kind/preset/key" -> true, for edits made in this window
pending: null, // {kind, slot, preset, key} of an apply awaiting its reply
error: '', // the last error the plugin reported, if any
assigned: true, // filament only: the shown slot mounts a preset, so it is editable
switches: false, // filament only: applying will select that preset in the filament tab
editedName: null, // filament only: the preset the filament settings have open
busy: true,
filter: '',
statusText: '',
statusCls: '',
};
const $ = id => document.getElementById(id);
const esc = s => String(s == null ? '' : s)
.replace(/[&<>"']/g, c => ({'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'}[c]));
/* ------------------------------------------------------------------ paint */
function paint() {
paintSeg();
const p = S.preset;
const slotTag = S.kind === 'filament' && S.slot
? '<span class="tag">slot ' + S.slot + '</span>' : '';
$('pname').textContent = p ? p.name : (S.busy ? 'Loading…' : 'No preset');
$('pname').title = p ? p.name : '';
$('ptag').innerHTML = slotTag + (p
? '<span class="tag">' + (p.is_system ? 'system' : 'user') + '</span>'
+ (p.is_dirty ? '<span class="tag on">modified</span>' : '<span class="tag">saved</span>')
: '');
$('pcount').textContent = S.rows.length + (S.rows.length === 1 ? ' setting' : ' settings');
$('refresh').disabled = S.busy;
paintSlots();
paintNotice();
renderList();
paintEditor();
paintStatus();
}
function paintSeg() {
// Built once (see buildSeg) so a click never loses focus; only the state is repainted.
document.querySelectorAll('#seg button').forEach(b =>
b.setAttribute('aria-pressed', String(b.dataset.kind === S.kind)));
}
/* the filament slot strip: one chip per mounted slot, shown for filament only */
function paintSlots() {
const show = S.kind === 'filament' && (S.slots.length > 0 || S.busy);
$('slotbar').hidden = !show;
if (!show) { $('slots').innerHTML = ''; $('slotnote').innerHTML = ''; return; }
// Rebuilding the chips drops keyboard focus; put it back on the same slot's chip.
const focused = document.activeElement && document.activeElement.dataset
? document.activeElement.dataset.slot : null;
$('slots').innerHTML = S.slots.map(s => {
const selected = s.slot === S.slot;
const linked = !selected && sharesSelected(s.name);
const label = s.name == null ? '<span class="nil">empty slot</span>' : esc(s.name);
const hint = s.name ? ': ' + s.name : ': no preset';
return '<button type="button" class="chip' + (linked ? ' linked' : '')
+ (s.open ? ' open' : '') + '"'
+ ' data-slot="' + s.slot + '" aria-pressed="' + selected + '"'
+ ' title="' + esc('Filament slot ' + s.slot + hint
+ (s.open ? ' — open in the filament settings' : '')) + '">'
+ '<span class="n">' + s.slot + '</span><span class="s">' + label + '</span></button>';
}).join('');
$('slotnote').innerHTML = shareNote();
if (focused) {
const chip = document.querySelector('#slots .chip[data-slot="' + focused + '"]');
if (chip) chip.focus();
}
}
function slotName(slot) {
const found = S.slots.find(s => s.slot === slot);
return found && found.name ? found.name : null;
}
// Applying selects the slot's preset first, so say when that switches the filament tab. An
// empty slot is the only unavailable one, and it says so instead of offering an edit.
function paintNotice() {
const el = $('notice');
if (S.kind !== 'filament' || S.busy) { el.innerHTML = ''; return; }
// With nothing mounted the list already says so; avoid naming a slot number here.
if (!S.slots.length) { el.innerHTML = ''; return; }
const name = S.preset ? S.preset.name : null;
if (!name) {
el.innerHTML = 'Slot ' + S.slot + ' holds no filament preset. Assign one in the '
+ 'OrcaSlicer filament settings first.';
return;
}
if (!S.switches) { el.innerHTML = ''; return; }
const open = S.editedName
? ', while the filament settings have <b>' + esc(S.editedName) + '</b> open'
: '';
el.innerHTML = 'Slot ' + S.slot + ' uses <b>' + esc(name) + '</b>' + open
+ '. Applying switches the filament tab to <b>' + esc(name) + '</b> first — Orca may '
+ 'ask about unsaved changes there — then sets the value.';
}
function sharesSelected(name) {
const current = slotName(S.slot);
return !!name && !!current && name === current;
}
function listSlots(numbers) {
if (numbers.length === 1) return String(numbers[0]);
return numbers.slice(0, -1).join(', ') + ' and ' + numbers[numbers.length - 1];
}
// Slots mounting the same preset are one preset, so say which slots an edit reaches.
function shareNote() {
const name = slotName(S.slot);
if (!name) return '';
const sharing = S.slots.filter(s => s.name === name).map(s => s.slot);
if (sharing.length < 2) return '';
return 'Slots ' + listSlots(sharing) + ' mount the same filament preset, so an edit '
+ 'here changes every one of them.';
}
function changedKey(presetName, key) {
return S.kind + '/' + (presetName || '?') + '/' + key;
}
function paintStatus() {
const el = $('status');
if (S.statusText) {
el.textContent = S.statusText;
el.className = S.statusCls;
} else if (S.busy) {
el.textContent = 'Working…';
el.className = '';
} else {
el.textContent = IDLE;
el.className = '';
}
}
function setStatus(text, cls) {
S.statusText = text || '';
S.statusCls = cls || '';
paintStatus();
}
function visibleRows() {
const q = S.filter.trim().toLowerCase();
if (!q) return S.rows;
return S.rows.filter(r => r.k.toLowerCase().includes(q) || r.v.toLowerCase().includes(q));
}
function renderList() {
const scroller = $('rows');
const top = scroller.scrollTop;
$('qcount').textContent = String(visibleRows().length);
if (!S.rows.length) {
let text = 'This preset reports no settings.';
if (S.busy) text = 'Loading settings…';
else if (S.error) text = 'These values could not be read — see the message below.';
else if (S.kind === 'filament' && !S.slots.length) text = 'No filament slots are mounted.';
else if (S.kind === 'filament' && !S.preset) text = 'This filament slot has no preset.';
scroller.innerHTML = '<div class="empty">' + text + '</div>';
return;
}
const rows = visibleRows();
if (!rows.length) {
scroller.innerHTML = '<div class="empty">No setting matches “' + esc(S.filter) + '”.</div>';
return;
}
scroller.innerHTML = rows.map(r => {
const value = r.v === '' ? '<span class="nil">empty</span>' : esc(r.v);
return '<button type="button" class="row'
+ (S.changed[changedKey(S.preset && S.preset.name, r.k)] ? ' changed' : '') + '"'
+ ' data-key="' + esc(r.k) + '"'
+ ' aria-selected="' + (r.k === S.selected) + '"'
+ ' title="' + esc(r.k + ' = ' + r.v) + '">'
+ '<span class="k">' + esc(r.k) + '</span>'
+ '<span class="v">' + value + '</span>'
+ '<span class="dot"></span></button>';
}).join('');
scroller.scrollTop = top;
}
function paintEditor() {
const row = S.rows.find(r => r.k === S.selected) || null;
// Every assigned slot is editable now that applying selects the slot's preset first, so
// Apply is off only for an empty slot, a missing selection, or a request in flight.
const selected = !!row && !S.busy;
$('ekey').textContent = row ? row.k : 'Select a setting';
$('ecur').textContent = row ? (row.v === '' ? '(empty)' : row.v) : '—';
$('evalue').disabled = !selected;
$('apply').disabled = !selected || !S.assigned;
$('reset').disabled = !selected;
}
/* --------------------------------------------------------------- actions */
function buildSeg() {
$('seg').innerHTML = SEG.map(([kind, label]) =>
'<button type="button" data-kind="' + kind + '">' + label + '</button>').join('');
}
function selectKey(key) {
S.selected = key;
const row = S.rows.find(r => r.k === key);
$('evalue').value = row ? row.v : '';
// Repaint the rows in place so the scroll position of a long list is kept.
document.querySelectorAll('#rows .row').forEach(el =>
el.setAttribute('aria-selected', String(el.dataset.key === key)));
paintEditor();
}
function switchKind(kind) {
S.kind = kind;
S.selected = null;
S.pending = null;
S.preset = null;
S.rows = [];
S.busy = true;
$('evalue').value = '';
setStatus('', '');
paint();
orca.postMessage({command: 'state', kind: kind, slot: S.slot});
}
// Two slots that mount the same preset show the same settings, so only a switch to a
// different preset drops the current selection and the value being typed.
function selectSlot(slot) {
if (S.busy || slot === S.slot) return;
const same = !!slotName(slot) && slotName(slot) === slotName(S.slot);
S.slot = slot;
S.pending = null;
S.busy = true;
if (!same) {
S.preset = null;
S.rows = [];
S.selected = null;
$('evalue').value = '';
}
setStatus('', '');
paint();
orca.postMessage({command: 'state', kind: S.kind, slot: slot});
}
function reload() {
if (S.busy) return;
S.busy = true;
S.pending = null;
setStatus('', '');
paint();
orca.postMessage({command: 'state', kind: S.kind, slot: S.slot});
}
function applyValue() {
const row = S.rows.find(r => r.k === S.selected);
// Mirror the Apply button: only a missing selection, a request in flight, or an empty
// slot blocks an edit, so Enter cannot send one the button itself would refuse.
if (!row || S.busy || !S.assigned) return;
S.pending = {
kind: S.kind, slot: S.slot,
preset: S.preset ? S.preset.name : null, key: row.k,
};
S.busy = true;
setStatus('', '');
paint();
orca.postMessage({command: 'apply', kind: S.kind, slot: S.slot, key: row.k,
value: $('evalue').value});
}
function flashKey(key) {
document.querySelectorAll('#rows .row').forEach(el => {
if (el.dataset.key !== key) return;
el.classList.remove('flash');
void el.offsetWidth; // restart the animation if it ran on this row already
el.classList.add('flash');
el.addEventListener('animationend', () => el.classList.remove('flash'), {once: true});
});
}
/* ----------------------------------------------------------------- wiring */
buildSeg();
$('seg').addEventListener('click', e => {
const button = e.target.closest('[data-kind]');
if (!button || S.busy || button.dataset.kind === S.kind) return;
switchKind(button.dataset.kind);
});
$('rows').addEventListener('click', e => {
const row = e.target.closest('.row');
if (row && !S.busy) selectKey(row.dataset.key);
});
$('slots').addEventListener('click', e => {
const chip = e.target.closest('[data-slot]');
if (chip && !S.busy) selectSlot(Number(chip.dataset.slot));
});
$('q').addEventListener('input', e => {
S.filter = e.target.value;
renderList();
});
$('apply').addEventListener('click', applyValue);
$('reset').addEventListener('click', () => {
const row = S.rows.find(r => r.k === S.selected);
if (row) $('evalue').value = row.v;
});
$('evalue').addEventListener('keydown', e => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); applyValue(); }
else if (e.key === 'Escape') { e.preventDefault(); $('reset').click(); }
});
$('refresh').addEventListener('click', reload);
$('close').addEventListener('click', () => orca.close());
/* -------------------------------------------------------------- messages */
orca.onMessage(msg => {
if (!msg || msg.command !== 'state') return;
if (msg.kind !== S.kind) return; // a reply for a category we already left
const pending = S.pending;
S.busy = false;
S.pending = null;
S.slots = msg.slots || [];
// Adopt the slot the plugin actually used (it clamps a slot that no longer exists).
if (S.kind === 'filament' && typeof msg.slot === 'number') S.slot = msg.slot;
S.preset = msg.preset || null;
S.rows = msg.rows || [];
S.error = msg.error || '';
// Filament editability is a slot concern; process and printer have a single edited preset.
S.assigned = S.kind === 'filament' ? !!msg.assigned : true;
S.switches = S.kind === 'filament' ? !!msg.switches : false;
S.editedName = S.kind === 'filament' ? (msg.edited_name || null) : null;
if (S.selected && !S.rows.some(r => r.k === S.selected)) S.selected = null;
if (msg.error) {
// Keep the typed value so it can be corrected, and keep the current selection.
setStatus('⚠ ' + msg.error, 'err');
} else {
if (pending) S.changed[changedKey(pending.preset, pending.key)] = true;
setStatus(msg.message || '', msg.message ? 'ok' : '');
}
paint();
if (!msg.error && pending) {
const row = S.rows.find(r => r.k === pending.key);
if (row) { // show the value as the preset now stores it
$('evalue').value = row.v;
flashKey(row.k);
}
}
});
paint();
orca.postMessage({command: 'state', kind: S.kind, slot: S.slot});
</script>
</body>
</html>"""
class PresetUpdateDemo(orca.script.ScriptPluginCapabilityBase):
window = None
kind = "process" # the category the open window is showing, for a re-run refresh
slot = 1 # the filament slot the open window is showing
def get_name(self):
return "Preset update demo"
def execute(self):
try:
if self.window is not None and self.window.is_open():
self._post_state(self.kind, self.slot)
return orca.ExecutionResult.success("Preset update demo refreshed.")
self.window = orca.host.ui.create_window(
title="Preset update demo", html=PAGE, width=820, height=560,
on_message=self.on_message, on_close=self.on_close,
)
return orca.ExecutionResult.success("Preset update demo opened.")
except Exception as error:
message = "Preset update demo failed: %s" % error
orca.host.ui.message(message, title="Preset update demo", buttons="ok", icon="error")
return orca.ExecutionResult.failure(orca.PluginResult.RecoverableError, message)
def on_close(self):
self.window = None
def _post_state(self, kind="process", slot=1, message="", error=""):
try:
payload = _state(orca.host.preset_bundle(), kind, slot, message, error)
except Exception as state_error:
payload = {"command": "state", "kind": kind, "slot": slot, "slots": [],
"assigned": False, "switches": False, "edited_name": None,
"preset": None, "rows": [], "message": message,
"error": str(state_error)}
if self.window is not None and self.window.is_open():
self.window.post(payload)
def on_message(self, message):
kind = "process"
slot = 1
try:
message = message or {}
kind = message.get("kind", "process")
if not isinstance(kind, str) or kind not in KIND_KEYS:
raise RuntimeError("Unknown preset category %r" % (kind,))
self.kind = kind
slot = message.get("slot", 1)
command = message.get("command")
if command == "state":
self.slot = slot
self._post_state(kind, slot)
return
if command == "apply":
key = message.get("key")
value = message.get("value")
if not isinstance(key, str) or not key:
raise RuntimeError("A setting key is required")
if not isinstance(value, str):
raise RuntimeError("A value string is required")
where = ""
if kind == "filament":
presets = _slot_presets(orca.host.preset_bundle())
# Validate the slot strictly: an out-of-range slot must fail loudly
# rather than edit a different filament. A slot with no preset has
# nothing to write, which is the only slot shape the backend refuses.
slot = _parse_slot(slot, len(presets))
if presets[slot - 1] is None:
raise RuntimeError("Filament slot %d has no preset to edit" % slot)
_apply(kind, key, value, slot)
where = " on slot %d" % slot
else:
_apply(kind, key, value)
shown = value if value else "(empty)"
self.slot = slot
self._post_state(
kind, slot,
message='Set %s = "%s"%s. The edit stays in the preset tab until you save it.'
% (key, shown, where),
)
return
raise RuntimeError("Unknown command %r" % (command,))
except Exception as error:
safe_kind = kind if isinstance(kind, str) and kind in KIND_KEYS else "process"
self._post_state(safe_kind, slot, error=str(error))
@orca.plugin
class PresetUpdateDemoPackage(orca.base):
def register_capabilities(self):
orca.register_capability(PresetUpdateDemo)
+16 -8
View File
@@ -4607,6 +4607,16 @@ unsigned int PresetBundle::sync_ams_list(std::vector<std::pair<DynamicPrintConfi
maps.erase(j);
}
}
}
if (is_placeholder) {
// Orca: an empty AMS slot is a placeholder, not a filament - never synthesize a
// preset for it. Kept here only to keep index alignment with ams_infos; the sync
// drops it so no filament slot is created or retained for an empty tray.
ams_filament_presets.push_back("");
ams_filament_colors.push_back("");
ams_filament_color_types.push_back("");
ams_multi_color_filment.push_back({});
} else if (use_map) {
ams_filament_presets.push_back("Generic PLA");//for unknow matieral
auto default_unknown_color = "#CECECE";
ams_filament_colors.push_back(default_unknown_color);
@@ -4615,12 +4625,6 @@ unsigned int PresetBundle::sync_ams_list(std::vector<std::pair<DynamicPrintConfi
filament_multi_color.push_back(default_unknown_color);
}
ams_multi_color_filment.push_back(filament_multi_color);
} else if (is_placeholder) {
// Orca: push placeholders to keep index alignment with ams_infos
ams_filament_presets.push_back("");
ams_filament_colors.push_back("");
ams_filament_color_types.push_back("");
ams_multi_color_filment.push_back({});
}
continue;
}
@@ -4984,6 +4988,10 @@ unsigned int PresetBundle::sync_ams_list(std::vector<std::pair<DynamicPrintConfi
result_multi_colors.push_back(
i < ams_multi_color_filment.size() ? ams_multi_color_filment[i]
: std::vector<std::string>{ams_filament_colors[i]});
} else if (i < ams_infos.size() && ams_infos[i].is_placeholder) {
// Orca: an empty AMS slot is a placeholder, not a filament, so drop it instead of
// keeping or filling a slot for it. The device AMS panel still shows the empty tray.
continue;
} else if (i < exist_presets.size()) {
// Empty tray or beyond tray count: keep existing filament
result_colors.push_back(exist_colors[i]);
@@ -5008,8 +5016,8 @@ unsigned int PresetBundle::sync_ams_list(std::vector<std::pair<DynamicPrintConfi
filament_color_type->values = result_color_types;
this->filament_presets = result_presets;
ams_multi_color_filment = result_multi_colors;
filament_map->values.resize(total, 1);
filament_volume_map->values.resize(total, static_cast<int>(NozzleVolumeType::nvtStandard));
filament_map->values.resize(result_presets.size(), 1);
filament_volume_map->values.resize(result_presets.size(), static_cast<int>(NozzleVolumeType::nvtStandard));
} else {
// BBL: existing wholesale replace
filament_color->values = ams_filament_colors;
+5 -4
View File
@@ -858,10 +858,11 @@ void PrintObject::contour_z()
BOOST_LOG_TRIVIAL(debug) << "Contouring in parallel - start";
TriangleMesh mesh = this->m_model_object->raw_mesh();
// A PrintObject groups the instances that share their whole transformation but the XY shift: an
// instance rotated, scaled or mirrored differently is a PrintObject of its own. So the first
// instance stands for all of them.
const ModelInstance *inst = m_instances.front().model_instance;
if (m_model_object->instances.size() != 1) {
throw RuntimeError("ContourZ: unexpected number of instances");
}
ModelInstance *inst = m_model_object->instances.front();
Point center_offset = this->center_offset();
Geometry::Transformation trans = inst->get_transformation();
+72 -260
View File
@@ -85,96 +85,6 @@ static std::string float_to_string_with_precision(float value, int precision = 3
return stream.str();
}
static std::string colour_to_ams_string(const wxColour& color)
{
char col_buf[10];
sprintf(col_buf, "%02X%02X%02X%02X", (int)color.Red(), (int)color.Green(), (int)color.Blue(), (int)color.Alpha());
return col_buf;
}
static wxColour mix_colour(const wxColour& left, const wxColour& right, double ratio)
{
ratio = std::max(0.0, std::min(1.0, ratio));
auto mix_channel = [ratio](unsigned char l, unsigned char r) {
return static_cast<unsigned char>(std::round(l + (r - l) * ratio));
};
return wxColour(mix_channel(left.Red(), right.Red()),
mix_channel(left.Green(), right.Green()),
mix_channel(left.Blue(), right.Blue()),
mix_channel(left.Alpha(), right.Alpha()));
}
static std::vector<ColorPickerPopup::ColorItem> collect_ams_color_items(DevFilaSystem* fila_system)
{
std::vector<ColorPickerPopup::ColorItem> items;
if (!fila_system) return items;
for (const auto& ams_pair : fila_system->GetAmsList()) {
DevAms* ams = ams_pair.second;
if (!ams) continue;
for (const auto& tray_pair : ams->GetTrays()) {
DevAmsTray* tray = tray_pair.second;
if (!tray || !tray->is_tray_info_ready()) continue;
ColorPickerPopup::ColorItem item;
for (const std::string& col : tray->cols) {
item.colors.emplace_back(DevAmsTray::decode_color(col));
}
if (item.colors.empty() && !tray->color.empty()) {
item.colors.emplace_back(DevAmsTray::decode_color(tray->color));
}
if (item.colors.empty()) continue;
item.ctype = item.colors.size() > 1 ? tray->ctype : 2;
items.emplace_back(std::move(item));
}
}
return items;
}
static std::vector<ColorPickerPopup::ColorItem> collect_preset_color_items(const std::string& filament_id)
{
std::vector<ColorPickerPopup::ColorItem> items;
if (filament_id.empty()) return items;
auto* clr_query = GUI::wxGetApp().get_filament_color_code_query();
if (!clr_query) return items;
auto* agent = wxGetApp().getAgent();
const std::string catalog_id = agent ? agent->from_orca_filament_id(filament_id) : filament_id;
FilamentColorCodes* color_codes = clr_query->GetFilaInfoMap(wxString::FromUTF8(catalog_id));
if (!color_codes || !color_codes->GetFilamentColor2CodeMap()) return items;
std::set<std::string> seen;
for (const auto& color_pair : *color_codes->GetFilamentColor2CodeMap()) {
const FilamentColor& fila_color = color_pair.first;
FilamentColorCode* color_code = color_pair.second;
if (!color_code || fila_color.GetColors().empty()) continue;
ColorPickerPopup::ColorItem item;
item.ctype = fila_color.ColorCount() < 2 ? 2 :
(fila_color.m_color_type == FilamentColor::ColorType::GRADIENT_CLR ? 0 : 1);
item.name = color_code->GetFilaColorName();
std::string key = std::to_string(item.ctype);
for (const wxColour& color : fila_color.GetColors()) {
item.colors.emplace_back(color);
char rgba[9];
std::snprintf(rgba, sizeof(rgba), "%02X%02X%02X%02X",
static_cast<unsigned>(color.Red()), static_cast<unsigned>(color.Green()),
static_cast<unsigned>(color.Blue()), static_cast<unsigned>(color.Alpha()));
key += "|" + std::string(rgba);
}
if (item.colors.empty() || !seen.insert(key).second) continue;
items.emplace_back(std::move(item));
}
return items;
}
AMSMaterialsSetting::AMSMaterialsSetting(wxWindow *parent, wxWindowID id)
: DPIDialog(parent, id, _L("AMS Materials Setting"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX)
, m_color_picker_popup(ColorPickerPopup(this))
@@ -830,19 +740,8 @@ void AMSMaterialsSetting::on_select_ok(wxCommandEvent &event)
nozzle_temp_min.ToLong(&nozzle_temp_min_int);
nozzle_temp_max.ToLong(&nozzle_temp_max_int);
wxColour color = m_clr_picker->m_colour;
std::string tray_color = colour_to_ams_string(color);
std::vector<std::string> tray_colors;
int tray_ctype = 2;
// Only firmware advertising fun2[23] receives the manual multi-color fields.
if (obj->is_support_filament_manual_multi_color) {
for (const wxColour& selected_color : m_clr_picker->m_cols) {
tray_colors.emplace_back(colour_to_ams_string(selected_color));
}
if (tray_colors.empty()) {
tray_colors.emplace_back(tray_color);
}
tray_ctype = tray_colors.size() > 1 ? m_clr_picker->ctype : 2;
}
char col_buf[10];
sprintf(col_buf, "%02X%02X%02X%02X", (int)color.Red(), (int)color.Green(), (int)color.Blue(), (int)color.Alpha());
if (ams_filament_id.empty() || nozzle_temp_min.empty() || nozzle_temp_max.empty() || m_filament_type.empty()) {
BOOST_LOG_TRIVIAL(trace) << "Invalid Setting id";
@@ -861,33 +760,13 @@ void AMSMaterialsSetting::on_select_ok(wxCommandEvent &event)
<< ", tray_info_idx (filament_id) = " << ams_filament_id
<< ", setting_id = " << ams_setting_id
<< ", tray_type = " << m_filament_type
<< ", tray_color = " << tray_color
<< ", tray_color = " << col_buf
<< ", nozzle_temp_min = " << nozzle_temp_min_int
<< ", nozzle_temp_max = " << nozzle_temp_max_int;
// set filament
if (m_is_third) {
obj->command_ams_filament_settings(ams_id, slot_id, ams_filament_id, ams_setting_id, tray_color, m_filament_type, nozzle_temp_min_int, nozzle_temp_max_int,
tray_colors, tray_ctype);
// Refresh the edited tray immediately while its MQTT acknowledgement is pending.
DevAmsTray* tray = nullptr;
if (is_virtual_tray()) {
for (auto& virtual_tray : obj->vt_slot) {
if (virtual_tray.id == std::to_string(ams_id)) {
tray = &virtual_tray;
break;
}
}
} else {
tray = obj->GetFilaSystem()->GetAmsTray(std::to_string(ams_id), std::to_string(slot_id));
}
if (tray) {
tray->color = tray_color;
tray->cols = tray_colors;
tray->ctype = tray_ctype;
tray->set_hold_count();
}
obj->command_ams_filament_settings(ams_id, slot_id, ams_filament_id, ams_setting_id, std::string(col_buf), m_filament_type, nozzle_temp_min_int, nozzle_temp_max_int);
}
//reset param
@@ -1044,15 +923,8 @@ void AMSMaterialsSetting::set_ctype(int ctype)
void AMSMaterialsSetting::on_picker_color(wxCommandEvent& event)
{
std::vector<wxColour> colors = m_color_picker_popup.get_selected_colours();
if (colors.empty()) {
unsigned int color_num = event.GetInt();
colors.emplace_back(color_num >> 24 & 0xFF, color_num >> 16 & 0xFF, color_num >> 8 & 0xFF, color_num & 0xFF);
}
set_ctype(m_color_picker_popup.get_selected_ctype());
set_color(colors.front());
set_colors(colors);
unsigned int color_num = event.GetInt();
set_color(wxColour(color_num>>24&0xFF, color_num>>16&0xFF, color_num>>8&0xFF, color_num&0xFF));
}
void AMSMaterialsSetting::on_clr_picker(wxMouseEvent &event)
@@ -1067,12 +939,14 @@ void AMSMaterialsSetting::on_clr_picker(wxMouseEvent &event)
}
}
m_color_picker_popup.set_ams_colours(collect_ams_color_items(obj->GetFilaSystem().get()));
m_color_picker_popup.set_preset_colours(collect_preset_color_items(ams_filament_id));
m_color_picker_popup.set_def_colour(m_clr_picker->m_colour, m_clr_picker->m_cols, m_clr_picker->ctype);
std::vector<wxColour> ams_colors;
obj->GetFilaSystem()->CollectAmsColors(ams_colors);
wxPoint img_pos = m_clr_picker->ClientToScreen(wxPoint(0, 0));
wxPoint popup_pos(img_pos.x - m_color_picker_popup.GetSize().x - FromDIP(95), img_pos.y - FromDIP(65));
m_color_picker_popup.Position(popup_pos, wxSize(0, 0));
m_color_picker_popup.set_ams_colours(ams_colors);
m_color_picker_popup.set_def_colour(m_clr_picker->m_colour);
m_color_picker_popup.Popup();
}
@@ -1861,46 +1735,7 @@ void ColorPicker::doRender(wxDC& dc)
auto radius = m_show_full ? size.x / 2 - FromDIP(1) : size.x / 2;
if (m_selected) radius -= FromDIP(1);
if (m_show_full && m_cols.size() > 1) {
if (ctype == 0) {
const double center_x = size.x / 2.0;
const double center_y = size.y / 2.0;
const double draw_radius = radius;
dc.SetPen(*wxTRANSPARENT_PEN);
for (int x = 0; x < size.x; ++x) {
const double dx = x + 0.5 - center_x;
if (std::abs(dx) > draw_radius) continue;
const double half_height = std::sqrt(std::max(0.0, draw_radius * draw_radius - dx * dx));
const int top = std::max(0, static_cast<int>(std::ceil(center_y - half_height)));
const int bottom = std::min(size.y - 1, static_cast<int>(std::floor(center_y + half_height)));
const double pos = size.x > 1 ? static_cast<double>(x) / (size.x - 1) : 0.0;
const double scaled = pos * (m_cols.size() - 1);
const size_t idx = std::min(static_cast<size_t>(scaled), m_cols.size() - 2);
const double ratio = scaled - idx;
if (top <= bottom) {
dc.SetBrush(wxBrush(mix_colour(m_cols[idx], m_cols[idx + 1], ratio)));
dc.DrawRectangle(x, top, 1, bottom - top + 1);
}
}
}
else {
float ev_angle = 360.0 / m_cols.size();
const float overlap = 2.0f;
wxPoint center(size.x / 2, size.y / 2);
dc.SetPen(*wxTRANSPARENT_PEN);
dc.SetBrush(wxBrush(m_cols.front()));
dc.DrawCircle(center.x, center.y, radius);
for (int i = 0; i < m_cols.size(); i++) {
dc.SetBrush(m_cols[i]);
float startAngle = 270.0f + i * ev_angle;
float endAngle = startAngle + ev_angle;
dc.DrawEllipticArc(center.x - radius, center.y - radius, 2 * radius, 2 * radius, startAngle - overlap, endAngle + overlap);
}
}
}
else if (alpha == 0) {
if (alpha == 0) {
wxSize bmp_size = m_bitmap_transparent_def.GetBmpSize();
int center_x = (size.x - bmp_size.x) / 2;
int center_y = (size.y - bmp_size.y) / 2;
@@ -1942,6 +1777,52 @@ void ColorPicker::doRender(wxDC& dc)
dc.SetPen(wxPen(wxColour("#6B6B6B")));
dc.SetBrush(*wxTRANSPARENT_BRUSH);
dc.DrawCircle(size.x / 2, size.y / 2, radius);
if (m_cols.size() > 1) {
if (ctype == 0) {
int left = FromDIP(0);
float total_width = size.x;
int gwidth = std::round(total_width / (m_cols.size() - 1));
for (int i = 0; i < m_cols.size() - 1; i++) {
if ((left + gwidth) > (size.x)) {
gwidth = size.x - left;
}
auto rect = wxRect(left, 0, gwidth, size.y);
dc.GradientFillLinear(rect, m_cols[i], m_cols[i + 1], wxEAST);
left += gwidth;
}
if (wxGetApp().dark_mode()) {
dc.DrawBitmap(m_bitmap_border_dark, wxPoint(0, 0));
}
else {
dc.DrawBitmap(m_bitmap_border, wxPoint(0, 0));
}
}
else {
float ev_angle = 360.0 / m_cols.size();
float startAngle = 270.0;
float endAngle = 270.0;
dc.SetPen(*wxTRANSPARENT_PEN);
for (int i = 0; i < m_cols.size(); i++) {
dc.SetBrush(m_cols[i]);
endAngle += ev_angle;
endAngle = endAngle > 360.0 ? endAngle - 360.0 : endAngle;
wxPoint center(size.x / 2, size.y / 2);
dc.DrawEllipticArc(center.x - radius, center.y - radius, 2 * radius, 2 * radius, startAngle, endAngle);
startAngle += ev_angle;
startAngle = startAngle > 360.0 ? startAngle - 360.0 : startAngle;
}
if (wxGetApp().dark_mode()) {
dc.DrawBitmap(m_bitmap_border_dark, wxPoint(0, 0));
}
else {
dc.DrawBitmap(m_bitmap_border, wxPoint(0, 0));
}
}
}
}
if (m_is_empty) {
@@ -2010,21 +1891,19 @@ ColorPickerPopup::ColorPickerPopup(wxWindow* parent)
m_ams_fg_sizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
//other
m_other_fg_sizer = new wxFlexGridSizer(0, 8, 0, 0);
m_other_fg_sizer->SetFlexibleDirection(wxBOTH);
m_other_fg_sizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
wxFlexGridSizer* fg_sizer;
fg_sizer = new wxFlexGridSizer(0, 8, 0, 0);
fg_sizer->SetFlexibleDirection(wxBOTH);
fg_sizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
for (wxColour col : m_def_colors) {
auto cp = new ColorPicker(m_def_color_box, wxID_ANY, wxDefaultPosition, wxDefaultSize);
cp->set_color(col);
cp->set_colors({col});
cp->ctype = 2;
cp->set_selected(false);
cp->SetBackgroundColour(StateColor::darkModeColorFor(wxColour(238,238,238)));
m_color_pickers.push_back(cp);
m_default_color_pickers.push_back(cp);
m_other_fg_sizer->Add(cp, 0, wxALL, FromDIP(3));
fg_sizer->Add(cp, 0, wxALL, FromDIP(3));
cp->Bind(wxEVT_LEFT_DOWN, [this, cp](auto& e) {
set_def_colour(cp->m_colour);
@@ -2091,7 +1970,7 @@ ColorPickerPopup::ColorPickerPopup(wxWindow* parent)
m_sizer_box->Add(m_sizer_ams, 1, wxEXPAND|wxLEFT|wxRIGHT, FromDIP(10));
m_sizer_box->Add(m_ams_fg_sizer, 0, wxEXPAND|wxLEFT|wxRIGHT, FromDIP(10));
m_sizer_box->Add(m_sizer_other, 1, wxEXPAND|wxLEFT|wxRIGHT, FromDIP(10));
m_sizer_box->Add(m_other_fg_sizer, 0, wxEXPAND|wxLEFT|wxRIGHT, FromDIP(10));
m_sizer_box->Add(fg_sizer, 0, wxEXPAND|wxLEFT|wxRIGHT, FromDIP(10));
m_sizer_box->Add(m_sizer_custom, 0, wxEXPAND|wxLEFT|wxRIGHT, FromDIP(10));
m_sizer_box->Add(m_custom_cp, 0, wxEXPAND|wxLEFT|wxRIGHT, FromDIP(16));
m_sizer_box->Add(0, 0, 0, wxTOP, FromDIP(10));
@@ -2102,7 +1981,7 @@ ColorPickerPopup::ColorPickerPopup(wxWindow* parent)
m_def_color_box->Fit();
m_sizer_main->Add(m_def_color_box, 0, wxALL | wxEXPAND, 10);
SetSizerAndFit(m_sizer_main);
SetSizer(m_sizer_main);
Layout();
Fit();
@@ -2140,15 +2019,13 @@ void ColorPickerPopup::on_custom_clr_picker(wxMouseEvent& /*event*/)
wxPostEvent(GetParent(), evt);
}
void ColorPickerPopup::set_ams_colours(const std::vector<ColorItem>& ams)
void ColorPickerPopup::set_ams_colours(std::vector<wxColour> ams)
{
m_ams_fg_sizer->Clear(false);
if (m_ams_color_pickers.size() > 0) {
for (ColorPicker* col_pick:m_ams_color_pickers) {
std::vector<ColorPicker*>::iterator iter = find(m_color_pickers.begin(), m_color_pickers.end(), col_pick);
if (iter != m_color_pickers.end()) {
col_pick->Hide();
col_pick->Destroy();
m_color_pickers.erase(iter);
}
@@ -2158,22 +2035,17 @@ void ColorPickerPopup::set_ams_colours(const std::vector<ColorItem>& ams)
}
m_ams_color_items = ams;
for (const ColorItem& item : m_ams_color_items) {
if (item.colors.empty()) continue;
m_ams_colors = ams;
for (wxColour col : m_ams_colors) {
auto cp = new ColorPicker(m_def_color_box, wxID_ANY, wxDefaultPosition, wxDefaultSize);
cp->set_color(item.colors.front());
cp->set_colors(item.colors);
cp->ctype = item.colors.size() > 1 ? item.ctype : 2;
cp->set_show_full(true);
cp->set_color(col);
cp->set_selected(false);
cp->SetBackgroundColour(StateColor::darkModeColorFor(wxColour(238,238,238)));
m_color_pickers.push_back(cp);
m_ams_color_pickers.push_back(cp);
m_ams_fg_sizer->Add(cp, 0, wxALL, FromDIP(3));
cp->Bind(wxEVT_LEFT_DOWN, [this, cp](auto& e) {
set_def_colour(cp->m_colour, cp->m_cols, cp->ctype);
set_def_colour(cp->m_colour);
wxCommandEvent evt(EVT_SELECTED_COLOR);
unsigned long g_col = ((cp->m_colour.Red() & 0xff) << 24) + ((cp->m_colour.Green() & 0xff) << 16) + ((cp->m_colour.Blue() & 0xff) << 8) + (cp->m_colour.Alpha() & 0xff);
@@ -2186,68 +2058,9 @@ void ColorPickerPopup::set_ams_colours(const std::vector<ColorItem>& ams)
Fit();
}
void ColorPickerPopup::set_preset_colours(const std::vector<ColorItem>& preset_colors)
{
m_other_fg_sizer->Clear(false);
if (!m_preset_color_pickers.empty()) {
for (ColorPicker* col_pick : m_preset_color_pickers) {
auto iter = std::find(m_color_pickers.begin(), m_color_pickers.end(), col_pick);
if (iter != m_color_pickers.end()) {
col_pick->Hide();
col_pick->Destroy();
m_color_pickers.erase(iter);
}
}
m_preset_color_pickers.clear();
}
for (const ColorItem& item : preset_colors) {
if (item.colors.empty()) continue;
auto cp = new ColorPicker(m_def_color_box, wxID_ANY, wxDefaultPosition, wxDefaultSize);
cp->set_color(item.colors.front());
cp->set_colors(item.colors);
cp->ctype = item.colors.size() > 1 ? item.ctype : 2;
cp->set_show_full(true);
cp->set_selected(false);
cp->SetBackgroundColour(StateColor::darkModeColorFor(wxColour(238,238,238)));
if (!item.name.empty()) {
cp->SetToolTip(item.name);
}
m_color_pickers.push_back(cp);
m_preset_color_pickers.push_back(cp);
cp->Bind(wxEVT_LEFT_DOWN, [this, cp](auto& e) {
set_def_colour(cp->m_colour, cp->m_cols, cp->ctype);
wxCommandEvent evt(EVT_SELECTED_COLOR);
unsigned long g_col = ((cp->m_colour.Red() & 0xff) << 24) + ((cp->m_colour.Green() & 0xff) << 16) + ((cp->m_colour.Blue() & 0xff) << 8) + (cp->m_colour.Alpha() & 0xff);
evt.SetInt(g_col);
wxPostEvent(GetParent(), evt);
});
}
const bool show_default_colours = m_preset_color_pickers.empty();
for (ColorPicker* cp : m_default_color_pickers) {
cp->Show(show_default_colours);
}
for (ColorPicker* cp : (show_default_colours ? m_default_color_pickers : m_preset_color_pickers)) {
m_other_fg_sizer->Add(cp, 0, wxALL, FromDIP(3));
}
m_other_fg_sizer->Layout();
Layout();
Fit();
}
void ColorPickerPopup::set_def_colour(wxColour col, std::vector<wxColour> cols, int ctype)
void ColorPickerPopup::set_def_colour(wxColour col)
{
m_def_col = col;
if (cols.empty()) {
cols.push_back(col);
}
m_def_cols = cols;
m_def_ctype = m_def_cols.size() > 1 ? ctype : 2;
for (ColorPicker* cp : m_color_pickers) {
if (cp->m_selected) {
@@ -2256,8 +2069,7 @@ void ColorPickerPopup::set_def_colour(wxColour col, std::vector<wxColour> cols,
}
for (ColorPicker* cp : m_color_pickers) {
if (!cp->IsShown()) continue;
if (cp->ctype == m_def_ctype && cp->m_cols == m_def_cols) {
if (cp->m_colour == m_def_col) {
cp->set_selected(true);
break;
}
+4 -19
View File
@@ -82,22 +82,14 @@ public:
class ColorPickerPopup : public PopupWindow
{
public:
struct ColorItem
{
std::vector<wxColour> colors;
int ctype = 2;
wxString name;
};
ScalableBitmap m_ts_bitmap_custom;
wxStaticBitmap* m_ts_stbitmap_custom;
StaticBox* m_custom_cp;
StaticBox* m_def_color_box;
wxFlexGridSizer* m_ams_fg_sizer;
wxFlexGridSizer* m_other_fg_sizer;
wxColour m_def_col;
std::vector<wxColour> m_def_colors;
std::vector<ColorItem> m_ams_color_items;
std::vector<wxColour> m_ams_colors;
std::vector<ColorPicker*> m_color_pickers;
std::vector<ColorPicker*> m_ams_color_pickers;
@@ -105,20 +97,13 @@ public:
ColorPickerPopup(wxWindow* parent);
~ColorPickerPopup() {};
void on_custom_clr_picker(wxMouseEvent& event);
void set_ams_colours(const std::vector<ColorItem>& ams);
void set_preset_colours(const std::vector<ColorItem>& preset_colors);
void set_def_colour(wxColour col, std::vector<wxColour> cols = {}, int ctype = 2);
const std::vector<wxColour>& get_selected_colours() const { return m_def_cols; }
int get_selected_ctype() const { return m_def_ctype; }
void set_ams_colours(std::vector<wxColour> ams);
void set_def_colour(wxColour col);
void paintEvent(wxPaintEvent& evt);
virtual void OnDismiss() wxOVERRIDE;
virtual bool ProcessLeftDown(wxMouseEvent& event) wxOVERRIDE;
private:
std::vector<ColorPicker*> m_default_color_pickers;
std::vector<ColorPicker*> m_preset_color_pickers;
std::vector<wxColour> m_def_cols;
int m_def_ctype = 2;
public:
};
+1 -3
View File
@@ -747,9 +747,7 @@ Print::ApplyStatus BackgroundSlicingProcess::apply(const Model& model, const Dyn
// Orca: prevent resetting under gcode viewer mode
if (invalidated != PrintBase::APPLY_STATUS_UNCHANGED) {
// Use the app’s plater accessor instead of going through mainframe, otherwise anything during startup that reaches apply()
// (loading presets, config or input files, e.g. from the CLI) therefore dereferences a null `mainframe` and crashes.
const auto plater = GUI::wxGetApp().plater();
const auto plater = GUI::wxGetApp().mainframe->m_plater;
if (plater && plater->only_gcode_mode()) {
invalidated = PrintBase::APPLY_STATUS_UNCHANGED;
}
+5 -2
View File
@@ -163,8 +163,8 @@ public:
~devPrinterUtil() = delete;
public:
static bool IsVirtualSlot(int ams_id) { return (ams_id == VIRTUAL_TRAY_MAIN_ID || ams_id == VIRTUAL_TRAY_DEPUTY_ID);}
static bool IsVirtualSlot(const std::string& ams_id) { return (ams_id == VIRTUAL_AMS_MAIN_ID_STR || ams_id == VIRTUAL_AMS_DEPUTY_ID_STR); }
static bool IsVirtualSlot(int ams_id);
static bool IsVirtualSlot(const std::string& ams_id);
};
namespace GUI
@@ -198,3 +198,6 @@ template<> struct std::hash<NozzleDef>
return h1 ^ (h2 + 0x9e3779b9 + (h1 << 6) + (h1 >> 2));
};
};
// key(extruder_id) -> { key1(nozzle type info), val1( number of the nozzle type)}
using ExtruderNozzleInfos = std::unordered_map<int, std::unordered_map<NozzleDef, int>>;
+114 -22
View File
@@ -8,6 +8,7 @@
#include <cstdlib>
#include <chrono>
#include <nlohmann/json.hpp>
#include <wx/app.h>
#include <wx/colour.h>
#include <string>
#include <wx/string.h>
@@ -33,6 +34,36 @@
using namespace nlohmann;
namespace Slic3r {
bool devPrinterUtil::IsVirtualSlot(int ams_id)
{
// When the app or preset bundle is unavailable we cannot know the vendor's
// extruder count, so fall back deterministically to the fixed Bambu pair
// {255, 254} rather than guessing from an unknown generic layout.
if (wxTheApp == nullptr || GUI::wxGetApp().preset_bundle == nullptr || GUI::wxGetApp().preset_bundle->is_bbl_vendor())
return ams_id == VIRTUAL_TRAY_MAIN_ID || ams_id == VIRTUAL_TRAY_DEPUTY_ID;
const int extruder_count = GUI::wxGetApp().preset_bundle->get_printer_extruder_count();
return ams_id >= VIRTUAL_TRAY_MAIN_ID - extruder_count + 1 && ams_id <= VIRTUAL_TRAY_MAIN_ID;
}
bool devPrinterUtil::IsVirtualSlot(const std::string& ams_id)
{
// Strict: only a fully numeric string is a valid slot id. std::stoi alone
// would accept trailing garbage (e.g. "255abc" -> 255).
if (ams_id.empty())
return false;
for (char c : ams_id) {
if (c < '0' || c > '9')
return false;
}
try {
return IsVirtualSlot(std::stoi(ams_id));
} catch (...) {
return false;
}
}
static int _hex_digit_to_int(const char c) { return (c >= '0' && c <= '9') ? c - '0' : (c >= 'A' && c <= 'F') ? c - 'A' + 10 : (c >= 'a' && c <= 'f') ? c - 'a' + 10 : -1; }
wxColour DevAmsTray::decode_color(const std::string &color)
@@ -200,18 +231,22 @@ wxString DevAms::GetDisplayName() const
int DevAms::GetSlotCount() const
{
// GetAmsType() maps AMS_LITE_MIXED -> AMS_LITE, so N9 reports 4 slots like AMS-Lite.
auto ams_type = GetAmsType();
if (ams_type == AMS || ams_type == AMS_LITE || ams_type == N3F)
{
return 4;
}
else if (ams_type == N3S)
{
// N3S is a 1-slot Bambu contract, so report 1 regardless of whether the
// preset bundle is momentarily unavailable (m_trays.size() can be 0).
if (GetAmsType() == N3S)
return 1;
if (wxTheApp != nullptr && GUI::wxGetApp().preset_bundle != nullptr &&
GUI::wxGetApp().preset_bundle->is_bbl_vendor()) {
// GetAmsType() maps AMS_LITE_MIXED -> AMS_LITE, so N9 reports 4 slots like AMS-Lite.
auto ams_type = GetAmsType();
if (ams_type == AMS || ams_type == AMS_LITE || ams_type == N3F)
{
return 4;
}
}
return 1;
return static_cast<int>(m_trays.size());
}
DevAmsTray* DevAms::GetTray(const std::string& tray_id) const
@@ -302,13 +337,21 @@ int DevFilaSystem::GetExtruderIdByAmsId(const std::string& ams_id) const
{
return it->second->GetExtruderId();
}
else if (stoi(ams_id) == VIRTUAL_TRAY_MAIN_ID)
{
return MAIN_EXTRUDER_ID;
const bool is_bbl_vendor = wxTheApp != nullptr && GUI::wxGetApp().preset_bundle != nullptr && GUI::wxGetApp().preset_bundle->is_bbl_vendor();
if (!is_bbl_vendor && GetOwner()) {
for (const auto& tray : GetOwner()->vt_slot) {
if (tray.id == ams_id)
return VIRTUAL_TRAY_MAIN_ID - std::stoi(ams_id);
}
}
else if (stoi(ams_id) == VIRTUAL_TRAY_DEPUTY_ID)
{
if (is_bbl_vendor && ams_id == VIRTUAL_AMS_MAIN_ID_STR)
return MAIN_EXTRUDER_ID;
if (is_bbl_vendor && ams_id == VIRTUAL_AMS_DEPUTY_ID_STR)
return DEPUTY_EXTRUDER_ID;
if (!is_bbl_vendor && devPrinterUtil::IsVirtualSlot(ams_id)) {
return VIRTUAL_TRAY_MAIN_ID - std::stoi(ams_id);
}
assert(false && __FUNCTION__);
@@ -325,9 +368,22 @@ std::string DevFilaSystem::GetNozzleFlowStringByAmsId(const std::string& ams_id)
std::map<int, DevAmsSlotId> DevFilaSystem::GetTrayIndexMap()
{
std::map<int, DevAmsSlotId> tray_id_map;
tray_id_map[VIRTUAL_TRAY_MAIN_ID] = DevAmsSlotId{VIRTUAL_TRAY_MAIN_ID, 0};
tray_id_map[VIRTUAL_TRAY_DEPUTY_ID] = DevAmsSlotId{VIRTUAL_TRAY_DEPUTY_ID, 0};
const bool is_bbl_vendor = wxTheApp != nullptr && GUI::wxGetApp().preset_bundle != nullptr && GUI::wxGetApp().preset_bundle->is_bbl_vendor();
if (is_bbl_vendor) {
tray_id_map[VIRTUAL_TRAY_MAIN_ID] = DevAmsSlotId{VIRTUAL_TRAY_MAIN_ID, 0};
tray_id_map[VIRTUAL_TRAY_DEPUTY_ID] = DevAmsSlotId{VIRTUAL_TRAY_DEPUTY_ID, 0};
} else if (GetOwner()) {
for (const auto& tray : GetOwner()->vt_slot) {
try {
const int tray_id = std::stoi(tray.id);
tray_id_map[tray_id] = DevAmsSlotId{tray_id, 0};
} catch (...) {
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << " invalid virtual tray id: " << tray.id;
}
}
}
int generic_tray_index = 0;
for (auto& [ams_id, ams_item] : GetAmsList()) {
for (auto &[slot_id, slot_item] : ams_item->GetTrays()) {
if (ams_item && slot_item) {
@@ -335,9 +391,11 @@ std::map<int, DevAmsSlotId> DevFilaSystem::GetTrayIndexMap()
int ams_id_int = stoi(ams_id);
int slot_id_int = stoi(slot_id);
int tray_index = -1;
if (ams_item->GetAmsType() == DevAms::N3S) {
if (!is_bbl_vendor) {
tray_index = generic_tray_index + slot_id_int;
} else if (ams_item->GetAmsType() == DevAms::N3S) {
tray_index = ams_id_int;
} else if(ams_item->GetAmsType() == DevAms::AMS_LITE && ams_item->IsAmsLiteMixed()) {
} else if (ams_item->GetAmsType() == DevAms::AMS_LITE && ams_item->IsAmsLiteMixed()) {
tray_index = 24 + slot_id_int;
} else {
tray_index = (ams_id_int * 4 + slot_id_int);
@@ -348,6 +406,8 @@ std::map<int, DevAmsSlotId> DevFilaSystem::GetTrayIndexMap()
}
}
}
if (!is_bbl_vendor)
generic_tray_index += static_cast<int>(ams_item->GetTrays().size());
}
return tray_id_map;
@@ -456,6 +516,13 @@ void DevFilaSystemParser::ParseV1_0(const json& jj, MachineObject* obj, DevFilaS
ams_id_set.insert(it->first);
}
// Bambu trays index their exist bit as ams_id*4+tray_id; a generic (non-Bambu) unit
// reports its own lane count, so its trays carry a cumulative lane index instead.
// Same index DevFilaSystem::GetTrayIndexMap() builds and the agent sets bits with.
const bool is_bbl_vendor = wxTheApp != nullptr && GUI::wxGetApp().preset_bundle != nullptr &&
GUI::wxGetApp().preset_bundle->is_bbl_vendor();
int generic_tray_base = 0;
for (auto it = j_ams.begin(); it != j_ams.end(); it++)
{
if (!it->contains("id")) continue;
@@ -795,7 +862,18 @@ void DevFilaSystemParser::ParseV1_0(const json& jj, MachineObject* obj, DevFilaS
if (type_id < 4)
{
curr_tray->is_exists = (obj->tray_exist_bits & (1 << (ams_id_int * 4 + tray_id_int))) != 0 ? true : false;
if (is_bbl_vendor)
{
curr_tray->is_exists = (obj->tray_exist_bits & (1 << (ams_id_int * 4 + tray_id_int))) != 0 ? true : false;
}
else
{
// A generic unit is not four slots wide, so its trays carry a
// cumulative lane index across units instead of ams_id*4+tray_id.
const int tray_bit = generic_tray_base + tray_id_int;
curr_tray->is_exists = tray_bit >= 0 && tray_bit < 32 &&
(obj->tray_exist_bits & (1UL << tray_bit)) != 0;
}
}
else if (type_id == DevAms::AMS_LITE_MIXED)
{
@@ -851,6 +929,9 @@ void DevFilaSystemParser::ParseV1_0(const json& jj, MachineObject* obj, DevFilaS
}
}
}
if (!is_bbl_vendor && it->contains("tray") && (*it)["tray"].is_array()) {
generic_tray_base += static_cast<int>((*it)["tray"].size());
}
}
// remove not in amsList
for (auto it = ams_id_set.begin(); it != ams_id_set.end(); it++)
@@ -913,6 +994,8 @@ void DevFilaSystemParser::ParseAgentFilament(const json& data, MachineObject* ob
}
ams->m_exist = true;
ams->m_binded_extruder_set = {ext_id};
ams->m_binded_switcher_pos.reset();
ams->m_current_temperature = u.value("temperature", (float) INVALID_AMS_TEMPERATURE);
ams->m_humidity_percent = u.value("humidity_percent", -1);
ams->m_left_dry_time = u.value("dry_time_min", 0);
@@ -995,16 +1078,22 @@ void DevFilaSystemParser::ParseAgentFilament(const json& data, MachineObject* ob
}
// --- external / direct spools -> obj->vt_slot ---
// extruder 0 -> main virtual slot, extruder >0 -> deputy.
// Keep one virtual slot per extruder. The legacy two-extruder mapping uses
// 255 for extruder 0 and 254 for extruder 1; continue that sequence for
// additional extruders (253, 252, ...).
if (obj && data.contains("external") && data["external"].is_array())
{
std::map<int, DevAmsTray> external_slots;
obj->vt_slot.clear();
for (const auto& e : data["external"])
{
if (!e.is_object())
continue;
const int ext = e.value("extruder", MAIN_EXTRUDER_ID);
const int vt_id = (ext == MAIN_EXTRUDER_ID) ? VIRTUAL_TRAY_MAIN_ID : VIRTUAL_TRAY_DEPUTY_ID;
if (ext < MAIN_EXTRUDER_ID || ext >= VIRTUAL_TRAY_MAIN_ID)
continue;
const int vt_id = VIRTUAL_TRAY_MAIN_ID - ext;
DevAmsTray tray(std::to_string(vt_id));
tray.is_exists = e.value("loaded", false);
tray.m_fila_type = e.value("material", std::string());
@@ -1013,8 +1102,11 @@ void DevFilaSystemParser::ParseAgentFilament(const json& data, MachineObject* ob
tray.nozzle_temp_min = std::to_string(e.value("nozzle_temp_min", 0));
tray.nozzle_temp_max = std::to_string(e.value("nozzle_temp_max", 0));
tray.remain = e.value("remain_percent", -1);
obj->vt_slot.push_back(tray);
external_slots.insert_or_assign(ext, std::move(tray));
}
for (auto& entry : external_slots)
obj->vt_slot.push_back(std::move(entry.second));
}
}
+2 -2
View File
@@ -348,7 +348,7 @@ public:
DevAmsTray* GetAmsTray(const std::string& ams_id, const std::string& tray_id) const;
void CollectAmsColors(std::vector<wxColour>& ams_colors) const;
// Map a linear tray index -> {ams_id, slot_id}. Includes the two virtual (external-spool) trays,
// Map a linear tray index -> {ams_id, slot_id}. Includes virtual external-spool trays,
// N3S single-slot units, and the A2L/N9 AMS-Lite-mixed layout (trays 24-27).
std::map<int, DevAmsSlotId> GetTrayIndexMap();
@@ -433,4 +433,4 @@ struct DevFilamentDryingPreset
float filament_dev_ams_drying_heat_distortion_temperature = 0.0f;
};
}// namespace Slic3r
}// namespace Slic3r
+37 -17
View File
@@ -13,6 +13,7 @@
#include "slic3r/GUI/DeviceCore/DevDefs.h"
#include "libslic3r/PrintConfig.hpp"
#include <boost/log/trivial.hpp>
#include <wx/app.h>
#include <wx/string.h>
#include <string>
#include "libslic3r/CommonDefs.hpp"
@@ -27,6 +28,7 @@
#include <unordered_map>
#include <optional>
#include <cmath>
#include "slic3r/GUI/GUI_App.hpp"
using json = nlohmann::json;
@@ -176,34 +178,52 @@ DevFirmwareVersionInfo DevNozzle::GetFirmwareInfo() const
int DevNozzle::GetLogicExtruderId() const
{
int total_ext_count = GetTotalExtruderCount();
if (total_ext_count == 1) {
return LOGIC_UNIQUE_EXTRUDER_ID;
} else if (total_ext_count == 2) {
if (AtLeftExtruder()) {
return LOGIC_L_EXTRUDER_ID;
} else if (AtRightExtruder()) {
return LOGIC_R_EXTRUDER_ID;
const bool is_bbl_vendor = wxTheApp != nullptr && GUI::wxGetApp().preset_bundle != nullptr &&
GUI::wxGetApp().preset_bundle->is_bbl_vendor();
if (is_bbl_vendor) {
if (total_ext_count == 1) {
return LOGIC_UNIQUE_EXTRUDER_ID;
} else if (total_ext_count == 2) {
if (AtLeftExtruder()) {
return LOGIC_L_EXTRUDER_ID;
} else if (AtRightExtruder()) {
return LOGIC_R_EXTRUDER_ID;
}
}
assert(0);
return LOGIC_UNIQUE_EXTRUDER_ID;
}
assert(0);
return LOGIC_UNIQUE_EXTRUDER_ID;
// For some reason, BBL's logical extruder ID is inverted:
// physical extruder id = 0 (MAIN_EXTRUDER_ID) vs logical extruder id = 1 (LOGIC_R_EXTRUDER_ID)
// Likely because logical id reads from left to right (left = 0, right = 1)
// For generic N extruders, this inversion does not apply.
if (IsOnRack()) return INVALID_EXTRUDER_ID;
return m_nozzle_id;
}
int DevNozzle::GetExtruderId() const
{
int total_ext_count = GetTotalExtruderCount();
if (total_ext_count == 1) {
return MAIN_EXTRUDER_ID;
} else if (total_ext_count == 2) {
if (AtRightExtruder()) {
const bool is_bbl_vendor = wxTheApp != nullptr && GUI::wxGetApp().preset_bundle != nullptr &&
GUI::wxGetApp().preset_bundle->is_bbl_vendor();
if (is_bbl_vendor) {
int total_ext_count = GetTotalExtruderCount();
if (total_ext_count == 1) {
return MAIN_EXTRUDER_ID;
} else if (AtLeftExtruder()) {
return DEPUTY_EXTRUDER_ID;
} else if (total_ext_count == 2) {
if (AtRightExtruder()) {
return MAIN_EXTRUDER_ID;
} else if (AtLeftExtruder()) {
return DEPUTY_EXTRUDER_ID;
}
}
return MAIN_EXTRUDER_ID;
}
return MAIN_EXTRUDER_ID;
return m_nozzle_id;
}
bool DevNozzle::AtLeftExtruder() const
+64 -53
View File
@@ -65,6 +65,7 @@
#include <unordered_set>
#include <utility>
#include <vector>
#include <wx/app.h>
#include <wx/colour.h>
#include <tuple>
#include <wx/app.h>
@@ -806,8 +807,12 @@ bool MachineObject::is_extrusion_cali_finished()
DevAmsTray *MachineObject::get_curr_tray()
{
const std::string& cur_ams_id = m_extder_system->GetCurrentAmsId();
if (cur_ams_id.compare(std::to_string(VIRTUAL_TRAY_MAIN_ID)) == 0) {
return &vt_slot[0];
if (devPrinterUtil::IsVirtualSlot(cur_ams_id)) {
for (auto& tray : vt_slot) {
if (tray.id == cur_ams_id)
return &tray;
}
return nullptr;
}
DevAms* curr_ams = get_curr_Ams();
@@ -1273,19 +1278,24 @@ int MachineObject::get_bed_temperature_limit()
bool MachineObject::is_filament_installed()
{
if (m_extder_system->GetTotalExtderCount() > 0) {
// right//or single
auto ext = m_extder_system->m_extders[MAIN_EXTRUDER_ID];
if (ext.m_ext_has_filament) {
// if (m_extder_system->GetTotalExtderCount() > 0) {
// // right//or single
// auto ext = m_extder_system->m_extders[MAIN_EXTRUDER_ID];
// if (ext.m_ext_has_filament) {
// return true;
// }
// }
// /*left*/
// if (m_extder_system->GetTotalExtderCount() > 1) {
// auto ext = m_extder_system->m_extders[DEPUTY_EXTRUDER_ID];
// if (ext.m_ext_has_filament) {
// return true;
// }
// }
for (auto& ext : m_extder_system->m_extders) {
if (ext.m_ext_has_filament)
return true;
}
}
/*left*/
if (m_extder_system->GetTotalExtderCount() > 1) {
auto ext = m_extder_system->m_extders[DEPUTY_EXTRUDER_ID];
if (ext.m_ext_has_filament) {
return true;
}
}
return false;
}
@@ -1798,8 +1808,7 @@ int MachineObject::command_ams_calibrate(int ams_id)
return command_with_dialog(m_agent->command_ams_calibrate(get_dev_id(), ams_id, MachineObject::m_sequence_id++, is_lan_mode_printer()));
}
int MachineObject::command_ams_filament_settings(int ams_id, int slot_id, std::string filament_id, std::string setting_id, std::string tray_color, std::string tray_type,
int nozzle_temp_min, int nozzle_temp_max, const std::vector<std::string>& tray_colors, int tray_ctype)
int MachineObject::command_ams_filament_settings(int ams_id, int slot_id, std::string filament_id, std::string setting_id, std::string tray_color, std::string tray_type, int nozzle_temp_min, int nozzle_temp_max)
{
int tag_tray_id = 0;
int tag_ams_id = ams_id;
@@ -1828,10 +1837,6 @@ int MachineObject::command_ams_filament_settings(int ams_id, int slot_id, std::s
j["print"]["nozzle_temp_min"] = nozzle_temp_min;
j["print"]["nozzle_temp_max"] = nozzle_temp_max;
j["print"]["tray_type"] = tray_type;
if (!tray_colors.empty()) {
j["print"]["cols"] = tray_colors;
j["print"]["ctype"] = tray_ctype;
}
return this->publish_json(j);
}
@@ -2632,13 +2637,10 @@ void MachineObject::reset()
json empty_j;
print_json.diff2all_base_reset(empty_j);
for (auto i = 0; i < vt_slot.size(); i++) {
vt_slot[i].reset();
if (i == 1) {
vt_slot.erase(vt_slot.begin() + 1);
}
}
for (auto& tray : vt_slot)
tray.reset();
if (vt_slot.size() > 1)
vt_slot.erase(vt_slot.begin() + 1, vt_slot.end());
// why: reset reuses MachineObject, so release its lazy subtask
// before dropping the pointer to prevent reconnect leaks.
if (subtask_) {
@@ -4119,25 +4121,28 @@ int MachineObject::parse_json(std::string tunnel, std::string payload, bool key_
if (jj.contains("vir_slot") && jj["vir_slot"].is_array()) {
for (auto it = jj["vir_slot"].begin(); it != jj["vir_slot"].end(); it++) {
auto vslot = parse_vt_tray(it.value().get<json>());
try {
const auto tray_json = it.value().get<json>();
if (!tray_json.is_object() || !tray_json.contains("id") || !tray_json["id"].is_string())
continue;
if (vslot.id == std::to_string(VIRTUAL_TRAY_MAIN_ID)) {
auto it = std::next(vt_slot.begin(), 0);
if (it != vt_slot.end()) {
vt_slot[0] = vslot;
}
else {
vt_slot.push_back(vslot);
const auto tray_id_str = tray_json["id"].get<std::string>();
int tray_id = 0;
const auto result = std::from_chars(tray_id_str.data(), tray_id_str.data() + tray_id_str.size(), tray_id);
if (result.ec != std::errc{} || result.ptr != tray_id_str.data() + tray_id_str.size()
|| tray_id < 0 || tray_id > VIRTUAL_TRAY_MAIN_ID)
continue;
auto vslot = parse_vt_tray(tray_json);
const auto index = static_cast<std::vector<DevAmsTray>::size_type>(VIRTUAL_TRAY_MAIN_ID - tray_id);
while (vt_slot.size() <= index) {
const int placeholder_id = VIRTUAL_TRAY_MAIN_ID - static_cast<int>(vt_slot.size());
vt_slot.emplace_back(std::to_string(placeholder_id));
}
vt_slot[index] = vslot;
}
else if (vslot.id == std::to_string(VIRTUAL_TRAY_DEPUTY_ID)) {
auto it = std::next(vt_slot.begin(), 1);
if (it != vt_slot.end()) {
vt_slot[1] = vslot;
}
else {
vt_slot.push_back(vslot);
}
catch (...) {
continue;
}
}
@@ -5275,16 +5280,17 @@ DevAmsTray MachineObject::parse_vt_tray(json vtray)
bool MachineObject::contains_tray(const std::string &ams_id, const std::string &tray_id) const
{
if (ams_id != VIRTUAL_AMS_MAIN_ID_STR && ams_id != VIRTUAL_AMS_DEPUTY_ID_STR) {
const bool is_bbl_vendor = wxTheApp != nullptr && GUI::wxGetApp().preset_bundle != nullptr && GUI::wxGetApp().preset_bundle->is_bbl_vendor();
if (is_bbl_vendor && ams_id != VIRTUAL_AMS_MAIN_ID_STR && ams_id != VIRTUAL_AMS_DEPUTY_ID_STR)
return m_fila_system->GetAmsTray(ams_id, tray_id) != nullptr;
} else {
if (!is_bbl_vendor || ams_id == VIRTUAL_AMS_MAIN_ID_STR || ams_id == VIRTUAL_AMS_DEPUTY_ID_STR) {
for (const auto& tray : vt_slot) {
if (tray.id == ams_id) { return true; }
if (tray.id == ams_id) return true;
}
}
return false;
return !is_bbl_vendor && m_fila_system->GetAmsTray(ams_id, tray_id) != nullptr;
}
DevAmsTray MachineObject::get_tray(const std::string &ams_id, const std::string &tray_id) const
@@ -5294,13 +5300,19 @@ DevAmsTray MachineObject::get_tray(const std::string &ams_id, const std::string
return DevAmsTray(tray_id);
}
if (ams_id != VIRTUAL_AMS_MAIN_ID_STR && ams_id != VIRTUAL_AMS_DEPUTY_ID_STR) {
const bool is_bbl_vendor = wxTheApp != nullptr && GUI::wxGetApp().preset_bundle != nullptr && GUI::wxGetApp().preset_bundle->is_bbl_vendor();
if (is_bbl_vendor && ams_id != VIRTUAL_AMS_MAIN_ID_STR && ams_id != VIRTUAL_AMS_DEPUTY_ID_STR) {
auto tray = m_fila_system->GetAmsTray(ams_id, tray_id);
if (tray) { return *tray;};
if (tray) return *tray;
}
else {
else if (!is_bbl_vendor || ams_id == VIRTUAL_AMS_MAIN_ID_STR || ams_id == VIRTUAL_AMS_DEPUTY_ID_STR) {
for (const auto &tray : vt_slot) {
if (tray.id == ams_id) { return tray; }
if (tray.id == ams_id) return tray;
}
if (!is_bbl_vendor) {
auto tray = m_fila_system->GetAmsTray(ams_id, tray_id);
if (tray) return *tray;
}
}
@@ -5483,7 +5495,6 @@ void MachineObject::parse_new_info(json print)
is_support_pa_mode = (get_flag_bits_no_border(fun2, 3) == 1);
is_support_remote_dry = (get_flag_bits_no_border(fun2, 5) == 1);
is_support_check_track_switch_match_slice_printer = get_flag_bits_no_border(fun2, 19) == 1;
is_support_filament_manual_multi_color = (get_flag_bits_no_border(fun2, 23) == 1);
if (DevPrinterConfigUtil::support_print_check_firmware_for_tpu_left(printer_type)) {
m_firmware_support_print_tpu_left = get_flag_bits_no_border(fun2, 7) == 1;
+1 -2
View File
@@ -674,7 +674,6 @@ public:
bool is_support_remote_dry = false;
bool is_support_check_track_switch_match_slice_printer{false};
bool is_support_pa_mode{false};
bool is_support_filament_manual_multi_color{false};
std::optional<bool> m_firmware_support_print_tpu_left;
bool installed_upgrade_kit{false};
@@ -805,7 +804,7 @@ public:
int command_ams_switch_filament(bool switch_filament);
int command_ams_air_print_detect(bool air_print_detect);
int command_ams_calibrate(int ams_id);
int command_ams_filament_settings(int ams_id, int slot_id, std::string filament_id, std::string setting_id, std::string tray_color, std::string tray_type, int nozzle_temp_min, int nozzle_temp_max, const std::vector<std::string>& tray_colors = {}, int tray_ctype = 2);
int command_ams_filament_settings(int ams_id, int slot_id, std::string filament_id, std::string setting_id, std::string tray_color, std::string tray_type, int nozzle_temp_min, int nozzle_temp_max);
int command_ams_select_tray(std::string tray_id);
int command_ams_refresh_rfid(int ams_id, int slot_id);
int command_ams_control(std::string action);
+1 -1
View File
@@ -96,7 +96,7 @@ void FilamentColorCodeQuery::LoadFromLocal()
const auto& fila_color_strs = json_data_item["fila_color"].get<std::vector<wxString>>();
for (const auto& color_str : fila_color_strs) {
if (color_str.size() > 3) /* Skip the value like "#0"*/{
fila_color.AddColor(wxColour(color_str));
fila_color.m_colors.emplace(wxColour(color_str));
}
}
}
-11
View File
@@ -87,17 +87,6 @@ struct FilamentColor
public:
size_t ColorCount() const noexcept { return m_colors.size(); }
// Preserve catalog endpoint order for display while retaining set-based lookup identity.
const std::vector<wxColour>& GetColors() const noexcept { return m_color_list; }
void AddColor(const wxColour& color)
{
if (m_colors.insert(color).second) m_color_list.push_back(color);
}
private:
std::vector<wxColour> m_color_list;
public:
void EndSet(int ctype)
{
+4 -6
View File
@@ -83,13 +83,11 @@ namespace Slic3r::GUI::GLGizmoUtils {
bool clicked = toolbar_circular_button(icon, "##wiki_guide_btn", scale);
if (url && *url && clicked)
wxLaunchDefaultBrowser(wxString::FromUTF8(url));
// ImGuiWrapper::tooltip keeps the text readable on the dark tooltip background whatever text colour the
// host window pushed; a negative wrap position keeps the URL on one line.
if (ImGui::IsItemHovered()){
if(url && *url)
wxGetApp().imgui()->tooltip(_u8L("Wiki Guide") + "\n" + url, -1.f);
ImGui::SetTooltip("%s\n%s", _u8L("Wiki Guide").c_str(), url);
else
wxGetApp().imgui()->tooltip(_u8L("Wiki Guide"), -1.f);
ImGui::SetTooltip("%s", _u8L("Wiki Guide").c_str());
}
return clicked; // for dynamically generated links
}
@@ -103,9 +101,9 @@ namespace Slic3r::GUI::GLGizmoUtils {
wxLaunchDefaultBrowser(wxString::FromUTF8(url));
if (ImGui::IsItemHovered()){
if(url && *url)
wxGetApp().imgui()->tooltip(_u8L("Video Guide") + "\n" + url, -1.f);
ImGui::SetTooltip("%s\n%s", _u8L("Video Guide").c_str(), url);
else
wxGetApp().imgui()->tooltip(_u8L("Video Guide"), -1.f);
ImGui::SetTooltip("%s", _u8L("Video Guide").c_str());
}
return clicked; // for dynamically generated links
}
@@ -857,12 +857,11 @@ void GizmoObjectManipulation::do_render_move_window(ImGuiWrapper *imgui_wrapper,
if (render_combo(imgui_wrapper, "", modes, selection_idx, 0, coord_combo_width)) {
combox_changed = true;
}
ImGuiWrapper::pop_combo_style();
// After pop_combo_style(): its light popup background would hide the tooltip's white text.
if (ImGui::IsItemHovered()) {
auto tooltip_str = _L("Coordinate system used for transform actions.");
imgui_wrapper->tooltip(tooltip_str, imgui_wrapper->calc_text_size(tooltip_str).x + 3 * space_size);
}
ImGuiWrapper::pop_combo_style();
// ORCA use TextColored to match axes color
float offset_to_center = (unit_size - ImGui::CalcTextSize("O").x) / 2;
@@ -965,12 +964,11 @@ void GizmoObjectManipulation::do_render_move_window(ImGuiWrapper *imgui_wrapper,
if (render_combo(imgui_wrapper, "", align_modes, align_mode_idx, 0, coord_combo_width))
m_align_to_parent = align_mode_idx + 1 == align_modes.size();
ImGui::PopID();
ImGuiWrapper::pop_combo_style();
// After pop_combo_style(): its light popup background would hide the tooltip's white text.
if (ImGui::IsItemHovered()) {
wxString tooltip_str = _L("Reference for alignment");
imgui_wrapper->tooltip(tooltip_str, imgui_wrapper->calc_text_size(tooltip_str).x + 3 * space_size);
}
ImGuiWrapper::pop_combo_style();
const bool dark_mode = wxGetApp().dark_mode();
int current_axis = -1;
@@ -1379,12 +1377,11 @@ void GizmoObjectManipulation::do_render_scale_input_window(ImGuiWrapper* imgui_w
if (render_combo(imgui_wrapper, "", modes, selection_idx, 0, coord_combo_width)) {
combox_changed = true;
}
ImGuiWrapper::pop_combo_style();
// After pop_combo_style(): its light popup background would hide the tooltip's white text.
if (ImGui::IsItemHovered()) {
auto tooltip_str = _L("Coordinate system used for transform actions.");
imgui_wrapper->tooltip(tooltip_str, imgui_wrapper->calc_text_size(tooltip_str).x + 3 * space_size);
}
ImGuiWrapper::pop_combo_style();
// ORCA use TextColored to match axes color
float offset_to_center = (unit_size - ImGui::CalcTextSize("O").x) / 2;
-12
View File
@@ -816,18 +816,6 @@ DPIFrame(NULL, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, BORDERLESS_FRAME_
bool MainFrame::handle_global_shortcut(const KeyChord& chord)
{
// ImGui draws its text fields (the text tool's box, a sketch value field) on the GL canvas, so
// while one of them is typed into the focused wx window is that canvas or an in-canvas frame:
// neither is a wxControl, so focus_keeps_space() cannot see it and CHAR_HOOK takes the chord
// here first -- Space opened the Speed Dial, Ctrl+P the Preferences, and the field never saw
// the key. ImGui raises WantCaptureKeyboard while one of its items owns the keyboard, so leave
// the key to it then. A focused wxControl (text field, list, web view) is untouched: those
// keep their own keys, and ImGui's flag can outlive the focus moving to one of them.
wxWindow* const focus = wxWindow::FindFocus();
ImGuiWrapper* const imgui = wxGetApp().imgui();
if (focus != nullptr && imgui != nullptr && imgui->want_keyboard() && dynamic_cast<wxControl*>(focus) == nullptr)
return false;
const std::optional<Shortcut> shortcut = wxGetApp().shortcuts().lookup(ShortcutContext::Global, chord);
if (!shortcut.has_value())
return false;
-15
View File
@@ -1332,21 +1332,6 @@ boost::any ConfigOptionsGroup::get_config_value2(const DynamicPrintConfig& confi
return ret;
}
bool ConfigOptionsGroup::commit_config_value(const t_config_option_key& opt_key, int opt_index)
{
if (m_config == nullptr)
return false;
// m_opt_map is filled while the option lines are created, so it still resolves the option when
// the group's controls (and thus its fields) have not been built yet.
const std::string opt_id = option_id_in_map(m_opt_map, opt_key, opt_index);
if (opt_id.empty())
return false;
on_change_OG(opt_id, get_config_value2(*m_config, opt_key, opt_index));
return true;
}
Field* ConfigOptionsGroup::get_fieldc(const t_config_option_key& opt_key, int opt_index)
{
Field* field = get_field(opt_key);
-40
View File
@@ -119,37 +119,6 @@ using column_t = std::function<wxWindow*(wxWindow* parent, const Line&)>;
using t_optionfield_map = std::map<t_config_option_key, t_field>;
using t_opt_map = std::map< std::string, std::pair<std::string, int> >;
// The option id a group's option map holds for opt_key, and the index it carries. `opt_index` is
// an in/out parameter: a negative value asks for the option's single entry, an explicit one selects
// that index. Returns an empty string when the map does not own the option, or when a negative index
// matches several entries -- a vector option the GUI edits one index at a time, which has no single
// value to commit. A group fills the map while its option lines are created (OptionsGroup::append_line
// / ConfigOptionsGroup::get_option), so this resolves an option even before its controls (and its
// field) have been built.
inline std::string option_id_in_map(const t_opt_map& options, const t_config_option_key& opt_key, int& opt_index)
{
if (opt_index >= 0) {
for (const auto& opt : options) {
if (opt.second.first == opt_key && opt.second.second == opt_index) {
opt_index = opt.second.second;
return opt.first;
}
}
return {};
}
std::string opt_id;
for (const auto& opt : options) {
if (opt.second.first != opt_key)
continue;
if (!opt_id.empty())
return {}; // several entries: a vector option, not one value
opt_id = opt.first;
opt_index = opt.second.second;
}
return opt_id;
}
class OptionsGroup {
public:
const bool staticbox{true};
@@ -363,15 +332,6 @@ public:
boost::any get_config_value(const DynamicPrintConfig& config, const std::string& opt_key, int opt_index = -1);
// BBS: restore all pages in preset
boost::any get_config_value2(const DynamicPrintConfig& config, const std::string& opt_key, int opt_index = -1);
// Re-run this group's committed-change path for one of its options without a widget event:
// build the option's value from the config this group edits (get_config_value2, the same form
// the option's field reports) and dispatch on_change_OG(), so the group's option-specific
// conversion (e.g. the printer_agent canonicalization) and its registered change handler run
// exactly as for a hand edit. The option map is filled while the option lines are created, so
// this resolves an option whose field is not built yet (a lazy page, or an option the GUI has
// no field for). Returns false when this group does not own the option, or when opt_index < 0
// matches several entries (a vector option the GUI edits index by index has no single value).
bool commit_config_value(const t_config_option_key& opt_key, int opt_index = -1);
Field* get_fieldc(const t_config_option_key& opt_key, int opt_index);
std::pair<OG_CustomCtrl*, bool*> get_custom_ctrl_with_blinking_ptr(const t_config_option_key& opt_key, int opt_index/* = -1*/);
+16 -1
View File
@@ -6071,6 +6071,8 @@ void Sidebar::on_bed_type_change(BedType bed_type)
* - Map key encoding:
* - Virtual trays: 0x10000 + vt_tray.id (first/main extruder), or just vt_tray.id (secondary)
* - AMS trays: 0x10000 + (ams_id * 4 + slot_id) (main extruder), or (ams_id * 4 + slot_id) (secondary)
* - Generic (non-Bambu) units are not four slots wide: their trays index by a cumulative lane
* count across units instead of ams_id * 4 + slot_id
* - The 0x10000 flag indicates the main/right extruder
* - Map value: DynamicPrintConfig with filament properties (id, type, color, etc.)
*
@@ -6136,13 +6138,26 @@ std::map<int, DynamicPrintConfig> Sidebar::build_filament_ams_list(MachineObject
return std::string();
};
const bool is_bbl_vendor = wxTheApp != nullptr && wxGetApp().preset_bundle != nullptr && wxGetApp().preset_bundle->is_bbl_vendor();
auto list = obj->GetFilaSystem()->GetAmsList();
for (auto ams : list) {
int ams_id = std::stoi(ams.first);
int extruder = ams.second->GetExtruderId() ? 0 : 0x10000; // Main (first) extruder at right
// Bambu units are four slots wide; a generic unit reports its own lane count and its trays
// carry a cumulative lane index. The AMS map is keyed by string id, so count preceding units
// numerically to keep this the same index the parser and the agent use.
int generic_tray_base = 0;
if (!is_bbl_vendor) {
for (const auto& other : list) {
if (std::stoi(other.first) < ams_id)
generic_tray_base += static_cast<int>(other.second->GetTrays().size());
}
}
for (auto tray : ams.second->GetTrays()) {
int slot_id = std::stoi(tray.first);
filament_ams_list.emplace(extruder + (ams_id * 4 + slot_id),
const int tray_index = is_bbl_vendor ? ams_id * 4 + slot_id : generic_tray_base + slot_id;
filament_ams_list.emplace(extruder + tray_index,
build_tray_config(*tray.second, get_ams_name(ams_id, slot_id), std::to_string(ams_id), std::to_string(slot_id)));
}
}
File diff suppressed because it is too large Load Diff
+36 -4
View File
@@ -1,6 +1,8 @@
#ifndef slic3r_StatusPanel_hpp_
#define slic3r_StatusPanel_hpp_
#include <vector>
#include "libslic3r/ProjectTask.hpp"
#include "DeviceManager.hpp"
#include "MonitorPage.hpp"
@@ -66,6 +68,7 @@
#include "StagedBuild.hpp"
class StepIndicator;
class wxChoice;
#define COMMAND_TIMEOUT 5
@@ -140,28 +143,36 @@ class ExtruderImage : public wxWindow
ScalableBitmap *m_left_extruder_active_empty;
ScalableBitmap *m_left_extruder_unactive_filled;
ScalableBitmap *m_left_extruder_unactive_empty;
ScalableBitmap *m_right_extruder_active_filled;
ScalableBitmap *m_right_extruder_active_empty;
ScalableBitmap *m_right_extruder_unactive_filled;
ScalableBitmap *m_right_extruder_unactive_empty;
ScalableBitmap *m_extruder_single_nozzle_empty_load;
ScalableBitmap *m_extruder_single_nozzle_empty_unload;
ScalableBitmap *m_extruder_single_nozzle_filled_load;
ScalableBitmap *m_extruder_single_nozzle_filled_unload;
ExtruderState m_left_ext_state = {ExtruderState::EMPTY_LOAD};
ExtruderState m_right_ext_state = {ExtruderState::EMPTY_LOAD};
ExtruderState m_single_ext_state = {ExtruderState::EMPTY_LOAD};
std::vector<ExtruderState> m_multi_extruder_states;
bool m_generic_nozzle_display{false};
public:
void update(int nozzle_num, int nozzle_id);
void update(ExtruderState single_state);
void update(ExtruderState right_state, ExtruderState left_state);
void update(ExtruderState state, int idx);
void msw_rescale();
void updateGenericSize();
void setExtruderCount(int nozzle_num);
void setGenericNozzleDisplay(bool enabled);
void setExtruderUsed(std::string loc);
void setExtruderUsed(int nozzle_idx);
void paintEvent(wxPaintEvent &evt);
void render(wxDC &dc);
@@ -495,6 +506,8 @@ protected:
std::vector<ExtruderImage *> m_extruderImage;
SwitchBoard * m_nozzle_btn_panel;
wxChoice* m_generic_nozzle_selector{nullptr};
int m_generic_nozzle_selector_count{0};
wxStaticText * m_text_tasklist_caption;
@@ -507,10 +520,23 @@ protected:
wxBoxSizer * m_misc_ctrl_sizer;
StaticBox* m_fan_panel;
StaticLine * m_line_nozzle;
TempInput* m_tempCtrl_nozzle;
wxWindowID m_nozzle_temp_control_id{wxID_ANY};
wxWindow* m_temp_nozzle_parent{nullptr};
wxBoxSizer* m_temp_nozzle_sizer{nullptr};
size_t m_temp_nozzle_active_count{0};
TempInput* m_tempCtrl_nozzle{nullptr};
int m_temp_nozzle_timeout{ 0 };
TempInput* m_tempCtrl_nozzle_deputy;
TempInput* m_tempCtrl_nozzle_deputy{nullptr};
int m_temp_nozzle_deputy_timeout{ 0 };
std::vector<TempInput*> m_tempCtrl_nozzles;
std::vector<int> m_temp_nozzle_timeouts;
// Last (dev_id, device toolhead count, preset nozzle count) we warned about, to avoid log spam.
std::string m_last_mismatch_dev_id;
int m_last_mismatch_device_count{-1};
int m_last_mismatch_preset_count{-1};
TempInput * m_tempCtrl_bed;
int m_temp_bed_timeout {0};
TempInput * m_tempCtrl_chamber;
@@ -550,6 +576,7 @@ protected:
/* AMS control box <-> live nozzle-rack panel toggle (rack printers only) */
SwitchBoard* m_ams_rack_switch{ nullptr };
MultiSwitchButton* m_ams_nozzle_switch{ nullptr };
AMSControl* m_ams_control;
StaticBox* m_ams_control_box;
@@ -624,6 +651,9 @@ public:
wxBoxSizer *create_temp_axis_group(wxWindow *parent);
wxBoxSizer *create_temp_control(wxWindow *parent);
TempInput* create_nozzle_temp_control(wxWindow *parent, wxWindowID id);
void set_temp_input_colors(TempInput* temp_ctrl);
void ensure_nozzle_temp_controls(size_t count);
wxBoxSizer *create_misc_control(wxWindow *parent);
wxBoxSizer *create_axis_control(wxWindow *parent);
wxPanel *create_bed_control(wxWindow *parent);
@@ -654,6 +684,7 @@ private:
friend class MonitorPanel;
void wire_controls();
bool load_thumbnail_from_url(const wxString &url, MachineObject *obj);
void sync_nozzle_temp_controls(size_t count);
protected:
std::shared_ptr<SliceInfoPopup> m_slice_info_popup;
@@ -801,6 +832,7 @@ protected:
void update_cloud_subtask(MachineObject *obj);
void update_sdcard_subtask(MachineObject *obj);
void update_temp_ctrl(MachineObject *obj);
void check_extruder_count_mismatch(MachineObject* obj);
void update_misc_ctrl(MachineObject *obj);
void update_ams(MachineObject* obj);
void update_rack(MachineObject* obj);
-96
View File
@@ -46,7 +46,6 @@
#include "slic3r/GUI/DeviceCore/DevConfigUtil.h"
#include <deque>
#include <exception>
#include <stdexcept>
#include "libslic3r/LifecycleEvents.hpp"
#include "libslic3r/Point.hpp"
#include "slic3r/GUI/SettingsIndex.hpp"
@@ -1646,101 +1645,6 @@ void Tab::load_config(const DynamicPrintConfig& config)
}
}
// The option keys a preset of `type` may hold. The tab's config shares the global
// print_config_def with every other preset type, so membership has to be checked against the
// preset type's own key list instead of the config definition, or a printer setting could be
// written into the process preset.
static const std::vector<std::string>& preset_type_options(Preset::Type type)
{
static const std::vector<std::string> none;
switch (type) {
case Preset::TYPE_PRINT: return Preset::print_options();
case Preset::TYPE_FILAMENT: return Preset::filament_options();
case Preset::TYPE_PRINTER: return Preset::printer_options();
default: return none;
}
}
static const char* preset_type_name(Preset::Type type)
{
switch (type) {
case Preset::TYPE_PRINT: return "process";
case Preset::TYPE_FILAMENT: return "filament";
case Preset::TYPE_PRINTER: return "printer";
default: return "preset";
}
}
// Set one option of the currently edited preset from its serialized string form, then run the
// same update path a hand edit runs. The edited preset is not saved: it only becomes dirty,
// exactly as if the field had been edited by hand.
void Tab::apply_preset_config_value(const std::string& opt_key, const std::string& value)
{
if (m_config == nullptr)
throw std::runtime_error("The preset configuration is not available");
if (wxGetApp().plater() == nullptr)
throw std::runtime_error("OrcaSlicer main window is not available");
const std::vector<std::string>& options = preset_type_options(m_type);
if (std::find(options.begin(), options.end(), opt_key) == options.end())
throw std::invalid_argument(format("Unknown %1% preset setting \"%2%\"", preset_type_name(m_type), opt_key));
// Parse strictly, keeping a backup: the strict deserializer can already have mutated the option
// when it rejects a bad value, so a failed update has to restore the preset it was given.
const ConfigOption* previous_option = m_config->option(opt_key);
std::unique_ptr<ConfigOption> previous(previous_option != nullptr ? previous_option->clone() : nullptr);
try {
m_config->set_deserialize_strict(opt_key, value);
} catch (const ConfigurationError& err) {
if (previous)
m_config->set_key_value(opt_key, previous.release());
else
m_config->erase(opt_key);
throw std::invalid_argument(err.what());
}
// Run the same commit path the GUI runs for this setting, so its key-specific behaviour
// (ConfigOptionsGroup::on_change_OG, including the printer_agent canonicalization, the group's
// pre-checks and Tab::on_value_change()) runs exactly as for a hand edit. A built field supplies
// the field's typed/clamped value; otherwise the owning ConfigOptionsGroup builds the value from
// the config it edits and dispatches the same on_change_OG(). The field is refreshed from the
// config just committed first, so it reports the committed value rather than a stale one.
bool committed = false;
if (Page* field_page = nullptr; Field* field = get_field(opt_key, &field_page)) {
field_page->reload_config();
field->field_changed();
committed = true;
} else {
for (const PageShp& page : m_pages) {
for (const ConfigOptionsGroupShp& group : page->m_optgroups) {
if (group->commit_config_value(opt_key)) {
committed = true;
break;
}
}
if (committed)
break;
}
}
if (committed) {
// The commit path already ran update_dirty() (dirty flag, preset combo and, on the printer
// tab, the printer-agent switch); refresh the visible page and push the config to the plater.
reload_config();
update();
} else {
// The GUI edits this setting through a custom widget rather than a group (e.g.
// compatible_printers), so take the same shared no-field commit path the widget uses. Saved
// mode skips the value write (the strict parse above already did it) and keeps the path's
// compatibility recompute, dirty flag, preset-combo and plater updates.
load_key_value(opt_key, boost::any(), /*saved_value=*/true);
// The widget itself normally re-reads its value after load_key_value(); with no widget to do
// that, sync the visible page so a custom widget (the compatible-printers row) reflects the
// new value.
reload_config();
}
}
// Reload current $self->{config} (aka $self->{presets}->edited_preset->config) into the UI fields.
void Tab::reload_config()
{
-11
View File
@@ -424,17 +424,6 @@ public:
//BBS update plater presets if update_plater_presets = true
void update_tab_ui(bool update_plater_presets = false);
void load_config(const DynamicPrintConfig& config);
// Host/plugin API: set one option of this tab's currently edited preset from its serialized
// string value, then run the same committed-change path a field edit runs. `opt_key` must be a
// setting of this tab's preset type, so a key of another preset type (e.g. a printer setting
// passed to the process tab) is rejected instead of written silently. `value` is parsed by the
// strict config deserializer, which raises std::invalid_argument for an unknown key or a value
// the option cannot parse, and leaves the preset unchanged. The key-specific behaviour runs
// through its ConfigOptionsGroup::on_change_OG(): with the option's built field it uses the
// field's typed value, otherwise the owning group builds the value and dispatches the same call,
// so a not-yet-built field still gets it. A key the GUI edits through a custom widget instead
// takes the shared no-field commit path, Tab::load_key_value() in saved mode.
void apply_preset_config_value(const std::string& opt_key, const std::string& value);
virtual void reload_config();
void update_mode();
void update_visibility();
+502 -21
View File
@@ -244,7 +244,7 @@ AMSControl::AMSControl(wxWindow *parent, wxWindowID id, const wxPoint &pos, cons
m_sizer_ams_body->Add(m_sizer_ams_area_right, wxALIGN_CENTER, 0);
m_sizer_body->Add(m_sizer_ams_items, 0, wxALIGN_CENTER, 0);
m_sizer_body->Add(0, 0, 1, wxEXPAND | wxTOP, FromDIP(10));
m_sizer_ams_gap = m_sizer_body->Add(0, 0, 1, wxEXPAND | wxTOP, FromDIP(10));
m_sizer_body->Add(m_sizer_ams_body, 0, wxALIGN_CENTER, 0);
m_sizer_body->Add(m_sizer_down_road, 0, wxALIGN_CENTER, 0);
m_sizer_body->Add(m_sizer_ams_option, 0, wxEXPAND, 0);
@@ -371,7 +371,7 @@ bool AMSControl::IsAmsInRightPanel(std::string ams_id) {
return false;
}
}
else{
else if (m_total_ext_count == 1){
for (auto id : m_item_ids[MAIN_EXTRUDER_ID]){
if (id == ams_id){
return true;
@@ -379,6 +379,10 @@ bool AMSControl::IsAmsInRightPanel(std::string ams_id) {
}
return false;
}
else {
// Generic N Nozzles
}
return false;
}
void AMSControl::AmsSelectedSwitch(wxCommandEvent& event) {
@@ -519,7 +523,7 @@ void AMSControl::msw_rescale()
m_button_ams_setting_press.msw_rescale();
m_button_ams_setting->SetBitmap(m_button_ams_setting_normal.bmp());
m_extruder->msw_rescale();
if (m_extruder) m_extruder->msw_rescale();
if (m_button_extruder_feed) m_button_extruder_feed->Rescale(); // ORCA
if (m_button_extruder_back) m_button_extruder_back->Rescale(); // ORCA
@@ -603,6 +607,8 @@ void AMSControl::CreateAms()
void AMSControl::ClearAms() {
m_sizer_ams_items->Clear(false);
m_simplebook_ams_right->DeleteAllPages();
m_simplebook_ams_left->DeleteAllPages();
m_simplebook_ams_right->DestroyChildren();
@@ -613,7 +619,7 @@ void AMSControl::ClearAms() {
m_simplebook_ams_left->Refresh();
for (auto it : m_ams_preview_list) {
delete it.second;
if (it.second) it.second->Destroy();
}
m_ams_preview_list.clear();
m_ext_image_list.clear();
@@ -624,12 +630,181 @@ void AMSControl::ClearAms() {
m_ams_item_list.clear();
m_sizer_prv_right->Clear();
m_sizer_prv_left->Clear();
m_item_ids = { {}, {} };
if (m_nozzle_book) {
m_nozzle_book->Destroy();
m_nozzle_book = nullptr;
} else {
for (auto &pane : m_nozzle_panes) {
if (pane.preview_panel) pane.preview_panel->Destroy();
if (pane.ams_book) pane.ams_book->Destroy();
if (pane.page) pane.page->Destroy();
}
}
m_item_ids.assign(std::max(m_total_ext_count, 2), {});
m_nozzle_panes.clear();
m_active_nozzle_id = 0;
m_current_ams.clear();
m_current_show_ams_left.clear();
m_current_show_ams_right.clear();
pair_id.clear();
}
void AMSControl::restore_legacy_ams_layout()
{
m_sizer_ams_items->Clear(false);
m_sizer_ams_items->SetOrientation(wxHORIZONTAL);
m_sizer_body->GetItem(m_sizer_ams_items)->SetFlag(wxALIGN_CENTER);
m_sizer_ams_items->Add(m_panel_prv_left, 0, wxLEFT | wxRIGHT, FromDIP(5));
m_sizer_ams_items->Add(m_panel_prv_right, 0, wxLEFT | wxRIGHT, FromDIP(5));
m_panel_prv_left->Show();
m_panel_prv_right->Show();
m_simplebook_ams_left->Show();
m_simplebook_ams_right->Show();
m_panel_down_road->Show();
m_sizer_body->Show(m_sizer_ams_body, true);
m_sizer_option_mid->Show(m_extruder, true);
m_down_road->SetSingleSideLayout(false);
m_sizer_ams_gap->SetProportion(1);
m_sizer_ams_gap->SetBorder(FromDIP(10));
m_down_road->SetNozzleCount(m_total_ext_count);
}
bool AMSControl::use_multi_nozzle_layout() const
{
const bool is_bbl = wxGetApp().preset_bundle && wxGetApp().preset_bundle->is_bbl_vendor();
return is_bbl ? m_total_ext_count > 2 : m_nozzle_book != nullptr;
}
void AMSControl::CreateAmsMultiNozzle(const std::string &series_name, const std::string &printer_type) {
const size_t pane_count = static_cast<size_t>(std::max(m_total_ext_count, 0));
m_nozzle_panes.resize(pane_count);
m_active_nozzle_id = 0;
m_sizer_ams_items->Clear(false);
m_sizer_ams_items->SetOrientation(wxVERTICAL);
m_sizer_body->GetItem(m_sizer_ams_items)->SetFlag(wxALIGN_CENTER);
m_sizer_body->Show(m_sizer_ams_body, false);
m_sizer_ams_gap->SetProportion(0);
m_sizer_ams_gap->SetBorder(0);
m_panel_prv_left->Hide();
m_panel_prv_right->Hide();
m_simplebook_ams_left->Hide();
m_simplebook_ams_right->Hide();
m_panel_down_road->Show();
m_sizer_option_mid->Show(m_extruder, true);
m_switcher->Hide();
m_down_road->SetNozzleCount(1);
m_down_road->SetSingleSideLayout(true, AMSPanelPos::LEFT_PANEL);
m_down_road->UpdateLeft(1, AMSRoadShowMode::AMS_ROAD_MODE_SINGLE);
m_down_road->UpdateRight(1, AMSRoadShowMode::AMS_ROAD_MODE_NONE);
m_extruder->updateNozzleNum(1, series_name);
m_nozzle_book = new wxSimplebook(m_amswin, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0);
m_nozzle_book->SetMinSize(wxSize(FromDIP(264), -1));
m_nozzle_book->SetBackgroundColour(StateColor::darkModeColorFor(AMS_CONTROL_DEF_BLOCK_BK_COLOUR));
m_sizer_ams_items->Add(m_nozzle_book, 0, wxALIGN_CENTER);
for (size_t nozzle_id = 0; nozzle_id < pane_count; ++nozzle_id) {
auto &pane = m_nozzle_panes[nozzle_id];
// A generic page is one H2C side. Keep the left-side geometry as the
// canonical single-nozzle presentation; the road and AMS item code
// still use the same side-specific paths as the legacy layout.
pane.panel_pos = AMSPanelPos::LEFT_PANEL;
pane.page = new wxPanel(m_nozzle_book, wxID_ANY);
pane.page->SetMinSize(wxSize(FromDIP(264), -1));
pane.page->SetBackgroundColour(StateColor::darkModeColorFor(AMS_CONTROL_DEF_BLOCK_BK_COLOUR));
pane.page_sizer = new wxBoxSizer(wxVERTICAL);
pane.page->SetSizer(pane.page_sizer);
pane.preview_panel = new wxScrolledWindow(pane.page, wxID_ANY);
pane.preview_panel->SetScrollRate(10, 0);
pane.preview_panel->SetSize(AMS_ITEMS_PANEL_SIZE);
pane.preview_panel->SetMinSize(AMS_ITEMS_PANEL_SIZE);
pane.preview_panel->SetBackgroundColour(StateColor::darkModeColorFor(AMS_CONTROL_DEF_BLOCK_BK_COLOUR));
pane.preview_sizer = new wxBoxSizer(wxHORIZONTAL);
pane.preview_panel->SetSizer(pane.preview_sizer);
// Generic lane cards grow to their calculated width for 1-8 lanes. Keep the
// book at the legacy minimum, but allow the page to expand to that width.
pane.ams_book = new wxSimplebook(pane.page, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0);
pane.ams_book->SetMinSize(wxSize(FromDIP(264), -1));
pane.ams_book->SetBackgroundColour(StateColor::darkModeColorFor(AMS_CONTROL_DEF_BLOCK_BK_COLOUR));
// wxALIGN_CENTER does not centre horizontally inside a HORIZONTAL sizer, so a book wider
// than pane.ams_area's own minimum would sit at ams_area's left edge and overflow to the
// right, shifting the whole card column off the shared down-road connector axis. A pair of
// stretch spacers keeps the book centred on the pane (and thus on the connector) at any
// book width; ams_area is expanded below so the spacers have room to work with.
pane.ams_area = new wxBoxSizer(wxHORIZONTAL);
pane.ams_area->AddStretchSpacer(1);
pane.ams_area->Add(pane.ams_book, 0, wxALIGN_CENTER, 0);
pane.ams_area->AddStretchSpacer(1);
pane.page_sizer->Add(pane.preview_panel, 0, wxALIGN_CENTER | wxTOP, FromDIP(5));
pane.page_sizer->Add(pane.ams_area, 0, wxEXPAND | wxTOP, FromDIP(10));
m_nozzle_book->AddPage(pane.page, wxEmptyString, nozzle_id == 0);
}
auto add_info = [this, series_name, printer_type, pane_count](AMSinfo info) {
if (pane_count == 0) return;
info.nozzle_id = std::clamp(info.nozzle_id, 0, static_cast<int>(pane_count) - 1);
AddAmsPreview(info, info.ams_type);
if (info.ams_type == AMSModel::EXT_AMS && info.cans.size() == 1)
AddAms({info}, series_name, printer_type, m_nozzle_panes[info.nozzle_id].panel_pos);
else
AddAms(info);
};
for (const auto &info : m_ams_info)
add_info(info);
for (auto &info : m_ext_info) {
const int virtual_tray_id = std::atoi(info.ams_id.c_str());
if (virtual_tray_id <= VIRTUAL_TRAY_MAIN_ID &&
virtual_tray_id >= VIRTUAL_TRAY_MAIN_ID - static_cast<int>(pane_count) + 1)
info.nozzle_id = VIRTUAL_TRAY_MAIN_ID - virtual_tray_id;
add_info(info);
}
for (auto &pane : m_nozzle_panes) {
if (pane.ams_book && pane.ams_book->GetPageCount() > 0)
pane.ams_book->SetSelection(0);
if (pane.preview_sizer) pane.preview_sizer->Layout();
if (pane.preview_panel) pane.preview_panel->FitInside();
if (pane.ams_book) pane.ams_book->Layout();
if (pane.page) pane.page->Layout();
if (!pane.current_ams.empty()) {
auto preview = m_ams_preview_list.find(pane.current_ams);
if (preview != m_ams_preview_list.end() && preview->second)
preview->second->OnSelected();
}
}
if (m_nozzle_book && pane_count > 0) {
m_nozzle_book->SetSelection(0);
m_current_ams = m_nozzle_panes[0].current_ams;
if (!m_current_ams.empty())
SwitchAms(m_current_ams);
else {
m_down_road->UpdateLeft(1, AMSRoadShowMode::AMS_ROAD_MODE_NONE);
m_down_road->UpdateRight(1, AMSRoadShowMode::AMS_ROAD_MODE_NONE);
}
}
m_amswin->Layout();
m_amswin->Fit();
// Generic N Nozzles
}
void AMSControl::CreateAmsDoubleNozzle(const std::string &series_name, const std::string &printer_type)
{
restore_legacy_ams_layout();
std::vector<AMSinfo> single_info_left;
std::vector<AMSinfo> single_info_right;
@@ -751,6 +926,8 @@ void AMSControl::CreateAmsDoubleNozzle(const std::string &series_name, const std
void AMSControl::CreateAmsSingleNozzle(const std::string &series_name, const std::string &printer_type)
{
restore_legacy_ams_layout();
std::vector<int>m_item_nums{0,0};
std::vector<AMSinfo> single_info;
@@ -979,6 +1156,17 @@ void AMSControl::UpdateAms(const std::string &series_name,
if (m_ams_info[i].routes_to_main_extruder() != ams_info[i].routes_to_main_extruder()) {
fresh = true;
}
if (m_ams_info[i].nozzle_id != ams_info[i].nozzle_id) {
fresh = true;
}
}
for (int i = 0; i < static_cast<int>(m_ext_info.size()); ++i) {
if (m_ext_info[i].ams_id != ext_info[i].ams_id ||
m_ext_info[i].nozzle_id != ext_info[i].nozzle_id ||
m_ext_info[i].ext_type != ext_info[i].ext_type) {
fresh = true;
}
}
}
else{
@@ -993,11 +1181,16 @@ void AMSControl::UpdateAms(const std::string &series_name,
m_dev_id = dev_id;
if (fresh){
ClearAms();
if (m_total_ext_count >= 2){
CreateAmsDoubleNozzle(series_name, printer_type);
}else{
CreateAmsSingleNozzle(series_name, printer_type);
bool is_bbl = wxGetApp().preset_bundle && wxGetApp().preset_bundle->is_bbl_vendor();
if (is_bbl) {
if (m_total_ext_count == 1)
CreateAmsSingleNozzle(series_name, printer_type);
else if (m_total_ext_count == 2)
CreateAmsDoubleNozzle(series_name, printer_type);
}
else
CreateAmsMultiNozzle(series_name, printer_type);
SetSize(wxSize(FromDIP(578), -1));
SetMinSize(wxSize(FromDIP(578), -1));
Layout();
@@ -1070,7 +1263,7 @@ void AMSControl::UpdateAms(const std::string &series_name,
}
/*update ams extruder*/
if (m_extruder->updateNozzleNum(m_total_ext_count, series_name))
if (m_total_ext_count <= 2 && m_extruder->updateNozzleNum(m_total_ext_count, series_name))
{
m_amswin->Layout();
}
@@ -1106,7 +1299,15 @@ void AMSControl::AddAmsPreview(AMSinfo info, AMSModel type)
{
AMSPreview *ams_prv = nullptr;
if (info.routes_to_main_extruder())
// Match AddAms: the generic multi-nozzle layout's preview panel is the visible one for
// non-Bambu vendors at any extruder count, not only above two.
if (use_multi_nozzle_layout()) {
const int nozzle_id = std::clamp(info.nozzle_id, 0, m_total_ext_count - 1);
auto &pane = m_nozzle_panes[nozzle_id];
ams_prv = new AMSPreview(pane.preview_panel, wxID_ANY, info, type);
pane.preview_sizer->Add(ams_prv, 0, wxALIGN_CENTER | wxLEFT, FromDIP(6));
}
else if (info.routes_to_main_extruder())
{
ams_prv = new AMSPreview(m_panel_prv_right, wxID_ANY, info, type);
m_sizer_prv_right->Add(ams_prv, 0, wxALIGN_CENTER | wxLEFT, FromDIP(6));
@@ -1129,6 +1330,54 @@ void AMSControl::AddAmsPreview(AMSinfo info, AMSModel type)
void AMSControl::createAms(wxSimplebook* parent, int& idx, AMSinfo info, AMSPanelPos pos) {
auto ams_item = new AmsItem(parent, info, info.ams_type, pos);
parent->InsertPage(idx, ams_item, wxEmptyString, true);
// Generic AMS cards may be wider than the legacy 264 DIP page. Propagate
// that calculated width through the page and simplebook so 5-8 lanes are
// laid out fully instead of being clipped by the old minimum width.
if (info.ams_type == AMSModel::GENERIC_AMS) {
const int required_width = ams_item->GetMinSize().x;
if (required_width > 0) {
const int page_width = std::max(parent->GetMinSize().x, required_width);
parent->SetMinSize(wxSize(page_width, -1));
if (auto *page = parent->GetParent()) {
page->SetMinSize(wxSize(std::max(page->GetMinSize().x, page_width), -1));
if (auto *nozzle_book = page->GetParent())
nozzle_book->SetMinSize(wxSize(std::max(nozzle_book->GetMinSize().x, page_width), -1));
}
}
// Above eight lanes, AmsItem is a fixed-minimum viewport over a wider
// lane strip. Expand the viewport through its page's sizers rather
// than propagating the strip's virtual width into the card/book.
// Reset back to the centered fixed layout for eight or fewer lanes so a
// later small unit is not left in expand mode.
const bool generic_lane_layout = !wxGetApp().preset_bundle || !wxGetApp().preset_bundle->is_bbl_vendor();
if (generic_lane_layout) {
if (auto *page = parent->GetParent()) {
auto pane = std::find_if(m_nozzle_panes.begin(), m_nozzle_panes.end(),
[page](const NozzleAmsPane &candidate) { return candidate.page == page; });
if (pane != m_nozzle_panes.end() && m_nozzle_book) {
const bool expand_viewport = info.cans.size() > 8;
if (auto *book_item = pane->ams_area->GetItem(pane->ams_book)) {
book_item->SetProportion(expand_viewport ? 1 : 0);
book_item->SetFlag(expand_viewport ? wxEXPAND : wxALIGN_CENTER);
}
// Keep the centring spacers (items 0 and 2) elastic only in the centred layout;
// in the >8-lane viewport they must collapse so the book can fill ams_area.
if (auto *lead = pane->ams_area->GetItem(static_cast<size_t>(0)))
lead->SetProportion(expand_viewport ? 0 : 1);
if (auto *trail = pane->ams_area->GetItem(static_cast<size_t>(2)))
trail->SetProportion(expand_viewport ? 0 : 1);
if (auto *area_item = pane->page_sizer->GetItem(pane->ams_area))
area_item->SetFlag(wxEXPAND | wxTOP);
if (auto *nozzle_book_item = m_sizer_ams_items->GetItem(m_nozzle_book))
nozzle_book_item->SetFlag(expand_viewport ? wxEXPAND : wxALIGN_CENTER);
if (auto *items_item = m_sizer_body->GetItem(m_sizer_ams_items))
items_item->SetFlag(expand_viewport ? wxEXPAND : wxALIGN_CENTER);
m_amswin->Layout();
}
}
}
}
ams_item->set_selection(idx);
idx++;
@@ -1153,7 +1402,10 @@ AMSRoadShowMode AMSControl::findFirstMode(AMSPanelPos pos) {
if (item->second->get_ams_model() == AMSModel::EXT_AMS && item->second->get_ext_type() == AMSModelOriginType::LITE_EXT) return AMSRoadShowMode::AMS_ROAD_MODE_AMS_LITE;
return AMSRoadShowMode::AMS_ROAD_MODE_FOUR;
}
else{
else if (item->second->get_can_count() > GENERIC_AMS_SLOT_NUM) {
return AMSRoadShowMode::AMS_ROAD_MODE_GENERIC;
}
else {
for (auto ids : pair_id){
if (ids.first == ams_id || ids.second == ams_id){
return AMSRoadShowMode::AMS_ROAD_MODE_DOUBLE;
@@ -1172,8 +1424,13 @@ void AMSControl::createAmsPanel(wxSimplebook *parent, int &idx, std::vector<AMSi
wxPanel* book_panel = new wxPanel(parent);
wxBoxSizer* book_sizer = new wxBoxSizer(wxHORIZONTAL);
book_panel->SetBackgroundColour(StateColor::darkModeColorFor(AMS_CONTROL_DEF_LIB_BK_COLOUR));
book_panel->SetSize(AMS_PANEL_SIZE);
book_panel->SetMinSize(AMS_PANEL_SIZE);
// Size the page to the AMS book it becomes, not to the legacy fixed width: an AMS card is
// added directly as the book page (so it always spans the book), while a single external
// spool is wrapped here. Matching the book keeps the Ext card centred on the same axis as
// the AMS cards and the shared down-road connector anchored below them.
const wxSize book_panel_size(std::max(parent->GetMinSize().x, AMS_PANEL_SIZE.x), AMS_PANEL_SIZE.y);
book_panel->SetSize(book_panel_size);
book_panel->SetMinSize(book_panel_size);
AmsItem* ams1 = nullptr, * ams2 = nullptr;
ams1 = new AmsItem(book_panel, infos[0], infos[0].ams_type, pos);
@@ -1200,6 +1457,14 @@ void AMSControl::createAmsPanel(wxSimplebook *parent, int &idx, std::vector<AMSi
//book_sizer->Add(ams1, 0, wxALIGN_CENTER_HORIZONTAL, 0);
book_sizer->Add(ams1, 0, wxLEFT, (book_panel->GetSize().x - ams1->GetSize().x) / 2);
}
else if (pos == AMSPanelPos::SINGLE_PANEL) {
// Centre the single external-spool card explicitly, using the same fixed-margin
// technique as the Lite-EXT branch above. Two stretch spacers centred the card
// against the wrapper's own width rather than the AMS book, which left the card
// (and the connector drawn below it) off the book/connector axis.
book_sizer->Add(ams1, 0, wxLEFT,
std::max(0, (book_panel_size.x - ams1->GetSize().x) / 2));
}
else{
auto ext_image = new AMSExtImage(book_panel, pos, m_total_ext_count, false);
book_sizer->Add(ams1, 0, wxLEFT, FromDIP(30));
@@ -1228,7 +1493,20 @@ void AMSControl::createAmsPanel(wxSimplebook *parent, int &idx, std::vector<AMSi
void AMSControl::AddAms(AMSinfo info, AMSPanelPos pos)
{
if (m_total_ext_count > 1){
// The generic multi-nozzle layout (non-Bambu vendors) owns the only visible book; a unit must
// land there for any extruder count. Keying off m_total_ext_count instead sent 1- and 2-extruder
// generic printers into the legacy simplebooks that CreateAmsMultiNozzle hides.
if (use_multi_nozzle_layout()) {
const int nozzle_id = std::clamp(info.nozzle_id, 0, m_total_ext_count - 1);
auto &pane = m_nozzle_panes[nozzle_id];
pane.item_ids.push_back(info.ams_id);
m_item_ids[nozzle_id].push_back(info.ams_id);
if (pane.current_ams.empty()) pane.current_ams = info.ams_id;
createAms(pane.ams_book, pane.page_index, info, AMSPanelPos::SINGLE_PANEL);
pane.ams_book->Fit();
pane.ams_book->Layout();
}
else if (m_total_ext_count == 2){
if (info.routes_to_main_extruder()){
createAms(m_simplebook_ams_right, m_right_page_index, info, AMSPanelPos::RIGHT_PANEL);
}
@@ -1239,6 +1517,9 @@ void AMSControl::AddAms(AMSinfo info, AMSPanelPos pos)
else if (m_total_ext_count == 1){
createAms(m_simplebook_ams_left, m_left_page_index, info, AMSPanelPos::LEFT_PANEL);
}
else {
// Generic N Nozzles
}
m_simplebook_ams_left->Layout();
m_simplebook_ams_right->Layout();
m_simplebook_ams_left->Refresh();
@@ -1269,7 +1550,19 @@ void AMSControl::AddAms(std::vector<AMSinfo> single_info, const std::string &ser
if (single_info.size() <= 0){
return;
}
if (m_total_ext_count == 2) {
if (use_multi_nozzle_layout()) {
const int nozzle_id = std::clamp(single_info.front().nozzle_id, 0, m_total_ext_count - 1);
auto &pane = m_nozzle_panes[nozzle_id];
for (const auto &info : single_info) {
pane.item_ids.push_back(info.ams_id);
m_item_ids[nozzle_id].push_back(info.ams_id);
}
if (pane.current_ams.empty()) pane.current_ams = single_info.front().ams_id;
createAmsPanel(pane.ams_book, pane.page_index, single_info, series_name, printer_type, AMSPanelPos::SINGLE_PANEL, m_total_ext_count);
pane.ams_book->Fit();
pane.ams_book->Layout();
}
else if (m_total_ext_count == 2) {
if (single_info[0].routes_to_main_extruder()) {
createAmsPanel(m_simplebook_ams_right, m_right_page_index, single_info, series_name, printer_type, AMSPanelPos::RIGHT_PANEL, m_total_ext_count);
}
@@ -1285,6 +1578,9 @@ void AMSControl::AddAms(std::vector<AMSinfo> single_info, const std::string &ser
createAmsPanel(m_simplebook_ams_left, m_left_page_index, single_info, series_name, printer_type, AMSPanelPos::LEFT_PANEL, m_total_ext_count);
}
}
else {
// Generic N Nozzles
}
m_simplebook_ams_left->Layout();
m_simplebook_ams_right->Layout();
@@ -1322,6 +1618,21 @@ void AMSControl::AddAms(std::vector<AMSinfo> single_info, const std::string &ser
void AMSControl::AddAmsPreview(std::vector<AMSinfo>single_info, AMSPanelPos pos) {
if (single_info.size() <= 0) return;
if (use_multi_nozzle_layout()) {
const int nozzle_id = std::clamp(single_info.front().nozzle_id, 0, m_total_ext_count - 1);
auto &pane = m_nozzle_panes[nozzle_id];
for (const auto &info : single_info) {
auto *ams_prv = new AMSPreview(pane.preview_panel, wxID_ANY, info, info.ams_type);
pane.preview_sizer->Add(ams_prv, 0, wxALIGN_CENTER | wxLEFT, FromDIP(6));
ams_prv->Bind(wxEVT_LEFT_DOWN, [this, ams_prv](wxMouseEvent &e) {
SwitchAms(ams_prv->get_ams_id());
e.Skip();
});
m_ams_preview_list[info.ams_id] = ams_prv;
}
return;
}
AMSPreview* ams_prv = nullptr;
AMSPreview* ams_prv2 = nullptr;
if (pos == AMSPanelPos::RIGHT_PANEL){
@@ -1360,8 +1671,97 @@ void AMSControl::AddAmsPreview(std::vector<AMSinfo>single_info, AMSPanelPos pos)
}
}
void AMSControl::SelectNozzle(int nozzle_id)
{
if (nozzle_id < 0 || nozzle_id >= static_cast<int>(m_nozzle_panes.size()))
return;
if (m_active_nozzle_id == nozzle_id &&
(!m_nozzle_book || m_nozzle_book->GetSelection() == nozzle_id))
return;
m_active_nozzle_id = nozzle_id;
if (m_nozzle_book && m_nozzle_book->GetSelection() != nozzle_id)
m_nozzle_book->SetSelection(nozzle_id);
m_current_ams = m_nozzle_panes[nozzle_id].current_ams;
if (!m_current_ams.empty()) {
SwitchAms(m_current_ams);
return;
}
if (m_down_road) {
m_down_road->UpdateLeft(1, AMSRoadShowMode::AMS_ROAD_MODE_NONE);
m_down_road->UpdateRight(1, AMSRoadShowMode::AMS_ROAD_MODE_NONE);
}
if (m_extruder)
m_extruder->OnAmsLoading(false, 0);
post_event(SimpleEvent(EVT_AMS_SWITCH));
}
void AMSControl::SwitchAms(std::string ams_id)
{
if (use_multi_nozzle_layout()) {
NozzleAmsPane *pane = nullptr;
int nozzle_id = -1;
for (int index = 0; index < static_cast<int>(m_nozzle_panes.size()); ++index) {
auto &candidate = m_nozzle_panes[index];
if (std::find(candidate.item_ids.begin(), candidate.item_ids.end(), ams_id) != candidate.item_ids.end()) {
pane = &candidate;
nozzle_id = index;
break;
}
}
if (!pane) return;
m_active_nozzle_id = nozzle_id;
if (m_nozzle_book && m_nozzle_book->GetSelection() != nozzle_id)
m_nozzle_book->SetSelection(nozzle_id);
pane->current_ams = ams_id;
m_current_ams = ams_id;
m_current_select = ams_id;
for (const auto &id : pane->item_ids) {
auto preview = m_ams_preview_list.find(id);
if (preview == m_ams_preview_list.end() || !preview->second) continue;
if (id == ams_id) preview->second->OnSelected();
else preview->second->UnSelected();
}
auto item = m_ams_item_list.find(ams_id);
if (item != m_ams_item_list.end() && item->second) {
if (pane->ams_book)
pane->ams_book->SetSelection(item->second->get_selection());
AMSRoadShowMode road_mode = AMSRoadShowMode::AMS_ROAD_MODE_SINGLE;
if (item->second->get_can_count() == GENERIC_AMS_SLOT_NUM)
road_mode = AMSRoadShowMode::AMS_ROAD_MODE_FOUR;
else if (item->second->get_can_count() > GENERIC_AMS_SLOT_NUM)
road_mode = AMSRoadShowMode::AMS_ROAD_MODE_GENERIC;
else if (item->second->get_ams_model() == AMSModel::N3S_AMS)
road_mode = AMSRoadShowMode::AMS_ROAD_MODE_SINGLE_N3S;
else if (item->second->get_ams_model() == AMSModel::AMS_LITE ||
(item->second->get_ams_model() == AMSModel::EXT_AMS &&
item->second->get_ext_type() == AMSModelOriginType::LITE_EXT))
road_mode = AMSRoadShowMode::AMS_ROAD_MODE_AMS_LITE;
if (m_down_road) {
if (pane->panel_pos == AMSPanelPos::LEFT_PANEL) {
m_down_road->UpdateLeft(1, road_mode);
m_down_road->UpdateRight(1, AMSRoadShowMode::AMS_ROAD_MODE_NONE);
} else {
m_down_road->UpdateLeft(1, AMSRoadShowMode::AMS_ROAD_MODE_NONE);
m_down_road->UpdateRight(1, road_mode);
}
m_down_road->UpdatePassRoad(pane->panel_pos, -1, AMSPassRoadSTEP::AMS_ROAD_STEP_NONE);
}
if (m_extruder)
m_extruder->OnAmsLoading(false, 0);
}
post_event(SimpleEvent(EVT_AMS_SWITCH));
return;
}
if(ams_id == m_current_show_ams_left || ams_id == m_current_show_ams_right){return;}
bool is_in_right = IsAmsInRightPanel(ams_id);
@@ -1432,13 +1832,17 @@ void AMSControl::SwitchAms(std::string ams_id)
else {
AMSRoadShowMode mode = AMSRoadShowMode::AMS_ROAD_MODE_SINGLE;
if (item->get_ams_model() == AMSModel::N3S_AMS)
if (item->get_can_count() > GENERIC_AMS_SLOT_NUM)
mode = AMSRoadShowMode::AMS_ROAD_MODE_GENERIC;
else if (item->get_ams_model() == AMSModel::N3S_AMS)
mode = AMSRoadShowMode::AMS_ROAD_MODE_SINGLE_N3S;
for (auto it : pair_id) {
if (it.first == ams_id || it.second == ams_id) {
mode = AMSRoadShowMode::AMS_ROAD_MODE_DOUBLE;
break;
if (item->get_can_count() <= GENERIC_AMS_SLOT_NUM) {
for (auto it : pair_id) {
if (it.first == ams_id || it.second == ams_id) {
mode = AMSRoadShowMode::AMS_ROAD_MODE_DOUBLE;
break;
}
}
}
pos == AMSPanelPos::LEFT_PANEL ? m_down_road->UpdateLeft(m_total_ext_count, mode)
@@ -1500,6 +1904,20 @@ void AMSControl::SetExtruder(bool on_off, int nozzle_id, std::string ams_id, std
AmsItem *item = nullptr;
if (m_ams_item_list.find(ams_id) != m_ams_item_list.end()) { item = m_ams_item_list[ams_id]; }
if (use_multi_nozzle_layout()) {
if (nozzle_id < 0 || nozzle_id >= static_cast<int>(m_nozzle_panes.size()))
return;
if (!m_extruder)
return;
if (on_off && item)
m_extruder->OnAmsLoading(true, 0, item->GetTagColr(slot_id));
else
m_extruder->OnAmsLoading(false, 0);
return;
}
if (on_off && item) {
auto col = item->GetTagColr(slot_id);
m_extruder->OnAmsLoading(true, nozzle_id, col);
@@ -1624,6 +2042,69 @@ void AMSControl::SetAmsStep(std::string ams_id, std::string canid, AMSPassRoadTy
else{
return;
}
if (use_multi_nozzle_layout()) {
const int nozzle_id = std::clamp(ams->get_nozzle_id(), 0, m_total_ext_count - 1);
if (nozzle_id >= static_cast<int>(m_nozzle_panes.size()))
return;
auto &pane = m_nozzle_panes[nozzle_id];
AMSRoadShowMode road_mode = AMSRoadShowMode::AMS_ROAD_MODE_SINGLE;
if (ams->get_can_count() == GENERIC_AMS_SLOT_NUM)
road_mode = AMSRoadShowMode::AMS_ROAD_MODE_FOUR;
else if (ams->get_can_count() > GENERIC_AMS_SLOT_NUM)
road_mode = AMSRoadShowMode::AMS_ROAD_MODE_GENERIC;
else if (ams->get_ams_model() == AMSModel::N3S_AMS)
road_mode = AMSRoadShowMode::AMS_ROAD_MODE_SINGLE_N3S;
else if (ams->get_ams_model() == AMSModel::AMS_LITE ||
(ams->get_ams_model() == AMSModel::EXT_AMS && ams->get_ext_type() == AMSModelOriginType::LITE_EXT))
road_mode = AMSRoadShowMode::AMS_ROAD_MODE_AMS_LITE;
if (can_index >= 0 && can_index < static_cast<int>(info.cans.size()) && m_down_road)
m_down_road->SetPassRoadColour(pane.panel_pos == AMSPanelPos::LEFT_PANEL,
info.cans[can_index].material_colour);
if (m_down_road) {
if (pane.panel_pos == AMSPanelPos::LEFT_PANEL) {
m_down_road->UpdateLeft(1, road_mode);
m_down_road->UpdateRight(1, AMSRoadShowMode::AMS_ROAD_MODE_NONE);
} else {
m_down_road->UpdateLeft(1, AMSRoadShowMode::AMS_ROAD_MODE_NONE);
m_down_road->UpdateRight(1, road_mode);
}
}
int road_length = 0;
if (step == AMSPassRoadSTEP::AMS_ROAD_STEP_NONE) {
ams->SetAmsStep(ams_id, canid, type, AMSPassRoadSTEP::AMS_ROAD_STEP_NONE);
if (m_down_road)
m_down_road->UpdatePassRoad(pane.panel_pos, -1, AMSPassRoadSTEP::AMS_ROAD_STEP_NONE);
if (m_extruder)
m_extruder->OnAmsLoading(false, 0);
}
else if (step == AMSPassRoadSTEP::AMS_ROAD_STEP_COMBO_LOAD_STEP1) {
ams->SetAmsStep(ams_id, canid, type, AMSPassRoadSTEP::AMS_ROAD_STEP_1);
if (m_down_road)
m_down_road->UpdatePassRoad(pane.panel_pos, road_length, AMSPassRoadSTEP::AMS_ROAD_STEP_1);
if (m_extruder)
m_extruder->OnAmsLoading(false, 0);
}
else if (step == AMSPassRoadSTEP::AMS_ROAD_STEP_COMBO_LOAD_STEP2) {
ams->SetAmsStep(ams_id, canid, type, AMSPassRoadSTEP::AMS_ROAD_STEP_2);
if (m_down_road)
m_down_road->UpdatePassRoad(pane.panel_pos, road_length, AMSPassRoadSTEP::AMS_ROAD_STEP_2);
if (m_extruder)
m_extruder->OnAmsLoading(true, 0, ams->GetTagColr(canid));
}
else if (step == AMSPassRoadSTEP::AMS_ROAD_STEP_COMBO_LOAD_STEP3) {
ams->SetAmsStep(ams_id, canid, type, AMSPassRoadSTEP::AMS_ROAD_STEP_3);
if (m_down_road)
m_down_road->UpdatePassRoad(pane.panel_pos, road_length, AMSPassRoadSTEP::AMS_ROAD_STEP_3);
if (m_extruder)
m_extruder->OnAmsLoading(true, 0, ams->GetTagColr(canid));
}
return;
}
if (can_index >= 0 && can_index < info.cans.size())
{
m_down_road->SetPassRoadColour(left, info.cans[can_index].material_colour);
+27
View File
@@ -47,6 +47,20 @@ public:
void on_retry();
protected:
struct NozzleAmsPane
{
wxPanel* page{nullptr};
wxBoxSizer* page_sizer{nullptr};
wxScrolledWindow* preview_panel{nullptr};
wxBoxSizer* preview_sizer{nullptr};
wxSimplebook* ams_book{nullptr};
wxBoxSizer* ams_area{nullptr};
AMSPanelPos panel_pos{AMSPanelPos::LEFT_PANEL};
std::vector<std::string> item_ids;
std::string current_ams;
int page_index{0};
};
std::string m_current_ams;
std::string m_current_slot_left;
std::string m_current_slot_right;
@@ -63,6 +77,9 @@ protected:
std::string m_dev_id;
std::vector<std::vector<std::string>> m_item_ids{ {}, {} };
std::vector<NozzleAmsPane> m_nozzle_panes;
wxSimplebook* m_nozzle_book{nullptr};
int m_active_nozzle_id{0};
std::vector<std::pair<std::string, std::string>> pair_id;
int m_total_ext_count = 1;
@@ -103,6 +120,7 @@ protected:
wxSimplebook *m_simplebook_ams_left{nullptr};
wxSimplebook *m_simplebook_ams_right{ nullptr };
wxSimplebook *m_simplebook_bottom{nullptr};
wxSizerItem *m_sizer_ams_gap{nullptr};
wxPanel *m_panel_down_road{ nullptr };
int m_left_page_index = 0;
int m_right_page_index = 0;
@@ -156,6 +174,7 @@ public:
void createAms(wxSimplebook* parent, int& idx, AMSinfo info, AMSPanelPos pos);
void createAmsPanel(wxSimplebook *parent, int &idx, std::vector<AMSinfo> infos, const std::string &series_name, const std::string &printer_type, AMSPanelPos pos, int total_ext_num);
AMSRoadShowMode findFirstMode(AMSPanelPos pos);
void restore_legacy_ams_layout();
AMSModel m_ams_model{AMSModel::EXT_AMS};
AMSModel m_ext_model{AMSModel::EXT_AMS};
@@ -183,6 +202,7 @@ public:
void UpdatePassRoad(std::string ams_id, AMSPassRoadType type, AMSPassRoadSTEP step);
void CreateAms();
void CreateAmsMultiNozzle(const std::string& series_name, const std::string& printer_type);
void CreateAmsDoubleNozzle(const std::string &series_name, const std::string& printer_type);
void CreateAmsSingleNozzle(const std::string &series_name, const std::string &printer_type);
void ClearAms();
@@ -210,6 +230,8 @@ public:
void SetExtruder(bool on_off, int nozzle_id, std::string ams_id, std::string slot_id);
void SetAmsStep(std::string ams_id, std::string canid, AMSPassRoadType type, AMSPassRoadSTEP step);
void SwitchAms(std::string ams_id);
void SelectNozzle(int nozzle_id);
int GetActiveNozzleId() const { return m_active_nozzle_id; }
void msw_rescale();
void on_filament_load(wxCommandEvent &event);
@@ -234,6 +256,11 @@ public:
private:
std::string get_filament_id(const std::string& ams_id, const std::string& can_id);
// True when AMS units are laid out on the generic multi-nozzle book. Bambu
// printers keep the legacy count-based single/double-nozzle layout at any
// extruder count; other vendors use the book created for them.
bool use_multi_nozzle_layout() const;
public:
std::string m_current_select;
};
+350 -112
View File
@@ -38,12 +38,11 @@
#include <cstddef>
#include <wx/simplebook.h>
#include <wx/dcgraph.h>
#include <wx/graphics.h>
#include <memory>
#include <boost/log/trivial.hpp>
#include <wx/timer.h>
#include <wx/sizer.h>
#include <wx/scrolwin.h>
#include "CalibUtils.hpp"
#include "slic3r/GUI/wxExtensions.hpp"
@@ -78,6 +77,48 @@ namespace Slic3r { namespace GUI {
//#define AMS_SINGLE_CAN_SIZE wxSize(FromDIP(78), 144)
#define AMS_CANS_WINDOW_SIZE wxSize(FromDIP(264), FromDIP(174))
#define AMS_SINGLE_CAN_SIZE wxSize(FromDIP(78), FromDIP(174))
int generic_ams_layout_width(wxWindow *window, int lane_count)
{
const int base_width = window->FromDIP(264);
const int lane_width = window->FromDIP(52);
const int lane_gap = window->FromDIP(4);
if (lane_count <= 4)
return base_width;
// Lane centers are distributed as width * (index + 1) / (count + 1).
// Keep at least one card width plus the requested gap between centers.
return std::max(base_width, (lane_count + 1) * (lane_width + lane_gap));
}
std::vector<int> generic_ams_lane_centers(int lane_count, int width)
{
std::vector<int> centers;
if (lane_count <= 0)
return centers;
centers.reserve(lane_count);
for (int lane = 0; lane < lane_count; ++lane)
centers.push_back(width * (lane + 1) / (lane_count + 1));
return centers;
}
int generic_ams_preview_width(wxWindow *window, int lane_count)
{
const int base_width = window->FromDIP(52);
const int lane_width = window->FromDIP(9);
const int lane_gap = window->FromDIP(4);
if (lane_count <= 0)
return base_width;
return std::max(base_width, lane_count * lane_width + (lane_count + 1) * lane_gap);
}
bool use_generic_ams_layout(AMSModel model)
{
return model == AMSModel::GENERIC_AMS &&
(!wxGetApp().preset_bundle || !wxGetApp().preset_bundle->is_bbl_vendor());
}
bool AMSinfo::parse_ams_info(MachineObject *obj, DevAms *ams, bool remain_flag, bool humidity_flag)
{
if (!ams) return false;
@@ -172,10 +213,14 @@ void AMSinfo::parse_ext_info(MachineObject* obj, DevAmsTray tray) {
info.can_id = std::to_string(0);
this->cans.clear();
if (tray.id == std::to_string(VIRTUAL_TRAY_MAIN_ID))
try {
const int virtual_tray_id = std::stoi(tray.id);
if (virtual_tray_id >= 0 && virtual_tray_id <= VIRTUAL_TRAY_MAIN_ID)
this->nozzle_id = VIRTUAL_TRAY_MAIN_ID - virtual_tray_id;
}
catch (...) {
this->nozzle_id = 0;
else if (tray.id == std::to_string(VIRTUAL_TRAY_DEPUTY_ID))
this->nozzle_id = 1;
}
if (tray.is_tray_info_ready()) {
info.ctype = tray.ctype;
@@ -858,7 +903,11 @@ AMSextruder::AMSextruder(wxWindow *parent, wxWindowID id, int nozzle_num, const
void AMSextruder::TurnOff()
{
m_left_extruder->TurnOff();
if (m_left_extruder) m_left_extruder->TurnOff();
if (m_right_extruder) m_right_extruder->TurnOff();
for (auto *extruder : m_nozzle_extruders) {
if (extruder) extruder->TurnOff();
}
}
void AMSextruder::create(wxWindow *parent, wxWindowID id, const wxPoint &pos, const wxSize &size, int nozzle_num)
@@ -884,7 +933,7 @@ void AMSextruder::OnAmsLoading(bool load, int nozzle_id, wxColour col /*= AMS_CO
m_left_extruder->OnAmsLoading(load, col);
if (load) m_current_colur_deputy = col;
}
else if (m_nozzle_num > 1){
else if (m_nozzle_num == 2){
if (nozzle_id == MAIN_EXTRUDER_ID) {
m_right_extruder->OnAmsLoading(load, col);
if (m_current_colur != col){
@@ -898,6 +947,15 @@ void AMSextruder::OnAmsLoading(bool load, int nozzle_id, wxColour col /*= AMS_CO
}
}
}
else if (m_nozzle_num > 2) {
if (nozzle_id >= 0 && nozzle_id < static_cast<int>(m_nozzle_extruders.size())) {
m_nozzle_extruders[nozzle_id]->OnAmsLoading(load, col);
if (load) m_current_colur = col;
}
}
else {
// Generic N Nozzles
}
}
/*return true if something is updated*/
@@ -907,12 +965,26 @@ bool AMSextruder::updateNozzleNum(int nozzle_num, const std::string& series_name
m_series_name = series_name;
m_nozzle_num = nozzle_num;
this->DestroyChildren();
m_left_extruder = nullptr;
m_right_extruder = nullptr;
m_nozzle_extruders.clear();
m_right_extruder = new AMSextruderImage(this, wxID_ANY, "right_nozzle", AMS_EXTRUDER_DOUBLE_NOZZLE_BITMAP_SIZE);
m_bitmap_sizer = new wxBoxSizer(wxHORIZONTAL);
if (m_nozzle_num == 1) {
if (MachineObject::is_series_n(m_series_name)) {
m_left_extruder = new AMSextruderImage(this, wxID_ANY, "single_nozzle_n", AMS_EXTRUDER_SINGLE_NOZZLE_N_SIZE);
} else if (MachineObject::is_series_x(m_series_name) || MachineObject::is_series_p(m_series_name)) {
m_left_extruder = new AMSextruderImage(this, wxID_ANY, "single_nozzle_xp", AMS_EXTRUDER_SINGLE_NOZZLE_XP_SIZE);
} else {
m_left_extruder = new AMSextruderImage(this, wxID_ANY, "single_nozzle_xp", AMS_EXTRUDER_SINGLE_NOZZLE_XP_SIZE);
}
wxBoxSizer* m_bitmap_sizer = new wxBoxSizer(wxHORIZONTAL);
if (m_nozzle_num >= 2)
m_left_extruder->setShowState(true);
m_bitmap_sizer->Add(m_left_extruder, 0, wxALIGN_LEFT | wxALIGN_TOP, 0);
}
else if (m_nozzle_num == 2)
{
m_right_extruder = new AMSextruderImage(this, wxID_ANY, "right_nozzle", AMS_EXTRUDER_DOUBLE_NOZZLE_BITMAP_SIZE);
m_left_extruder = new AMSextruderImage(this, wxID_ANY, "left_nozzle", AMS_EXTRUDER_DOUBLE_NOZZLE_BITMAP_SIZE);
m_left_extruder->setShowState(true);
m_right_extruder->setShowState(true);
@@ -920,25 +992,17 @@ bool AMSextruder::updateNozzleNum(int nozzle_num, const std::string& series_name
m_bitmap_sizer->Add(m_right_extruder, 0, wxLEFT | wxALIGN_TOP, FromDIP(2));
m_bitmap_sizer->AddSpacer(2);
}
else if (m_nozzle_num > 2) {
for (int nozzle_id = 0; nozzle_id < m_nozzle_num; ++nozzle_id) {
auto *extruder = new AMSextruderImage(this, wxID_ANY, "single_nozzle_n", AMS_EXTRUDER_SINGLE_NOZZLE_N_SIZE);
extruder->setShowState(true);
m_nozzle_extruders.push_back(extruder);
m_bitmap_sizer->Add(extruder, 0, wxALIGN_LEFT | wxALIGN_TOP, 0);
}
}
else
{
if (MachineObject::is_series_n(m_series_name))
{
m_left_extruder = new AMSextruderImage(this, wxID_ANY, "single_nozzle_n", AMS_EXTRUDER_SINGLE_NOZZLE_N_SIZE);
}
else if(MachineObject::is_series_x(m_series_name) || MachineObject::is_series_p(m_series_name))
{
m_left_extruder = new AMSextruderImage(this, wxID_ANY, "single_nozzle_xp", AMS_EXTRUDER_SINGLE_NOZZLE_XP_SIZE);
}
else
{
m_left_extruder = new AMSextruderImage(this, wxID_ANY, "single_nozzle_xp", AMS_EXTRUDER_SINGLE_NOZZLE_XP_SIZE);
}
m_left_extruder->setShowState(true);
m_right_extruder->setShowState(false);
m_bitmap_sizer->Add(m_left_extruder, 0, wxALIGN_LEFT | wxALIGN_TOP, 0);
m_bitmap_sizer->Add(m_right_extruder, 0, wxLEFT | wxALIGN_TOP, FromDIP(3));
// Generic N Nozzles
}
SetSizer(m_bitmap_sizer);
@@ -953,6 +1017,9 @@ void AMSextruder::msw_rescale()
//m_amsSextruder->msw_rescale();
if (m_left_extruder) m_left_extruder->msw_rescale();
if (m_right_extruder) m_right_extruder->msw_rescale();
for (auto *extruder : m_nozzle_extruders) {
if (extruder) extruder->msw_rescale();
}
Layout();
Update();
Refresh();
@@ -1411,17 +1478,22 @@ void AMSLib::render_lite_lib(wxDC& dc)
dc.SetPen(wxPen(*wxTRANSPARENT_PEN));
if (m_info.material_cols.size() > 1) {
wxRect color_rect(FromDIP(10), FromDIP(10), libsize.x - FromDIP(18), libsize.y - FromDIP(18));
int left = FromDIP(10);
int gwidth = std::round(libsize.x / (m_info.material_cols.size() - 1));
//gradient
if (m_info.ctype == 0) {
fill_gradient_rect_east(dc, color_rect, m_info.material_cols.front(), m_info.material_cols.back());
for (int i = 0; i < m_info.material_cols.size() - 1; i++) {
auto rect = wxRect(left, FromDIP(10), libsize.x - FromDIP(18), libsize.y - FromDIP(18));
fill_gradient_rect_east(dc, rect, m_info.material_cols[i], m_info.material_cols[i + 1]);
left += gwidth;
}
}
else {
int cols_size = m_info.material_cols.size();
for (int i = 0; i < cols_size; i++) {
dc.SetBrush(wxBrush(m_info.material_cols[i]));
int x = color_rect.x + color_rect.width * i / cols_size;
int next_x = color_rect.x + color_rect.width * (i + 1) / cols_size;
dc.DrawRectangle(x, color_rect.y, next_x - x, color_rect.height);
float x = FromDIP(10) + ((float)libsize.x - FromDIP(18)) * i / cols_size;
dc.DrawRoundedRectangle(x, FromDIP(10), ((float)libsize.x - FromDIP(17)) / cols_size, libsize.y - FromDIP(20), 0);
}
dc.SetBrush(wxBrush(tmp_lib_colour));
}
@@ -1513,27 +1585,7 @@ void AMSLib::render_generic_lib(wxDC &dc)
int top = height - curr_height;
if (m_ams_model == EXT_AMS){
wxRect color_rect(FromDIP(1), FromDIP(1), size.x - FromDIP(2), size.y - FromDIP(1));
if ((m_info.ctype == 0 || m_info.ctype == 1) && m_info.material_cols.size() > 1 && alpha != 0) {
if (m_info.ctype == 0) {
fill_gradient_rect_east(dc, color_rect, m_info.material_cols.front(), m_info.material_cols.back());
}
else {
int cols_size = static_cast<int>(m_info.material_cols.size());
for (int i = 0; i < cols_size; i++) {
dc.SetPen(wxPen(*wxTRANSPARENT_PEN));
dc.SetBrush(wxBrush(m_info.material_cols[i]));
int x = color_rect.x + color_rect.width * i / cols_size;
int next_x = color_rect.x + color_rect.width * (i + 1) / cols_size;
dc.DrawRectangle(x, color_rect.y, next_x - x, color_rect.height);
}
}
dc.SetPen(wxPen(*wxTRANSPARENT_PEN));
dc.SetBrush(wxBrush(tmp_lib_colour));
}
else {
dc.DrawRoundedRectangle(color_rect.x, color_rect.y, color_rect.width, color_rect.height, m_radius - 1);
}
dc.DrawRoundedRectangle(FromDIP(1), FromDIP(1), size.x - FromDIP(2), size.y - FromDIP(1), m_radius - 1);
if (alpha == 0) {
dc.DrawBitmap(m_bitmap_transparent_def.bmp(), FromDIP(2), FromDIP(2));
}
@@ -2140,7 +2192,10 @@ AMSRoadUpPart::AMSRoadUpPart(wxWindow* parent, wxWindowID id, AMSinfo info, AMSM
m_ams_model = model;
if (m_ams_model == AMSModel::GENERIC_AMS){
create(parent, id, pos, wxSize(FromDIP(264), FromDIP(34)));
const int width = use_generic_ams_layout(m_ams_model)
? generic_ams_layout_width(this, static_cast<int>(m_amsinfo.cans.size()))
: FromDIP(264);
create(parent, id, pos, wxSize(width, FromDIP(34)));
}
else{
create(parent, id, pos, wxSize(FromDIP(78), FromDIP(34)));
@@ -2252,6 +2307,38 @@ void AMSRoadUpPart::doRender(wxDC& dc)
dc.SetPen(wxPen(AMS_CONTROL_GRAY500, 2, wxPENSTYLE_SOLID));
dc.SetBrush(wxBrush(*wxTRANSPARENT_BRUSH));
if (use_generic_ams_layout(m_ams_model)) {
const int lane_count = static_cast<int>(m_amsinfo.cans.size());
if (lane_count <= 0)
return;
const auto lane_centers = generic_ams_lane_centers(lane_count, size.x);
const int height = FromDIP(21);
for (const int lane_center : lane_centers)
dc.DrawLine(lane_center, 0, lane_center, height);
if (lane_centers.size() > 1)
dc.DrawLine(lane_centers.front(), height, lane_centers.back(), height);
dc.DrawLine(size.x / 2, height, size.x / 2, size.y);
if (m_load_step != AMSPassRoadSTEP::AMS_ROAD_STEP_NONE &&
m_load_slot_index >= 0 && m_load_slot_index < lane_count) {
const int lane_center = lane_centers[m_load_slot_index];
dc.SetPen(wxPen(_get_diff_clr(this, m_amsinfo.cans[m_load_slot_index].material_colour), 4, wxPENSTYLE_SOLID));
dc.DrawLine(lane_center, 0, lane_center, height);
dc.DrawLine(std::min(lane_center, size.x / 2), height,
std::max(lane_center, size.x / 2), height);
if (m_load_step == AMSPassRoadSTEP::AMS_ROAD_STEP_2 ||
m_load_step == AMSPassRoadSTEP::AMS_ROAD_STEP_3)
dc.DrawLine(size.x / 2, height, size.x / 2, size.y);
}
dc.SetPen(*wxTRANSPARENT_PEN);
dc.SetBrush(wxBrush(wxColour(194, 194, 194)));
dc.DrawRectangle(size.x / 2 - FromDIP(14), height - FromDIP(5), FromDIP(28), FromDIP(10));
return;
}
if ((m_ams_model == N3S_AMS || m_ams_model == EXT_AMS) && m_amsinfo.cans.size() != 4){
dc.DrawLine(((float)size.x / 2), (0), ((float)size.x / 2), (size.y));
if (m_load_step == AMSPassRoadSTEP::AMS_ROAD_STEP_2 || m_load_step == AMSPassRoadSTEP::AMS_ROAD_STEP_3){
@@ -2377,6 +2464,25 @@ void AMSRoadDownPart::UpdateRight(int nozzle_num, AMSRoadShowMode mode)
Refresh();
}
void AMSRoadDownPart::SetNozzleCount(int nozzle_num)
{
const int new_nozzle_num = std::max(1, nozzle_num);
if (m_nozzle_num == new_nozzle_num) return;
m_nozzle_num = new_nozzle_num;
Refresh();
}
void AMSRoadDownPart::SetSingleSideLayout(bool enabled, AMSPanelPos pos)
{
if (m_single_side_layout == enabled && m_single_side_pos == pos)
return;
m_single_side_layout = enabled;
m_single_side_pos = pos;
Refresh();
}
void AMSRoadDownPart::OnVamsLoading(bool load, wxColour col /*= AMS_CONTROL_GRAY500*/)
{
/*m_vams_loading = load;
@@ -2450,8 +2556,14 @@ void AMSRoadDownPart::doRender(wxDC& dc)
/*if (m_road_color.Alpha() == 0) { dc.SetPen(wxPen(*wxWHITE, m_passroad_width, wxPENSTYLE_SOLID)); }
else { dc.SetPen(wxPen(m_road_color, m_passroad_width, wxPENSTYLE_SOLID)); }*/
dc.SetPen(wxPen(AMS_CONTROL_GRAY500, 2, wxPENSTYLE_SOLID));
auto xpos = left_nozzle_pos.x;
if (m_left_rode_mode == AMSRoadShowMode::AMS_ROAD_MODE_NONE || m_right_rode_mode == AMSRoadShowMode::AMS_ROAD_MODE_NONE){
if (m_single_side_layout) {
dc.DrawLine(size.x / 2, 0, size.x / 2, size.y);
}
else if (
(m_left_rode_mode == AMSRoadShowMode::AMS_ROAD_MODE_NONE ||
m_right_rode_mode == AMSRoadShowMode::AMS_ROAD_MODE_NONE)){
auto length = 50;
if (m_left_rode_mode == AMSRoadShowMode::AMS_ROAD_MODE_AMS_LITE || m_right_rode_mode == AMSRoadShowMode::AMS_ROAD_MODE_AMS_LITE)
length = -13;
@@ -2482,6 +2594,9 @@ void AMSRoadDownPart::doRender(wxDC& dc)
case AMSRoadShowMode::AMS_ROAD_MODE_AMS_LITE:
dc.DrawLine(left_nozzle_pos.x, 0, left_nozzle_pos.x, size.y);
break;
case AMSRoadShowMode::AMS_ROAD_MODE_GENERIC:
// Generic N-lane geometry is intentionally left unimplemented.
break;
default:
break;
}
@@ -2509,23 +2624,41 @@ void AMSRoadDownPart::doRender(wxDC& dc)
dc.DrawLine(left_nozzle_pos.x, (size.y / 2), left_nozzle_pos.x + FromDIP(145), (size.y / 2));
dc.DrawLine(left_nozzle_pos.x + FromDIP(145), 0, left_nozzle_pos.x + FromDIP(145), (size.y / 2));
break;
case AMSRoadShowMode::AMS_ROAD_MODE_GENERIC:
// Generic N-lane geometry is intentionally left unimplemented.
break;
default:
break;
}
}
if (m_single_side_layout) {
if (m_pass_road_left_step == AMSPassRoadSTEP::AMS_ROAD_STEP_2 ||
m_pass_road_left_step == AMSPassRoadSTEP::AMS_ROAD_STEP_3) {
dc.SetPen(wxPen(_get_diff_clr(this, m_road_color[1]), 4, wxPENSTYLE_SOLID));
dc.DrawLine(size.x / 2, 0, size.x / 2, size.y);
}
return;
}
if (m_right_rode_mode != AMSRoadShowMode::AMS_ROAD_MODE_AMS_LITE){
if (m_nozzle_num == 2) {
if (m_nozzle_num == 1) {
if (m_right_rode_mode != AMSRoadShowMode::AMS_ROAD_MODE_NONE && m_left_rode_mode != AMSRoadShowMode::AMS_ROAD_MODE_NONE) {
dc.DrawLine((left_nozzle_pos.x), (size.y / 2), (right_nozzle_pos.x), (size.y / 2));
}
const auto &nozzle_pos = m_single_side_layout && m_single_side_pos == AMSPanelPos::RIGHT_PANEL
? right_nozzle_pos
: left_nozzle_pos;
dc.DrawLine(nozzle_pos.x, (size.y / 2), nozzle_pos.x, (size.y));
}
else if (m_nozzle_num == 2) {
/*dc.DrawLine(FromDIP(left_nozzle_pos.x), FromDIP(size.y / 2), FromDIP(left_nozzle_pos.x), FromDIP(size.y));
dc.DrawLine(FromDIP(right_nozzle_pos.x), FromDIP(size.y / 2), FromDIP(right_nozzle_pos.x), FromDIP(size.y));*/
dc.DrawLine((left_nozzle_pos.x), (size.y / 2), (left_nozzle_pos.x), (size.y));
dc.DrawLine((right_nozzle_pos.x), (size.y / 2), (right_nozzle_pos.x), (size.y));
}
else {
if (m_right_rode_mode != AMSRoadShowMode::AMS_ROAD_MODE_NONE && m_left_rode_mode != AMSRoadShowMode::AMS_ROAD_MODE_NONE) {
dc.DrawLine((left_nozzle_pos.x), (size.y / 2), (right_nozzle_pos.x), (size.y / 2));
}
dc.DrawLine((left_nozzle_pos.x), (size.y / 2), (left_nozzle_pos.x), (size.y));
// Generic N Nozzles
}
}
@@ -2550,10 +2683,16 @@ void AMSRoadDownPart::doRender(wxDC& dc)
dc.DrawLine(xpos, size.y / 2, xpos, size.y);*/
int x = left_nozzle_pos.x;
int len = m_right_road_length;
if (m_nozzle_num == 2) {
if (m_nozzle_num == 1) {
// Keep the single-nozzle path anchored at the left nozzle.
}
else if (m_nozzle_num == 2) {
x = right_nozzle_pos.x;
len = len - 14;
}
else {
// Generic N Nozzles
}
dc.DrawLine(((x)), (size.y / 2), x + FromDIP(len), (size.y / 2));
dc.DrawLine(x + FromDIP(len), (0), x + FromDIP(len), (size.y / 2));
dc.DrawLine((x), (size.y / 2), (x), (size.y));
@@ -2561,10 +2700,16 @@ void AMSRoadDownPart::doRender(wxDC& dc)
else{
int x = left_nozzle_pos.x;
int len = m_right_road_length;
if (m_nozzle_num == 2) {
if (m_nozzle_num == 1) {
// Keep the single-nozzle path anchored at the left nozzle.
}
else if (m_nozzle_num == 2) {
x = right_nozzle_pos.x;
len = len - 14;
}
else {
// Generic N Nozzles
}
dc.DrawLine(((x)), (size.y / 2), x + FromDIP(len), (size.y / 2));
dc.DrawLine(x + FromDIP(len), (0), x + FromDIP(len), (size.y / 2));
dc.DrawLine((x), (size.y / 2), (x), (size.y));
@@ -2588,7 +2733,7 @@ void AMSRoadDownPart::doRender(wxDC& dc)
}
void AMSRoadDownPart::UpdatePassRoad(AMSPanelPos pos, int len, AMSPassRoadSTEP step) {
if (m_nozzle_num >= 2){
if (m_nozzle_num == 2){
if (pos == AMSPanelPos::LEFT_PANEL){
if (m_left_road_length == len && m_pass_road_left_step == step){ return; }
m_left_road_length = len;;
@@ -2600,7 +2745,7 @@ void AMSRoadDownPart::UpdatePassRoad(AMSPanelPos pos, int len, AMSPassRoadSTEP s
m_pass_road_right_step = step;
}
}
else{
else if (m_nozzle_num == 1){
if (pos == AMSPanelPos::LEFT_PANEL) {
if (m_left_road_length == len && m_pass_road_left_step == step && m_right_road_length == -1) { return; }
m_left_road_length = len;
@@ -2614,6 +2759,9 @@ void AMSRoadDownPart::UpdatePassRoad(AMSPanelPos pos, int len, AMSPassRoadSTEP s
m_pass_road_right_step = step;
}
}
else {
// Generic N Nozzles
}
Refresh();
}
@@ -2632,7 +2780,10 @@ AMSPreview::AMSPreview(wxWindow* parent, wxWindowID id, AMSinfo amsinfo, AMSMode
{
wxWindow::Create(parent, id, pos);
if (itemType == AMSModel::GENERIC_AMS || itemType == AMSModel::AMS_LITE || itemType == AMSModel::N3F_AMS) {
create(parent, id, pos, AMS_PREV_FOUR_SIZE);
if (itemType == AMSModel::GENERIC_AMS && use_generic_ams_layout(itemType))
create(parent, id, pos, wxSize(generic_ams_preview_width(this, static_cast<int>(amsinfo.cans.size())), AMS_PREV_FOUR_SIZE.y));
else
create(parent, id, pos, AMS_PREV_FOUR_SIZE);
}
else {
create(parent, id, pos, AMS_PREV_SINGLE_SIZE);
@@ -2667,7 +2818,13 @@ void AMSPreview::UpdateInfo(AMSinfo amsinfo)
m_amsinfo = amsinfo;
m_ams_item_type = amsinfo.ams_type;
if (m_ams_item_type == AMSModel::GENERIC_AMS || m_ams_item_type == AMSModel::AMS_LITE || m_ams_item_type == AMSModel::N3F_AMS) {
if (m_ams_item_type == AMSModel::GENERIC_AMS && use_generic_ams_layout(m_ams_item_type)) {
const wxSize generic_size(generic_ams_preview_width(this, static_cast<int>(m_amsinfo.cans.size())), AMS_PREV_FOUR_SIZE.y);
SetSize(generic_size);
SetMinSize(generic_size);
SetMaxSize(generic_size);
}
else if (m_ams_item_type == AMSModel::GENERIC_AMS || m_ams_item_type == AMSModel::AMS_LITE || m_ams_item_type == AMSModel::N3F_AMS) {
SetMinSize(AMS_PREV_FOUR_SIZE);
SetMaxSize(AMS_PREV_FOUR_SIZE);
} else {
@@ -2775,8 +2932,41 @@ void AMSPreview::doRender(wxDC &dc)
dc.DrawRoundedRectangle(0, 0, size.x, size.y, FromDIP(3));
auto left = 0;
//four slot
if (m_ams_item_type != AMSModel::EXT_AMS && m_ams_item_type != AMSModel::N3S_AMS){
// Generic AMS previews use the same normalized lane centers as the card row and connector.
if (m_ams_item_type == AMSModel::GENERIC_AMS && use_generic_ams_layout(m_ams_item_type)) {
const int lane_count = static_cast<int>(m_amsinfo.cans.size());
const auto lane_centers = generic_ams_lane_centers(lane_count, size.x);
const int cube_width = FromDIP(9);
const int cube_height = FromDIP(14);
for (int lane = 0; lane < lane_count; ++lane) {
const Caninfo &can = m_amsinfo.cans[lane];
const int cube_left = lane_centers[lane] - cube_width / 2;
const int cube_top = (size.y - cube_height) / 2;
wxRect rect(cube_left, cube_top, cube_width, cube_height);
if (can.material_colour.Alpha() == 0) {
if (wxGetApp().dark_mode())
dc.DrawBitmap(m_ts_bitmap_cube_dark.bmp(), cube_left - FromDIP(1), (size.y - m_ts_bitmap_cube_dark.GetBmpHeight()) / 2);
else
dc.DrawBitmap(m_ts_bitmap_cube.bmp(), cube_left - FromDIP(1), (size.y - m_ts_bitmap_cube.GetBmpHeight()) / 2);
}
else if (can.material_state == AMSCanType::AMS_CAN_TYPE_EMPTY) {
dc.SetPen(wxPen(wxColor(0, 0, 0)));
dc.DrawLine(rect.GetRight() - FromDIP(1), rect.GetTop() + FromDIP(1),
rect.GetLeft() + FromDIP(1), rect.GetBottom() - FromDIP(1));
}
else {
wxColour color = can.material_colour;
change_the_opacity(color);
dc.SetPen(wxPen(*wxTRANSPARENT_PEN));
dc.SetBrush(wxBrush(color));
dc.DrawRoundedRectangle(rect, 2);
}
}
}
// four slot
else if (m_ams_item_type != AMSModel::EXT_AMS && m_ams_item_type != AMSModel::N3S_AMS){
left = FromDIP(8);
for (std::vector<Caninfo>::iterator iter = m_amsinfo.cans.begin(); iter != m_amsinfo.cans.end(); iter++) {
@@ -2861,38 +3051,30 @@ void AMSPreview::doRender(wxDC &dc)
//dc.DrawRoundedRectangle((size.x - rec_size.x) / 2, (size.y - rec_size.y) / 2, rec_size.x, rec_size.y, FromDIP(2));
if (iter.material_cols.size() > 1)
{
const wxSize swatch_size = m_ams_item_type == AMSModel::N3S_AMS ? AMS_ITEM_CUBE_SIZE : AMS_ITEM_CUBE_SIZE2;
const wxRect rect((size.x - swatch_size.x) / 2, (size.y - swatch_size.y) / 2, swatch_size.x, swatch_size.y);
const int radius = m_ams_item_type == AMSModel::N3S_AMS ? 0 : FromDIP(3);
std::unique_ptr<wxGraphicsContext> owned_gc;
wxGraphicsContext* gc = dc.GetGraphicsContext();
if (!gc) {
owned_gc.reset(wxGraphicsContext::CreateFromUnknownDC(dc));
gc = owned_gc.get();
}
if (gc) {
wxGraphicsGradientStops stops(iter.material_cols.front(), iter.material_cols.back());
const size_t count = iter.material_cols.size();
if (iter.ctype == 0) {
for (size_t i = 1; i + 1 < count; ++i)
stops.Add(iter.material_cols[i], static_cast<float>(i) / (count - 1));
} else {
// Two stops at each boundary keep multicolour bands distinct.
for (size_t i = 1; i < count; ++i) {
const float position = static_cast<float>(i) / count;
stops.Add(iter.material_cols[i - 1], position);
stops.Add(iter.material_cols[i], position);
int fleft = (size.x - AMS_ITEM_CUBE_SIZE.x) / 2;
float total_width = AMS_ITEM_CUBE_SIZE.x;
int gwidth = (total_width / (iter.material_cols.size()));
if (iter.ctype == 0) {
for (int i = 0; i < iter.material_cols.size() - 1; i++) {
if ((fleft + gwidth) > (AMS_ITEM_CUBE_SIZE.x)) {
gwidth = (fleft + AMS_ITEM_CUBE_SIZE.x) - fleft;
}
auto rect = wxRect(fleft, (size.y - AMS_ITEM_CUBE_SIZE.y) / 2, gwidth, AMS_ITEM_CUBE_SIZE.y);
fill_gradient_rect_east(dc, rect, iter.material_cols[i], iter.material_cols[i + 1]);
fleft += gwidth;
}
}
else {
int cols_size = iter.material_cols.size();
for (int i = 0; i < cols_size; i++) {
dc.SetPen(wxPen(*wxTRANSPARENT_PEN));
dc.SetBrush(wxBrush(iter.material_cols[i]));
float x = (size.x - AMS_ITEM_CUBE_SIZE.x) / 2 + total_width * i / cols_size;
dc.DrawRectangle(x, (size.y - AMS_ITEM_CUBE_SIZE.y) / 2, total_width / cols_size, AMS_ITEM_CUBE_SIZE.y);
}
gc->PushState();
gc->SetPen(*wxTRANSPARENT_PEN);
gc->SetBrush(gc->CreateLinearGradientBrush(rect.x, rect.y, rect.x + rect.width, rect.y, stops));
gc->DrawRoundedRectangle(rect.x, rect.y, rect.width, rect.height, radius);
gc->PopState();
} else {
dc.SetPen(*wxTRANSPARENT_PEN);
dc.SetBrush(iter.material_colour);
dc.DrawRoundedRectangle(rect, radius);
}
}
else {
@@ -3183,10 +3365,19 @@ AmsItem::AmsItem(wxWindow *parent,AMSinfo info, AMSModel model, AMSPanelPos pos
m_panel_pos = pos;
if (m_ams_model == AMSModel::GENERIC_AMS){
wxWindow::Create(parent, wxID_ANY, wxDefaultPosition, AMS_CANS_WINDOW_SIZE);
SetSize(AMS_CANS_WINDOW_SIZE);
SetMinSize(AMS_CANS_WINDOW_SIZE);
SetMaxSize(AMS_CANS_WINDOW_SIZE);
const int lane_count = static_cast<int>(m_info.cans.size());
const int width = use_generic_ams_layout(m_ams_model) && lane_count <= 8
? generic_ams_layout_width(this, lane_count)
: FromDIP(264);
const wxSize generic_size(width, FromDIP(174));
wxWindow::Create(parent, wxID_ANY, wxDefaultPosition, generic_size);
SetSize(generic_size);
SetMinSize(generic_size);
// For large lane counts the card is a viewport, not the lane strip. Let
// its parent allocate the available width; the scrolled child retains
// the wider virtual content size.
if (!(use_generic_ams_layout(m_ams_model) && lane_count > 8))
SetMaxSize(generic_size);
}
else{
wxWindow::Create(parent, wxID_ANY, wxDefaultPosition, AMS_SINGLE_CAN_SIZE);
@@ -3212,12 +3403,43 @@ void AmsItem::create(wxWindow *parent)
if (m_ams_model != AMSModel::AMS_LITE) {
sizer_can = new wxBoxSizer(wxHORIZONTAL);
sizer_item = new wxBoxSizer(wxVERTICAL);
auto it = m_info.cans.begin();
for (; it != m_info.cans.end(); it++) {
AddCan(*it, m_can_count, m_info.cans.size(), sizer_can);
const bool generic_layout = use_generic_ams_layout(m_ams_model);
const int lane_count = static_cast<int>(m_info.cans.size());
const int content_width = generic_layout ? generic_ams_layout_width(this, lane_count) : 0;
const bool scroll_lanes = generic_layout && lane_count > 8;
const auto lane_centers = generic_layout
? generic_ams_lane_centers(lane_count, content_width)
: std::vector<int>();
m_can_parent = this;
if (scroll_lanes) {
m_can_scroll = new wxScrolledWindow(this, wxID_ANY);
m_can_scroll->SetScrollRate(FromDIP(10), 0);
m_can_scroll->SetMinSize(wxSize(FromDIP(264), FromDIP(143)));
m_can_scroll->SetBackgroundColour(StateColor::darkModeColorFor(AMS_CONTROL_DEF_LIB_BK_COLOUR));
m_can_scroll_sizer = new wxBoxSizer(wxVERTICAL);
m_can_scroll->SetSizer(m_can_scroll_sizer);
m_can_parent = m_can_scroll;
}
int previous_right = 0;
for (int can_index = 0; can_index < lane_count; ++can_index) {
if (generic_layout) {
const int left = lane_centers[can_index] - FromDIP(26);
sizer_can->AddSpacer(std::max(0, left - previous_right));
AddCan(m_info.cans[can_index], m_can_count, m_info.cans.size(), sizer_can);
previous_right = left + FromDIP(52);
}
else {
AddCan(m_info.cans[can_index], m_can_count, m_info.cans.size(), sizer_can);
}
m_can_count++;
}
it = m_info.cans.begin();
if (generic_layout)
sizer_can->AddSpacer(std::max(0, content_width - previous_right));
if (generic_layout)
sizer_can->SetMinSize(wxSize(content_width, -1));
//auto road_panel = new wxWindow(this, wxID_ANY);
//auto road_panel = new wxPanel(this, wxID_ANY);
//road_panel->SetSize(AMS_CAN_ROAD_SIZE);
@@ -3232,11 +3454,18 @@ void AmsItem::create(wxWindow *parent)
sizer_item->Add(m_ext_image, 0, wxALIGN_CENTER, 0);
}
}
m_panel_road = new AMSRoadUpPart(this, wxID_ANY, m_info, m_ams_model);
m_panel_road = new AMSRoadUpPart(m_can_parent, wxID_ANY, m_info, m_ams_model);
sizer_item->Add(sizer_can, 0, wxALIGN_CENTER_HORIZONTAL, 0);
//sizer_item->Add(m_panel_road, 0, wxALIGN_CENTER_HORIZONTAL, 0);
sizer_item->Add(m_panel_road, 1, wxEXPAND);
if (scroll_lanes) {
m_can_scroll_sizer->Add(sizer_can, 0, wxALIGN_LEFT, 0);
m_can_scroll_sizer->Add(m_panel_road, 0, wxALIGN_LEFT, 0);
sizer_item->Add(m_can_scroll, 1, wxEXPAND);
}
else {
sizer_item->Add(sizer_can, 0, wxALIGN_CENTER_HORIZONTAL, 0);
//sizer_item->Add(m_panel_road, 0, wxALIGN_CENTER_HORIZONTAL, 0);
sizer_item->Add(m_panel_road, 1, wxEXPAND);
}
SetSizer(sizer_item);
}
@@ -3260,13 +3489,17 @@ void AmsItem::create(wxWindow *parent)
Layout();
Fit();
if (m_can_scroll) {
m_can_scroll->Layout();
m_can_scroll->FitInside();
}
Thaw();
//Refresh();
}
void AmsItem::AddCan(Caninfo caninfo, int canindex, int maxcan, wxBoxSizer* sizer)
{
auto amscan = new wxWindow(this, wxID_ANY);
auto amscan = new wxWindow(m_can_parent ? m_can_parent : this, wxID_ANY);
amscan->SetSize(wxSize(FromDIP(52), FromDIP(109)));
amscan->SetMinSize(wxSize(FromDIP(52), FromDIP(109)));
@@ -3347,7 +3580,8 @@ void AmsItem::AddCan(Caninfo caninfo, int canindex, int maxcan, wxBoxSizer* size
amscan->Layout();
amscan->Fit();
sizer->Add(amscan, 0, wxUP | wxLEFT | wxRIGHT, FromDIP(5));
const int margin = use_generic_ams_layout(m_ams_model) ? 0 : FromDIP(5);
sizer->Add(amscan, 0, wxUP | wxLEFT | wxRIGHT, margin);
m_can_lib_list[caninfo.can_id] = m_panel_lib;
//m_can_road_list[caninfo.can_id] = m_panel_road;
@@ -3472,6 +3706,10 @@ void AmsItem::UpdateInfo(AMSinfo info)
}
Layout();
if (m_can_scroll) {
m_can_scroll->Layout();
m_can_scroll->FitInside();
}
}
void AmsItem::SetDefSelectCan()
+10
View File
@@ -30,6 +30,7 @@
#include <wx/string.h>
#include <wx/timer.h>
#include <wx/sizer.h>
#include <wx/scrolwin.h>
#include "slic3r/GUI/DeviceCore/DevFilaSwitch.h" // Orca: DevFilaSwitch::SwitchPos for inlet-aware AMS placement
@@ -96,6 +97,7 @@ enum class AMSRoadShowMode : int {
AMS_ROAD_MODE_SINGLE,
AMS_ROAD_MODE_SINGLE_N3S,
AMS_ROAD_MODE_AMS_LITE,
AMS_ROAD_MODE_GENERIC,
AMS_ROAD_MODE_NONE
};
@@ -480,6 +482,7 @@ public:
//AMSextruderImage *m_amsSextruder{nullptr};
AMSextruderImage* m_left_extruder = nullptr;
AMSextruderImage* m_right_extruder = nullptr;
std::vector<AMSextruderImage*> m_nozzle_extruders;
AMSextruder(wxWindow *parent, wxWindowID id, int nozzle_num, const wxPoint &pos = wxDefaultPosition, const wxSize &size = wxDefaultSize);
~AMSextruder();
@@ -681,6 +684,8 @@ public:
// void Update(AMSRoadDownPartMode nozzle, AMSRoadShowMode left_mode, AMSRoadShowMode right_mode, int left_len, int right_len);
void UpdateLeft(int nozzle_num, AMSRoadShowMode mode);
void UpdateRight(int nozzle_num, AMSRoadShowMode mode);
void SetNozzleCount(int nozzle_num);
void SetSingleSideLayout(bool enabled, AMSPanelPos pos = AMSPanelPos::LEFT_PANEL);
void OnVamsLoading(bool load, wxColour col = AMS_CONTROL_GRAY500);
void SetPassRoadColour(bool left, wxColour col);
@@ -698,6 +703,8 @@ private:
AMSRoadShowMode m_left_rode_mode = {AMSRoadShowMode::AMS_ROAD_MODE_FOUR};
AMSRoadShowMode m_right_rode_mode = {AMSRoadShowMode::AMS_ROAD_MODE_FOUR};
bool m_selected = {false};
bool m_single_side_layout = {false};
AMSPanelPos m_single_side_pos = {AMSPanelPos::LEFT_PANEL};
int m_left_road_length = {-1};
int m_right_road_length = {-1};
@@ -864,6 +871,9 @@ private:
std::map<std::string, AMSLib*> m_can_lib_list;
//std::map<std::string, AMSRoad*> m_can_road_list;
wxScrolledWindow* m_can_scroll = { nullptr };
wxBoxSizer* m_can_scroll_sizer = { nullptr };
wxWindow* m_can_parent = { nullptr };
AMSRoadUpPart* m_panel_road = { nullptr };
std::map<std::string, AMSrefresh*> m_can_refresh_list;
AMSHumidity* m_humidity = { nullptr };
+18 -3
View File
@@ -420,6 +420,14 @@ ExtruderBadge::ExtruderBadge(wxWindow* parent) : wxPanel(parent)
void ExtruderBadge::SetExtruderInfo(int extruder_id, const std::string& diameter, const NozzleVolumeType& volume_type)
{
// The badge renders exactly two extruders (left/right). A generic non-BBL printer with
// N > 2 can report an out-of-range id here (see MultiNozzleStatusTable::UpdateRackInfo);
// reject it rather than writing past the two-element lists.
if (extruder_id < 0 || extruder_id >= static_cast<int>(m_diameter_list.size())) {
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": out-of-range extruder_id " << extruder_id;
return;
}
m_diameter_list[extruder_id] = diameter;
m_volume_type_list[extruder_id] = volume_type;
@@ -867,14 +875,21 @@ void MultiNozzleStatusTable::UpdateRackInfo(std::weak_ptr<DevNozzleRack> rack)
bool has_right = false;
for (auto& elem : nozzles_in_extruder) {
auto& nozzle = elem.second;
int extruder_id = nozzle.AtLeftExtruder() ? 0 : 1;
if (nozzle.AtRightExtruder())
has_right = true;
int extruder_id{};
if (wxGetApp().preset_bundle && wxGetApp().preset_bundle->is_bbl_vendor()) {
extruder_id = nozzle.AtLeftExtruder() ? 0 : 1;
if (nozzle.AtRightExtruder())
has_right = true;
}
else
extruder_id = nozzle.GetExtruderId();
NozzleVolumeType volume_type = DevNozzle::ToNozzleVolumeType(nozzle.m_nozzle_flow);
m_badge->SetExtruderInfo(extruder_id, format_diameter_to_str(nozzle.GetNozzleDiameter()), volume_type);
}
// TODO: Update for N extruders
m_badge->SetExtruderValid(has_right);
}
}
+3
View File
@@ -184,6 +184,9 @@ void TempInput::SetFinish()
wxCommandEvent event(wxCUSTOMEVT_SET_TEMP_FINISH);
event.SetInt(temp_type);
event.SetString(wxString::Format("%d", m_input_type));
// N-extruder temp controls all share TEMP_OF_NORMAL_TYPE, so the string payload above can't
// tell them apart; carry widget identity so the listener can find which one fired.
event.SetEventObject(this);
wxPostEvent(this->GetParent(), event);
}
+400 -89
View File
@@ -38,6 +38,7 @@
#include <boost/log/trivial.hpp>
#include <algorithm>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cctype>
#include <ios>
@@ -61,6 +62,42 @@ namespace websocket = beast::websocket;
namespace net = boost::asio;
using tcp = net::ip::tcp;
// Decimal value of a string that is nothing but digits, or -1 when it is empty or not a number.
int decimal_number(const std::string& digits)
{
if (digits.empty() || !std::all_of(digits.begin(), digits.end(), [](unsigned char c) { return std::isdigit(c) != 0; }))
return -1;
try {
return std::stoi(digits);
} catch (...) {
return -1;
}
}
// Lane database keys address a lane either as "T<N>" (0-based tool index) or as "lane<N>"
// (1-based, the AFC/Happy Hare style). Returns -1 when the key carries no usable lane number.
int lane_index_from_key(const std::string& lane_key)
{
if (lane_key.size() > 1 && (lane_key[0] == 'T' || lane_key[0] == 't'))
return decimal_number(lane_key.substr(1));
if (lane_key.size() > 4 && lane_key.compare(0, 4, "lane") == 0) {
const int lane_number = decimal_number(lane_key.substr(4));
return lane_number > 0 ? lane_number - 1 : -1;
}
return -1;
}
// AFC names toolheads "extruder", "extruder1", ... and derives the toolhead index from the name
// itself (AFC_lane.lane_extruder_index): no suffix is 0, otherwise the suffix is the index.
int extruder_index_from_name(const std::string& toolhead)
{
if (toolhead == "extruder")
return 0;
if (toolhead.size() > 8 && toolhead.compare(0, 8, "extruder") == 0)
return decimal_number(toolhead.substr(8));
return -1;
}
struct WsEndpoint
{
std::string host;
@@ -443,19 +480,7 @@ int MoonrakerPrinterAgent::set_queue_on_main_fn(QueueOnMainFn fn)
void MoonrakerPrinterAgent::build_ams_payload(int ams_count, int max_lane_index, const std::vector<AmsTrayData>& trays)
{
// Look up MachineObject via DeviceManager
auto* dev_manager = GUI::wxGetApp().getDeviceManager();
if (!dev_manager) {
return;
}
MachineObject* obj = dev_manager->get_my_machine(device_info.dev_id);
if (!obj) {
return;
}
// Build BBL-format JSON for DevFilaSystemParser::ParseV1_0
nlohmann::json ams_json = nlohmann::json::object();
nlohmann::json ams_array = nlohmann::json::array();
// Calculate ams_exist_bits and tray_exist_bits
@@ -463,11 +488,9 @@ void MoonrakerPrinterAgent::build_ams_payload(int ams_count, int max_lane_index,
unsigned long tray_exist_bits = 0;
for (int ams_id = 0; ams_id < ams_count; ++ams_id) {
ams_exist_bits |= (1 << ams_id);
nlohmann::json ams_unit = nlohmann::json::object();
ams_unit["id"] = std::to_string(ams_id);
ams_unit["info"] = "0002"; // treat as AMS_LITE
if (ams_id < 32) {
ams_exist_bits |= (1UL << ams_id);
}
nlohmann::json tray_array = nlohmann::json::array();
int max_slot_in_this_ams = std::min(3, max_lane_index - ams_id * 4);
@@ -483,43 +506,135 @@ void MoonrakerPrinterAgent::build_ams_payload(int ams_count, int max_lane_index,
}
}
nlohmann::json tray_json = nlohmann::json::object();
tray_json["id"] = std::to_string(slot_id);
tray_json["tag_uid"] = "0000000000000000";
if (tray && tray->has_filament) {
tray_exist_bits |= (1 << slot_index);
tray_json["tray_info_idx"] = tray->tray_info_idx;
tray_json["tray_type"] = tray->tray_type;
tray_json["tray_color"] = normalize_color_value(tray->tray_color);
// Add temperature data if provided
if (tray->bed_temp > 0) {
tray_json["bed_temp"] = std::to_string(tray->bed_temp);
}
if (tray->nozzle_temp > 0) {
tray_json["nozzle_temp_max"] = std::to_string(tray->nozzle_temp);
}
} else {
tray_json["tray_info_idx"] = "";
tray_json["tray_type"] = "";
tray_json["tray_color"] = "00000000";
tray_json["tray_slot_placeholder"] = "1";
if (tray && tray->has_filament && slot_index < 32) {
tray_exist_bits |= (1UL << slot_index);
}
tray_array.push_back(tray_json);
static const AmsTrayData empty_tray;
tray_array.push_back(make_ams_tray_json(std::to_string(slot_id), tray ? *tray : empty_tray));
}
nlohmann::json ams_unit = nlohmann::json::object();
ams_unit["id"] = std::to_string(ams_id);
// Generic unit: type 1 (AMS) maps to AMSModel::GENERIC_AMS, which drives the
// variable-lane rendering. This is not a real Bambu AMS-Lite.
ams_unit["info"] = "0001";
ams_unit["tray"] = tray_array;
ams_array.push_back(ams_unit);
}
BOOST_LOG_TRIVIAL(info) << "MoonrakerPrinterAgent::build_ams_payload: Parsed " << trays.size() << " trays";
submit_ams_payload(ams_array, ams_exist_bits, tray_exist_bits);
}
void MoonrakerPrinterAgent::build_ams_payload_grouped(const std::vector<AmsTrayData>& trays)
{
// One AMS box per extruder, best effort. Lane-data changers (AFC, recent Happy Hare) report an
// extruder per lane but no physical box layout, so a box here is a logical feed group, not a
// discovered unit. Lanes without an extruder fall back to the main extruder.
std::map<int, std::vector<const AmsTrayData*>> boxes;
for (const auto& tray : trays) {
boxes[tray.extruder_id].push_back(&tray);
}
nlohmann::json ams_array = nlohmann::json::array();
unsigned long ams_exist_bits = 0;
unsigned long tray_exist_bits = 0;
int ams_id = 0;
// Cumulative lane index across all boxes, in box then slot order. A lane maps to exactly one
// extruder, so this is the lane's identity; the parser derives the same index for generic units.
int lane_index = 0;
for (auto& [extruder_id, lanes] : boxes) {
if (ams_id < 32) {
ams_exist_bits |= (1UL << ams_id);
}
// Keep a deterministic slot order within the box.
std::stable_sort(lanes.begin(), lanes.end(),
[](const AmsTrayData* a, const AmsTrayData* b) { return a->slot_index < b->slot_index; });
nlohmann::json tray_array = nlohmann::json::array();
for (size_t slot = 0; slot < lanes.size(); ++slot) {
const AmsTrayData& tray = *lanes[slot];
// A logical feed group is not a four-slot Bambu AMS: the bit is the lane's cumulative
// index, not ams_id*4+slot. DevFilaSystemParser::ParseV1_0 reads the same index.
const int bit = lane_index++;
if (tray.has_filament && bit < 32) {
tray_exist_bits |= (1UL << bit);
}
tray_array.push_back(make_ams_tray_json(std::to_string(slot), tray));
}
nlohmann::json ams_unit = nlohmann::json::object();
ams_unit["id"] = std::to_string(ams_id);
// info: bits 0-3 = unit type (1 = AMS, i.e. AMSModel::GENERIC_AMS), bits 8-11 = bound
// extruder id. A logical feed group is a generic unit, not a Bambu AMS-Lite.
const int info_val = 1 | ((extruder_id & 0x0F) << 8);
const char* hex_digits = "0123456789ABCDEF";
std::string info = "0000";
info[3] = hex_digits[info_val & 0x0F];
info[2] = hex_digits[(info_val >> 4) & 0x0F];
info[1] = hex_digits[(info_val >> 8) & 0x0F];
info[0] = hex_digits[(info_val >> 12) & 0x0F];
ams_unit["info"] = info;
ams_unit["tray"] = tray_array;
ams_array.push_back(ams_unit);
++ams_id;
}
BOOST_LOG_TRIVIAL(info) << "MoonrakerPrinterAgent::build_ams_payload_grouped: Parsed " << trays.size()
<< " trays in " << boxes.size() << " extruder box(es)";
submit_ams_payload(ams_array, ams_exist_bits, tray_exist_bits);
}
nlohmann::json MoonrakerPrinterAgent::make_ams_tray_json(const std::string& tray_id, const AmsTrayData& tray)
{
nlohmann::json tray_json = nlohmann::json::object();
tray_json["id"] = tray_id;
tray_json["tag_uid"] = "0000000000000000";
if (tray.has_filament) {
tray_json["tray_info_idx"] = tray.tray_info_idx;
tray_json["tray_type"] = tray.tray_type;
tray_json["tray_color"] = normalize_color_value(tray.tray_color);
// Add temperature data if provided
if (tray.bed_temp > 0) {
tray_json["bed_temp"] = std::to_string(tray.bed_temp);
}
if (tray.nozzle_temp > 0) {
tray_json["nozzle_temp_max"] = std::to_string(tray.nozzle_temp);
}
} else {
tray_json["tray_info_idx"] = "";
tray_json["tray_type"] = "";
tray_json["tray_color"] = "00000000";
tray_json["tray_slot_placeholder"] = "1";
}
return tray_json;
}
void MoonrakerPrinterAgent::submit_ams_payload(const nlohmann::json& ams_array, unsigned long ams_exist_bits, unsigned long tray_exist_bits)
{
// Look up MachineObject via DeviceManager
auto* dev_manager = GUI::wxGetApp().getDeviceManager();
if (!dev_manager) {
return;
}
MachineObject* obj = dev_manager->get_my_machine(device_info.dev_id);
if (!obj) {
return;
}
// Format as hex strings (matching BBL protocol)
std::ostringstream ams_exist_ss;
ams_exist_ss << std::hex << std::uppercase << ams_exist_bits;
std::ostringstream tray_exist_ss;
tray_exist_ss << std::hex << std::uppercase << tray_exist_bits;
nlohmann::json ams_json = nlohmann::json::object();
ams_json["ams"] = ams_array;
ams_json["ams_exist_bits"] = ams_exist_ss.str();
ams_json["tray_exist_bits"] = tray_exist_ss.str();
@@ -530,7 +645,6 @@ void MoonrakerPrinterAgent::build_ams_payload(int ams_count, int max_lane_index,
// Call the parser to populate DevFilaSystem
DevFilaSystemParser::ParseV1_0(print_json, obj, obj->GetFilaSystem().get(), false);
BOOST_LOG_TRIVIAL(info) << "MoonrakerPrinterAgent::build_ams_payload: Parsed " << trays.size() << " trays";
// Set printer_type so update_sync_status() can match it against the preset's printer type.
// Without this, the comparison fails and all sync badges are cleared.
@@ -570,17 +684,15 @@ bool MoonrakerPrinterAgent::fetch_filament_info(std::string dev_id, FilamentSync
if (fetch_moonraker_filament_data(trays, max_lane_index)) {
BOOST_LOG_TRIVIAL(info) << "MoonrakerPrinterAgent::fetch_filament_info: Detected Moonraker filament system with "
<< (max_lane_index + 1) << " lanes";
int ams_count = (max_lane_index + 4) / 4;
build_ams_payload(ams_count, max_lane_index, trays);
build_ams_payload_grouped(trays);
return true;
}
// Attempt Happy Hare first (more widely adopted, supports more filament changers)
// Fall back to the Happy Hare `mmu` object for HH builds that do not publish lane_data
if (fetch_hh_filament_info(trays, max_lane_index)) {
BOOST_LOG_TRIVIAL(info) << "MoonrakerPrinterAgent::fetch_filament_info: Detected Happy Hare MMU with "
<< (max_lane_index + 1) << " gates";
int ams_count = (max_lane_index + 4) / 4;
build_ams_payload(ams_count, max_lane_index, trays);
build_ams_payload_grouped(trays);
return true;
}
@@ -686,6 +798,30 @@ int MoonrakerPrinterAgent::safe_json_int(const nlohmann::json& obj, const char*
return 0;
}
int MoonrakerPrinterAgent::safe_json_int_flexible(const nlohmann::json& obj, const char* key, int default_value)
{
auto it = obj.find(key);
if (it == obj.end())
return default_value;
if (it->is_number_integer())
return it->get<int>();
if (it->is_string()) {
const std::string s = it->get<std::string>();
if (s.empty())
return default_value;
try {
std::size_t consumed = 0;
const int value = std::stoi(s, &consumed);
if (consumed != s.size()) // reject partial parses such as "2oops"
return default_value;
return value;
} catch (...) {
return default_value;
}
}
return default_value;
}
std::string MoonrakerPrinterAgent::safe_array_string(const nlohmann::json& arr, int idx)
{
if (arr.is_array() && idx >= 0 && idx < static_cast<int>(arr.size()) && arr[idx].is_string())
@@ -789,28 +925,39 @@ bool MoonrakerPrinterAgent::fetch_moonraker_filament_data(std::vector<AmsTrayDat
trays.clear();
max_lane_index = 0;
// The lane_data namespace carries no extruder field; read the lane -> toolhead binding from the
// AFC printer objects so lanes on different toolheads end up in different AMS boxes.
std::map<std::string, int> lane_extruder;
fetch_afc_lane_extruders(lane_extruder);
for (const auto& [lane_key, lane_obj] : value.items()) {
if (!lane_obj.is_object()) {
continue;
}
// Extract lane index from the "lane" field (tool number, 0-based)
std::string lane_str = safe_json_string(lane_obj, "lane");
int lane_index = -1;
if (!lane_str.empty()) {
try {
lane_index = std::stoi(lane_str);
} catch (...) {
lane_index = -1;
}
}
// Lane tool number (0-based). AFC reports it as a string in the documented sample but it
// can also be a number; accept either and skip lanes without a usable index. Databases
// written without a "lane" field fall back to the key, which names the lane either as
// "T<N>" (0-based) or as "lane<N>" (1-based).
int lane_index = safe_json_int_flexible(lane_obj, "lane", -1);
if (lane_index < 0) {
continue;
lane_index = lane_index_from_key(lane_key);
if (lane_index < 0) {
continue;
}
}
AmsTrayData tray;
tray.slot_index = lane_index;
// AFC exposes the lane's extruder/toolhead as "extruder_index"; tolerate "extruder_id" as
// an alias. lane_data has neither, so fall back to the AFC lane objects and only then to
// the main extruder (best effort).
tray.extruder_id = safe_json_int_flexible(lane_obj, "extruder_index",
safe_json_int_flexible(lane_obj, "extruder_id", -1));
if (tray.extruder_id < 0) {
const auto it = lane_extruder.find(lane_key);
tray.extruder_id = it != lane_extruder.end() ? it->second : 0;
}
tray.tray_color = safe_json_string(lane_obj, "color");
tray.tray_type = safe_json_string(lane_obj, "material");
tray.bed_temp = safe_json_int(lane_obj, "bed_temp");
@@ -915,50 +1062,119 @@ bool MoonrakerPrinterAgent::fetch_hh_filament_info(std::vector<AmsTrayData>& tra
return false;
}
// Parse gate data
// Parse gate data. Every gate becomes a lane so empty/unknown gates surface
// as empty AMS slots rather than vanishing. HH is single-extruder, so all
// lanes belong to feed group 0.
trays.clear();
max_lane_index = 0;
for (int gate_idx = 0; gate_idx < num_gates; ++gate_idx) {
// Check gate_status: -1 = unknown, 0 = empty, 1 or 2 = available
int status = safe_array_int(gate_status, gate_idx);
if (status <= 0) {
continue; // Skip unknown or empty gates
}
// Extract gate data
std::string material = safe_array_string(gate_material, gate_idx);
std::string color = safe_array_string(gate_color, gate_idx);
int nozzle_temp = safe_array_int(gate_temperature, gate_idx);
// Skip if no material type (empty gate)
if (material.empty()) {
continue;
}
AmsTrayData tray;
tray.slot_index = gate_idx;
tray.tray_type = material;
tray.tray_color = color;
tray.nozzle_temp = nozzle_temp;
tray.bed_temp = 0; // HH doesn't provide bed temp in gate arrays
tray.has_filament = true;
tray.extruder_id = 0;
auto* bundle = GUI::wxGetApp().preset_bundle;
tray.tray_info_idx = bundle
? bundle->filaments.filament_id_by_type(tray.tray_type)
: map_filament_type_to_generic_id(tray.tray_type);
if (status > 0 && !material.empty()) {
tray.tray_type = material;
tray.tray_color = color;
tray.nozzle_temp = nozzle_temp;
tray.bed_temp = 0; // HH doesn't provide bed temp in gate arrays
tray.has_filament = true;
auto* bundle = GUI::wxGetApp().preset_bundle;
tray.tray_info_idx = bundle
? bundle->filaments.filament_id_by_type(tray.tray_type)
: map_filament_type_to_generic_id(tray.tray_type);
} else {
tray.has_filament = false;
}
max_lane_index = std::max(max_lane_index, gate_idx);
trays.push_back(tray);
}
if (trays.empty()) {
BOOST_LOG_TRIVIAL(info) << "MoonrakerPrinterAgent::fetch_hh_filament_info: No valid HH gates found";
max_lane_index = num_gates - 1;
return true;
}
// AFC writes its filament data into the lane_data database namespace, and the records of the
// fixture/agent write path carry no extruder field, so the lane -> toolhead binding has to be read
// from the printer objects: each AFC_lane <name>.extruder names the toolhead its lane feeds, and
// the toolhead's name carries its own index. Best effort: on failure every lane keeps the fallback
// of the main extruder.
bool MoonrakerPrinterAgent::fetch_afc_lane_extruders(std::map<std::string, int>& lane_extruder)
{
auto query_objects = [this](const std::string& query_string, nlohmann::json& out) {
auto http = Http::get(join_url(device_info.base_url, "/printer/objects/query?" + query_string));
if (!device_info.api_key.empty()) {
http.header("X-Api-Key", device_info.api_key);
}
std::string body;
unsigned status_code = 0;
http.timeout_connect(5)
.timeout_max(10)
.on_complete([&](std::string response, unsigned status) {
body = std::move(response);
status_code = status;
})
.perform_sync();
if (status_code != 200) {
return false;
}
out = nlohmann::json::parse(body, nullptr, false, true);
return !out.is_discarded();
};
nlohmann::json afc_json;
if (!query_objects("AFC", afc_json) || !afc_json.contains("result") ||
!afc_json["result"].contains("status") || !afc_json["result"]["status"].contains("AFC")) {
return false;
}
return true;
const auto& afc = afc_json["result"]["status"]["AFC"];
const auto& lanes = afc.contains("lanes") ? afc["lanes"] : nlohmann::json::array();
if (!lanes.is_array() || lanes.empty()) {
return false;
}
// Query every lane object in one request; the object names are "AFC_lane <lane name>".
std::string query_string;
for (const auto& lane : lanes) {
if (!lane.is_string()) {
return false;
}
if (!query_string.empty()) {
query_string += "&";
}
query_string += "AFC_lane%20" + lane.get<std::string>();
}
nlohmann::json lanes_json;
if (!query_objects(query_string, lanes_json) || !lanes_json.contains("result") ||
!lanes_json["result"].contains("status")) {
return false;
}
const auto& status = lanes_json["result"]["status"];
for (const auto& lane : lanes) {
const std::string name = lane.get<std::string>();
const std::string key = "AFC_lane " + name;
if (!status.contains(key) || !status[key].is_object() || !status[key].contains("extruder") ||
!status[key]["extruder"].is_string()) {
continue;
}
const std::string toolhead = status[key]["extruder"].get<std::string>();
const int toolhead_index = extruder_index_from_name(toolhead);
if (toolhead_index >= 0) {
lane_extruder[name] = toolhead_index;
}
}
return !lane_extruder.empty();
}
int MoonrakerPrinterAgent::handle_request(const std::string& dev_id, const std::string& json_str)
@@ -1059,6 +1275,25 @@ int MoonrakerPrinterAgent::handle_request(const std::string& dev_id, const std::
}
}
// Tool selection is printer-specific G-code. Moonraker forwards the
// conventional T<index> command to Klipper, where the printer can
// implement logical selection or a physical toolhead attach macro.
if (cmd == "select_extruder") {
if (!json["print"].contains("extruder_index") || !json["print"]["extruder_index"].is_number_integer()) {
BOOST_LOG_TRIVIAL(error) << "MoonrakerPrinterAgent: select_extruder missing integer extruder_index, full json: " << json_str;
return BAMBU_NETWORK_ERR_INVALID_RESULT;
}
const int extruder_idx = json["print"]["extruder_index"].get<int>();
if (extruder_idx < 0) {
BOOST_LOG_TRIVIAL(error) << "MoonrakerPrinterAgent: select_extruder received negative extruder_index: " << extruder_idx;
return BAMBU_NETWORK_ERR_INVALID_RESULT;
}
send_gcode_async(dev_id, "T" + std::to_string(extruder_idx));
return BAMBU_NETWORK_SUCCESS;
}
if (cmd == "home") {
send_gcode_async(dev_id, "G28");
return BAMBU_NETWORK_SUCCESS;
@@ -1155,7 +1390,7 @@ bool MoonrakerPrinterAgent::query_printer_status(const std::string& base_url,
nlohmann::json& status,
std::string& error) const
{
std::string url = join_url(base_url, "/printer/objects/query?print_stats&virtual_sdcard&extruder&heater_bed&fan");
std::string url = join_url(base_url, "/printer/objects/query?print_stats&virtual_sdcard&toolhead&extruder&heater_bed&fan");
std::string response_body;
bool success = false;
@@ -1563,11 +1798,12 @@ void MoonrakerPrinterAgent::run_status_stream(std::string dev_id, std::string ba
}
for (const auto& name : this->available_objects) {
if (name == "extruder" || name.rfind("extruder", 0) == 0) {
const bool is_main_extruder = name == "extruder";
const bool is_additional_extruder =
name.rfind("extruder", 0) == 0 && name.size() > 8 &&
std::all_of(name.begin() + 8, name.end(), [](unsigned char c) { return std::isdigit(c) != 0; });
if (is_main_extruder || is_additional_extruder) {
subscribe_objects.insert(name);
if (name == "extruder") {
break;
}
}
}
} else {
@@ -1863,6 +2099,81 @@ nlohmann::json MoonrakerPrinterAgent::build_print_payload_locked() const
}
}
// MachineObject::parse_new_info() only parses device.extruder when the four
// legacy new-protocol fields are present. Moonraker has no equivalents, so
// empty values act as compatibility markers without enabling any features.
std::map<int, const nlohmann::json*> extruder_status;
for (const auto& item : status_cache.items()) {
int extruder_id = -1;
if (item.key() == "extruder") {
extruder_id = 0;
} else if (item.key().rfind("extruder", 0) == 0 && item.key().size() > 8 &&
std::all_of(item.key().begin() + 8, item.key().end(), [](unsigned char c) { return std::isdigit(c) != 0; })) {
try {
extruder_id = std::stoi(item.key().substr(8));
} catch (...) {
extruder_id = -1;
}
}
if (extruder_id >= 0 && item.value().is_object()) {
extruder_status.emplace(extruder_id, &item.value());
}
}
if (!extruder_status.empty()) {
auto& device_extruder = payload["print"]["device"]["extruder"];
int current_extruder_id = 0;
if (status_cache.contains("toolhead") && status_cache["toolhead"].is_object() &&
status_cache["toolhead"].contains("extruder") && status_cache["toolhead"]["extruder"].is_string()) {
const std::string active_extruder = status_cache["toolhead"]["extruder"].get<std::string>();
if (active_extruder != "extruder" && active_extruder.rfind("extruder", 0) == 0 && active_extruder.size() > 8 &&
std::all_of(active_extruder.begin() + 8, active_extruder.end(), [](unsigned char c) { return std::isdigit(c) != 0; })) {
try {
const int parsed_id = std::stoi(active_extruder.substr(8));
if (parsed_id >= 0 && parsed_id < 16 && extruder_status.count(parsed_id) != 0) {
current_extruder_id = parsed_id;
}
} catch (...) {
// Keep the main extruder as the fallback for malformed status data.
}
}
}
const int extruder_count = std::min<int>(static_cast<int>(extruder_status.size()), 0xF);
device_extruder["state"] = extruder_count | (current_extruder_id << 4);
device_extruder["info"] = nlohmann::json::array();
auto encoded_temperature = [](const nlohmann::json& status, const char* key) {
if (!status.contains(key) || !status[key].is_number()) {
return 0;
}
const double temperature = status[key].get<double>();
return std::clamp(static_cast<int>(temperature + 0.5), 0, 65535);
};
for (const auto& [extruder_id, status] : extruder_status) {
const int current_temperature = encoded_temperature(*status, "temperature");
const int target_temperature = encoded_temperature(*status, "target");
device_extruder["info"].push_back({
{"id", extruder_id},
{"filam_bak", nlohmann::json::array()},
{"info", 1 << 3}, // The configured Moonraker extruder has a toolhead.
{"temp", current_temperature | (target_temperature << 16)},
{"spre", 0},
{"snow", 0},
{"star", 0},
{"stat", 0},
{"hnow", 0},
});
}
payload["print"]["cfg"] = "";
payload["print"]["fun"] = "";
payload["print"]["aux"] = "";
payload["print"]["stat"] = "";
}
if (status_cache.contains("heater_bed") && status_cache["heater_bed"].is_object()) {
const auto& bed = status_cache["heater_bed"];
if (bed.contains("temperature") && bed["temperature"].is_number()) {
@@ -7,6 +7,7 @@
#include <functional>
#include <cstdint>
#include <atomic>
#include <map>
#include <memory>
#include <mutex>
#include <set>
@@ -88,6 +89,7 @@ protected:
// Tray data for AMS payload building
struct AmsTrayData {
int slot_index = 0; // 0-based slot index
int extruder_id = 0; // Extruder this lane feeds (AFC extruder_index); 0 when unknown
bool has_filament = false;
std::string tray_type; // Material type (e.g., "PLA", "ASA")
std::string tray_color; // Raw color (#RRGGBB, 0xRRGGBB, or RRGGBBAA)
@@ -99,6 +101,10 @@ protected:
// Build ams JSON and call parser
void build_ams_payload(int ams_count, int max_lane_index, const std::vector<AmsTrayData>& trays);
// Build ams JSON with one box per extruder (best effort, for lane_data-based filament
// changers such as AFC) and call the parser. Boxes are ordered by extruder id.
void build_ams_payload_grouped(const std::vector<AmsTrayData>& trays);
// Methods that derived classes may need to override or access
virtual bool init_device_info(const std::string& dev_id, const std::string& dev_ip, const std::string& username, const std::string& password, bool use_ssl, const std::string& port);
virtual bool fetch_device_info(const std::string& base_url, const std::string& api_key, MoonrakerDeviceInfo& info, std::string& error) const;
@@ -163,10 +169,22 @@ private:
// System-specific filament fetch methods
bool fetch_hh_filament_info(std::vector<AmsTrayData>& trays, int& max_lane_index);
bool fetch_moonraker_filament_data(std::vector<AmsTrayData>& trays, int& max_lane_index);
// Lane name -> toolhead index, read from the AFC printer objects (the lane_data database has no
// extruder field). Returns false when AFC is not present or the objects cannot be read.
bool fetch_afc_lane_extruders(std::map<std::string, int>& lane_extruder);
// Build one BBL tray JSON object (placeholder when the tray has no filament).
static nlohmann::json make_ams_tray_json(const std::string& tray_id, const AmsTrayData& tray);
// Wrap the AMS boxes into the payload ParseV1_0 understands and apply the pull-mode
// readiness state (printer_type, push counters, storage, module versions).
void submit_ams_payload(const nlohmann::json& ams_array, unsigned long ams_exist_bits, unsigned long tray_exist_bits);
// JSON helper methods
static std::string safe_json_string(const nlohmann::json& obj, const char* key);
static int safe_json_int(const nlohmann::json& obj, const char* key);
// Accepts either a JSON number or a numeric string (AFC reports some fields as strings).
static int safe_json_int_flexible(const nlohmann::json& obj, const char* key, int default_value);
static std::string safe_array_string(const nlohmann::json& arr, int idx);
static int safe_array_int(const nlohmann::json& arr, int idx);
static std::string normalize_color_value(const std::string& color);
@@ -17,7 +17,6 @@
#include <slic3r/GUI/GUI_App.hpp>
#include <slic3r/GUI/MainFrame.hpp>
#include <slic3r/GUI/Plater.hpp>
#include <slic3r/GUI/PresetComboBoxes.hpp> // TabPresetComboBox::set_filament_idx
#include <slic3r/GUI/Tab.hpp>
#include <pybind11/stl.h>
@@ -49,110 +48,6 @@ PresetCollection& printer_presets(PresetBundle& bundle)
return static_cast<PresetCollection&>(bundle.printers);
}
// Handle to one category of currently edited preset. It is a category, not a snapshot: it always
// resolves the preset the matching tab edits now, so it stays valid across preset switches.
struct PresetEditor
{
Preset::Type type = Preset::TYPE_INVALID;
};
const char* preset_tab_name(Preset::Type type)
{
switch (type) {
case Preset::TYPE_PRINT: return "process";
case Preset::TYPE_FILAMENT: return "filament";
case Preset::TYPE_PRINTER: return "printer";
default: return "preset";
}
}
void update_edited_preset(Preset::Type type, const std::string& key, const std::string& value)
{
PluginHostUi::run_on_ui_thread([&] {
GUI::GUI_App& app = GUI::wxGetApp();
if (app.is_closing())
throw std::runtime_error("OrcaSlicer is closing");
if (app.preset_bundle == nullptr)
throw std::runtime_error("Preset bundle is not available");
if (app.plater() == nullptr)
throw std::runtime_error("OrcaSlicer main window is not available");
GUI::Tab* tab = app.get_tab(type);
if (tab == nullptr)
throw std::runtime_error(std::string("The ") + preset_tab_name(type) + " preset tab is not available");
// The tab for this preset type exists, but the selected printer's technology may not use it
// (the print tab no-ops under SLA); refuse instead of writing a value the UI cannot apply.
if (!tab->supports_printer_technology(app.preset_bundle->printers.get_selected_preset().printer_technology()))
throw std::runtime_error(std::string("The ") + preset_tab_name(type)
+ " preset is not available for the selected printer technology");
tab->apply_preset_config_value(key, value);
});
}
// Slot-addressed filament update. `slot_number` is 1-based, matching the GUI's filament slots and
// the values PresetBundle::filament_presets holds. The slot's assigned preset is resolved to its
// internal name; when that is not the preset the filament tab edits, the tab is switched through
// Tab::select_preset() - the normal UI preselection flow, so a dirty edited preset still prompts
// the user and a declined prompt cancels the call with a clear error and no change.
void update_filament_slot(int slot_number, const std::string& key, const std::string& value)
{
PluginHostUi::run_on_ui_thread([&] {
GUI::GUI_App& app = GUI::wxGetApp();
if (app.is_closing())
throw std::runtime_error("OrcaSlicer is closing");
if (app.preset_bundle == nullptr)
throw std::runtime_error("Preset bundle is not available");
if (app.plater() == nullptr)
throw std::runtime_error("OrcaSlicer main window is not available");
PresetBundle& bundle = *app.preset_bundle;
if (slot_number < 1 || static_cast<size_t>(slot_number) > bundle.filament_presets.size())
throw std::out_of_range("Filament slot " + std::to_string(slot_number) + " is out of range; slot numbers are 1-based and this printer has "
+ std::to_string(bundle.filament_presets.size()) + " filament slot(s)");
const std::string& assigned_name = bundle.filament_presets[static_cast<size_t>(slot_number) - 1];
if (assigned_name.empty())
throw std::runtime_error("Filament slot " + std::to_string(slot_number) + " has no assigned filament preset");
// Resolve the assigned name the way the app does, so a renamed/aliased entry maps to the
// internal preset it now identifies. Copy the name out before selecting anything: the
// collection can be reallocated while switching.
Preset* slot_preset = bundle.filaments.find_preset(assigned_name);
if (slot_preset == nullptr)
throw std::runtime_error("Filament slot " + std::to_string(slot_number) + " is assigned \"" + assigned_name
+ "\", which does not resolve to a filament preset");
const std::string target_name = slot_preset->name;
GUI::Tab* tab = app.get_tab(Preset::TYPE_FILAMENT);
if (tab == nullptr)
throw std::runtime_error("The filament preset tab is not available");
if (!tab->supports_printer_technology(bundle.printers.get_selected_preset().printer_technology()))
throw std::runtime_error("The filament preset is not available for the selected printer technology");
// Switch to the slot's preset through the normal preset selection, never a forced one, so the
// user's unsaved-changes prompt is honoured. A declined prompt returns false here.
if (bundle.filaments.get_edited_preset().name != target_name) {
if (!tab->select_preset(target_name))
throw std::runtime_error("Switching the edited filament preset to \"" + target_name + "\" for filament slot "
+ std::to_string(slot_number) + " was canceled; the setting was not changed");
}
// select_preset() can still leave a different preset edited (e.g. the target disappeared), so
// re-check before writing anything.
if (bundle.filaments.get_edited_preset().name != target_name)
throw std::runtime_error("The edited filament preset is \"" + bundle.filaments.get_edited_preset().name
+ "\", not \"" + target_name + "\"; the setting was not changed");
// Match PlaterPresetComboBox::switch_to_tab(): record which 0-based filament slot this tab
// combobox now edits, so the GUI shows the slot the value was written for.
if (GUI::TabPresetComboBox* combo = tab->get_combo_box())
combo->set_filament_idx(slot_number - 1);
tab->apply_preset_config_value(key, value);
});
}
void reload_local_bundle(const std::string& bundle_id)
{
bool reloaded = false;
@@ -224,47 +119,6 @@ void host_bindings::register_presets(py::module_& host)
.value("Plate", Preset::TYPE_PLATE)
.value("Model", Preset::TYPE_MODEL);
py::class_<PresetEditor>(preset, "PresetEditor",
"Handle to a category of currently edited preset. It is not a snapshot: it always "
"resolves the preset the matching tab edits now, so it stays usable across preset "
"switches. update() edits the preset in place; the change is not saved to disk.")
.def_readonly("type", &PresetEditor::type)
.def(
"update",
[](const PresetEditor& editor, const std::string& key, const std::string& value) {
update_edited_preset(editor.type, key, value);
},
py::arg("key"), py::arg("value"),
"Set one setting of the currently edited preset and run the same committed-change path as "
"editing the setting in the GUI; the edited preset becomes dirty until saved/exported. "
"key must be a setting of this preset category and value its serialized string form, "
"otherwise ValueError is raised and nothing is written. A setting edited through a field "
"runs that field's validation even before its page has been opened; one the GUI edits "
"outside a field (such as compatible printers) also recomputes preset compatibility.")
.def(
"update",
[](const PresetEditor& editor, int slot_number, const std::string& key, const std::string& value) {
if (editor.type != Preset::TYPE_FILAMENT)
throw std::invalid_argument("The slot_number form of update() is only available on "
"orca.host.preset.filament; call update(key, value) on this editor");
update_filament_slot(slot_number, key, value);
},
py::arg("slot_number"), py::arg("key"), py::arg("value"),
"Set one setting of the filament preset assigned to a 1-based filament slot. When that preset "
"is not the one currently edited the call switches to it through the normal preset-selection "
"flow, so an unsaved edited preset still prompts the user and a declined prompt cancels the "
"call with an error and no change. An out-of-range, empty or unresolved slot is rejected with "
"a clear error. Other preset editors accept only update(key, value); this form raises "
"ValueError on them.");
// The three preset categories edited by the main tabs. `process` is the print/process preset,
// `printer` the machine preset and `filament` the currently edited filament preset (its
// 3-argument form addresses a 1-based filament slot); each only accepts its own settings, so a
// printer setting passed to `process` is rejected instead of written silently.
preset.attr("process") = py::cast(PresetEditor{Preset::TYPE_PRINT});
preset.attr("printer") = py::cast(PresetEditor{Preset::TYPE_PRINTER});
preset.attr("filament") = py::cast(PresetEditor{Preset::TYPE_FILAMENT});
py::class_<Preset, std::unique_ptr<Preset, py::nodelete>>(host, "Preset")
.def_readonly("type", &Preset::type)
.def_readonly("name", &Preset::name)
-125
View File
@@ -30,7 +30,6 @@
#include "libslic3r/Line.hpp"
#include "libslic3r/ExtrusionEntity.hpp"
#include "libslic3r/BoundingBox.hpp"
#include <functional>
#include <map>
#include <set>
#include <string>
@@ -597,127 +596,3 @@ TEST_CASE("Body centering survives islands merging and splitting between layers"
}
}
}
TEST_CASE("Z contouring slices an object that has several instances", "[PrintObject]")
{
Print print;
Model model;
place_two_cube_instances_apart(10., { { "zaa_enabled", "1" } }, print, model);
REQUIRE(print.objects().size() == 1);
REQUIRE(print.objects().front()->instances().size() == 2);
CHECK_NOTHROW(print.process());
CHECK(print.objects().front()->is_step_done(posContouring));
}
TEST_CASE("Z contouring slices instances of one object that are turned differently", "[PrintObject]")
{
// An instance turned about Z is sliced as a PrintObject of its own, with the same ModelObject behind it.
Print print;
Model model;
place_two_cube_instances_apart(10., { { "zaa_enabled", "1" } }, print, model);
model.objects.front()->instances.back()->set_rotation(Z, PI / 4.);
print.apply(model, DynamicPrintConfig(print.full_print_config()));
REQUIRE(print.objects().size() == 2);
CHECK_NOTHROW(print.process());
for (const PrintObject *object : print.objects())
CHECK(object->is_step_done(posContouring));
}
// A box tilted about X, so that its top slopes along Y and Z contouring has a surface to follow, with
// one instance for each Z rotation given, laid out in a row.
static void slice_tilted_box_instances(const std::vector<double> &z_rotations, Print &print, Model &model)
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({ { "zaa_enabled", "1" } });
TriangleMesh box = make_cube(20, 20, 10);
box.rotate_x(float(PI / 12.));
ModelObject *object = model.add_object();
object->add_volume(std::move(box));
for (size_t idx = 0; idx < z_rotations.size(); ++idx) {
ModelInstance *instance = object->add_instance();
instance->set_offset(Vec3d(50. + 50. * double(idx), 100., 0.));
instance->set_rotation(Z, z_rotations[idx]);
}
object->ensure_on_bed();
print.auto_assign_extruders(object);
print.apply(model, config);
print.validate();
print.set_status_silent();
print.process();
}
// The Z that contouring gave each point of the object's extrusions, by layer and by XY in the
// PrintObject's own frame, which does not depend on where its instances stand on the bed.
static std::vector<std::map<std::pair<coord_t, coord_t>, coord_t>> contoured_heights(const PrintObject &object)
{
std::vector<std::map<std::pair<coord_t, coord_t>, coord_t>> heights(object.layer_count());
for (size_t layer_idx = 0; layer_idx < object.layer_count(); ++layer_idx) {
auto &layer_heights = heights[layer_idx];
std::function<void(const ExtrusionEntity &)> visit = [&](const ExtrusionEntity &entity) {
if (const auto *path = dynamic_cast<const ExtrusionPath *>(&entity)) {
if (path->z_contoured)
for (const Point3 &pt : path->polyline.points)
layer_heights[{ pt.x(), pt.y() }] = pt.z();
} else if (const auto *multipath = dynamic_cast<const ExtrusionMultiPath *>(&entity)) {
for (const ExtrusionPath &path : multipath->paths)
visit(path);
} else if (const auto *loop = dynamic_cast<const ExtrusionLoop *>(&entity)) {
for (const ExtrusionPath &path : loop->paths)
visit(path);
} else if (const auto *collection = dynamic_cast<const ExtrusionEntityCollection *>(&entity)) {
for (const ExtrusionEntity *child : collection->entities)
visit(*child);
}
};
for (const LayerRegion *region : object.get_layer(int(layer_idx))->regions()) {
visit(region->perimeters);
visit(region->fills);
}
}
return heights;
}
TEST_CASE("Z contouring follows the surface of each instance as it is turned", "[PrintObject]")
{
// Two instances of a box with a sloped top, the second turned a quarter turn about Z: its top slopes
// along X instead of Y. Each is contoured against the box turned as that instance is, so it has to
// match the same box placed alone with that turn.
Print print;
Model model;
slice_tilted_box_instances({ 0., PI / 2. }, print, model);
REQUIRE(print.objects().size() == 2);
for (const PrintObject *object : print.objects()) {
const double z_rotation = object->instances().front().model_instance->get_rotation().z();
Print reference;
Model reference_model;
slice_tilted_box_instances({ z_rotation }, reference, reference_model);
REQUIRE(reference.objects().size() == 1);
const auto heights = contoured_heights(*object);
const auto reference_heights = contoured_heights(*reference.objects().front());
REQUIRE(heights.size() == reference_heights.size());
size_t matched = 0, lifted = 0;
for (size_t layer_idx = 0; layer_idx < heights.size(); ++layer_idx) {
const coord_t print_z = scaled(object->get_layer(int(layer_idx))->print_z);
for (const auto &[xy, z] : heights[layer_idx]) {
const auto it = reference_heights[layer_idx].find(xy);
if (it == reference_heights[layer_idx].end())
continue;
INFO("layer " << layer_idx << ", rotation " << z_rotation);
CHECK(std::abs(z - it->second) <= scaled(0.001));
++matched;
if (std::abs(z - print_z) > scaled(0.01))
++lifted;
}
}
INFO("rotation " << z_rotation);
// Enough points in common to mean something, and contouring did move some of them.
CHECK(matched > 100);
CHECK(lifted > 0);
}
}
+1
View File
@@ -5,6 +5,7 @@ add_executable(${_TEST_NAME}_tests
test_config_value_formatter.cpp
test_creality_cfs_match.cpp
test_dev_mapping.cpp
test_dev_extder_system.cpp
test_device_access.cpp
test_moonraker_discovery.cpp
test_network_discovery.cpp
@@ -0,0 +1,161 @@
// Match the include environment that libslic3r_gui TUs get from pchheader.hpp: Windows.h with
// WIN32_LEAN_AND_MEAN/NOMINMAX must come first so rpcndr.h's `byte` is processed before <cstddef>
// makes std::byte a competing candidate (otherwise the Windows COM headers pulled in via
// DeviceManager.hpp error with an ambiguous `byte`). wx/timer.h must precede DeviceManager.hpp,
// which includes DeviceErrorDialog.hpp (uses wxTimerEvent) before its own wx/timer.h include.
#include "catch2/catch_test_macros.hpp"
#include "catch2/catch_message.hpp"
#include <slic3r/GUI/DeviceCore/DevDefs.h>
#include <string>
#include <utility>
#include <vector>
#ifdef WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <Windows.h>
#endif
#include <catch2/catch_all.hpp>
#include <wx/timer.h>
#include "slic3r/GUI/DeviceManager.hpp"
#include "slic3r/GUI/DeviceCore/DevExtruderSystem.h"
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using namespace Slic3r;
TEST_CASE("Extruder state decodes a generic toolhead set", "[DevExtderSystem]")
{
MachineObject obj(nullptr, nullptr, "test", "test_dev", "127.0.0.1");
// device.extruder.state packing: count 0..3, current 4..7, target 8..11,
// switch 12..14, loading 15..18, busy 19.
const int extruder_count = 4;
const int current_extruder = 2;
const int switch_state = ES_BUSY;
const int loading_extruder = 1;
const int state = extruder_count | (current_extruder << 4) | (3 << 8) |
(switch_state << 12) | (loading_extruder << 15) | (1 << 19);
json extruder = { {"state", state}, {"info", json::array()} };
for (int id = 0; id < extruder_count; ++id) {
// info: bit 1 has filament, bit 3 nozzle present.
// temp: current 0..15, target 16..31. spre/snow/star: slot 0..7, ams 8..15.
extruder["info"].push_back({
{"id", id},
{"filam_bak", json::array({id})},
{"info", (id % 2 == 0 ? 2 : 0) | 8},
{"temp", (200 + id) | ((250 + id) << 16)},
{"spre", 10 << 8},
{"snow", id | ((20 + id) << 8)},
{"star", 30 << 8},
{"stat", 0},
{"hnow", id},
});
}
ExtderSystemParser::ParseV2_0(extruder, obj.GetExtderSystem());
REQUIRE(obj.GetExtderSystem()->GetTotalExtderCount() == extruder_count);
CHECK(obj.GetExtderSystem()->GetCurrentExtderId() == current_extruder);
CHECK(static_cast<int>(obj.GetExtderSystem()->GetSwitchState()) == switch_state);
CHECK(obj.GetExtderSystem()->GetLoadingExtderId() == loading_extruder);
CHECK(obj.GetExtderSystem()->IsBusyLoading());
for (int id = 0; id < extruder_count; ++id) {
const auto ext = obj.GetExtderSystem()->GetExtderById(id);
REQUIRE(ext.has_value());
INFO("extruder " << id);
CHECK(ext->GetExtId() == id);
CHECK(ext->GetCurrentTemp() == 200 + id);
CHECK(ext->GetTargetTemp() == 250 + id);
CHECK(ext->HasFilamentInExt() == (id % 2 == 0));
CHECK(ext->GetFilamBackup() == std::vector<int>{id});
CHECK(ext->GetSlotPre().ams_id == "10");
CHECK(ext->GetSlotNow().ams_id == std::to_string(20 + id));
CHECK(ext->GetSlotNow().slot_id == std::to_string(id));
CHECK(ext->GetSlotTarget().ams_id == "30");
CHECK(ext->GetNozzleId() == id);
}
}
TEST_CASE("Legacy single-toolhead parser fills only the main extruder", "[DevExtderSystem]")
{
MachineObject obj(nullptr, nullptr, "test", "test_dev", "127.0.0.1");
REQUIRE(obj.GetExtderSystem()->GetTotalExtderCount() == 1);
// ParseV1_0 is the legacy single/dual fallback. It returns unless the system reports exactly
// one toolhead, so it only ever writes MAIN_EXTRUDER_ID's fields.
const json legacy = {
{"nozzle_temper", 210},
{"nozzle_target_temper", 245},
{"ams", {{"tray_now", "2"}, {"tray_tar", "3"}}}
};
ExtderSystemParser::ParseV1_0(legacy, obj.GetExtderSystem());
const auto ext = obj.GetExtderSystem()->GetExtderById(MAIN_EXTRUDER_ID);
REQUIRE(ext.has_value());
CHECK(ext->GetCurrentTemp() == 210);
CHECK(ext->GetTargetTemp() == 245);
// Below 0x80 the tray pointer encodes ams_id = value / 4, slot_id = value % 4.
CHECK(ext->GetSlotNow().ams_id == "0");
CHECK(ext->GetSlotNow().slot_id == "2");
CHECK(ext->GetSlotTarget().ams_id == "0");
CHECK(ext->GetSlotTarget().slot_id == "3");
CHECK(obj.GetExtderSystem()->IsBusyLoading());
CHECK(obj.GetExtderSystem()->GetLoadingExtderId() == MAIN_EXTRUDER_ID);
}
// ParseV2_0 does not enforce the documented extruder dialect invariants: the count in `state` and
// the id ordering of `info[]` are trusted, not checked. This test pins the resulting behavior.
TEST_CASE("Malformed extruder payload is stored by info array position", "[DevExtderSystem]")
{
const auto extder_info = [](int id) {
// Every key ParseV2_0 reads must be present.
return json{ {"id", id}, {"filam_bak", json::array()}, {"info", 0}, {"temp", 0},
{"spre", 0}, {"snow", 0}, {"star", 0}, {"stat", 0}, {"hnow", 0} };
};
SECTION("state count disagrees with info length") {
MachineObject obj(nullptr, nullptr, "test", "test_dev", "127.0.0.1");
// `state` reports 2 toolheads but info[] carries 3.
json info = json::array();
for (int id = 0; id < 3; ++id)
info.push_back(extder_info(id));
ExtderSystemParser::ParseV2_0(json{ {"state", 2}, {"info", info} }, obj.GetExtderSystem());
// The info array wins: three toolheads are stored. m_total_extder_count still holds 2, so
// GetTotalExtderCount() would trip its debug assert; only the stored vector is inspected.
CHECK(obj.GetExtderSystem()->GetTotalExtderSize() == 3);
for (int id = 0; id < 3; ++id) {
const auto ext = obj.GetExtderSystem()->GetExtderById(id);
REQUIRE(ext.has_value());
CHECK(ext->GetExtId() == id);
}
}
SECTION("info id differs from the array index") {
MachineObject obj(nullptr, nullptr, "test", "test_dev", "127.0.0.1");
// ids 1 and 2 sit at array positions 0 and 1.
json info = json::array({extder_info(1), extder_info(2)});
ExtderSystemParser::ParseV2_0(json{ {"state", 2}, {"info", info} }, obj.GetExtderSystem());
// Toolheads are stored by array position; the payload id is kept but is not the lookup key.
const auto first = obj.GetExtderSystem()->GetExtderById(0);
REQUIRE(first.has_value());
CHECK(first->GetExtId() == 1);
const auto second = obj.GetExtderSystem()->GetExtderById(1);
REQUIRE(second.has_value());
CHECK(second->GetExtId() == 2);
}
}
+161 -1
View File
@@ -13,10 +13,14 @@
#include <Windows.h>
#endif
#include <set>
#include <string>
#include <utility>
#include <vector>
#include <catch2/catch_test_macros.hpp>
#include "slic3r/GUI/DeviceCore/DevDefs.h"
#include "libslic3r/ProjectTask.hpp"
#include <vector>
#include <catch2/catch_message.hpp>
#include <catch2/catch_all.hpp>
@@ -65,6 +69,162 @@ TEST_CASE("AMS tray placeholder state follows the latest status", "[DevFilaSyste
CHECK_FALSE(tray->is_slot_placeholder);
}
TEST_CASE("Agent filament slots preserve every extruder and AMS binding", "[DevFilaSystem]")
{
MachineObject obj(nullptr, nullptr, "test", "test_dev", "127.0.0.1");
const json filament = json::parse(R"({
"units": [
{ "id": "0", "extruder": 0, "slots": [
{ "index": 0, "loaded": true, "material": "PLA", "color": "FF5733FF" },
{ "index": 1, "loaded": true, "material": "PLA", "color": "33C1FFFF" },
{ "index": 2, "loaded": true, "material": "PLA", "color": "8D33FFFF" },
{ "index": 3, "loaded": false, "material": "", "color": "00000000" }
] },
{ "id": "1", "extruder": 1, "slots": [
{ "index": 0, "loaded": true, "material": "ASA", "color": "33C1FFFF" },
{ "index": 1, "loaded": true, "material": "ASA", "color": "8D33FFFF" },
{ "index": 2, "loaded": true, "material": "ASA", "color": "FF5733FF" },
{ "index": 3, "loaded": false, "material": "", "color": "00000000" }
] },
{ "id": "2", "extruder": 2, "slots": [
{ "index": 0, "loaded": true, "material": "ABS", "color": "8D33FFFF" },
{ "index": 1, "loaded": true, "material": "ABS", "color": "FF5733FF" },
{ "index": 2, "loaded": true, "material": "ABS", "color": "33C1FFFF" },
{ "index": 3, "loaded": false, "material": "", "color": "00000000" }
] },
{ "id": "3", "extruder": 3, "slots": [
{ "index": 0, "loaded": true, "material": "PETG", "color": "FF5733FF" },
{ "index": 1, "loaded": true, "material": "PETG", "color": "33C1FFFF" },
{ "index": 2, "loaded": true, "material": "PETG", "color": "8D33FFFF" },
{ "index": 3, "loaded": false, "material": "", "color": "00000000" }
] }
],
"external": [
{ "extruder": 3, "loaded": true, "material": "PETG", "preset_id": "P3" },
{ "extruder": 0, "loaded": true, "material": "PLA", "preset_id": "P0" },
{ "extruder": 2, "loaded": false, "material": "ABS", "preset_id": "P2" },
{ "extruder": 1, "loaded": true, "material": "ASA", "preset_id": "P1" }
]
})");
DevFilaSystemParser::ParseAgentFilament(filament, &obj, obj.GetFilaSystem().get());
REQUIRE(obj.vt_slot.size() == 4);
CHECK(obj.vt_slot[0].id == "255");
CHECK(obj.vt_slot[1].id == "254");
CHECK(obj.vt_slot[2].id == "253");
CHECK(obj.vt_slot[3].id == "252");
CHECK(obj.vt_slot[0].setting_id == "P0");
CHECK(obj.vt_slot[1].setting_id == "P1");
CHECK(obj.vt_slot[2].setting_id == "P2");
CHECK(obj.vt_slot[3].setting_id == "P3");
REQUIRE(obj.GetFilaSystem()->GetAmsCount() == 4);
for (int extruder = 0; extruder < 4; ++extruder) {
const auto& ams = obj.GetFilaSystem()->GetAmsList().at(std::to_string(extruder));
CHECK(ams->GetExtruderId() == extruder);
CHECK(ams->GetBindedExtruderSet() == std::set<int>{extruder});
REQUIRE(ams->GetTrays().size() == 4);
CHECK(ams->GetTrays().at("0")->color != ams->GetTrays().at("1")->color);
CHECK(ams->GetTrays().at("1")->color != ams->GetTrays().at("2")->color);
CHECK_FALSE(ams->GetTrays().at("3")->is_exists);
}
CHECK(obj.contains_tray("253", "0"));
CHECK(obj.get_tray("253", "0").setting_id == "P2");
CHECK(obj.GetFilaSystem()->GetExtruderIdByAmsId("253") == 2);
const auto tray_index_map = obj.GetFilaSystem()->GetTrayIndexMap();
REQUIRE(tray_index_map.count(252) == 1);
CHECK(tray_index_map.at(252).first == 252);
CHECK(tray_index_map.at(252).second == 0);
}
TEST_CASE("Generic AMS tray index map uses cumulative lane counts", "[DevMapping]")
{
MachineObject obj(nullptr, nullptr, "test", "test_dev", "127.0.0.1");
// A well-formed generic payload pairs "units" with "external". An empty external array resets
// vt_slot, clearing the default virtual tray (255) MachineObject's constructor seeds; otherwise
// that phantom external tray lands in GetTrayIndexMap and inflates the map size.
json filament = { {"units", json::array()}, {"external", json::array()} };
for (int ams_id = 0; ams_id < 2; ++ams_id) {
json unit = {
{"id", std::to_string(ams_id)},
{"extruder", ams_id},
{"slots", json::array()}
};
for (int slot_id = 0; slot_id < 5; ++slot_id)
unit["slots"].push_back({{"index", slot_id}, {"loaded", false}});
filament["units"].push_back(std::move(unit));
}
DevFilaSystemParser::ParseAgentFilament(filament, &obj, obj.GetFilaSystem().get());
const auto tray_index_map = obj.GetFilaSystem()->GetTrayIndexMap();
REQUIRE(tray_index_map.size() == 10);
CHECK(tray_index_map.at(0).first == 0);
CHECK(tray_index_map.at(0).second == 0);
CHECK(tray_index_map.at(4).first == 0);
CHECK(tray_index_map.at(4).second == 4);
CHECK(tray_index_map.at(5).first == 1);
CHECK(tray_index_map.at(5).second == 0);
CHECK(tray_index_map.at(9).first == 1);
CHECK(tray_index_map.at(9).second == 4);
}
TEST_CASE("Generic tray index map handles unequal per-unit slot counts", "[DevMapping]")
{
MachineObject obj(nullptr, nullptr, "test", "test_dev", "127.0.0.1");
// An "external" array must accompany "units" so vt_slot is reset (see the cumulative test above).
json filament = { {"units", json::array()}, {"external", json::array()} };
const std::vector<int> slot_counts = {4, 12};
for (int ams_id = 0; ams_id < static_cast<int>(slot_counts.size()); ++ams_id) {
json unit = { {"id", std::to_string(ams_id)}, {"extruder", ams_id}, {"slots", json::array()} };
for (int slot_id = 0; slot_id < slot_counts[ams_id]; ++slot_id)
unit["slots"].push_back({{"index", slot_id}, {"loaded", false}});
filament["units"].push_back(std::move(unit));
}
DevFilaSystemParser::ParseAgentFilament(filament, &obj, obj.GetFilaSystem().get());
const auto tray_index_map = obj.GetFilaSystem()->GetTrayIndexMap();
REQUIRE(tray_index_map.size() == 16);
// Unit 0 occupies global lanes 0..3; unit 1 continues at 4..15 because the counter advances
// by the reported tray count, not by a fixed four-slot stride.
CHECK(tray_index_map.at(0).first == 0);
CHECK(tray_index_map.at(0).second == 0);
CHECK(tray_index_map.at(3).first == 0);
CHECK(tray_index_map.at(3).second == 3);
CHECK(tray_index_map.at(4).first == 1);
CHECK(tray_index_map.at(4).second == 0);
CHECK(tray_index_map.at(15).first == 1);
CHECK(tray_index_map.at(15).second == 11);
}
TEST_CASE("A generic AMS unit reports its reported tray count", "[DevFilaSystem]")
{
MachineObject obj(nullptr, nullptr, "test", "test_dev", "127.0.0.1");
json filament = { {"units", json::array()}, {"external", json::array()} };
const std::vector<int> slot_counts = {8, 1};
for (int ams_id = 0; ams_id < static_cast<int>(slot_counts.size()); ++ams_id) {
json unit = { {"id", std::to_string(ams_id)}, {"extruder", ams_id}, {"slots", json::array()} };
for (int slot_id = 0; slot_id < slot_counts[ams_id]; ++slot_id)
unit["slots"].push_back({{"index", slot_id}, {"loaded", false}});
filament["units"].push_back(std::move(unit));
}
DevFilaSystemParser::ParseAgentFilament(filament, &obj, obj.GetFilaSystem().get());
// Non-Bambu units are not capped at the four-slot Bambu contract; the reported tray count wins.
const auto& ams_list = obj.GetFilaSystem()->GetAmsList();
REQUIRE(ams_list.at("0")->GetSlotCount() == 8);
REQUIRE(ams_list.at("1")->GetSlotCount() == 1);
}
TEST_CASE("Switch-bound AMS trays map to the left extruder", "[DevMapping]")
{
MachineObject obj(nullptr, nullptr, "test", "test_dev", "127.0.0.1");
@@ -1,6 +1,5 @@
#include <catch2/catch_test_macros.hpp>
#include <catch2/catch_all.hpp>
#include <catch2/generators/catch_generators.hpp>
#include <slic3r/GUI/DeviceCore/DevManager.h>
#include <slic3r/GUI/DeviceManager.hpp>
@@ -17,7 +16,6 @@
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
using namespace Slic3r;
using json = nlohmann::json;
@@ -51,21 +49,6 @@ public:
AgentInfo get_agent_info() override { return m_info; }
int send_message(std::string dev_id, std::string json_str, int, int) override
{
published_device = std::move(dev_id);
published_message = json::parse(json_str);
return 0;
}
int send_message_to_printer(std::string dev_id, std::string json_str, int qos, int flag) override
{
return send_message(std::move(dev_id), std::move(json_str), qos, flag);
}
std::string published_device;
json published_message;
private:
AgentInfo m_info;
};
@@ -177,62 +160,3 @@ TEST_CASE("Device manager filters and rehomes devices by printer-agent ownership
CHECK(manager.get_my_machine_list("integration-agent-a").empty());
CHECK(manager.get_my_machine_list("integration-agent-b").count(machine.dev_id) == 1);
}
TEST_CASE("AMS filament settings keep legacy single-color commands compatible", "[DeviceManager][AMSMaterialsSetting][integration]")
{
ScopedAppConfig app_config;
auto agent = std::make_shared<TestPrinterAgent>("integration-agent");
NetworkAgent network(nullptr, agent);
DeviceManager manager(&network, false, &app_config.config);
MachineObject object(&manager, &network, "Test printer", "integration-device", "192.0.2.10");
object.dev_connection_type = GENERATE("lan", "cloud");
REQUIRE(object.command_ams_filament_settings(1, 2, "filament-id", "setting-id", "FF000080", "PLA", 190, 220) == 0);
const json& payload = agent->published_message.at("print");
CHECK(agent->published_device == object.get_dev_id());
CHECK(payload.at("command") == "ams_filament_setting");
CHECK(payload.at("ams_id") == 1);
CHECK(payload.at("slot_id") == 2);
CHECK(payload.at("tray_color") == "FF000080");
CHECK_FALSE(payload.contains("cols"));
CHECK_FALSE(payload.contains("ctype"));
}
TEST_CASE("AMS filament settings preserve ordered gradient and multicolor RGBA components", "[DeviceManager][AMSMaterialsSetting][integration]")
{
ScopedAppConfig app_config;
auto agent = std::make_shared<TestPrinterAgent>("integration-agent");
NetworkAgent network(nullptr, agent);
DeviceManager manager(&network, false, &app_config.config);
MachineObject object(&manager, &network, "Test printer", "integration-device", "192.0.2.10");
object.dev_connection_type = GENERATE("lan", "cloud");
const int color_type = GENERATE(0, 1);
const std::vector<std::string> colors{"FF000080", "0000FF40", "00FF00FF"};
REQUIRE(object.command_ams_filament_settings(1, 2, "filament-id", "setting-id", colors.front(), "PLA", 190, 220,
colors, color_type) == 0);
const json& payload = agent->published_message.at("print");
CHECK(payload.at("tray_color") == colors.front());
CHECK(payload.at("cols").get<std::vector<std::string>>() == colors);
CHECK(payload.at("ctype") == color_type);
}
TEST_CASE("AMS filament settings default a supplied single-color list to type two", "[DeviceManager][AMSMaterialsSetting][integration]")
{
ScopedAppConfig app_config;
auto agent = std::make_shared<TestPrinterAgent>("integration-agent");
NetworkAgent network(nullptr, agent);
DeviceManager manager(&network, false, &app_config.config);
MachineObject object(&manager, &network, "Test printer", "integration-device", "192.0.2.10");
object.dev_connection_type = GENERATE("lan", "cloud");
const std::vector<std::string> colors{"FF000080"};
REQUIRE(object.command_ams_filament_settings(1, 2, "filament-id", "setting-id", colors.front(), "PLA", 190, 220,
colors) == 0);
const json& payload = agent->published_message.at("print");
CHECK(payload.at("cols").get<std::vector<std::string>>() == colors);
CHECK(payload.at("ctype") == 2);
}
-120
View File
@@ -1,19 +1,3 @@
// why: keep the Windows headers ahead of libslic3r. Model.hpp pulls in Format/STEP.hpp, and
// OCCT's Standard_Macro.hxx defines NOUSER and NOGDI on Windows so that windows.h does not
// collide with OCCT's identifiers. Defined that early they also hide the USER and GDI
// declarations, and the wx MSW headers Field.hpp reaches (wx/wxprec.h -> wx/msw/private.h)
// need WNDPROC, RGB and the ::GetWindowRect family. Including windows.h first, as
// libslic3r_gui does through pchheader.hpp or win_platform.hpp, keeps them.
#ifdef WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <Windows.h>
#endif
#include <catch2/catch_all.hpp>
#include <cstddef>
@@ -22,12 +6,8 @@
#include <libslic3r/TriangleMesh.hpp>
#include <slic3r/GUI/DockPanel.hpp>
#include <slic3r/GUI/AuiPaneLayout.hpp>
#include <slic3r/GUI/OptionsGroup.hpp>
#include <slic3r/GUI/Widgets/WebHosting.hpp>
#include <map>
#include <utility>
#include <catch2/catch_test_macros.hpp>
#include <catch2/catch_message.hpp>
#include <catch2/matchers/catch_matchers_floating_point.hpp>
@@ -157,106 +137,6 @@ TEST_CASE("Plugin host API exposes host-owned bundle and preset surface to Pytho
CHECK(printers.attr("find_preset")(printer_preset.name).attr("name").cast<std::string>() == printer_preset.name);
}
TEST_CASE("Plugin host API exposes the editable preset category handles and guards them before Orca app initialization",
"[PluginHost][Python]")
{
py::object host = import_orca_module().attr("host");
py::object preset = host.attr("preset");
REQUIRE(has_attr(preset, "PresetEditor"));
REQUIRE(has_attr(preset, "process"));
REQUIRE(has_attr(preset, "printer"));
REQUIRE(has_attr(preset, "filament"));
py::object process = preset.attr("process");
py::object printer = preset.attr("printer");
py::object filament = preset.attr("filament");
CHECK(process.attr("type").cast<Slic3r::Preset::Type>() == Slic3r::Preset::TYPE_PRINT);
CHECK(printer.attr("type").cast<Slic3r::Preset::Type>() == Slic3r::Preset::TYPE_PRINTER);
CHECK(filament.attr("type").cast<Slic3r::Preset::Type>() == Slic3r::Preset::TYPE_FILAMENT);
for (const py::object& editor : { process, printer, filament })
CHECK(has_attr(editor, "update"));
// With no wx application the call must fail cleanly, like the rest of host.preset, and must not
// be mistaken for a missing attribute or an argument error.
for (const py::object& editor : { process, printer, filament }) {
try {
editor.attr("update")("layer_height", "0.25");
FAIL("preset editor update unexpectedly succeeded without a wx application");
} catch (const py::error_already_set& error) {
CHECK(error.matches(PyExc_RuntimeError));
CHECK(std::string(error.what()).find("OrcaSlicer application is not initialized") != std::string::npos);
}
}
}
TEST_CASE("Plugin host API exposes the filament slot form of preset update and guards it", "[PluginHost][Python]")
{
py::object host = import_orca_module().attr("host");
py::object preset = host.attr("preset");
// The filament editor accepts update(slot_number, key, value) as well as update(key, value); with
// no wx application it reaches the same clean failure as the rest of host.preset. The slot
// validation and the switch/cancel path need a running app, so they are not exercised here.
try {
preset.attr("filament").attr("update")(1, "layer_height", "0.25");
FAIL("slot-addressed filament update unexpectedly succeeded without a wx application");
} catch (const py::error_already_set& error) {
CHECK(error.matches(PyExc_RuntimeError));
CHECK(std::string(error.what()).find("OrcaSlicer application is not initialized") != std::string::npos);
}
// The process and printer editors accept only update(key, value); the slot form is rejected
// before any application access, naming the editor that does accept it.
for (const char* name : { "process", "printer" }) {
CAPTURE(name);
try {
preset.attr(name).attr("update")(1, "layer_height", "0.25");
FAIL("slot-addressed update on a non-filament editor unexpectedly succeeded");
} catch (const py::error_already_set& error) {
CHECK(error.matches(PyExc_ValueError));
CHECK(std::string(error.what()).find("only available on") != std::string::npos);
}
}
}
TEST_CASE("A settings group resolves an option's id from its option map", "[PluginHost]")
{
using Slic3r::GUI::option_id_in_map;
using Slic3r::GUI::t_opt_map;
// The map ConfigOptionsGroup::get_option leaves: a scalar option, and a per-extruder option
// whose entries carry their index.
t_opt_map options;
options.emplace("layer_height", std::make_pair(std::string("layer_height"), -1));
options.emplace("nozzle_diameter#0", std::make_pair(std::string("nozzle_diameter"), 0));
options.emplace("nozzle_diameter#1", std::make_pair(std::string("nozzle_diameter"), 1));
// A negative index resolves a scalar option and yields its own (negative) index.
int index = -1;
CHECK(option_id_in_map(options, "layer_height", index) == "layer_height");
CHECK(index == -1);
// A negative index on a vector option matches several entries, so it resolves to nothing.
index = -1;
CHECK(option_id_in_map(options, "nozzle_diameter", index).empty());
// An explicit index selects that entry.
index = 1;
CHECK(option_id_in_map(options, "nozzle_diameter", index) == "nozzle_diameter#1");
CHECK(index == 1);
// An index no entry carries, and a key the map does not own, resolve to nothing.
index = 7;
CHECK(option_id_in_map(options, "nozzle_diameter", index).empty());
index = -1;
CHECK(option_id_in_map(options, "wall_loops", index).empty());
const t_opt_map empty;
CHECK(option_id_in_map(empty, "layer_height", index).empty());
}
TEST_CASE("Plugin host API reports unavailable GUI objects before Orca app initialization", "[PluginHost][Python]")
{
py::object host = import_orca_module().attr("host");