Merge remote-tracking branch 'remotes/local_63/dev_27_63' into superslicer_2.7.63

This commit is contained in:
supermerill 2026-05-20 11:07:20 +02:00
commit fa6c255c9b
168 changed files with 13226 additions and 5197 deletions

View file

@ -6,7 +6,8 @@ on:
- Nigthly
- nightly_dev
- nightly_master
- nightly_2.7.62
- nightly_macos_intel
- nightly_2.7.63
- debug_macos
jobs:
@ -46,7 +47,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: macos_intel_2.7
key: macos_intel_2.7.63
path: deps/build/destdir
- if: steps.cache-action.outputs.cache-hit != 'true'
name: build deps if new cache
@ -87,7 +88,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: macos_intel_2.7
key: macos_intel_2.7.63
path: deps/build/destdir
- name: build slicer
run: ./BuildMacOS.sh -siv

View file

@ -6,7 +6,8 @@ on:
- Nigthly
- nightly_dev
- nightly_master
- nightly_2.7.62
- nightly_macos
- nightly_2.7.63
- debug_macos
jobs:
@ -44,7 +45,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: macos_arm_2.7
key: macos_arm_2.7.63
path: deps/build/destdir
- if: steps.cache-action.outputs.cache-hit != 'true'
name: build deps if new cache
@ -68,7 +69,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: macos_arm_2.7
key: macos_arm_2.7.63
path: deps/build/destdir
- name: build slicer
run: ./BuildMacOS.sh -asiv

View file

@ -40,7 +40,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: macos_arm_debug_2.7
key: macos_arm_debug_2.7.63
path: deps/build/destdir
- if: steps.cache-action.outputs.cache-hit != 'true'
name: build deps if new cache
@ -64,7 +64,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: macos_arm_debug_2.7
key: macos_arm_debug_2.7.63
path: deps/build/destdir
- name: build slicer
run: ./BuildMacOS.sh -basiv

View file

@ -40,7 +40,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: macos_arm_2.7
key: macos_arm_2.7.63
path: deps/build/destdir
- if: steps.cache-action.outputs.cache-hit != 'true'
name: build deps if new cache
@ -64,7 +64,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: macos_arm_2.7
key: macos_arm_2.7.63
path: deps/build/destdir
- name: build slicer
run: ./BuildMacOS.sh -asi

View file

@ -42,7 +42,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: macos_intel_debug_2.7
key: macos_intel_debug_2.7.63
path: deps/build/destdir
- if: steps.cache-action.outputs.cache-hit != 'true'
name: build deps if new cache
@ -83,7 +83,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: macos_intel_debug_2.7
key: macos_intel_debug_2.7.63
path: deps/build/destdir
- name: build slicer
run: ./BuildMacOS.sh -bsiv

View file

@ -43,7 +43,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: macos_intel_2.7
key: macos_intel_2.7.63
path: deps/build/destdir
- if: steps.cache-action.outputs.cache-hit != 'true'
name: build deps if new cache
@ -84,7 +84,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: macos_intel_2.7
key: macos_intel_2.7.63
path: deps/build/destdir
- name: build slicer
run: ./BuildMacOS.sh -si

View file

@ -32,7 +32,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: ubu_gtk2_2.7
key: ubu_gtk2_2.7.63
path: deps/build/destdir
- if: steps.cache-action.outputs.cache-hit != 'true'
name: build deps if new cache

View file

@ -30,7 +30,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: ubu_gtk2_debug_2.7
key: ubu_gtk2_debug_2.7.63
path: deps/build/destdir
- if: steps.cache-action.outputs.cache-hit != 'true'
name: build deps if new cache

View file

@ -32,7 +32,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: ubu_gtk2_2.7
key: ubu_gtk2_2.7.63
path: deps/build/destdir
- if: steps.cache-action.outputs.cache-hit != 'true'
name: build deps if new cache

View file

@ -6,7 +6,8 @@ on:
- Nigthly
- nightly_dev
- nightly_master
- nightly_2.7.62
- nightly_ubuntu
- nightly_2.7.63
- debug_ubuntu
jobs:
@ -32,7 +33,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: ubu_gtk3_2.7
key: ubu_gtk3_2.7.63
path: deps/build/destdir
- if: steps.cache-action.outputs.cache-hit != 'true'
name: build deps if new cache

View file

@ -30,7 +30,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: ubu_gtk3_debug_2.7
key: ubu_gtk3_debug_2.7.63
path: deps/build/destdir
- if: steps.cache-action.outputs.cache-hit != 'true'
name: build deps if new cache

View file

@ -32,7 +32,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: ubu_gtk3_2.7
key: ubu_gtk3_2.7.63
path: deps/build/destdir
- if: steps.cache-action.outputs.cache-hit != 'true'
name: build deps if new cache

View file

@ -7,7 +7,9 @@ on:
- nightly_dev
- nightly_2.7.62
- nightly_master
- nightly_2.7.63
- debug_win
- nightly_win
jobs:
build_dep:
@ -22,7 +24,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: win_2.7
key: win_2.7.63
path: deps/build/destdir
- if: steps.cache-action.outputs.cache-hit != 'true'
name: build deps if new cache
@ -50,7 +52,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: win_2.7
key: win_2.7.63
path: deps/build/destdir
- run: dir deps
- run: dir deps/build

View file

@ -13,13 +13,17 @@ jobs:
steps:
- uses: actions/checkout@v3
- uses: ilammy/msvc-dev-cmd@v1
- uses: shogo82148/actions-setup-perl@v1
with:
perl-version: "5.42"
distribution: strawberry
- name: mkdir in deps
run: mkdir deps/build
- name: dep cache
id: cache-action
uses: actions/cache@v3
with:
key: win_debug_2.7
key: win_debug_2.7.63
path: deps/build/destdir
- if: steps.cache-action.outputs.cache-hit != 'true'
name: build deps if new cache
@ -38,12 +42,15 @@ jobs:
- name: update submodule profiles
working-directory: ./resources/profiles
run: git submodule update --init
# - run: mkdir deps/destdir
- uses: shogo82148/actions-setup-perl@v1
with:
perl-version: "5.42"
distribution: strawberry
- name: dep cache
id: cache-action
uses: actions/cache@v3
with:
key: win_debug_2.7
key: win_debug_2.7.63
path: deps/build/destdir
- run: dir deps
- run: dir deps/build

View file

@ -13,13 +13,17 @@ jobs:
steps:
- uses: actions/checkout@v3
- uses: ilammy/msvc-dev-cmd@v1
- uses: shogo82148/actions-setup-perl@v1
with:
perl-version: "5.42"
distribution: strawberry
- name: mkdir in deps
run: mkdir deps/build
- name: dep cache
id: cache-action
uses: actions/cache@v3
with:
key: win_2.7
key: win_2.7.63
path: deps/build/destdir
- if: steps.cache-action.outputs.cache-hit != 'true'
name: build deps if new cache
@ -38,6 +42,10 @@ jobs:
- name: update submodule profiles
working-directory: ./resources/profiles
run: git submodule update --init
- uses: shogo82148/actions-setup-perl@v1
with:
perl-version: "5.42"
distribution: strawberry
- name: change date in version
shell: powershell
run: |
@ -47,7 +55,7 @@ jobs:
id: cache-action
uses: actions/cache@v3
with:
key: win_2.7
key: win_2.7.63
path: deps/build/destdir
- run: dir deps
- run: dir deps/build

View file

@ -248,6 +248,7 @@ then
fi
echo -e " \n[3/8] Configuring dependencies ... \n"
BUILD_ARGS=""
#BUILD_ARGS="-DOPENSSL_ARCH=\"darwin64-arm64-cc\""
if [[ -n "$BUILD_ARCH" ]]
then
BUILD_ARGS="${BUILD_ARGS} -DCMAKE_OSX_ARCHITECTURES:STRING=${BUILD_ARCH}"
@ -323,6 +324,8 @@ then
make dep_MPFR -j$NCORES
echo -e "[4/8] Building dep_Catch2 ...\n"
make dep_Catch2 -j$NCORES
echo -e "[4/8] Building dep_OpenSSL ...\n"
make dep_OpenSSL -j$NCORES
# fi
# make deps
@ -348,6 +351,18 @@ then
echo -e "\n ... done\n"
fi
echo "> ls deps/build/destdir/usr/local"
ls -al deps/build/destdir/usr/local
echo "> ls deps/build/destdir/usr/local/lib"
ls -al deps/build/destdir/usr/local/lib
echo "> ls deps/build/destdir/usr/local/lib/cmake/openssl"
ls -al deps/build/destdir/usr/local/lib/cmake/openssl
echo "> cat deps/build/destdir/usr/local/lib/cmake/openssl/openssl-targets.cmake"
cat deps/build/destdir/usr/local/lib/cmake/openssl/openssl-targets.cmake
echo "> cat deps/build/destdir/usr/local/lib/cmake/openssl/openssl-targets.cmake"
cat deps/build/destdir/usr/local/lib/cmake/openssl/openssl-targets-release.cmake
if [[ -n "$BUILD_SLIC3R" ]]
then
echo -e "[4/8] Configuring Slicer ...\n"
@ -385,7 +400,7 @@ then
else
BUILD_ARGS="${BUILD_ARGS} -DCMAKE_BUILD_TESTS=0"
fi
# cmake
pushd build > /dev/null
if [[ "$BUILD_ARCH" == "$BUILD_ARCH_x86" ]]

View file

@ -237,7 +237,8 @@ if (APPLE)
if (CMAKE_OSX_DEPLOYMENT_TARGET)
message("OS X Deployment Target: ${CMAKE_OSX_DEPLOYMENT_TARGET}")
else ()
message("OS X Deployment Target: (default)")
set(CMAKE_OSX_DEPLOYMENT_TARGET "11.3" CACHE STRING "Minimum OS X deployment version" FORCE)
message("OS X Deployment Target: default to ${CMAKE_OSX_DEPLOYMENT_TARGET}")
endif ()
endif ()

View file

@ -204,7 +204,8 @@ counter = 2;
while os.path.isdir(release_path) and os.listdir(release_path):
release_path = f"{base_path}_{counter}";
counter += 1;
os.mkdir(release_path);
if not os.path.isdir(release_path):
os.mkdir(release_path);
#urllib.urlretrieve ("https://api.github.com/repos/"+repo+"/actions/artifacts", release_path+"artifacts.json");
need_more = True

View file

@ -5,6 +5,7 @@ const vec3 back_color_light = vec3(0.365, 0.365, 0.365);
uniform sampler2D texture;
uniform bool transparent_background;
uniform bool solid_color;
uniform bool svg_source;
varying vec2 tex_coord;
@ -18,7 +19,7 @@ vec4 svg_color()
vec3 back_color = vec3(mix(back_color_light, back_color_dark, smoothstep(0.0, 0.5, length(abs(tex_coord.xy) - vec2(0.5)))));
// blends foreground with background
return vec4(mix(back_color, fore_color.rgb, fore_color.a), transparent_background ? fore_color.a : 1.0);
return vec4(mix(back_color, fore_color.rgb, fore_color.a), (transparent_background || !solid_color) ? fore_color.a : 1.0);
}
vec4 non_svg_color()

View file

@ -5,6 +5,7 @@ const vec3 back_color_light = vec3(0.365, 0.365, 0.365);
uniform sampler2D in_texture;
uniform bool transparent_background;
uniform bool solid_color;
uniform bool svg_source;
in vec2 tex_coord;
@ -20,7 +21,7 @@ vec4 svg_color()
vec3 back_color = vec3(mix(back_color_light, back_color_dark, smoothstep(0.0, 0.5, length(abs(tex_coord.xy) - vec2(0.5)))));
// blends foreground with background
return vec4(mix(back_color, fore_color.rgb, fore_color.a), transparent_background ? fore_color.a : 1.0);
return vec4(mix(back_color, fore_color.rgb, fore_color.a), (transparent_background || !solid_color) ? fore_color.a : 1.0);
}
vec4 non_svg_color()

View file

@ -7,6 +7,7 @@ const vec3 back_color_light = vec3(0.365, 0.365, 0.365);
uniform sampler2D texture;
uniform bool transparent_background;
uniform bool solid_color;
uniform bool svg_source;
varying vec2 tex_coord;
@ -20,7 +21,7 @@ vec4 svg_color()
vec3 back_color = vec3(mix(back_color_light, back_color_dark, smoothstep(0.0, 0.5, length(abs(tex_coord.xy) - vec2(0.5)))));
// blends foreground with background
return vec4(mix(back_color, fore_color.rgb, fore_color.a), transparent_background ? fore_color.a : 1.0);
return vec4(mix(back_color, fore_color.rgb, fore_color.a), (transparent_background || !solid_color) ? fore_color.a : 1.0);
}
vec4 non_svg_color()

View file

@ -23,6 +23,8 @@ Gui_color = 296acc
Gui_color_light = 3d83ed
splash_screen_editor = vector_finesse.jpg
splash_screen_gcodeviewer = prusa-gcodepreview.jpg
Gui_skybox_dark = 7A7A7A
Gui_skybox_light = C0C0C0
Gui_plater = 3C3C3C
Gui_plater_grid = D0D0D0
Tag_Simple = 7DF028

View file

@ -4,9 +4,12 @@ group:Name and Size
setting:idx:tool_name
setting:idx:nozzle_diameter
update_nozzle_diameter
group:Layer height limits
setting:idx:min_layer_height
setting:idx:max_layer_height
group:Limits
line:Layer height limits
setting:idx:min_layer_height
setting:idx:max_layer_height
end_line
setting:idx:extruder_clearance
group:Offsets (for multi-extruder printers)
setting:idx:extruder_offset
setting:idx:extruder_temperature_offset
@ -59,8 +62,12 @@ group:General wipe
setting:idx:label$_:sidetext_width$5:seam_gap
setting:idx:label$for external perimeters:sidetext_width$5:seam_gap_external
end_line
group:others
setting:idx:temperature_heat_speed
group:Retraction when tool is disabled (advanced settings for multi-extruder setups)
setting:label$Minimum retraction:idx:retract_length_toolchange
setting:label$Extra unretraction:idx:retract_restart_extra_toolchange
setting:idx:retract_restart_wipe_toolchange
setting:idx:retract_restart_toolchange_on_perimeter
group:Preview
reset_to_filament_color

View file

@ -340,6 +340,7 @@ group:Options for support material and raft
setting:sidetext_width$7:support_material_xy_spacing
setting:dont_support_bridges
setting:support_material_synchronize_layers
setting:support_max_slope
group:Options for support material interface
setting:support_material_interface_layer_height
line:Pattern
@ -356,7 +357,7 @@ group:Options for support material interface
setting:label$Bottom:support_material_bottom_interface_layers
end_line
setting:support_material_interface_contact_loops
setting:support_material_bottom_interface_expansion
group:Organic supports
line:Tree Branch angle
setting:label$Maximum:support_tree_angle
@ -576,6 +577,7 @@ group:Wipe tower
setting:label$Spacing between lines:wipe_tower_extra_spacing
end_line
setting:wipe_tower_no_sparse_layers
setting:wipe_tower_rest_in_middle
line:Priming
setting:single_extruder_multi_material_priming
setting:priming_position
@ -600,6 +602,10 @@ group:Sequential printing
setting:label$Step:parallel_objects_step
setting:label$Max z:parallel_objects_step_max_z
end_line
line:Island Parallel printing step
setting:label$:parallel_islands
setting:label$Minimum island distance:parallel_islands_min_distance
end_line
setting:complete_objects_one_skirt
setting:complete_objects_sort
line:Extruder clearance (mm)

View file

@ -22,6 +22,7 @@ add_subdirectory(libigl)
add_subdirectory(hints)
add_subdirectory(qoi)
add_subdirectory(libnest2d)
add_subdirectory(quickdigest5)
find_package(Qhull 7.2 REQUIRED)
add_library(qhull INTERFACE)

View file

@ -394,7 +394,7 @@ static int StringRegexFind(const string& rex, asUINT start, asUINT& outLengthOfM
// https://www.regular-expressions.info/stdregex.html
//
// std::wregex pattern(L"[[:alpha:]]+");
// bool result = std::regex_match(std::wstring(L"abcdéfg"), pattern);
// bool result = std::regex_match(std::wstring(L"abcd<EFBFBD>fg"), pattern);
//
// The solution from stack overflow doesn't work with MSVC
// https://stackoverflow.com/questions/11254232/do-c11-regular-expressions-work-with-utf-8-strings
@ -402,7 +402,7 @@ static int StringRegexFind(const string& rex, asUINT start, asUINT& outLengthOfM
// std::locale old;
// std::locale::global(std::locale("en_US.UTF-8"));
// std::regex pattern("[[:alpha:]]+", std::regex_constants::extended);
// bool result = std::regex_match(std::string(u8"abcdéfg"), pattern);
// bool result = std::regex_match(std::string(u8"abcd<EFBFBD>fg"), pattern);
//
// I've tried setting the manifest to use utf8 code page but it also doesn't work with MSVC
// https://learn.microsoft.com/en-us/windows/apps/design/globalizing/use-utf8-code-page

294
src/libslic3r/Api/README.md Normal file
View file

@ -0,0 +1,294 @@
# libslic3r api
These header files contains the object to extends to create a new plugin.
currently work_in_progress
note: items with tag Planned are currently ideas that are not implemented and so may not work and may need extensive modifications.
Other items are already implemented, but may need some modifications in the future to fit into the framework
## how it works
The libsli3r contains structure with the slicing data.
Each plugin implements process that allow to create/modify these data to go to the next stages.
the slicer will call the activated process one after another to create the gcode.
## data
Main data Objects:
* Print
* Model
* ModelObject
* Object
* PrintRegion
* Layer
* LayerRegion
* LayerSliceIsland
* LayerRegionIsland
* Surface
for gcode cgeneration:
* PrintOrdering
* LayerExtusion
Some fields in the data objects may not be modifiable after a certain step. If a process call a setter method when it's not allowed anymore, an exception is emitted. This allow to use some pointers safely, as the object are now ensured to not be erased.
### Print
Entry point, there is at most one print object per plater (There may be multiple Print object in the slicer, if they choose to have multiple pater and one Print per plater).
The Print object contains the pointer to all other data.
The print contains the objects, which are independent with each other.
Model & ModelObject are the 3D inputs
### Object
TO FILL
has only one Print pointer.
### Layer
A layer of a object. It's defined by its object, the print z and the print height (and the bottom z can be computed from these two).
it contains the Expolygons slice, as it got from the slicing.
It contains a list of LayerSliceIsland and a list or LayerRegion.
It has only one Object pointer.
Note: support are now normal layers (in Slic3r and derivative, they are specials) and support extrusions can be in normal layers if the printz & printheight are the same.
Note2: for not-planar printing, the layer are pre-deformed. the deformation is saved for renormalizattion after the slicing, but the layers are still flat in all the steps in the slicer.
### LayerSliceIsland
Contains an ExPolygon, a list of LayerRegionIsland.
Contains a list of LayerSliceIsland's pointer from above and a list of LayerSliceIsland's pointer from below. All of these have their ExPolygon overlap our one.
Has only one Layer pointer
### PrintRegion
A region. It may have modified settings, and modified properties. A print can contains many regions.
### LayerRegion
Contains a list of ExPolygon (its slice)
Contains a list of Surface
Has a Layer pointer, a PrintRegion pointer
A sliced region on this layer.
LayerRegion can't overlap each other?
### LayerRegionIsland
The most precise data holder.
It is included inside a LayerSliceIsland.
It is inside at least one LayerRegion. It can have multiple one if they have the same properties needed for a given process.
It is set for only one extruder.
It contains the extrusion to be printed, stored by broad category (perimeter, infill, support, ...).
It should only contains a single ExPolygon, that may be the same or smaller than the LayerSliceIsland.
If you intersect the LayerRegion and the LayerSliceIsland, you may have multiple ExPolygons. In this case, you need to create a LayerRegionIsland for each sub-island.
Most of the time, when you want to add some new extrusions in the data store, you have to request for a compatible LayerRegionIsland. If it doesn't exists, then it will be created.
### Surface
A ExPolygon with surface types (top, bottom, solid infill, etc..) and some other properties.
### PrintOrdering
Planned
it's an ordering of LayerRegionIsland that only increase in layer_z
it contains a list of OrderingLayer, each one with a layer_z.
An OrderingLayer has a list of set<<LayerRegionIsland, LayerSliceIsland>>
We can get the multiple Layers (some may be from different objects) it touches from the LayerSliceIsland.
We can get the multiple regions (some may be from different objects) it touches from the LayerRegionIsland.
It also have a list of LayerExtusion to be filled by the LayerRegionIsland extrusions
LayerRegionIsland are immutable.
LayerExtusion are mutable.
### LayerExtusion
Planned
An List of <ExtrusionEntity, const LayerRegionIsland*> to be printed.
The extrusionEntiy are mutable, the LayerRegionIsland is for reference, to get to the region's settings.
## steps
stages are listed in their order.
A step can be unique or multiple. A unique step means that only one process can be registered for it, else it can have multiple ones. In this case, their order can be random or defined from process preferences.
### slicing
Unique
input: Print, Model, ModelObject, Object
output: Layer, LayerSliceIsland, LayerRegion
Slice the parts of the modelobject to create the Layers of the object.
Slice the modifiers of the modelobject to create the LayerRegions of the object.
Slice other volumes of the modelobject to be able to use them afterwards (brim, seam, support, etc)
assign an extruder to each region.
### slicing modifications
Multiple
input : Print, Object, Layer, LayerSliceIsland, LayerRegion
output: Layer, LayerSliceIsland, LayerRegion
Modify the slices from the slicing. It's a bit like modifying the input geometry.
current:
holes to polyholes
max overhangs
curve smoothing
### surface creation
create surfaces from Islands
### Perimeter Generator pre-process
Multiple
for things like "avoid overhangs on bridges area"
### Perimeter Generator
Unique
input: Layer, LayerSliceIsland, LayerRegion, Surface
output: Layer, LayerSliceIsland, LayerRegion, Surface, LayerRegionIsland
Create perimeters.
It create LayerRegionIsland as needed to store the perimeter extrusions.
It modify the surfaces so the infill surfaces don't overlap with perimeter.
currently, the core algorithm takes a single surface and output perimeter extrusions & infill polygons from it. The process do the piping around it.
### prepare_infill
multiple
input: Layer, LayerSliceIsland, LayerRegion, Surface
output: Layer, LayerSliceIsland, LayerRegion, Surface
modify the surfaces and their tag so it's possible to infill them with the right process at the right spot.
detect the top, bottom, the void, the sparse, bridge areas.
exemples of current process list in use ('ensure vertical shell thickness' changes it):
detect_surfaces_type->prepare_fill_surfaces->process_external_surfaces->discover_horizontal_shells
detect_surfaces_type->prepare_fill_surfaces->discover_vertical_shells->process_external_surfaces
### prepare_infill_post_process
multiple
input: Layer, LayerSliceIsland, LayerRegion, Surface
output: Layer, LayerSliceIsland, LayerRegion, Surface
alter surfaces from prepare_infill for various purpose.
current post-processes:
clean_surfaces
tag_under_bridge
bridge_over_infill
combine_infill
compute_max_sparse_spacing
### infill
Multiple
input: Layer, LayerSliceIsland, LayerRegion, Surface
output: Layer, LayerSliceIsland, LayerRegion, Surface, LayerRegionIsland
Infill a surface and output the extrusions result into a LayerRegionIsland.
note:
It combines same surfaces of LayerRegion with same properties to have the biggest surface possible.
current infill processes:
* 'normal' infill
* ironing
### Generate Support Spots
Detect surfaces that are problematic and should be supported.
TODO: currently this algorithm is on the side. It should be incorporated into the main workflow and maybe used as input for the "create support"
### Create support
Unique
input: Object, Layer, LayerSliceIsland, LayerRegion, Surface
output: Object, Layer, LayerSliceIsland, LayerRegion, Surface, LayerRegionIsland
create support:
can create layers
can create extrusions
### Slicing post process
Multiple
input: Print, Object, Layer, LayerSliceIsland, LayerRegion, Surface, LayerRegionIsland
output: Print, Object, Layer, LayerSliceIsland, LayerRegion, Surface, LayerRegionIsland
process to create data or extrusions before everything is set in stone for the sorting.
current:
estimate_curled_extrusions
calculate_overhanging_perimeters
create brim and skirt (they need to be created into a LayerRegionIsland like everyone else, but this one can be special)
create arcs
## Ordering
Unique
input: Print, Object, Layer, LayerSliceIsland, LayerRegion, Surface, LayerRegionIsland
Output: PrintOrdering
Order the LayerRegionIsland for printing.
there is multiple ordering algorithm.
The normal one first sort all layers from all objects by print_z, then in each group by extruder, then islands by proximity (or not at all, ready to be sorted on extrusion proximity)
The parallel object sort by object first, then by layers, extruder, island.
The parallel step is a combination of both.
The output Ordering object keep the ordering
## wipetower
Unique
Input: LayerRegionIsland, PrintOrdering
Output: LayerRegionIsland, PrintOrdering
Create wipetower(s). It uses the wipetowers model/volume from the print/ObjectModel.
There is one wipetower if normal printing, there is one wipetower per object if parallel objects printing (Planned).
Using the ordering, the wipetower toolchanges are planned.
As there may be extra wipes, the wipetower size & extrusion can't be computed right now, so the extrusions added into the Ordering are placeholders.
## Layer stiching
Unique
Input: PrintOrdering
Output: PrintOrdering, LayerExtusion
go over each layer to decide the order of each extrusion. Choose seams.
Should be made sequentially to use the previous layer position to minimise travel.
To prevent bottleneck, the layers already computed can be passed in the next steps via pipelining, until one process need to have everything synchronized (like the result of compute layer time)
## extrusion post-processing
Multiple
Input: PrintOrdering, LayerExtusion
Output: PrintOrdering, LayerExtusion
modify the extrusions or their order
The GcodeWriter need to be changed into an utility to traverse the extrusions to be able to easily see the current state.
Note: most now can be done in // (by layer)
current:
seam notch
loop cut (add seam gap)
generate speed & acceleration (by region -> Planned)
generate retract & lift
generate retract-wipe
generate wipe-tower wipe (prevent filament grinding by too much retraction on the same spot) (Planned)
generate heating
generate fan speed
compute layer time
min layer time
heating advance (Planned)
fan speed advance
## generate gcode
UNIQUE
Input: Ordering, LayerExtusion
output: gcode file
from the extrusion, generate gcode
note: can now be done in //

View file

@ -104,6 +104,12 @@ uint32_t AppConfig::create_color(float saturation, float value, EAppColorType co
return rgb2int(rgb_color);
}
ColorRGB AppConfig::get_color(const std::string &key) const {
std::string hex_str = get(key);
uint32_t int_color = hex2int(hex_str);
return int2rgb(int_color);
}
// Override missing or keys with their defaults.
void AppConfig::set_defaults()
{
@ -177,7 +183,7 @@ void AppConfig::set_defaults()
if (get("tab_icon_size").empty())
set("tab_icon_size", "32");
if (get("font_size").empty())
if (get("font_size").empty() || get_int("font_size") <= 0)
set("font_size", "0");
if (get("side_panel_width").empty())
@ -716,7 +722,8 @@ void AppConfig::init_ui_layout() {
//get default color from the ini file
//try to load colors from ui file
std::map<std::string, std::string> key2color = { {"Gui_color_dark", "cabe39"}, {"Gui_color", "eddc21"}, {"Gui_color_light", "ffee38"} };
std::map<std::string, std::string> key2color = { {"Gui_color_dark", "cabe39"}, {"Gui_color", "eddc21"}, {"Gui_color_light", "ffee38"},
{"Gui_skybox_dark", "7A7A7A"}, {"Gui_skybox_light", "C0C0C0"}, {"Gui_plater", "3C3C3C"}, {"Gui_plater_grid", "D0D0D0"}};
boost::property_tree::ptree tree_colors;
boost::filesystem::path path_colors = boost::filesystem::path(layout_config_path()) / "colors.ini";
try {
@ -779,6 +786,18 @@ void AppConfig::init_ui_layout() {
if (get("color_light").empty())
set("color_light", key2color["Gui_color_light"]);
if (get("color_skybox_dark").empty())
set("color_skybox_dark", key2color["Gui_skybox_dark"]);
if (get("color_skybox_light").empty())
set("color_skybox_light", key2color["Gui_skybox_light"]);
if (get("color_plater").empty())
set("color_plater", key2color["Gui_plater"]);
if (get("color_plater_grid").empty())
set("color_plater_grid", key2color["Gui_plater_grid"]);
{
// try to load splashscreen from ui file
std::map<std::string, std::string> key2splashscreen = {{"splash_screen_editor", ""},

View file

@ -20,6 +20,8 @@
namespace Slic3r {
class ColorRGB;
class AppConfig
{
public:
@ -141,6 +143,7 @@ public:
{ return this->get(key) == "1"; }
int get_int(const std::string &key) const
{ return atoi(this->get(key).c_str()); }
ColorRGB get_color(const std::string &key) const;
bool set(const std::string &section, const std::string &key, const std::string &value)
{
#ifndef NDEBUG

View file

@ -700,7 +700,7 @@ ExtrusionEntityCollection make_brim(const Print &print, PrintTryCancel try_cance
for (; i < j; ++ i) {
this_loop_trimmed.entities.emplace_back(new ExtrusionPath({
ExtrusionRole::Skirt,
ExtrusionFlow{ float(flow.mm3_per_mm()), float(flow.width()), float(print.skirt_first_layer_height()) } }));
ExtrusionFlow{ float(flow.mm3_per_mm()), float(flow.width()), float(print.skirt_first_layer_height()) } }, nullptr));
const ClipperLib_Z::Path &path = *loops_trimmed_order[i].first;
Points &points = dynamic_cast<ExtrusionPath*>(this_loop_trimmed.entities.back())->polyline.points;
points.reserve(path.size());
@ -827,7 +827,7 @@ void extrude_brim_from_tree(const Print& print, std::vector<std::vector<BrimLoop
//def: push into extrusions, in the right order
float mm3_per_mm = float(flow.mm3_per_mm());
float width = float(flow.width());
float height = float(print.get_min_first_layer_height());
float height = float(unscaled(print.get_min_first_layer_height()));
int nextIdx = 0;
std::function<void(BrimLoop&, ExtrusionEntityCollection*)>* extrude_ptr;
std::function<void(BrimLoop&, ExtrusionEntityCollection*) > extrude = [&mm3_per_mm, &width, &height, &extrude_ptr, &nextIdx, extrude_cw](BrimLoop& to_cut, ExtrusionEntityCollection* parent) {
@ -846,11 +846,11 @@ void extrude_brim_from_tree(const Print& print, std::vector<std::vector<BrimLoop
pline.reverse();
}
if (pline.back() == pline.front()) {
ExtrusionPath path({ExtrusionRole::Skirt, {mm3_per_mm, width, height}}, false);
ExtrusionPath path({ExtrusionRole::Skirt, {mm3_per_mm, width, height}}, nullptr, false);
path.polyline = pline;
to_add.push_back(new ExtrusionLoop(std::move(path), elrSkirt));
} else {
ExtrusionPath *extrusion_path = new ExtrusionPath({ExtrusionRole::Skirt, {mm3_per_mm, width, height}}, false);
ExtrusionPath *extrusion_path = new ExtrusionPath({ExtrusionRole::Skirt, {mm3_per_mm, width, height}}, nullptr, false);
extrusion_path->polyline = pline;
to_add.push_back(extrusion_path);
}
@ -889,11 +889,11 @@ void extrude_brim_from_tree(const Print& print, std::vector<std::vector<BrimLoop
pline.reverse();
}
if (pline.back() == pline.front()) {
ExtrusionPath path({ExtrusionRole::Skirt, {mm3_per_mm, width, height}}, false);
ExtrusionPath path({ExtrusionRole::Skirt, {mm3_per_mm, width, height}}, nullptr, false);
path.polyline = pline;
to_add.push_back(new ExtrusionLoop(std::move(path), elrSkirt));
} else {
ExtrusionPath *extrusion_path = new ExtrusionPath({ExtrusionRole::Skirt, {mm3_per_mm, width, height}}, false);
ExtrusionPath *extrusion_path = new ExtrusionPath({ExtrusionRole::Skirt, {mm3_per_mm, width, height}}, nullptr, false);
extrusion_path->polyline = pline;
to_add.push_back(extrusion_path);
}
@ -1039,7 +1039,22 @@ void make_brim(const Print& print, const Flow& flow, const PrintObjectPtrs& obje
}
}
if (!object->support_layers().empty()) {
ExPolygons polys = union_ex(object->support_layers().front()->support_fills.polygons_covered_by_spacing(flow.spacing_ratio(), float(SCALED_EPSILON)));
ExPolygons polys;
for (const LayerSliceIslandPtr &island : object->support_layers().front()->islands()) {
for (const LayerRegionIslandPtr &region_island : island->regions_islands()) {
if (region_island->has_extrusion(LayerRegionIsland::SUPPORT)) {
expolygons_append(polys,
region_island->extrusion(LayerRegionIsland::SUPPORT)
.polygons_covered_by_spacing(flow.spacing_ratio(), float(SCALED_EPSILON)));
}
if (region_island->has_extrusion(LayerRegionIsland::SUPPORT_INTERFACE)) {
expolygons_append(polys,
region_island->extrusion(LayerRegionIsland::SUPPORT_INTERFACE)
.polygons_covered_by_spacing(flow.spacing_ratio(), float(SCALED_EPSILON)));
}
}
}
polys = union_ex(polys);
for (ExPolygon& poly : polys) {
if (brim_offset == 0) {
object_islands.push_back(std::move(poly));
@ -1213,7 +1228,22 @@ void make_brim_ears(const Print& print, const Flow& flow, const PrintObjectPtrs&
}
if (!object->support_layers().empty()) {
ExPolygons polys = union_ex(object->support_layers().front()->support_fills.polygons_covered_by_spacing(flow.spacing_ratio(), float(SCALED_EPSILON)));
ExPolygons polys;
for (const LayerSliceIslandPtr &island : object->support_layers().front()->islands()) {
for (const LayerRegionIslandPtr &region_island : island->regions_islands()) {
if (region_island->has_extrusion(LayerRegionIsland::SUPPORT)) {
expolygons_append(polys,
region_island->extrusion(LayerRegionIsland::SUPPORT)
.polygons_covered_by_spacing(flow.spacing_ratio(), float(SCALED_EPSILON)));
}
if (region_island->has_extrusion(LayerRegionIsland::SUPPORT_INTERFACE)) {
expolygons_append(polys,
region_island->extrusion(LayerRegionIsland::SUPPORT_INTERFACE)
.polygons_covered_by_spacing(flow.spacing_ratio(), float(SCALED_EPSILON)));
}
}
}
polys = union_ex(polys);
//put ears over supports unless it's more than 30% fill
if (object->config().raft_first_layer_density.get_abs_value(1.) > 0.3) {
for (ExPolygon& poly : polys) {
@ -1437,9 +1467,22 @@ void make_brim_interior(const Print& print, const Flow& flow, const PrintObjectP
}
if (!object->support_layers().empty()) {
spacing = scaled(object->config().support_material_interface_spacing.value) + support_material_flow(object, float(print.get_min_first_layer_height())).scaled_width() * 1.5;
ExPolygons polys = closing_ex(
union_ex(object->support_layers().front()->support_fills.polygons_covered_by_spacing(flow.spacing_ratio(), float(SCALED_EPSILON)))
, spacing);
ExPolygons polys;
for (const LayerSliceIslandPtr &island : object->support_layers().front()->islands()) {
for (const LayerRegionIslandPtr &region_island : island->regions_islands()) {
if (region_island->has_extrusion(LayerRegionIsland::SUPPORT)) {
expolygons_append(polys,
region_island->extrusion(LayerRegionIsland::SUPPORT)
.polygons_covered_by_spacing(flow.spacing_ratio(), float(SCALED_EPSILON)));
}
if (region_island->has_extrusion(LayerRegionIsland::SUPPORT_INTERFACE)) {
expolygons_append(polys,
region_island->extrusion(LayerRegionIsland::SUPPORT_INTERFACE)
.polygons_covered_by_spacing(flow.spacing_ratio(), float(SCALED_EPSILON)));
}
}
}
polys = closing_ex(union_ex(polys), spacing);
for (ExPolygon& poly : polys) {
if (brim_offset == 0) {
object_islands.push_back(std::move(poly));

View file

@ -198,12 +198,16 @@ set(SLIC3R_SOURCES
GCode/SeamPlacer.hpp
#GCode/SmoothPath.cpp
#GCode/SmoothPath.hpp
GCode/TemperatureMover.cpp
GCode/TemperatureMover.hpp
GCode/ToolOrdering.cpp
GCode/ToolOrdering.hpp
GCode/Wipe.cpp
GCode/Wipe.hpp
GCode/WipeTower.cpp
GCode/WipeTower.hpp
GCode/WipeTower2.cpp
GCode/WipeTower2.hpp
GCode/WipeTowerIntegration.cpp
GCode/WipeTowerIntegration.hpp
GCode/GCodeProcessor.cpp
@ -624,6 +628,7 @@ target_link_libraries(libslic3r
JPEG::JPEG
qoi
LibBGCode::bgcode_convert
quickdigest5
)
if (APPLE)

View file

@ -1090,6 +1090,9 @@ Slic3r::Polygons offset(const Slic3r::Polyline &polyline, const double delta, Cl
Slic3r::Polygons offset(const Slic3r::Polylines &polylines, const double delta, ClipperLib::JoinType joinType, double miterLimit, ClipperLib::EndType end_type)
{ assert(delta > 0); return to_polygons(clipper_union<ClipperLib::Paths>(raw_offset_polyline(ClipperUtils::PolylinesProvider(polylines), delta, joinType, miterLimit, end_type))); }
Slic3r::ExPolygons offset_ex(const Slic3r::Polyline &polyline, const double delta, ClipperLib::JoinType joinType, double miterLimit, ClipperLib::EndType end_type)
{ assert(delta > 0); return PolyTreeToExPolygons(clipper_union<ClipperLib::PolyTree>(raw_offset_polyline(ClipperUtils::SinglePathProvider(polyline.points), delta, joinType, miterLimit, end_type))); }
Polygons contour_to_polygons(const Polygon &polygon, const float line_width, ClipperLib::JoinType join_type, double miter_limit){
assert(line_width > 1.f); return to_polygons(clipper_union<ClipperLib::Paths>(
raw_offset(ClipperUtils::SinglePathProvider(polygon.points), line_width/2, join_type, miter_limit, ClipperLib::etClosedLine)));}
@ -1435,6 +1438,7 @@ Slic3r::Polygons diff(const Slic3r::ExPolygons &subject, const Slic3r::ExPolygon
{ return _clipper(ClipperLib::ctDifference, ClipperUtils::ExPolygonsProvider(subject), ClipperUtils::ExPolygonsProvider(clip), do_safety_offset); }
Slic3r::Polygons diff(const Slic3r::Surfaces &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset)
{ return _clipper(ClipperLib::ctDifference, ClipperUtils::SurfacesProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); }
Slic3r::Polygons intersection(const Slic3r::Polygon &subject, const Slic3r::Polygon &clip, ApplySafetyOffset do_safety_offset)
{ return _clipper(ClipperLib::ctIntersection, ClipperUtils::SinglePathProvider(subject.points), ClipperUtils::SinglePathProvider(clip.points), do_safety_offset); }
Slic3r::Polygons intersection(const Slic3r::Polygon &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset)
@ -1888,7 +1892,7 @@ ClipperLib_Z::Paths clip_extrusion(const ClipperLib_Z::Paths& subjects, const Cl
prev = Point(subject.front().x(), subject.front().y());
}
Point projected_pt;
if (double dist_sqr = line_alg::distance_to_squared(Line(prev, curr), pt, &projected_pt); dist_sqr < dist_sqr_min) {
if (double dist_sqr = Line::distance_to_squared_abp(prev, curr, pt, &projected_pt); dist_sqr < dist_sqr_min) {
dist_sqr_min = dist_sqr;
projected_pt_min = projected_pt;
it_a = &*std::prev(it);

View file

@ -354,6 +354,7 @@ Slic3r::Polygons offset(const Slic3r::ExPolygon &expolygon, const double delta
Slic3r::Polygons offset(const Slic3r::ExPolygons &expolygons, const double delta, ClipperLib::JoinType joinType = DefaultJoinType, double miterLimit = DefaultMiterLimit);
Slic3r::Polygons offset(const Slic3r::Surfaces &surfaces, const double delta, ClipperLib::JoinType joinType = DefaultJoinType, double miterLimit = DefaultMiterLimit);
Slic3r::Polygons offset(const Slic3r::SurfacesPtr &surfaces, const double delta, ClipperLib::JoinType joinType = DefaultJoinType, double miterLimit = DefaultMiterLimit);
Slic3r::ExPolygons offset_ex(const Slic3r::Polyline &polyline, const double delta, ClipperLib::JoinType joinType = DefaultLineJoinType, double miterLimit = DefaultLineMiterLimit, ClipperLib::EndType end_type = DefaultEndType);
Slic3r::ExPolygons offset_ex(const Slic3r::Polygon &polygon, const double delta, ClipperLib::JoinType joinType = DefaultJoinType, double miterLimit = DefaultMiterLimit);
Slic3r::ExPolygons offset_ex(const Slic3r::Polygons &polygons, const double delta, ClipperLib::JoinType joinType = DefaultJoinType, double miterLimit = DefaultMiterLimit);
Slic3r::ExPolygons offset_ex(const Slic3r::ExPolygon &expolygon, const double delta, ClipperLib::JoinType joinType = DefaultJoinType, double miterLimit = DefaultMiterLimit);

View file

@ -82,6 +82,7 @@ public:
ColorRGBA(float r, float g, float b, float a);
ColorRGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a);
ColorRGBA(const ColorRGBA& other) = default;
ColorRGBA(const ColorRGB &rgb) : m_data{rgb.r(), rgb.g(), rgb.b(), 1.0f} {}
ColorRGBA& operator = (const ColorRGBA& other) { m_data = other.m_data; return *this; }

View file

@ -485,6 +485,15 @@ double GraphData::interpolate(double x_value) const{
return y_value;
}
double GraphData::inverse_interpolate(double y_value) const {
GraphData inverse = *this;
// inverse x & y
for (Vec2d &data_point : inverse.graph_points) {
std::swap(data_point.x(), data_point.y());
}
return inverse.interpolate(y_value);
}
bool GraphData::validate() const
{
if (this->begin_idx < 0 || this->end_idx < 0 || this->end_idx < this->begin_idx)
@ -1435,7 +1444,19 @@ double ConfigBase::get_computed_value(const t_config_option_key &opt_key, int ex
if (raw_opt->type() == coFloatOrPercent) {
auto cofop = static_cast<const ConfigOptionFloatOrPercent*>(raw_opt);
if (cofop->value == 0 && boost::ends_with(opt_key, "_extrusion_width")) {
return Flow::extrusion_width(opt_key, *this, extruder_id);
int idx = extruder_id;
if (extruder_id < 0) {
const ConfigOption* opt_extruder_id = nullptr;
if ((opt_extruder_id = this->option("extruder")) == nullptr)
if ((opt_extruder_id = this->option("current_extruder")) == nullptr
|| opt_extruder_id->get_int() < 0 || opt_extruder_id->get_int() >= uint16_t(-1)) {
std::stringstream ss; ss << "Flow::extrusion_width(): " << opt_key << " need to has the extuder id to get the right value, but it's not available";
throw ConfigurationError(ss.str());
}
extruder_id = opt_extruder_id->get_int();
idx = extruder_id;
}
return Flow::extrusion_width(opt_key, *this, idx);
}
if (!cofop->percent)
return cofop->value;

View file

@ -59,6 +59,11 @@ namespace Slic3r {
double value;
bool percent;
double get_abs_value(double ratio_over) const {
return this->percent ? (ratio_over * this->value / 100) : this->value;
}
double get_float(size_t idx = 0) const { return get_abs_value(1.); }
bool is_percent(size_t idx = 0) const { return this->percent; }
private:
friend class cereal::access;
template<class Archive> void serialize(Archive& ar) { ar(this->value); ar(this->percent); }
@ -97,8 +102,9 @@ namespace Slic3r {
// data is the useable part of the graph
Pointfs data() const;
size_t data_size() const;
double interpolate(double x_value) const;
double inverse_interpolate(double y_value) const;
//return false if data are not good
bool validate() const;
@ -152,6 +158,11 @@ namespace Slic3r {
std::vector<GraphData::GraphType> allowed_types;
// the values when you click on the "reset" button (dynamically set to the current data stored in the setting)
GraphData reset_vals;
// min & max enforced points. if no values here, no enforced points.
// if only one, only the min is enforced.
// if the first value has nan x, only the max is enforced
// if more than 2 values, other are ignored
Pointfs enforced_values;
};
}
@ -1628,6 +1639,7 @@ private:
template<class Archive> void serialize(Archive &ar) { ar(cereal::base_class<ConfigOptionFloats>(this)); }
};
// note: maybe should be a ConfigOptionSingle<FloatOrPercent>
class ConfigOptionFloatOrPercent : public ConfigOptionPercent
{
public:

View file

@ -16,23 +16,23 @@ namespace CustomGCode {
// then CustomGCode::Info.gcodes should be updated considering this option.
extern void update_custom_gcode_per_print_z_from_config(Info& info, DynamicPrintConfig* config)
{
auto *colorprint_heights = config->option<ConfigOptionFloats>("colorprint_heights");
auto *colorprint_heights = config->option<ConfigOptionFloats>("colorprint_heights");
if (colorprint_heights == nullptr)
return;
if (info.gcodes.empty() && ! colorprint_heights->empty()) {
// Convert the old colorprint_heighs only if there is no equivalent data in a new format.
// Convert the old colorprint_heighs only if there is no equivalent data in a new format.
const std::vector<std::string>& colors = ColorPrintColors::get();
info.gcodes.clear();
info.gcodes.reserve(colorprint_heights->size());
int i = 0;
for (auto val : colorprint_heights->get_values())
info.gcodes.emplace_back(Item{ val, ColorChange, 1, colors[(++i)%7] });
for (double val : colorprint_heights->get_values())
info.gcodes.emplace_back(Item{Layer::scale_to_layer_coord(val), ColorChange, 1, colors[(++i)%7] });
info.mode = SingleExtruder;
}
}
// The "colorprint_heights" config value has been deprecated. At this point of time it has been converted
// to a new format and therefore it shall be erased.
// The "colorprint_heights" config value has been deprecated. At this point of time it has been converted
// to a new format and therefore it shall be erased.
config->erase("colorprint_heights");
}
@ -59,29 +59,29 @@ extern void check_mode_for_custom_gcode_per_print_z(Info& info)
// Return pairs of <print_z, 1-based extruder ID> sorted by increasing print_z from custom_gcode_per_print_z.
// print_z corresponds to the first layer printed with the new extruder.
std::vector<std::pair<double, uint16_t>> custom_tool_changes(const Info& custom_gcode_per_print_z, size_t num_extruders)
std::vector<std::pair<coord_t, uint16_t>> custom_tool_changes(const Info& custom_gcode_per_print_z, size_t num_extruders)
{
std::vector<std::pair<double, uint16_t>> custom_tool_changes;
std::vector<std::pair<coord_t, uint16_t>> custom_tool_changes;
for (const Item& custom_gcode : custom_gcode_per_print_z.gcodes)
if (custom_gcode.type == ToolChange) {
// If extruder count in PrinterSettings was changed, use default (0) extruder for extruders, more than num_extruders
assert(custom_gcode.extruder >= 0);
custom_tool_changes.emplace_back(custom_gcode.print_z, static_cast<uint16_t>(size_t(custom_gcode.extruder) > num_extruders ? 1 : custom_gcode.extruder));
custom_tool_changes.emplace_back(custom_gcode.print_z_, static_cast<uint16_t>(size_t(custom_gcode.extruder) > num_extruders ? 1 : custom_gcode.extruder));
}
return custom_tool_changes;
}
// Return pairs of <print_z, 1-based extruder ID> sorted by increasing print_z from custom_gcode_per_print_z.
// Where print_z corresponds to the layer on which we perform a color change for the specified extruder.
std::vector<std::pair<double, uint16_t>> custom_color_changes(const Info& custom_gcode_per_print_z, size_t num_extruders)
std::vector<std::pair<coord_t, uint16_t>> custom_color_changes(const Info& custom_gcode_per_print_z, size_t num_extruders)
{
std::vector<std::pair<double, uint16_t>> custom_color_changes;
std::vector<std::pair<coord_t, uint16_t>> custom_color_changes;
for (const Item& custom_gcode : custom_gcode_per_print_z.gcodes)
if (custom_gcode.type == ColorChange) {
// If extruder count in PrinterSettings was changed, ignore custom g-codes for extruder ids bigger than num_extruders.
assert(custom_gcode.extruder >= 0);
if (size_t(custom_gcode.extruder) <= num_extruders) {
custom_color_changes.emplace_back(custom_gcode.print_z, static_cast<uint16_t>(custom_gcode.extruder));
custom_color_changes.emplace_back(custom_gcode.print_z_, static_cast<uint16_t>(custom_gcode.extruder));
}
}
return custom_color_changes;

View file

@ -9,6 +9,8 @@
#include <vector>
#include <cstdint>
#include "libslic3r.h"
namespace Slic3r {
class DynamicPrintConfig;
@ -26,18 +28,18 @@ enum Type
struct Item
{
bool operator<(const Item& rhs) const { return this->print_z < rhs.print_z; }
bool operator<(const Item& rhs) const { return this->print_z_ < rhs.print_z_; }
bool operator==(const Item& rhs) const
{
return (rhs.print_z == this->print_z ) &&
return (rhs.print_z_ == this->print_z_ ) &&
(rhs.type == this->type ) &&
(rhs.extruder == this->extruder ) &&
(rhs.color == this->color ) &&
(rhs.extra == this->extra );
}
bool operator!=(const Item& rhs) const { return ! (*this == rhs); }
double print_z;
coord_t print_z_;
Type type;
int extruder; // Informative value for ColorChangeCode and ToolChangeCode
// "gcode" == ColorChangeCode => M600 will be applied for "extruder" extruder
@ -90,11 +92,11 @@ extern void check_mode_for_custom_gcode_per_print_z(Info& info);
// Return pairs of <print_z, 1-based extruder ID> sorted by increasing print_z from custom_gcode_per_print_z.
// print_z corresponds to the first layer printed with the new extruder.
std::vector<std::pair<double, uint16_t>> custom_tool_changes(const Info& custom_gcode_per_print_z, size_t num_extruders);
std::vector<std::pair<coord_t, uint16_t>> custom_tool_changes(const Info& custom_gcode_per_print_z, size_t num_extruders);
// Return pairs of <print_z, 1-based extruder ID> sorted by increasing print_z from custom_gcode_per_print_z.
// Where print_z corresponds to the layer on which we perform a color change for the specified extruder.
std::vector<std::pair<double, uint16_t>> custom_color_changes(const Info& custom_gcode_per_print_z, size_t num_extruders);
std::vector<std::pair<coord_t, uint16_t>> custom_color_changes(const Info& custom_gcode_per_print_z, size_t num_extruders);
} // namespace CustomGCode

View file

@ -99,6 +99,7 @@ public:
const Polygon& contour_or_hole(size_t idx) const { return (idx == 0) ? this->contour : this->holes[idx - 1]; }
#ifdef _DEBUGINFO
#pragma UNOPTIMIZE
void assert_valid() const {
contour.assert_valid();
assert(contour.is_counter_clockwise());
@ -469,6 +470,8 @@ inline ExPolygons to_expolygons(const Polygons &polys)
return ex_polys;
}
// trasform a list of contour (ccw) into expolygons
// polys.size() == return.size()
inline ExPolygons to_expolygons(Polygons &&polys)
{
ExPolygons ex_polys;
@ -480,6 +483,8 @@ inline ExPolygons to_expolygons(Polygons &&polys)
return ex_polys;
}
// trasform a list of contour (ccw) into expolygons
// polys.size() == return.size()
inline Points to_points(const ExPolygon &expoly)
{
Points out;
@ -539,6 +544,22 @@ inline void polygons_append(Polygons &dst, ExPolygons &&src)
}
}
inline void expolygons_append(ExPolygons &dst, const Polygons &src)
{
for (const Polygon& poly: src) {
assert(poly.is_counter_clockwise());
dst.emplace_back(poly);
}
}
inline void expolygons_append(ExPolygons &dst, Polygons &&src)
{
for (Polygon& poly: src) {
assert(poly.is_counter_clockwise());
dst.emplace_back(std::move(poly));
}
}
inline void expolygons_append(ExPolygons &dst, const ExPolygons &src)
{
dst.insert(dst.end(), src.begin(), src.end());

View file

@ -26,6 +26,7 @@ void ExtrusionVisitor::use(ExtrusionMultiPath &multipath) { default_use(multipat
void ExtrusionVisitor::use(ExtrusionMultiPath3D &multipath3D) { default_use(multipath3D); }
void ExtrusionVisitor::use(ExtrusionLoop &loop) { default_use(loop); }
void ExtrusionVisitor::use(ExtrusionEntityCollection &collection) { default_use(collection); }
void ExtrusionVisitor::use(ExtrusionNop &nop) { default_use(nop); }
void ExtrusionVisitorConst::use(const ExtrusionPath &path) { default_use(path); }
void ExtrusionVisitorConst::use(const ExtrusionPath3D &path3D) { default_use(path3D); }
@ -33,12 +34,106 @@ void ExtrusionVisitorConst::use(const ExtrusionMultiPath &multipath) { default_u
void ExtrusionVisitorConst::use(const ExtrusionMultiPath3D &multipath3D) { default_use(multipath3D); }
void ExtrusionVisitorConst::use(const ExtrusionLoop &loop) { default_use(loop); }
void ExtrusionVisitorConst::use(const ExtrusionEntityCollection &collection) { default_use(collection); }
void ExtrusionVisitorConst::use(const ExtrusionNop &nop) { default_use(nop); }
void ExtrusionEntity::visit(ExtrusionVisitor &&visitor) {
this->visit(visitor);
void ExtrusionEntity::visit(ExtrusionVisitor &&visitor) { this->visit(visitor); }
void ExtrusionEntity::visit(ExtrusionVisitorConst &&visitor) const { this->visit(visitor); }
ExtrusionPropertyNone &ExtrusionPropertyNone::instance() {
static ExtrusionPropertyNone instance;
return instance;
}
void ExtrusionEntity::visit(ExtrusionVisitorConst &&visitor) const {
this->visit(visitor);
void ExtrusionPropertyVisitor::default_use(ExtrusionProperty &thing) {
assert(dynamic_cast<ExtrusionPropertyNone *>(&thing) != nullptr);
};
void ExtrusionPropertyVisitor::use(ExtrusionMultiProperties &thing) {
for (std::unique_ptr<ExtrusionProperty> &prop : thing.properties)
prop->visit(*this);
};
void ExtrusionPropertyVisitor::use(ExtrusionPropertySpeed &thing) { default_use(thing); };
void ExtrusionPropertyVisitor::use(ExtrusionPropertyModifier &thing) { default_use(thing); };
void ExtrusionPropertyVisitor::use(ExtrusionPropertyCustomGcode &thing) { default_use(thing); };
void ExtrusionPropertyVisitor::use(ExtrusionPropertySpecialCommand &thing) { default_use(thing); };
void ExtrusionPropertyVisitor::use(ExtrusionPropertyOverhang &thing) { default_use(thing); };
void ExtrusionPropertyVisitor::use(ExtrusionPropertyZOffset &thing) { default_use(thing); };
void ExtrusionPropertyVisitorConst::default_use(const ExtrusionProperty &thing) {
assert(dynamic_cast<const ExtrusionPropertyNone *>(&thing) != nullptr);
};
void ExtrusionPropertyVisitorConst::use(const ExtrusionMultiProperties &thing) {
for (const std::unique_ptr<ExtrusionProperty> &prop : thing.properties)
prop->visit(*this);
};
void ExtrusionPropertyVisitorConst::use(const ExtrusionPropertySpeed &thing) { default_use(thing); };
void ExtrusionPropertyVisitorConst::use(const ExtrusionPropertyModifier &thing) { default_use(thing); };
void ExtrusionPropertyVisitorConst::use(const ExtrusionPropertyCustomGcode &thing) { default_use(thing); };
void ExtrusionPropertyVisitorConst::use(const ExtrusionPropertySpecialCommand &thing) { default_use(thing); };
void ExtrusionPropertyVisitorConst::use(const ExtrusionPropertyOverhang &thing) { default_use(thing); };
void ExtrusionPropertyVisitorConst::use(const ExtrusionPropertyZOffset &thing) { default_use(thing); };
std::unique_ptr<ExtrusionProperty> ExtrusionEntity::clone_properties() const {
return m_property ? m_property->clone() : nullptr;
}
ExtrusionProperty *ExtrusionEntity::get_root_property() {
return m_property.get();
}
const ExtrusionProperty *ExtrusionEntity::get_root_property() const {
return m_property.get();
}
ExtrusionProperty& ExtrusionEntity::add_property(const ExtrusionProperty &attr) {
if (!m_property) {
m_property = attr.clone();
return *m_property;
} else {
ExtrusionMultiProperties* vec = dynamic_cast<ExtrusionMultiProperties*>(m_property.get());
if (vec == nullptr) {
vec = new ExtrusionMultiProperties();
vec->properties.push_back(std::move(m_property));
m_property = std::unique_ptr<ExtrusionProperty>(vec);
}
return vec->push_back(attr);
}
}
void ExtrusionEntity::add_property(std::unique_ptr<ExtrusionProperty> &&attr) {
if (!m_property) {
m_property = std::move(attr);
} else {
ExtrusionMultiProperties* vec = dynamic_cast<ExtrusionMultiProperties*>(m_property.get());
if (vec == nullptr) {
vec = new ExtrusionMultiProperties();
vec->properties.push_back(std::move(m_property));
m_property = std::unique_ptr<ExtrusionProperty>(vec);
}
vec->push_back(std::move(attr));
}
}
Point ExtrusionNop::NOT_A_POINT = Point((std::numeric_limits<coord_t>::max)(), (std::numeric_limits<coord_t>::max)());
ExtrusionPropertyOverhang &ExtrusionPath::overhang_attributes_mutable() {
if (!m_property) {
m_property = std::make_unique<ExtrusionPropertyOverhang>();
return *static_cast<ExtrusionPropertyOverhang*>(m_property.get());
} else if (auto ptr = dynamic_cast<ExtrusionPropertyOverhang*>(m_property.get()); ptr) {
// quick test, instead of going trough the visitor, as this should be the case for most of overhangs.
return *ptr;
} else {
return AddGetEEAttribute<ExtrusionPropertyOverhang>().add_or_get(*this);
}
}
const ExtrusionPropertyOverhang *ExtrusionPath::overhang_attributes() const {
if (!m_property) {
return nullptr;
} else if (auto ptr = dynamic_cast<const ExtrusionPropertyOverhang*>(m_property.get()); ptr) {
// quick test, instead of going trough the visitor, as this should be the case for most of overhangs.
return ptr;
} else {
return GetEEAttribute<ExtrusionPropertyOverhang>().get(*this);
}
}
void ExtrusionPath::intersect_expolygons(const ExPolygons &collection, ExtrusionEntityCollection *retval) const
@ -85,13 +180,14 @@ void ExtrusionPath::_inflate_collection(const Polylines &polylines, ExtrusionEnt
{
ExtrusionEntitiesPtr to_add;
for (const Polyline &polyline : polylines)
to_add.push_back(new ExtrusionPath(ArcPolyline{polyline}, this->attributes(), this->can_reverse()));
to_add.push_back(new ExtrusionPath(ArcPolyline{polyline}, this->attributes(), this->clone_properties(), this->can_reverse()));
collection->append(std::move(to_add));
}
void ExtrusionPath::polygons_covered_by_width(Polygons &out, const float scaled_epsilon) const
{
polygons_append(out, offset(this->polyline.to_polyline(), double(scale_(m_attributes.width / 2)) + scaled_epsilon));
//polygons_append(out, offset(this->polyline.to_polyline(), double(scale_(m_attributes.width / 2)) + scaled_epsilon));
out = union_(out, offset(this->polyline.to_polyline(), double(scale_(m_attributes.width / 2)) + scaled_epsilon));
}
void ExtrusionPath::polygons_covered_by_spacing(Polygons &out, const float spacing_ratio, const float scaled_epsilon) const
@ -103,7 +199,14 @@ void ExtrusionPath::polygons_covered_by_spacing(Polygons &out, const float spaci
// TODO: check BRIDGE_FLOW here
auto flow = bridge ? Flow::bridging_flow(m_attributes.width, 0.f) :
Flow::new_from_width(m_attributes.width, 0.f, m_attributes.height, spacing_ratio);
polygons_append(out, offset(this->polyline.to_polyline(), 0.5f * float(flow.scaled_spacing()) + scaled_epsilon, Slic3r::ClipperLib::jtMiter, 10));
if (out.empty()) {
out = offset(this->polyline.to_polyline(), 0.5f * float(flow.scaled_spacing()) + scaled_epsilon,
Slic3r::ClipperLib::jtMiter, 10);
} else {
out = union_(out,
offset(this->polyline.to_polyline(), 0.5f * float(flow.scaled_spacing()) + scaled_epsilon,
Slic3r::ClipperLib::jtMiter, 10));
}
}
//note: don't suppport arc
@ -183,10 +286,25 @@ ExtrusionRole ExtrusionLoop::role() const
ExtrusionRole role = this->paths.front().role();
for (const ExtrusionPath &path : this->paths)
if (role != path.role()) {
return ExtrusionRole::Mixed;
// ignore travel role
if (role == ExtrusionRole::Travel) {
role = path.role();
} else if (path.role() != ExtrusionRole::Travel) {
return ExtrusionRole::Mixed;
}
}
return role;
}
bool ExtrusionLoop::has_role(ExtrusionRole test_role) const
{
if (this->paths.empty())
return false;
for (const ExtrusionPath &path : this->paths)
if (path.has_role(test_role)) {
return true;
}
return false;
}
bool ExtrusionLoop::split_at_vertex(const Point &point, const double scaled_epsilon)
{
@ -313,8 +431,8 @@ void ExtrusionLoop::split_at(const Point &point, bool prefer_non_overhang, const
// now split path_idx in two parts
const ExtrusionPath &path = this->paths[close_p.path_idx];
assert(path.polyline.is_valid());
ExtrusionPath p1(path.attributes(), can_reverse());
ExtrusionPath p2(path.attributes(), can_reverse());
ExtrusionPath p1(path.attributes(), path.clone_properties(), can_reverse());
ExtrusionPath p2(path.attributes(), path.clone_properties(), can_reverse());
path.polyline.split_at(close_p.foot_pt, p1.polyline, p2.polyline);
if (this->paths.size() == 1) {
@ -721,11 +839,12 @@ void SimplifyVisitor::use(ExtrusionEntityCollection &collection)
#ifdef _DEBUGINFO
void LoopAssertVisitor::use(const ExtrusionPath &path) {
if (!m_check_length)
release_assert (!path.role().is_overhang() || path.overhang_attributes());
if (m_check_length <= 0)
return;
release_assert(!path.empty());
release_assert(path.mm3_per_mm() > 0.000001 || path.role() == ExtrusionRole::ThinWall);
release_assert(path.length() > SCALED_EPSILON);
release_assert(path.mm3_per_mm() > 0.000001 || path.role() == ExtrusionRole::Travel);
release_assert(path.length() > m_check_length);
for (size_t idx = 1; idx < path.size(); ++idx)
release_assert(!path.polyline.get_point(idx - 1).coincides_with_epsilon(path.polyline.get_point(idx)));
}
@ -736,12 +855,11 @@ void LoopAssertVisitor::use(const ExtrusionLoop& loop) {
}
Point last_pt = loop.last_point();
for (const ExtrusionPath &path : loop.paths) {
release_assert (!path.role().is_overhang() || path.overhang_attributes());
release_assert(path.polyline.size() >= 2);
release_assert(!m_check_length || path.length() >= SCALED_EPSILON);
release_assert(path.length() >= m_check_length);
release_assert(path.first_point() == last_pt);
if(m_check_length)
for (size_t idx = 1; idx < path.size(); ++idx)
release_assert(!path.polyline.get_point(idx - 1).coincides_with_epsilon(path.polyline.get_point(idx)));
use(path);
last_pt = path.last_point();
}
release_assert(loop.paths.front().first_point() == loop.paths.back().last_point());

View file

@ -15,6 +15,7 @@
#include "Polyline.hpp"
#include <cassert>
#include <limits>
#include <numeric>
#include <optional>
#include <string_view>
@ -33,6 +34,7 @@ class ExtrusionPath3D;
class ExtrusionMultiPath;
class ExtrusionMultiPath3D;
class ExtrusionLoop;
class ExtrusionNop;
class ExtrusionVisitor {
@ -44,6 +46,7 @@ public:
virtual void use(ExtrusionMultiPath3D &multipath3D);
virtual void use(ExtrusionLoop &loop);
virtual void use(ExtrusionEntityCollection &collection);
virtual void use(ExtrusionNop &nop);
};
class ExtrusionVisitorConst {
public:
@ -54,20 +57,309 @@ public:
virtual void use(const ExtrusionMultiPath3D &multipath3D);
virtual void use(const ExtrusionLoop &loop);
virtual void use(const ExtrusionEntityCollection &collection);
virtual void use(const ExtrusionNop &nop);
};
class ExtrusionProperty;
class ExtrusionPropertyNone;
class ExtrusionMultiProperties;
class ExtrusionPropertySpeed;
class ExtrusionPropertyModifier;
class ExtrusionPropertyCustomGcode;
class ExtrusionPropertySpecialCommand;
class ExtrusionPropertyOverhang;
class ExtrusionPropertyZOffset;
class ExtrusionPropertyVisitor {
public:
virtual void default_use(ExtrusionProperty&);
virtual void use(ExtrusionMultiProperties&);
virtual void use(ExtrusionPropertySpeed&);
virtual void use(ExtrusionPropertyModifier&);
virtual void use(ExtrusionPropertyCustomGcode&);
virtual void use(ExtrusionPropertySpecialCommand&);
virtual void use(ExtrusionPropertyOverhang&);
virtual void use(ExtrusionPropertyZOffset&);
};
class ExtrusionPropertyVisitorConst {
public:
virtual void default_use(const ExtrusionProperty&);
virtual void use(const ExtrusionMultiProperties&);
virtual void use(const ExtrusionPropertySpeed&);
virtual void use(const ExtrusionPropertyModifier&);
virtual void use(const ExtrusionPropertyCustomGcode&);
virtual void use(const ExtrusionPropertySpecialCommand&);
virtual void use(const ExtrusionPropertyOverhang&);
virtual void use(const ExtrusionPropertyZOffset&);
};
// std::variant or class heirachy?
// std::visit/switch(on index()) vs custom visitor
// => only use variant if you need a visitor with classes that don't inherit same ancestor.
class ExtrusionProperty
{
public:
virtual std::unique_ptr<ExtrusionProperty> clone() const = 0;
virtual void visit(ExtrusionPropertyVisitor &visitor) = 0;
virtual void visit(ExtrusionPropertyVisitorConst &visitor) const = 0;
};
//using ExtrusionPropertiesPtr = std::vector<ExtrusionProperty*>;
class ExtrusionPropertyNone : public ExtrusionProperty
{
public:
bool operator==(ExtrusionPropertyNone const& rhs) const { return true; }
std::unique_ptr<ExtrusionProperty> clone() const override { assert(false); return std::make_unique<ExtrusionPropertyNone>(); }
void visit(ExtrusionPropertyVisitor &visitor) override {}
void visit(ExtrusionPropertyVisitorConst &visitor) const override {}
static ExtrusionPropertyNone& instance();
};
class ExtrusionMultiProperties : public ExtrusionProperty
{
public:
std::vector<std::unique_ptr<ExtrusionProperty>> properties;
ExtrusionMultiProperties() {}
ExtrusionMultiProperties(const ExtrusionMultiProperties& rhs){
for (const std::unique_ptr<ExtrusionProperty> &prop : rhs.properties) {
this->properties.push_back(prop->clone());
}
}
ExtrusionProperty& push_back(const ExtrusionProperty &attr) {
properties.push_back(attr.clone());
return *properties.back();
}
void push_back(std::unique_ptr<ExtrusionProperty> &&attr) {
properties.push_back(std::move(attr));
}
std::unique_ptr<ExtrusionProperty> clone() const override { return std::make_unique<ExtrusionMultiProperties>(*this); }
void visit(ExtrusionPropertyVisitor &visitor) override { visitor.use(*this); }
void visit(ExtrusionPropertyVisitorConst &visitor) const override { visitor.use(*this);}
};
// These are a state. They are used for all children if it's not overriden.
// After the end of this entity, it'sreverted to previous state.
class ExtrusionPropertySpeed : public ExtrusionProperty
{
public:
float speed_mm_per_s = -1.f;
float accel_mm_per_s2 = -1.f;
float pressure_adv = -1.f;
float fan_speed_percent = -1.f; // between 0 and 100
float temperature_C = -1.f;
// ROLE_OVERRIDE?
ExtrusionPropertySpeed(float speed = -1, float accel = -1, float pa = -1, float fan = -1, float temp = -1)
: speed_mm_per_s(speed)
, accel_mm_per_s2(accel)
, pressure_adv(pa)
, fan_speed_percent(fan)
, temperature_C(temp) {}
ExtrusionPropertySpeed &speed(float speed) {
speed_mm_per_s = (speed);
return *this;
}
ExtrusionPropertySpeed &acceleration(float accel) {
accel_mm_per_s2 = (accel);
return *this;
}
ExtrusionPropertySpeed &presure_advance(float pa) {
pressure_adv = (pa);
return *this;
}
ExtrusionPropertySpeed &fan_speed(float fspeed) {
assert(fspeed >= -1 && fspeed <= 100);
fan_speed_percent = (fspeed);
return *this;
}
ExtrusionPropertySpeed &temperature(float temp) {
temperature_C = (temp);
return *this;
}
std::unique_ptr<ExtrusionProperty> clone() const override {
return std::make_unique<ExtrusionPropertySpeed>(*this);
}
void visit(ExtrusionPropertyVisitor &visitor) override { visitor.use(*this); }
void visit(ExtrusionPropertyVisitorConst &visitor) const override { visitor.use(*this); }
};
// this store switch to activate/deactivate/enforce certain gcode feature like retract, lift, etc.
class ExtrusionPropertyModifier : public ExtrusionProperty
{
public:
// enforce a blind travel to the first point of the extrusion, even if the processor think it don't move
bool enforce_travel = false;
bool enforce_retraction = false;
bool enforce_unlift = false;
bool disable_retraction = false;
bool disable_lift = false;
bool toolchange_retraction = false;
ExtrusionPropertyModifier() {}
ExtrusionPropertyModifier &set_enforce_travel(bool enforce = true) {
enforce_travel = enforce;
return *this;
}
ExtrusionPropertyModifier &set_enforce_retraction(bool enforce = true) {
enforce_retraction = enforce;
return *this;
}
ExtrusionPropertyModifier &set_enforce_unlift(bool enforce = true) {
enforce_unlift = enforce;
return *this;
}
ExtrusionPropertyModifier &set_disable_retraction(bool disable = true) {
disable_retraction = disable;
return *this;
}
ExtrusionPropertyModifier &set_disable_lift(bool disable = true) {
disable_lift = disable;
return *this;
}
ExtrusionPropertyModifier &set_toolchange_retraction(bool is = true) {
toolchange_retraction = is;
return *this;
}
std::unique_ptr<ExtrusionProperty> clone() const override {
return std::make_unique<ExtrusionPropertyModifier>(*this);
}
void visit(ExtrusionPropertyVisitor &visitor) override { visitor.use(*this); }
void visit(ExtrusionPropertyVisitorConst &visitor) const override { visitor.use(*this); }
};
class ExtrusionPropertyCustomGcode : public ExtrusionProperty
{
public:
enum class Code {
GCODE,
COMMENT, // the string is a comment to put at the end of the lines. only if verbose.
};
Code code;
std::string gcode;
ExtrusionPropertyCustomGcode(const std::string &str) : gcode(str), code(Code::GCODE) {
if (!str.empty() && str[0] == ';') {
code = Code::COMMENT;
if (str.size() > 1 && str[1] == ' ') {
gcode = gcode.substr(2);
} else {
gcode = gcode.substr(1);
}
}
}
ExtrusionPropertyCustomGcode(Code c, const std::string &str) : gcode(str), code(c) {}
std::unique_ptr<ExtrusionProperty> clone() const override { return std::make_unique<ExtrusionPropertyCustomGcode>(*this); }
void visit(ExtrusionPropertyVisitor &visitor) override { visitor.use(*this); }
void visit(ExtrusionPropertyVisitorConst &visitor) const override { visitor.use(*this);}
};
// these are one-shot. They are not a state
class ExtrusionPropertySpecialCommand : public ExtrusionProperty
{
public:
enum class Code {
TOOLCHANGE, // to tool 'extra_data' (uint16_t)
SAVE_AND_RESET_SPEED_RATIO, // also set new speed ratio to extra_data (1 = 100%)
RESTORE_SPEED_RATIO,
FLUSH_PLANNER_QUEUE,
EXTRUSION, // only e move, by extra_data mm
RETRACT, // only e move, by extra_data mm, but taggued retract/unretract
//WIPE_RETRACT_LIFT, //trigger auto-wipe, retract & lift, like before a travel
PAUSE, // pause (G4) for extra_data miliseconds (int)
//SET_TEMP, // for extra_data °C should be done via ExtrusionPropertySpeed.temperature
WAIT_FOR_TEMP, // wait for current temperature, given by ExtrusionPropertySpeed
DISABLE_PREVIEW,
ENABLE_PREVIEW,
EXTRUDER_CURRENT, // set extruder trimpot to extra_data
};
Code code;
double extra_data; // idx of new tool, set speed ratio, etc.
ExtrusionPropertySpecialCommand(Code c) : code(c), extra_data(0) {}
ExtrusionPropertySpecialCommand(Code c, double data) : code(c), extra_data(data) {}
std::unique_ptr<ExtrusionProperty> clone() const override { return std::make_unique<ExtrusionPropertySpecialCommand>(*this); }
void visit(ExtrusionPropertyVisitor &visitor) override { visitor.use(*this); }
void visit(ExtrusionPropertyVisitorConst &visitor) const override { visitor.use(*this);}
};
// Old ExtruionPath::ExtrusionAttributes::OverhangAttributes is now an ExtrusionProperty
class ExtrusionPropertyOverhang : public ExtrusionProperty
{
public:
float start_distance_from_prev_layer = -1; // mm
float end_distance_from_prev_layer = -1; // mm
float proximity_to_curled_lines = 0; // value between 0 and 1
bool has_full_overhangs_flow = false;
bool has_full_overhangs_speed = false;
bool has_dynamic_overhangs_flow = false;
bool has_dynamic_overhangs_speed = false;
ExtrusionPropertyOverhang() {}
ExtrusionPropertyOverhang(float start_dist, float end_dist)
: start_distance_from_prev_layer(start_dist), end_distance_from_prev_layer(end_dist) {}
ExtrusionPropertyOverhang(float start_dist, float end_dist, float curled_ratio)
: start_distance_from_prev_layer(start_dist)
, end_distance_from_prev_layer(end_dist)
, proximity_to_curled_lines(curled_ratio) {}
ExtrusionPropertyOverhang(float start_dist, float end_dist, float curled_ratio, bool full_flow, bool full_speed, bool dynamic_flow, bool dynamic_speed)
: start_distance_from_prev_layer(start_dist)
, end_distance_from_prev_layer(end_dist)
, proximity_to_curled_lines(curled_ratio)
, has_full_overhangs_flow(full_flow)
, has_full_overhangs_speed(full_speed)
, has_dynamic_overhangs_flow(dynamic_flow)
, has_dynamic_overhangs_speed(dynamic_speed) {}
std::unique_ptr<ExtrusionProperty> clone() const override { return std::make_unique<ExtrusionPropertyOverhang>(*this); }
void visit(ExtrusionPropertyVisitor &visitor) override { visitor.use(*this); }
void visit(ExtrusionPropertyVisitorConst &visitor) const override { visitor.use(*this);}
};
// Old ExtruionPath3D offset are now blended in the ExtrusionPath (the ArcPolyline has the offsets
// this property is to change the plane of an ee.
class ExtrusionPropertyZOffset : public ExtrusionProperty
{
public:
coord_t z_offset; // 1 offset for evrything or an offset for each point
ExtrusionPropertyZOffset() {}
// one z for the whole entity
ExtrusionPropertyZOffset(coord_t offset) : z_offset(offset) {}
std::unique_ptr<ExtrusionProperty> clone() const override { return std::make_unique<ExtrusionPropertyZOffset>(*this); }
void visit(ExtrusionPropertyVisitor &visitor) override { visitor.use(*this); }
void visit(ExtrusionPropertyVisitorConst &visitor) const override { visitor.use(*this);}
};
class ExtrusionEntity
{
protected:
static inline std::atomic_int64_t id_generator;
uint64_t m_id; // for travel map
static inline std::atomic_int32_t id_generator;
uint32_t m_id; // for travel map
// even if no_sort, allow to reverse() us (and our entities if they allow it, but they should)
bool m_can_reverse;
bool m_can_reverse; //TODO: use (int64_t) m_id sign to embed this property, currently not an issue as 32+8 <= 64
// unique_ptr to avoid creating one empty one, most of the time there is nothing and it's lighter that way.
std::unique_ptr<ExtrusionProperty> m_property = nullptr;
ExtrusionEntity(bool can_reverse) : m_can_reverse(can_reverse) , m_id(++id_generator) {}
ExtrusionEntity(uint64_t id, bool can_reverse) : m_can_reverse(can_reverse), m_id(id) {}
ExtrusionEntity(std::unique_ptr<ExtrusionProperty> &&eprop, bool can_reverse)
: m_property(std::move(eprop)), m_can_reverse(can_reverse), m_id(++id_generator) {}
ExtrusionEntity(const ExtrusionEntity &rhs)
: m_can_reverse(rhs.m_can_reverse)
, m_id(rhs.m_id)
, m_property(rhs.m_property ? rhs.m_property->clone() : nullptr) {}
ExtrusionEntity(ExtrusionEntity &&rhs)
: m_can_reverse(rhs.m_can_reverse), m_id(rhs.m_id), m_property(std::move(rhs.m_property)) {}
ExtrusionEntity &operator=(const ExtrusionEntity &rhs) {
this->m_id = rhs.m_id;
this->m_can_reverse = rhs.m_can_reverse;
this->m_property = rhs.m_property ? rhs.m_property->clone() : nullptr;
return *this;
}
ExtrusionEntity &operator=(ExtrusionEntity &&rhs) {
this->m_id = rhs.m_id;
this->m_can_reverse = rhs.m_can_reverse;
this->m_property = std::move(rhs.m_property);
return *this;
}
public:
uint64_t get_id() const { return m_id; }
virtual ExtrusionRole role() const = 0;
virtual bool has_role(ExtrusionRole) const = 0;
virtual bool is_collection() const { return false; }
virtual bool is_loop() const { return false; }
virtual bool can_reverse() const { return m_can_reverse; }
@ -103,8 +395,65 @@ public:
virtual void visit(ExtrusionVisitorConst &visitor) const = 0;
void visit(ExtrusionVisitor &&visitor); // note: need 'using ExtrusionEntity::visit;' to be called from children classes
void visit(ExtrusionVisitorConst &&visitor) const;
bool has_properties() const { return m_property.operator bool(); }
std::unique_ptr<ExtrusionProperty> clone_properties() const;
ExtrusionProperty *get_root_property();
const ExtrusionProperty *get_root_property() const;
// take ownership
ExtrusionProperty &add_property(const ExtrusionProperty &attr);
void add_property(std::unique_ptr<ExtrusionProperty> &&attr);
void clear_properties() { m_property.reset(); }
};
// only cary an ExtrusionProperty
class ExtrusionNop : public ExtrusionEntity
{
ExtrusionRole m_role = ExtrusionRole::None;
public:
static Point NOT_A_POINT;
// this can have a position, to move the head.
Point position = NOT_A_POINT;
ExtrusionNop() : ExtrusionEntity(true) {}
ExtrusionNop(const ExtrusionNop& other) : ExtrusionEntity(other), m_role(other.m_role), position(other.position) {}
ExtrusionNop(ExtrusionNop&& other) : ExtrusionEntity(std::move(other)), m_role(other.m_role), position(std::move(other.position)) {}
ExtrusionNop(const ExtrusionProperty &attr) : ExtrusionEntity(true) { this->add_property(attr); }
ExtrusionNop &operator=(const ExtrusionNop &rhs) {
ExtrusionEntity::operator=(rhs);
this->m_role = rhs.m_role;
this->position = rhs.position;
return *this;
}
ExtrusionNop &operator=(ExtrusionNop &rhs) {
ExtrusionEntity::operator=(rhs);
this->m_role = rhs.m_role;
this->position = rhs.position;
return *this;
}
//ExtrusionNop(std::unique_ptr<ExtrusionProperty> sptr_attr) : ExtrusionEntity(true) { this->add_property(std::move(sptr_attr)); }
ExtrusionRole role() const override { return m_role; }
void set_role(ExtrusionRole new_role) { m_role = new_role; }
bool has_role(ExtrusionRole test_role) const override { return (m_role & test_role) == test_role; }
ExtrusionEntity *clone() const override { return new ExtrusionNop(*this); }
// Create a new object, initialize it with this object using the move semantics.
virtual ExtrusionEntity* clone_move() { return new ExtrusionNop(std::move(*this)); }
void reverse() override {}
const Point &first_point() const override { return position; }
const Point& last_point() const override { return position; }
const Point& middle_point() const override { return position; }
void polygons_covered_by_width(Polygons &out, const float scaled_epsilon) const override {}
void polygons_covered_by_spacing(Polygons &out, const float spacing_ratio, const float scaled_epsilon) const override {}
Polygons polygons_covered_by_width(const float scaled_epsilon = 0.f) const override { return {}; }
Polygons polygons_covered_by_spacing(const float spacing_ratio, const float scaled_epsilon) const override { return {}; }
ArcPolyline as_polyline() const override { return {}; }
void collect_polylines(ArcPolylines &dst) const override {}
void collect_points(Points &dst) const override {}
coordf_t length() const override { return 0; }
bool empty() const override { return true; }
double total_volume() const override { return 0; }
void visit(ExtrusionVisitor &visitor) override { visitor.use(*this); }
void visit(ExtrusionVisitorConst &visitor) const override { visitor.use(*this); }
};
//FIXME: this is unsafe. it's a collection of row pointer that isn't ours
using ExtrusionEntitiesPtr = std::vector<ExtrusionEntity*>;
@ -133,6 +482,7 @@ private:
//FIXME: this is still unsafe. it's a collection of unsafe container.
using ExtrusionEntityReferences = std::vector<ExtrusionEntityReference>;
//TODO: convert ExtrusionFlow to ExtrusionProperty
struct ExtrusionFlow
{
ExtrusionFlow() = default;
@ -141,7 +491,11 @@ struct ExtrusionFlow
ExtrusionFlow(const Flow &flow) :
mm3_per_mm(flow.mm3_per_mm()), width(flow.width()), height(flow.height()) {}
void set_force_e_per_mm() { this->height = -2; }
bool force_e_per_mm() const { return this->height == -2; }
// Volumetric velocity. mm^3 of plastic per mm of linear head motion. Used by the G-code generator.
// !!! if height == -2, then mm3_per_mm is changed into e_per_mm (used for exact unretraction) !!! (very unsafe, don't use it for normal extrusions)
double mm3_per_mm{ -1. };
// Width of the extrusion, used for visualization purposes & for seam notch %. Unscaled
float width{ -1.f };
@ -154,32 +508,18 @@ inline bool operator==(const ExtrusionFlow &lhs, const ExtrusionFlow &rhs)
return lhs.mm3_per_mm == rhs.mm3_per_mm && lhs.width == rhs.width && lhs.height == rhs.height;
}
struct OverhangAttributes {
float start_distance_from_prev_layer;
float end_distance_from_prev_layer;
float proximity_to_curled_lines; //value between 0 and 1
bool has_full_overhangs_flow = false;
bool has_full_overhangs_speed = false;
bool has_dynamic_overhangs_flow = false;
bool has_dynamic_overhangs_speed = false;
};
// move it into extrusion path, it's only used by it?
struct ExtrusionAttributes : ExtrusionFlow
{
ExtrusionAttributes() = default;
ExtrusionAttributes(ExtrusionRole role) : role{ role } {}
ExtrusionAttributes(ExtrusionRole role, const Flow &flow) : role{ role }, ExtrusionFlow{ flow } {}
ExtrusionAttributes(ExtrusionRole role, const ExtrusionFlow &flow) : role{ role }, ExtrusionFlow{ flow } {}
ExtrusionAttributes(ExtrusionRole role, const ExtrusionFlow &flow, OverhangAttributes overhang)
: role{role}, ExtrusionFlow{flow}, overhang_attributes(overhang) {}
// What is the role / purpose of this extrusion?
ExtrusionRole role{ ExtrusionRole::None };
// set to true to prevent seam on this path.
bool no_seam = false;
// OVerhangAttributes are currently computed for perimeters if dynamic overhangs are enabled.
// They are used to control fan and print speed in export.
std::optional<OverhangAttributes> overhang_attributes;
};
inline bool operator==(const ExtrusionAttributes &lhs, const ExtrusionAttributes &rhs)
@ -192,22 +532,40 @@ class ExtrusionPath : public ExtrusionEntity
{
public:
ArcPolyline polyline; //TODO: protected
// force to set the ExtrusionProperty (to nullptr) to be sure you didn't forget it
//ExtrusionPath(ExtrusionRole role) : ExtrusionEntity(true), m_attributes{role} {}
ExtrusionPath(const ExtrusionAttributes &attributes, bool can_reverse = true) : ExtrusionEntity(can_reverse), m_attributes(attributes) {}
ExtrusionPath(const ExtrusionPath &rhs) : ExtrusionEntity(rhs.m_id, rhs.m_can_reverse), polyline(rhs.polyline), m_attributes(rhs.m_attributes) {}
ExtrusionPath(ExtrusionPath &&rhs) : ExtrusionEntity(rhs.m_id, rhs.m_can_reverse), polyline(std::move(rhs.polyline)), m_attributes(rhs.m_attributes) {}
ExtrusionPath(const ArcPolyline &polyline, const ExtrusionAttributes &attribs, bool can_reverse = true) : ExtrusionEntity(can_reverse), polyline(polyline), m_attributes(attribs) {}
ExtrusionPath(ArcPolyline &&polyline, const ExtrusionAttributes &attribs, bool can_reverse = true) : ExtrusionEntity(can_reverse), polyline(std::move(polyline)), m_attributes(attribs) {}
//ExtrusionPath(const ExtrusionAttributes &attributes, bool can_reverse = true) : ExtrusionEntity(can_reverse), m_attributes(attributes) {}
ExtrusionPath(const ExtrusionAttributes &attributes,
std::unique_ptr<ExtrusionProperty> &&eprop,
bool can_reverse = true)
: ExtrusionEntity(std::move(eprop), can_reverse), m_attributes(attributes) {}
ExtrusionPath(const ExtrusionPath &rhs) : ExtrusionEntity(rhs), polyline(rhs.polyline), m_attributes(rhs.m_attributes) {}
ExtrusionPath(ExtrusionPath &&rhs) : ExtrusionEntity(rhs), polyline(std::move(rhs.polyline)), m_attributes(rhs.m_attributes) {}
//ExtrusionPath(const ArcPolyline &polyline, const ExtrusionAttributes &attribs, bool can_reverse = true)
//: ExtrusionEntity(can_reverse), polyline(polyline), m_attributes(attribs) {}
//ExtrusionPath(ArcPolyline &&polyline, const ExtrusionAttributes &attribs, bool can_reverse = true)
//: ExtrusionEntity(can_reverse), polyline(std::move(polyline)), m_attributes(attribs) {}
ExtrusionPath(const ArcPolyline &polyline,
const ExtrusionAttributes &attribs,
std::unique_ptr<ExtrusionProperty> &&eprop,
bool can_reverse = true)
: ExtrusionEntity(std::move(eprop), can_reverse), polyline(polyline), m_attributes(attribs) {}
ExtrusionPath(ArcPolyline &&polyline,
const ExtrusionAttributes &attribs,
std::unique_ptr<ExtrusionProperty> &&eprop,
bool can_reverse = true)
: ExtrusionEntity(std::move(eprop),can_reverse)
, polyline(std::move(polyline))
, m_attributes(attribs) {}
ExtrusionPath &operator=(const ExtrusionPath &rhs) {
this->m_can_reverse = rhs.m_can_reverse;
ExtrusionEntity::operator=(rhs);
this->polyline = rhs.polyline;
m_attributes = rhs.m_attributes;
return *this;
}
ExtrusionPath &operator=(ExtrusionPath &&rhs) {
this->m_can_reverse = rhs.m_can_reverse;
ExtrusionEntity::operator=(rhs);
this->polyline = std::move(rhs.polyline);
m_attributes = rhs.m_attributes;
return *this;
@ -237,12 +595,14 @@ public:
const ExtrusionAttributes& attributes() const { return m_attributes; }
ExtrusionRole role() const override { return m_attributes.role; }
bool has_role(ExtrusionRole test_role) const override { return (m_attributes.role & test_role) == test_role; }
float width() const { return m_attributes.width; }
float height() const { return m_attributes.height; }
double mm3_per_mm() const { return m_attributes.mm3_per_mm; }
// Minimum volumetric velocity of this extrusion entity. Used by the constant nozzle pressure algorithm.
double min_mm3_per_mm() const { return m_attributes.mm3_per_mm; }
std::optional<OverhangAttributes>& overhang_attributes_mutable() { return m_attributes.overhang_attributes; }
ExtrusionPropertyOverhang &overhang_attributes_mutable();
const ExtrusionPropertyOverhang *overhang_attributes() const; // can be null if not present
ExtrusionAttributes& attributes_mutable() { return m_attributes; }
void set_role(ExtrusionRole new_role) { m_attributes.role = new_role; }
@ -288,6 +648,7 @@ public:
typedef std::vector<ExtrusionPath> ExtrusionPaths;
ExtrusionPaths clip_end(ExtrusionPaths& paths, coordf_t distance);
//TODO remove, replaced by ExtrusionPropertyZOffset
class ExtrusionPath3D : public ExtrusionPath {
protected:
void init() {
@ -299,7 +660,12 @@ public:
std::vector<coord_t> z_offsets;
//ExtrusionPath3D(ExtrusionRole role) : ExtrusionPath(role) { /*std::cout << "new path3D\n"; */};
ExtrusionPath3D(const ExtrusionAttributes &attributes, bool can_reverse) : ExtrusionPath(attributes, can_reverse) { init(); };
ExtrusionPath3D(const ExtrusionAttributes &attributes,
std::unique_ptr<ExtrusionProperty> &&eprop,
bool can_reverse)
: ExtrusionPath(attributes, std::move(eprop), can_reverse) {
init();
};
ExtrusionPath3D(const ExtrusionPath &rhs) : ExtrusionPath(rhs) { init(); }
ExtrusionPath3D(ExtrusionPath &&rhs) : ExtrusionPath(rhs) { init(); }
ExtrusionPath3D(const ExtrusionPath3D &rhs) : ExtrusionPath(rhs), z_offsets(rhs.z_offsets) { init(); }
@ -308,17 +674,13 @@ public:
ExtrusionPath3D &operator=(const ExtrusionPath3D &rhs)
{
this->m_can_reverse = rhs.m_can_reverse;
this->m_attributes = rhs.m_attributes;
this->polyline = rhs.polyline;
ExtrusionPath::operator=(rhs);
z_offsets = rhs.z_offsets;
return *this;
}
ExtrusionPath3D &operator=(ExtrusionPath3D &&rhs)
{
this->m_can_reverse = rhs.m_can_reverse;
this->m_attributes = rhs.m_attributes;
this->polyline = std::move(rhs.polyline);
ExtrusionPath::operator=(rhs);
z_offsets = std::move(rhs.z_offsets);
return *this;
}
@ -345,24 +707,25 @@ typedef std::vector<ExtrusionPath3D> ExtrusionPaths3D;
// Single continuous extrusion path, possibly with varying extrusion thickness, extrusion height or bridging / non bridging.
// it's like an unsortable collection of only unreversable THING
// note: the ExtrusionProperty of a multipath is applied to each path, properties of a path is not transfered to the next one.
template <typename THING = ExtrusionEntity>
class ExtrusionMultiEntity : public ExtrusionEntity {
public:
std::vector<THING> paths;
ExtrusionMultiEntity(): ExtrusionEntity(false) {};
ExtrusionMultiEntity(const ExtrusionMultiEntity &rhs) : paths(rhs.paths), ExtrusionEntity(rhs.m_id, rhs.m_can_reverse) {}
ExtrusionMultiEntity(ExtrusionMultiEntity &&rhs) : paths(std::move(rhs.paths)), ExtrusionEntity(rhs.m_id, rhs.m_can_reverse) {}
ExtrusionMultiEntity(const ExtrusionMultiEntity &rhs) : paths(rhs.paths), ExtrusionEntity(rhs) {}
ExtrusionMultiEntity(ExtrusionMultiEntity &&rhs) : paths(std::move(rhs.paths)), ExtrusionEntity(rhs) {}
ExtrusionMultiEntity(const std::vector<THING> &paths) : paths(paths), ExtrusionEntity(false) {};
ExtrusionMultiEntity(const THING &path): ExtrusionEntity(false) { this->paths.push_back(path); }
ExtrusionMultiEntity &operator=(const ExtrusionMultiEntity &rhs) {
this->m_can_reverse = rhs.m_can_reverse;
ExtrusionEntity::operator=(rhs);
this->paths = rhs.paths;
return *this;
}
ExtrusionMultiEntity &operator=(ExtrusionMultiEntity &&rhs) {
this->m_can_reverse = rhs.m_can_reverse;
ExtrusionEntity::operator=(rhs);
this->paths = std::move(rhs.paths);
return *this;
}
@ -387,6 +750,15 @@ public:
}
return role;
}
bool has_role(ExtrusionRole test_role) const override {
if (this->paths.empty())
return false;
for (const ExtrusionPath &path : this->paths)
if (path.has_role(test_role)) {
return true;
}
return false;
}
// Is it really what you can call a middle point?:
@ -454,12 +826,12 @@ public:
ExtrusionMultiPath(const ExtrusionPath &path) :ExtrusionMultiEntity(path) {}
ExtrusionMultiPath &operator=(const ExtrusionMultiPath &rhs) {
this->m_can_reverse = rhs.m_can_reverse;
ExtrusionEntity::operator=(rhs);
this->paths = rhs.paths;
return *this;
}
ExtrusionMultiPath &operator=(ExtrusionMultiPath &&rhs) {
this->m_can_reverse = rhs.m_can_reverse;
ExtrusionEntity::operator=(rhs);
this->paths = std::move(rhs.paths);
return *this;
}
@ -483,8 +855,16 @@ public:
ExtrusionMultiPath3D(const ExtrusionPaths3D &paths) : ExtrusionMultiEntity(paths) {};
ExtrusionMultiPath3D(const ExtrusionPath3D &path) :ExtrusionMultiEntity(path) {}
ExtrusionMultiPath3D& operator=(const ExtrusionMultiPath3D& rhs) { this->paths = rhs.paths; return *this; }
ExtrusionMultiPath3D& operator=(ExtrusionMultiPath3D&& rhs) { this->paths = std::move(rhs.paths); return *this; }
ExtrusionMultiPath3D &operator=(const ExtrusionMultiPath3D &rhs) {
ExtrusionEntity::operator=(rhs);
this->paths = rhs.paths;
return *this;
}
ExtrusionMultiPath3D &operator=(ExtrusionMultiPath3D &&rhs) {
ExtrusionEntity::operator=(rhs);
this->paths = std::move(rhs.paths);
return *this;
}
virtual ExtrusionMultiPath3D* clone() const override { return new ExtrusionMultiPath3D(*this); }
virtual ExtrusionMultiPath3D* clone_move() override { return new ExtrusionMultiPath3D(std::move(*this)); }
@ -499,11 +879,13 @@ public:
};
// Single continuous extrusion loop, possibly with varying extrusion thickness, extrusion height or bridging / non bridging.
// note: the ExtrusionProperty of a multipath is applied to each path, properties of a path is not transfered to the next one.
class ExtrusionLoop : public ExtrusionEntity
{
public:
ExtrusionPaths paths;
//ExtrusionLoop(const ExtrusionLoop& rhs) : ExtrusionEntity(rhs), paths(rhs.paths), m_loop_role(rhs.m_loop_role) {}
ExtrusionLoop(ExtrusionLoopRole role = elrDefault) : m_loop_role(role) , ExtrusionEntity(false) {}
ExtrusionLoop(const ExtrusionPaths &paths, ExtrusionLoopRole role = elrDefault) : paths(paths), m_loop_role(role), ExtrusionEntity(false) {
assert(!this->paths.empty());
@ -556,6 +938,7 @@ public:
// This used to be used to avoid placing seams on overhangs, but now the EdgeGrid is used instead.
//bool has_overhang_point(const Point &point) const;
ExtrusionRole role() const override;
bool has_role(ExtrusionRole test_role) const override;
ExtrusionLoopRole loop_role() const { return m_loop_role; }
// Produce a list of 2D polygons covered by the extruded paths, offsetted by the extrusion width.
// Increase the offset by scaled_epsilon to achieve an overlap, so a union will produce no gaps.
@ -601,7 +984,7 @@ inline void extrusion_paths_append(ExtrusionPaths &dst, Polylines &polylines, co
for (Polyline &polyline : polylines) {
assert(polyline.is_valid());
if (polyline.is_valid())
dst.emplace_back(polyline, attributes, can_reverse);
dst.emplace_back(polyline, attributes, nullptr, can_reverse);
}
}
@ -611,7 +994,33 @@ inline void extrusion_paths_append(ExtrusionPaths &dst, Polylines &&polylines, c
for (Polyline &polyline : polylines) {
assert(polyline.is_valid());
if (polyline.is_valid())
dst.emplace_back(std::move(polyline), attributes, can_reverse);
dst.emplace_back(std::move(polyline), attributes, nullptr, can_reverse);
}
polylines.clear();
}
inline void extrusion_paths_append(ExtrusionPaths &dst,
Polylines &polylines,
const ExtrusionAttributes &attributes,
const ExtrusionPropertyOverhang &overhangs_attr,
bool can_reverse = true) {
dst.reserve(dst.size() + polylines.size());
for (Polyline &polyline : polylines) {
assert(polyline.is_valid());
if (polyline.is_valid())
dst.emplace_back(polyline, attributes, overhangs_attr.clone(), can_reverse);
}
}
inline void extrusion_paths_append(ExtrusionPaths &dst,
Polylines &&polylines,
const ExtrusionAttributes &attributes,
const ExtrusionPropertyOverhang &overhangs_attr,
bool can_reverse = true) {
dst.reserve(dst.size() + polylines.size());
for (Polyline &polyline : polylines) {
assert(polyline.is_valid());
if (polyline.is_valid())
dst.emplace_back(std::move(polyline), attributes, overhangs_attr.clone(), can_reverse);
}
polylines.clear();
}
@ -766,12 +1175,34 @@ public:
};
class CreateBoundingBoxVisitor : public ExtrusionVisitorRecursive {
BoundingBox bb;
public:
using ExtrusionVisitorRecursive::use;
CreateBoundingBoxVisitor() {}
void use(ExtrusionPath &path) override {
for (const Geometry::ArcWelder::Segment & pt: path.polyline.get_arc()) {
bb.merge(pt.point);
}
}
void use(ExtrusionPath3D &path3D) override {
for (const Geometry::ArcWelder::Segment & pt: path3D.polyline.get_arc()) {
bb.merge(pt.point);
}
}
static inline BoundingBox create(ExtrusionEntity &ee) {
CreateBoundingBoxVisitor visitor;
ee.visit(visitor);
return visitor.bb;
}
};
#ifdef _DEBUGINFO
struct LoopAssertVisitor : public ExtrusionVisitorRecursiveConst {
using ExtrusionVisitorRecursiveConst::use;
bool m_check_length;
LoopAssertVisitor() : m_check_length(true) {}
LoopAssertVisitor(bool check_length) : m_check_length(check_length) {}
coord_t m_check_length;
LoopAssertVisitor() : m_check_length(SCALED_EPSILON) {}
LoopAssertVisitor(coord_t check_length) : m_check_length(check_length) {}
virtual void default_use(const ExtrusionEntity& entity) override {};
virtual void use(const ExtrusionPath &path) override;
virtual void use(const ExtrusionLoop& loop) override;
@ -786,6 +1217,46 @@ struct LoopAssertVisitor : public ExtrusionVisitorRecursiveConst {
#endif
template<typename AttributeType>
class AddGetEEAttribute : public ExtrusionPropertyVisitor
{
static_assert(std::is_base_of<ExtrusionProperty, AttributeType>::value, "AttributeType must inherit ExtrusionProperty");
public:
using ExtrusionPropertyVisitor::use;
AttributeType *found = nullptr;
void default_use(ExtrusionProperty &thing) override {};
void use(AttributeType &prop) override { found = &prop;}
AttributeType &add_or_get(ExtrusionEntity &entity) {
if (entity.get_root_property()) {
entity.get_root_property()->visit(*this);
}
if (found) {
return *found;
} else {
AttributeType *new_speed = new AttributeType();
entity.add_property(std::unique_ptr<ExtrusionProperty>(new_speed));
return *new_speed;
}
}
};
template<typename AttributeType>
class GetEEAttribute : public ExtrusionPropertyVisitorConst
{
static_assert(std::is_base_of<ExtrusionProperty, AttributeType>::value, "AttributeType must inherit ExtrusionProperty");
public:
using ExtrusionPropertyVisitorConst::use;
const AttributeType *found = nullptr;
void default_use(const ExtrusionProperty &thing) override {};
void use(const AttributeType &prop) override { found = &prop;}
const AttributeType *get(const ExtrusionEntity &entity) {
if (entity.get_root_property()) {
entity.get_root_property()->visit(*this);
}
return found;
}
};
}
#endif

View file

@ -36,6 +36,7 @@ ExtrusionEntityCollection::ExtrusionEntityCollection(const ExtrusionPaths &paths
ExtrusionEntityCollection& ExtrusionEntityCollection::operator= (const ExtrusionEntityCollection &other)
{
this->m_property = other.m_property ? other.m_property->clone() : nullptr;
this->m_no_sort = other.m_no_sort;
this->m_can_reverse = other.m_can_reverse;
this->m_id = other.m_id;
@ -52,6 +53,31 @@ void ExtrusionEntityCollection::swap(ExtrusionEntityCollection &c)
std::swap(this->m_id, c.m_id);
}
ExtrusionRole ExtrusionEntityCollection::role() const
{
ExtrusionRole out{ ExtrusionRole::None };
for (const ExtrusionEntity *ee : m_entities) {
ExtrusionRole er = ee->role();
if (out == ExtrusionRole::None) {
out = er;
}else if (out != er) {
return ExtrusionRole::Mixed;
}
}
return out;
}
bool ExtrusionEntityCollection::has_role(ExtrusionRole test_role) const
{
if (this->entities().empty())
return false;
for (const ExtrusionEntity *entity : this->entities())
if (entity->has_role(test_role)) {
return true;
}
return false;
}
void ExtrusionEntityCollection::clear()
{
for (size_t i = 0; i < this->m_entities.size(); ++i)

View file

@ -49,8 +49,8 @@ public:
ExtrusionEntitiesPtr& set_entities() { return m_entities; }
ExtrusionEntityCollection() : m_no_sort(false), ExtrusionEntity(true) {}
ExtrusionEntityCollection(bool can_sort, bool can_reverse) : m_no_sort(!can_sort), ExtrusionEntity(can_reverse) {}
ExtrusionEntityCollection(const ExtrusionEntityCollection &other) : m_no_sort(other.m_no_sort), ExtrusionEntity(other.m_id, other.m_can_reverse) { this->append(other.entities()); }
ExtrusionEntityCollection(ExtrusionEntityCollection &&other) : m_entities(std::move(other.m_entities)), m_no_sort(other.m_no_sort), ExtrusionEntity(other.m_id, other.m_can_reverse) {}
ExtrusionEntityCollection(const ExtrusionEntityCollection &other) : m_no_sort(other.m_no_sort), ExtrusionEntity(other) { this->append(other.entities()); }
ExtrusionEntityCollection(ExtrusionEntityCollection &&other) : m_entities(std::move(other.m_entities)), m_no_sort(other.m_no_sort), ExtrusionEntity(other) {}
explicit ExtrusionEntityCollection(const ExtrusionPaths &paths);
ExtrusionEntityCollection& operator=(const ExtrusionEntityCollection &other);
ExtrusionEntityCollection& operator=(ExtrusionEntityCollection &&other) {
@ -79,30 +79,26 @@ public:
//ExtrusionEntitiesPtr::iterator end() { return this->entities.end(); }
bool is_collection() const override { return true; }
ExtrusionRole role() const override {
ExtrusionRole out{ ExtrusionRole::None };
for (const ExtrusionEntity *ee : m_entities) {
ExtrusionRole er = ee->role();
if (out == ExtrusionRole::None) {
out = er;
}else if (out != er) {
return ExtrusionRole::Mixed;
}
}
return out;
}
ExtrusionRole role() const override;
bool has_role(ExtrusionRole test_role) const override;
void set_can_sort_reverse(bool can_sort, bool can_reverse) { this->m_no_sort = !can_sort; this->m_can_reverse = can_reverse; }
bool can_sort() const { return !this->m_no_sort; }
bool can_reverse() const override { return can_sort() || this->m_can_reverse; }
void clear();
void swap (ExtrusionEntityCollection &c);
void append(const ExtrusionEntity &entity) { this->m_entities.emplace_back(entity.clone()); }
void append(ExtrusionEntity &&entity) { this->m_entities.emplace_back(entity.clone_move()); }
void append(const ExtrusionEntity &entity) { this->m_entities.push_back(entity.clone()); }
void append(ExtrusionEntity &&entity) { this->m_entities.push_back(entity.clone_move()); }
// take ownership, empty the container.
template<typename ENTITY> void append(std::unique_ptr<ENTITY> &entity)
{
static_assert(std::is_base_of<ExtrusionEntity, ENTITY>::value, "ENTITY not derived from ExtrusionEntity in ExtrusionCollection::append(unique_ptr<ENTITY>)");
this->m_entities.push_back(entity.release());
}
void append_at(ExtrusionEntity &&entity, size_t position) { assert(position <= m_entities.size()); this->m_entities.insert(this->m_entities.begin() + position, entity.clone_move()); }
void append(const ExtrusionEntitiesPtr &entities) {
this->m_entities.reserve(this->m_entities.size() + entities.size());
for (const ExtrusionEntity *ptr : entities)
this->m_entities.emplace_back(ptr->clone());
this->m_entities.push_back(ptr->clone());
}
void append(ExtrusionEntitiesPtr &&src) {
if (m_entities.empty())
@ -224,11 +220,11 @@ inline void extrusion_entities_append_paths(ExtrusionEntityCollection &dst, Poly
for (Polyline &polyline : polylines)
if (polyline.is_valid()) {
if (polyline.back() == polyline.front()) {
ExtrusionPath path(ExtrusionAttributes(role, ExtrusionFlow(mm3_per_mm, width, height)), can_reverse);
ExtrusionPath path(ExtrusionAttributes(role, ExtrusionFlow(mm3_per_mm, width, height)), nullptr, can_reverse);
path.polyline = polyline;
dst.append(ExtrusionLoop(std::move(path)));
} else {
ExtrusionPath extrusion_path(ExtrusionAttributes(role, ExtrusionFlow(mm3_per_mm, width, height)), can_reverse);
ExtrusionPath extrusion_path(ExtrusionAttributes(role, ExtrusionFlow(mm3_per_mm, width, height)), nullptr, can_reverse);
extrusion_path.polyline = polyline;
dst.append(std::move(extrusion_path));
}
@ -241,11 +237,11 @@ inline void extrusion_entities_append_paths(ExtrusionEntityCollection &dst, Poly
for (Polyline &polyline : polylines)
if (polyline.is_valid()) {
if (polyline.back() == polyline.front()) {
ExtrusionPath path(path_attr, can_reverse);
ExtrusionPath path(path_attr, nullptr, can_reverse);
path.polyline = polyline;
dst.append(ExtrusionLoop(std::move(path)));
} else {
ExtrusionPath extrusion_path(path_attr, can_reverse);
ExtrusionPath extrusion_path(path_attr, nullptr, can_reverse);
extrusion_path.polyline = std::move(polyline);
dst.append(std::move(extrusion_path));
}
@ -257,7 +253,7 @@ inline void extrusion_entities_append_loops(ExtrusionEntityCollection &dst, Poly
//dst.reserve(dst.size() + loops.size());
for (Polygon & polygon : loops) {
if (polygon.is_valid()) {
ExtrusionPath path(path_attr, can_reverse);
ExtrusionPath path(path_attr, nullptr, can_reverse);
path.polyline.append(polygon.points);
path.polyline.append(path.polyline.front());
dst.append(ExtrusionLoop(std::move(path)));
@ -270,7 +266,7 @@ inline void extrusion_entities_append_loops(ExtrusionEntityCollection &dst, Poly
//dst.reserve(dst.size() + loops.size());
for (Polygon &polygon : loops) {
if (polygon.is_valid()) {
ExtrusionPath path(path_attr, can_reverse);
ExtrusionPath path(path_attr, nullptr, can_reverse);
path.polyline.append(std::move(polygon.points));
path.polyline.append(path.polyline.front());
ExtrusionLoop loop(std::move(path));
@ -288,11 +284,11 @@ inline void extrusion_entities_append_loops_and_paths(ExtrusionEntityCollection
for (Polyline &polyline : polylines) {
if (polyline.is_valid()) {
if (polyline.is_closed()) {
ExtrusionPath extrusion_path(path_attr, can_reverse);
ExtrusionPath extrusion_path(path_attr, nullptr, can_reverse);
extrusion_path.polyline = std::move(polyline);
dst.append(ExtrusionLoop(std::move(extrusion_path)));
} else {
ExtrusionPath extrusion_path(path_attr, can_reverse);
ExtrusionPath extrusion_path(path_attr, nullptr, can_reverse);
extrusion_path.polyline = std::move(polyline);
dst.append(std::move(extrusion_path));
}

View file

@ -20,8 +20,7 @@ GCodeExtrusionRole extrusion_role_to_gcode_extrusion_role(ExtrusionRole role)
if (role == ExtrusionRole::None) return GCodeExtrusionRole::None;
if (role == ExtrusionRole::ExternalPerimeter) return GCodeExtrusionRole::ExternalPerimeter;
if (role == ExtrusionRole::Perimeter) return GCodeExtrusionRole::Perimeter;
if (role == ExtrusionRole::OverhangExternalPerimeter) return GCodeExtrusionRole::OverhangPerimeter;
if (role == ExtrusionRole::OverhangPerimeter) return GCodeExtrusionRole::OverhangPerimeter;
if (role.is_overhang()) return GCodeExtrusionRole::OverhangPerimeter;
if (role == ExtrusionRole::InternalInfill) return GCodeExtrusionRole::InternalInfill;
if (role == ExtrusionRole::SolidInfill) return GCodeExtrusionRole::SolidInfill;
if (role == ExtrusionRole::TopSolidInfill) return GCodeExtrusionRole::TopSolidInfill;
@ -33,7 +32,7 @@ GCodeExtrusionRole extrusion_role_to_gcode_extrusion_role(ExtrusionRole role)
if (role == ExtrusionRole::Skirt) return GCodeExtrusionRole::Skirt;
if (role == ExtrusionRole::SupportMaterial) return GCodeExtrusionRole::SupportMaterial;
if (role == ExtrusionRole::SupportMaterialInterface) return GCodeExtrusionRole::SupportMaterialInterface;
if (role == ExtrusionRole::WipeTower) return GCodeExtrusionRole::WipeTower;
if (role.is_wipetower()) return GCodeExtrusionRole::WipeTower;
if (role == ExtrusionRole::Milling) return GCodeExtrusionRole::Milling;
if (role == ExtrusionRole::Travel) return GCodeExtrusionRole::Travel;
assert(false);
@ -144,7 +143,7 @@ std::string role_to_code(ExtrusionRole role)
return L("Supp");
else if (role == ExtrusionRole::SupportMaterialInterface)
return L("SuppI");
else if (role == ExtrusionRole::WipeTower)
else if (role.is_wipetower())
return L("WTower");
else if (role == ExtrusionRole::Milling)
return L("Mill");

View file

@ -123,7 +123,8 @@ enum ExtrusionRoleModifier : uint16_t {
// Support material extrusion
ERM_Support = 1 << 2, //4
ERM_Skirt = 1 << 3, //8 //(brim if not external)
ERM_Wipe = 1 << 4, //16
// wipe tower alone -> moves.. ; with ERM_Solid -> wiping ; with ERM_Bridge -> ramming
ERM_WipeTower = 1 << 4, //16
ERM_Mill = 1 << 5, //32
// 2) Extrusion modifiers
ERM_External = 1 << 6, //64
@ -180,7 +181,7 @@ struct ExtrusionRole
{
private:
ExtrusionRoleModifier m;
static constexpr const ExtrusionRoleModifier BaseType{ERM_Perimeter | ERM_Infill | ERM_Support | ERM_Skirt | ERM_Wipe | ERM_Mill | ERM_Travel | ERM_Mixed};
static constexpr const ExtrusionRoleModifier BaseType{ERM_Perimeter | ERM_Infill | ERM_Support | ERM_Skirt | ERM_WipeTower | ERM_Mill | ERM_Travel | ERM_Mixed};
public:
ExtrusionRole() = delete;
ExtrusionRole(ExtrusionRoleModifier mods) : m(mods) {
@ -237,14 +238,21 @@ public:
// Support interface material, printed with soluble plastic.
static constexpr const ExtrusionRoleModifier SupportMaterialInterface{ExtrusionRoleModifier::ERM_Support |
ExtrusionRoleModifier::ERM_External};
// Wipe tower material.
static constexpr const ExtrusionRoleModifier WipeTower{ExtrusionRoleModifier::ERM_Wipe};
// Milling
static constexpr const ExtrusionRoleModifier Milling{ExtrusionRoleModifier::ERM_Mill};
// Extrusion role for a collection with multiple extrusion roles.
static constexpr const ExtrusionRoleModifier Mixed{ExtrusionRoleModifier::ERM_Mixed};
// Travel
static constexpr const ExtrusionRoleModifier Travel{ExtrusionRoleModifier::ERM_Travel};
// Wipe tower material.
// wieptower thingy
static constexpr const ExtrusionRoleModifier WipeTower{ExtrusionRoleModifier::ERM_WipeTower};
// wieptower ramming
static constexpr const ExtrusionRoleModifier WipeTowerRamming{ExtrusionRoleModifier::ERM_WipeTower |
ExtrusionRoleModifier::ERM_Bridge};
// wipetower wiping
static constexpr const ExtrusionRoleModifier WipeTowerWipe{ExtrusionRoleModifier::ERM_WipeTower |
ExtrusionRoleModifier::ERM_Solid};
bool is_perimeter() const { return (m & ExtrusionRoleModifier::ERM_Perimeter); }
bool is_external_perimeter() const { return this->is_perimeter() && this->is_external(); } // includes external overhang
@ -262,7 +270,8 @@ public:
// Brim is currently marked as skirt.
bool is_skirt() const { return (m & ExtrusionRoleModifier::ERM_Skirt); }
bool is_wipetower() const { return (m & ExtrusionRoleModifier::ERM_WipeTower); }
ExtrusionRole operator|(ExtrusionRole b) const { return ExtrusionRole(this->m | b.m); }
ExtrusionRole operator&(ExtrusionRole b) const { return ExtrusionRole(this->m & b.m); }

File diff suppressed because it is too large Load diff

View file

@ -183,11 +183,11 @@ double Fill::compute_unscaled_volume_to_fill(const Surface* surface, const FillP
if (this->no_overlap_expolygons.empty()) {
polyline_volume = unscaled(unscaled(surface->area())) * params.flow.height();
} else {
for (const ExPolygon& poly : intersection_ex(ExPolygons{ surface->expolygon }, this->no_overlap_expolygons)) {
for (const ExPolygon& poly : intersection_ex(ExPolygons{surface->expolygon}, this->no_overlap_expolygons)) {
polyline_volume += params.flow.height() * unscaled(unscaled(poly.area()));
//note: the no_overlap_expolygons is already at spacing from the centerline of the perimeter.
}
// note: the no_overlap_expolygons is already at spacing from the centerline of the perimeter.
}
}
return polyline_volume;
}
@ -308,7 +308,12 @@ void Fill::fill_surface_extrusion_with_gap_fill(const Surface *surface,
// check if not over-extruding
if (!params.dont_adjust && params.full_infill() && !params.flow.bridge() && params.fill_exactly) {
// compute the path of the nozzle -> extruded volume
double extruded_volume = ExtrusionVolume{}.get(*coll_nosort);
ExtrusionVolume compute_volume;
if (params.flow.spacing_ratio() != 1) {
Flow bigger_flow = Flow::new_from_spacing(params.flow.spacing(), params.flow.nozzle_diameter(), params.flow.height(), 1.f , false);
compute_volume.set_flow_mult(bigger_flow.mm3_per_mm() / params.flow.mm3_per_mm());
}
double extruded_volume = compute_volume.get(*coll_nosort);
// compute flow to remove spacing_ratio from the equation
// compute real volume to fill
double polyline_volume = compute_unscaled_volume_to_fill(surface, params);
@ -325,11 +330,11 @@ void Fill::fill_surface_extrusion_with_gap_fill(const Surface *surface,
#if _DEBUG
this->debug_verify_flow_mult = mult_flow;
#endif
}
mult_flow *= params.flow_mult;
if (mult_flow != 1) {
// apply to extrusions
ExtrusionModifyFlow{mult_flow}.set(*coll_nosort);
mult_flow *= params.flow_mult;
if (mult_flow != 1) {
// apply to extrusions
ExtrusionModifyFlow{mult_flow}.set(*coll_nosort);
}
}
} else {
#if _DEBUG
@ -3309,11 +3314,13 @@ static double evaluate_support_arch_cost(const Polyline &pl)
if (ymin > ymax)
std::swap(ymin, ymax);
double dmax = 0;
distf_t dmax = 0;
// Maximum distance in Y axis out of the (ymin, ymax) band and from the (front, back) line.
Linef line { front.cast<double>(), back.cast<double>() };
for (const Point &pt : pl.points)
dmax = std::max<double>(std::max(dmax, line_alg::distance_to(line, Vec2d(pt.cast<double>()))), std::max(pt.y() - ymax, ymin - pt.y()));
for (const Point &pt : pl.points) {
distf_t dist = std::sqrt(line_alg::distance_to_squared(line, Vec2d(pt.cast<double>())));
dmax = std::max<distf_t>(std::max(dmax, dist), distf_t(std::max(pt.y() - ymax, ymin - pt.y())));
}
return dmax;
}

View file

@ -95,7 +95,7 @@ void append_loop_into_collection(ExtrusionEntityCollection& storage, ExtrusionRo
if (ensure_valid(polygon, params.fill_resolution)) {
//default to ccw
polygon.make_counter_clockwise();
ExtrusionPath path(ExtrusionAttributes{good_role, ExtrusionFlow{flow, float(width), float(height)}}, false);
ExtrusionPath path(ExtrusionAttributes{good_role, ExtrusionFlow{flow, float(width), float(height)}}, nullptr, false);
path.polyline.append(std::move(polygon.points));
path.polyline.append(path.polyline.front());
storage.append(ExtrusionLoop{ std::move(path) });

View file

@ -3395,7 +3395,7 @@ FillRectilinearSawtooth::fill_surface_extrusion(const Surface *surface, const Fi
extrusions->paths.push_back(ExtrusionPath3D(ExtrusionAttributes{good_role,
{params.flow.mm3_per_mm() * params.flow_mult,
params.flow.width() * params.flow_mult, params.flow.height()}},
false));
nullptr, false));
ExtrusionPath3D *current_extrusion = &(extrusions->paths.back());
const Points &pts = poly.points;
coord_t next_zhop = tooth_spacing_min + (coord_t)abs((safe_rand() / (float)RAND_MAX) * (tooth_spacing_max - tooth_spacing_min));
@ -3441,7 +3441,7 @@ FillRectilinearSawtooth::fill_surface_extrusion(const Surface *surface, const Fi
ExtrusionPath3D(ExtrusionAttributes{good_role,
{params.flow.nozzle_diameter() * params.flow.nozzle_diameter() * PI / 4,
params.flow.nozzle_diameter(), params.flow.nozzle_diameter()}},
false));
nullptr, false));
current_extrusion = &(extrusions->paths.back());
current_extrusion->push_back(last, 0);
current_extrusion->push_back(last, tooth_zhop);
@ -3450,7 +3450,7 @@ FillRectilinearSawtooth::fill_surface_extrusion(const Surface *surface, const Fi
extrusions->paths.push_back(
ExtrusionPath3D(ExtrusionAttributes{good_role,
{0, params.flow.nozzle_diameter() / 10, params.flow.nozzle_diameter() / 10}},
false));
nullptr, false));
current_extrusion = &(extrusions->paths.back());
//add first point
current_extrusion->push_back(last, tooth_zhop);
@ -3464,7 +3464,7 @@ FillRectilinearSawtooth::fill_surface_extrusion(const Surface *surface, const Fi
ExtrusionPath3D(ExtrusionAttributes{good_role,
{params.flow.mm3_per_mm() / std::sqrt(2),
float(params.flow.width() / std::sqrt(2)), params.flow.height()}},
false));
nullptr, false));
current_extrusion = &(extrusions->paths.back());
current_extrusion->push_back(last, tooth_zhop);
//add next point at scaled_nozzle_diam distance
@ -3477,7 +3477,7 @@ FillRectilinearSawtooth::fill_surface_extrusion(const Surface *surface, const Fi
ExtrusionPath3D(ExtrusionAttributes{good_role,
{params.flow.mm3_per_mm() * params.flow_mult,
params.flow.width() * params.flow_mult, params.flow.height()}},
false));
nullptr, false));
current_extrusion = &(extrusions->paths.back());
//add first point
current_extrusion->push_back(last, 0);

View file

@ -58,7 +58,7 @@ DistanceField::DistanceField(const coord_t& radius, const Polygons& current_outl
if (contour.size() > 2) {
Point prev = contour.points.back();
for (const Point &p2 : contour.points) {
d2 = std::min(d2, Line::distance_to_squared(sp, prev, p2));
d2 = std::min(d2, Line::distance_to_squared_abp(prev, p2, sp));
prev = p2;
}
}

View file

@ -135,7 +135,7 @@ GroundingLocation Layer::getBestGroundingLocation
Point prev = contour.points.back();
for (const Point &p2 : contour.points) {
Point closest_point;
if (double d = line_alg::distance_to_squared(Line{prev, p2}, unsupported_location, &closest_point); d < d2) {
if (double d = Line::distance_to_squared_abp(prev, p2, unsupported_location, &closest_point); d < d2) {
d2 = d;
node_location = closest_point;
}

View file

@ -255,7 +255,7 @@ Node::RectilinearJunction Node::straighten(
const NodeSPtr& parent_node = m_parent.lock();
if (parent_node &&
(child_p->m_p - parent_node->m_p).cast<int64_t>().squaredNorm() < max_remove_colinear_dist2 &&
Line::distance_to_squared(m_p, parent_node->m_p, child_p->m_p) < close_enough * close_enough) {
Line::distance_to_squared_abp(parent_node->m_p, child_p->m_p, m_p) < close_enough * close_enough) {
child_p->m_parent = m_parent;
for (auto& sibling : parent_node->m_children)
{ // find this node among siblings

View file

@ -12,7 +12,6 @@
#include "I18N.hpp"
#include "Print.hpp"
#include "Layer.hpp"
#include "Layer.hpp"
#include <cassert>
#include <cmath>
@ -27,6 +26,10 @@ FlowErrorNegativeSpacing::FlowErrorNegativeSpacing() :
FlowErrorNegativeFlow::FlowErrorNegativeFlow() :
FlowError("Flow::mm3_per_mm() produced negative flow. Did you set some extrusion width too small, or the (maximum) layer height too high?") {}
coord_t Flow::scaled_height() const {
return Layer::scale_to_layer_coord(this->m_height);
}
// This static method returns a sane extrusion width default.
float Flow::auto_extrusion_width(FlowRole role, float nozzle_diameter)
{

View file

@ -76,6 +76,7 @@ public:
// Non bridging flow: Layer height.
// Bridging flow: Bridge thread diameter = layer height.
float height() const { return m_height; }
coord_t scaled_height() const;
// Spacing between the extrusion centerlines.
float spacing() const;// { return m_spacing; } use the compute, as I can't be 100% sure yet that this cachced value is good.
coord_t scaled_spacing() const { return scale_t(spacing()); }
@ -163,7 +164,7 @@ private:
// // Gap fill violates this condition.
// //assert(width >= height);
// }
//TODO: change from float to coord_t
float m_width { 0 };
float m_height { 0 };
float m_spacing { 0 };

View file

@ -1704,7 +1704,7 @@ namespace Slic3r {
type = static_cast<CustomGCode::Type>(tree.get<int>("<xmlattr>.type"));
extra = tree.get<std::string>("<xmlattr>.extra", "");
}
m_model->custom_gcode_per_print_z.gcodes.push_back(CustomGCode::Item{print_z, type, extruder, color, extra}) ;
m_model->custom_gcode_per_print_z.gcodes.push_back(CustomGCode::Item{Layer::scale_to_layer_coord(print_z), type, extruder, color, extra}) ;
}
}
}
@ -4010,7 +4010,7 @@ bool _3MF_Exporter::_add_custom_gcode_per_print_z_file_to_archive( mz_zip_archiv
pt::ptree& code_tree = main_tree.add("code", "");
// store data of custom_gcode_per_print_z
code_tree.put("<xmlattr>.print_z" , code.print_z );
code_tree.put("<xmlattr>.print_z" , unscaled(code.print_z_) );
code_tree.put("<xmlattr>.type" , static_cast<int>(code.type));
code_tree.put("<xmlattr>.extruder" , code.extruder );
code_tree.put("<xmlattr>.color" , code.color );

View file

@ -713,7 +713,7 @@ void AMFParserContext::endElement(const char * /* name */)
CustomGCode::Type type = static_cast<CustomGCode::Type>(atoi(m_value[3].c_str()));
const std::string& extra= m_value[4];
m_model.custom_gcode_per_print_z.gcodes.push_back(CustomGCode::Item{print_z, type, extruder, color, extra});
m_model.custom_gcode_per_print_z.gcodes.push_back(CustomGCode::Item{Layer::scale_to_layer_coord(print_z), type, extruder, color, extra});
for (std::string& val: m_value)
val.clear();
@ -1353,7 +1353,7 @@ bool store_amf(std::string &path, Model *model, const DynamicPrintConfig *config
{
pt::ptree& code_tree = main_tree.add("code", "");
// store custom_gcode_per_print_z gcodes information
code_tree.put("<xmlattr>.print_z" , code.print_z );
code_tree.put("<xmlattr>.print_z" , unscaled(code.print_z_) );
code_tree.put("<xmlattr>.type" , static_cast<int>(code.type));
code_tree.put("<xmlattr>.extruder" , code.extruder );
code_tree.put("<xmlattr>.info" , code.color );

View file

@ -171,7 +171,7 @@ void HFP::set_custom_gcode_z(Model &model) const {
if (!m_filament_set.empty()) {
for (int i = 0; i < m_filament_set.size(); i++) {
model.custom_gcode_per_print_z.gcodes.push_back(CustomGCode::Item{m_layer_height * m_slider_values[i],
model.custom_gcode_per_print_z.gcodes.push_back(CustomGCode::Item{Layer::scale_to_layer_coord(m_layer_height * m_slider_values[i]),
type, extruder, m_filament_set[i].Color,
extra});
}

File diff suppressed because it is too large Load diff

View file

@ -36,6 +36,7 @@
#include "GCode/RetractWhenCrossingPerimeters.hpp"
// #include "GCode/SmoothPath.hpp"
#include "GCode/SpiralVase.hpp"
#include "GCode/TemperatureMover.hpp"
#include "GCode/ToolOrdering.hpp"
#include "GCode/Wipe.hpp"
#include "GCode/WipeTowerIntegration.hpp"
@ -101,11 +102,23 @@ namespace GCode {
struct ObjectLayerToPrint
{
ObjectLayerToPrint() : object_layer(nullptr), support_layer(nullptr) {}
const Layer* object_layer;
const SupportLayer* support_layer;
const Layer* layer() const { return (object_layer != nullptr) ? object_layer : support_layer; }
const PrintObject* object() const { return (this->layer() != nullptr) ? this->layer()->object() : nullptr; }
coordf_t print_z() const { return (object_layer != nullptr && support_layer != nullptr) ? 0.5 * (object_layer->print_z + support_layer->print_z) : this->layer()->print_z; }
const Layer *object_layer;
const SupportLayer *support_layer;
// if filled, it restrict the islands needed to be printed (can be in support or/and object)
// used as adress check, so you can store nullptr.
std::set<const LayerSliceIsland*> islands;
// if mmu, extruder order override
std::vector<uint16_t> extruders_order;
// wipetower managment, for parallel object/islands
bool allow_wipe_tower = true; // allow to print wipetoer & finish wieptower layer
coord_t finish_wipe_tower_until = 0; // before printing anything, finish all unfinish wp layer until this z (should be <= _print_z())
const Layer *layer() const { return (object_layer != nullptr) ? object_layer : support_layer; }
const PrintObject *object() const { return (this->layer() != nullptr) ? this->layer()->object() : nullptr; }
coord_t _print_z() const {
assert(object_layer == nullptr || support_layer == nullptr ||
object_layer->scaled_print_z() == support_layer->scaled_print_z());
return this->layer()->scaled_print_z();
}
};
struct PrintObjectInstance
@ -119,7 +132,7 @@ struct PrintObjectInstance
} // namespace GCode
class GCodeGenerator : ExtrusionVisitorConst {
class GCodeGenerator : ExtrusionVisitorConst, ExtrusionPropertyVisitorConst {
public:
GCodeGenerator();
@ -133,7 +146,7 @@ public:
const Vec2d& origin() const { return m_origin; }
void set_origin(const Vec2d &pointf);
void set_origin(const coordf_t x, const coordf_t y) { this->set_origin(Vec2d(x, y)); }
uint16_t last_extruder() const { return m_writer.tool() ? m_writer.tool()->id() : size_t(0); }
uint16_t last_extruder(uint16_t def = 0) const { return m_writer.tool() ? uint16_t(m_writer.tool()->id()) : def; }
const Point& last_pos() const { assert(m_last_pos); return *m_last_pos; }
bool last_pos_defined() const { return m_last_pos.has_value(); }
void set_last_pos(const Point &pos) { m_last_pos = pos; }
@ -172,6 +185,7 @@ public:
Point gcode_to_point(const Vec2d &point) const;
const FullPrintConfig &config() const { return m_config; }
const Layer* layer() const { return m_layer; }
const Layer* current_z_layer() const { return m_pos_layer; }
GCodeWriter& writer() { return m_writer; }
const GCodeWriter& writer() const { return m_writer; }
PlaceholderParser& placeholder_parser() { return m_placeholder_parser_integration.parser; }
@ -241,10 +255,16 @@ private:
};
void _do_export(Print &print, GCodeOutputStream &file, ThumbnailsGeneratorCallback thumbnail_cb);
void _move_to_print_object(std::string& gcode_out, const Print& print, size_t finished_objects, uint16_t initial_extruder_id);
void _init_multiextruders(const Print& print, std::string& gcode_out, GCodeWriter& writer, const ToolOrdering& tool_ordering, const std::string& custom_gcode);
void _init_multiextruders(const Print& print, std::string& gcode_out, GCodeWriter& writer, const std::vector<ToolOrdering>& tool_ordering, const std::string& custom_gcode);
static ObjectsLayerToPrint collect_layers_to_print(const PrintObject &object, Print::StatusMonitor &status_monitor);
static std::vector<std::pair<coordf_t, ObjectsLayerToPrint>> collect_layers_to_print(const Print &print, Print::StatusMonitor &status_monitor);
static ObjectsLayerToPrint collect_layers_to_print(const PrintObject &object, Print::StatusMonitor &status_monitor);
static std::vector<std::pair<coord_t, ObjectsLayerToPrint>> collect_layers_to_print(const Print &print, Print::StatusMonitor &status_monitor);
static std::vector<ObjectsLayerToPrint> separate_islands(const ObjectsLayerToPrint object_layers,
const coord_t start_e,
const Point last_position,
const coord_t max_height,
const std::vector<GraphData> &extruder_min_dist,
const uint16_t current_extruder_id);
LayerResult process_layer(
@ -268,7 +288,7 @@ private:
Print::StatusMonitor &status_monitor,
const ToolOrdering &tool_ordering,
const std::vector<const PrintInstance*> &print_object_instances_ordering,
const std::vector<std::pair<coordf_t, ObjectsLayerToPrint>> &layers_to_print,
const std::vector<std::pair<coord_t, ObjectsLayerToPrint>> &layers_to_print,
std::string &preamble,
GCodeOutputStream &output_stream);
// Process all layers of a single object instance (sequential mode) with a parallel pipeline:
@ -285,19 +305,33 @@ private:
void set_extruders(const std::vector<uint16_t> &extruder_ids);
std::string preamble();
std::string change_layer(double print_z);
std::string change_layer(coord_t from_z, coord_t to_z);
std::string visitor_gcode;
bool visitor_flipped; //TODO use instead of reverse() at extrude_entity
bool visitor_in_use = false;
std::string visitor_root_state = ""; // to know what kind of thing we're doing.
std::string_view visitor_comment;
double visitor_speed;
virtual void use(const ExtrusionPath &path) override { visitor_gcode += extrude_path(path, visitor_comment, visitor_speed); };
virtual void use(const ExtrusionPath3D &path3D) override { visitor_gcode += extrude_path_3D(path3D, visitor_comment, visitor_speed); };
virtual void use(const ExtrusionMultiPath &multipath) override { visitor_gcode += extrude_multi_path(multipath, visitor_comment, visitor_speed); };
virtual void use(const ExtrusionMultiPath3D &multipath) override { visitor_gcode += extrude_multi_path3D(multipath, visitor_comment, visitor_speed); };
virtual void use(const ExtrusionLoop &loop) override { visitor_gcode += extrude_loop(loop, visitor_comment, visitor_speed); };
virtual void use(const ExtrusionPath &path) override;
virtual void use(const ExtrusionPath3D &path3D) override;
virtual void use(const ExtrusionMultiPath &multipath) override;
virtual void use(const ExtrusionMultiPath3D &multipath) override;
virtual void use(const ExtrusionLoop &loop) override;
virtual void use(const ExtrusionEntityCollection &collection) override;
virtual void use(const ExtrusionNop &command) override;
void start_using_extrusion(const ExtrusionEntity &entity);
void end_using_extrusion(const ExtrusionEntity &entity);
virtual void default_use(const ExtrusionProperty&) override;
virtual void use(const ExtrusionMultiProperties&) override;
virtual void use(const ExtrusionPropertySpeed&) override;
virtual void use(const ExtrusionPropertyCustomGcode&) override;
virtual void use(const ExtrusionPropertyModifier&) override;
virtual void use(const ExtrusionPropertySpecialCommand&) override;
//virtual void use(const ExtrusionPropertyOverhang&) override; // no need for this one
virtual void use(const ExtrusionPropertyZOffset&) override;
std::string extrude_entity(const ExtrusionEntityReference &entity, const std::string_view description, double speed = -1.);
std::string extrude_loop(const ExtrusionLoop &loop, const std::string_view description, double speed = -1.);
std::string extrude_loop_vase(const ExtrusionPaths& normal_loop_paths, const ExtrusionLoop &original_loop, const std::string_view description, double speed = -1.);
@ -359,9 +393,9 @@ private:
// if no m_region, then it will take the default region config from print_object
// if no print_object, then it will take the default region config from print
void set_region_for_extrude(const Print &print, const PrintObject *print_object, const LayerRegion *layerm, std::string &gcode);
void extrude_perimeters(const ExtrudeArgs &print_args, const LayerIsland &island, std::string &gcode);
void extrude_infill(const ExtrudeArgs &print_args, const LayerIsland &island, bool is_infill_first, std::string &gcode);
void extrude_ironing(const ExtrudeArgs &print_args, const LayerIsland &island, std::string &gcode);
void extrude_perimeters(const ExtrudeArgs &print_args, const LayerRegionIsland &island, std::string &gcode);
void extrude_infill(const ExtrudeArgs &print_args, const LayerRegionIsland &island, bool is_infill_first, std::string &gcode);
void extrude_ironing(const ExtrudeArgs &print_args, const LayerRegionIsland &island, std::string &gcode);
void extrude_skirt(ExtrusionLoop &loop_src, const ExtrusionFlow &extrusion_flow_override, std::string &gcode, const std::string_view description);
std::string extrude_support(const ExtrusionEntityReferences &support_fills);
bool shall_print_this_extrusion_collection(const ExtrudeArgs & print_args,
@ -381,7 +415,7 @@ private:
);
Polyline travel_to(std::string& gcode, const Point &end_point, ExtrusionRole role);
void write_travel_to(std::string& gcode, Polyline& travel, std::string comment);
std::vector<coord_t> get_travel_elevation(Polyline& travel, double z_change);
std::vector<coord_t> get_travel_elevation(Polyline& travel, coord_t z_change);
//std::string travel_to_first_position(const Vec3crd& point);
bool can_cross_perimeter(const Polyline& travel, bool offset);
bool needs_retraction(const Polyline &travel, ExtrusionRole role = ExtrusionRole::None, coordf_t max_min_dist = 0);
@ -389,9 +423,9 @@ private:
std::string retract_and_wipe(bool toolchange = false, bool inhibit_lift = false);
std::string unretract() { return m_writer.unlift() + m_writer.unretract(); }
// enforce lift_min
void set_extra_lift(const float previous_print_z, const int layer_id, const PrintConfig& print_config, GCodeWriter & writer, int extruder_id);
std::string set_extruder(uint16_t extruder_id, double print_z, bool no_toolchange = false);
std::string toolchange(uint16_t extruder_id, double print_z);
void set_extra_lift(const coord_t previous_print_z, const int layer_id, const PrintConfig& print_config, GCodeWriter & writer, int extruder_id);
std::string set_extruder(uint16_t extruder_id, coord_t print_z, bool no_toolchange = false);
std::string toolchange(uint16_t extruder_id, coord_t print_z);
bool line_distancer_is_required(const std::vector<uint16_t>& extruder_ids);
// Cache for custom seam enforcers/blockers for each layer.
@ -401,6 +435,7 @@ private:
bool m_need_layer_collision_already_printed = false;
std::vector<std::pair<ArcPolylines, coord_t>> m_layer_collision_already_printed_2_width;
void init_layer_for_collision_check(const Layer *object_layer);
void add_travel_obstacle(const ObjectsLayerToPrint &layer_group);
public:
/* Origin of print coordinates expressed in unscaled G-code coordinates.
This affects the input arguments supplied to the extrude*() and travel_to()
@ -451,7 +486,11 @@ private:
AvoidCrossingPerimeters m_avoid_crossing_perimeters;
JPSPathFinder m_avoid_crossing_curled_overhangs;
RetractWhenCrossingPerimeters m_retract_when_crossing_perimeters;
// m_travel_obstacle_tracker works on this layer's extrusions.
GCode::TravelObstacleTracker m_travel_obstacle_tracker;
// m_travel_obstacles track tall objects for sequential printing.
// contains the expolygon & the height of it
std::map<coord_t, std::pair<ExPolygons, BoundingBox>> m_z_to_obstacles;
bool m_enable_loop_clipping;
// If enabled, the G-code generator will put following comments at the ends
// of the G-code lines: _EXTRUDE_SET_SPEED, _WIPE, _BRIDGE_FAN_START, _BRIDGE_FAN_END, _BRIDGE_INTERNAL_FAN_START, _BRIDGE_INTERNAL_FAN_END
@ -462,7 +501,9 @@ private:
bool m_enable_extrusion_role_markers;
int m_check_markers = 0;
// HACK to avoid multiple Z move.
// FIXME: force a lift?
std::string m_delayed_layer_change;
coord_t m_delayed_layer_change_current_print_z;
// Keeps track of the last extrusion role passed to the processor
GCodeExtrusionRole m_last_processor_extrusion_role;
// For Progress bar indicator, in sequential mode (complete objects)
@ -481,9 +522,11 @@ private:
// Current layer processed. In sequential printing mode, only a single copy will be printed.
// In non-sequential mode, all its copies will be printed.
const Layer* m_layer;
// layer at our current position, can be different than m_layer before the wipe & retract & delayed layer change
const Layer* m_pos_layer;
// last layers printed at our current Z, to
std::vector<const Layer*> m_last_object_layers;
coordf_t m_last_layers_z{ 0.0 };
coord_t m_last_layers_z{ 0 };
const PrintRegion* m_region = nullptr;
// m_layer is an object layer and it is being printed over raft surface.
bool m_object_layer_over_raft; // idx of the current instance printed. (or the last one)
@ -517,14 +560,22 @@ private:
// Not know the gapfill role for retract_lift_top
GCodeExtrusionRole m_last_not_gapfill_extrusion_role;
// Support for G-Code Processor
double m_last_height{ 0.0 };
double m_last_layer_z{ 0.0 };
double m_max_layer_z{ 0.0 };
double m_last_width{ 0.0 };
coord_t m_last_height_{ 0 };
coord_t m_last_layer_z_{ 0 };
coord_t m_max_layer_z_{ 0 };
float m_last_path_flow_width{ 0 };
// filament used since the beginning for each extruder, updated after the before_layer_gcode. in mm
std::vector<double> m_last_layer_used_filament;
// to pass between before_xtrude and after_extrude.
double m_overhang_fan_override{ -1.0 };
// from extrusion properties.
std::vector<const ExtrusionEntity*> m_current_entity;
std::vector<std::pair<const ExtrusionEntity*, const ExtrusionPropertySpeed*>> m_speed_override;
std::vector<std::pair<const ExtrusionEntity*, const ExtrusionPropertyModifier*>> m_modifier_override;
std::vector<std::pair<const ExtrusionEntity*, coord_t>> m_z_override;
std::vector<int16_t> m_saved_temp;
bool m_force_unretract{false};
bool m_no_gcodeviewer_tag{false};
#if ENABLE_GCODE_VIEWER_DATA_CHECKING
double m_last_mm3_per_mm;
#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
@ -532,11 +583,12 @@ private:
const PrintInstance* m_last_instance {nullptr};
std::optional<Point> m_last_pos;
// for ramping lift: if enabled, and this is set, then you will need to move Z at the next travel.
// note: rampng lift and these kind of trick should eb reworked & improve when the gcode creation will be split in multiplt subsystem, these working on a chain of "command" objects. That way it should be easier to move the Z / travel accrodingly.
// for ramping lift: this is set, then you will need to move Z at the next travel (from this z to the current alyer).
// note: rampng lift and these kind of trick should be reworked & improve when the gcode creation will be split in multiplt subsystem, these working on a chain of "command" objects. That way it should be easier to move the Z / travel accrodingly.
// the dangerous thing with it is when you cancel an object, then the Z move and the travel need to be dealt with correctly. currently, it's a pain to to do that.
std::optional<double> m_new_z_target = {};
double m_next_lift_min{0};
// note2: if 0 or negative, it just enforce the current z before the travel.
std::optional<coord_t> _m_force_move_z_from = {};
coord_t _m_next_lift_min{0};
double m_current_perimeter_extrusion_width = 0.4;
std::optional<unsigned> m_layer_change_extruder_id;
@ -546,6 +598,7 @@ private:
int32_t m_last_command_buffer_used = 0;
std::string m_last_description;
double m_last_speed_mm_per_sec;
bool m_need_z_reset_after_path_3D = false;
std::unique_ptr<CoolingBuffer> m_cooling_buffer;
std::unique_ptr<SpiralVase> m_spiral_vase;
@ -553,12 +606,13 @@ private:
int32_t m_spiral_vase_layer = 0;
std::unique_ptr<GCodeFindReplace> m_find_replace;
std::unique_ptr<PressureEqualizer> m_pressure_equalizer;
std::unique_ptr<GCode::WipeTowerIntegration> m_wipe_tower;
std::map<coord_t, std::shared_ptr<WipeTowerLayer>> m_wipe_tower_layers;
std::shared_ptr<WipeTowerLayer> m_wipe_tower_current_layer;
// to get extruded volume, for stats
const WipeTowerData *m_wipe_tower_data;
// Heights (print_z) at which the skirt has already been extruded.
std::vector<coordf_t> m_skirt_done;
std::vector<coord_t> m_skirt_done;
// Has the brim been extruded already? Brim is being extruded only for the first object of a multi-object print.
std::map<std::pair<const PrintObject *, int>, bool> m_brim_done;
// Flag indicating whether the nozzle temperature changes from 1st to 2nd layer were performed.
@ -587,6 +641,7 @@ private:
//some post-processing on the file, with their data class
std::unique_ptr<FanMover> m_fan_mover;
std::unique_ptr<TemperatureMover> m_temperature_mover;
std::function<void()> m_throw_if_canceled = [](){};
@ -622,8 +677,6 @@ private:
static void cooldown_marker_init();
};
std::vector<const PrintInstance*> sort_object_instances_by_model_order(const Print& print);
}
#endif

View file

@ -645,19 +645,25 @@ static coord_t get_perimeter_spacing_external(const Layer &layer)
{
size_t regions_count = 0;
coord_t perimeter_spacing = 0.f;
for (const PrintObject *object : layer.object()->print()->objects())
if (const Layer *l = object->get_layer_at_printz(layer.print_z, EPSILON); l)
for (const LayerRegion *layer_region : l->regions())
if (layer_region != nullptr && ! layer_region->slices().empty()) {
for (const PrintObject *object : layer.object()->print()->objects()) {
assert(object->get_layer_at_printz(layer.unscaled_print_z(), EPSILON * 4) ==
object->get_layer_at_printz(layer.scaled_print_z()));
if (const Layer *l = object->get_layer_at_printz(layer.scaled_print_z()); l) {
for (const LayerRegion *layer_region : l->regions()) {
if (layer_region != nullptr && !layer_region->slices().empty()) {
perimeter_spacing += layer_region->flow(frPerimeter).scaled_spacing();
++ regions_count;
++regions_count;
}
}
}
}
assert(perimeter_spacing >= 0.f);
if (regions_count != 0)
if (regions_count != 0) {
perimeter_spacing /= regions_count;
else
} else {
perimeter_spacing = get_default_perimeter_spacing(*layer.object());
}
return perimeter_spacing;
}
@ -1092,11 +1098,13 @@ static void jump_between_island(AvoidCrossingPerimeters::Boundary &boundary, //
break;
}
}
// if in a hole (and not next to the contour in the bbox)
// bboxes overlap, but maybe the polygon not
if (hole_contour != size_t(-1)) {
start_island = hole_contour;
}
} else if (boundary.bboxes[end_island].contains(boundary.bboxes[start_island])) {
}
if (boundary.bboxes[end_island].contains(boundary.bboxes[start_island])) {
// find hole
size_t hole_contour = size_t(-1);
for (size_t hole_idx = end_island + 1;
@ -1106,6 +1114,7 @@ static void jump_between_island(AvoidCrossingPerimeters::Boundary &boundary, //
break;
}
}
// if in a hole (and not next to the contour in the bbox)
// bboxes overlap, but maybe the polygon not
if (hole_contour != size_t(-1)) {
end_island = hole_contour;
@ -1477,7 +1486,8 @@ static void jump_between_island(AvoidCrossingPerimeters::Boundary &boundary, //
}
}
}
#ifdef _DEBUG
//#ifdef _DEBUG
#ifdef false
std::chrono::time_point<std::chrono::high_resolution_clock> time_mid = std::chrono::high_resolution_clock::now();
std::chrono::time_point<std::chrono::high_resolution_clock> time_end;
@ -2258,9 +2268,9 @@ static ExPolygons get_boundary(const Layer &layer, uint16_t extruder_id, std::ve
ExPolygons perimeter_boundary;
ExPolygons boundary;
//get perimeter_boundary from layerregion
for (const LayerRegion *lregion : layer.regions()) {
append(perimeter_boundary, lregion->m_perimeter_slices);
//get perimeter_boundary from islands
for (const LayerSliceIslandPtr &layer_island : layer.islands()) {
append(perimeter_boundary, layer_island->get_perimeter_slices());
}
perimeter_boundary = union_ex(perimeter_boundary);
@ -2278,12 +2288,13 @@ static ExPolygons get_boundary(const Layer &layer, uint16_t extruder_id, std::ve
#ifdef INCLUDE_SUPPORTS_IN_BOUNDARY
append(boundary, inner_offset(support_layer->support_islands.expolygons, 1.5 * perimeter_spacing));
#endif
auto *layer_below = layer.object()->get_first_layer_bellow_printz(layer.print_z, EPSILON);
assert(layer.object()->get_first_layer_below_printz(layer.unscaled_print_z(), EPSILON*4) == layer.object()->get_first_layer_below_printz(layer.scaled_print_z() + SCALED_EPSILON));
auto *layer_below = layer.object()->get_first_layer_below_printz(layer.scaled_print_z() + SCALED_EPSILON);
if (layer_below) { // why?
perimeter_boundary.clear();
//get perimeter_boundary from layerregion
for (const LayerRegion *lregion : layer_below->regions()) {
append(perimeter_boundary, lregion->m_perimeter_slices);
//get perimeter_boundary from islands
for (const LayerSliceIslandPtr &layer_island : layer_below->islands()) {
append(perimeter_boundary, layer_island->get_perimeter_slices());
}
perimeter_boundary = union_ex(perimeter_boundary);
auto old_2_new_expolygons_supp = inner_offset(perimeter_boundary, coordf_t(1.5 * perimeter_spacing));
@ -2356,7 +2367,7 @@ static ExPolygons get_boundary(const Layer &layer, uint16_t extruder_id, std::ve
if (same_extruders) {
if (lregion->region().config().perimeter_extruder.value ==
extruder_id + 1) {
clip = union_ex(clip, lregion->get_cached_slices());
clip = union_ex(clip, lregion->get_raw_slices());
}
} else {
if (lregion->region().config().infill_extruder.value !=
@ -2367,7 +2378,7 @@ static ExPolygons get_boundary(const Layer &layer, uint16_t extruder_id, std::ve
extruder_id + 1) {
assert(lregion->region().config().infill_extruder.value !=
extruder_id + 1);
clip = union_ex(clip, diff_ex(lregion->get_cached_slices(), lregion->fill_expolygons()));
clip = union_ex(clip, diff_ex(lregion->get_raw_slices(), lregion->fill_expolygons()));
} else {
assert(lregion->region().config().infill_extruder.value ==
extruder_id + 1);
@ -2397,11 +2408,13 @@ static Polygons get_boundary_external(const Layer &layer)
#ifdef INCLUDE_SUPPORTS_IN_BOUNDARY
ExPolygons supports_per_obj;
#endif
if (const Layer *l = object->get_layer_at_printz(layer.print_z, EPSILON); l)
assert(object->get_layer_at_printz(layer.unscaled_print_z(), EPSILON * 4) == object->get_layer_at_printz(layer.scaled_print_z()));
if (const Layer *l = object->get_layer_at_printz(layer.scaled_print_z()); l)
for (const ExPolygon &island : l->lslices())
append(holes_per_obj, island.holes);
if (support_layer) {
auto *layer_below = object->get_first_layer_bellow_printz(layer.print_z, EPSILON);
assert(layer.object()->get_first_layer_below_printz(layer.unscaled_print_z(), EPSILON*4) == layer.object()->get_first_layer_below_printz(layer.scaled_print_z() + SCALED_EPSILON));
auto *layer_below = object->get_first_layer_below_printz(layer.scaled_print_z() + SCALED_EPSILON);
if (layer_below)
for (const ExPolygon &island : layer_below->lslices())
append(holes_per_obj, island.holes);
@ -2544,6 +2557,9 @@ Polyline AvoidCrossingPerimeters::travel_to(const GCodeGenerator &gcodegen, cons
nearest_end = bb_coord_t.nearest_point(nearest_end);
}
travel_intersection_count = avoid_perimeters(m_internal, nearest_start/*startf.cast<coord_t>()*/, nearest_end/*endf.cast<coord_t>()*/, perimeter_spacing, *gcodegen.layer(), result_pl);
assert(result_pl.size() > 1);
for (size_t i = 1; i < result_pl.size(); i++)
assert(!result_pl.points[i - 1].coincides_with_epsilon(result_pl.points[i]));
result_pl.points.front() = start;
result_pl.points.back() = end;
}
@ -2566,10 +2582,16 @@ Polyline AvoidCrossingPerimeters::travel_to(const GCodeGenerator &gcodegen, cons
nearest_end = bb_coord_t.nearest_point(nearest_end);
}
travel_intersection_count = avoid_perimeters(m_external, nearest_start/*startf.cast<coord_t>()*/, nearest_end/*endf.cast<coord_t>()*/, 0, *gcodegen.layer(), result_pl);
assert(result_pl.size() > 1);
for (size_t i = 1; i < result_pl.size(); i++)
assert(!result_pl.points[i - 1].coincides_with_epsilon(result_pl.points[i]));
result_pl.points.front() = start;
result_pl.points.back() = end;
}
}
assert(result_pl.size() > 1);
for (size_t i = 1; i < result_pl.size(); i++)
assert(!result_pl.points[i - 1].coincides_with_epsilon(result_pl.points[i]));
if(result_pl.empty()) {
// Travel line is completely outside the bounding box.
@ -2620,9 +2642,9 @@ void AvoidCrossingPerimeters::init_layer(const Layer &layer)
m_init_to = &layer;
float ext_perimeter_width = get_external_perimeter_width(layer);
//get perimeter_boundary from layerregion instead of layer.lslices()
for (const LayerRegion *lregion : layer.regions()) {
append(m_lslices_offset, lregion->m_perimeter_slices);
//get perimeter_boundary from island instead of layer.lslices()
for (const LayerSliceIslandPtr &layer_island : layer.islands()) {
append(m_lslices_offset, layer_island->get_perimeter_slices());
}
m_lslices_offset = offset_ex(m_lslices_offset, -ext_perimeter_width / 2);
@ -2974,7 +2996,8 @@ static ExPolygons get_boundary_external(const Layer &layer)
ExPolygons polygons_per_obj;
//FIXME with different layering, layers on other objects will not be found at this object's print_z.
// Search an overlap of layers?
if (const Layer* l = object->get_layer_at_printz(layer.print_z, EPSILON); l)
assert(object->get_layer_at_printz(layer.unscaled_print_z(), EPSILON * 4) == object->get_layer_at_printz(layer.scaled_print_z()));
if (const Layer* l = object->get_layer_at_printz(layer.scaled_print_z()); l)
for (const LayerRegion *layer_region : l->regions())
for (const Surface &surface : layer_region->slices.surfaces)
polygons_per_obj.emplace_back(surface.expolygon);

View file

@ -128,7 +128,7 @@ static std::vector<ExtrusionPaths> getFakeExtrusionPathsFromWipeTower(const Wipe
ExtrusionPath path(ArcPolyline(Points{minCorner, {maxCorner.x(), minCorner.y()}, maxCorner, {minCorner.x(), maxCorner.y()}, minCorner }),
ExtrusionAttributes{ ExtrusionRole::WipeTower, ExtrusionFlow{ 0.0, 0.0, lh } });
ExtrusionAttributes{ ExtrusionRole::WipeTower, ExtrusionFlow{ 0.0, 0.0, lh } }, nullptr);
paths.push_back({ path });
// We added the border, now add several parallel lines so we can detect an object that is fully inside the tower.
@ -259,20 +259,36 @@ void getExtrusionPathsFromEntity(const ExtrusionEntityCollection *entity, Extrus
getExtrusionPathImpl(entity, paths);
}
ExtrusionPaths getExtrusionPathsFromLayer(LayerRegionPtrs layerRegionPtrs)
ExtrusionPaths getExtrusionPathsFromLayer(const std::vector<LayerSliceIslandPtr> &layer_islands)
{
ExtrusionPaths paths;
for (auto regionPtr : layerRegionPtrs) {
getExtrusionPathsFromEntity(&regionPtr->perimeters(), paths);
if (!regionPtr->perimeters().empty()) { getExtrusionPathsFromEntity(&regionPtr->fills(), paths); }
for (const LayerSliceIslandPtr &layer_island_ptr : layer_islands) {
for (const LayerRegionIslandPtr &region_island_ptr : layer_island_ptr->regions_islands()) {
if (region_island_ptr->has_extrusion(LayerRegionIsland::PERIMETERS)) {
getExtrusionPathsFromEntity(&region_island_ptr->extrusion(LayerRegionIsland::PERIMETERS), paths);
if (region_island_ptr->has_extrusion(LayerRegionIsland::INFILLS)) {
getExtrusionPathsFromEntity(&region_island_ptr->extrusion(LayerRegionIsland::INFILLS), paths);
}
}
}
}
return paths;
}
ExtrusionPaths getExtrusionPathsFromSupportLayer(const SupportLayer *supportLayer)
{
assert(supportLayer);
ExtrusionPaths paths;
getExtrusionPathsFromEntity(&supportLayer->support_fills, paths);
for (const LayerSliceIslandPtr &island : supportLayer->islands()) {
for (const LayerRegionIslandPtr &region_island : island->regions_islands()) {
if (region_island->has_extrusion(LayerRegionIsland::SUPPORT)) {
getExtrusionPathsFromEntity(&region_island->extrusion(LayerRegionIsland::SUPPORT), paths);
}
if (region_island->has_extrusion(LayerRegionIsland::SUPPORT_INTERFACE)) {
getExtrusionPathsFromEntity(&region_island->extrusion(LayerRegionIsland::SUPPORT_INTERFACE), paths);
}
}
}
return paths;
}
@ -280,7 +296,7 @@ std::pair<std::vector<ExtrusionPaths>, std::vector<ExtrusionPaths>> getAllLayers
{
std::vector<ExtrusionPaths> objPaths, supportPaths;
for (auto layerPtr : obj->layers()) { objPaths.push_back(getExtrusionPathsFromLayer(layerPtr->regions())); }
for (auto layerPtr : obj->layers()) { objPaths.push_back(getExtrusionPathsFromLayer(layerPtr->islands())); }
for (auto supportLayerPtr : obj->support_layers()) { supportPaths.push_back(getExtrusionPathsFromSupportLayer(supportLayerPtr)); }
@ -310,14 +326,14 @@ ConflictComputeOpt ConflictChecker::find_inter_of_lines(const LineWithIDs &lines
ConflictResultOpt ConflictChecker::find_inter_of_lines_in_diff_objs(SpanOfConstPtrs<PrintObject> objs,
const WipeTowerData& wipe_tower_data) // find the first intersection point of lines in different objects
{
if (objs.empty() || (objs.size() == 1 && objs.front()->instances().size() == 1 && wipe_tower_data.number_of_toolchanges == 0)) { return {}; }
if (objs.empty() || (objs.size() == 1 && objs.front()->instances().size() == 1 && wipe_tower_data.number_of_toolchanges <= 0)) { return {}; }
// The code ported from BS uses void* to identify objects...
// Let's use the address of this variable to represent the wipe tower.
int wtptr = 0;
LinesBucketQueue conflictQueue;
if (! wipe_tower_data.z_and_depth_pairs.empty()) {
if (! wipe_tower_data.z_and_depth_pairs.empty() && wipe_tower_data.tool_changes.size() > 0) {
// The wipe tower is being generated.
const Vec2d plate_origin = Vec2d::Zero();
std::vector<ExtrusionPaths> wtpaths = getFakeExtrusionPathsFromWipeTower(wipe_tower_data);

View file

@ -886,8 +886,7 @@ float CoolingBuffer::calculate_layer_slowdown(std::vector<PerExtruderAdjustments
float total = elapsed_time_total0;
for (auto it = cur_begin; it != by_slowdown_time.end(); ++ it)
total += (*it)->time_total;
float slowdown_below_layer_time = adj.slowdown_below_layer_time * 1.001f;
if (total > slowdown_below_layer_time) {
if (total * 1.001f >= adj.slowdown_below_layer_time) {
// The current total time is above the minimum threshold of the rest of the extruders, don't adjust anything.
} else {
// Adjust this and all the following (higher m_config.slowdown_below_layer_time) extruders.
@ -895,11 +894,11 @@ float CoolingBuffer::calculate_layer_slowdown(std::vector<PerExtruderAdjustments
float max_time = elapsed_time_total0;
for (auto it = cur_begin; it != by_slowdown_time.end(); ++ it)
max_time += (*it)->time_maximum;
if (max_time > slowdown_below_layer_time) {
if (max_time > adj.slowdown_below_layer_time) {
if (m_cooling_logic_proportional)
extruder_range_slow_down_proportional(cur_begin, by_slowdown_time.end(), elapsed_time_total0, total, slowdown_below_layer_time);
extruder_range_slow_down_proportional(cur_begin, by_slowdown_time.end(), elapsed_time_total0, total, adj.slowdown_below_layer_time);
else
extruder_range_slow_down_non_proportional(cur_begin, by_slowdown_time.end(), slowdown_below_layer_time - total);
extruder_range_slow_down_non_proportional(cur_begin, by_slowdown_time.end(), adj.slowdown_below_layer_time - total);
} else {
// Slow down to maximum possible.
for (auto it = cur_begin; it != by_slowdown_time.end(); ++ it)

View file

@ -16,15 +16,15 @@ ExtrusionPaths calculate_and_split_overhanging_extrusions(const ExtrusionPath
const AABBTreeLines::LinesDistancer<Linef> &unscaled_prev_layer,
const AABBTreeLines::LinesDistancer<CurledLine> &prev_layer_curled_lines,
const double &nozzle_diameter) {
//assert(!path.attributes().overhang_attributes.has_value() || path.attributes().overhang_attributes->has_full_overhangs_speed ||
// path.attributes().overhang_attributes->has_dynamic_overhangs_speed);
if (!path.attributes().overhang_attributes) {
//assert(path.overhang_attributes() == nullptr || path.overhang_attributes()->has_full_overhangs_speed ||
// path.overhang_attributes()->has_dynamic_overhangs_speed);
if (path.overhang_attributes() == nullptr) {
return { path };
} else {
if (!path.attributes().overhang_attributes->has_dynamic_overhangs_flow && !path.attributes().overhang_attributes->has_dynamic_overhangs_speed) {
if (!path.overhang_attributes()->has_dynamic_overhangs_flow && !path.overhang_attributes()->has_dynamic_overhangs_speed) {
// not inside the dynamic range
//path.attributes().overhang_attributes->start_distance_from_prev_layer = 1;
//path.attributes().overhang_attributes->end_distance_from_prev_layer = 1;
//path.overhang_attributes()->start_distance_from_prev_layer = 1;
//path.overhang_attributes()->end_distance_from_prev_layer = 1;
return { path };
}
}
@ -81,7 +81,7 @@ ExtrusionPaths calculate_and_split_overhanging_extrusions(const ExtrusionPath
for (size_t idx : line_indices) {
const CurledLine &line = prev_layer_curled_lines.get_line(idx);
float distance_from_curled = unscaled(line_alg::distance_to(line, Point::new_scale(middle)));
float distance_from_curled = unscaled(std::sqrt(line_alg::distance_to_squared(line, Point::new_scale(middle))));
float proximity = (1.0 - (distance_from_curled / dist_limit)) * (1.0 - (distance_from_curled / dist_limit)) *
(line.curled_height / (path.height() * 10.0f)); // max_curled_height_factor from SupportSpotGenerator
proximity_to_curled_lines = std::max(proximity_to_curled_lines, proximity);
@ -93,22 +93,21 @@ ExtrusionPaths calculate_and_split_overhanging_extrusions(const ExtrusionPath
}
ExtrusionPaths result;
ExtrusionAttributes new_attrs = path.attributes();
new_attrs.overhang_attributes = std::optional<OverhangAttributes>(
{calculated_distances[0].first,
calculated_distances[0].first,
calculated_distances[0].second,
path.attributes().overhang_attributes->has_full_overhangs_flow,
path.attributes().overhang_attributes->has_full_overhangs_speed,
path.attributes().overhang_attributes->has_dynamic_overhangs_flow,
path.attributes().overhang_attributes->has_dynamic_overhangs_speed});
result.emplace_back(new_attrs);
result.emplace_back(path.attributes(), path.clone_properties(), path.can_reverse());
ExtrusionPropertyOverhang overhang_attributes(calculated_distances[0].first,
calculated_distances[0].first,
calculated_distances[0].second);
overhang_attributes.has_full_overhangs_flow = path.overhang_attributes()->has_full_overhangs_flow;
overhang_attributes.has_full_overhangs_speed = path.overhang_attributes()->has_full_overhangs_speed;
overhang_attributes.has_dynamic_overhangs_flow = path.overhang_attributes()->has_dynamic_overhangs_flow;
overhang_attributes.has_dynamic_overhangs_speed = path.overhang_attributes()->has_dynamic_overhangs_speed;
result.back().overhang_attributes_mutable() = overhang_attributes;
result.back().polyline.append(Point::new_scale(extended_points[0].position));
size_t sequence_start_index = 0;
for (size_t i = 1; i < extended_points.size(); i++) {
if (!result.back().polyline.back().coincides_with_epsilon(Point::new_scale(extended_points[i].position))) {
result.back().polyline.append(Point::new_scale(extended_points[i].position));
result.back().overhang_attributes_mutable()->end_distance_from_prev_layer = extended_points[i].distance;
result.back().overhang_attributes_mutable().end_distance_from_prev_layer = extended_points[i].distance;
}
if (std::abs(calculated_distances[sequence_start_index].first - calculated_distances[i].first) < 0.01 * nozzle_diameter &&
std::abs(calculated_distances[sequence_start_index].second - calculated_distances[i].second) < 0.001) {
@ -118,13 +117,14 @@ ExtrusionPaths calculate_and_split_overhanging_extrusions(const ExtrusionPath
} else if (i + 1 < extended_points.size()) { // do not start new path if this is last point!
// start new path, parameters differ
// store the distance in mm
new_attrs.overhang_attributes->start_distance_from_prev_layer = calculated_distances[i].first;
new_attrs.overhang_attributes->end_distance_from_prev_layer = calculated_distances[i].first;
overhang_attributes.start_distance_from_prev_layer = calculated_distances[i].first;
overhang_attributes.end_distance_from_prev_layer = calculated_distances[i].first;
// already between 0 and 1
new_attrs.overhang_attributes->proximity_to_curled_lines = calculated_distances[i].second;
overhang_attributes.proximity_to_curled_lines = calculated_distances[i].second;
sequence_start_index = i;
if (result.back().size() > 1) {
result.emplace_back(new_attrs);
result.emplace_back(path.attributes(), path.clone_properties(), path.can_reverse());
result.back().overhang_attributes_mutable() = overhang_attributes;
result.back().polyline.append(Point::new_scale(extended_points[i].position));
} else {
assert(result.back().size() == 1);
@ -139,15 +139,14 @@ ExtrusionPaths calculate_and_split_overhanging_extrusions(const ExtrusionPath
}
//remove overhang role, as it prevents placing seams on it.
for (ExtrusionPath &res_path : result) {
assert(res_path.attributes().overhang_attributes);
assert(res_path.overhang_attributes());
//res_path.attributes_mutable().role = (res_path.role() & ExtrusionRoleModifier(~ExtrusionRoleModifier::ERM_Bridge));
//assert(res_path.role() == ExtrusionRole::Perimeter || res_path.role() == ExtrusionRole::ExternalPerimeter);
}
#ifdef _DEBUG
for (auto &path : result) {
assert(path.attributes().overhang_attributes.has_value());
assert(path.attributes().overhang_attributes->start_distance_from_prev_layer >= 0 &&
path.attributes().overhang_attributes->end_distance_from_prev_layer >= 0);
assert(path.overhang_attributes() && path.overhang_attributes()->start_distance_from_prev_layer >= 0 &&
path.overhang_attributes()->end_distance_from_prev_layer >= 0);
}
assert(is_approx(result.front().first_point(), path.first_point()));
assert(is_approx(result.back().last_point(), path.last_point()));
@ -168,13 +167,29 @@ ExtrusionPaths calculate_and_split_overhanging_extrusions(const ExtrusionPath
result.front().polyline.set_front(path.first_point());
result.back().polyline.set_back(path.last_point());
for (const ExtrusionPath &res_path : result) {
assert(!res_path.attributes().overhang_attributes.has_value() ||
res_path.attributes().overhang_attributes->has_full_overhangs_speed ||
res_path.attributes().overhang_attributes->has_dynamic_overhangs_speed);
assert(res_path.overhang_attributes() == nullptr ||
res_path.overhang_attributes()->has_full_overhangs_speed ||
res_path.overhang_attributes()->has_dynamic_overhangs_speed);
}
return result;
};
//class CalculateSplitOverhangVisitor : public ExtrusionVisitorRecursiveConst {
//public:
// ExtrusionEntities current_collection;
// const AABBTreeLines::LinesDistancer<Linef> &unscaled_prev_layer;
// const AABBTreeLines::LinesDistancer<CurledLine> &prev_layer_curled_lines;
// const double max_width
// using ExtrusionVisitorRecursiveConst::use;
// CalculateSplitOverhangVisitor() {
// }
// void use(const ExtrusionPath &path) override { volume += unscaled(path3D.length()) * path3D.mm3_per_mm(); }
// void use(const ExtrusionPath3D &path3D) override {
// result.append(std::move(new_mp)); //TODO split
// }
// double get(const ExtrusionEntityCollection &coll);
//};
ExtrusionEntityCollection calculate_and_split_overhanging_extrusions(const ExtrusionEntityCollection *ecc,
const AABBTreeLines::LinesDistancer<Linef> &unscaled_prev_layer,
const AABBTreeLines::LinesDistancer<CurledLine> &prev_layer_curled_lines,
@ -231,17 +246,19 @@ ExtrusionEntityCollection calculate_and_split_overhanging_extrusions(const Extru
};
float calculate_overhang_speed(const ExtrusionAttributes &attributes,
const FullPrintConfig &config,
size_t extruder_id) {
assert(attributes.overhang_attributes.has_value());
if (!attributes.overhang_attributes.has_value())
float calculate_overhang_speed(const ExtrusionPath &path,
const FullPrintConfig &config,
size_t extruder_id)
{
const ExtrusionPropertyOverhang *overhang_attributes = path.overhang_attributes();
assert(overhang_attributes);
if(!overhang_attributes)
return -1;
float speed_ratio = 0; // 0: overhangs speed, 1= perimeter/externalperimeter speed.
// enforce config.overhangs_width_speed.is_enabled() to be able to compute overhangs_dynamic_speed, for simplicity sake.
if (config.overhangs_width_speed.is_enabled() && config.overhangs_dynamic_speed.is_enabled()) {
if (attributes.overhang_attributes->start_distance_from_prev_layer == 0 &&
attributes.overhang_attributes->end_distance_from_prev_layer == 0) {
if (overhang_attributes->start_distance_from_prev_layer == 0 &&
overhang_attributes->end_distance_from_prev_layer == 0) {
speed_ratio = 1;
} else {
assert(config.overhangs);
@ -262,53 +279,44 @@ float calculate_overhang_speed(const ExtrusionAttributes &attributes,
graph.graph_points[graph.begin_idx].x() = 0;
graph.graph_points[graph.end_idx - 1].y() = 100;
// interpolate
assert(attributes.overhang_attributes->start_distance_from_prev_layer >= 0);
assert(attributes.overhang_attributes->end_distance_from_prev_layer >= 0);
float extrusion_ratio =
std::min(graph.interpolate(
100 -
100 *
std::min(1.f,
attributes.overhang_attributes->start_distance_from_prev_layer /
max_dynamic_distance)),
graph.interpolate(100 -
100 *
std::min(1.f,
attributes.overhang_attributes->end_distance_from_prev_layer /
max_dynamic_distance)));
assert(attributes.width * attributes.overhang_attributes->proximity_to_curled_lines >= 0 &&
attributes.width * attributes.overhang_attributes->proximity_to_curled_lines <= 1);
float curled_extrusion_ratio = graph.interpolate(
100 - 100 * attributes.overhang_attributes->proximity_to_curled_lines);
speed_ratio = std::min(extrusion_ratio, curled_extrusion_ratio) / 100.0;
assert(overhang_attributes->start_distance_from_prev_layer >= 0);
assert(overhang_attributes->end_distance_from_prev_layer >= 0);
float extrusion_ratio = std::min(
graph.interpolate(100 - 100 * std::min(1.f, overhang_attributes->start_distance_from_prev_layer / max_dynamic_distance)),
graph.interpolate(100 - 100 * std::min(1.f, overhang_attributes->end_distance_from_prev_layer / max_dynamic_distance)));
assert(path.width() * overhang_attributes->proximity_to_curled_lines >= 0 &&
path.width() * overhang_attributes->proximity_to_curled_lines <= 1);
float curled_extrusion_ratio = graph.interpolate(100 - 100 * overhang_attributes->proximity_to_curled_lines);
speed_ratio = std::min(extrusion_ratio, curled_extrusion_ratio) / 100.0;
assert(speed_ratio >= 0 && speed_ratio <= 1);
}
}
return speed_ratio;
}
float calculate_overhang_fan_speed(const ExtrusionAttributes &attributes,
float calculate_overhang_fan_speed(const ExtrusionPath &path,
const FullPrintConfig &config,
size_t extruder_id) {
assert(attributes.overhang_attributes.has_value());
if (!attributes.overhang_attributes.has_value())
const ExtrusionPropertyOverhang *overhang_attributes = path.overhang_attributes();
assert(overhang_attributes);
if (overhang_attributes == nullptr)
return -1;
float fan_speed = -1;
std::vector<std::pair<int, ConfigOptionInts>> overhang_with_fan_speeds = {{100, ConfigOptionInts{0}}};
if (config.overhangs_dynamic_fan_speed.is_enabled(extruder_id) &&
attributes.overhang_attributes->start_distance_from_prev_layer > 0 &&
attributes.overhang_attributes->end_distance_from_prev_layer > 0) {
overhang_attributes->start_distance_from_prev_layer > 0 &&
overhang_attributes->end_distance_from_prev_layer > 0) {
GraphData graph = config.overhangs_dynamic_fan_speed.get_at(extruder_id);
//interpolate
assert((attributes.overhang_attributes->start_distance_from_prev_layer >= 0 &&
attributes.overhang_attributes->start_distance_from_prev_layer <= 1) ||
attributes.overhang_attributes->start_distance_from_prev_layer == 2);
assert((attributes.overhang_attributes->end_distance_from_prev_layer >= 0 &&
attributes.overhang_attributes->end_distance_from_prev_layer <= 1) ||
attributes.overhang_attributes->end_distance_from_prev_layer == 2);
assert((overhang_attributes->start_distance_from_prev_layer >= 0 &&
overhang_attributes->start_distance_from_prev_layer <= 1) ||
overhang_attributes->start_distance_from_prev_layer == 2);
assert((overhang_attributes->end_distance_from_prev_layer >= 0 &&
overhang_attributes->end_distance_from_prev_layer <= 1) ||
overhang_attributes->end_distance_from_prev_layer == 2);
fan_speed = std::min(
graph.interpolate(100 - 100 * std::min(1.f, attributes.overhang_attributes->start_distance_from_prev_layer)),
graph.interpolate(100 - 100 * std::min(1.f, attributes.overhang_attributes->end_distance_from_prev_layer)));
graph.interpolate(100 - 100 * std::min(1.f, overhang_attributes->start_distance_from_prev_layer)),
graph.interpolate(100 - 100 * std::min(1.f, overhang_attributes->end_distance_from_prev_layer)));
assert(fan_speed >= 0 && fan_speed <= 100);
}
return fan_speed;
@ -321,10 +329,10 @@ void apply_overhang_flow(ExtrusionPath &path,
size_t extruder_id) {
ExtrusionAttributes &attributes = path.attributes_mutable();
const PrintRegionConfig &region_config = layer_region.region().config();
if (!attributes.overhang_attributes.has_value() || attributes.overhang_attributes->has_full_overhangs_flow ||
const ExtrusionPropertyOverhang *overhang_attributes = path.overhang_attributes();
if (overhang_attributes == nullptr || overhang_attributes->has_full_overhangs_flow ||
!region_config.overhangs_flow_ratio.is_enabled() || !region_config.overhangs_dynamic_flow.is_enabled())
return;
const OverhangAttributes &overhang_attr = *attributes.overhang_attributes;
const double nzl_diam_mm = print_config.nozzle_diameter.get_at(extruder_id);
GraphData graph = region_config.overhangs_dynamic_flow.value;
@ -341,16 +349,16 @@ void apply_overhang_flow(ExtrusionPath &path,
graph.graph_points[graph.begin_idx].x() = 0;
graph.graph_points[graph.end_idx - 1].y() = 100;
// interpolate
assert(attributes.overhang_attributes->start_distance_from_prev_layer >= 0);
assert(attributes.overhang_attributes->end_distance_from_prev_layer >= 0);
assert(overhang_attributes->start_distance_from_prev_layer >= 0);
assert(overhang_attributes->end_distance_from_prev_layer >= 0);
float extrusion_ratio =
(graph.interpolate(std::min(1., attributes.overhang_attributes->start_distance_from_prev_layer / max_dynamic_distance_mm))+
graph.interpolate(std::min(1., attributes.overhang_attributes->end_distance_from_prev_layer / max_dynamic_distance_mm)))/2;
(graph.interpolate(std::min(1., overhang_attributes->start_distance_from_prev_layer / max_dynamic_distance_mm))+
graph.interpolate(std::min(1., overhang_attributes->end_distance_from_prev_layer / max_dynamic_distance_mm)))/2;
assert(extrusion_ratio >= 0 && extrusion_ratio <= 1);
double max_overhang_mm =
std::max(attributes.overhang_attributes->start_distance_from_prev_layer,
attributes.overhang_attributes->end_distance_from_prev_layer);
std::max(overhang_attributes->start_distance_from_prev_layer,
overhang_attributes->end_distance_from_prev_layer);
Flow overhang_flow = layer_region.bridging_flow(attributes.role.is_external() ? FlowRole::frExternalPerimeter :
FlowRole::frPerimeter);

View file

@ -258,11 +258,11 @@ ExtrusionEntityCollection calculate_and_split_overhanging_extrusions(
const AABBTreeLines::LinesDistancer<CurledLine> &prev_layer_curled_lines,
const double &nzl_diam);
float calculate_overhang_speed(const ExtrusionAttributes &attributes,
float calculate_overhang_speed(const ExtrusionPath &path,
const FullPrintConfig &config,
size_t extruder_id);
float calculate_overhang_fan_speed(const ExtrusionAttributes &attributes,
float calculate_overhang_fan_speed(const ExtrusionPath &path,
const FullPrintConfig &config,
size_t extruder_id);

View file

@ -21,7 +21,7 @@ const std::string& FanMover::process_gcode(const std::string& gcode, bool flush)
m_buffer_time_size += data.time;
}
if(!gcode.empty())
if (!gcode.empty())
m_parser.parse_buffer(gcode,
[this](GCodeReader& reader, const GCodeReader::GCodeLine& line) { /*m_process_output += line.raw() + "\n";*/ this->_process_gcode_line(reader, line); });
@ -40,22 +40,22 @@ const std::string& FanMover::process_gcode(const std::string& gcode, bool flush)
return m_process_output;
}
bool is_end_of_word(char c) {
return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == 0;
}
namespace FanMover_func {
float get_axis_value(const std::string& line, char axis)
bool is_end_of_word(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == 0; }
float get_axis_value(const std::string &line, char axis)
{
char match[3] = " X";
match[1] = axis;
match[1] = axis;
size_t pos = line.find(match) + 2;
//size_t end = std::min(line.find(' ', pos + 1), line.find(';', pos + 1));
// size_t end = std::min(line.find(' ', pos + 1), line.find(';', pos + 1));
// Try to parse the numeric value.
const char* c = line.c_str();
char* pend = nullptr;
errno = 0;
double v = strtod(c + pos, &pend);
const char *c = line.c_str();
char * pend = nullptr;
errno = 0;
double v = strtod(c + pos, &pend);
if (pend != nullptr && errno == 0 && pend != c) {
// The axis value has been parsed correctly.
return float(v);
@ -63,33 +63,52 @@ float get_axis_value(const std::string& line, char axis)
return NAN;
}
void change_axis_value(std::string& line, char axis, const float new_value, const int decimal_digits)
void change_axis_value(std::string &line, char axis, const float new_value, const int decimal_digits)
{
char match[3] = " X";
match[1] = axis;
match[1] = axis;
size_t pos = line.find(match) + 2;
size_t end = std::min(line.find(' ', pos + 1), line.find(';', pos + 1));
line = line.replace(pos, end - pos, to_string_nozero(new_value, decimal_digits));
line = line.replace(pos, end - pos, to_string_nozero(new_value, decimal_digits));
}
int16_t get_fan_speed(const std::string &line, GCodeFlavor flavor) {
int16_t get_fan_speed(const std::string &line, GCodeFlavor flavor)
{
if (line.compare(0, 4, "M106") == 0) {
if (flavor == (gcfMach3) || flavor == (gcfMachinekit)) {
return (int16_t)get_axis_value(line, 'P');
return (int16_t) FanMover_func::get_axis_value(line, 'P');
} else {
return (int16_t)get_axis_value(line, 'S');
return (int16_t) FanMover_func::get_axis_value(line, 'S');
}
} else if (line.compare(0, 4, "M127") == 0 || line.compare(0, 4, "M107") == 0) {
return 0;
} else if ((flavor == (gcfMakerWare) || flavor == (gcfSailfish)) && line.compare(0, 4, "M126") == 0) {
return (int16_t)get_axis_value(line, 'T');
return (int16_t) FanMover_func::get_axis_value(line, 'T');
} else {
return -1;
}
}
bool parse_number(const std::string_view sv, int& out)
{
{
// Legacy conversion, which is costly due to having to make a copy of the string before conversion.
try {
assert(sv.size() < 1024);
assert(sv.data() != nullptr);
std::string str{ sv };
size_t read = 0;
out = std::stoi(str, &read);
return str.size() == read;
}
catch (...) {
return false;
}
}
}
} // namespace FanMover_func
void FanMover::_put_in_middle_G1(std::list<BufferData>::iterator item_to_split, float nb_sec_since_itemtosplit_start, BufferData &&line_to_write, float max_time) {
assert(item_to_split != m_buffer.end());
// if the fan is at the end of the g1 and the diff is less than 10% of the delay, then don't bother
@ -115,31 +134,31 @@ void FanMover::_put_in_middle_G1(std::list<BufferData>::iterator item_to_split,
before.dx = item_to_split->dx * percent;
item_to_split->x += before.dx;
item_to_split->dx = item_to_split->dx * (1-percent);
change_axis_value(before.raw, 'X', before.x + before.dx, 3);
FanMover_func::change_axis_value(before.raw, 'X', before.x + before.dx, 3);
}
if (item_to_split->dy != 0) {
before.dy = item_to_split->dy * percent;
item_to_split->y += before.dy;
item_to_split->dy = item_to_split->dy * (1 - percent);
change_axis_value(before.raw, 'Y', before.y + before.dy, 3);
FanMover_func::change_axis_value(before.raw, 'Y', before.y + before.dy, 3);
}
if (item_to_split->dz != 0) {
before.dz = item_to_split->dz * percent;
item_to_split->z += before.dz;
item_to_split->dz = item_to_split->dz * (1 - percent);
change_axis_value(before.raw, 'Z', before.z + before.dz, 3);
FanMover_func::change_axis_value(before.raw, 'Z', before.z + before.dz, 3);
}
if (item_to_split->de != 0) {
if (relative_e) {
before.de = item_to_split->de * percent;
change_axis_value(before.raw, 'E', before.de, 5);
FanMover_func::change_axis_value(before.raw, before.e_axis_char, before.de, 5);
item_to_split->de = item_to_split->de * (1 - percent);
change_axis_value(item_to_split->raw, 'E', item_to_split->de, 5);
FanMover_func::change_axis_value(item_to_split->raw, item_to_split->e_axis_char, item_to_split->de, 5);
} else {
before.de = item_to_split->de * percent;
item_to_split->e += before.de;
item_to_split->de = item_to_split->de * (1 - percent);
change_axis_value(before.raw, 'E', before.e + before.de, 5);
FanMover_func::change_axis_value(before.raw, before.e_axis_char, before.e + before.de, 5);
}
}
//add before then line_to_write, then there is the modified data.
@ -163,26 +182,26 @@ void FanMover::_print_in_middle_G1(BufferData& line_to_split, float nb_sec_from_
//will also print before if line_to_split.time == 0
m_process_output += line_to_write + (line_to_write.back() == '\n' ? "" : "\n");
m_process_output += line_to_split.raw + "\n";
}else if(line_to_split.raw.size() > 2
} else if (line_to_split.raw.size() > 2
&& line_to_split.raw[0] == 'G' && line_to_split.raw[1] == '1' && line_to_split.raw[2] == ' ') {
float percent = nb_sec_from_item_start / line_to_split.time;
std::string before = line_to_split.raw;
std::string& after = line_to_split.raw;
if (line_to_split.dx != 0) {
change_axis_value(before, 'X', line_to_split.x + line_to_split.dx * percent, 3);
FanMover_func::change_axis_value(before, 'X', line_to_split.x + line_to_split.dx * percent, 3);
}
if (line_to_split.dy != 0) {
change_axis_value(before, 'Y', line_to_split.y + line_to_split.dy * percent, 3);
FanMover_func::change_axis_value(before, 'Y', line_to_split.y + line_to_split.dy * percent, 3);
}
if (line_to_split.dz != 0) {
change_axis_value(before, 'Z', line_to_split.z + line_to_split.dz * percent, 3);
FanMover_func::change_axis_value(before, 'Z', line_to_split.z + line_to_split.dz * percent, 3);
}
if (line_to_split.de != 0) {
if (relative_e) {
change_axis_value(before, 'E', line_to_split.de * percent, 5);
change_axis_value(after, 'E', line_to_split.de * (1 - percent), 5);
FanMover_func::change_axis_value(before, line_to_split.e_axis_char, line_to_split.de * percent, 5);
FanMover_func::change_axis_value(after, line_to_split.e_axis_char, line_to_split.de * (1 - percent), 5);
} else {
change_axis_value(before, 'E', line_to_split.e + line_to_split.de * percent, 5);
FanMover_func::change_axis_value(before, line_to_split.e_axis_char, line_to_split.e + line_to_split.de * percent, 5);
}
}
m_process_output += before + "\n";
@ -218,37 +237,18 @@ std::string FanMover::_set_fan(int16_t speed, std::string_view comment) {
std::string str = GCodeWriter::set_fan(m_writer.config.gcode_flavor.value, m_writer.config.gcode_comments.value,
speed, tool ? tool->fan_offset() : 0, m_writer.config.fan_percentage.value,
comment);
if(!str.empty() && str.back() == '\n')
if (!str.empty() && str.back() == '\n')
return str.substr(0,str.size()-1);
return str;
}
bool parse_number(const std::string_view sv, int& out)
{
{
// Legacy conversion, which is costly due to having to make a copy of the string before conversion.
try {
assert(sv.size() < 1024);
assert(sv.data() != nullptr);
std::string str{ sv };
size_t read = 0;
out = std::stoi(str, &read);
return str.size() == read;
}
catch (...) {
return false;
}
}
}
//FIXME: add other firmware
// or just create that damn new gcode writer arch
void FanMover::_process_T(const std::string_view command)
{
if (command.length() > 1 && command[1] >= '0' && command[1] <= '9') {
int eid = 0;
if (!parse_number(command.substr(1), eid) || eid < 0 || eid > 255) {
if (!FanMover_func::parse_number(command.substr(1), eid) || eid < 0 || eid > 255) {
GCodeFlavor flavor = m_writer.config.gcode_flavor;
// Specific to the MMU2 V2 (see https://www.help.prusa3d.com/en/article/prusa-specific-g-codes_112173):
if ((flavor == gcfMarlinLegacy || flavor == gcfMarlinFirmware) && (command == "Tx" || command == "Tc" || command == "T?"))
@ -351,7 +351,7 @@ void FanMover::_process_gcode_line(GCodeReader& reader, const GCodeReader::GCode
}
case 'M':
{
fan_speed = get_fan_speed(line.raw(), m_writer.config.gcode_flavor);
fan_speed = FanMover_func::get_fan_speed(line.raw(), m_writer.config.gcode_flavor);
if (fan_speed >= 0) {
const auto fan_baseline = (m_writer.config.fan_percentage.value ? 100.0 : 255.0);
fan_speed = 100 * fan_speed / fan_baseline;
@ -405,7 +405,7 @@ void FanMover::_process_gcode_line(GCodeReader& reader, const GCodeReader::GCode
time_count -= it->time;
if (time_count< 0) {
//found something that is lower than us
_put_in_middle_G1(it, it->time + time_count, BufferData(std::string(line.raw()), 0, fan_speed, true), nb_seconds_delay);
_put_in_middle_G1(it, it->time + time_count, BufferData(std::string(line.raw()), line.e_char(), 0, fan_speed, true), nb_seconds_delay);
//found, stop
break;
}
@ -451,7 +451,7 @@ void FanMover::_process_gcode_line(GCodeReader& reader, const GCodeReader::GCode
//i'm printed by the m_current_kickstart
time = -1;
}
} else if(m_back_buffer_fan_speed < fan_speed - 10){ //only kickstart if more than 10% change
} else if (m_back_buffer_fan_speed < fan_speed - 10){ //only kickstart if more than 10% change
//don't write this line, as it will need to be delayed
time = -1;
//get the duration of kickstart
@ -459,7 +459,7 @@ void FanMover::_process_gcode_line(GCodeReader& reader, const GCodeReader::GCode
//if kickstart, write the M106 S[fan_baseline] first
//set the target speed and set the kickstart flag
put_in_buffer(BufferData(_set_fan(100, "kickstart fan")//m_writer.set_fan(100, true)); //FIXME extruder id (or use the gcode writer, but then you have to disable the multi-thread thing
, 0, fan_speed, true));
, 'P', 0, fan_speed, true));
//kickstart!
//m_process_output += m_writer.set_fan(100, true) + "\n";
//add the normal speed line for the future
@ -481,7 +481,7 @@ void FanMover::_process_gcode_line(GCodeReader& reader, const GCodeReader::GCode
}
}
} else {
if(!line.raw().empty() && line.raw().front() == ';')
if (!line.raw().empty() && line.raw().front() == ';')
{
if (line.raw().size() > 10 && line.raw().rfind(";TYPE:", 0) == 0) {
// get the type of the next extrusions
@ -502,7 +502,7 @@ void FanMover::_process_gcode_line(GCodeReader& reader, const GCodeReader::GCode
}
if (time >= 0) {
BufferData& new_data = put_in_buffer(BufferData(line.raw(), time, fan_speed));
BufferData& new_data = put_in_buffer(BufferData(line.raw(), line.e_char(), time, fan_speed));
if (line.has(Axis::X)) {
new_data.x = reader.x();
new_data.dx = line.dist_X(reader);
@ -538,7 +538,7 @@ void FanMover::_process_gcode_line(GCodeReader& reader, const GCodeReader::GCode
m_current_kickstart.time -= time;
if (m_current_kickstart.time < 0) {
// prev is possible because we just do an emplace_back.
_put_in_middle_G1(prev(m_buffer.end()), time + m_current_kickstart.time, BufferData{ m_current_kickstart.raw, 0, m_current_kickstart.fan_speed, true }, kickstart);
_put_in_middle_G1(prev(m_buffer.end()), time + m_current_kickstart.time, BufferData{ m_current_kickstart.raw, m_current_kickstart.e_axis_char, 0, m_current_kickstart.fan_speed, true }, kickstart);
}
}
}

View file

@ -13,28 +13,33 @@
namespace Slic3r {
class BufferData {
public:
//raw string, contains end position
std::string raw;
// time to go from start to end
float time;
int16_t fan_speed;
bool is_kickstart;
// start position
float x = 0, y = 0, z = 0, e = 0;
// delta to go to end position
float dx = 0, dy = 0, dz = 0, de = 0;
BufferData(std::string line, float time = 0, int16_t fan_speed = 0, float is_kickstart = false) : raw(line), time(time), fan_speed(fan_speed), is_kickstart(is_kickstart){
//avoid double \n
if(!line.empty() && line.back() == '\n') line.pop_back();
}
};
class FanMover
{
class BufferData
{
public:
// raw string, contains end position
std::string raw;
// time to go from start to end
float time;
int16_t fan_speed;
bool is_kickstart;
// start position
float x = 0, y = 0, z = 0, e = 0;
// delta to go to end position
float dx = 0, dy = 0, dz = 0, de = 0;
char e_axis_char = 'E';
BufferData(std::string line, char e_axis, float time = 0, int16_t fan_speed = 0, float is_kickstart = false)
: raw(line), time(time), fan_speed(fan_speed), is_kickstart(is_kickstart), e_axis_char(e_axis)
{
// avoid double \n
if (!line.empty() && line.back() == '\n')
line.pop_back();
}
};
private:
const std::regex regex_fan_speed;
const float nb_seconds_delay; // in s
const bool with_D_option;
const bool relative_e;
@ -65,12 +70,22 @@ private:
std::string m_process_output;
public:
FanMover(const GCodeWriter& writer, const float nb_seconds_delay, const bool with_D_option, const bool relative_e,
const bool only_overhangs, const float kickstart)
: regex_fan_speed("S[0-9]+"),
nb_seconds_delay(nb_seconds_delay>0 ? std::max(0.01f,nb_seconds_delay) : 0),
with_D_option(with_D_option)
, relative_e(relative_e), only_overhangs(only_overhangs), kickstart(kickstart), m_writer(writer){}
FanMover(const GCodeWriter &writer,
const FullPrintConfig & config,
const float nb_seconds_delay,
const bool with_D_option,
const bool relative_e,
const bool only_overhangs,
const float kickstart) :
nb_seconds_delay(nb_seconds_delay > 0 ? std::max(0.01f, nb_seconds_delay) : 0)
, with_D_option(with_D_option)
, relative_e(relative_e)
, only_overhangs(only_overhangs)
, kickstart(kickstart)
, m_writer(writer)
{
m_parser.apply_config(config);
}
// Adds the gcode contained in the given string to the analysis and returns it after removing the workcodes
const std::string& process_gcode(const std::string& gcode, bool flush);

View file

@ -678,7 +678,7 @@ void GCodeProcessor::apply_config(const PrintConfig& config)
// With MM setups like Prusa MMU2, the filaments may be expected to be parked at the beginning.
// Remember the parking position so the initial load is not included in filament estimate.
if (m_single_extruder_multi_material && extruders_count > 1 && config.wipe_tower) {
if (m_single_extruder_multi_material && extruders_count > 1 /*&& config.wipe_tower*/) {
m_parking_position = float(config.parking_pos_retraction.value);
m_extra_loading_move = float(config.extra_loading_move);
}
@ -2207,7 +2207,7 @@ void GCodeProcessor::process_tags(const std::string_view comment, bool producers
if (m_extruder_id == extruder_id) {
m_cp_color.current = m_extruder_colors[extruder_id];
store_move_vertex(EMoveType::Color_change);
CustomGCode::Item item = { static_cast<double>(m_end_position[2]), CustomGCode::ColorChange, extruder_id + 1, color, "" };
CustomGCode::Item item = { Layer::scale_to_layer_coord(m_end_position[2]), CustomGCode::ColorChange, extruder_id + 1, color, "" };
m_result.custom_gcode_per_print_z.emplace_back(item);
m_options_z_corrector.set();
process_custom_gcode_time(CustomGCode::ColorChange);
@ -2220,7 +2220,7 @@ void GCodeProcessor::process_tags(const std::string_view comment, bool producers
// pause print tag
if (comment == reserved_tag(ETags::Pause_Print)) {
store_move_vertex(EMoveType::Pause_Print);
CustomGCode::Item item = { static_cast<double>(m_end_position[2]), CustomGCode::PausePrint, m_extruder_id + 1, "", "" };
CustomGCode::Item item = { Layer::scale_to_layer_coord(m_end_position[2]), CustomGCode::PausePrint, m_extruder_id + 1, "", "" };
m_result.custom_gcode_per_print_z.emplace_back(item);
m_options_z_corrector.set();
process_custom_gcode_time(CustomGCode::PausePrint);
@ -2230,7 +2230,7 @@ void GCodeProcessor::process_tags(const std::string_view comment, bool producers
// custom code tag
if (comment == reserved_tag(ETags::Custom_Code)) {
store_move_vertex(EMoveType::Custom_GCode);
CustomGCode::Item item = { static_cast<double>(m_end_position[2]), CustomGCode::Custom, m_extruder_id + 1, "", "" };
CustomGCode::Item item = { Layer::scale_to_layer_coord(m_end_position[2]), CustomGCode::Custom, m_extruder_id + 1, "", "" };
m_result.custom_gcode_per_print_z.emplace_back(item);
m_options_z_corrector.set();
return;

View file

@ -490,7 +490,7 @@ namespace Slic3r {
move.position = position;
move.height = height;
m_result.moves.erase(m_result.moves.begin() + *m_move_id);
m_result.custom_gcode_per_print_z[*m_custom_gcode_per_print_z_id].print_z = position.z();
m_result.custom_gcode_per_print_z[*m_custom_gcode_per_print_z_id].print_z_ = Layer::scale_to_layer_coord(position.z());
reset();
}

View file

@ -254,6 +254,14 @@ std::string GCodeWriter::write_pressure_advance(double pa) {
return gcode;
}
int16_t GCodeWriter::get_temperature(int tool) {
//use m_tool if tool isn't set
if (tool < 0 && m_tool != nullptr)
tool = m_tool->id();
return m_last_temperature;
}
std::string GCodeWriter::set_temperature(const int16_t temperature, bool wait, int tool)
{
//use m_tool if tool isn't set
@ -707,7 +715,7 @@ std::string GCodeWriter::travel_to_xyz(const Vec3d &point, const bool is_lift, c
}
m_pos = point;
GCodeG1Formatter w(this->get_default_gcode_formatter());
bool has_x_y = w.emit_xy(point.head<2>(), m_pos_str_x, m_pos_str_y);
if (!has_x_y) {
@ -748,6 +756,22 @@ std::string GCodeWriter::travel_to_z(const double z, const std::string_view comm
return this->get_travel_to_z_gcode(z, comment);
}
std::string GCodeWriter::ensure_z(const double z, const std::string_view comment) {
/* If target Z is lower than current Z but higher than nominal Z
we don't perform the move but we only adjust the nominal Z by
reducing the lift amount that will be used for unlift. */
// note that if we move but it's lower and we are lifted, we can wait a bit for unlifting, to avoid possible dance on layer change.
double current_z = z < 0 ? (m_pos.z() - m_lifted) : z;
if (current_z < m_pos.z()) {
m_lifted = m_pos.z() - current_z;
if (std::abs(m_lifted) < EPSILON)
m_lifted = 0.;
current_z = m_pos.z();
} else {
m_lifted = 0.;
}
return this->get_travel_to_z_gcode(current_z, comment);
}
std::string GCodeWriter::get_travel_to_z_gcode(const double z, const std::string_view comment)
{
@ -804,6 +828,19 @@ void GCodeWriter::_extrude_e(GCodeFormatter &w, double dE)
}
}
std::string GCodeWriter::extrude_to_e(const double dE, const double speed_mm_s, const std::string_view comment)
{
assert(dE == dE);
GCodeG1Formatter w(this->get_default_gcode_formatter());
_extrude_e(w, dE);
if (speed_mm_s > 0) {
w.emit_f(speed_mm_s * 60.);
}
w.emit_comment(this->config.gcode_comments, comment);
return write_acceleration() + w.string();
}
std::string GCodeWriter::extrude_to_xy(const Vec2d &point, const double dE, const std::string_view comment)
{
assert(dE == dE);
@ -1100,7 +1137,7 @@ std::string GCodeWriter::unretract()
gcode += w.string();
}
}
return gcode;
}

View file

@ -56,6 +56,7 @@ public:
const Tool* get_tool(uint16_t id) const;
std::string preamble();
std::string postamble() const;
int16_t get_temperature(int tool = -1);
std::string set_temperature(int16_t temperature, bool wait = false, int tool = -1);
std::string set_bed_temperature(uint32_t temperature, bool wait = false);
void set_pressure_advance(double pa);
@ -84,9 +85,12 @@ public:
std::string travel_arc_to_xy(const Vec2d& point, const Vec2d& center_offset, const bool is_ccw, const double speed, const std::string_view comment);
std::string travel_to_xyz(const Vec3d &point, const bool is_lift, const double speed = 0.0, const std::string_view comment = {});
std::string travel_to_z(const double z, const std::string_view comment = {});
// like travel_to_z, but force write the z to the current z (or z if higher)
std::string ensure_z(const double z = -1, const std::string_view comment = {});
// low-level method to force a z travel, disregarding the lift and other thigns. Prefer using "travel_to_z" "lift" and "unlift".
std::string get_travel_to_z_gcode(const double z, const std::string_view comment = {});
bool will_move_z(const double z) const;
std::string extrude_to_e(const double dE, const double speed_mm_s = 0.0, const std::string_view comment = {});
std::string extrude_to_xy(const Vec2d &point, const double dE, const std::string_view comment = {});
std::string extrude_arc_to_xy(const Vec2d& point, const Vec2d& center_offset, const double dE, const bool is_ccw, const std::string_view comment = {}); //BBS: generate G2 or G3 extrude which moves by arc
std::string extrude_arc_to_xyz(const Vec3d& point, const Vec2d& center_offset, const double dE, const bool is_ccw, const std::string_view comment = {}); //BBS: generate G2 or G3 extrude which moves by arc

View file

@ -110,23 +110,30 @@ BoundingBoxf get_print_extrusions_extents(const Print &print)
return bbox;
}
BoundingBoxf get_print_object_extrusions_extents(const PrintObject &print_object, const coordf_t max_print_z)
BoundingBoxf get_print_object_extrusions_extents(const PrintObject &print_object, const coord_t max_print_z)
{
BoundingBoxf bbox;
for (const Layer *layer : print_object.layers()) {
if (layer->print_z > max_print_z)
if (layer->scaled_print_z() > max_print_z)
break;
BoundingBoxf bbox_this;
for (const LayerRegion *layerm : layer->regions()) {
bbox_this.merge(extrusionentity_extents(layerm->perimeters()));
for (const ExtrusionEntity *ee : layerm->fills())
// fill represents infill extrusions of a single island.
bbox_this.merge(extrusionentity_extents(*dynamic_cast<const ExtrusionEntityCollection*>(ee)));
for (const LayerSliceIslandPtr &layer_island_ptr : layer->islands()) {
for (const LayerRegionIslandPtr &region_island_ptr : layer_island_ptr->regions_islands()) {
if (region_island_ptr->has_extrusion(LayerRegionIsland::PERIMETERS)) {
bbox_this.merge(extrusionentity_extents(region_island_ptr->extrusion(LayerRegionIsland::PERIMETERS)));
}
if (region_island_ptr->has_extrusion(LayerRegionIsland::INFILLS)) {
bbox_this.merge(extrusionentity_extents(region_island_ptr->extrusion(LayerRegionIsland::INFILLS)));
}
// 2 next take care of the case 'dynamic_cast<const SupportLayer*>(layer);'
if (region_island_ptr->has_extrusion(LayerRegionIsland::SUPPORT)) {
bbox_this.merge(extrusionentity_extents(region_island_ptr->extrusion(LayerRegionIsland::SUPPORT)));
}
if (region_island_ptr->has_extrusion(LayerRegionIsland::SUPPORT_INTERFACE)) {
bbox_this.merge(extrusionentity_extents(region_island_ptr->extrusion(LayerRegionIsland::SUPPORT_INTERFACE)));
}
}
}
const SupportLayer *support_layer = dynamic_cast<const SupportLayer*>(layer);
if (support_layer)
for (const ExtrusionEntity *extrusion_entity : support_layer->support_fills.entities())
bbox_this.merge(extrusionentity_extents(extrusion_entity));
for (const PrintInstance &instance : print_object.instances()) {
BoundingBoxf bbox_translated(bbox_this);
bbox_translated.translate(unscale(instance.shift));
@ -138,17 +145,17 @@ BoundingBoxf get_print_object_extrusions_extents(const PrintObject &print_object
// Returns a bounding box of a projection of the wipe tower for the layers <= max_print_z.
// The projection does not contain the priming regions.
BoundingBoxf get_wipe_tower_extrusions_extents(const Print &print, const coordf_t max_print_z)
BoundingBoxf get_wipe_tower_extrusions_extents(const Print &print, const coord_t max_print_z)
{
// Wipe tower extrusions are saved as if the tower was at the origin with no rotation
// We need to get position and angle of the wipe tower to transform them to actual position.
Transform2d trafo =
Eigen::Translation2d(print.config().wipe_tower_x.value, print.config().wipe_tower_y.value) *
Eigen::Rotation2Dd(Geometry::deg2rad(print.config().wipe_tower_rotation_angle.value));
Eigen::Translation2d(print.default_object_config().wipe_tower_x.value, print.default_object_config().wipe_tower_y.value) *
Eigen::Rotation2Dd(Geometry::deg2rad(print.default_object_config().wipe_tower_rotation_angle.value));
BoundingBoxf bbox;
for (const std::vector<WipeTower::ToolChangeResult> &tool_changes : print.wipe_tower_data().tool_changes) {
if (! tool_changes.empty() && tool_changes.front().print_z > max_print_z)
if (! tool_changes.empty() && Layer::scale_to_layer_coord(tool_changes.front().print_z) > max_print_z)
break;
for (const WipeTower::ToolChangeResult &tcr : tool_changes) {
for (size_t i = 1; i < tcr.extrusions.size(); ++ i) {

View file

@ -21,11 +21,11 @@ class BoundingBoxf;
BoundingBoxf get_print_extrusions_extents(const Print &print);
// Returns a bounding box of a projection of the object extrusions at z <= max_print_z.
BoundingBoxf get_print_object_extrusions_extents(const PrintObject &print_object, const coordf_t max_print_z);
BoundingBoxf get_print_object_extrusions_extents(const PrintObject &print_object, const coord_t max_print_z);
// Returns a bounding box of a projection of the wipe tower for the layers <= max_print_z.
// The projection does not contain the priming regions.
BoundingBoxf get_wipe_tower_extrusions_extents(const Print &print, const coordf_t max_print_z);
BoundingBoxf get_wipe_tower_extrusions_extents(const Print &print, const coord_t max_print_z);
// Returns a bounding box of the wipe tower priming extrusions.
BoundingBoxf get_wipe_tower_priming_extrusions_extents(const Print &print);

View file

@ -447,7 +447,7 @@ struct GlobalModelInfo {
;
//Extract perimeter polylines of the given layer
PolylineWithEnds extract_perimeter_polylines(const Layer *layer, const SeamPosition configured_seam_preference,
std::vector<const LayerRegion*> &corresponding_regions_out) {
std::vector<const LayerRegion*> &corresponding_regions_for_flow_out) {
PolylineWithEnds polylines;
@ -589,49 +589,56 @@ PolylineWithEnds extract_perimeter_polylines(const Layer *layer, const SeamPosit
this->perimeter_type = current_layer_region->region().config().perimeter_generator.value;
}
}
} visitor(corresponding_regions_out, &polylines, configured_seam_preference);
} visitor(corresponding_regions_for_flow_out, &polylines, configured_seam_preference);
for (const LayerRegion *layer_region : layer->regions()) {
for (const ExtrusionEntity *ex_entity : layer_region->perimeters()) {
visitor.set_current_layer_region(layer_region);
assert(!ex_entity->empty());
if (ex_entity->empty()) continue;
assert(ex_entity->is_collection()); //collection of inner, outer, and overhang perimeters
ex_entity->visit(visitor);
if (polylines.empty()) {
// maybe only thin walls?
visitor.also_thin_walls = true;
for (const LayerSliceIslandPtr &layer_island_ptr : layer->islands()) {
for (const LayerRegionIslandPtr &region_island_ptr : layer_island_ptr->regions_islands()) {
if(!region_island_ptr->has_extrusion(LayerRegionIsland::PERIMETERS)) continue;
for (const ExtrusionEntity *ex_entity : region_island_ptr->extrusion(LayerRegionIsland::PERIMETERS)) {
const LayerRegion *lregion = *region_island_ptr->regions().begin();
visitor.set_current_layer_region(lregion);
assert(!ex_entity->empty());
if (ex_entity->empty())
continue;
assert(ex_entity->is_collection()); // collection of inner, outer, and overhang perimeters
ex_entity->visit(visitor);
if (polylines.empty()) {
// can happen if the external is fully an overhang
bool old = visitor.also_overhangs;
visitor.also_overhangs = true;
// maybe only thin walls?
visitor.also_thin_walls = true;
ex_entity->visit(visitor);
visitor.also_overhangs = old;
if (polylines.empty()) {
// shouldn't happen
assert(ex_entity->role() == ExtrusionRole::ThinWall || layer_region->region().config().perimeter_generator == PerimeterGeneratorType::Arachne); // no loops
//ex_entity->visit(visitor);
// what to do in this case?
Points pts;
ex_entity->collect_points(pts);
assert(!pts.empty());
bool is_loop = pts.front() == pts.back();
assert(!is_loop);
polylines.emplace_back(std::move(pts), true, !is_loop, PolylineWithEnd::PolyDir::BOTH);
corresponding_regions_out.push_back(layer_region);
// can happen if the external is fully an overhang
bool old = visitor.also_overhangs;
visitor.also_overhangs = true;
ex_entity->visit(visitor);
visitor.also_overhangs = old;
if (polylines.empty()) {
// shouldn't happen
assert(ex_entity->role() == ExtrusionRole::ThinWall ||
lregion->region().config().perimeter_generator ==
PerimeterGeneratorType::Arachne); // no loops
// ex_entity->visit(visitor);
// what to do in this case?
Points pts;
ex_entity->collect_points(pts);
assert(!pts.empty());
bool is_loop = pts.front() == pts.back();
assert(!is_loop);
polylines.emplace_back(std::move(pts), true, !is_loop, PolylineWithEnd::PolyDir::BOTH);
corresponding_regions_for_flow_out.push_back(lregion);
}
}
visitor.also_thin_walls = false;
}
visitor.also_thin_walls = false;
}
}
}
if (polylines.empty()) { // If there are no perimeter polylines/polygons for whatever reason (disabled perimeters .. ) insert dummy point
// it is easier than checking everywhere if the layer is not emtpy, no seam will be placed to this layer anyway
polylines.emplace_back(Points{ /*Point { 0, 0 }*/ }, true, true, PolylineWithEnd::PolyDir::BOTH);
corresponding_regions_out.push_back(nullptr);
corresponding_regions_for_flow_out.push_back(nullptr);
}
assert(corresponding_regions_out.size() == polylines.size());
assert(corresponding_regions_for_flow_out.size() == polylines.size());
return polylines;
}
@ -639,7 +646,7 @@ PolylineWithEnds extract_perimeter_polylines(const Layer *layer, const SeamPosit
// Compute its type (Enfrocer,Blocker), angle, and position
//each SeamCandidate also contains pointer to shared Perimeter structure representing the polyline
// if Custom Seam modifiers are present, oversamples the polyline if necessary to better fit user intentions
void process_perimeter_polylines(const PolylineWithEnd &orig_polyline, float z_coord, const LayerRegion *region,
void process_perimeter_polylines(const PolylineWithEnd &orig_polyline, float z_coord, const LayerRegion *region_for_flow,
const GlobalModelInfo &global_model_info, PrintObjectSeamData::LayerSeams &result) {
if (orig_polyline.size() <= 1) {
return;
@ -651,7 +658,7 @@ void process_perimeter_polylines(const PolylineWithEnd &orig_polyline, float z_c
polyline.reverse();
assert(polyline.direction == PolylineWithEnd::PolyDir::CCW);
}
float angle_arm_len = region != nullptr ? region->flow(FlowRole::frExternalPerimeter).nozzle_diameter() : 0.5f;
float angle_arm_len = region_for_flow != nullptr ? region_for_flow->flow(FlowRole::frExternalPerimeter).nozzle_diameter() : 0.5f;
std::vector<float> lengths { };
for (size_t point_idx = 0; point_idx < polyline.size() - 1; ++point_idx) {
@ -670,7 +677,7 @@ void process_perimeter_polylines(const PolylineWithEnd &orig_polyline, float z_c
std::queue<Vec3f> oversampled_points { };
size_t orig_angle_index = 0;
perimeter.start_index = result.points.size();
perimeter.flow_width = region != nullptr ? region->flow(FlowRole::frExternalPerimeter).width() : 0.0f;
perimeter.flow_width = region_for_flow != nullptr ? region_for_flow->flow(FlowRole::frExternalPerimeter).width() : 0.0f;
bool some_point_enforced = false;
while (!orig_polyline_points.empty() || !oversampled_points.empty()) {
EnforcedBlockedSeamPoint type = EnforcedBlockedSeamPoint::Neutral;
@ -1255,13 +1262,13 @@ void SeamPlacer::gather_seam_candidates(const PrintObject *po, const SeamPlacerI
for (size_t layer_idx = next_layer_idx++; layer_idx < po->layers().size(); layer_idx = next_layer_idx++) {
PrintObjectSeamData::LayerSeams &layer_seams = seam_data.layers[layer_idx];
const Layer *layer = po->get_layer(layer_idx);
auto unscaled_z = layer->slice_z;
std::vector<const LayerRegion*> regions;
double unscaled_z = layer->slice_z;
std::vector<const LayerRegion*> regions_for_flow;
//NOTE corresponding region ptr may be null, if the layer has zero perimeters
PolylineWithEnds polygons_and_lines = extract_perimeter_polylines(layer, configured_seam_preference, regions);
PolylineWithEnds polygons_and_lines = extract_perimeter_polylines(layer, configured_seam_preference, regions_for_flow);
for (size_t poly_index = 0; poly_index < polygons_and_lines.size(); ++poly_index) {
process_perimeter_polylines(polygons_and_lines[poly_index], unscaled_z,
regions[poly_index], global_model_info, layer_seams);
regions_for_flow[poly_index], global_model_info, layer_seams);
}
auto functor = SeamCandidateCoordinateFunctor { layer_seams.points };
seam_data.layers[layer_idx].points_tree =
@ -1301,13 +1308,16 @@ void SeamPlacer::calculate_overhangs_and_layer_embedding(const PrintObject *po)
}
for (size_t layer_idx = r.begin(); layer_idx < r.end(); ++layer_idx) {
size_t regions_with_perimeter = 0;
for (const LayerRegion *region : po->layers()[layer_idx]->regions()) {
if (region->perimeters().size() > 0) {
regions_with_perimeter++;
size_t islands_with_perimeter = 0;
for (const LayerSliceIslandPtr &layer_island_ptr : po->layers()[layer_idx]->islands()) {
for (const LayerRegionIslandPtr &region_island_ptr : layer_island_ptr->regions_islands()) {
if (region_island_ptr->has_extrusion(LayerRegionIsland::PERIMETERS) &&
region_island_ptr->extrusion(LayerRegionIsland::PERIMETERS).size() > 0) {
islands_with_perimeter++;
}
}
};
bool should_compute_layer_embedding = regions_with_perimeter > 1;
}
bool should_compute_layer_embedding = islands_with_perimeter > 1;
std::unique_ptr<PerimeterDistancer> current_layer_distancer = std::make_unique<PerimeterDistancer>(
to_unscaled_linesf(po->layers()[layer_idx]->lslices()));
@ -1877,7 +1887,7 @@ std::tuple<bool,std::optional<Vec3f>> get_seam_from_modifier(const Layer& layer,
// get zs
seam_mesh->zs.clear();
for (const Layer *layer : po->layers()) {
seam_mesh->zs.push_back(float(layer->print_z));
seam_mesh->zs.push_back(float(layer->unscaled_print_z()));
}
std::vector<Polygons> layers = slice_mesh(seam_mesh->mesh.its, seam_mesh->zs, slicing_params);
assert(seam_mesh->zs.size() == layers.size());
@ -1908,19 +1918,19 @@ std::tuple<bool,std::optional<Vec3f>> get_seam_from_modifier(const Layer& layer,
Vec3d center_pos = (seam_mesh->bb_volume.min + seam_mesh->bb_volume.max) / 2;
double sphere_radius = std::min(seam_mesh->bb_volume.size().x() / 2, seam_mesh->bb_volume.size().y() / 2);
if (model_volume->type() == ModelVolumeType::SEAM_POSITION_CENTER) {
test_lambda_z = std::abs(layer.print_z - center_pos.z());
test_lambda_z = std::abs(layer.unscaled_print_z() - center_pos.z());
} else if (model_volume->type() == ModelVolumeType::SEAM_POSITION_CENTER_Z) {
double min_z = seam_mesh->bb_volume.min.z();
double max_z = seam_mesh->bb_volume.max.z();
assert(min_z < max_z);
if (layer.print_z + EPSILON < min_z || layer.print_z > max_z + EPSILON || seam_mesh->layers_bb.empty()) {
if (layer.unscaled_print_z() + EPSILON < min_z || layer.unscaled_print_z() > max_z + EPSILON || seam_mesh->layers_bb.empty()) {
// out of z, don't take it into account
continue;
}
// use slices to get the real center_pos
// find nearest z
size_t lidx = 0;
for (; lidx < seam_mesh->layers_bb.size() && seam_mesh->zs[lidx] + EPSILON < layer.print_z ; ++lidx) {}
for (; lidx < seam_mesh->layers_bb.size() && seam_mesh->zs[lidx] + EPSILON < layer.unscaled_print_z() ; ++lidx) {}
if (!seam_mesh->layers_bb[lidx].empty()) {
// set it
Point pt = (seam_mesh->layers_bb[lidx].min + seam_mesh->layers_bb[lidx].max) / 2;
@ -1931,13 +1941,13 @@ std::tuple<bool,std::optional<Vec3f>> get_seam_from_modifier(const Layer& layer,
} else if(model_volume->type() == ModelVolumeType::SEAM_POSITION_INSIDE && !loop.paths.empty()) {
double min_z = seam_mesh->bb_volume.min.z();
double max_z = seam_mesh->bb_volume.max.z();
if (layer.print_z + EPSILON < min_z || layer.print_z > max_z + EPSILON || seam_mesh->layers_contour.empty()) {
if (layer.unscaled_print_z() + EPSILON < min_z || layer.unscaled_print_z() > max_z + EPSILON || seam_mesh->layers_contour.empty()) {
// out of z, don't take it into account
continue;
}
//get layer idx
size_t lidx = 0;
for (; lidx < seam_mesh->layers_contour.size() && seam_mesh->zs[lidx] + EPSILON < layer.print_z ; ++lidx) {}
for (; lidx < seam_mesh->layers_contour.size() && seam_mesh->zs[lidx] + EPSILON < layer.unscaled_print_z() ; ++lidx) {}
// TODO Grid optimisation
Polyline loop_polyline = loop.as_polyline().to_polyline(scale_t(loop.paths.front().width()));
//move the object's polyline to its plater position.
@ -1979,7 +1989,7 @@ std::tuple<bool,std::optional<Vec3f>> get_seam_from_modifier(const Layer& layer,
Point xy_lambda = Point::new_scale(center_pos.x(), center_pos.y());
Point nearest = polygon.point_projection(xy_lambda).first;
Vec3d polygon_3dpoint{ unscaled(nearest.x()), unscaled(nearest.y()), (double)layer.print_z };
Vec3d polygon_3dpoint{ unscaled(nearest.x()), unscaled(nearest.y()), layer.unscaled_print_z() };
double test_lambda_dist = (polygon_3dpoint - center_pos).norm();
max_lambda_radius = std::max(max_lambda_radius, sphere_radius);

View file

@ -41,7 +41,7 @@ struct TriangleMeshForSeam
TriangleMesh mesh;
BoundingBoxf3 bb_volume;
//std::vector<Vec3i32> face_edge_ids;
std::vector<float> zs;
std::vector<float> zs; //TODO convert from float into coord_t
std::vector<BoundingBox> layers_bb;
std::vector<Polygon> layers_contour;
};

View file

@ -0,0 +1,452 @@
#include "TemperatureMover.hpp"
#include "GCodeReader.hpp"
#include "LocalesUtils.hpp"
#include <iomanip>
#include <boost/log/trivial.hpp>
namespace Slic3r {
const std::string& TemperatureMover::process_gcode(const std::string& gcode, bool flush)
{
m_process_output = "";
if (m_max_seconds_delay > 0) {
// recompute buffer time to recover from rounding
m_buffer_time_size = 0;
for (auto &data : m_buffer) {
assert(data.time >= 0 && data.time < 1000000 && !std::isnan(data.time));
m_buffer_time_size += data.time;
}
if (!gcode.empty())
m_parser.parse_buffer(gcode, [this](GCodeReader &reader, const GCodeReader::GCodeLine &line) {
/*m_process_output += line.raw() + "\n";*/
this->_process_gcode_line(reader, line);
});
if (flush) {
while (!m_buffer.empty()) {
write_buffer_data();
}
}
return m_process_output;
} else {
// not activated, skip processing and return the gcode as is.
return gcode;
}
}
namespace TemperatureMover_func {
bool is_end_of_word(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == 0; }
float get_axis_value(const std::string &line, char axis)
{
char match[3] = " X";
match[1] = axis;
size_t pos = line.find(match) + 2;
// size_t end = std::min(line.find(' ', pos + 1), line.find(';', pos + 1));
// Try to parse the numeric value.
const char *c = line.c_str();
char * pend = nullptr;
errno = 0;
double v = strtod(c + pos, &pend);
if (pend != nullptr && errno == 0 && pend != c) {
// The axis value has been parsed correctly.
return float(v);
}
return NAN;
}
float get_nematx_axis_value(const std::string &line)
{
size_t pos = line.find('=');
if (pos == std::string::npos) {
return -1.f;
}
pos++;
// size_t end = std::min(line.find(' ', pos + 1), line.find(';', pos + 1));
// Try to parse the numeric value.
const char *c = line.c_str();
char * pend = nullptr;
errno = 0;
double v = strtod(c + pos, &pend);
if (pend != nullptr && errno == 0 && pend != c) {
// The axis value has been parsed correctly.
return float(v);
}
return NAN;
}
void change_axis_value(std::string &line, char axis, const float new_value, const int decimal_digits)
{
char match[3] = " X";
match[1] = axis;
size_t pos = line.find(match) + 2;
size_t end = std::min(line.find(' ', pos + 1), line.find(';', pos + 1));
line = line.replace(pos, end - pos, to_string_nozero(new_value, decimal_digits));
}
bool parse_number(const std::string_view sv, int& out)
{
// Legacy conversion, which is costly due to having to make a copy of the string before conversion.
try {
assert(sv.size() < 1024);
assert(sv.data() != nullptr);
std::string str{ sv };
size_t read = 0;
out = std::stoi(str, &read);
return str.size() == read;
}
catch (...) {
return false;
}
}
} // namespace TemperatureMover_func
std::tuple<int16_t, uint16_t> TemperatureMover::_get_temperature_with_extruder_idx(const std::string &line,
GCodeFlavor flavor) {
if (line.compare(0, 4, "M104") == 0 || line.compare(0, 4, "M109") == 0) {
return std::tuple<int16_t, uint16_t>((int16_t) TemperatureMover_func::get_nematx_axis_value(line),
m_current_extruder);
}
return std::tuple<int16_t, uint16_t>(int16_t(-1), uint16_t(0));
}
void TemperatureMover::_put_in_middle_G1(std::list<BufferData>::reverse_iterator item_to_split, float nb_sec_since_itemtosplit_start, BufferData &&line_to_write, float max_time) {
assert(item_to_split != m_buffer.rend());
// if the fan is at the end of the g1 and the diff is less than 10% of the delay, then don't bother
if (nb_sec_since_itemtosplit_start > item_to_split->time * 0.9 && (item_to_split->time - nb_sec_since_itemtosplit_start) < max_time * 0.1) {
// doesn't really need to be split, print it after
m_buffer.insert(next(item_to_split).base(), line_to_write);
} else
// if it's almost at the start of the g1, and the time "lost" is less than 10%
if (nb_sec_since_itemtosplit_start < item_to_split->time * 0.1 && nb_sec_since_itemtosplit_start < max_time * 0.1) {
// doesn't really need to be split, print it before
m_buffer.insert(item_to_split.base(), line_to_write);
} else if (item_to_split->raw.size() > 2
&& item_to_split->raw[0] == 'G' && item_to_split->raw[1] == '1' && item_to_split->raw[2] == ' ') {
assert(nb_sec_since_itemtosplit_start < item_to_split->time);
float after_percent = nb_sec_since_itemtosplit_start / item_to_split->time;
BufferData before = *item_to_split;
before.time *= (1 - after_percent);
item_to_split->time *= after_percent;
if (item_to_split->dx != 0) {
before.dx = item_to_split->dx * (1 - after_percent);
item_to_split->x += before.dx;
item_to_split->dx = item_to_split->dx * after_percent;
TemperatureMover_func::change_axis_value(before.raw, 'X', before.x + before.dx, 3);
}
if (item_to_split->dy != 0) {
before.dy = item_to_split->dy * (1 - after_percent);
item_to_split->y += before.dy;
item_to_split->dy = item_to_split->dy * after_percent;
TemperatureMover_func::change_axis_value(before.raw, 'Y', before.y + before.dy, 3);
}
if (item_to_split->dz != 0) {
before.dz = item_to_split->dz * (1 - after_percent);
item_to_split->z += before.dz;
item_to_split->dz = item_to_split->dz * after_percent;
TemperatureMover_func::change_axis_value(before.raw, 'Z', before.z + before.dz, 3);
}
if (item_to_split->de != 0) {
if (relative_e) {
before.de = item_to_split->de * (1 - after_percent);
TemperatureMover_func::change_axis_value(before.raw, before.e_axis_char, before.de, 5);
item_to_split->de = item_to_split->de * after_percent;
TemperatureMover_func::change_axis_value(item_to_split->raw, item_to_split->e_axis_char, item_to_split->de, 5);
} else {
before.de = item_to_split->de * (1 - after_percent);
item_to_split->e += before.de;
item_to_split->de = item_to_split->de * after_percent;
TemperatureMover_func::change_axis_value(before.raw, before.e_axis_char, before.e + before.de, 5);
}
}
// add before then line_to_write, then there is the modified data.
before.raw += " ; before";
m_buffer.insert(next(item_to_split).base(), line_to_write);
m_buffer.insert(next(item_to_split).base(), before);
item_to_split->raw += " ; after";
} else {
//not a G1, print it before or after
if (nb_sec_since_itemtosplit_start > item_to_split->time * 0.5f) {
m_buffer.insert(next(item_to_split).base(), line_to_write);
} else {
m_buffer.insert(item_to_split.base(), line_to_write);
}
}
}
void TemperatureMover::_remove_low_heat(int16_t min_temp, uint16_t extr_idx, float past_sec) {
// erase in the buffer -> don't cooldown if you are in the process of heating.
// we began at the "recent" side , and remove as long as we don't push past_sec to
auto it = m_buffer.begin();
while (it != m_buffer.end() && past_sec > 0) {
past_sec -= it->time;
if (it->temperature_extruder_idx == extr_idx && it->temperature >= 0 &&
it->temperature < min_temp) {
//found something that is lower than us
it = remove_from_buffer(it);
} else {
++it;
}
}
}
//FIXME: add other firmware
// or just create that damn new gcode writer arch
void TemperatureMover::_process_T(const std::string_view command)
{
if (command.length() > 1 && command[1] >= '0' && command[1] <= '9') {
int eid = 0;
if (!TemperatureMover_func::parse_number(command.substr(1), eid) || eid < 0 || eid > 255) {
GCodeFlavor flavor = m_writer.config.gcode_flavor;
// Specific to the MMU2 V2 (see https://www.help.prusa3d.com/en/article/prusa-specific-g-codes_112173):
if ((flavor == gcfMarlinLegacy || flavor == gcfMarlinFirmware) && (command == "Tx" || command == "Tc" || command == "T?"))
return;
// T-1 is a valid gcode line for RepRap Firmwares (used to deselects all tools) see https://github.com/prusa3d/PrusaSlicer/issues/5677
if ((flavor != gcfRepRap && flavor != gcfSprinter) || eid != -1)
m_current_extruder = static_cast<uint16_t>(0);
} else {
m_current_extruder = static_cast<uint16_t>(eid);
}
}
}
void TemperatureMover::_process_ACTIVATE_EXTRUDER(const std::string_view cmd)
{
if (size_t cmd_end = cmd.find("ACTIVATE_EXTRUDER"); cmd_end != std::string::npos) {
size_t extruder_pos_start = cmd.find("EXTRUDER", cmd_end + std::string_view("ACTIVATE_EXTRUDER").size()) + std::string_view("EXTRUDER").size();
assert(cmd[extruder_pos_start - 1] == 'R');
if (extruder_pos_start != std::string::npos) {
//remove next char until '-' or [0-9]
while (extruder_pos_start < cmd.size() && (cmd[extruder_pos_start] == ' ' || cmd[extruder_pos_start] == '=' || cmd[extruder_pos_start] == '\t'))
++extruder_pos_start;
size_t extruder_pos_end = extruder_pos_start + 1;
while (extruder_pos_end < cmd.size() && cmd[extruder_pos_end] != ' ' && cmd[extruder_pos_end] != '\t' && cmd[extruder_pos_end] != '\r' && cmd[extruder_pos_end] != '\n')
++extruder_pos_end;
std::string_view extruder_name = cmd.substr(extruder_pos_start, extruder_pos_end-extruder_pos_start);
// we have a "name". It may be whatever or "extruder" + X
for (const Extruder &extruder : m_writer.extruders()) {
if (m_writer.config.tool_name.get_at(extruder.id()) == extruder_name) {
m_current_extruder = static_cast<uint16_t>(extruder.id());
return;
}
}
std::string extruder_str("extruder");
if (extruder_str == extruder_name) {
m_current_extruder = static_cast<uint16_t>(0);
return;
}
for (const Extruder &extruder : m_writer.extruders()) {
if (extruder_str + std::to_string(extruder.id()) == extruder_name) {
m_current_extruder = static_cast<uint16_t>(extruder.id());
return;
}
}
}
BOOST_LOG_TRIVIAL(error) << "invalid ACTIVATE_EXTRUDER gcode command: '" << cmd << "', ignored by the fam mover post-process.";
}
}
void TemperatureMover::_process_gcode_line(GCodeReader& reader, const GCodeReader::GCodeLine& line)
{
// processes 'normal' gcode lines
bool need_flush = false;
std::string cmd(line.cmd());
double time = 0;
int16_t new_temperature = -1;
uint16_t temperature_extruder_idx = 0;
if (cmd.length() > 1) {
if (::toupper(cmd[0]) == 'G') {
assert(!line.has_f() || line.f() > 0);
if (line.has_f() && line.f() > 0) {
m_current_speed = line.f() / 60.0f;
}
}
switch (::toupper(cmd[0])) {
case 'A':
_process_ACTIVATE_EXTRUDER(line.raw());
break;
case 'T':
case 't':
_process_T(cmd);
break;
case 'G':
{
if (::atoi(&cmd[1]) == 1 || ::atoi(&cmd[1]) == 0) {
double distx = line.dist_X(reader);
double disty = line.dist_Y(reader);
double distz = line.dist_Z(reader);
double dist = distx * distx + disty * disty + distz * distz;
if (dist > 0) {
dist = std::sqrt(dist);
assert(m_current_speed > 0 && m_current_speed < 1000000 && !std::isnan(m_current_speed));
time = dist / m_current_speed;
assert(time >= 0 && time < 1000000 && !std::isnan(time));
}
} else if (::atoi(&cmd[1]) == 2 || ::atoi(&cmd[1]) == 3) {
// TODO: compute real dist
double distx = line.dist_X(reader);
double disty = line.dist_Y(reader);
double dist = distx * distx + disty * disty;
if (dist > 0) {
dist = std::sqrt(dist);
assert(m_current_speed > 0 && m_current_speed < 1000000 && !std::isnan(m_current_speed));
time = dist / m_current_speed;
assert(time >= 0 && time < 1000000 && !std::isnan(time));
}
}
break;
}
case 'M':
{
std::tie(new_temperature, temperature_extruder_idx) =
this->_get_temperature_with_extruder_idx(line.raw(), m_writer.config.gcode_flavor);
if (new_temperature >= 0) {
if (!m_is_custom_gcode) {
// if slow down => put in the queue. if not =>
if (m_back_buffer_temperatures[temperature_extruder_idx] >= 0 &&
m_back_buffer_temperatures[temperature_extruder_idx] < new_temperature) {
if (temperature_extruder_idx < heating_speed.size() && heating_speed[temperature_extruder_idx] > 0) {
//compute delay
double nb_seconds_delay = (new_temperature - m_back_buffer_temperatures[temperature_extruder_idx]) / heating_speed[temperature_extruder_idx];
//don't put this command in the queue
time = -1;
// this M104 need to go in the past
// first erase everything lower than that value
//_remove_low_heat(new_temperature, temperature_extruder_idx, nb_seconds_delay);
// then write the heat command
if (!m_buffer.empty() && (m_buffer_time_size - m_buffer.front().time * 0.1) > nb_seconds_delay) {
//_print_in_middle_G1(m_buffer.front(), float(m_buffer_time_size - nb_seconds_delay), line.raw());
//remove_from_buffer(m_buffer.begin());
float time_count = nb_seconds_delay;
auto rit = m_buffer.rbegin();
while (rit != m_buffer.rend() && time_count > 0) {
time_count -= rit->time;
if (time_count< 0) {
//found something that is lower than us
_put_in_middle_G1(rit, rit->time + time_count, BufferData(std::string(line.raw()), line.e_char() ,0, new_temperature, temperature_extruder_idx), nb_seconds_delay);
//found, stop
break;
} else if (rit->temperature >= 0 && rit->temperature_extruder_idx == temperature_extruder_idx &&
rit->temperature <= new_temperature) {
//found something that is lower than us
auto it = rit.base();
++rit;
remove_from_buffer(it);
} else {
++rit;
}
}
} else {
// buffer not enough, write it before the buffer.
m_process_output += line.raw() + "\n";
}
}
}
m_back_buffer_temperatures[temperature_extruder_idx] = new_temperature;
} else {
put_in_buffer(BufferData(std::string("; m_is_custom_gcode, so not touched: ") + line.raw(), line.e_char(), 0, -1, 0));
// have to flush the buffer to avoid erasing a temperature command.
need_flush = true;
}
}
break;
}
}
} else {
if(!line.raw().empty() && line.raw().front() == ';')
{
if (line.raw().size() > 10 && line.raw().rfind(";TYPE:", 0) == 0) {
// get the type of the next extrusions
std::string extrusion_string = line.raw().substr(6, line.raw().size() - 6);
current_role = string_to_gcode_extrusion_role(extrusion_string);
assert(current_role != GCodeExtrusionRole::None);
}
if (line.raw().size() > 16) {
if (line.raw().rfind("; custom gcode", 0) != std::string::npos) {
if (line.raw().rfind("; custom gcode end", 0) != std::string::npos) {
m_is_custom_gcode = false;
} else {
m_is_custom_gcode = true;
}
}
}
}
}
if (time >= 0) {
BufferData& new_data = put_in_buffer(BufferData(line.raw(), line.e_char(), time, new_temperature, temperature_extruder_idx));
if (line.has(Axis::X)) {
new_data.x = reader.x();
new_data.dx = line.dist_X(reader);
}
if (line.has(Axis::Y)) {
new_data.y = reader.y();
new_data.dy = line.dist_Y(reader);
}
if (line.has(Axis::Z)) {
new_data.z = reader.z();
new_data.dz = line.dist_Z(reader);
}
if (line.has(Axis::E)) {
new_data.e = reader.e();
if (relative_e) {
new_data.de = line.e();
// GCode reader doesn't know it's relative extrusion, we have to do it ourself.
//assert(new_data.e == 0);
new_data.e = 0;
} else
new_data.de = line.dist_E(reader);
}
assert(new_data.dx == 0 || reader.x() == new_data.x);
assert(new_data.dx == 0 || std::abs(reader.x() + new_data.dx - line.x()) < 0.00002f);
assert(new_data.dy == 0 || reader.y() == new_data.y);
assert(new_data.dy == 0 || std::abs(reader.y() + new_data.dy - line.y()) < 0.00002f);
assert(new_data.de == 0 || (relative_e?0:reader.e()) == new_data.e);
assert(new_data.de == 0 || std::abs((relative_e?0.f:reader.e()) + new_data.de - line.e()) < 0.00001f);
//assert(new_data.de == 0 ||(relative_e?0.f:reader.e()) + new_data.de == line.e());
}
// puts the line back into the gcode
//if buffer too big, flush it.
if (time >= 0) {
// Add EPSILON to allow to have a buffer even with 0 m_buffer_time_size, so multiple consecutive M106 can be culled.
while (!m_buffer.empty() && (need_flush || m_buffer_time_size - m_buffer.front().time > m_max_seconds_delay + EPSILON) ){
write_buffer_data();
}
}
#if _DEBUG
double sum = 0;
for (auto& data : m_buffer) sum += data.time;
assert( std::abs(m_buffer_time_size - sum) < 0.01);
#endif
}
void TemperatureMover::write_buffer_data()
{
BufferData &frontdata = m_buffer.front();
if (frontdata.temperature < 0 || frontdata.temperature != m_front_buffer_temperatures[frontdata.temperature_extruder_idx] ) {
m_process_output += frontdata.raw + "\n";
if (frontdata.temperature >= 0) {
m_front_buffer_temperatures[frontdata.temperature_extruder_idx] = frontdata.temperature;
}
} else {
assert(frontdata.temperature == m_front_buffer_temperatures[frontdata.temperature_extruder_idx]);
m_process_output += "; skip temp, as it's already set: " + frontdata.raw + "\n";
}
remove_from_buffer(m_buffer.begin());
}
} // namespace Slic3r

View file

@ -0,0 +1,126 @@
#ifndef slic3r_GCode_TemperatureMover_hpp_
#define slic3r_GCode_TemperatureMover_hpp_
#include "libslic3r/ExtrusionEntity.hpp"
#include "libslic3r/GCodeReader.hpp"
#include "libslic3r/GCode/GCodeWriter.hpp"
#include "libslic3r/Point.hpp"
#include "libslic3r/PrintConfig.hpp"
#include "libslic3r/libslic3r.h"
#include <regex>
namespace Slic3r {
class TemperatureMover
{
class BufferData
{
public:
// raw string, contains end position
std::string raw;
// time to go from start to end
float time;
int16_t temperature = -1;
uint16_t temperature_extruder_idx = uint16_t(0);
// start position
float x = 0, y = 0, z = 0, e = 0;
// delta to go to end position
float dx = 0, dy = 0, dz = 0, de = 0;
char e_axis_char = 'E';
BufferData(std::string line, char e_axis, float time, int16_t temperature, uint16_t extruder_idx)
: raw(line), time(time), temperature(temperature), temperature_extruder_idx(extruder_idx), e_axis_char(e_axis)
{
// avoid double \n
if (!line.empty() && line.back() == '\n')
line.pop_back();
}
};
private:
const std::regex regex_temperature_set;
const std::vector<double> heating_speed; // in °C/s
float m_max_seconds_delay;
const bool relative_e;
GCodeReader m_parser{};
const GCodeWriter& m_writer;
//current value (at the back of the buffer), when parsing a new line
GCodeExtrusionRole current_role = GCodeExtrusionRole::Custom;
// in unit/second
double m_current_speed = 1000 / 60.0;
bool m_is_custom_gcode = false;
uint16_t m_current_extruder = 0;
// variable for when you add a line (front of the buffer)
int m_front_buffer_temperatures[256];
int m_back_buffer_temperatures[256];
//buffer
std::list<BufferData> m_buffer;
double m_buffer_time_size = 0;
// The output of process_layer()
std::string m_process_output;
public:
TemperatureMover(const GCodeWriter &writer,
const FullPrintConfig &config,
const std::vector<double> heating_speed,
const bool relative_e)
: regex_temperature_set("S[0-9]+")
, heating_speed(heating_speed)
, relative_e(relative_e)
, m_writer(writer)
{
m_parser.apply_config(config);
m_max_seconds_delay = 0;
for (double speed : heating_speed) {
float delay = 300.f / float(speed);
if (delay > m_max_seconds_delay) {
m_max_seconds_delay = delay;
}
}
std::fill(std::begin(m_front_buffer_temperatures),std::end(m_front_buffer_temperatures),int16_t(-1));
std::fill(std::begin(m_back_buffer_temperatures),std::end(m_back_buffer_temperatures),int16_t(-1));
}
// Adds the gcode contained in the given string to the analysis and returns it after removing the workcodes
const std::string& process_gcode(const std::string& gcode, bool flush);
private:
BufferData& put_in_buffer(BufferData&& data) {
assert(data.time >= 0 && data.time < 1000000 && !std::isnan(data.time));
m_buffer_time_size += data.time;
if (!m_buffer.empty() && data.temperature_extruder_idx == m_buffer.back().temperature_extruder_idx &&
data.temperature >= 0 && m_buffer.back().temperature >= 0) {
// erase last item
m_buffer.back() = data;
} else {
m_buffer.emplace_back(data);
}
return m_buffer.back();
}
std::list<BufferData>::iterator remove_from_buffer(std::list<BufferData>::iterator data) {
assert(data->time >= 0 && data->time < 1000000 && !std::isnan(data->time));
m_buffer_time_size -= data->time;
return m_buffer.erase(data);
}
// Processes the given gcode line
void _process_gcode_line(GCodeReader& reader, const GCodeReader::GCodeLine& line);
void _process_ACTIVATE_EXTRUDER(const std::string_view command);
void _process_T(const std::string_view command);
//void _print_in_middle_G1(BufferData& line_to_split, float nb_sec, const std::string& line_to_write);
void _put_in_middle_G1(std::list<BufferData>::reverse_iterator item_to_split, float nb_sec_since_itemtosplit_start, BufferData &&line_to_write, float max_time);
void _remove_low_heat(int16_t min_temp, uint16_t extr_idx, float past_sec);
std::tuple<int16_t, uint16_t> _get_temperature_with_extruder_idx(const std::string &line, GCodeFlavor flavor);
void write_buffer_data();
};
} // namespace Slic3r
#endif /* slic3r_GCode_TemperatureMover_hpp_ */

View file

@ -81,14 +81,14 @@ uint16_t LayerTools::extruder(const ExtrusionEntityCollection &extrusions, const
return (extruder == 0) ? 0 : extruder - 1;
}
static double calc_max_layer_height(const PrintConfig &config, double max_object_layer_height)
static coord_t calc_max_layer_height(const PrintConfig &config, coord_t max_object_layer_height)
{
double max_layer_height = std::numeric_limits<double>::max();
coord_t max_layer_height = std::numeric_limits<coord_t>::max();
for (size_t i = 0; i < config.nozzle_diameter.size(); ++ i) {
double mlh = config.max_layer_height.get_abs_value(i, config.nozzle_diameter.get_at(i));
if (mlh == 0. || !config.max_layer_height.is_enabled())
mlh = 0.75 * config.nozzle_diameter.get_at(i);
max_layer_height = std::min(max_layer_height, mlh);
max_layer_height = std::min(max_layer_height, Layer::scale_to_layer_coord(mlh));
}
// The Prusa3D Fast (0.35mm layer height) print profile sets a higher layer height than what is normally allowed
// by the nozzle. This is a hack and it works by increasing extrusion width. See GH #3919.
@ -104,31 +104,32 @@ ToolOrdering::ToolOrdering(const PrintObject &object, uint16_t first_extruder, b
if (object.layers().empty())
return;
m_objects = {&object};
// Initialize the print layers for just a single object.
{
std::vector<double> zs;
std::vector<coord_t> zs;
zs.reserve(zs.size() + object.layers().size() + object.support_layers().size());
for (auto layer : object.layers()) {
zs.emplace_back(layer->print_z);
zs.emplace_back(layer->scaled_print_z());
}
for (auto layer : object.support_layers()) {
if (layer->has_extrusions()) {
zs.emplace_back(layer->print_z);
zs.emplace_back(layer->scaled_print_z());
}
}
this->initialize_layers(zs);
}
double max_layer_height = calc_max_layer_height(object.print()->config(), object.config().layer_height);
coord_t max_layer_height = calc_max_layer_height(object.print()->config(), Layer::scale_to_layer_coord(object.config().layer_height));
// Collect extruders required to print the layers.
this->collect_extruders(object, {}, std::vector<std::pair<double, uint16_t>>(), std::vector<std::pair<double, uint16_t>>());
this->collect_extruders(object, {}, std::vector<std::pair<coord_t, uint16_t>>(), std::vector<std::pair<coord_t, uint16_t>>());
// Reorder the extruders to minimize tool switches.
this->reorder_extruders(first_extruder);
// note: wipetower isn't compatible with print_objects_step anyway
this->fill_wipe_tower_partitions(object.print()->config(), object.layers().front()->print_z - object.layers().front()->height, max_layer_height);
this->fill_wipe_tower_partitions(object.print()->config(), object.layers().front()->scaled_bottom_z(), max_layer_height);
this->collect_extruder_statistics(prime_multi_material);
@ -144,32 +145,33 @@ ToolOrdering::ToolOrdering(const PrintObject &object, const GCode::ObjectsLayerT
if (object.layers().empty() || layers.empty())
return;
m_objects = {&object};
// Initialize the print layers for just a single object.
double bottom_z = -1;
coord_t bottom_z = -1;
{
std::vector<double> zs;
std::vector<coord_t> zs;
zs.reserve(layers.size() * 2);
for (auto o_s_layer : layers) {
if (o_s_layer.object_layer) {
zs.emplace_back(o_s_layer.object_layer->print_z);
if (bottom_z < 0 || bottom_z > o_s_layer.object_layer->print_z - o_s_layer.object_layer->height) {
bottom_z = o_s_layer.object_layer->print_z - o_s_layer.object_layer->height;
zs.emplace_back(o_s_layer.object_layer->scaled_print_z());
if (bottom_z < 0 || bottom_z > o_s_layer.object_layer->scaled_bottom_z()) {
bottom_z = o_s_layer.object_layer->scaled_bottom_z();
}
}
if (o_s_layer.support_layer) {
zs.emplace_back(o_s_layer.support_layer->print_z);
if (bottom_z < 0 || bottom_z > o_s_layer.support_layer->print_z - o_s_layer.support_layer->height) {
bottom_z = o_s_layer.support_layer->print_z - o_s_layer.support_layer->height;
zs.emplace_back(o_s_layer.support_layer->scaled_print_z());
if (bottom_z < 0 || bottom_z > o_s_layer.support_layer->scaled_bottom_z()) {
bottom_z = o_s_layer.support_layer->scaled_bottom_z();
}
}
}
this->initialize_layers(zs);
}
double max_layer_height = calc_max_layer_height(object.print()->config(), object.config().layer_height);
coord_t max_layer_height = calc_max_layer_height(object.print()->config(), Layer::scale_to_layer_coord(object.config().layer_height));
// Collect extruders required to print the layers.
this->collect_extruders(object, layers, std::vector<std::pair<double, uint16_t>>(), std::vector<std::pair<double, uint16_t>>());
this->collect_extruders(object, layers, std::vector<std::pair<coord_t, uint16_t>>(), std::vector<std::pair<coord_t, uint16_t>>());
// Reorder the extruders to minimize tool switches.
this->reorder_extruders(first_extruder);
@ -188,43 +190,44 @@ ToolOrdering::ToolOrdering(const Print &print, uint16_t first_extruder, bool pri
{
m_objects.clear();
m_print_config_ptr = &print.config();
m_print_object_config_ptr = &print.default_object_config();
// Initialize the print layers for all objects and all layers.
coord_t object_bottom_z = 0;
coord_t max_layer_height = 0;
{
std::vector<double> zs;
std::vector<coord_t> zs;
for (const PrintObject *object : print.objects()) {
m_objects.push_back(object);
zs.reserve(zs.size() + object->layers().size() + object->support_layers().size());
for (auto layer : object->layers()) {
if (layer->has_extrusions()) {
zs.emplace_back(unscaled(scale_t(layer->print_z + SCALING_FACTOR * 0.5)));
zs.emplace_back(layer->scaled_print_z());
}
}
for (auto layer : object->support_layers()) {
if (layer->has_extrusions()) {
zs.emplace_back(unscaled(scale_t(layer->print_z + SCALING_FACTOR * 0.5)));
zs.emplace_back(layer->scaled_print_z());
}
}
// Find first object layer that is not empty and save its print_z
for (const Layer *layer : object->layers()) {
if (layer->has_extrusions()) {
object_bottom_z = scale_t(layer->print_z - layer->height + SCALING_FACTOR * 0.5);
object_bottom_z = layer->scaled_bottom_z();
break;
}
}
max_layer_height = std::max(max_layer_height, scale_t(object->config().layer_height.value + SCALING_FACTOR * 0.5));
max_layer_height = std::max(max_layer_height, Layer::scale_to_layer_coord(object->config().layer_height.value));
}
this->initialize_layers(zs);
}
max_layer_height = scale_t(calc_max_layer_height(print.config(), unscaled(max_layer_height)) + SCALING_FACTOR * 0.5);
max_layer_height = calc_max_layer_height(print.config(), max_layer_height);
// Use the extruder switches from Model::custom_gcode_per_print_z to override the extruder to print the object.
// Do it only if all the objects were configured to be printed with a single extruder.
std::vector<std::pair<double, uint16_t>> per_layer_extruder_switches;
std::vector<std::pair<coord_t, uint16_t>> per_layer_extruder_switches;
uint16_t num_extruders = uint16_t(print.config().nozzle_diameter.size());
if (num_extruders > 1 && print.object_extruders().size() == 1 && // the current Print's configuration is CustomGCode::MultiAsSingle
print.model().custom_gcode_per_print_z.mode == CustomGCode::MultiAsSingle) {
@ -235,19 +238,22 @@ ToolOrdering::ToolOrdering(const Print &print, uint16_t first_extruder, bool pri
// Color changes for each layer to determine which extruder needs to be picked before color change.
// This is done just for multi-extruder printers without enabled Single Extruder Multi Material (tool changer printers).
std::vector<std::pair<double, uint16_t>> per_layer_color_changes;
std::vector<std::pair<coord_t, uint16_t>> per_layer_color_changes;
if (num_extruders > 1 && print.model().custom_gcode_per_print_z.mode == CustomGCode::MultiExtruder && !print.config().single_extruder_multi_material) {
per_layer_color_changes = custom_color_changes(print.model().custom_gcode_per_print_z, num_extruders);
}
// Collect extruders required to print the layers.
for (auto object : print.objects())
m_objects.clear();
for (const PrintObject *object : print.objects()) {
m_objects.push_back(object);
this->collect_extruders(*object, {}, per_layer_extruder_switches, per_layer_color_changes);
}
// Reorder the extruders to minimize tool switches.
this->reorder_extruders(first_extruder);
this->fill_wipe_tower_partitions(print.config(), unscaled(object_bottom_z), unscaled(max_layer_height));
this->fill_wipe_tower_partitions(print.config(), object_bottom_z, max_layer_height);
if (this->insert_wipe_tower_extruder()) {
// Now convert the 0-based list to 1-based again, because that is what reorder_extruder expects.
@ -256,25 +262,30 @@ ToolOrdering::ToolOrdering(const Print &print, uint16_t first_extruder, bool pri
++extruder;
}
this->reorder_extruders(first_extruder);
this->fill_wipe_tower_partitions(print.config(), unscaled(object_bottom_z), unscaled(max_layer_height));
this->fill_wipe_tower_partitions(print.config(), object_bottom_z, max_layer_height);
}
this->collect_extruder_statistics(prime_multi_material);
this->mark_skirt_layers(print.config(), unscaled(max_layer_height));
this->mark_skirt_layers(print.config(), max_layer_height);
}
void ToolOrdering::initialize_layers(std::vector<double> &zs)
void ToolOrdering::initialize_layers(std::vector<coord_t> &zs)
{
sort_remove_duplicates(zs);
// Merge numerically very close Z values.
for (size_t i = 0; i < zs.size();) {
// Find the last layer with roughly the same print_z.
size_t j = i + 1;
coordf_t zmax = zs[i] + EPSILON;
for (; j < zs.size() && zs[j] <= zmax; ++ j) ;
// Assign an average print_z to the set of layers with nearly equal print_z.
m_layer_tools.emplace_back(LayerTools(0.5 * (zs[i] + zs[j-1])));
coord_t zmax = zs[i] + SCALED_EPSILON * 4;
for (; j < zs.size() && zs[j] <= zmax; ++j) {
assert(zs[j] == zs[i]);
assert(false); // duplicates are already removed
}
assert(j == i + 1);
//// Assign an average print_z to the set of layers with nearly equal print_z.
//m_layer_tools.emplace_back(LayerTools(0.5 * (zs[i] + zs[j-1])));
m_layer_tools.push_back(LayerTools(zs[i], true));
i = j;
}
}
@ -298,15 +309,15 @@ void ToolOrdering::initialize_layers(std::vector<double> &zs)
void ToolOrdering::collect_extruders(
const PrintObject &object,
const GCode::ObjectsLayerToPrint &layers,
const std::vector<std::pair<double, uint16_t>> &per_layer_extruder_switches,
const std::vector<std::pair<double, uint16_t>> &per_layer_color_changes
const std::vector<std::pair<coord_t, uint16_t>> &per_layer_extruder_switches,
const std::vector<std::pair<coord_t, uint16_t>> &per_layer_color_changes
) {
// Collect the support extruders.
auto collect_support_layer = [&](const SupportLayer* support_layer) {
if(!support_layer->has_extrusions())
return;
LayerTools *layer_tools = this->tools_for_layer(support_layer->print_z);
ExtrusionRole role = support_layer->support_fills.role();
LayerTools *layer_tools = this->tools_for_layer(support_layer->scaled_print_z());
ExtrusionRole role = support_layer->role();
bool has_support = role == ExtrusionRole::Mixed || role == ExtrusionRole::SupportMaterial;
bool has_interface = role == ExtrusionRole::Mixed || role == ExtrusionRole::SupportMaterialInterface;
uint16_t extruder_support = object.config().support_material_extruder.value;
@ -331,28 +342,32 @@ void ToolOrdering::collect_extruders(
}
// Extruder overrides are ordered by print_z.
std::vector<std::pair<double, uint16_t>>::const_iterator it_per_layer_extruder_override = per_layer_extruder_switches.begin();
std::vector<std::pair<coord_t, uint16_t>>::const_iterator it_per_layer_extruder_override = per_layer_extruder_switches.begin();
uint16_t extruder_override = 0;
std::vector<std::pair<double, uint16_t>>::const_iterator it_per_layer_color_changes = per_layer_color_changes.begin();
std::vector<std::pair<coord_t, uint16_t>>::const_iterator it_per_layer_color_changes = per_layer_color_changes.begin();
// Collect the object extruders.
auto collect_object_layer = [&](const Layer* layer) {
LayerTools *layer_tools_ptr = this->tools_for_layer(layer->print_z);
LayerTools *layer_tools_ptr = this->tools_for_layer(layer->scaled_print_z());
if (!layer_tools_ptr)
return;
LayerTools &layer_tools = *layer_tools_ptr;
// Override extruder with the next
for (; it_per_layer_extruder_override != per_layer_extruder_switches.end() && it_per_layer_extruder_override->first < layer->print_z + EPSILON; ++ it_per_layer_extruder_override)
extruder_override = (int)it_per_layer_extruder_override->second;
for (; it_per_layer_extruder_override != per_layer_extruder_switches.end() &&
it_per_layer_extruder_override->first <= layer->scaled_print_z();
++it_per_layer_extruder_override)
extruder_override = (int) it_per_layer_extruder_override->second;
// Store the current extruder override (set to zero if no overriden), so that layer_tools.wiping_extrusions().is_overridable_and_mark() will use it.
layer_tools.extruder_override = extruder_override;
// Append the extruder needed to be picked before performing the color change.
for (; it_per_layer_color_changes != per_layer_color_changes.end() && it_per_layer_color_changes->first < layer->print_z + EPSILON; ++it_per_layer_color_changes) {
if (std::abs(it_per_layer_color_changes->first - layer->print_z) < EPSILON) {
for (; it_per_layer_color_changes != per_layer_color_changes.end() &&
it_per_layer_color_changes->first <= layer->scaled_print_z();
++it_per_layer_color_changes) {
if (it_per_layer_color_changes->first == layer->scaled_print_z()) {
assert(layer_tools.extruder_needed_for_color_changer == 0); // Just on color change per layer is allowed.
layer_tools.extruder_needed_for_color_changer = it_per_layer_color_changes->second;
layer_tools.extruders.emplace_back(it_per_layer_color_changes->second);
@ -360,58 +375,63 @@ void ToolOrdering::collect_extruders(
}
// What extruders are required to print this object layer?
for (const LayerRegion *layerm : layer->regions()) {
const PrintRegion &region = layerm->region();
for (const LayerSliceIslandPtr &layer_island_ptr : layer->islands()) {
for (const LayerRegionIslandPtr &region_island_ptr : layer_island_ptr->regions_islands()) {
const PrintRegion &one_region = (*region_island_ptr->regions().begin())->region();
if (region_island_ptr->has_extrusion(LayerRegionIsland::PERIMETERS)) {
bool something_nonoverriddable = true;
// TODO: is it okay?
// TODO: ensure that the split by extruder was already done at slicing.
if (! layerm->perimeters().empty()) {
bool something_nonoverriddable = true;
if (m_print_config_ptr) { // in this case complete_objects is false (see ToolOrdering constructors)
something_nonoverriddable = false;
for (const ExtrusionEntity* eec : layerm->perimeters().entities()) // let's check if there are nonoverriddable entities()
if (is_overriddable(dynamic_cast<const ExtrusionEntityCollection&>(*eec), layer_tools, *m_print_config_ptr, object, region))
if (m_print_config_ptr) { // in this case complete_objects is false (see ToolOrdering constructors)
something_nonoverriddable = false;
// let's check if there are nonoverriddable entities()
if (is_overriddable(region_island_ptr->extrusion(LayerRegionIsland::PERIMETERS), layer_tools,
*m_print_config_ptr, object, one_region))
layer_tools.wiping_extrusions_nonconst().set_something_overridable();
else
something_nonoverriddable = true;
}
if (something_nonoverriddable)
layer_tools.extruders.emplace_back(
extruder_override == 0 ? one_region.config().perimeter_extruder.value : extruder_override);
layer_tools.has_object = true;
}
if (something_nonoverriddable)
layer_tools.extruders.emplace_back(extruder_override == 0 ? region.config().perimeter_extruder.value : extruder_override);
bool has_infill = false;
bool has_solid_infill = false;
bool something_nonoverriddable = false;
if (region_island_ptr->has_extrusion(LayerRegionIsland::INFILLS)) {
// fill represents infill extrusions of a single island.
const auto &fill = region_island_ptr->extrusion(LayerRegionIsland::INFILLS);
// we search as deep as available, in case there is some gapfill role
if (HasRoleVisitor::search(fill.entities(), HasSolidInfillVisitor{}))
has_solid_infill = true;
else if (HasRoleVisitor::search(fill.entities(), HasInfillVisitor{}))
has_infill = true;
layer_tools.has_object = true;
}
bool has_infill = false;
bool has_solid_infill = false;
bool something_nonoverriddable = false;
for (const ExtrusionEntity *ee : layerm->fills()) {
// fill represents infill extrusions of a single island.
const auto *fill = dynamic_cast<const ExtrusionEntityCollection*>(ee);
// we search as deep as available, in case there is some gapfill role
if (HasRoleVisitor::search(fill->entities(), HasSolidInfillVisitor{}))
has_solid_infill = true;
else if (HasRoleVisitor::search(fill->entities(), HasInfillVisitor{}))
has_infill = true;
if (m_print_config_ptr) {
if (is_overriddable(*fill, layer_tools, *m_print_config_ptr, object, region))
layer_tools.wiping_extrusions_nonconst().set_something_overridable();
else
something_nonoverriddable = true;
if (m_print_config_ptr) {
if (is_overriddable(fill, layer_tools, *m_print_config_ptr, object, one_region))
layer_tools.wiping_extrusions_nonconst().set_something_overridable();
else
something_nonoverriddable = true;
}
}
}
if (something_nonoverriddable || !m_print_config_ptr) {
if (extruder_override == 0) {
if (has_solid_infill)
layer_tools.extruders.emplace_back(region.config().solid_infill_extruder);
if (has_infill)
layer_tools.extruders.emplace_back(region.config().infill_extruder);
} else if (has_solid_infill || has_infill)
layer_tools.extruders.emplace_back(extruder_override);
if (something_nonoverriddable || !m_print_config_ptr) {
if (extruder_override == 0) {
if (has_solid_infill)
layer_tools.extruders.emplace_back(one_region.config().solid_infill_extruder);
if (has_infill)
layer_tools.extruders.emplace_back(one_region.config().infill_extruder);
} else if (has_solid_infill || has_infill)
layer_tools.extruders.emplace_back(extruder_override);
}
if (has_solid_infill || has_infill)
layer_tools.has_object = true;
}
if (has_solid_infill || has_infill)
layer_tools.has_object = true;
}
};
if (layers.empty()) {
@ -481,7 +501,7 @@ void ToolOrdering::reorder_extruders(uint16_t last_extruder_id)
// On first layer with wipe tower, prefer a soluble extruder
// at the beginning, so it is not wiped on the first layer.
if (lt == m_layer_tools[0] && m_print_config_ptr && m_print_config_ptr->wipe_tower) {
if (lt == m_layer_tools[0] && m_print_config_ptr && m_print_object_config_ptr && m_print_object_config_ptr->wipe_tower) {
for (size_t i = 0; i<lt.extruders.size(); ++i)
if (m_print_config_ptr->filament_soluble.get_at(lt.extruders[i]-1)) { // 1-based...
std::swap(lt.extruders[i], lt.extruders.front());
@ -505,7 +525,7 @@ void ToolOrdering::reorder_extruders(uint16_t last_extruder_id)
}
}
void ToolOrdering::fill_wipe_tower_partitions(const PrintConfig &config, coordf_t object_bottom_z, coordf_t max_layer_height)
void ToolOrdering::fill_wipe_tower_partitions(const PrintConfig &config, coord_t object_bottom_z, coord_t max_layer_height)
{
if (m_layer_tools.empty())
return;
@ -528,29 +548,30 @@ void ToolOrdering::fill_wipe_tower_partitions(const PrintConfig &config, coordf_
//FIXME this is a hack to get the ball rolling.
for (LayerTools &lt : m_layer_tools)
lt.has_wipe_tower = (lt.has_object && lt.wipe_tower_partitions > 0) || lt.print_z < object_bottom_z + EPSILON;
lt.has_wipe_tower = (lt.has_object && lt.wipe_tower_partitions > 0) || lt._print_z <= object_bottom_z;
// Test for a raft, insert additional wipe tower layer to fill in the raft separation gap.
for (size_t i = 0; i + 1 < m_layer_tools.size(); ++ i) {
const LayerTools &lt = m_layer_tools[i];
const LayerTools &lt_next = m_layer_tools[i + 1];
if (lt.print_z < object_bottom_z + EPSILON && lt_next.print_z >= object_bottom_z + EPSILON) {
if (lt._print_z <= object_bottom_z && lt_next._print_z > object_bottom_z) {
// lt is the last raft layer. Find the 1st object layer.
size_t j = i + 1;
for (; j < m_layer_tools.size() && ! m_layer_tools[j].has_wipe_tower; ++ j);
if (j < m_layer_tools.size()) {
const LayerTools &lt_object = m_layer_tools[j];
coordf_t gap = lt_object.print_z - lt.print_z;
coordf_t gap = lt_object._print_z - lt._print_z;
assert(gap > 0.f);
if (gap > max_layer_height + EPSILON) {
if (gap > max_layer_height) {
// Insert one additional wipe tower layer between lh.print_z and lt_object.print_z.
LayerTools lt_new(0.5f * (lt.print_z + lt_object.print_z));
assert(lt._print_z == lt_object._print_z);
LayerTools lt_new(std::max(lt._print_z, lt_object._print_z), true);
// Find the 1st layer above lt_new.
for (j = i + 1; j < m_layer_tools.size() && m_layer_tools[j].print_z < lt_new.print_z - EPSILON; ++ j);
if (std::abs(m_layer_tools[j].print_z - lt_new.print_z) < EPSILON) {
m_layer_tools[j].has_wipe_tower = true;
} else {
LayerTools &lt_extra = *m_layer_tools.insert(m_layer_tools.begin() + j, lt_new);
for (j = i + 1; j < m_layer_tools.size() && m_layer_tools[j]._print_z < lt_new._print_z - EPSILON; ++ j);
if (std::abs(m_layer_tools[j]._print_z - lt_new._print_z) < EPSILON) {
m_layer_tools[j].has_wipe_tower = true;
} else {
LayerTools &lt_extra = *m_layer_tools.insert(m_layer_tools.begin() + j, lt_new);
//LayerTools &lt_prev = m_layer_tools[j];
LayerTools &lt_next = m_layer_tools[j + 1];
assert(! m_layer_tools[j - 1].extruders.empty() && ! lt_next.extruders.empty());
@ -582,34 +603,34 @@ void ToolOrdering::fill_wipe_tower_partitions(const PrintConfig &config, coordf_
lt_next.has_wipe_tower = true;
// We should also check that the next wipe tower layer is no further than max_layer_height:
uint16_t j = i+1;
double last_wipe_tower_print_z = lt_next.print_z;
coord_t last_wipe_tower_print_z = lt_next._print_z;
while (++j < m_layer_tools.size()-1 && !m_layer_tools[j].has_wipe_tower)
if (m_layer_tools[j+1].print_z - last_wipe_tower_print_z > max_layer_height + EPSILON) {
if ((m_layer_tools[j+1]._print_z - last_wipe_tower_print_z) > max_layer_height) {
m_layer_tools[j].has_wipe_tower = true;
last_wipe_tower_print_z = m_layer_tools[j].print_z;
last_wipe_tower_print_z = m_layer_tools[j]._print_z;
}
}
// Calculate the wipe_tower_layer_height values.
coordf_t wipe_tower_print_z_last = 0.;
coord_t wipe_tower_print_z_last = 0.;
for (LayerTools &lt : m_layer_tools)
if (lt.has_wipe_tower) {
lt.wipe_tower_layer_height = lt.print_z - wipe_tower_print_z_last;
wipe_tower_print_z_last = lt.print_z;
lt.wipe_tower_layer_height = lt._print_z - wipe_tower_print_z_last;
wipe_tower_print_z_last = lt._print_z;
}
}
bool ToolOrdering::insert_wipe_tower_extruder()
{
if (!m_print_config_ptr->wipe_tower)
if (!m_print_object_config_ptr->wipe_tower)
return false;
// In case that wipe_tower_extruder is set to non-zero, we must make sure that the extruder will be in the list.
bool changed = false;
if (m_print_config_ptr->wipe_tower_extruder != 0) {
if (m_print_object_config_ptr->wipe_tower_extruder != 0) {
for (LayerTools& lt : m_layer_tools) {
if (lt.wipe_tower_partitions > 0) {
lt.extruders.emplace_back(m_print_config_ptr->wipe_tower_extruder - 1);
lt.extruders.emplace_back(m_print_object_config_ptr->wipe_tower_extruder - 1);
sort_remove_duplicates(lt.extruders);
changed = true;
}
@ -653,7 +674,7 @@ void ToolOrdering::collect_extruder_statistics(bool prime_multi_material)
}
// Layers are marked for infinite skirt aka draft shield. Not all the layers have to be printed.
void ToolOrdering::mark_skirt_layers(const PrintConfig &config, coordf_t max_layer_height)
void ToolOrdering::mark_skirt_layers(const PrintConfig &config, coord_t max_layer_height)
{
if (m_layer_tools.empty())
return;
@ -674,9 +695,9 @@ void ToolOrdering::mark_skirt_layers(const PrintConfig &config, coordf_t max_lay
// Don't print skirt above the last object layer.
break;
// Mark some printing intermediate layers as having skirt.
double last_z = m_layer_tools[i].print_z;
coord_t last_z = m_layer_tools[i]._print_z;
for (size_t k = i + 1; k < j; ++ k) {
if (m_layer_tools[k + 1].print_z - last_z > max_layer_height + EPSILON) {
if ((m_layer_tools[k + 1]._print_z - last_z) > max_layer_height) {
// Layer k is the last one not violating the maximum layer height.
// Don't extrude skirt on empty layers.
while (m_layer_tools[k].extruders.empty())
@ -687,7 +708,7 @@ void ToolOrdering::mark_skirt_layers(const PrintConfig &config, coordf_t max_lay
break;
}
m_layer_tools[k].has_skirt = true;
last_z = m_layer_tools[k].print_z;
last_z = m_layer_tools[k]._print_z;
}
}
i = j;
@ -726,17 +747,22 @@ void ToolOrdering::assign_custom_gcodes(const Print &print)
for (uint16_t i : lt.extruders)
extruder_printing_above[i] = true;
// Skip all custom G-codes above this layer and skip all extruder switches.
for (; custom_gcode_it != custom_gcode_per_print_z.gcodes.rend() && (custom_gcode_it->print_z > lt.print_z + EPSILON || custom_gcode_it->type == CustomGCode::ToolChange); ++ custom_gcode_it);
for (; custom_gcode_it != custom_gcode_per_print_z.gcodes.rend() &&
(custom_gcode_it->print_z_ > lt._print_z ||
custom_gcode_it->type == CustomGCode::ToolChange);
++custom_gcode_it)
;
if (custom_gcode_it == custom_gcode_per_print_z.gcodes.rend())
// Custom G-codes were processed.
break;
// Some custom G-code is configured for this layer or a layer below.
const CustomGCode::Item &custom_gcode = *custom_gcode_it;
// print_z of the layer below the current layer.
coordf_t print_z_below = 0.;
coord_t print_z_below = 0.;
if (auto it_lt_below = it_lt; ++ it_lt_below != m_layer_tools.rend())
print_z_below = it_lt_below->print_z;
if (custom_gcode.print_z > print_z_below + 0.5 * EPSILON) {
print_z_below = it_lt_below->_print_z;
assert(custom_gcode.print_z_ < 1000);
if (Layer::scale_to_layer_coord(custom_gcode.print_z_) > print_z_below) {
// The custom G-code applies to the current layer.
bool color_change = custom_gcode.type == CustomGCode::ColorChange;
bool tool_change = custom_gcode.type == CustomGCode::ToolChange;
@ -755,13 +781,13 @@ void ToolOrdering::assign_custom_gcodes(const Print &print)
}
}
const LayerTools* ToolOrdering::tools_for_layer(coordf_t print_z) const
const LayerTools* ToolOrdering::tools_for_layer(coord_t print_z) const
{
// get the first layer at EPSILON from our target
//auto it_layer_tools = std::lower_bound(m_layer_tools.begin(), m_layer_tools.end(), LayerTools(print_z - EPSILON));
size_t idx_lower_bound;
for (idx_lower_bound = 0; idx_lower_bound < m_layer_tools.size(); ++idx_lower_bound) {
if (m_layer_tools[idx_lower_bound].print_z >= print_z - EPSILON) {
if (m_layer_tools[idx_lower_bound]._print_z >= print_z - EPSILON) {
break;
}
}
@ -769,9 +795,9 @@ const LayerTools* ToolOrdering::tools_for_layer(coordf_t print_z) const
if (idx_lower_bound >= m_layer_tools.size())
return nullptr;
// as we're at epsilon, just check just in case there is a better layer just a bit higher.
double dist_min = std::abs(m_layer_tools[idx_lower_bound].print_z - print_z);
double dist_min = std::abs(m_layer_tools[idx_lower_bound]._print_z - print_z);
for (; idx_lower_bound + 1 < m_layer_tools.size(); ++idx_lower_bound) {
double d = std::abs(m_layer_tools[idx_lower_bound + 1].print_z - print_z);
double d = std::abs(m_layer_tools[idx_lower_bound + 1]._print_z - print_z);
if (d >= dist_min) {
break;
}
@ -856,52 +882,54 @@ float WipingExtrusions::mark_wiping_extrusions(const Print& print, const LayerTo
const PrintObject* object = object_list[i];
// Finds this layer:
const Layer* this_layer = object->get_layer_at_printz(lt.print_z, EPSILON);
const Layer* this_layer = object->get_layer_at_printz(Layer::scale_to_layer_coord(lt._print_z));
assert(object->get_layer_at_printz(unscaled(lt._print_z), SCALED_EPSILON * 2) == this_layer);
if (this_layer == nullptr)
continue;
size_t num_of_copies = object->instances().size();
// iterate through copies (aka PrintObject instances) first, so that we mark neighbouring infills to minimize travel moves
for (uint16_t copy = 0; copy < num_of_copies; ++copy) {
for (const LayerRegion *layerm : this_layer->regions()) {
const auto &region = layerm->region();
if (!region.config().wipe_into_infill && !object->config().wipe_into_objects)
continue;
for (size_t copy = 0; copy < num_of_copies; ++copy) {
for (const LayerSliceIslandPtr &layer_island_ptr : this_layer->islands()) {
for (const LayerRegionIslandPtr &region_island_ptr : layer_island_ptr->regions_islands()) {
const PrintRegion &one_region = (*region_island_ptr->regions().begin())->region();
if (!one_region.config().wipe_into_infill && !object->config().wipe_into_objects)
continue;
bool wipe_into_infill_only = ! object->config().wipe_into_objects && one_region.config().wipe_into_infill;
if (region_island_ptr->has_extrusion(LayerRegionIsland::INFILLS) &&
(one_region.config().infill_first != perimeters_done || wipe_into_infill_only)) {
const ExtrusionEntityCollection &fill = region_island_ptr->extrusion(LayerRegionIsland::INFILLS);
bool wipe_into_infill_only = ! object->config().wipe_into_objects && region.config().wipe_into_infill;
if (region.config().infill_first != perimeters_done || wipe_into_infill_only) {
for (const ExtrusionEntity* ee : layerm->fills()) {
// iterate through all infill Collections
auto* fill = dynamic_cast<const ExtrusionEntityCollection*>(ee);
if (!is_overriddable(*fill, lt, print.config(), *object, region))
if (!is_overriddable(fill, lt, print.config(), *object, one_region))
continue;
if (wipe_into_infill_only && ! region.config().infill_first)
if (wipe_into_infill_only && ! one_region.config().infill_first)
// In this case we must check that the original extruder is used on this layer before the one we are overridding
// (and the perimeters will be finished before the infill is printed):
if (!lt.is_extruder_order(lt.perimeter_extruder(region), new_extruder))
if (!lt.is_extruder_order(lt.perimeter_extruder(one_region), new_extruder))
continue;
if ((!is_entity_overridden(fill, copy) && fill->total_volume() > min_infill_volume)) { // this infill will be used to wipe this extruder
set_extruder_override(fill, copy, new_extruder, num_of_copies);
if ((volume_to_wipe -= float(fill->total_volume())) <= 0.f)
if ((!is_entity_overridden(&fill, copy) && fill.total_volume() > min_infill_volume)) { // this infill will be used to wipe this extruder
set_extruder_override(&fill, copy, new_extruder, num_of_copies);
if ((volume_to_wipe -= float(fill.total_volume())) <= 0.f)
// More material was purged already than asked for.
return 0.f;
return 0.f;
}
}
}
// Now the same for perimeters - see comments above for explanation:
if (object->config().wipe_into_objects && region.config().infill_first == perimeters_done)
{
for (const ExtrusionEntity* ee : layerm->perimeters()) {
auto* fill = dynamic_cast<const ExtrusionEntityCollection*>(ee);
if (is_overriddable(*fill, lt, print.config(), *object, region) && !is_entity_overridden(fill, copy) && fill->total_volume() > min_infill_volume) {
set_extruder_override(fill, copy, new_extruder, num_of_copies);
if ((volume_to_wipe -= float(fill->total_volume())) <= 0.f)
// More material was purged already than asked for.
return 0.f;
// Now the same for perimeters - see comments above for explanation:
if (region_island_ptr->has_extrusion(LayerRegionIsland::PERIMETERS) &&
object->config().wipe_into_objects && one_region.config().infill_first == perimeters_done)
{
const ExtrusionEntityCollection &perimeter = region_island_ptr->extrusion(LayerRegionIsland::PERIMETERS);
if (is_overriddable(perimeter, lt, print.config(), *object, one_region) &&
!is_entity_overridden(&perimeter, copy) &&
perimeter.total_volume() > min_infill_volume) {
set_extruder_override(&perimeter, copy, new_extruder, num_of_copies);
if ((volume_to_wipe -= float(perimeter.total_volume())) <= 0.f)
// More material was purged already than asked for.
return 0.f;
}
}
}
@ -929,46 +957,47 @@ void WipingExtrusions::ensure_perimeters_infills_order(const Print& print, const
for (const PrintObject* object : print.objects()) {
// Finds this layer:
const Layer* this_layer = object->get_layer_at_printz(lt.print_z, EPSILON);
const Layer* this_layer = object->get_layer_at_printz(lt._print_z);
assert(object->get_layer_at_printz(unscaled(lt._print_z), SCALED_EPSILON * 2) == this_layer);
if (this_layer == nullptr)
continue;
size_t num_of_copies = object->instances().size();
for (size_t copy = 0; copy < num_of_copies; ++copy) { // iterate through copies first, so that we mark neighbouring infills to minimize travel moves
for (const LayerRegion *layerm : this_layer->regions()) {
const auto &region = layerm->region();
if (!region.config().wipe_into_infill && !object->config().wipe_into_objects)
continue;
for (const ExtrusionEntity* ee : layerm->fills()) { // iterate through all infill Collections
auto* fill = dynamic_cast<const ExtrusionEntityCollection*>(ee);
assert(fill);
if (!is_overriddable(*fill, lt, print.config(), *object, region)
|| is_entity_overridden(fill, copy) )
// iterate through copies first, so that we mark neighbouring infills to minimize travel moves
for (size_t copy = 0; copy < num_of_copies; ++copy) {
for (const LayerSliceIslandPtr &layer_island_ptr : this_layer->islands()) {
for (const LayerRegionIslandPtr &region_island_ptr : layer_island_ptr->regions_islands()) {
const PrintRegion &one_region = (*region_island_ptr->regions().begin())->region();
if (!one_region.config().wipe_into_infill && !object->config().wipe_into_objects)
continue;
// This infill could have been overridden but was not - unless we do something, it could be
// printed before its perimeter, or not be printed at all (in case its original extruder has
// not been added to LayerTools
// Either way, we will now force-override it with something suitable:
if (region.config().infill_first
|| object->config().wipe_into_objects // in this case the perimeter is overridden, so we can override by the last one safely
|| lt.is_extruder_order(lt.perimeter_extruder(region), last_nonsoluble_extruder) // !infill_first, but perimeter is already printed when last extruder prints
|| ! lt.has_extruder(lt.infill_extruder(region))) // we have to force override - this could violate infill_first (FIXME)
set_extruder_override(fill, copy, (region.config().infill_first ? first_nonsoluble_extruder : last_nonsoluble_extruder), num_of_copies);
else {
// In this case we can (and should) leave it to be printed normally.
// Force overriding would mean it gets printed before its perimeter.
}
}
if (region_island_ptr->has_extrusion(LayerRegionIsland::INFILLS)) { // iterate through all infill Collections
const ExtrusionEntityCollection &fill = region_island_ptr->extrusion(LayerRegionIsland::INFILLS);
// Now the same for perimeters - see comments above for explanation:
for (const ExtrusionEntity* ee : layerm->perimeters()) { // iterate through all perimeter Collections
auto* fill = dynamic_cast<const ExtrusionEntityCollection*>(ee);
assert(fill);
if (is_overriddable(*fill, lt, print.config(), *object, region) && ! is_entity_overridden(fill, copy))
set_extruder_override(fill, copy, (region.config().infill_first ? last_nonsoluble_extruder : first_nonsoluble_extruder), num_of_copies);
if (!is_overriddable(fill, lt, print.config(), *object, one_region)
|| is_entity_overridden(&fill, copy) )
continue;
// This infill could have been overridden but was not - unless we do something, it could be
// printed before its perimeter, or not be printed at all (in case its original extruder has
// not been added to LayerTools
// Either way, we will now force-override it with something suitable:
if (one_region.config().infill_first
|| object->config().wipe_into_objects // in this case the perimeter is overridden, so we can override by the last one safely
|| lt.is_extruder_order(lt.perimeter_extruder(one_region), last_nonsoluble_extruder) // !infill_first, but perimeter is already printed when last extruder prints
|| ! lt.has_extruder(lt.infill_extruder(one_region))) // we have to force override - this could violate infill_first (FIXME)
set_extruder_override(&fill, copy, (one_region.config().infill_first ? first_nonsoluble_extruder : last_nonsoluble_extruder), num_of_copies);
else {
// In this case we can (and should) leave it to be printed normally.
// Force overriding would mean it gets printed before its perimeter.
}
}
// Now the same for perimeters - see comments above for explanation:
if (region_island_ptr->has_extrusion(LayerRegionIsland::PERIMETERS)) { // iterate through all perimeter Collections
const ExtrusionEntityCollection &perimeter = region_island_ptr->extrusion(LayerRegionIsland::PERIMETERS);
if (is_overriddable(perimeter, lt, print.config(), *object, one_region) && ! is_entity_overridden(&perimeter, copy))
set_extruder_override(&perimeter, copy, (one_region.config().infill_first ? last_nonsoluble_extruder : first_nonsoluble_extruder), num_of_copies);
}
}
}
}

View file

@ -81,8 +81,8 @@ class LayerTools
public:
// Changing these operators to epsilon version can make a problem in cases where support and object layers get close to each other.
// In case someone tries to do it, make sure you know what you're doing and test it properly (slice multiple objects at once with supports).
bool operator< (const LayerTools &rhs) const { return print_z < rhs.print_z; }
bool operator==(const LayerTools &rhs) const { return print_z == rhs.print_z; }
bool operator< (const LayerTools &rhs) const { return _print_z < rhs._print_z; }
bool operator==(const LayerTools &rhs) const { return _print_z == rhs._print_z; }
bool is_extruder_order(uint16_t a, uint16_t b) const;
bool has_extruder(uint16_t extruder) const { return std::find(this->extruders.begin(), this->extruders.end(), extruder) != this->extruders.end(); }
@ -94,7 +94,7 @@ public:
// Returns a zero based extruder this eec should be printed with, according to PrintRegion config or extruder_override if overriden.
uint16_t extruder(const ExtrusionEntityCollection &extrusions, const PrintRegion &region) const;
double print_z = 0.;
coord_t _print_z = 0;
bool has_object = false;
bool has_support = false;
// Zero based extruder IDs, ordered to minimize tool switches.
@ -115,7 +115,7 @@ public:
// Number of wipe tower partitions to support the required number of tool switches
// and to support the wipe tower partitions above this one.
size_t wipe_tower_partitions = 0;
double wipe_tower_layer_height = 0.;
coord_t wipe_tower_layer_height = 0.;
// Custom G-code (color change, extruder switch, pause) to be performed before this layer starts to print.
const CustomGCode::Item *custom_gcode = nullptr;
@ -125,7 +125,7 @@ public:
private:
// to access LayerTools private constructor
friend class ToolOrdering;
LayerTools(const coordf_t z) : print_z(z) {}
LayerTools(const coord_t z, bool scaledok) : _print_z(z) {}
// This object holds list of extrusion that will be used for extruder wiping
WipingExtrusions m_wiping_extrusions;
@ -166,8 +166,8 @@ public:
const std::vector<uint16_t>& all_extruders() const { return m_all_printing_extruders; }
// Find LayerTools with the closest print_z.
const LayerTools* tools_for_layer(coordf_t print_z) const;
LayerTools* tools_for_layer(coordf_t print_z) { return const_cast<LayerTools*>(std::as_const(*this).tools_for_layer(print_z)); }
const LayerTools* tools_for_layer(coord_t print_z) const;
LayerTools* tools_for_layer(coord_t print_z) { return const_cast<LayerTools*>(std::as_const(*this).tools_for_layer(print_z)); }
const LayerTools& front() const { return m_layer_tools.front(); }
const LayerTools& back() const { return m_layer_tools.back(); }
@ -175,20 +175,27 @@ public:
std::vector<LayerTools>::const_iterator end() const { return m_layer_tools.end(); }
bool empty() const { return m_layer_tools.empty(); }
std::vector<LayerTools>& layer_tools() { return m_layer_tools; }
const std::vector<LayerTools>& layer_tools() const { return m_layer_tools; }
bool has_wipe_tower() const { return ! m_layer_tools.empty() && m_first_printing_extruder != (uint16_t)-1 && m_layer_tools.front().wipe_tower_partitions > 0; }
int toolchanges_count() const;
const std::vector<const PrintObject*> &objects() const { return m_objects; }
const std::vector<const PrintObject *>& objects() const { return m_objects; };
private:
void initialize_layers(std::vector<double> &zs);
void collect_extruders(const PrintObject &object, const GCode::ObjectsLayerToPrint &layers, const std::vector<std::pair<double, uint16_t>> &per_layer_extruder_switches, const std::vector<std::pair<double, uint16_t>> &per_layer_color_changes);
void initialize_layers(std::vector<coord_t> &zs);
void collect_extruders(const PrintObject &object,
const GCode::ObjectsLayerToPrint &layers,
const std::vector<std::pair<coord_t, uint16_t>> &per_layer_extruder_switches,
const std::vector<std::pair<coord_t, uint16_t>> &per_layer_color_changes);
void reorder_extruders(uint16_t last_extruder_id);
void fill_wipe_tower_partitions(const PrintConfig &config, coordf_t object_bottom_z, coordf_t max_layer_height);
void fill_wipe_tower_partitions(const PrintConfig &config,
coord_t object_bottom_z,
coord_t max_layer_height);
bool insert_wipe_tower_extruder();
void mark_skirt_layers(const PrintConfig &config, coordf_t max_layer_height);
void mark_skirt_layers(const PrintConfig &config, coord_t max_layer_height);
void collect_extruder_statistics(bool prime_multi_material);
std::vector<LayerTools> m_layer_tools;
std::vector<const PrintObject*> m_objects;
// First printing extruder, including the multi-material priming sequence.
uint16_t m_first_printing_extruder = (uint16_t)-1;
// Final printing extruder.
@ -197,8 +204,7 @@ private:
std::vector<uint16_t> m_all_printing_extruders;
const PrintConfig* m_print_config_ptr = nullptr;
std::vector<const PrintObject*> m_objects;
const PrintObjectConfig* m_print_object_config_ptr = nullptr;
};
} // namespace SLic3r

View file

@ -119,7 +119,6 @@ AABBTreeLines::LinesDistancer<ObjectOrExtrusionLinef> get_previous_layer_distanc
return AABBTreeLines::LinesDistancer{std::move(lines)};
}
//note: using the third-level of extrusion from the layerm.perimeters() is extremly unsafe!
std::pair<AABBTreeLines::LinesDistancer<ObjectOrExtrusionLinef>, size_t> TravelObstacleTracker::get_current_layer_distancer(const ObjectsLayerToPrint &objects_to_print)
{
std::vector<ObjectOrExtrusionLinef> lines;
@ -134,20 +133,13 @@ std::pair<AABBTreeLines::LinesDistancer<ObjectOrExtrusionLinef>, size_t> TravelO
for (const PrintInstance &instance : layer->object()->instances()) {
visitor.instance = &instance;
visitor.instance_idx = &instance - &layer->object()->instances().front();
for (const LayerSlice &lslice : layer->lslices_ex) {
for (const LayerIsland &island : lslice.islands) {
const LayerRegion &layerm = *layer->get_region(island.perimeters.region());
for (uint32_t perimeter_id : island.perimeters) {
assert(dynamic_cast<const ExtrusionEntityCollection *>(layerm.perimeters().entities()[perimeter_id]));
const auto *eec = static_cast<const ExtrusionEntityCollection *>(layerm.perimeters().entities()[perimeter_id]);
if (eec) {
for (const ExtrusionEntity *ee : *eec) {
const LayerRegion &layerm = *layer->get_region(island.perimeters.region());
for (uint32_t perimeter_id : island.perimeters) {
visitor.process(ee);
}
++extrusion_entity_cnt;
}
for (const LayerSliceIslandPtr &layer_island_ptr : layer->islands()) {
for (const LayerRegionIslandPtr &region_island_ptr : layer_island_ptr->regions_islands()) {
const LayerRegion &layerm = **region_island_ptr->regions().begin(); // FIXME multiple regions
if (region_island_ptr->has_extrusion(LayerRegionIsland::PERIMETERS)) {
for (const ExtrusionEntity *ee : region_island_ptr->extrusion(LayerRegionIsland::PERIMETERS)) {
visitor.process(ee);
++extrusion_entity_cnt;
}
}
}

View file

@ -149,13 +149,19 @@ std::string Wipe::wipe(GCodeGenerator &gcodegen, bool toolchange)
double wipe_length = wipe_total_length;
/*const*/double lift_length = extruder.id() < 0 ? 0 : gcodegen.config().wipe_lift_length.get_abs_value(extruder.id(), wipe_length);
lift_length = std::min(lift_length, wipe_total_length);
if (gcodegen.writer().get_lift() > 0) {
// already lifted? weird, but don't lift more.
assert(false);
lift_length = 0;
}
double no_lift_length = wipe_total_length - lift_length;
assert(no_lift_length >= 0);
const double lift = extruder.id() < 0 ? 0 : gcodegen.config().wipe_lift.get_abs_value(extruder.id(), gcodegen.layer()->height);
const double lift_per_mm = lift / lift_length;
const double lift_mm = extruder.id() < 0 ? 0 : gcodegen.config().wipe_lift.get_abs_value(extruder.id(), gcodegen.layer()->unscaled_height());
const double lift_per_mm = lift_mm / lift_length;
const double initial_z = gcodegen.writer().get_position().z();
assert(gcodegen.current_z_layer() && gcodegen.current_z_layer()->scaled_print_z() == Layer::scale_to_layer_coord(initial_z));
double current_z = initial_z;
const double final_z = gcodegen.writer().get_position().z() + lift;
const double final_z = initial_z + lift_mm;
auto wipe_linear = [&gcode, &gcodegen, &retract_length, &wipe_length, &no_lift_length, &current_z, xy_to_e, use_firmware_retract, lift_per_mm, final_z]
(const Vec2d &prev_quantized, Vec2d &p, bool &done)->bool { //return false if point is used, true if need to be recalled again
bool partial_segment = false;

View file

@ -642,15 +642,15 @@ WipeTower::WipeTower(const PrintConfig& config, const PrintObjectConfig& default
m_object_config(&default_object_config),
m_region_config(&default_region_config),
m_semm(config.single_extruder_multi_material.value),
m_wipe_tower_pos(config.wipe_tower_x, config.wipe_tower_y),
m_wipe_tower_width(float(config.wipe_tower_width)),
m_wipe_tower_rotation_angle(float(config.wipe_tower_rotation_angle)),
m_wipe_tower_pos(default_object_config.wipe_tower_x, default_object_config.wipe_tower_y),
m_wipe_tower_width(float(default_object_config.wipe_tower_width)),
m_wipe_tower_rotation_angle(float(default_object_config.wipe_tower_rotation_angle)),
m_speed(float(config.wipe_tower_speed)),
m_wipe_tower_cone_angle(float(config.wipe_tower_cone_angle)),
m_extra_spacing(float(config.wipe_tower_extra_spacing/100.)),
m_wipe_tower_cone_angle(float(default_object_config.wipe_tower_cone_angle)),
m_extra_spacing(float(default_object_config.wipe_tower_extra_spacing/100.)),
m_y_shift(0.f),
m_z_pos(0.f),
m_bridging(float(config.wipe_tower_bridging)),
m_bridging(float(default_object_config.wipe_tower_bridging)),
m_no_sparse_layers(config.wipe_tower_no_sparse_layers),
m_gcode_flavor(config.gcode_flavor),
m_travel_speed(config.travel_speed),
@ -718,10 +718,10 @@ void WipeTower::set_extruder(size_t idx)
m_filpar.push_back(FilamentParameters());
m_filpar[idx].material = m_config->filament_type.get_at(idx);
if (m_config->wipe_tower_extruder == 0) {
if (m_object_config->wipe_tower_extruder == 0) {
m_filpar[idx].is_soluble = m_config->filament_soluble.get_at(idx);
} else {
m_filpar[idx].is_soluble = (idx != size_t(m_config->wipe_tower_extruder - 1));
m_filpar[idx].is_soluble = (idx != size_t(m_object_config->wipe_tower_extruder - 1));
}
m_filpar[idx].temperature = m_config->temperature.get_at(idx);
m_filpar[idx].first_layer_temperature = m_config->first_layer_temperature.get_at(idx);
@ -764,7 +764,7 @@ void WipeTower::set_extruder(size_t idx)
m_filpar[idx].max_e_speed = (max_vol_speed / filament_area());
m_nozzle_diameter = nozzle_diameter; // all extruders are now assumed to have the same diameter
m_perimeter_width = m_config->wipe_tower_extrusion_width.get_abs_value(nozzle_diameter); // all extruders are now assumed to have the same diameter
m_perimeter_width = m_object_config->wipe_tower_extrusion_width.get_abs_value(nozzle_diameter); // all extruders are now assumed to have the same diameter
if (m_semm) {
std::istringstream stream{m_config->filament_ramming_parameters.get_at(idx)};
@ -1636,9 +1636,9 @@ WipeTower::ToolChangeResult WipeTower::finish_layer()
);
const double spacing = brim_flow.spacing();
// How many perimeters shall the brim have?
size_t loops_num = (m_config->wipe_tower_brim_width.get_abs_value(m_nozzle_diameter) + spacing / 2) / spacing;
size_t loops_num = (m_object_config->wipe_tower_brim_width.get_abs_value(m_nozzle_diameter) + spacing / 2) / spacing;
// ensure the loops_num is within bounds
if (m_config->wipe_tower_brim_width.get_abs_value(m_nozzle_diameter) <= 0) {
if (m_object_config->wipe_tower_brim_width.get_abs_value(m_nozzle_diameter) <= 0) {
loops_num = 0;
}
assert(loops_num < 999);

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,317 @@
///|/ Copyright (c) Prusa Research 2017 - 2023 Lukáš Matěna @lukasmatena, Vojtěch Bubník @bubnikv
///|/
///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher
///|/
#ifndef slic3r_GCode_WipeTower2_hpp_
#define slic3r_GCode_WipeTower2_hpp_
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <sstream>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include <tcbspan/span.hpp>
#include "libslic3r/Point.hpp"
#include "libslic3r/Polyline.hpp"
#include "libslic3r/Print.hpp"
#include "libslic3r/Config.hpp"
#include "libslic3r/Flow.hpp"
#include "libslic3r/ExtrusionEntityCollection.hpp"
namespace Slic3r
{
class PrintConfig;
class PrintObjectConfig;
class PrintRegionConfig;
class FullPrintConfig;
class Print;
enum GCodeFlavor : unsigned char;
class Layer;
class PrintObject;
// For const correctness: Wrapping a vector of non-const pointers as a span of const pointers.
template<class T>
using SpanOfConstPtrs = tcb::span<const T* const>;
/**
* WipeTower:
* 1) in print, plan(layers) is called. This will compute the needed space for toolchanges, purges.
* Whiththat, it ahs the max bb per layer.
* 2) in print, it can get the max boundingbox from the toolchanges, purges
* 4) in gcode, when a new layer start, it gets the info if a purge is needed (todo, currently not possible as
* retractions are done after) and the toolchange order
* 3) in gcode, when a toolchange occur: it gets the paths from
* infill, it goes to wp, ram & unload, changetool, [go to infill] unretract & wipe (wp/infill).
* It print the border & infill of the wipetower if needed (before going into infill).
*
* */
class WipeTowerLayer;
class WipeTower2
{
protected:
// config for us
const PrintConfig *m_config;
// if global wipetower, this is the default object_config
const PrintObjectConfig *m_object_config;
const PrintRegionConfig *m_region_config;
// position relative to object coordinates or platter coordinates
Point m_position; //cached from m_object_config
coord_t max_line_width = -1;
coord_t min_line_width = -1;
public:
//std::vector<std::shared_ptr<WipeTowerLayer>> wipe_tower_layers;
//std::map<coord_t, std::shared_ptr<WipeTowerLayer>> print_z_to_wipe_tower_layer;
// ===== for print =====
void set_config(const PrintConfig *config, const PrintObjectConfig *object_config, const PrintRegionConfig *region_config);
coord_t width() const;
Vec2d position() const;
coord_t extra_spacing() const;
double rotation_angle() const;
//((ConfigOptionFloat, wipe_tower_per_color_wipe))
//((ConfigOptionFloat, wipe_tower_cone_angle))
//((ConfigOptionFloat, wipe_tower_bridging))
//((ConfigOptionInt, wipe_tower_extruder))
// general info about a filament, computed from config.
struct FilamentToolchangeInfo
{
uint16_t tool_id = -1;
// purge the nozzle before retracting
double purge_volume; // mm3
double purge_flow_mm3_sec;
coord_t purge_width;
coord_t purge_spacing;
//Flow purge_flow;
// wipe after unretracting (also used for unretracting)
// when going into this tool, what's the worst wipe dist?
//distf_t wipe_volume_max_from; // mm3
//// when going from this tool, what's the worst wipe length?
//distf_t wipe_volume_max_to; // mm3
double wipe_volume_min; // mm3
coord_t wipe_width;
coord_t wipe_spacing;
double wipe_speed;
//Flow wipe_flow;
};
// one per extruder
std::vector<FilamentToolchangeInfo> m_filament_change_data;
// fused layers (with same z & height) info (general layer, can have multiple object or only one)
struct ObjectLayerData
{
//WipeTowerLayer *wipe_tower_layer;
coord_t real_z;
coord_t real_height;
// when the real_height is too low, it's merged with previous layer(s).
// this vector stores the layer order (this is present inside)
std::vector<const Layer *> my_layers;
static int64_t compute_layer_key(coord_t z, coord_t height);
//std::unique_ptr<WipeTowerLayer> create_wipe_tower_layer();
};
// layer_key (z & height) to LayerData
std::map<int64_t, std::unique_ptr<ObjectLayerData>> m_layer_data;
// fused layers (same z, can have different height) info
// as we can use the same tool at the same z for different height before switching to another one.
struct ZLayerData
{
coord_t real_z;
std::vector<uint16_t> extruders; // from Toolordering (should be ordered correctly)
coord_t estimated_wipe_tower_length; // from extruder toolchange
};
// data to construct a wipe tower layer.
struct WipeTowerLayerData
{
coord_t extrusion_z;
coord_t extrusion_height;
std::vector<ObjectLayerData *> fused_with;
std::map<coord_t, ZLayerData> extruders_data;
coord_t estimated_wipe_tower_length; // from extruder toolchange
//distf_t worst_needed_length;
//distf_t worst_needed_length_with_fused;
std::vector<const Layer *> layers() const;
std::vector<const PrintObject *> objects() const;
};
std::vector<std::unique_ptr<WipeTowerLayerData>> m_WTLayer_data;
std::map<coord_t, WipeTowerLayerData*> m_printz_to_WTLayer_data;
// init m_filament_change_data and m_layer_data, m_printz_to_WTLayer_data
void init(const Print *print, const SpanOfConstPtrs<PrintObject> &objects, ToolOrdering &ordering);
std::map<coord_t, std::shared_ptr<WipeTowerLayer>> create_layers() const;
// get tower width at this z (if nothing at this width, return 0)
//distf_t get_max_length(coord_t z);
// rough estimation
static std::vector<std::vector<float>> extract_wipe_volumes(const ConfigBase &config);
static coord_t floatz_tolayer_coord(double z);
ExtrusionEntityCollection prime(const std::vector<uint16_t> &tools, coord_t first_layer_height);
bool has_toolchange() const;
static std::pair<double, double> get_wipe_tower_cone_base(double width,
double height,
double depth,
double angle_deg);
Flow get_ramming_flow(const uint16_t tool_id, const bool first_layer, const double layer_height);
//TODO
// in mm3
double get_loading_volume(uint16_t tool_idx) {
return 1;
}
double get_loading_speed(uint16_t tool_idx) {
return 1;
}
double get_prime_volume(uint16_t tool_idx) {
return 1;
}
double get_prime_speed(uint16_t tool_idx) {
return 1;
}
double get_unloading_volume(uint16_t tool_idx) {
return 1;
}
double get_unloading_speed(uint16_t tool_idx) {
return 1;
}
double get_first_layer_acceleration(uint16_t tool_idx) {
return 1;
}
double get_first_layer_pa(uint16_t tool_idx) {
return 1;
}
double get_first_layer_fan_speed(uint16_t tool_idx) {
return 1;
}
friend class WipeTowerLayer;
};
// ===== for gcode =====
// plan
class WipeTowerLayer
{
protected:
public:
// config for us
const PrintConfig *m_config;
// if global wipetower, this is the default object_config
const PrintObjectConfig *m_object_config;
const WipeTower2* m_wipe_tower_info;
//const WipeTower2::WipeTowerLayerData* m_layer_data;
// all layer z purged in this layer;
std::set<coord_t> layers_z;
std::vector<const Layer *> layers;
// this layer extrusion information
size_t wipetower_layer_idx = 0;
coord_t extrusion_z;
coord_t extrusion_height;
std::vector<coord_t> uninitialized_z;
std::vector<coord_t> initialized_z;
bool m_is_finished = false;
coord_t m_current_y_pos = 0;
coord_t m_max_y_pos;
coord_t m_wipetower_max_y_pos;
Flow brim_flow;
Polylines brim;
bool brim_done = false;
Flow tower_perimeter_flow;
Polylines tower_perimeters;
uint16_t perimeter_tool_idx = uint16_t(-1);
bool perimeter_done = false;
bool y_down = true;
Point last_point;
struct Toolchange
{
const Layer *layer;
uint16_t from_tool_id;
Flow purge_flow;
Polyline purge_lines;
uint16_t to_tool_id;
Flow wipe_flow;
Polyline wipe_lines;
bool done = false;
};
// print_z & old_tool & new_tool => toolchange
std::map<std::tuple<coord_t, uint16_t, uint16_t>, Toolchange> m_toolchanges;
struct Purge
{
uint16_t tool_id;
Flow purge_flow;
Polyline purge_lines;
bool done = false;
};
std::vector<Purge> m_purges;
// ===== for both =====
public:
WipeTowerLayer(const WipeTower2 *wipetower)
: m_wipe_tower_info(wipetower), m_config(wipetower->m_config), m_object_config(wipetower->m_object_config) {}
// gcode
// plan the whole layer toolchanges & purges.
void init(const std::vector<const Layer *> layers,
const std::vector<uint16_t> &ordered_extruders,
const std::vector<uint16_t> &purges);
// ask to create the next extrusions
//ExtrusionEntityCollection create_toolchange(uint16_t from, uint16_t to, Point current_pos);
//ExtrusionEntityCollection create_purge(uint16_t toolid, Point current_pos);
ExtrusionEntityCollection tool_change(const Layer *layer, uint16_t old_tool, uint16_t new_tool, double de_retraction_new_tool = 0);
bool finish_layer(ExtrusionEntityCollection &collection, uint16_t current_extruder, bool force = false);
protected:
void toolchange_load(ExtrusionEntityCollection &collection,
const Polyline &loading_lines,
const uint16_t tool_id);
bool toolchange_Unload(ExtrusionEntityCollection &collection,
const Polyline &ramming_lines,
const uint16_t tool_id,
const Flow &ramming_flow);
void toolchange_Wipe(ExtrusionEntityCollection &collection,
Polyline wipe_lines,
const Flow wipe_flow,
const uint16_t tool_id,
const double de_retraction_new_tool);
void toolchange_Change(ExtrusionEntityCollection &collection, const uint16_t new_tool);
bool print_perimeter(ExtrusionEntityCollection &collection, bool for_toolchange = false);
coord_t compute_y(coord_t raw_y);
};
} // namespace Slic3r
#endif // slic3r_GCode_WipeTower2_hpp_

View file

@ -35,7 +35,8 @@ std::string WipeTowerIntegration::toolchange_gcode_from_wipe_tower_generator(GCo
if (tcr.priming || (new_extruder_id >= 0)) {
if (is_ramming)
gcodegen.m_wipe.reset_path(); // We don't want wiping on the ramming lines.
toolchange_gcode_str = gcodegen.set_extruder(new_extruder_id, tcr.print_z); // TODO: toolchange_z vs print_z
toolchange_gcode_str = gcodegen.set_extruder(new_extruder_id,
scale_t(tcr.print_z + EPSILON)); // TODO: toolchange_z vs print_z
}
assert(toolchange_gcode_str.empty() || toolchange_gcode_str.back() == '\n');
return toolchange_gcode_str;
@ -102,7 +103,7 @@ std::string WipeTowerIntegration::append_tcr(GCodeGenerator &gcodegen, const Wip
if (should_travel_to_tower || m_has_force_travel) {
const Point xy_point = wipe_tower_point_to_object_point(gcodegen, start_pos);
if (should_travel_to_tower) {
gcode += gcodegen.retract_and_wipe();
gcode += gcodegen.retract_and_wipe(needs_toolchange);
gcodegen.m_avoid_crossing_perimeters.use_external_mp_once();
need_unretract = true;
}

View file

@ -14,13 +14,14 @@ class WipeTowerIntegration {
public:
WipeTowerIntegration(
const PrintConfig &print_config,
const PrintObjectConfig &object_config,
const std::vector<WipeTower::ToolChangeResult> &priming,
const std::vector<std::vector<WipeTower::ToolChangeResult>> &tool_changes,
const WipeTower::ToolChangeResult &final_purge) :
m_left(/*float(print_config.wipe_tower_x.value)*/ 0.f),
m_right(float(/*print_config.wipe_tower_x.value +*/ print_config.wipe_tower_width.value)),
m_wipe_tower_pos(float(print_config.wipe_tower_x.value), float(print_config.wipe_tower_y.value)),
m_wipe_tower_rotation(float(print_config.wipe_tower_rotation_angle)),
m_right(float(/*print_config.wipe_tower_x.value +*/ object_config.wipe_tower_width.value)),
m_wipe_tower_pos(float(object_config.wipe_tower_x.value), float(object_config.wipe_tower_y.value)),
m_wipe_tower_rotation(float(object_config.wipe_tower_rotation_angle)),
m_extruder_offsets(print_config.extruder_offset.get_values()),
m_priming(priming),
m_tool_changes(tool_changes),

View file

@ -63,9 +63,13 @@ const char* GCodeReader::parse_line_internal(const char *ptr, const char *end, G
case 'Z': axis = Z; break;
case 'F': axis = F; break;
default:
if (*c == m_extrusion_axis) {
if (m_extrusion_axis != 0)
axis = E;
if (*c == m_extrusion_axis && m_extrusion_axis != 0) {
axis = E;
gline.m_e_char = *c;
} else if(*c > m_extrusion_axis && *c + 20 < m_extrusion_axis && m_extrusion_axis != 0) {
// kind of a multiple extruder with a letter per extruder.
axis = E;
gline.m_e_char = *c;
} else if (*c >= 'A' && *c <= 'Z')
// Unknown axis, but we still want to remember that such a axis was seen.
axis = UNKNOWN_AXIS;

View file

@ -74,6 +74,8 @@ public:
float e() const { return m_axis[E]; }
float f() const { return m_axis[F]; }
char e_char() const { return m_e_char; }
static bool cmd_is(const std::string &gcode_line, const char *cmd_test) {
const char *cmd = GCodeReader::skip_whitespaces(gcode_line.c_str());
// Skip line number
@ -100,6 +102,7 @@ public:
std::string m_raw;
float m_axis[NUM_AXES];
uint32_t m_mask;
char m_e_char;
friend class GCodeReader;
};
class FakeGCodeLine : public GCodeLine {

View file

@ -751,7 +751,7 @@ Path fit_path(const Points &src_in, double tolerance, double fit_circle_percent_
Line line(arc->start_point, arc->end_point);
bool arc_valid = false;
for (auto it2 = std::next(begin); it2 != std::prev(end); ++ it2)
if (line_alg::distance_to_squared(line, *it2) > tolerance2) {
if (line.distance_to_squared(*it2) > tolerance2) {
// Polyline could not be fitted by a line segment, thus the arc is considered valid.
arc_valid = true;
break;
@ -1068,7 +1068,7 @@ PathSegmentProjection point_to_path_projection(const Path &path, const Point &po
// Linear segment
Point proj;
// distance_to_squared() will possibly return the start or end point of a line segment.
if (double d2 = line_alg::distance_to_squared(Line(prev, it->point), point, &proj); d2 < out.distance2) {
if (double d2 = Line::distance_to_squared_abp(prev, it->point, point, &proj); d2 < out.distance2) {
out.point = proj;
out.distance2 = d2;
out.center = {0, 0};

View file

@ -502,7 +502,7 @@ get_coeff_from_angle_countour(Point& point, const ExPolygon& contour, coord_t mi
angle = angle_ccw(point_before - point_nearest, \
point_after - point_nearest); // point_nearest.ccw_angle(point_before, point_after);if (angle >=
// PI) angle = 2 * PI - angle;
assert(angle < PI);
assert(angle <= PI);
//compute the diff from 90°
angle = abs(angle - PI / 2);
if (point_near.coincides_with_epsilon(point_nearest) && std::max(nearest_dist, near_dist) + SCALED_EPSILON < point_nearest.distance_to(point_near)) {
@ -2502,7 +2502,7 @@ unsafe_variable_width(const ThickPolyline& polyline, const ExtrusionRole role, c
#endif
ExtrusionPaths paths;
ExtrusionPath path(role, false);
ExtrusionPath path(role, nullptr, false);
ThickLines lines = polyline.thicklines();
Flow current_flow = flow;
@ -2531,7 +2531,11 @@ unsafe_variable_width(const ThickPolyline& polyline, const ExtrusionRole role, c
// split lines ?
if (resolution_internal < line_len) {
if (thickness_delta > tolerance && ceil(float(thickness_delta) / float(tolerance)) > 2) {
const uint16_t segments = 1 + (uint16_t)std::min((uint32_t)16000, (uint32_t)ceil(float(thickness_delta) / float(tolerance)));
const uint32_t max_segments = std::min(1 + int(line_len / resolution_internal),
int(line_len / (SCALED_EPSILON * 2)));
const uint16_t segments = 1 +
(uint16_t) std::min(std::min(max_segments, (uint32_t) 16000),
(uint32_t) ceil(float(thickness_delta) / float(tolerance)));
Points pp;
std::vector<coordf_t> width;
{
@ -2729,7 +2733,7 @@ unsafe_variable_width(const ThickPolyline& polyline, const ExtrusionRole role, c
assert(!std::isnan(current_flow.mm3_per_mm()));
assert(!std::isnan(current_flow.width()));
assert(!std::isnan(current_flow.height()));
path = { ExtrusionAttributes{ role, current_flow }, false };
path = ExtrusionPath( ExtrusionAttributes{ role, current_flow }, nullptr, false );
path.polyline.append(line.a);
path.polyline.append(line.b);
assert(path.polyline.is_valid());
@ -2754,7 +2758,7 @@ unsafe_variable_width(const ThickPolyline& polyline, const ExtrusionRole role, c
assert(!std::isnan(current_flow.mm3_per_mm()));
assert(!std::isnan(current_flow.width()));
assert(!std::isnan(current_flow.height()));
path = { ExtrusionAttributes{ role, current_flow }, false };
path = ExtrusionPath( ExtrusionAttributes{ role, current_flow }, nullptr, false );
path.polyline.append(line.a);
path.polyline.append(line.b);
assert(path.polyline.is_valid());
@ -2784,8 +2788,10 @@ ExtrusionEntitiesPtr
ExtrusionEntitiesPtr coll;
for (const ThickPolyline& p : polylines) {
#if _DEBUG
for (size_t idx_pt = 1; idx_pt < p.size(); ++idx_pt)
for (size_t idx_pt = 1; idx_pt < p.size(); ++idx_pt) {
assert(!p.points[idx_pt - 1].coincides_with_epsilon(p.points[idx_pt]));
assert(p.points[idx_pt - 1].distance_to(p.points[idx_pt]) >= SCALED_EPSILON);
}
#endif
ExtrusionMultiPath multi_paths = variable_width(p, role, flow, resolution_internal, tolerance, can_reverse);
// Append paths to collection.
@ -2800,7 +2806,23 @@ ExtrusionEntitiesPtr
assert(!it->polyline.get_point(idx_pt - 1).coincides_with_epsilon(it->polyline.get_point(idx_pt)));
#endif
if (multi_paths.paths.front().first_point().coincides_with_epsilon(multi_paths.paths.back().last_point())) {
coll.push_back(new ExtrusionLoop(std::move(multi_paths.paths)));
// check if real loop or fluke
int nb_points = 0;
for (ExtrusionPath &path : multi_paths.paths) {
nb_points += path.size() -1;
}
if (nb_points > 2) {
// good enough
coll.push_back(new ExtrusionLoop(std::move(multi_paths.paths)));
} else {
// fluke, not big enough
assert(multi_paths.paths.size() <= 2);
assert(multi_paths.paths.front().size() > 1);
if (multi_paths.paths.front().size() > 2) {
multi_paths.paths.front().polyline.pop_back();
}
coll.push_back(multi_paths.paths.front().clone_move());
}
} else {
if (role == ExtrusionRole::ThinWall) {
//thin walls : avoid to cut them, please.

View file

@ -215,7 +215,7 @@ void JPSPathFinder::add_obstacles(const Layer *layer, const Point &global_origin
{
if (layer == nullptr) return;
this->print_z = layer->print_z;
this->print_z = layer->scaled_print_z();
Lines obstacles;
obstacles.reserve(layer->curled_lines.size());
for (const Line &l : layer->curled_lines) { obstacles.push_back(Line{l.a + global_origin, l.b + global_origin}); }
@ -303,7 +303,7 @@ Polyline JPSPathFinder::find_path(const Point &p0, const Point &p1)
return r;
};
auto scaled_point = [](const Point &p) { return Point::new_scale(p.x(), p.y()); };
::Slic3r::SVG svg(debug_out_path(("path_jps" + std::to_string(print_z) + "_" + std::to_string(safe_rand(1000))).c_str()).c_str(),
::Slic3r::SVG svg(debug_out_path(("path_jps" + std::to_string(unscaled(print_z)) + "_" + std::to_string(safe_rand(1000))).c_str()).c_str(),
BoundingBox(scaled_point(search_box.min), scaled_point(search_box.max)));
for (const auto &p : inpassable) { svg.draw(scaled_point(p), "black", scale_(0.4)); }
for (const auto &qn : astar_cache) { svg.draw(scaled_point(qn.second.node.position), "blue", scale_(0.3)); }

View file

@ -20,7 +20,7 @@ class JPSPathFinder
{
using Pixel = Point;
std::unordered_set<Pixel, PointHash> inpassable;
coordf_t print_z;
coord_t print_z;
BoundingBox max_search_box;
Lines bed_shape;

File diff suppressed because it is too large Load diff

View file

@ -1,3 +1,4 @@
///|/ Copyright (c) SuperSlicer 2018 - 2025 Durand Rémi @supermerill
///|/ Copyright (c) Prusa Research 2016 - 2023 Pavel Mikuš @Godrak, Vojtěch Bubník @bubnikv, Lukáš Hejl @hejllukas, Lukáš Matěna @lukasmatena
///|/ Copyright (c) Slic3r 2014 - 2015 Alessandro Ranellucci @alranel
///|/ Copyright (c) 2015 Maksim Derbasov @ntfshard
@ -6,7 +7,7 @@
///|/ Copyright (c) Prusa Research 2016 - 2022 Vojtěch Bubník @bubnikv
///|/ Copyright (c) Slic3r 2011 - 2016 Alessandro Ranellucci @alranel
///|/
///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher
///|/ SuperSlicer, PrusaSlicer, Slic3r are released under the terms of the AGPLv3 or higher
///|/
#ifndef slic3r_Layer_hpp_
#define slic3r_Layer_hpp_
@ -26,8 +27,11 @@ class ExPolygon;
using ExPolygons = std::vector<ExPolygon>;
class Layer;
using LayerPtrs = std::vector<Layer*>;
class LayerSliceIsland;
class LayerRegionIsland;
class LayerRegion;
using LayerRegionPtrs = std::vector<LayerRegion*>;
using LayerRegionSetConstPtrs = std::set<const LayerRegion*>;
class PrintRegion;
class PrintObject;
@ -39,68 +43,6 @@ namespace FillLightning {
class Generator;
};
// Range of indices, providing support for range based loops.
template<typename T>
class IndexRange
{
public:
IndexRange(T ibegin, T iend) : m_begin(ibegin), m_end(iend) {}
IndexRange() = default;
// Just a bare minimum functionality iterator required by range-for loop.
class Iterator {
public:
T operator*() const { return m_idx; }
bool operator!=(const Iterator &rhs) const { return m_idx != rhs.m_idx; }
void operator++() { ++ m_idx; }
private:
friend class IndexRange<T>;
Iterator(T idx) : m_idx(idx) {}
T m_idx;
};
Iterator begin() const { assert(m_begin <= m_end); return Iterator(m_begin); };
Iterator end() const { assert(m_begin <= m_end); return Iterator(m_end); };
bool empty() const { assert(m_begin <= m_end); return m_begin >= m_end; }
T size() const { assert(m_begin <= m_end); return m_end - m_begin; }
private:
// Index of the first extrusion in LayerRegion.
T m_begin { 0 };
// Index of the last extrusion in LayerRegion.
T m_end { 0 };
};
using ExtrusionRange = IndexRange<uint32_t>;
using ExPolygonRange = IndexRange<uint32_t>;
// Range of extrusions, referencing the source region by an index.
class LayerExtrusionRange : public ExtrusionRange
{
public:
LayerExtrusionRange(uint32_t iregion, ExtrusionRange extrusion_range) : m_region(iregion), ExtrusionRange(extrusion_range) {}
LayerExtrusionRange() = default;
// Index of LayerRegion in Layer.
uint32_t region() const { return m_region; };
private:
// Index of LayerRegion in Layer.
uint32_t m_region { 0 };
};
// One LayerIsland may be filled with solid fill, sparse fill, top / bottom fill.
static constexpr const size_t LayerExtrusionRangesStaticSize = 3;
using LayerExtrusionRanges =
#ifdef NDEBUG
// To reduce memory allocation in release mode.
boost::container::small_vector<LayerExtrusionRange, LayerExtrusionRangesStaticSize>;
#else // NDEBUG
// To ease debugging.
std::vector<LayerExtrusionRange>;
#endif // NDEBUG
class LayerRegion
{
public:
@ -110,18 +52,11 @@ public:
// collection of surfaces generated by slicing the original geometry
// divided by type top/bottom/internal
[[nodiscard]] const SurfaceCollection& slices() const { return m_slices; }
[[nodiscard]] const SurfaceCollection& slices() const { /*assert(surfaces_filled);*/ return m_slices; }
bool has_slices() const { return m_slices.empty(); }
// Unspecified fill polygons, used for overhang detection ("ensure vertical wall thickness feature")
// and for re-starting of infills.
[[nodiscard]] const ExPolygons& fill_expolygons() const { return m_fill_expolygons; }
// and their bounding boxes
[[nodiscard]] const BoundingBoxes& fill_expolygons_bboxes() const { return m_fill_expolygons_bboxes; }
// Storage for fill regions produced for a single LayerIsland, of which infill splits into multiple islands.
// Not used for a plain single material print with no infill modifiers.
[[nodiscard]] const ExPolygons& fill_expolygons_composite() const { return m_fill_expolygons_composite; }
// and their bounding boxes
[[nodiscard]] const BoundingBoxes& fill_expolygons_composite_bboxes() const { return m_fill_expolygons_composite_bboxes; }
//// Unspecified fill polygons, used for intersecting when we don't want the infill/perimeter overlap
//// note: if empty, that means there is no overlap, so you don't need to intersect with it.
[[nodiscard]] const ExPolygons& fill_no_overlap_expolygons() const { return m_fill_no_overlap_expolygons; }
@ -129,55 +64,32 @@ public:
// divided by type top/bottom/internal
[[nodiscard]] const SurfaceCollection& fill_surfaces() const { return m_fill_surfaces; }
[[nodiscard]] SurfaceCollection& set_fill_surfaces() { return m_fill_surfaces; }
// Unspecified fill polygons, used for overhang detection ("ensure vertical wall thickness feature")
// and for re-starting of infills.
// computed from islands. use islands if it's easier for you.
[[nodiscard]] const ExPolygons& fill_expolygons() const;
// collection of extrusion paths/loops filling gaps
// These fills are generated by the perimeter generator.
// They are not printed on their own, but they are copied to this->fills during infill generation.
[[nodiscard]] const ExtrusionEntityCollection& thin_fills() const { return m_thin_fills; }
private:
mutable uint64_t m_cache_fill_expolygons_computed = 0;
mutable ExPolygons m_cache_fill_expolygons;
// create my fill_expolygons from all islands that reference me.
ExPolygons _compute_fill_expolygons() const;
public:
// collection of polylines representing the unsupported bridge edges
[[nodiscard]] const Polylines& unsupported_bridge_edges() const { return m_unsupported_bridge_edges; }
// ordered collection of extrusion paths/loops to build all perimeters
// (this collection contains only ExtrusionEntityCollection objects)
[[nodiscard]] const ExtrusionEntityCollection& perimeters() const { return m_perimeters; }
[[nodiscard]] const std::set<LayerRegion *> &perimeters_regions() const { return m_perimeters_regions; }
// collection of expolygons representing the milling path of the first milling cutter
[[nodiscard]] const ExtrusionEntityCollection& millings() const { return m_millings; }
// ordered collection of extrusion paths to fill surfaces
// (this collection contains only ExtrusionEntityCollection objects)
[[nodiscard]] const ExtrusionEntityCollection& fills() const { return m_fills; }
[[nodiscard]] const ExtrusionEntityCollection& ironings() const { return m_ironings; }
// only for Layer & PrintObject
[[nodiscard]] ExtrusionEntityCollection& set_fills() { return m_fills; }
[[nodiscard]] ExtrusionEntityCollection& set_ironings() { return m_ironings; }
void clear();
void clear();
Flow flow(FlowRole role) const;
Flow flow(FlowRole role, double layer_height) const;
coordf_t bridging_height_avg() const;
double bridging_height_avg_mm() const;
Flow bridging_flow(FlowRole role, BridgeType force_type = BridgeType::btNone) const;
void slices_to_fill_surfaces_clipped(coord_t opening_offset);
void prepare_fill_surfaces();
// Produce perimeter extrusions, gap fill extrusions and fill polygons for input slices.
void make_perimeters(
// Input slices for which the perimeters, gap fills and fill expolygons are to be generated.
const SurfaceCollection &slices,
// all regions merged into us for creating perimeters.
// can be used to apply some configurations only on specific areas.
const std::set<LayerRegion*> &regions,
// Ranges of perimeter extrusions and gap fill extrusions per suface, referencing
// newly created extrusions stored at this LayerRegion.
std::vector<std::pair<ExtrusionRange, ExtrusionRange>> &perimeter_and_gapfill_ranges,
// All fill areas produced for all input slices above.
ExPolygons &fill_expolygons,
// Ranges of fill areas above per input slice.
std::vector<ExPolygonRange> &fill_expolygons_ranges);
void make_milling_post_process(const SurfaceCollection& slices);
void process_external_surfaces(const Layer *lower_layer, const Polygons *lower_layer_covered);
void process_external_surfaces_old(const Layer *lower_layer, const Polygons *lower_layer_covered);
double infill_area_threshold() const;
@ -193,24 +105,15 @@ public:
void export_region_slices_to_svg_debug(const char *name) const;
void export_region_fill_surfaces_to_svg_debug(const char *name) const;
// Is there any valid extrusion assigned to this LayerRegion?
bool has_extrusions() const { return !this->perimeters().empty() || !this->fills().empty()
|| !this->ironings().empty() || !this->thin_fills().empty(); }
void simplify_extrusion_entity();
const ExPolygons &get_cached_slices() const { return m_raw_slices; }
const ExPolygons &get_raw_slices() const { return m_raw_slices; }
const ExPolygons &get_raw_bounding_box() const { return m_raw_slices; }
void set_raw_slices(ExPolygons&& raw_slices) { m_raw_slices = std::move(raw_slices); }
protected:
friend class Layer;
friend class PrintObject;
LayerRegion(Layer *layer, const PrintRegion *region) : m_layer(layer), m_region(region) {
//these are sorted in the island by idx, so they shoul never change.
m_perimeters.set_can_sort_reverse(false, false);
m_fills.set_can_sort_reverse(false, false);
m_ironings.set_can_sort_reverse(false, false);
}
LayerRegion(Layer *layer, const PrintRegion *region) : m_layer(layer), m_region(region) {}
~LayerRegion() = default;
private:
@ -232,144 +135,178 @@ private:
public:
// collection of surfaces generated by slicing the original geometry
// divided by type top/bottom/internal
// TODO: separate them per island.
SurfaceCollection m_slices;
ExPolygons m_perimeter_slices;
#if _DEBUG
bool surfaces_filled = false;
#endif
private:
// Unspecified fill polygons, used for overhang detection ("ensure vertical wall thickness feature")
// and for re-starting of infills.
ExPolygons m_fill_expolygons;
// and their bounding boxes
BoundingBoxes m_fill_expolygons_bboxes;
// Storage for fill regions produced for a single LayerIsland, of which infill splits into multiple islands.
// Not used for a plain single material print with no infill modifiers.
ExPolygons m_fill_expolygons_composite;
// and their bounding boxes
BoundingBoxes m_fill_expolygons_composite_bboxes;
// Unspecified fill polygons, used for intersecting when we don't want the infill/perimeter overlap
// note: if empty, that means there is no overlap, so you don't need to intersect with it.
//// Unspecified fill polygons, used for intersecting when we don't want the infill/perimeter overlap
//// note: never empty.
ExPolygons m_fill_no_overlap_expolygons;
// Collection of surfaces for infill generation, created by splitting m_slices by m_fill_expolygons.
SurfaceCollection m_fill_surfaces;
// Collection of extrusion paths/loops filling gaps
// These fills are generated by the perimeter generator.
// They are not printed on their own, but they are copied to this->fills during infill generation.
ExtrusionEntityCollection m_thin_fills;
// collection of polylines representing the unsupported bridge edges
Polylines m_unsupported_bridge_edges;
// ordered collection of extrusion paths/loops to build all perimeters
// (this collection contains only ExtrusionEntityCollection objects)
ExtrusionEntityCollection m_perimeters;
// regions where the perimeters can be.
std::set<LayerRegion *> m_perimeters_regions;
// collection of expolygons representing the milling path of the first milling cutter
ExtrusionEntityCollection m_millings;
// ordered collection of extrusion paths to fill surfaces
// (this collection contains only ExtrusionEntityCollection objects)
ExtrusionEntityCollection m_fills;
ExtrusionEntityCollection m_ironings;
// collection of expolygons representing the bridged areas (thus not
// needing support material)
// Polygons bridged;
};
//// One LayerIsland may be filled with solid fill, sparse fill, top / bottom fill.
//static constexpr const size_t LayerExtrusionRangesStaticSize = 3;
//using LayerExtrusionRanges =
//#ifdef NDEBUG
// // To reduce memory allocation in release mode.
// boost::container::small_vector<LayerExtrusionRange, LayerExtrusionRangesStaticSize>;
//#else // NDEBUG
// // To ease debugging.
// std::vector<LayerExtrusionRange>;
//#endif // NDEBUG
// LayerSlice contains one or more LayerIsland objects,
// each LayerIsland containing a set of perimeter extrusions extruded with one particular PrintRegionConfig parameters
// and one or multiple
struct LayerIsland
// kind of similar as old's LayerIsland
class LayerRegionIsland
{
private:
friend class Layer;
static constexpr const uint32_t fill_region_composite_id = std::numeric_limits<uint32_t>::max();
//// 0-based extruder, -1 => not set yet (any).
//// when the LayerRegionIsland will be sorted, if one has infill & peri extrusion with != extruder,
//// then it will split into two.
uint16_t m_extruder_id = uint16_t(-1);
std::map<ExtrusionRole, ExtrusionEntityCollection> m_extrusion_regions;
// my regions
LayerRegionSetConstPtrs m_regions;
public:
// if true, then can be used by any extruder for wiping.
bool can_be_used_to_wipe = false;
//LayerRegionIsland(const LayerRegionSetConstPtrs &regions) : m_regions(regions) {}
LayerRegionIsland(const LayerRegionSetConstPtrs &regions, uint16_t extruder_id) : m_regions(regions), m_extruder_id(extruder_id) {}
static inline ExtrusionRole PERIMETERS = ExtrusionRole::Perimeter;
static inline ExtrusionRole GAP_FILLS = ExtrusionRole::GapFill;
static inline ExtrusionRole INFILLS = ERM_Infill;
static inline ExtrusionRole IRONINGS = ExtrusionRole::Ironing;
static inline ExtrusionRole MILLS = ExtrusionRole::Milling;
static inline ExtrusionRole SUPPORT = ExtrusionRole::SupportMaterial;
static inline ExtrusionRole SUPPORT_INTERFACE = ExtrusionRole::SupportMaterialInterface;
bool has_extrusion(ExtrusionRole role) const {
auto it = m_extrusion_regions.find(role);
if(it == m_extrusion_regions.end()) return false;
return !it->second.empty();
}
bool has_extrusions() const;
const ExtrusionEntityCollection &extrusion(ExtrusionRole role) const {
assert(has_extrusion(role));
return m_extrusion_regions.at(role);
}
void remove_empty_extrusions();
ExtrusionEntityCollection & mutable_extrusion(ExtrusionRole role) {
return m_extrusion_regions[role];
}
const LayerRegionSetConstPtrs &regions() const { return m_regions; }
void simplify_extrusion_entity(const Layer& layer);
uint16_t extruder_id() const { return m_extruder_id; };
};
using LayerRegionIslandPtr = std::unique_ptr<LayerRegionIsland>;
// kind of similar as old's LayerSlice
class LayerSliceIsland
{
public:
// only filled when Layer's LayerSliceIsland are locked.
// used by supportspotgenerator (badly)
struct Link
{
LayerSliceIsland* to;
float area;
};
std::vector<Link> overlaps_above;
std::vector<Link> overlaps_below;
const ExPolygons &get_perimeter_slices() { return m_perimeter_slices; }
protected:
ExPolygon m_slice;
BoundingBox m_bbox;
// only regions that are relevant for this island
LayerRegionSetConstPtrs m_regions;
// storing unique_ptr because it's easier to have consistent objects while manipulating the vector.
std::vector<LayerRegionIslandPtr> m_extrusions;
// cache, can be accessed via m_regions. Only set after fill_regions.
Layer *m_layer = nullptr;
// Unspecified fill polygons, used for intersecting when we don't want the infill/perimeter overlap
// note: if empty, that means there is no overlap, so you don't need to intersect with it.
ExPolygons m_fill_no_overlap_expolygons;
ExPolygons m_fill_expolygons;
BoundingBoxes m_fill_expolygons_bboxes;
// to get the boundary in avoid_crossing_perimeters. Filled by make_perimeters()
ExPolygons m_perimeter_slices;
public:
// Perimeter extrusions in LayerRegion belonging to this island.
LayerExtrusionRange perimeters;
// Thin fills of the same region as perimeters. Generated by classic perimeter generator, while Arachne puts them into perimeters.
ExtrusionRange thin_fills;
// Infill + gapfill extrusions in LayerRegion belonging to this island.
LayerExtrusionRanges fills;
// pp ironings are created after fills. TODO: should be LayerExtrusionRange like perimeters, or ExtrusionRange like thin_fills? I guess there is only one region inside, right?
LayerExtrusionRanges ironings;
// Region that is to be filled with the fills above (thin fills, regular fills, ironings?).
// Pointing to either LayerRegion::fill_expolygons() or LayerRegion::fill_expolygons_composite()
// based on this->fill_expolygons_composite() flag.
ExPolygonRange fill_expolygons;
// Index of LayerRegion with LayerRegion::fill_expolygons() if not fill_expolygons_composite().
uint32_t fill_region_id;
bool fill_expolygons_composite() const { return this->fill_region_id == fill_region_composite_id; }
// Centroid of this island used for path planning.
// Point centroid;
bool has_extrusions() const { return ! this->perimeters.empty() || ! this->fills.empty(); }
LayerSliceIsland(const ExPolygon &slice);
void fill_regions(Layer& layer);
void add_fill_range(const LayerExtrusionRange &new_fill_range) {
// Compress ranges.
if (! this->fills.empty() && this->fills.back().region() == new_fill_range.region() && *this->fills.back().end() == *new_fill_range.begin())
this->fills.back() = { new_fill_range.region(), { *this->fills.back().begin(), *new_fill_range.end() } };
else
this->fills.push_back(new_fill_range);
}
void add_ironing_range(const LayerExtrusionRange &new_ironing_range) {
// Compress ranges.
if (!this->ironings.empty() && this->ironings.back().region() == new_ironing_range.region() &&
*this->ironings.back().end() == *new_ironing_range.begin())
this->ironings.back() = {new_ironing_range.region(), {*this->ironings.back().begin(), *new_ironing_range.end()}};
else
this->ironings.push_back(new_ironing_range);
}
ExPolygon &get_mutable_slice() { return m_slice; }
const ExPolygon &get_slice() const { return m_slice; }
const BoundingBox &get_bounding_box() const { return m_bbox; }
const LayerRegionSetConstPtrs &regions() const { return m_regions; }
const std::vector<LayerRegionIslandPtr> &regions_islands() const { return m_extrusions; }
std::vector<LayerRegionIslandPtr> &regions_islands() { return m_extrusions; }
const Layer *layer() const { return m_layer; }
LayerRegionIsland& get_or_add_region_island(const LayerRegionSetConstPtrs &regions, uint16_t extruder_id = uint16_t(-1));
LayerRegionIsland& add_new_region_island(const LayerRegionSetConstPtrs &regions, uint16_t extruder_id = uint16_t(-1));
// Unspecified fill polygons, used for overhang detection ("ensure vertical wall thickness feature")
// and for re-starting of infills.
[[nodiscard]] const ExPolygons& fill_expolygons() const { return m_fill_expolygons; }
// and their bounding boxes
[[nodiscard]] const BoundingBoxes& fill_expolygons_bboxes() const { return m_fill_expolygons_bboxes; }
// return true if this expolygon is (inside) this island.
// TODO remove when the fill surfaces will be linked to their islands (maybe moved here)
bool is_expolygons_from_region(const ExPolygon &expolygon) const;
// Is there any valid extrusion assigned to one LayerRegionIslandPtr?
bool has_extrusions() const;
//// Unspecified fill polygons, used for intersecting when we don't want the infill/perimeter overlap
//// note: if empty, that means there is no overlap, so you don't need to intersect with it.
[[nodiscard]] const ExPolygons& fill_no_overlap_expolygons() const { return m_fill_no_overlap_expolygons; }
void make_perimeters(LayerRegionIsland &region_island);
};
using LayerSliceIslandPtr = std::unique_ptr<LayerSliceIsland>;
static constexpr const size_t LayerIslandsStaticSize = 1;
using LayerIslands =
#ifdef NDEBUG
// To reduce memory allocation in release mode.
boost::container::small_vector<LayerIsland, LayerIslandsStaticSize>;
#else // NDEBUG
// To ease debugging.
std::vector<LayerIsland>;
#endif // NDEBUG
// One connected island of a layer. LayerSlice may consist of one or more LayerIslands.
struct LayerSlice
{
struct Link {
int32_t slice_idx;
float area;
};
static constexpr const size_t LinksStaticSize = 4;
using Links =
#ifdef NDEBUG
// To reduce memory allocation in release mode.
boost::container::small_vector<Link, LinksStaticSize>;
#else // NDEBUG
// To ease debugging.
std::vector<Link>;
#endif // NDEBUG
BoundingBox bbox;
Links overlaps_above;
Links overlaps_below;
// One island for each region or region set that generates its own perimeters.
// For multi-material prints or prints with regions of different perimeter parameters,
// a LayerSlice may be split into multiple LayerIslands.
// For most prints there will be just one island.
LayerIslands islands;
bool has_extrusions() const { for (const LayerIsland &island : islands) if (island.has_extrusions()) return true; return false; }
};
using LayerSlices = std::vector<LayerSlice>;
//static constexpr const size_t LayerIslandsStaticSize = 1;
//using LayerIslands =
//#ifdef NDEBUG
// // To reduce memory allocation in release mode.
// boost::container::small_vector<LayerIsland, LayerIslandsStaticSize>;
//#else // NDEBUG
// // To ease debugging.
// std::vector<LayerIsland>;
//#endif // NDEBUG
class Layer
{
coord_t m_height; // layer height
coord_t m_print_z; // Z used for printing
public:
// Sequential index of this layer in PrintObject::m_layers, offsetted by the number of raft layers.
size_t id() const { return m_id; }
@ -380,29 +317,43 @@ public:
Layer *upper_layer;
Layer *lower_layer;
// bool slicing_errors;
double slice_z; // Z used for slicing in unscaled coordinates
double print_z; // Z used for printing in unscaled coordinates
double height; // layer height in unscaled coordinates
double bottom_z() const { return this->print_z - this->height; }
// heights
static coord_t scale_to_layer_coord(double z);
double slice_z; // Z used for slicing, in unscaled coordinates
coord_t scaled_print_z() const { assert(scale_to_layer_coord(unscaled(m_print_z)) == m_print_z); return m_print_z; }
double unscaled_print_z() const { assert(scale_to_layer_coord(unscaled(m_print_z)) == m_print_z); return unscaled(m_print_z); }
coord_t scaled_height() const { return m_height; }
double unscaled_height() const { return unscaled(m_height); }
coord_t scaled_bottom_z() const { return this->m_print_z - this->m_height; }
//Extrusions estimated to be seriously malformed, estimated during "Estimating curled extrusions" step. These lines should be avoided during fast travels.
//TODO: put in island
CurledLines curled_lines;
protected:
// geometric island.
// Collection of expolygons generated by slicing the possibly multiple meshes of the source geometry
// (with possibly differing extruder ID and slicing parameters) and merged.
// For the first layer, if the Elephant foot compensation is applied, this lslice is uncompensated, therefore
// it includes the Elephant foot effect, thus it corresponds to the shape of the printed 1st layer.
// These lslices aka islands are chained by the shortest traverse distance and this traversal
// order will be applied by the G-code generator to the extrusions fitting into these lslices.
// These lslices are also used to detect overhangs and overlaps between successive layers, therefore it is important
// that the 1st lslice is not compensated by the Elephant foot compensation algorithm.
protected:
ExPolygons m_lslices;
// that the lslice is not compensated by the Elephant foot compensation algorithm.
ExPolygons m_lslices; // now in LayerSliceIsland, here is just a cache for quicker lslices()
// in unique_ptr to be sure the address doesn't change when updating the vector.
std::vector<LayerSliceIslandPtr> m_islands;
bool m_islands_locked = false;
public:
// shortcut to get slices stored in islands
const ExPolygons & lslices() const { return m_lslices; }
ExPolygons & set_lslices() { return m_lslices; }
std::vector<size_t> lslice_indices_sorted_by_print_order;
LayerSlices lslices_ex;
void set_islands(ExPolygons && new_islands);
const std::vector<LayerSliceIslandPtr> &islands() const { return m_islands; }
LayerSliceIsland& get_mutable_island(size_t idx) { return *m_islands[idx]; }
// to be called after LayerRegion's m_slices are created (but still not separated)
// create surfaces in layerregion, and fill regionislands.
void add_regions_to_islands();
size_t region_count() const { return m_regions.size(); }
const LayerRegion* get_region(size_t idx) const { return m_regions[idx]; }
@ -414,12 +365,8 @@ public:
void make_slices();
// After creating the slices on all layers, chain the islands overlapping in Z.
static void build_up_down_graph(Layer &below, Layer &above);
// Backup and restore raw sliced regions if needed.
//FIXME Review whether not to simplify the code by keeping the raw_slices all the time.
void backup_untyped_slices();
// erase LayerRegion's 'slices' surfaces and recreate one from raw
void restore_untyped_slices();
// To improve robustness of detect_surfaces_type() when reslicing (working with typed slices), see GH issue #7442.
void restore_untyped_slices_no_extra_perimeters();
// Slices merged into islands, to be used by the elephant foot compensation to trim the individual surfaces with the shrunk merged slices.
ExPolygons merged(coordf_t offset_scaled = 0) const;
void make_perimeters();
@ -427,10 +374,24 @@ public:
void make_fills(FillAdaptive::Octree *adaptive_fill_octree,
FillAdaptive::Octree *support_fill_octree,
FillLightning::Generator *lightning_generator);
void make_ironing();
Polylines generate_sparse_infill_polylines_for_anchoring(FillAdaptive::Octree *adaptive_fill_octree,
FillAdaptive::Octree *support_fill_octree,
FillLightning::Generator* lightning_generator) const;
void make_ironing();
protected:
void _make_fills(LayerSliceIsland &island,
FillAdaptive::Octree *adaptive_fill_octree,
FillAdaptive::Octree *support_fill_octree,
FillLightning::Generator *lightning_generator);
void _make_ironing(LayerSliceIsland &island);
Polylines _generate_sparse_infill_polylines_for_anchoring(const LayerSliceIsland &island,
FillAdaptive::Octree *adaptive_fill_octree,
FillAdaptive::Octree *support_fill_octree,
FillLightning::Generator* lightning_generator) const;
public:
void export_region_slices_to_svg(const char *path) const;
void export_region_fill_surfaces_to_svg(const char *path) const;
@ -438,42 +399,34 @@ public:
void export_region_slices_to_svg_debug(const char *name) const;
void export_region_fill_surfaces_to_svg_debug(const char *name) const;
// Is there any valid extrusion assigned to this LayerRegion?
virtual bool has_extrusions() const { for (auto layerm : m_regions) if (layerm->has_extrusions()) return true; return false; }
// virtual bool has_extrusions() const { for (const LayerSlice &lslice : lslices_ex) if (lslice.has_extrusions()) return true; return false; }
// Is there any valid extrusion assigned to any island-region?
bool has_extrusions() const;
void simplify_extrusion_path() {
for (LayerSliceIslandPtr &island_ptr : m_islands)
for (LayerRegionIslandPtr &regisland : island_ptr->regions_islands())
regisland->simplify_extrusion_entity(*this);
}
void simplify_extrusion_path() { for (auto layerm : m_regions) layerm->simplify_extrusion_entity(); }
protected:
friend class PrintObject;
friend std::vector<Layer*> new_layers(PrintObject*, const std::vector<coordf_t>&);
friend std::string fix_slicing_errors(LayerPtrs&, const std::function<void()>&);
Layer(size_t id, PrintObject *object, coordf_t height, coordf_t print_z, coordf_t slice_z) :
Layer(size_t id, PrintObject *object, coord_t height, coord_t print_z, double slice_z, bool scaledok) :
upper_layer(nullptr), lower_layer(nullptr),
//slicing_errors(false),
slice_z(slice_z), print_z(print_z), height(height),
m_id(id), m_object(object) {}
slice_z(slice_z), m_print_z(print_z), m_height(height),
m_id(id), m_object(object) {
assert(print_z > 100);
assert(height > 100);
assert(scale_to_layer_coord(unscaled(print_z)) == print_z);
}
virtual ~Layer();
// Clear fill extrusions, remove them from layer islands.
void clear_fills();
private:
void sort_perimeters_into_islands(
// Slices for which perimeters and fill_expolygons were just created.
// The slices may have been created by merging multiple source slices with the same perimeter parameters.
const SurfaceCollection &slices,
// Region where the perimeters, gap fills and fill expolygons are stored.
const uint32_t region_id,
// Perimeters and gap fills produced by the perimeter generator for the slices,
// sorted by the source slices.
const std::vector<std::pair<ExtrusionRange, ExtrusionRange>> &perimeter_and_gapfill_ranges,
// Fill expolygons produced for all source slices above.
ExPolygons &&fill_expolygons,
// Fill expolygon ranges sorted by the source slices.
const std::vector<ExPolygonRange> &fill_expolygons_ranges,
// If the current layer consists of multiple regions, then the fill_expolygons above are split by the source LayerRegion surfaces.
const std::vector<uint32_t> &layer_region_ids);
// Sequential index of layer, 0-based, offsetted by number of raft layers.
size_t m_id;
PrintObject *m_object;
@ -483,36 +436,27 @@ private:
class SupportLayer : public Layer
{
public:
// Polygons covered by the supports: base, interface and contact areas.
// Used to suppress retraction if moving for a support extrusion over these support_islands.
ExPolygons support_islands;
// Slightly inflated bounding boxes of the above, for faster intersection query.
BoundingBoxes support_islands_bboxes;
// Extrusion paths for the support base and for the support interface and contacts.
ExtrusionEntityCollection support_fills;
// Is there any valid extrusion assigned to this LayerRegion?
virtual bool has_extrusions() const { return ! support_fills.empty(); }
// Zero based index of an interface layer, used for alternating direction of interface / contact layers.
size_t interface_id() const { return m_interface_id; }
ExtrusionRole role() const;
void simplify_support_extrusion_path();
protected:
friend class PrintObject;
// The constructor has been made public to be able to insert additional support layers for the skirt or a wipe tower
// between the raft and the object first layer.
SupportLayer(size_t id, size_t interface_id, PrintObject *object, coordf_t height, coordf_t print_z, coordf_t slice_z) :
Layer(id, object, height, print_z, slice_z), m_interface_id(interface_id) {}
SupportLayer(size_t id, size_t interface_id, PrintObject *object, coord_t height, coord_t print_z, double slice_z, bool scaledok) :
Layer(id, object, height, print_z, slice_z, scaledok), m_interface_id(interface_id) {}
virtual ~SupportLayer() = default;
size_t m_interface_id;
};
template<typename LayerContainer>
inline std::vector<float> zs_from_layers(const LayerContainer &layers)
inline std::vector<float> slice_z_from_layers(const LayerContainer &layers)
{
std::vector<float> zs;
zs.reserve(layers.size());

View file

@ -1,7 +1,8 @@
///|/ Copyright (c) superslicer 2019 - 2025 Durand Rémi @supermerill
///|/ Copyright (c) Prusa Research 2016 - 2023 Vojtěch Bubník @bubnikv, Pavel Mikuš @Godrak, Lukáš Matěna @lukasmatena, Lukáš Hejl @hejllukas
///|/ Copyright (c) Slic3r 2014 - 2016 Alessandro Ranellucci @alranel
///|/
///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher
///|/ SuperSlicer, PrusaSlicer is released under the terms of the AGPLv3 or higher
///|/
#include "ExPolygon.hpp"
#include "Flow.hpp"
@ -26,23 +27,13 @@
namespace Slic3r {
void LayerRegion::clear() {
this->m_perimeters.clear();
this->m_millings.clear();
this->m_unsupported_bridge_edges.clear();
this->m_fill_surfaces.clear();
this->m_fills.clear();
this->m_ironings.clear();
this->m_thin_fills.clear();
this->m_fill_expolygons.clear();
this->m_fill_expolygons_bboxes.clear();
this->m_fill_expolygons_composite.clear();
this->m_fill_expolygons_composite_bboxes.clear();
this->m_fill_no_overlap_expolygons.clear();
}
Flow LayerRegion::flow(FlowRole role) const
{
return this->flow(role, m_layer->height);
return this->flow(role, (float)m_layer->unscaled_height());
}
Flow LayerRegion::flow(FlowRole role, double layer_height) const
@ -51,14 +42,14 @@ Flow LayerRegion::flow(FlowRole role, double layer_height) const
}
// Average diameter of nozzles participating on extruding this region.
coordf_t LayerRegion::bridging_height_avg() const
double LayerRegion::bridging_height_avg_mm() const
{
const PrintRegionConfig& region_config = this->region().config();
if (region_config.bridge_type == BridgeType::btFromNozzle) {
const PrintConfig& print_config = this->layer()->object()->print()->config();
return region().nozzle_dmr_avg(print_config) * sqrt(region_config.bridge_flow_ratio.get_abs_value(1));
} else if (region_config.bridge_type == BridgeType::btFromHeight) {
return this->layer()->height;
return this->layer()->unscaled_height();
} else if (region_config.bridge_type == BridgeType::btFromFlow) {
return this->bridging_flow(FlowRole::frInfill).height();
}
@ -81,7 +72,7 @@ Flow LayerRegion::bridging_flow(FlowRole role, BridgeType force_type) const
Flow reference_flow = flow(role);
diameter = sqrt(4 * reference_flow.mm3_per_mm() / PI);
} else if (bridge_type == BridgeType::btFromHeight) {
diameter = m_layer->height;
diameter = m_layer->unscaled_height();
} else /*if (bridge_type == BridgeType::btFromNozzle)*/ {
// The good Slic3r way: Use rounded extrusions.
// Get the configured nozzle_diameter for the extruder associated to the flow role requested.
@ -101,6 +92,42 @@ Flow LayerRegion::bridging_flow(FlowRole role, BridgeType force_type) const
}*/
}
const ExPolygons& LayerRegion::fill_expolygons() const {
uint64_t hash_islands = 0;
int shift = 0;
for (const LayerSliceIslandPtr &layer_island_ptr : this->layer()->islands()) {
if (layer_island_ptr->regions().find(this) != layer_island_ptr->regions().end()) {
for (const ExPolygon &expoly : layer_island_ptr->fill_expolygons()) {
hash_islands ^= (uint64_t(&expoly) << shift);
shift++;
}
}
shift++;
}
if (m_cache_fill_expolygons_computed == 0 || m_cache_fill_expolygons_computed != hash_islands) {
m_cache_fill_expolygons_computed = hash_islands;
m_cache_fill_expolygons = _compute_fill_expolygons();
}
return m_cache_fill_expolygons;
}
ExPolygons LayerRegion::_compute_fill_expolygons() const {
ExPolygons my_fill_expolygons;
size_t nb_add = 0;
for (const LayerSliceIslandPtr &layer_island_ptr : this->layer()->islands()) {
if (auto &regions = layer_island_ptr->regions(); regions.find(this) != regions.end()) {
append(my_fill_expolygons, layer_island_ptr->fill_expolygons());
nb_add++;
}
}
if (nb_add > 1) {
my_fill_expolygons = union_safety_offset_ex(my_fill_expolygons);
my_fill_expolygons = intersection_ex(my_fill_expolygons, this->get_raw_slices());
}
ensure_valid(my_fill_expolygons);
return my_fill_expolygons;
}
// Fill in layerm->m_fill_surfaces by trimming the layerm->slices by layerm->fill_expolygons.
void LayerRegion::slices_to_fill_surfaces_clipped(coord_t opening_offset)
{
@ -113,162 +140,30 @@ void LayerRegion::slices_to_fill_surfaces_clipped(coord_t opening_offset)
// Trim surfaces by the fill_boundaries.
m_fill_surfaces.surfaces.clear();
for (auto const& [srf_type, expoly] : polygons_by_surface) {
if (!expoly.empty())
for (ExPolygon& expoly_to_test : ensure_valid(intersection_ex(expoly, this->fill_expolygons()))) {
ExPolygons expolys_to_test = expoly_to_test.simplify(std::max(SCALED_EPSILON, scale_t(this->layer()->object()->print()->config().resolution.value)));
if (!expoly.empty()) {
for (ExPolygon &expoly_to_test : ensure_valid(intersection_ex(expoly, fill_expolygons()))) {
ExPolygons expolys_to_test = expoly_to_test.simplify(
std::max(SCALED_EPSILON, scale_t(this->layer()->object()->print()->config().resolution.value)));
if (!opening_ex(expolys_to_test, opening_offset).empty()) {
this->m_fill_surfaces.append({ expoly_to_test }, srf_type);
this->m_fill_surfaces.append({expoly_to_test}, srf_type);
}
}
}
}
// Produce perimeter extrusions, gap fill extrusions and fill polygons for input slices.
void LayerRegion::make_perimeters(
// Input slices for which the perimeters, gap fills and fill expolygons are to be generated.
const SurfaceCollection &slices,
// can be used to apply some configurations only on specific areas.
const std::set<LayerRegion*> &lregions,
// Ranges of perimeter extrusions and gap fill extrusions per suface, referencing
// newly created extrusions stored at this LayerRegion.
std::vector<std::pair<ExtrusionRange, ExtrusionRange>> &perimeter_and_gapfill_ranges,
// All fill areas produced for all input slices above.
ExPolygons &fill_expolygons,
// Ranges of fill areas above per input slice.
std::vector<ExPolygonRange> &fill_expolygons_ranges)
{
this->m_perimeters.clear();
this->m_thin_fills.clear();
this->m_perimeters_regions = lregions;
assert(this->m_perimeters_regions.empty() || this->m_perimeters_regions.find(this) != this->m_perimeters_regions.end());
perimeter_and_gapfill_ranges.reserve(perimeter_and_gapfill_ranges.size() + slices.size());
// There may be more expolygons produced per slice, thus this reserve is conservative.
fill_expolygons.reserve(fill_expolygons.size() + slices.size());
fill_expolygons_ranges.reserve(fill_expolygons_ranges.size() + slices.size());
const PrintConfig &print_config = this->layer()->object()->print()->config();
const PrintRegionConfig &region_config = this->region().config();
// This needs to be in sync with PrintObject::_slice() slicing_mode_normal_below_layer!
bool spiral_vase = print_config.spiral_vase &&
//FIXME account for raft layers.
(this->layer()->id() >= size_t(region_config.bottom_solid_layers.value) &&
this->layer()->print_z >= region_config.bottom_solid_min_thickness - EPSILON);
Flow bridging_flow = (region_config.overhangs.get_bool() && region_config.overhangs_flow_ratio.is_enabled()) ?
this->bridging_flow(frExternalPerimeter) :
this->flow(frPerimeter);
//this is a factory, the content will be copied into the PerimeterGenerator
PerimeterGenerator::Parameters params(
this->layer(),
this->flow(frPerimeter),
this->flow(frExternalPerimeter),
bridging_flow,
this->flow(frSolidInfill),
region_config,
this->layer()->object()->config(),
print_config,
spiral_vase,
(region_config.perimeter_generator.value == PerimeterGeneratorType::Arachne) //use_arachne
);
// perimeter bonding set.
if (params.perimeter_flow.spacing_ratio() == 1
&& params.ext_perimeter_flow.spacing_ratio() == 1
&& params.config.external_perimeters_first
&& params.object_config.perimeter_bonding.value > 0) {
params.infill_gap = (1 - params.object_config.perimeter_bonding.get_abs_value(1)) * params.get_ext_perimeter_spacing();
params.ext_perimeter_spacing2 -= params.infill_gap;
}
const ExPolygons *lower_slices = this->layer()->lower_layer ? &this->layer()->lower_layer->lslices() : nullptr;
const ExPolygons *upper_slices = this->layer()->upper_layer ? &this->layer()->upper_layer->lslices() : nullptr;
std::vector<BoundingBox> lower_bbox;
std::vector<BoundingBox> upper_bbox;
if (lower_slices != nullptr) {
for (const ExPolygon &lowerp : *lower_slices) {
lower_bbox.emplace_back(lowerp.contour.points);
}
}
if (upper_slices != nullptr) {
for (const ExPolygon &upperp : *upper_slices) {
upper_bbox.emplace_back(upperp.contour.points);
}
}
assert((lower_slices == nullptr && lower_bbox.empty()) || (lower_slices->size() == lower_bbox.size()));
assert((upper_slices == nullptr && upper_bbox.empty()) || (upper_slices->size() == upper_bbox.size()));
for (const Surface &surface : slices) {
size_t perimeters_begin = m_perimeters.size();
size_t gap_fills_begin = m_thin_fills.size();
size_t fill_expolygons_begin = fill_expolygons.size();
params.region_setting.segregate_regions(surface.expolygon, this->m_perimeters_regions);
PerimeterGenerator::PerimeterGenerator g{params};
g.throw_if_canceled = [this]() { this->layer()->object()->print()->throw_if_canceled(); };
// only send lower & upper slcies that are overlapping the surfaces bb
BoundingBox surface_bbox(surface.expolygon.contour.points);
ExPolygons lower_slices_srf;
for (size_t i = 0; i < lower_bbox.size(); ++i) {
if (lower_bbox[i].overlap(surface_bbox)) {
lower_slices_srf.push_back((*lower_slices)[i]);
}
}
ExPolygons upper_slices_srf;
for (size_t i = 0; i < upper_bbox.size(); ++i) {
if (upper_bbox[i].overlap(surface_bbox)) {
upper_slices_srf.push_back((*upper_slices)[i]);
}
}
g.process(
// input:
surface, &lower_slices_srf, slices, &upper_slices_srf,
// output:
// Loops with the external thin walls
&m_perimeters,
// Gaps without the thin walls
&m_thin_fills,
// Infills without the gap fills
fill_expolygons,
// mask for "no overlap" area
m_fill_no_overlap_expolygons
);
for(auto *peri : this->m_perimeters.entities()) assert(!peri->empty());
perimeter_and_gapfill_ranges.emplace_back(
ExtrusionRange{ uint32_t(perimeters_begin), uint32_t(m_perimeters.size()) },
ExtrusionRange{ uint32_t(gap_fills_begin), uint32_t(m_thin_fills.size()) });
fill_expolygons_ranges.emplace_back(ExtrusionRange{ uint32_t(fill_expolygons_begin), uint32_t(fill_expolygons.size()) });
append(m_perimeter_slices, g.perimeter_boundary);
}
m_perimeter_slices = union_ex(m_perimeter_slices);
}
void LayerRegion::make_milling_post_process(const SurfaceCollection& slices) {
MillingPostProcess mill(// input:
&slices,
(this->layer()->lower_layer != nullptr) ? &this->layer()->lower_layer->lslices() : nullptr,
this->region().config(),
this->layer()->object()->config(),
this->layer()->object()->print()->config()
);
m_millings = mill.process(this->layer());
}
#if 1
// Extract surfaces of given type from surfaces, extract fill (layer) thickness of one of the surfaces.
static ExPolygons fill_surfaces_extract_expolygons(Surfaces &surfaces, std::initializer_list<SurfaceType> surface_types, double &thickness)
static ExPolygons fill_surfaces_extract_expolygons(Surfaces &surfaces, std::initializer_list<SurfaceType> surface_types, coord_t &thickness)
{
assert(!surfaces.empty());
size_t cnt = 0;
for (const Surface &surface : surfaces)
if (std::find(surface_types.begin(), surface_types.end(), surface.surface_type) != surface_types.end()) {
++cnt;
thickness = surface.thickness;
assert(surface.scaled_thickness() != 0);
thickness = surface.scaled_thickness();
}
if (cnt == 0)
return {};
@ -296,7 +191,7 @@ Surfaces expand_bridges_detect_orientations(
{
using namespace Slic3r::Algorithm;
double thickness;
coord_t thickness;
ExPolygons bridges_ex = fill_surfaces_extract_expolygons(surfaces, {stPosBottom | stDensSolid | stModBridge}, thickness);
if (bridges_ex.empty())
return {};
@ -487,7 +382,7 @@ static Surfaces expand_merge_surfaces(
{
using namespace Slic3r::Algorithm;
double thickness;
coord_t thickness;
ExPolygons src = fill_surfaces_extract_expolygons(surfaces, {surface_type}, thickness);
if (src.empty())
return {};
@ -605,9 +500,10 @@ void LayerRegion::process_external_surfaces(const Layer *lower_layer, const Poly
const coord_t scaled_resolution = std::max(SCALED_EPSILON, scale_t(this->layer()->object()->print()->config().resolution.value));
// Expand the top / bottom / bridge surfaces into the shell thickness solid infills.
double layer_thickness;
ExPolygons shells = union_ex(fill_surfaces_extract_expolygons(m_fill_surfaces.surfaces, { stPosInternal | stDensSolid }, layer_thickness));
ExPolygons sparse = union_ex(fill_surfaces_extract_expolygons(m_fill_surfaces.surfaces, { stPosInternal | stDensSparse }, layer_thickness));
coord_t layer_solid_thickness = 0;
coord_t layer_sparse_thickness = 0;
ExPolygons shells = union_ex(fill_surfaces_extract_expolygons(m_fill_surfaces.surfaces, { stPosInternal | stDensSolid }, layer_solid_thickness));
ExPolygons sparse = union_ex(fill_surfaces_extract_expolygons(m_fill_surfaces.surfaces, { stPosInternal | stDensSparse }, layer_sparse_thickness));
ExPolygons init_shells = shells;
ExPolygons init_sparse = sparse;
#ifdef _DEBUG
@ -626,7 +522,7 @@ void LayerRegion::process_external_surfaces(const Layer *lower_layer, const Poly
SurfaceCollection bridges;
const auto expansion_params_into_sparse_infill = RegionExpansionParameters::build(expansion_min, expansion_step, max_nr_expansion_steps);
{
BOOST_LOG_TRIVIAL(trace) << "Processing external surface, detecting bridges. layer" << this->layer()->print_z;
BOOST_LOG_TRIVIAL(trace) << "Processing external surface, detecting bridges. layer" << this->layer()->unscaled_print_z();
const double custom_angle = this->region().config().bridge_angle.value;
const auto expansion_params_into_solid_infill = RegionExpansionParameters::build(expansion_bottom_bridge, expansion_step, max_nr_expansion_steps);
if (this->region().config().bridge_angle.is_enabled()) {
@ -677,17 +573,27 @@ void LayerRegion::process_external_surfaces(const Layer *lower_layer, const Poly
}
#endif
reserve_more(m_fill_surfaces.surfaces, shells.size() + sparse.size() + bridges.size() + bottoms.size() + tops.size());
{
if (!shells.empty()) {
Surface solid_templ(stPosInternal | stDensSolid, {});
solid_templ.thickness = layer_thickness;
assert(layer_solid_thickness == -1); // should be >0 but it's set on infill, well after here, we do that for nothing.
if (layer_solid_thickness > 0) {
solid_templ.set_scaled_thickness(layer_solid_thickness);
}
ensure_valid(shells/*, scaled_resolution*/);
m_fill_surfaces.append(std::move(shells), solid_templ);
} else {
//assert(layer_solid_thickness == 0);
}
{
if (!sparse.empty()) {
Surface sparse_templ(stPosInternal | stDensSparse, {});
sparse_templ.thickness = layer_thickness;
assert(layer_sparse_thickness -1); // should be >0 but it's set on infill, well after here, we do that for nothing.
if (layer_sparse_thickness > 0) {
sparse_templ.set_scaled_thickness(layer_sparse_thickness);
}
ensure_valid(sparse/*, scaled_resolution*/);
m_fill_surfaces.append(std::move(sparse), sparse_templ);
} else {
// assert(layer_sparse_thickness == 0);
}
for(auto&srf : bridges.surfaces) srf.expolygon.assert_valid();
for(auto&srf : bottoms) srf.expolygon.assert_valid();
@ -1071,7 +977,7 @@ void LayerRegion::process_external_surfaces_old(const Layer *lower_layer, const
// 3) Merge the groups with the same group id, detect bridges.
{
BOOST_LOG_TRIVIAL(trace) << "Processing external surface, detecting bridges. layer" << this->layer()->print_z << ", bridge groups: " << n_groups;
BOOST_LOG_TRIVIAL(trace) << "Processing external surface, detecting bridges. layer" << this->layer()->unscaled_print_z() << ", bridge groups: " << n_groups;
for (size_t group_id = 0; group_id < n_groups; ++ group_id) {
size_t n_bridges_merged = 0;
size_t idx_last = (size_t)-1;
@ -1086,12 +992,12 @@ void LayerRegion::process_external_surfaces_old(const Layer *lower_layer, const
continue;
// Collect the initial ungrown regions and the grown polygons.
ExPolygons initial;
Polygons grown;
ExPolygons grown;
for (size_t i = 0; i < bridges.size(); ++ i) {
if (bridge_group[i] != group_id)
continue;
initial.push_back(std::move(bridges[i].expolygon));
polygons_append(grown, bridges_grown[i]);
append(grown, union_ex(bridges_grown[i]));
}
// detect bridge direction before merging grown surfaces otherwise adjacent bridges
// would get merged into a single one while they need different directions
@ -1161,52 +1067,55 @@ void LayerRegion::process_external_surfaces_old(const Layer *lower_layer, const
const coord_t scaled_resolution = std::max(SCALED_EPSILON, scale_t(this->layer()->object()->print()->config().resolution.value));
{
// Intersect the grown surfaces with the actual fill boundaries.
Polygons bottom_polygons = to_polygons(bottom);
ExPolygons bottom_expolygons = to_expolygons(bottom);
// Merge top and bottom in a single collection.
surfaces_append(top, std::move(bottom));
for (size_t i = 0; i < top.size(); ++ i) {
Surface &s1 = top[i];
if (s1.empty())
continue;
Polygons polys;
polygons_append(polys, to_polygons(std::move(s1)));
ExPolygons expolys;
expolys.push_back(std::move(s1.expolygon));
for (size_t j = i + 1; j < top.size(); ++ j) {
Surface &s2 = top[j];
if (! s2.empty() && surfaces_could_merge(s1, s2)) {
polygons_append(polys, to_polygons(std::move(s2)));
//polygons_append(polys, to_polygons(std::move(s2)));
expolys.push_back(std::move(s2.expolygon));
s2.clear();
}
}
if (s1.has_pos_top()) {
// Trim the top surfaces by the bottom surfaces. This gives the priority to the bottom surfaces.
polys = diff(polys, bottom_polygons);
expolys = diff_ex(expolys, bottom_expolygons);
}
surfaces_append(
new_surfaces,
// Don't use a safety offset as fill_boundaries were already united using the safety offset.
ensure_valid(intersection_ex(polys, fill_boundaries)/*, scaled_resolution*/),
ensure_valid(intersection_ex(expolys, fill_boundaries)/*, scaled_resolution*/),
s1);
//s1.clear();
}
}
// Subtract the new top surfaces from the other non-top surfaces and re-add them.
Polygons new_polygons = to_polygons(new_surfaces);
ExPolygons new_expolygons = to_expolygons(new_surfaces);
for (size_t i = 0; i < internal.size(); ++ i) {
Surface &s1 = internal[i];
if (s1.empty())
continue;
Polygons polys;
polygons_append(polys, to_polygons(std::move(s1)));
ExPolygons expolys;
expolys.push_back(std::move(s1.expolygon));
for (size_t j = i + 1; j < internal.size(); ++ j) {
Surface &s2 = internal[j];
if (! s2.empty() && surfaces_could_merge(s1, s2)) {
polygons_append(polys, to_polygons(std::move(s2)));
expolys.push_back(std::move(s2.expolygon));
s2.clear();
}
}
ExPolygons new_expolys = diff_ex(polys, new_polygons);
polygons_append(new_polygons, to_polygons(new_expolys));
ExPolygons new_expolys = diff_ex(expolys, new_expolygons);
new_expolygons = union_ex(new_expolygons, new_expolys);
surfaces_append(new_surfaces, ensure_valid(std::move(new_expolys)/*, scaled_resolution*/), s1);
//s1.clear();
}
set_fill_surfaces().surfaces = std::move(new_surfaces);
@ -1399,33 +1308,5 @@ void LayerRegion::export_region_fill_surfaces_to_svg_debug(const char *name) con
this->export_region_fill_surfaces_to_svg(debug_out_path("LayerRegion-fill_surfaces-%s-%d.svg", name, idx ++).c_str());
}
void LayerRegion::simplify_extrusion_entity()
{
const PrintConfig& print_config = this->layer()->object()->print()->config();
const bool spiral_mode = print_config.spiral_vase;
ArcFittingType enable_arc_fitting = print_config.arc_fitting.value;
if (spiral_mode)
enable_arc_fitting = ArcFittingType::Disabled;
coordf_t scaled_resolution = scale_d(print_config.resolution.value);
if (enable_arc_fitting != ArcFittingType::Disabled) {
scaled_resolution = scale_d(print_config.arc_fitting_resolution.get_abs_value(std::max(EPSILON, unscaled(scaled_resolution))));
}
if (scaled_resolution == 0) scaled_resolution = enable_arc_fitting != ArcFittingType::Disabled ? SCALED_EPSILON * 2 : SCALED_EPSILON;
scaled_resolution = std::max(double(SCALED_EPSILON), scaled_resolution);
//Ligne 652: SimplifyVisitor(coordf_t scaled_resolution, ArcFittingType use_arc_fitting, const ConfigOptionFloatOrPercent *arc_fitting_tolearance)
//call simplify for all paths
Slic3r::SimplifyVisitor visitor{scaled_resolution, enable_arc_fitting,
print_config.arc_fitting_ignore_holes,
&print_config.arc_fitting_tolerance,
enable_arc_fitting != ArcFittingType::Disabled ? SCALED_EPSILON * 2 :
SCALED_EPSILON};
this->m_perimeters.visit(visitor);
this->m_fills.visit(visitor);
this->m_ironings.visit(visitor);
this->m_millings.visit(visitor);
}
}

View file

@ -50,7 +50,7 @@ bool Line::intersection_infinite(const Line &other, Point* point) const
return true;
}
coordf_t Line::perp_distance_to(const Point &point) const
distf_t Line::perp_distance_to(const Point &point) const
{
const Line &line = *this;
const Vec2d v = (line.b - line.a).cast<double>();
@ -140,7 +140,7 @@ BoundingBox get_extents(const Lines &lines)
}
Point Line::point_at(coordf_t distance) const {
Point Line::point_at(distf_t distance) const {
Point point;
coordf_t len = this->length();
point = this->a;
@ -151,10 +151,10 @@ Point Line::point_at(coordf_t distance) const {
return point;
}
double Line::distance_to_squared_abp(const Point &a, const Point &b, const Point &point, Point *nearest_point) {
distsqrf_t Line::distance_to_squared_abp(const Point &a, const Point &b, const Point &point, Point *nearest_point) {
const Vec2d v = ((b) - (a)).cast<double>();
const Vec2d va = (point - (a)).cast<double>();
const double l2 = v.squaredNorm();
const distsqrf_t l2 = v.squaredNorm();
if (l2 == 0.0) {
// a == b case
if (nearest_point) {
@ -188,5 +188,4 @@ double Line::distance_to_squared_abp(const Point &a, const Point &b, const Point
}
return (w - va).squaredNorm();
}
} // namespace Slic3r

View file

@ -76,7 +76,7 @@ auto angle_to_x(const L &l)
// Distance to the closest point of line.
template<class L>
inline double distance_to_squared(const L &line, const Vec<Dim<L>, Scalar<L>> &point, Vec<Dim<L>, Scalar<L>> *nearest_point)
inline distsqrf_t distance_to_squared(const L &line, const Vec<Dim<L>, Scalar<L>> &point, Vec<Dim<L>, Scalar<L>> *nearest_point)
{
using VecType = Vec<Dim<L>, double>;
const VecType v = (get_b(line) - get_a(line)).template cast<double>();
@ -108,17 +108,17 @@ inline double distance_to_squared(const L &line, const Vec<Dim<L>, Scalar<L>> &p
// Distance to the closest point of line.
template<class L>
double distance_to_squared(const L &line, const Vec<Dim<L>, Scalar<L>> &point)
distsqrf_t distance_to_squared(const L &line, const Vec<Dim<L>, Scalar<L>> &point)
{
Vec<Dim<L>, Scalar<L>> nearest_point;
return distance_to_squared<L>(line, point, &nearest_point);
}
template<class L>
double distance_to(const L &line, const Vec<Dim<L>, Scalar<L>> &point)
{
return std::sqrt(distance_to_squared(line, point));
}
//template<class L>
//distf_t distance_to(const L &line, const Vec<Dim<L>, Scalar<L>> &point)
//{
// return std::sqrt(distance_to_squared(line, point));
//}
// Returns a squared distance to the closest point on the infinite.
// Returned nearest_point (and returned squared distance to this point) could be beyond the 'a' and 'b' ends of the segment.
@ -144,7 +144,7 @@ double distance_to_infinite_squared(const L &line, const Vec<Dim<L>, Scalar<L>>
// Returns a squared distance to the closest point on the infinite.
// Closest point (and returned squared distance to this point) could be beyond the 'a' and 'b' ends of the segment.
template<class L>
double distance_to_infinite_squared(const L &line, const Vec<Dim<L>, Scalar<L>> &point)
distsqrf_t distance_to_infinite_squared(const L &line, const Vec<Dim<L>, Scalar<L>> &point)
{
Vec<Dim<L>, Scalar<L>> nearest_point;
return distance_to_infinite_squared<L>(line, point, &nearest_point);
@ -153,7 +153,7 @@ double distance_to_infinite_squared(const L &line, const Vec<Dim<L>, Scalar<L>>
// Returns a distance to the closest point on the infinite.
// Closest point (and returned squared distance to this point) could be beyond the 'a' and 'b' ends of the segment.
template<class L>
double distance_to_infinite(const L &line, const Vec<Dim<L>, Scalar<L>> &point)
distf_t distance_to_infinite(const L &line, const Vec<Dim<L>, Scalar<L>> &point)
{
return std::sqrt(distance_to_infinite_squared(line, point));
}
@ -209,14 +209,14 @@ public:
void translate(double x, double y) { this->translate(Point(x, y)); }
void rotate(double angle, const Point &center) { this->a.rotate(angle, center); this->b.rotate(angle, center); }
void reverse() { std::swap(this->a, this->b); }
coordf_t length() const { return (b.cast<coordf_t>() - a.cast<coordf_t>()).norm(); }
distf_t length() const { return (b.cast<coordf_t>() - a.cast<coordf_t>()).norm(); }
Point midpoint() const { return (this->a + this->b) / 2; }
bool intersection_infinite(const Line &other, Point* point) const;
bool operator==(const Line &rhs) const { return this->a == rhs.a && this->b == rhs.b; }
double distance_to_squared(const Point &point) const { return distance_to_squared(point, this->a, this->b); }
double distance_to_squared(const Point &point, Point *closest_point) const { return line_alg::distance_to_squared(*this, point, closest_point); }
coordf_t distance_to(const Point &point) const { return distance_to(point, this->a, this->b); }
double distance_to_infinite_squared(const Point &point, Point *closest_point) const { return line_alg::distance_to_infinite_squared(*this, point, closest_point); }
distsqrf_t distance_to_squared(const Point &point) const { return distance_to_squared_abp(this->a, this->b, point); }
distsqrf_t distance_to_squared(const Point &point, Point *closest_point) const { return distance_to_squared_abp(this->a, this->b, point, closest_point); }
coordf_t distance_to(const Point &point) const { return std::sqrt(distance_to_squared_abp(this->a, this->b, point)); }
distsqrf_t distance_to_infinite_squared(const Point &point, Point *closest_point) const { return line_alg::distance_to_infinite_squared(*this, point, closest_point); }
coordf_t perp_distance_to(const Point &point) const;
bool parallel_to(double angle) const;
bool parallel_to(const Line& line) const;
@ -233,16 +233,17 @@ public:
// Extend the line from both sides by an offset.
void extend(coordf_t offset);
static inline double distance_to_squared(const Point &point, const Point &a, const Point &b) { return line_alg::distance_to_squared(Line{a, b}, Vec<2, coord_t>{point}); }
static coordf_t distance_to(const Point &point, const Point &a, const Point &b) { return sqrt(distance_to_squared(point, a, b)); }
// not precise enough. something is lost in the abstraction.
// { return line_alg::distance_to_squared(Line{a, b}, Vec<2, coord_t>{point}); }
//static coordf_t distance_to_abp(const Point &a, const Point &b, const Point &point) { return sqrt(distance_to_squared_abp(a, b, point)); }
Point point_at(coordf_t distance) const;
coord_t dot(const Line &l2) const { return vector().dot(l2.vector()); }
void extend_end(coordf_t distance) { Line line = *this; line.reverse(); this->b = line.point_at(-distance); }
void extend_start(coordf_t distance) { this->a = this->point_at(-distance); }
void extend_end(distf_t distance) { Line line = *this; line.reverse(); this->b = line.point_at(-distance); }
void extend_start(distf_t distance) { this->a = this->point_at(-distance); }
// Returns a distance to the closest point on the infinite.
// Closest point (and returned squared distance to this point) could be beyond the 'a' and 'b' ends of the segment.
static inline double distance_to_infinite_squared(const Point &point, const Point &a, const Point &b) { return line_alg::distance_to_infinite_squared(Line{a, b}, Vec<2, coord_t>{point}); }
static inline distsqrf_t distance_to_infinite_squared(const Point &point, const Point &a, const Point &b) { return line_alg::distance_to_infinite_squared(Line{a, b}, Vec<2, coord_t>{point}); }
static coordf_t distance_to_infinite(const Point &point, const Point &a, const Point &b) { return sqrt(distance_to_infinite_squared(point, a, b)); }
// version optimized to work on int-4 Points, to reduce cast & to avoid precision issues.
static double distance_to_squared_abp(const Point &a, const Point &b, const Point &point, Point *nearest_point = nullptr);

View file

@ -61,10 +61,10 @@ namespace Slic3r {
}
}
ExtrusionPath contour({ExtrusionRole::Milling});
ExtrusionPath contour({ExtrusionRole::Milling}, nullptr);
contour.attributes_mutable().mm3_per_mm = 0;
contour.attributes_mutable().width = (float)this->print_config.milling_diameter.get_at(0);
contour.attributes_mutable().height = (float)layer->height;
contour.attributes_mutable().height = (float)layer->unscaled_height();
contour.polyline.append(best_polyline.points[first_point_extract_idx]);
for (int32_t idx = first_point_idx; idx < poly.points.size(); idx++) {
contour.polyline.append(poly.points[idx]);
@ -86,14 +86,14 @@ namespace Slic3r {
}
}
//default path, without safe-guard up-down.
ExtrusionPath contour({ExtrusionRole::Milling});
ExtrusionPath contour({ExtrusionRole::Milling}, nullptr);
contour.polyline = ArcPolyline(poly.split_at_first_point());
//do a second pass on the first segment
if (contour.polyline.size() > 2)
contour.polyline.append(contour.polyline.get_point(1));
contour.attributes_mutable().mm3_per_mm = 0;
contour.attributes_mutable().width = (float)this->print_config.milling_diameter.get_at(0);
contour.attributes_mutable().height = (float)layer->height;
contour.attributes_mutable().height = (float)layer->unscaled_height();
out_coll.append(std::move(contour));
return;
@ -106,8 +106,8 @@ namespace Slic3r {
const coord_t milling_diameter = scale_t(this->print_config.milling_diameter.get_at(0));
ExPolygons milling_lines;
for (const Surface& surf : slices->surfaces) {
ExPolygons surf_milling = offset_ex(surf.expolygon, double(milling_diameter / 2), ClipperLib::jtRound);
for (const ExPolygon& surf_expolygon : *slices) {
ExPolygons surf_milling = offset_ex(surf_expolygon, double(milling_diameter / 2), ClipperLib::jtRound);
for (const ExPolygon& expoly : surf_milling)
// expoly.simplify(SCALED_RESOLUTION, &milling_lines); // should already be done
milling_lines.push_back(expoly);
@ -138,11 +138,14 @@ namespace Slic3r {
}
bool MillingPostProcess::can_be_milled(const Layer* layer) {
double max_first_layer = 0;
coord_t max_first_layer = 0;
//TODO zstep
for (double diam : this->print_config.nozzle_diameter.get_values())
max_first_layer = std::max(max_first_layer, this->config.milling_after_z.get_abs_value(this->object_config.first_layer_height.get_abs_value(diam)));
max_first_layer = std::max(max_first_layer,
Layer::scale_to_layer_coord(this->config.milling_after_z.get_abs_value(
this->object_config.first_layer_height.get_abs_value(diam))));
return !this->print_config.milling_diameter.empty() && this->config.milling_post_process
&& layer->bottom_z() >= max_first_layer;
&& layer->scaled_bottom_z() >= max_first_layer;
}
ExPolygons MillingPostProcess::get_unmillable_areas(const Layer* layer)
@ -153,12 +156,12 @@ namespace Slic3r {
ExPolygons milling_lines;
ExPolygons surfaces;
for (const Surface& surf : slices->surfaces) {
ExPolygons surf_milling = offset_ex(surf.expolygon, milling_radius, ClipperLib::jtRound);
for (const ExPolygon& surf_expolygon : *slices) {
ExPolygons surf_milling = offset_ex(surf_expolygon, milling_radius, ClipperLib::jtRound);
for (const ExPolygon& expoly : surf_milling)
// expoly.simplify(SCALED_RESOLUTION, &milling_lines); // should already be done
milling_lines.push_back(expoly);
surfaces.push_back(surf.expolygon);
surfaces.push_back(surf_expolygon);
}
union_safety_offset_ex(milling_lines);
union_safety_offset_ex(surfaces);

View file

@ -13,7 +13,7 @@ namespace Slic3r {
class MillingPostProcess {
public:
// Inputs:
const SurfaceCollection *slices;
const ExPolygons *slices;
const ExPolygons *lower_slices;
const PrintRegionConfig &config;
const PrintObjectConfig &object_config;
@ -21,7 +21,7 @@ public:
MillingPostProcess(
// Input:
const SurfaceCollection* slices,
const ExPolygons* slices,
const ExPolygons* lower_slices,
const PrintRegionConfig& config,
const PrintObjectConfig& object_config,

View file

@ -889,7 +889,7 @@ static inline std::vector<std::vector<ExPolygons>> mm_segmentation_top_and_botto
// Project upwards pointing painted triangles over top surfaces,
// project downards pointing painted triangles over bottom surfaces.
std::vector<std::vector<Polygons>> top_raw(num_extruders), bottom_raw(num_extruders);
std::vector<float> zs = zs_from_layers(layers);
std::vector<float> zs = slice_z_from_layers(layers);
Transform3d object_trafo = print_object.trafo_centered();
#ifdef MM_SEGMENTATION_DEBUG_TOP_BOTTOM
@ -995,9 +995,9 @@ static inline std::vector<std::vector<ExPolygons>> mm_segmentation_top_and_botto
// Number of regions for a queried color.
int num_regions { 0 };
// Maximum perimeter extrusion width for a queried color.
coordf_t extrusion_width { 0.f };
double extrusion_width { 0.};
// Minimum radius of a region to be printable. Used to filter regions by morphological opening.
coordf_t small_region_threshold { 0.f };
double small_region_threshold { 0.};
// Maximum number of top layers for a queried color.
int top_solid_layers { 0 };
// Maximum number of bottom layers for a queried color.
@ -1024,7 +1024,7 @@ static inline std::vector<std::vector<ExPolygons>> mm_segmentation_top_and_botto
// Gap fill enabled. Enable a single line of 1/2 extrusion width.
0.5f * (perimeter_extrusion_width) :
// Gap fill disabled. Enable two lines slightly overlapping.
(perimeter_extrusion_width) + 0.7f * Flow::rounded_rectangle_extrusion_spacing(perimeter_extrusion_width, float(layer.height), 1.f);
(perimeter_extrusion_width) + 0.7f * Flow::rounded_rectangle_extrusion_spacing(perimeter_extrusion_width, float(layer.unscaled_height()), 1.f);
out.small_region_threshold = scale_d(out.small_region_threshold * 0.5f);
++ out.num_regions;
}

View file

@ -437,7 +437,7 @@ Points MultiPoint::_douglas_peucker_plus(const Points& pts, const double toleran
size_t furthest_idx = anchor_idx;
// find point furthest from line seg created by (anchor, floater) and note it
for (size_t i = anchor_idx + 1; i < floater_idx; ++i) {
double dist_sq = Line::distance_to_squared(pts[i], *anchor, *floater);
double dist_sq = Line::distance_to_squared_abp(*anchor, *floater, pts[i]);
if (dist_sq > max_dist_sq) {
max_dist_sq = dist_sq;
furthest_idx = i;
@ -492,7 +492,7 @@ Points MultiPoint::_douglas_peucker_plus(const Points& pts, const double toleran
// find point furthest from line seg created by (anchor, floater) and note it
for (size_t i = start_idx + 1; i < end_idx; ++i) {
if (start_point->distance_to_square(pts[i]) > half_min_length_sq && end_point->distance_to_square(pts[i]) > half_min_length_sq) {
double dist_sq = Line::distance_to_squared(pts[i], *start_point, *end_point);
double dist_sq = Line::distance_to_squared_abp(*start_point, *end_point, pts[i]);
if (dist_sq > max_dist_sq) {
max_dist_sq = dist_sq;
furthest_idx = i;

Some files were not shown because too many files have changed in this diff Show more