Feat: Add multiple and 3D bed exclusion volumes (#13777)

# Description

This PR adds opt-in, height-aware exclusion volumes to OrcaSlicer,
including multi-nozzle handling, object and generated-geometry
validation, final G-code collision checking, and travel rerouting.

It grew from the original object-placement prototype into a
collision-aware slicing pipeline with documented limitations. The
central compatibility decision is that Orca's existing
`bed_exclude_area` keeps its historical meaning, while the new
`bed_exclude_volumes` setting explicitly enables the stronger
collision-aware behavior.

<img width="935" height="707" alt="Travel paths routed around exclusion
volumes"
src="https://github.com/user-attachments/assets/22925e5c-a3b1-4c26-be1a-8a89d9970cb5"
/>

Related issues: #5922, #10579, #10638 and #12774.

## Why this is useful

The existing 2D exclusion area prevents object placement in areas such
as the filament-cutter corner on Bambu printers. It cannot describe low
bed clips, raised tool docks, camera arms, flying-gantry hardware, or
other obstacles that occupy only part of the printer's Z range.

Treating every existing area as a physical motion obstacle would also be
unsafe for compatibility: some printers deliberately move into their
excluded material area. This PR therefore separates the two concepts
rather than changing the meaning of existing profiles.

| Setting | Purpose | Existing motion affected? |
| --- | --- | --- |
| `bed_exclude_area` | Existing bed-fixed material/placement keep-out |
No G-code checking or travel rerouting |
| `bed_exclude_volumes` | Shared 3D collision volumes |
Object/generated-material checks, G-code validation and travel rerouting
|
| `extruder_bed_exclude_volumes` | Per-extruder 3D collision volumes |
Same collision behavior, resolved for the active physical nozzle |

Bed areas and collision volumes are additive. A printer can retain an
existing cutter/material keep-out while adding separate physical
collision volumes. Belt printers retain the existing projection of bed
areas onto the tilted belt surface; collision volumes remain in model
coordinates.

## Configuration and syntax

`bed_exclude_volumes` accepts one or more polygonal prisms:

```text
XxY,XxY,...
```

defines a full-height collision volume.

```text
REGION|REGION|REGION
```

defines multiple independent volumes.

```text
ZMIN..ZMAX;XxY,XxY,...
```

defines a volume active only across that Z range. Either Z bound may be
omitted:

```text
..10;20x20,40x20,40x40,20x40
30..;20x20,40x20,40x40,20x40
```

For example:

```text
20x0,45x0,45x18,20x18|8..22;115x20,145x20,145x48,115x48
```

defines one full-height volume and one volume active from Z=8 mm to Z=22
mm. Z ranges are validated and clamped against the configured printable
height, and decimal parsing is locale-independent.

The CLI exposes the same distinction:

```text
--bed-exclude-area
--bed-exclude-volumes
```

Existing scripts using `--bed-exclude-area` retain the original polygon
format and behavior.

## Backward compatibility and migration

- Existing profiles and projects using only `bed_exclude_area` keep its
material/placement keep-out meaning; they do not implicitly enable
collision-volume checking or travel rerouting.
- Stock printer motion is not checked or rerouted against bed areas.
This is important for machines that deliberately enter an excluded
material area during cutting or loading.
- The new syntax is stored under separate config keys, so an older Orca
build does not try to deserialize a volumetric string as the existing
point-list option.
- In **Printer settings → Basic information → Printable space**,
**Excluded bed area** remains a normal editable field with Orca's
standard reset controls. **Toolhead collision volumes** is a separate
field directly below it. There is no Convert/Copy button and neither
setting clears the other.
- A bed-area polygon can be manually copied into the collision-volume
field to describe a full-height physical obstacle. Pasting volume syntax
into the bed-area field instead prompts for confirmation before adding
it to the appropriate volume definitions. The saved bed area, existing
volumes and selected nozzle mode are preserved; cancelling leaves them
unchanged.
- If a user does not configure the new volume keys, the new G-code
checker, rerouter, support trimming and nozzle-specific brim behavior
remain inactive.

This gives existing profiles a stable compatibility boundary while
allowing users and maintainers to migrate deliberately to full collision
checking over time.

## Multi-nozzle behavior

For multi-nozzle printers, the collision-volume mode selects one of
three behaviours. In individual mode, each extruder's definition is
edited on its own Extruder settings page. These modes apply only to
collision volumes; the excluded bed area stays shared and bed-fixed.

Collision volumes support three modes:

<img width="549" height="441" alt="Exclusion volume behavior selector"
src="https://github.com/user-attachments/assets/6ca8c2e2-d00e-4b32-9b12-bfbff0928966"
/>

### Shared

Every physical nozzle uses the same collision-volume definition.

<img width="2353" height="1633" alt="Shared exclusion volumes"
src="https://github.com/user-attachments/assets/96fe938b-07b4-4cd9-b587-e31f2ebba5f8"
/>

### Toolhead-relative (nozzle offsets)

The shared definition is treated as relative to the toolhead. Orca
derives the other nozzles' collision regions using their configured XY
offset from the reference nozzle. This is useful where the same physical
carriage must avoid an obstacle but its position changes when a
different offset nozzle prints at the same model coordinate.

<img width="1084" height="803" alt="Toolhead-relative exclusion volumes"
src="https://github.com/user-attachments/assets/e0790ee4-68b5-444f-90ac-22a5eba05eec"
/>

### Individual per extruder

Each physical extruder/nozzle has its own independent volume definition.
This supports machines whose valid region differs by tool and cannot be
derived from a simple nozzle offset.

<img width="1123" height="761" alt="Independent exclusion volumes for
three extruders"
src="https://github.com/user-attachments/assets/c6404ceb-9958-4df8-93ed-5ff2ac7dc658"
/>

Object validation resolves logical filament assignments to the physical
nozzle or nozzles that may print the object, including automatic Bambu
mapping. If an object may use several nozzles through painting,
feature-level assignments, modifiers, support or interface material, the
complete object is conservatively checked against every relevant
nozzle's volumes.

## Object validation and 3D preview

Object collision detection uses a cheap XY/Z broad phase followed by an
exact mesh-versus-prism test. The exact test:

- Avoids rejecting an object whose XY shadow overlaps a raised volume
while its real mesh remains clear.
- Detects normal surface crossings.
- Detects a volume completely enclosed inside a solid model.
- Respects object-instance and model-volume transforms.
- Separates the collision decision from optional preview-mesh
generation.

When a collision is found, Orca reports the relevant extruder where
possible and renders the intersecting model surface in red. The bed
preview shows a neutral grey footprint, a thin nozzle-colored ownership
border where appropriate, and a translucent 3D prism when a nearby
object makes the volume relevant. Raised volumes keep their ownership
outline on the bed rather than floating at their starting Z.

<img width="578" height="534" alt="Red model and exclusion-volume
intersection preview"
src="https://github.com/user-attachments/assets/d409f574-1790-48e5-b4a3-703273439954"
/>

Single-nozzle/shared geometry remains visually neutral; nozzle colors
are used when they convey distinct tool ownership.

The default automatic preview limits the translucent 3D geometry to
nearby object height to avoid obscuring the workspace. **View → Show all
collision volumes** displays the complete configured Z ranges, including
on an empty bed. Its default shortcut is **Ctrl+Shift+V**
(**Command+Shift+V** on macOS), and it can be changed in the shortcut
settings. Orca remembers this application-level display preference
independently of printer presets; it does not change collision checks or
slicing.

## Arrange and Fill Bed

Arrange and Fill Bed receive Z-aware, nozzle-aware obstacles, so an
object may occupy a footprint belonging only to another nozzle or pass
below a raised volume when its height permits it.

- Existing objects remain obstacles when Fill Bed creates new copies.
- Convex volume footprints are passed through accurately.
- Orca's current libnest2d path supports convex NFP obstacles only, so
non-convex volumes use a documented conservative bounding box until
convex decomposition is implemented.
- Orca's existing final alignment and normal unplaced-item behavior are
retained.

<img width="1097" height="846" alt="Fill Bed with multiple tools and
exclusion volumes"
src="https://github.com/user-attachments/assets/8c0ee5cf-624b-42a6-b57a-13c73400ac5c"
/>

## Brim and support generation

When collision volumes are enabled, object and support brims are clipped
against the relevant first-layer volume footprints before their final
extrusion paths are generated. Brim ownership is retained so touching
object and support brims cannot be merged and silently reassigned to a
nozzle whose volume they intersect. Established bed-edge and bed-area
brim clipping remains unchanged when collision volumes are not
configured.

<img width="1139" height="770" alt="Object and support brims clipped
around nozzle-specific volumes"
src="https://github.com/user-attachments/assets/2913ff31-53e4-4e43-8b27-1afba7e3bafb"
/>

Normal support and raft polygon categories are trimmed against the
relevant volumes over each support layer's actual vertical slab.
Support-material resolution accounts for explicit support/interface
tools, “current filament” behavior, alternating material layers,
automatic physical-nozzle mapping, support brims, and shared support
geometry.

TreeSupport3D receives active exclusion geometry during branch planning
so its existing avoidance machinery can steer branches around obstacles
rather than merely cutting finished paths.

## Final G-code collision validation

The final emitted G-code is checked as a safety backstop after slicing.
The checker tracks:

- The active physical nozzle and its XY offset.
- Absolute and relative XY/Z motion.
- Travel, extrusion and other parsed motion types.
- Tool selection and physical/nozzle mapping.
- Explicit motion in start, filament-change and tool-change G-code.
- Coordinate resets and common `G28` forms, including bare, spaced,
compact and parameterized axis selections.

Material keep-outs from `bed_exclude_area` are deliberately ignored by
the motion checker. Only explicit collision volumes constrain motion.

If Z is genuinely unknown, the check is conservative across all relevant
heights and the warning identifies that fact and includes the relevant
G-code line. The artificial first segment that the preview draws from
`(0,0)` is not treated as a real machine move.

## Travel rerouting

Generated travel moves are rerouted around active collision volumes when
a valid route exists.

Routing is:

- Aware of the travel's actual Z slab and planned lift/Z-hop.
- Resolved for the active physical nozzle.
- Constrained so any detour vertices added by Orca remain inside the
printable bed.
- Able to accept firmware-established start/end points on or beyond the
nominal bed edge.
- Revalidated before the replacement path is emitted.

The implementation covers ordinary generated travels, the first
generated move after start G-code, and moves following physical or
same-nozzle filament changes. Explicit movement commands in custom
start/tool-change G-code update the tracked position so the next
generated travel begins from the correct point without defeating Orca's
post-toolchange Z restoration.

Obstacle geometry is cached by extruder and active Z-region set, with
bounding-box rejection before expensive polygon work. Clear travels
therefore avoid repeatedly unioning and offsetting the same obstacles.

If no safe route can be found, Orca leaves the original move for the
final checker to report rather than emitting an assumed-safe detour.
Extrusion paths are validated but never rerouted.

<img width="1286" height="706" alt="Travel rerouting from start G-code
across multiple Z-aware volumes"
src="https://github.com/user-attachments/assets/a68cd98f-5576-4f78-af43-697e9f687a9b"
/>

And here is an example of independent nozzle travel rerouting:
<img width="2532" height="876" alt="image"
src="https://github.com/user-attachments/assets/28b0c26e-59d6-42b9-a64f-4c2205c4ea3f"
/>


## Testing and review status

Targeted Catch2 coverage now includes:

- Bed-area/volume parsing, validation, confirmed paste handling,
additive behavior and CLI options.
- Belt-surface projection of bed areas through both static and dynamic
region resolution, including the reported cube positions, with collision
volumes left unprojected.
- Shared, toolhead-relative and individual per-extruder resolution.
- Physical-nozzle and filament mapping.
- Exact object intersection, including fully enclosed prisms and
transformed instances.
- 3MF persistence.
- Arrange behavior for convex and non-convex obstacles.
- Brim bed-boundary and volume clipping regressions.
- Support and interface-material masks across support polygon
categories.
- G-code motion classification, coordinate tracking, homing forms and
tool selection.
- Safe travel rerouting, Z-aware activation, nozzle selection, off-bed
firmware endpoints and failure cases.

The reviewed `929beaee15` revision passed the CI checks, and review
testing confirmed that the unit tests and earlier arrange, tool-change Z
restoration, support, brim and brim-ownership regressions still pass.
Stock-output comparisons covered 12 printers × 3 jobs plus 17 project
files and produced G-code identical to `main` when the new feature was
not configured.

The belt projection correction and its regression coverage are included
in the latest update. Please use the checks below for the current head's
build and test status; earlier successful runs do not substitute for
validation of a new revision.

Review also compared CLI output against `main` across stock printers and
multi-filament projects. The compatibility regressions found during that
review—including stock Bambu cutter motion, preset dirty state,
unintended bed-area brim/support changes, tool-change Z restoration,
stale post-change origins, arrange rejection, router cost, locale
parsing and bed-edge brim clipping—have been addressed.

## Known limitations and follow-up work

The implementation deliberately favors conservative safety. A false
positive or some unused build volume is preferable to emitting a
movement that may collide with the machine. Collision warnings are not
an automatic repair or a guarantee of safe output.

- Skirts and draft shields are not regenerated or detoured around
collision volumes. The final checker can report an intersection, but
producing a valid closed loop around internal obstacles while remaining
inside the bed needs a dedicated solution.
- Extrusion paths are checked but not rerouted.
- Spiral Z-hop's circular XY sweep is generated after the primary travel
route has been planned. That sweep is not currently rerouted; the final
G-code checker can report a collision, but does not repair it.
- Orca cannot infer movement hidden inside an opaque firmware macro. A
deterministic macro endpoint should be exposed with explicit `G90`/`G91`
and `G0`/`G1` motion in Orca's custom G-code so the following travel can
be routed from a known position. Movements inside custom G-code are
checked, but only the generated travel after them is rerouted.
- Negative model parts are not applied to the raw object-intersection
mesh, so geometry removed only by a negative part can produce a
conservative false positive.
- Multi-nozzle object validation applies every relevant nozzle's volume
to the complete object rather than only its visibly painted surface.
- Support shared by several instances uses a conservative union of
relevant plate-space exclusions.
- Support avoidance trims or steers generated geometry but does not
perform structural support re-planning. Support above a raised volume
may resume over a void; native tree-support paths not using
TreeSupport3D are not yet volume-aware.
- Raised-only collision volumes are not yet fully represented in
prime/wipe-tower placement validation; the final G-code checker remains
the safety backstop.
- Existing cross-object support-to-support overlap behavior is outside
this PR.
- “No tool selected” carriage-only exclusions are not represented by
Orca's current backend and remain a possible future extension.

## Origin

This work began with the [Muon3D
M1](https://www.youtube.com/watch?v=jBatFQpTM6g), whose notched glass
bed leaves usable print volume above a low obstruction. Upstreaming the
capability lets other printers describe low clips, raised docks,
toolchanger hardware and per-tool clearance limits without requiring a
permanent fork.

Thank you to everyone who tested the implementation, reviewed the
architecture, identified regressions and helped improve the test
coverage—especially the multi-tool and macOS testers. Further
real-hardware feedback remains welcome, but the current implementation
and compatibility behavior are ready to merge.

Harry Loud  
Muon3D
This commit is contained in:
SoftFever authored and GitHub committed 2026-10-22 22:04:40 +08:00
commit f92f75e0fa
69 files changed
+6585 -275

No files matched your search

+268 -17
View File
@@ -1,4 +1,5 @@
#include "ArcFitter.hpp"
#include <tuple>
#include "BoundingBox.hpp"
#include "Circle.hpp"
#include "Config.hpp"
@@ -152,6 +153,53 @@ namespace fs = boost::filesystem;
namespace Slic3r {
namespace {
// Follow XY commands in a generated G-code block. This deliberately handles
// only standard motion/modal commands: an opaque macro that moves the head is
// already outside the position guarantees made by GCodeWriter.
std::optional<Vec2d> emitted_xy_after_gcode(const std::string &gcode, const Vec2d &initial_xy)
{
Vec2d position = initial_xy;
bool absolute = true;
bool coordinate_frame_known = true;
GCodeReader reader;
reader.parse_buffer(gcode, [&position, &absolute, &coordinate_frame_known](GCodeReader &, const GCodeReader::GCodeLine &line) {
if (line.cmd_is("G90")) {
absolute = true;
return;
}
if (line.cmd_is("G91")) {
absolute = false;
return;
}
const bool is_motion = line.cmd_is("G0") || line.cmd_is("G1") || line.cmd_is("G2") || line.cmd_is("G3");
if (is_motion) {
if (line.has_x())
position.x() = absolute ? line.x() : position.x() + line.x();
if (line.has_y())
position.y() = absolute ? line.y() : position.y() + line.y();
return;
}
// G92 changes the coordinate system without moving the machine, and
// G28 moves to a firmware-defined position. Do not invent a position
// if either command affects XY.
if (line.cmd_is("G92")) {
coordinate_frame_known = coordinate_frame_known && !line.has_x() && !line.has_y();
} else if (line.cmd_is("G28")) {
const bool homes_all = !line.has_x() && !line.has_y() && !line.has_z();
coordinate_frame_known = coordinate_frame_known && !homes_all && !line.has_x() && !line.has_y();
}
});
return coordinate_frame_known ? std::optional<Vec2d>(position) : std::nullopt;
}
} // namespace
//! macro used to mark string used at localization,
//! return same string
#define L(s) (s)
@@ -1056,6 +1104,9 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
if (new_filament_id != -1 && new_filament_id != tcr.new_tool)
throw Slic3r::InvalidArgument("Error: WipeTowerIntegration::append_tcr was asked to do a toolchange it didn't expect.");
const std::optional<GCode::ToolchangePositionState> position_before_toolchange =
gcodegen.capture_toolchange_position();
int new_extruder_id = get_extruder_index(*m_print_config, new_filament_id);
// Logical nozzle grouping for this print (null on paths that don't populate it).
@@ -1437,6 +1488,13 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
// We have informed the m_writer about the current extruder_id, we can ignore the generated G-code.
}
// The change G-code may move the carriage even when the incoming
// filament uses the same physical nozzle (the common AMS case).
// Synchronize before planning the tower-entry travel so exclusion
// avoidance starts from the emitted position, not the stale one.
if (position_before_toolchange)
gcodegen.synchronize_toolchange_position(*position_before_toolchange, toolchange_gcode_str);
if (need_travel_after_change_filament_gcode) {
// move to start_pos for wiping after toolchange
if (!is_used_travel_avoid_perimeter) {
@@ -1585,6 +1643,8 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
// Let the planner know we are traveling between objects.
gcodegen.m_avoid_crossing_perimeters.use_external_mp_once();
if (position_before_toolchange)
gcodegen.synchronize_toolchange_position(*position_before_toolchange, gcode);
return gcode;
}
@@ -1596,6 +1656,9 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
if (new_extruder_id != -1 && new_extruder_id != tcr.new_tool)
throw Slic3r::InvalidArgument("Error: WipeTowerIntegration::append_tcr was asked to do a toolchange it didn't expect.");
const std::optional<GCode::ToolchangePositionState> position_before_toolchange =
gcodegen.capture_toolchange_position();
std::string gcode;
// Toolchangeresult.gcode assumes the wipe tower corner is at the origin (except for priming lines)
@@ -1880,6 +1943,8 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
// Let the planner know we are traveling between objects.
gcodegen.m_avoid_crossing_perimeters.use_external_mp_once();
if (position_before_toolchange)
gcodegen.synchronize_toolchange_position(*position_before_toolchange, gcode);
return gcode;
}
@@ -2757,6 +2822,8 @@ void GCode::do_export(Print* print, const char* path, GCodeProcessorResult* resu
// BBS
m_curr_print = print;
m_skirt_group_done.clear();
m_pending_start_gcode_position.reset();
m_exclusion_volume_travel_avoidance.init(print->config(), print->get_plate_origin());
GCodeWriter::full_gcode_comment = print->config().gcode_comments;
CNumericLocalesSetter locales_setter;
@@ -2938,6 +3005,23 @@ void GCode::do_export(Print* print, const char* path, GCodeProcessorResult* resu
m_processor.result().nozzle_group_result = m_print->get_layered_nozzle_group_result();
m_processor.finalize(true);
if (m_processor.get_result().exclusion_volume_path_conflict) {
const int extruder_id = m_processor.get_result().exclusion_volume_conflict_extruder_id;
std::string warning = extruder_id >= 0 ?
Slic3r::format(
_(L("A G-code move intersects a collision volume for extruder %1%. This may cause a printer collision.")),
std::to_string(extruder_id + 1)) :
_(L("A G-code move intersects a collision volume. This may cause a printer collision."));
if (m_processor.get_result().exclusion_volume_conflict_used_unknown_z) {
warning += "\n" + Slic3r::format(
_(L("The intersecting move is at G-code line %1%. Its Z position is unknown after homing, so Orca checked it against every height.")),
std::to_string(m_processor.get_result().exclusion_volume_conflict_gcode_id));
}
print->active_step_add_warning(
PrintStateBase::WarningLevel::CRITICAL,
warning,
PrintStateBase::SlicingExclusionVolumeToolpath);
}
// DoExport::update_print_estimated_times_stats(m_processor, print->m_print_statistics);
DoExport::update_print_estimated_stats(m_processor, m_writer.extruders(), print->m_print_statistics, print->config());
// Printed-mass safety check. Flushed filament leaves the bed, so subtract it
@@ -3020,6 +3104,7 @@ namespace DoExport {
processor.initialize_from_context(nozzle_group_result);
processor.initialize_result_moves();
processor.apply_config(config);
processor.configure_exclusion_volume_path_check(config);
processor.enable_stealth_time_estimator(silent_time_estimator_enabled);
}
@@ -4449,6 +4534,17 @@ void GCode::_do_export(Print& print, GCodeOutputStream &file, ThumbnailsGenerato
}
}
// Direct output writes are parsed synchronously. Preserve the startup
// endpoint before the generator establishes its first model-space point,
// so that first travel can be planned from the position the G-code actually
// left the machine at rather than the default last_pos value.
GCodeProcessor::PositionState startup_position = m_processor.get_current_position();
const Vec2f plate_offset = m_writer.get_xy_offset();
startup_position.position.x() += plate_offset.x();
startup_position.position.y() += plate_offset.y();
m_pending_start_gcode_position = !m_last_pos_defined && startup_position.has_known_xy() ?
std::optional<GCodeProcessor::PositionState>(startup_position) : std::nullopt;
this->m_objsWithBrim.clear();
m_brim_done = false;
@@ -5886,8 +5982,13 @@ std::string GCode::generate_object_skirt_group(const Print &print,
object_skirt_tools, layer, extruder_id, m_skirt_group_done[group_idx]);
}
std::string GCode::generate_object_brim(const Print &print, const PrintObject &object, size_t instance_id, bool first_layer,
const Layer *object_layer)
std::string GCode::generate_object_brim(
const Print &print,
const PrintObject &object,
const size_t instance_id,
const bool first_layer,
const unsigned int extruder_id,
const Layer *object_layer)
{
// Belt printers lay the brim onto the tilted belt over many layers, so there is
// nothing special about the first one. The bands that coincide with an object
@@ -5926,8 +6027,17 @@ std::string GCode::generate_object_brim(const Print &print, const PrintObject &o
if (!first_layer)
return {};
auto emit_brim = [this](const ExtrusionEntityCollection& brim, const std::vector<ObjectInstanceID>& instances) {
const bool wait_for_owner_filament = has_bed_exclude_volumes(m_config) &&
active_bed_exclude_volume_mode(m_config) != BedExcludeVolumeMode::Shared;
auto emit_brim = [this, extruder_id, wait_for_owner_filament](const ExtrusionEntityCollection& brim,
const std::vector<ObjectInstanceID>& instances,
const unsigned int brim_filament_id) {
std::string gcode;
// Combined brims have an explicit owner filament. Waiting for that
// filament is only required when each nozzle has different obstacles.
// Otherwise retain Orca's established first-visit emission order.
if (wait_for_owner_filament && brim_filament_id != extruder_id)
return gcode;
const bool already_emitted = std::none_of(instances.begin(), instances.end(), [this](const ObjectInstanceID& instance) {
return m_objsWithBrim.find(instance) != m_objsWithBrim.end();
});
@@ -5952,7 +6062,7 @@ std::string GCode::generate_object_brim(const Print &print, const PrintObject &o
std::string gcode;
for (const Print::SkirtBrimGroup::Brim& brim : print.skirt_brim_groups()[group_idx].brims)
if (std::find(brim.instances.begin(), brim.instances.end(), object_instance_id) != brim.instances.end())
gcode += emit_brim(brim.brim, brim.instances);
gcode += emit_brim(brim.brim, brim.instances, brim.filament_id);
return gcode;
}
@@ -7470,10 +7580,10 @@ LayerResult GCode::process_layer(
// sweep below never re-emits it.
if (extruder_id == (unsigned int)(vobj.belt_brim_filament() - 1) &&
belt_brim_emitted.insert({ instance_to_print.layer_id, instance_to_print.instance_id }).second)
gcode += generate_object_brim(print, vobj, instance_to_print.instance_id, first_layer,
gcode += generate_object_brim(print, vobj, instance_to_print.instance_id, first_layer, extruder_id,
layer_to_print.object_layer);
} else {
gcode += generate_object_brim(print, vobj, instance_to_print.instance_id, first_layer,
gcode += generate_object_brim(print, vobj, instance_to_print.instance_id, first_layer, extruder_id,
layer_to_print.object_layer);
}
}
@@ -8012,7 +8122,7 @@ LayerResult GCode::process_layer(
continue;
if (m_writer.filament() == nullptr || m_writer.filament()->id() != brim0)
gcode += this->set_extruder(brim0, print_z);
gcode += generate_object_brim(print, *obj, instance_id, first_layer, ltp.object_layer);
gcode += generate_object_brim(print, *obj, instance_id, first_layer, brim0, ltp.object_layer);
}
}
this->set_origin(saved_origin);
@@ -8251,6 +8361,41 @@ void GCode::set_extruders(const std::vector<unsigned int> &extruder_ids)
}
}
std::optional<GCode::ToolchangePositionState> GCode::capture_toolchange_position()
{
if (m_exclusion_volume_travel_avoidance.empty() || !m_last_pos_defined || m_writer.filament() == nullptr)
return std::nullopt;
const Vec2d plate_offset = m_writer.get_xy_offset().cast<double>();
return ToolchangePositionState{
this->point_to_gcode(m_last_pos.to_point()) - plate_offset
};
}
void GCode::synchronize_toolchange_position(const ToolchangePositionState &before, const std::string &emitted_gcode)
{
if (m_writer.filament() == nullptr)
return;
const std::optional<Vec2d> emitted_xy = emitted_xy_after_gcode(emitted_gcode, before.emitted_xy);
if (!emitted_xy)
return;
// GCodeWriter stores coordinates before applying the per-plate output
// offset. Convert the parsed file coordinates back into that space, then
// into model space using the newly active nozzle offset.
const Vec2d writer_xy = *emitted_xy + m_writer.get_xy_offset().cast<double>();
Vec3d writer_position = m_writer.get_position();
writer_position.head<2>() = writer_xy;
m_writer.set_position(writer_position);
// Updating the known XY origin must not cancel Orca's deliberate
// post-toolchange Z restore. set_last_pos() normally marks the entire
// position as defined, so preserve the caller's state across the XY sync.
const bool last_pos_defined = m_last_pos_defined;
this->set_last_pos(this->gcode_to_point(writer_xy));
m_last_pos_defined = last_pos_defined;
}
void GCode::set_origin(const Vec2d &pointf)
{
// if origin increases (goes towards right), last_pos decreases because it goes towards left
@@ -10130,10 +10275,17 @@ std::string GCode::_encode_label_ids_to_base64(std::vector<size_t> ids)
// This method accepts &point in print coordinates.
std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string comment, double z/* = DBL_MAX*/)
{
const std::optional<GCodeProcessor::PositionState> start_gcode_position =
!m_exclusion_volume_travel_avoidance.empty() && !m_last_pos_defined &&
!m_writer.is_current_position_clear() && m_pending_start_gcode_position.has_value() ?
m_pending_start_gcode_position : std::nullopt;
/* Define the travel move as a line between current position and the taget point.
This is expressed in print coordinates, so it will need to be translated by
this->origin in order to get G-code coordinates. */
Polyline travel { this->last_pos(), point };
const Point travel_start = start_gcode_position ?
this->gcode_to_point(to_2d(start_gcode_position->position)) : this->last_pos();
Polyline travel { travel_start, point };
// check whether a straight travel move would need retraction
LiftType lift_type = LiftType::SpiralLift;
@@ -10143,6 +10295,66 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string
// Save state of use_external_mp_once for the case that will be needed to call twice m_avoid_crossing_perimeters.travel_to.
const bool used_external_mp_once = m_avoid_crossing_perimeters.used_external_mp_once();
std::string gcode;
bool exclusion_volume_travel_rerouted = false;
const auto active_extruder_id = [this]() {
if (m_writer.filament() == nullptr)
return -1;
const size_t id = m_writer.filament()->extruder_id();
return id < m_config.nozzle_diameter.size() ? int(id) : -1;
};
const auto to_gcode_point = [this](const Point &local_point) {
const Vec2d point = this->point_to_gcode(local_point);
return Point(scale_(point.x()), scale_(point.y()));
};
const auto to_local_point = [this](const Point &gcode_point) {
return this->gcode_to_point(unscaled(gcode_point));
};
const auto to_gcode_polyline = [&to_gcode_point](const Polyline &local_path) {
Polyline result;
result.points.reserve(local_path.points.size());
for (const Point &local_point : local_path.points)
result.append(to_gcode_point(local_point));
return result;
};
const auto to_local_polyline = [&to_local_point](const Polyline &gcode_path) {
Polyline result;
result.points.reserve(gcode_path.points.size());
for (const Point &gcode_point : gcode_path.points)
result.append(to_local_point(gcode_point));
return result;
};
const auto nominal_writer_z = [this]() {
return m_writer.get_position().z() - m_writer.get_zhop();
};
const auto route_around_exclusion_volumes = [&](
Polyline &path,
const std::optional<double> &start_z_override,
const bool include_planned_lift = false) {
if (m_exclusion_volume_travel_avoidance.empty() || path.size() < 2)
return false;
const double target_z = z == DBL_MAX ? m_nominal_z : z;
double route_start_z = start_z_override.value_or(nominal_writer_z());
double route_end_z = target_z;
if (include_planned_lift) {
const Vec2d destination_xy = this->point_to_gcode(path.back());
std::tie(route_start_z, route_end_z) = m_writer.planned_travel_z(
Vec3d(destination_xy.x(), destination_xy.y(), target_z),
m_need_change_layer_lift_z);
}
const ExclusionVolumeTravelAvoidance::Result result =
m_exclusion_volume_travel_avoidance.route(
to_gcode_polyline(path),
route_start_z,
route_end_z,
active_extruder_id());
if (!result.rerouted())
return false;
path = to_local_polyline(result.path);
return true;
};
// Orca: we don't need to optimize the Klipper as only set once
double jerk_to_set = 0.0;
@@ -10208,6 +10420,14 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string
//if (needs_retraction && m_layer_index > 1) exit(0);
}
const std::optional<double> start_gcode_z =
start_gcode_position && start_gcode_position->has_known_z() ?
std::optional<double>(start_gcode_position->position.z()) : std::nullopt;
if (route_around_exclusion_volumes(travel, start_gcode_z)) {
exclusion_volume_travel_rerouted = true;
needs_retraction = this->needs_retraction(travel, role, lift_type);
}
// Re-allow reduce_crossing_wall for the next travel moves
m_avoid_crossing_perimeters.reset_once_modifiers();
@@ -10223,16 +10443,22 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string
// When "Wipe while retracting" is enabled, then extruder moves to another position, and travel from this position can cross perimeters.
// Because of it, it is necessary to call avoid crossing perimeters again with new starting point after calling retraction()
// FIXME Lukas H.: Try to predict if this second calling of avoid crossing perimeters will be needed or not. It could save computations.
if (last_post_before_retract != this->last_pos() && m_config.reduce_crossing_wall
&& m_layer != nullptr) { // A brim apron layer has no Layer to avoid crossing
// If in the previous call of m_avoid_crossing_perimeters.travel_to was use_external_mp_once set to true restore this value for next call.
if (used_external_mp_once)
m_avoid_crossing_perimeters.use_external_mp_once();
travel = m_avoid_crossing_perimeters.travel_to(*this, point);
// If state of use_external_mp_once was changed reset it to right value.
if (used_external_mp_once)
m_avoid_crossing_perimeters.reset_once_modifiers();
if (last_post_before_retract != this->last_pos()) {
travel = Polyline { this->last_pos(), point };
if (m_config.reduce_crossing_wall && m_layer != nullptr) { // Belt brim apron layers have no Layer.
// If in the previous call of m_avoid_crossing_perimeters.travel_to was use_external_mp_once set to true restore this value for next call.
if (used_external_mp_once)
m_avoid_crossing_perimeters.use_external_mp_once();
travel = m_avoid_crossing_perimeters.travel_to(*this, point);
// If state of use_external_mp_once was changed reset it to right value.
if (used_external_mp_once)
m_avoid_crossing_perimeters.reset_once_modifiers();
}
}
exclusion_volume_travel_rerouted =
route_around_exclusion_volumes(travel, std::nullopt, true) ||
(last_post_before_retract == this->last_pos() && exclusion_volume_travel_rerouted);
} else {
// Reset the wipe path when traveling, so one would not wipe along an old path.
m_wipe.reset_path();
@@ -10264,6 +10490,24 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string
Vec3d dest3d(dest2d(0), dest2d(1), z == DBL_MAX ? m_nominal_z : z);
gcode += m_writer.travel_to_xyz(dest3d, comment, m_need_change_layer_lift_z);
m_need_change_layer_lift_z = false;
} else if (exclusion_volume_travel_rerouted && z != DBL_MAX) {
// Preserve the original sloped-Z move over the longer detour.
// The router activates every volume touched by the complete Z
// range, so this interpolation remains conservative.
const double start_z = m_writer.get_position().z();
const double total_length = std::max(travel.length(), 1.0);
double traveled = 0.0;
for (size_t i = 1; i < travel.size(); ++i) {
traveled += (travel.points[i] - travel.points[i - 1]).cast<double>().norm();
const Vec2d dest2d = this->point_to_gcode(travel.points[i]);
const Vec3d dest3d(
dest2d.x(),
dest2d.y(),
start_z + (z - start_z) * std::min(1.0, traveled / total_length));
gcode += m_writer.travel_to_xyz(dest3d, comment, i == 1 && m_need_change_layer_lift_z);
if (i == 1)
m_need_change_layer_lift_z = false;
}
} else {
// Extra movements emitted by avoid_crossing_perimeters, lift the z to normal height at the beginning, then apply the z
// ratio at the last point
@@ -10590,6 +10834,9 @@ std::string GCode::set_extruder(unsigned int new_filament_id, double print_z, bo
if (!m_writer.need_toolchange(new_filament_id))
return "";
const std::optional<ToolchangePositionState> position_before_toolchange =
this->capture_toolchange_position();
// if we are running a single-extruder setup, just set the extruder and return nothing
if (!m_writer.multiple_extruders) {
this->placeholder_parser().set("current_extruder", new_filament_id);
@@ -10644,6 +10891,8 @@ std::string GCode::set_extruder(unsigned int new_filament_id, double print_z, bo
gcode += toolchange_command;
if (Extruder *fil = m_writer.filament())
fil->set_config_index((int)get_filament_config_index((int)fil->id()));
if (position_before_toolchange)
this->synchronize_toolchange_position(*position_before_toolchange, gcode);
return gcode;
}
@@ -11060,6 +11309,8 @@ std::string GCode::set_extruder(unsigned int new_filament_id, double print_z, bo
imex_pem_tool_for((int) new_filament_id, m_imex_parallel_mode, m_config.physical_extruder_map));
//Orca: tool changer or IDEX's firmware may change Z position, so we set it to unknown/undefined
m_last_pos_defined = false;
if (position_before_toolchange)
this->synchronize_toolchange_position(*position_before_toolchange, gcode);
return gcode;
}