Compare commits

..
Author SHA1 Message Date
ExPikaPaka af29e4d553 Image adjustment panel for texture displacement layers (#16391) 2026-10-13 18:45:21 +08:00
SoftFever df392508b7 Fix texture projection UV orientation (#16393)
# Description
An image laid onto a model came out upside down under the box
(tri-planar) projection, and on three of a cube's six faces it was also
mirrored left to right.

The sampler treats `v = 0` as the height map's top pixel row, but every
projection built `v` from world +Z, so `v` grew upward. The mirroring is
a separate defect: both faces sharing a world plane got the same `u`.

Note: re-baking an existing project now places its texture upright, so
it will look different from before. Geometry already baked into a 3mf is
unaffected.

# Images
<img width="2420" height="1655" alt="image"
src="https://github.com/user-attachments/assets/dcf7f62f-0f51-4966-97e4-d0386eb454c2"
/>



# Tests
6 tests added in `tests/libslic3r/test_texture_displacement.cpp`,
covering all six cube faces and every mapping mode, plus a full bake of
a known asymmetric image.


<!--
> A guide for users on how to download the artifacts from this PR.
-->

[How to Download Pull Requests Artifacts for
Testing](https://www.orcaslicer.com/wiki/how_to_download_pr_artifacts)
2026-10-13 18:24:00 +08:00
SoftFever 11493a2236 Merge branch 'main' into fix-texture-uv-orientation 2026-10-13 18:16:02 +08:00
SoftFever df4c8cd531 Free G-code result and preview memory on reset (#16065)
GCodeProcessorResult declares a copy assignment, which suppresses the
implicit
move assignment, so `*result = std::move(processor.extract_result())`
binds to
the copy and duplicates the whole moves array: 96 bytes per move,
measured at
147.7 MiB in one allocation for a 597k facet model at 0.08 mm, with the
source
staying alive until the export returns.

Add the move assignment. It assigns exactly the same 39 members in the
same
order as the copy, including the ones the copy deliberately leaves
alone, so a
target that carries its own filament maps and nozzle type keeps them. A
move
constructor is intentionally not added: the type holds a std::mutex, so
it is
neither copy nor move constructible today and a partial one would leave
ten
members uninitialised.

reset() now releases the two print sized vectors rather than clearing
them. Its
callers are the paths that discard a result, so the memory went back
only at the
next slice.

ViewerImpl::reset() does the same for the two vectors sized by the
print, which
is what keeps a discarded preview resident, and counts m_vertices_colors
in the
reported CPU memory, where it was missing.
2026-10-13 18:06:46 +08:00
SoftFever bf5a378479 Free G-code result buffers with clear_and_shrink 2026-10-13 18:05:51 +08:00
Lam Wei Lun 01499e536e fix(gui): stop the UV editor pane from hijacking the shared GL context
The texture-displacement gizmo pushes pane state to the UV editor from the
preview rebuild that runs on every frame of a slider drag. Tile size is the
only one of the layer card's sliders whose value appears in that pane state,
so dragging it changes the "N.N mm tile" label, the panel relays out, and the
UV canvas receives a synchronous wxEVT_SIZE. Its on_size() flushes a paint
with Update(), and render() then makes the app's single shared wxGLContext
current on the UV drawable in the middle of the 3D canvas's frame.

On X11/GLX that out-of-turn context activation is fatal: the drawable the
3D canvas later swaps no longer belongs to the current context, the server
returns BadMatch, and GDK turns the unhandled X error into g_error(). EGL on
Wayland reports only a status, so the same theft silently corrupts the frame
instead of aborting - which is why the guard is not conditioned on the
display backend.

Add GLCanvas3D::is_frame_in_progress(), backed by a counter that
_render_frame() maintains through its existing scope guard, and let the UV
canvas skip the synchronous paint while a frame is on the stack, re-queueing
it with Refresh() so nothing is dropped. Rebind the context with
_set_current() before SwapBuffers() as well, so a surface that steals it by
some other route - a modal GL dialog a gizmo opens from its panel - cannot
turn the swap into the same fatal error.
2026-10-13 16:49:06 +08:00
SoftFever f33a9bf999 Merge branch 'main' into perf/gcode-result-move 2026-10-13 16:37:00 +08:00
HanifKoh 869e450981 Keep Per-Nozzle Values When a User Preset Syncs Through the Cloud (#16355)
The cloud upload sent only the keys that differ from the parent, so a
variant layout equal to the parent's was left out. On download the
loader sized every per-variant value by the missing layout, cut it to
one value and kept the parent's values for the other nozzles and nozzle
volume types. On dual-nozzle printers the right nozzle's settings
silently reverted to the parent's after a sync.

Upload the variant layout always, as the local save already does, and
read copies stored without it against the parent's layout when they
carry one value per parent variant.
2026-10-13 13:59:48 +08:00
hikaru0602 b920116fbd Fix manual tool change handling when loading G-code files (#15379)
Opened or drag-dropped G-code files ignored `; MANUAL_TOOL_CHANGE` comments, so the preview showed every move on the first filament. Only `apply_config(const PrintConfig&)` read `manual_filament_change`, and loading a file goes through `apply_config(const DynamicPrintConfig&)`. Read the option there too, initialize the flag to false, and add a regression test.
2026-10-12 20:03:04 -05:00
Downtime 237586675f fix(gui): remove legacy fixed-function OpenGL texture calls (#16270)
Debug builds asserted on startup because these calls raise GL errors on a core-profile context. Both draws already use shaders, so removing the calls changes nothing on compatibility contexts.
2026-10-12 20:01:57 -05:00
Ian Bassi 6d35ff6b9a Rewrite Fix Model on CGAL 6.2, fix Split to parts, remove Win10 SDK leftovers (#16366)
* Add CGAL-based mesh repair, drop Netfabb remnants

Add repair_mesh() in MeshRepair.cpp, a CGAL-based repair that replaces MeshBoolean::cgal::repair(). It welds cracks, cancels coincident triangles, fixes orientation, fills holes (including planar annular regions), removes local self-intersections, and unites crossing shells with libigl's exact boolean while following the nonzero winding rule used by slicing.

FixModelByCgal now repairs each volume in place without splitting it into parts, and reports whether the mesh was modified so unchanged meshes keep their painting and ids. The texture import repair prompt no longer depends on the Windows SDK, and the FIX_THROUGH_CGAL_ALWAYS conditionals are removed. The commented-out Netfabb/WIN10SDK build code is deleted.

libslic3r_cgal now builds with CGAL_LINKED_WITH_TBB and links TBB. Add docs/HLSD/mesh-repair.md and unit tests in test_mesh_repair.cpp.

* Parallelize repair while preserving separate shells

Repair connected mesh units and shells independently in parallel, keep crossing shells separate, and limit self-intersection remeshing to local defects. Update mesh-repair documentation and tests for the revised behavior.

* Make mesh repair deterministic and report its progress

Flags written from parallel loops were std::vector<bool>, whose neighbouring
bits share a word, so shells could be kept or dropped at random; they are now
std::vector<char>. Holes of up to 100 edges are filled with the search over all
triangles: the search restricted to a 3D Delaunay triangulation picks between
equally good fills differently from run to run.

Shells of fewer than four faces are dropped, as the volumes of two triangles
back to back need not cancel exactly, and a shell that self-intersection removal
changed is split again so the pieces it cut off are dropped too.

repair_mesh() takes a progress callback in place of the cancel callback, and
Fix Model reports each stage. The object's bounding box is now invalidated even
when a cancel or an error stops the repair after some volumes were replaced.

The edge-use sort, union-find and box-overlap code shared by several stages is
factored out, the topology analysed for welding is reused to build the work
units, the orientation pass checks only the edges it cut, and the output is
written from the shells without joining them first.

* Fix Split to parts crashing on flat pieces and staying offered after a repair

ModelVolume::split() added every piece to the object and then deleted the
pieces without a convex hull. When the first piece was flat, as often in a
triangle soup, that deleted the volume being split while split() and its
caller kept using it. A part made only of flat pieces lost all its volumes,
and a soup added thousands of pieces, saving a backup of the object for each
one it deleted. Pieces without a convex hull are now dropped before any joins
the object, the volume being split keeps the first remaining piece, and a part
with no solid piece is left whole. Other parts of the object without a convex
hull are no longer deleted as a side effect.

ModelVolume caches whether its mesh can be split, and set_mesh() kept the
cached value, so after Fix Model, Simplify or Emboss replaced a mesh, Split to
parts could still be offered for a single piece. set_mesh() and reset_mesh()
now clear the cache.

* Import STEP surface models with Split compound enabled

Splitting a compound kept only its solids, so a surface model, which OCCT
reads as a compound of loose faces, gave nothing to mesh and the import failed
with "Meshing of a model file failed or no valid shape". Each shell outside a
solid now becomes a part too, and loose faces stay together as one part, as
they do without splitting.

* Add Fix All for plates and re-enable --repair on the command line

ModelVolume::repair() applies repair_mesh() to a part and replaces the mesh
only when the repair changed it. Fix Model, the new Fix All and Fix All Plates
items of the plate context menu, and the command line's --repair option, which
had been commented out since the Win10 SDK repair was dropped, all use it.

With Keep painted feature after mesh change off, Fix Model cleared the painting
of every part of an object before repairing. Now only a part whose mesh changes
loses its painting, so fixing a whole project does not wipe it. The
notification counts the models that needed no repair instead of listing them as
repaired, and objects that did not change are not refreshed.
2026-10-12 21:59:17 -03:00
HMITCHR 075b03975f Read the initial filament start G-code through get_at() (#16080)
A filament_start_gcode list shorter than the filament count made the Bambu start-of-export path throw std::out_of_range. Use get_at() like the other filament_start_gcode reads, and add a regression test.
2026-10-12 19:55:02 -05:00
Kris Austin a379ec4a67 ci(macOS): retry stapler staple after notarization (#16424)
stapler fetches the notarization ticket from Apple's CloudKit server,
and a dropped connection there (NSURLError -1005, exit 68) failed the
whole macOS universal job twice on 2026-10-12, after notarization had
already been accepted. Rerunning the job passed, but repeats the full
build and both notarizations.

Wrap both stapler calls in the existing retry helper already used for
hdiutil in this step.
2026-10-12 19:36:45 -05:00
Alexandre Folle de Menezes 6700d4c5df Verify and improve AI pt_BR translations (#16377) 2026-10-12 20:57:57 -03:00
Downtimeandkenrap a28c9c3a82 fix(gui): guard gizmo actions before deferred initialization (#16268)
GLGizmosManager can be called while its gizmo list is empty, either at startup before the canvas has loaded the gizmos or after their init() failed. reset_all_states(), open_gizmo(), open_gizmo_by_shortcut() and activate_gizmo() now return early in that case. This fixes a Debug-build assert when a new project resets the gizmos at startup, and an out-of-bounds read in release builds when a gizmo shortcut key is pressed after gizmo init failed. activate_gizmo(Undefined) still returns true, since no gizmo is open. The reset_all_states() guard was first proposed in #16074 by kenrap.

Co-authored-by: kenrap <101818165+kenrap@users.noreply.github.com>
2026-10-12 18:25:17 -05:00
packerlschupfer 3dd547c8be CLI: Fix the -50 error reason assuming a 3mf upload (#16339)
The reason recorded for CLI_NO_SUITABLE_OBJECTS (-50) assumed a 3mf being uploaded. The CLI also slices STL, OBJ and STEP input, so the reason now states what both -50 sites check: the plate is empty, or no object on it is both printable and fully inside the print volume. The exit code is unchanged.

Adds tests/cli/test_cli_no_suitable_objects.sh.
2026-10-12 18:23:55 -05:00
f0e9cdc470 raft expansion (#16416)
Update ConfigManipulation.cpp

Co-authored-by: Accelerator <22743445+acceleratorlastorder@users.noreply.github.com>
Co-authored-by: Ian Bassi <12130714+ianalexis@users.noreply.github.com>
2026-10-12 18:24:25 -03:00
Downtime 58a71331d0 fix(gui): balance ImGui style stacks in gizmo windows (#16269)
Pop the FramePadding style var before end() in the move and rotate gizmo windows. It was pushed inside the window and popped after End(), which failed ImGui's style stack check in Debug builds.
2026-10-12 15:32:59 -05:00
packerlschupfer f127b758ed CLI: Don't rotate objects when arranging unless --allow-rotations is passed (#15033)
The CLI's arrange no longer rotates objects unless --allow-rotations is passed, which matches the GUI's default. STL, OBJ and STEP inputs are arranged even without --arrange, so a part that only fits the bed when rotated now exits with -50 unless --allow-rotations is given. The CLI prints that reason to stderr.
2026-10-12 15:17:38 -05:00
Fernando Marino` 1494de66de Bracket a toolchange's own gcode against FanMover splitting its moves (#15904)
FanMover could split a move inside change_filament_gcode to place a delayed fan command. It computed the split point from the last position the G-code set, but on Bambu printers the firmware moves the head during the T command, so the inserted waypoint sent the head to a spot the template never visits (#15789).

Both toolchange paths, set_extruder() and the Type1 append_tcr(), now wrap the template output in ;_FAN_MOVER_SKIP_START/END tags when fan speed-up or kick-start is on. FanMover keeps fan commands inside them where they are and drops the tags from the output. multifilament_config() also sizes the per-filament options that the wipe tower reads by index.
2026-10-12 14:26:20 -05:00
SoftFever 3ca182a98e Fix H2C start G-code record-data comments (#16406)
This fixes the H2C start G-code template by commenting the two
`========== record data ==========` separator lines.

Those lines are currently emitted as raw text inside
`machine_start_gcode`. Since they are not comments or G-code commands,
they can make the generated start sequence invalid or firmware-dependent
when the template is used. The fix preserves the separators as comments.

Fixes #16218.

Validation:
- Parsed the modified JSON profile with Python `json.loads`.
- Checked both `record data` separator lines now start with `;` after
unescaping the G-code string.
2026-10-13 01:07:25 +08:00
SoftFever 5e19fc0e6c Stop leaking layers on re-slice and honor each object's slice closing radius (#16066)
# Description

Re-slicing no longer leaks layers in two places. Tree supports dropped
the support layers above the topmost overhang without freeing them. And
an object that had sliced itself, then became identical to another
object (for example a copy whose original lost a per-object setting or
modifier), leaked its own layers when it switched to sharing that
object's slices; it now frees them once it takes the shared layers over.
If slicing is cancelled before that point, they still leak, as before.
Tree support also stops copying its collision and avoidance areas on
every lookup, and releases its working cache once supports are generated
instead of keeping it until the next slice. Elephant-foot compensation
now uses each object's own slice closing radius, where the first object
sliced in a session used to fix the value for every later slice.

Slicing output changes only on layers with more than one region printed
with elephant-foot compensation and no raft, and only where an object's
slice closing radius differs from the value the session had fixed.

# Screenshots/Recordings/Graphs

<!--
> Please attach relevant screenshots to showcase the UI changes.
> Please attach images that can help explain the changes.
-->

## Tests

Adds a regression test for an object that switches to sharing another
object's slices. The `fff_print` suite passes.

<!--
> A guide for users on how to download the artifacts from this PR.
-->

[How to Download Pull Requests Artifacts for
Testing](https://www.orcaslicer.com/wiki/how_to_download_pr_artifacts)

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-10-13 00:28:26 +08:00
SoftFever 3f4709aaa7 Fix stale and hidden highlights in the texture displacement gizmo (#16409)
# Description

Fixes highlights in the texture displacement gizmo that stayed on screen
after the state behind them changed, or were drawn where they could not
be seen. Erase whole model, Select whole model and Capture current view
update the paint highlight at once instead of on the next right-click. A
stroke released outside the 3D view ends on the next mouse move, in
every paint gizmo, rather than leaving the brush stuck in its pressed
colour. The layer textures stop showing an image that has been replaced.
Selecting islands in the UV editor switches a Normal view to Fast, where
their highlight is visible instead of buried under the displaced relief,
and Normal comes back once no island is selected unless another view was
picked in the meantime.

No change to slicing output; the changes are confined to the paint
gizmos and the UV editor.

# Screenshots/Recordings/Graphs

<!--
> Please attach relevant screenshots to showcase the UI changes.
> Please attach images that can help explain the changes.
-->

## Tests

<!--
> Please describe the tests that you have conducted to verify the
changes made in this PR.
-->

<!--
> A guide for users on how to download the artifacts from this PR.
-->

[How to Download Pull Requests Artifacts for
Testing](https://www.orcaslicer.com/wiki/how_to_download_pr_artifacts)
2026-10-13 00:23:33 +08:00
SoftFever c63bd5d474 Switch to the Fast view while UV islands are selected in the texture gizmo
The island highlight was hidden under the Normal view's relief. Normal comes back once no island is selected, unless another view was picked in the meantime.
2026-10-13 00:18:51 +08:00
SoftFever 6263502697 Free a sharing object's own layers only when it takes over the shared ones 2026-10-13 00:15:07 +08:00
HanifKoh 1a9201690d Draw Preview Segments With 16-Bit Indices (#16389)
The segment draw switched to an element buffer of 8-bit indices. GCN 1/2
GPUs cannot read 8-bit indices in hardware, so the driver converts them,
and on a Mac Pro 2013 FirePro under Windows Boot Camp the toolpaths come
out as scattered spikes. 16-bit indices are supported everywhere and keep
the eight shader runs per segment.
2026-10-13 00:09:18 +08:00
SoftFever c6a338f35f Fix stale paint highlights and textures in the texture displacement gizmo
Erase whole model, Select whole model and Capture current view update the
highlight at once. A stroke released outside the 3D view ends on the next mouse
move, in every paint gizmo, instead of leaving the brush in its pressed colour.
The layer textures no longer show an image that was replaced.
2026-10-12 23:18:38 +08:00
HanifKoh 4f2d2ae11a Wait for the PR's Deps Cache in clang-tidy When deps/ Changes (#16374)
* Wait for the PR's Deps Cache in clang-tidy When deps/ Changes

* Fail the clang-tidy Deps Wait When Listing Caches Keeps Failing

* Wait for Deps Through ci_deps_cache.sh in clang-tidy

Reuse the macOS deps wait for Linux: the job names, workflow and cache
ref are passed in, and a new 'own' mode waits for the PR's own build
when it changes deps/. A PR that keeps deps/ now waits for a running base
build with the same deps, and warns when it falls back to older ones. The
wait ends as soon as the deps job fails.
2026-10-12 23:17:41 +08:00
SoftFever c57b5dc6c5 Merge branch 'main' into perf/slicing-core-memory 2026-10-12 22:16:10 +08:00
ExPikaPaka 1abd6649c7 Put the UV orientation tests beside the projection tests
They were appended at the end of test_texture_displacement.cpp, where every
other open texture-displacement branch also appends, so the four of them
cannot be merged in any order without a conflict in a file none of them
really disagree about. Same tests, moved next to the patch-frame test they
belong with.
2026-10-12 13:58:28 +02:00
chenshj73 7d4ec3494c Fix H2C start G-code record-data comments 2026-10-12 19:30:32 +08:00
ExPikaPaka 56b559d36a Fix texture projection UV orientation
An image laid onto a model came out upside down under the ordinary box
(tri-planar) projection, and on three of a cube's six faces it was also
mirrored left to right, which reads as a 180 degree rotation.

DecodedHeightTexture::sample() defines v = 0 as the height map's first
pixel row, i.e. its top. Every projection built v from world +Z, so v
grew upward and the image landed bottom row up. The one path that was
already right is the projective "project from view" matrix, which
measures window y downward.

Both halves of the box basis were wrong:

- v is now negated on all three world planes, so the top of an image
  sits at the top of the model.
- u now carries a sign for the side of the plane the face is on, chosen
  so that u x v == -normal. Without it the two faces sharing a plane get
  one u and one of them is mirrored. The sign flips exactly where that
  plane's blend weight (the fourth power of a normal component) reaches
  zero, so the blended tri-planar sum stays continuous and the hard axis
  switch the old code removed does not come back.

The same v convention was missing from the other mapping modes:
cylindrical (which also had a left handed frame, right x up rather than
up x right, so its wrap ran mirrored), spherical, the affine branch of
view projection, and the flat chart fallback of the LSCM unwrap, which
now reuses the box basis so a cube face unwraps to the orientation
tri-planar would have given it.

The basis table is exported as box_projection_axes() and the gizmo's
adjust_tangent_basis() calls it instead of restating it, so the
placement ring and offset handle cannot drift from the bake. All four
preview shaders get the matching change, including projection_axes(),
whose tangent and bitangent have to flip with the coordinate or the
relief shading inverts.

Re-baking an existing project now places its texture upright, so it will
differ from how it looked before. Geometry already baked into a 3mf is
untouched, so nothing changes until the user re-bakes.

Verified by measuring the sampled texture row and column against world
position for every mapping mode on all six faces of a cube, and by a
full bake of a quadrant coded image, which lands each quadrant within
1e-3 mm of its expected depth.
2026-10-12 07:57:50 +02:00
ExPikaPaka bea412fddf Move the G-code processing result instead of copying it
GCodeProcessorResult declares a copy assignment, which suppresses the implicit
move assignment, so `*result = std::move(processor.extract_result())` binds to
the copy and duplicates the whole moves array: 96 bytes per move, measured at
147.7 MiB in one allocation for a 597k facet model at 0.08 mm, with the source
staying alive until the export returns.

Add the move assignment. It assigns exactly the same 39 members in the same
order as the copy, including the ones the copy deliberately leaves alone, so a
target that carries its own filament maps and nozzle type keeps them. A move
constructor is intentionally not added: the type holds a std::mutex, so it is
neither copy nor move constructible today and a partial one would leave ten
members uninitialised.

reset() now releases the two print sized vectors rather than clearing them. Its
callers are the paths that discard a result, so the memory went back only at the
next slice.

ViewerImpl::reset() does the same for the two vectors sized by the print, which
is what keeps a discarded preview resident, and counts m_vertices_colors in the
reported CPU memory, where it was missing.
2026-10-01 09:15:15 +02:00
ExPikaPaka 391c53a8da Take the print config by reference while simplifying extrusions
simplify_path, simplify_multi_path and simplify_loop each copied the whole
PrintConfig, 10520 bytes with around 200 heap owning members, once per extrusion
entity, from inside the parallel_for over all layers. LayerRegion.cpp already
binds a reference a few hundred lines above. Three more sites in Layer.cpp do the
same thing.

The tree support changes in the same area: draw_circles() dropped layers from an
owning vector without deleting them, so every re-slice leaked the layers above
the topmost overhang. std::stable_partition rather than std::remove_if, because
remove_if leaves moved-from duplicates of kept pointers in the tail and deleting
those would be a double free. The collision and avoidance accessors returned
ExPolygons by value out of a cache that hands them out by reference, several
times per node per layer. The preview cache is released when the support step
finishes instead of at the start of the next slice; nothing reads it in between.

set_shared_object() now releases the layers the object still owns before it
starts aliasing another object's. Both clear functions are no-ops once the alias
is set, so this cannot free the sharee's layers.

PrintObjectSlice.cpp: eps was a function local static inside a parallel_for, so
slice_closing_radius was latched once per process. This one changes output for
projects that override it per object, or on a re-slice after editing it. The old
behaviour was undefined: whichever object won the race set it for the session.
2026-10-01 09:15:15 +02:00
87 changed files with 4983 additions and 3368 deletions
+2 -6
View File
@@ -341,12 +341,12 @@ jobs:
# Notarize main DMG
xcrun notarytool submit "OrcaSlicer_Mac_universal_${{ env.ver }}.dmg" --apple-id "${{ secrets.APPLE_DEV_ACCOUNT }}" --team-id "${{ secrets.TEAM_ID }}" --password "${{ secrets.APP_PWD }}" --wait
xcrun stapler staple OrcaSlicer_Mac_universal_${{ env.ver }}.dmg
retry xcrun stapler staple OrcaSlicer_Mac_universal_${{ env.ver }}.dmg
# Notarize profile validator DMG if it exists
if [ -f "OrcaSlicer_profile_validator_Mac_universal_${{ env.ver }}.dmg" ]; then
xcrun notarytool submit "OrcaSlicer_profile_validator_Mac_universal_${{ env.ver }}.dmg" --apple-id "${{ secrets.APPLE_DEV_ACCOUNT }}" --team-id "${{ secrets.TEAM_ID }}" --password "${{ secrets.APP_PWD }}" --wait
xcrun stapler staple OrcaSlicer_profile_validator_Mac_universal_${{ env.ver }}.dmg
retry xcrun stapler staple OrcaSlicer_profile_validator_Mac_universal_${{ env.ver }}.dmg
fi
- name: Create DMG without notary
@@ -460,10 +460,6 @@ jobs:
- name: Build slicer Win
if: runner.os == 'Windows'
working-directory: ${{ github.workspace }}
# Orca: Removed Netfabb STL fixing service support in favor of CGAL.
# env:
# WindowsSdkDir: 'C:\Program Files (x86)\Windows Kits\10\'
# WindowsSDKVersion: '10.0.26100.0\'
# --tests builds the unit tests too; the unit_tests_windows_* jobs run them.
run: |
# cache-path is the install directory inside the deps build directory.
+70 -4
View File
@@ -16,6 +16,15 @@ on:
permissions:
contents: read
# Listing caches and builds while waiting for a deps cache.
actions: read
# Read by scripts/ci_deps_cache.sh.
env:
REPO: ${{ github.repository }}
WORKFLOW: build_all.yml
BASE_REF: ${{ github.base_ref }}
JOB: build_linux (${{ vars.SELF_HOSTED && 'orca-lnx-server' || 'ubuntu-24.04' }})
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
@@ -35,7 +44,7 @@ jobs:
# The PR merge commit plus its first parent, the base it is diffed against.
fetch-depth: 2
- name: Look for changed C++ files
- name: Look for changed files
id: changes
run: |
if git -c core.quotePath=false diff --name-only HEAD^1 -- src tests | grep -qE '\.(cpp|cc|cxx|hpp|h|hxx)$'; then
@@ -43,18 +52,75 @@ jobs:
else
echo "No C++ changes under src/ or tests/."
fi
if ! git diff --quiet HEAD^1 -- deps; then
echo "deps=true" >> "$GITHUB_OUTPUT"
fi
echo "deps-key=linux-clang-cache-orcaslicer_deps-build-${{ hashFiles('deps/**') }}" >> "$GITHUB_OUTPUT"
# Parsing needs the dependency headers, not a build of this PR's deps/, so
# a PR that changes deps/ falls back to the newest cache main has.
# Parsing needs the dependency headers, not a build of this PR's deps/.
# Without an exact match the job waits for the build that saves it: this
# PR's own when it changes deps/, otherwise a running push build of the
# base branch with the same deps. With neither, a PR that keeps deps/
# falls back to the newest cache.
- name: Restore cached deps
id: deps_cache
if: steps.changes.outputs.cpp == 'true'
uses: actions/cache/restore@v6
with:
path: ${{ github.workspace }}/deps/build/OrcaSlicer_dep
key: linux-clang-cache-orcaslicer_deps-build-${{ hashFiles('deps/**') }}
key: ${{ steps.changes.outputs.deps-key }}
- name: Look for a build to wait for
id: wait_check
if: steps.changes.outputs.cpp == 'true' && steps.deps_cache.outputs.cache-hit != 'true'
env:
GH_TOKEN: ${{ github.token }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: bash scripts/ci_deps_cache.sh ${{ steps.changes.outputs.deps == 'true' && 'own' || 'check' }}
# Linux Build Deps takes about 35 minutes on GitHub-hosted runners. The
# wait ends early when the deps job fails.
- name: Wait for the deps cache
if: steps.wait_check.outputs.wait-for != ''
timeout-minutes: 100
env:
GH_TOKEN: ${{ github.token }}
KEY: ${{ steps.changes.outputs.deps-key }}
CACHE_REF: ${{ steps.changes.outputs.deps == 'true' && github.ref || format('refs/heads/{0}', github.base_ref) }}
KEY_INPUTS: ${{ steps.wait_check.outputs.key-inputs }}
WAIT_FOR: ${{ steps.wait_check.outputs.wait-for }}
WAIT_SINCE: ${{ steps.wait_check.outputs.wait-since }}
WAIT_MINUTES: 90
run: bash scripts/ci_deps_cache.sh wait
- name: Restore the deps cache after waiting
id: waited_cache
if: steps.wait_check.outputs.wait-for != ''
uses: actions/cache/restore@v6
with:
path: ${{ github.workspace }}/deps/build/OrcaSlicer_dep
key: ${{ steps.changes.outputs.deps-key }}
- name: Fail without this PR's deps cache
if: steps.changes.outputs.deps == 'true' && steps.wait_check.outcome == 'success' && steps.waited_cache.outputs.cache-hit != 'true'
run: |
echo "::error::No deps cache ${{ steps.changes.outputs.deps-key }}. Check this PR's Linux Build Deps job, then rerun clang-tidy."
exit 1
- name: Restore the newest cached deps
id: newest_cache
if: steps.changes.outputs.deps != 'true' && steps.wait_check.outcome == 'success' && steps.waited_cache.outputs.cache-hit != 'true'
uses: actions/cache/restore@v6
with:
path: ${{ github.workspace }}/deps/build/OrcaSlicer_dep
key: ${{ steps.changes.outputs.deps-key }}
restore-keys: linux-clang-cache-orcaslicer_deps-build-
fail-on-cache-miss: true
- name: Warn about older deps
if: steps.newest_cache.outcome == 'success' && steps.newest_cache.outputs.cache-hit != 'true'
run: echo "::warning title=Older deps::No cache matches this PR's deps/, so clang-tidy parsed against ${{ steps.newest_cache.outputs.cache-matched-key }}. If it reports errors in code that uses a dependency, rerun clang-tidy once the base branch's Build all has saved the new deps."
- name: Apt-Install Dependencies
if: steps.changes.outputs.cpp == 'true' && !vars.SELF_HOSTED
uses: ./.github/actions/apt-install-deps
-41
View File
@@ -497,47 +497,6 @@ endif()
# Once we get rid of Perl and libslic3r is linked statically, we can get rid of -fPIC
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
# WIN10SDK_PATH is used to point CMake to the WIN10 SDK installation directory.
# We pick it from environment if it is not defined in another way
# ORCA: Removed Netfabb STL fixing service support in favor of CGAL.
# if(WIN32)
# if(NOT DEFINED WIN10SDK_PATH)
# if(DEFINED ENV{WIN10SDK_PATH})
# set(WIN10SDK_PATH "$ENV{WIN10SDK_PATH}")
# endif()
# endif()
# if(DEFINED WIN10SDK_PATH)
# #BBS: modify win10sdk_path
# if (EXISTS "${WIN10SDK_PATH}/winrt/windows.graphics.printing3d.h")
# set(WIN10SDK_INCLUDE_PATH "${WIN10SDK_PATH}")
# else()
# message("WIN10SDK_PATH is invalid: ${WIN10SDK_PATH}")
# message("${WIN10SDK_PATH}/winrt/windows.graphics.printing3d.h was not found")
# message("STL fixing by the Netfabb service will not be compiled")
# unset(WIN10SDK_PATH)
# endif()
# else()
# # Try to use the default Windows 10 SDK path.
# if (DEFINED ENV{WindowsSdkDir} AND DEFINED ENV{WindowsSDKVersion})
# set(WIN10SDK_INCLUDE_PATH "$ENV{WindowsSdkDir}/Include/$ENV{WindowsSDKVersion}")
# else ()
# set(WIN10SDK_INCLUDE_PATH "C:/Program Files (x86)/Windows Kits/10/Include/10.0.26100.0")
# endif ()
# if (NOT EXISTS "${WIN10SDK_INCLUDE_PATH}/winrt/windows.graphics.printing3d.h")
# message("${WIN10SDK_INCLUDE_PATH}/winrt/windows.graphics.printing3d.h was not found")
# message("STL fixing by the Netfabb service will not be compiled")
# unset(WIN10SDK_INCLUDE_PATH)
# endif()
# endif()
# if(WIN10SDK_INCLUDE_PATH)
# message("Building with Win10 Netfabb STL fixing service support")
# add_definitions(-DHAS_WIN10SDK)
# include_directories(SYSTEM "${WIN10SDK_INCLUDE_PATH}")
# else()
# message("Building without Win10 Netfabb STL fixing service support")
# endif()
# endif()
if (APPLE)
message("OS X SDK Path: ${CMAKE_OSX_SYSROOT}")
if (CMAKE_OSX_DEPLOYMENT_TARGET)
+135
View File
@@ -0,0 +1,135 @@
# Mesh repair — High Level Design
## Purpose and scope
Mesh repair turns a broken triangle mesh into closed, outward oriented shells that bound a solid, so that the
mesh slices predictably and the other mesh tools (booleans, cut, painting) get valid input. It runs on demand:
the *Fix Model* command of the context menu of an object or part and of the warning icon in the object list, *Fix
All* and *Fix All Plates* in the context menu of a plate, the prompt the Cut tool shows when a cut leaves open edges,
the *Repair and import* choice of texture import, and the `--repair` option of the command line. It is built on CGAL
and is the only repair the application has, on every platform.
`repair_mesh()` in `src/libslic3r/MeshRepair.cpp` does the work on one `TriangleMesh`, and `ModelVolume::repair()`
applies it to a part: it replaces the mesh only when the repair changed it, and remaps or drops the painting of a
replaced mesh. The GUI side, `fix_model_with_cgal_gui()` in `src/slic3r/Utils/FixModelByCgal.cpp`, runs it on a
worker thread for each volume of an object, or for one volume, behind a progress dialog. `repair_mesh()` reports its
progress between stages through a callback, which cancels the repair by throwing.
## What the repaired mesh is
The repair keeps what the slicer would print from the input. The slicer fills a layer where the winding number of
the input surface is not zero (`MeshSlicingParams::SlicingMode::Regular` uses Clipper's nonzero fill rule), so:
- Shells crossing each other print as their union. The repair keeps them as separate shells, as the parts of an
object are kept, and makes each of them an outward oriented solid.
- A shell inside a solid that is oriented like it adds nothing, and the repair removes it.
- A shell inside a solid that is oriented inward is a cavity, and stays one.
- A whole mesh turned inside out prints as a solid, and the repair turns it outward.
On top of that, it closes holes and cracks, gives inconsistently oriented triangles the orientation of their
neighbours, drops degenerate, duplicate and stray flat geometry, and removes small self-intersections inside a shell,
such as slivers and folds. Where none of this applies, it reports the mesh as unmodified and the caller keeps the
original mesh, its painting and its object id.
A volume is repaired in place and is never split into several parts: splitting by connectivity would turn a cavity
into a separate solid part and fill it. Each solid of the result is a shell of its own, so *Split to parts* still
separates them. Open pieces of the input whose borders meet exactly, which are pieces of one surface rather than
solids, come out as the one shell they form.
## Pipeline
The input is treated as a triangle soup. Every stage after the first only runs on what the previous ones could
not settle, so a valid mesh passes through quickly.
### Valid parts first
Parts of the input that are connected by vertex indices and are already closed, consistently oriented 2-manifolds
skip the soup stages and go straight to the shell stages. Merging their points with coincident points of other
parts would only make non-manifold junctions out of solids that touch, for example parts of an assembly exported
together or voxels written as separate cubes.
### Soup clean-up
The rest of the soup has its coincident points merged. Triangles with repeated corners are dropped. Coincident
triangles of opposite orientation are a wall between two solids touching face to face, so they cancel in pairs;
of the remaining copies of a triangle one is kept. A connected region that would vanish entirely through
cancelling is a two-sided export instead (every face written in both orientations), and keeps one copy of each
triangle.
Open edges then get their vertices welded within a tolerance of 1e-4 of the bounding box diagonal, which closes the
cracks some exporters leave between triangles that should share corners. A vertex is never welded further than a
quarter of its shortest edge, so welding cannot collapse fine detail. A soup that stays mostly open after welding has
cracks wider than that tolerance, and is welded again with ten and then a hundred times the tolerance.
### Work units
The soup is cut into units repaired independently and in parallel: its connected parts, except that open parts whose
bounding boxes touch share a unit, so that cracks and T-junctions between separately exported patches still close.
### Building the mesh
A unit whose edges are each shared by at most two triangles, running in opposite directions, and whose vertices each
have a single fan of triangles, becomes a `Surface_mesh` directly. Any other unit is oriented first. Triangles are
flipped so that neighbours across an edge shared by two of them agree, each part keeping the orientation the
majority of its area had, which keeps inward oriented cavities inward. Edges where that is impossible or that more
than two triangles share are cut, and each fan of triangles around a vertex gets its own copy of the vertex. If that
still leaves an invalid mesh, CGAL's `orient_polygon_soup()` orients the unit instead, and the parts it flipped
against their majority are reversed back. The linear pass exists because `orient_polygon_soup()` is several times
slower on large soups that need only a few fixes.
### Closing
Compatible borders are stitched, parts that can be stitched once reversed are merged, and borders still open are
snapped onto each other within the weld tolerance, which closes T-junctions. Exactly degenerate faces are removed.
Holes are filled last. Planar border loops that face each other in one plane, one inside the other, bound a single
region, such as a missing annulus at the end of a tube or a cap with features standing on it. Such a group is
triangulated at once with a 2D constrained Delaunay triangulation that fills only the faces at odd nesting depth,
so the openings inside the region stay open. The patch is used only if it closes every loop with the orientation
of the triangles around it. Every other loop is filled on its own with `triangulate_hole()`, which uses a 2D
constrained Delaunay triangulation when the loop is planar. Otherwise it searches the best triangulation among all
triangles over the loop for loops of up to 100 edges, and among the triangles of a 3D Delaunay triangulation for
longer ones, as the full search is cubic in the length of the loop. Beyond 200 edges the full search is not even
used as a fallback, and a fan around the loop's centroid closes a loop nothing else could.
The closed unit is split into its shells. The largest stays in place and the others are copied out, as converting
the whole mesh again costs seconds on large models.
### Shells
The shells of all units, together with the valid parts set aside at the start, are handled independently and in
parallel. Shells enclosing no volume, which hole filling makes out of stray flat patches, are dropped.
Self-intersections inside a shell are removed locally with `experimental::remove_self_intersections()`, which
remeshes the region around them. It is used only for local defects: a shell whose intersections involve more than
5 % of its faces is left as it is, and a result that changes the enclosed volume by more than 0.1 % is undone. On
heavily overlapping ornamental models the remeshing otherwise cuts parts down to slivers, while on genuine defects
it changes the volume by thousandths of a percent. Overlaps left in place slice correctly. Remeshing can cut
small pieces off a shell, so a shell it changed is split again and its pieces enclosing no volume are dropped.
Shells crossing others are found through their bounding boxes and an AABB tree per shell, and are made outward
oriented solids. For every other shell the winding number just outside it is summed from the orientation of the
shells containing it, tested from a point on its largest face. The shell bounds the solid only if the winding
number is zero on exactly one of its sides; it is then oriented so that the solid is inside, or dropped otherwise.
Crossing shells are not united. Slicing unites them anyway, uniting them exactly costs tens of seconds on models
made of many overlapping pieces, and it would fuse parts that *Split to parts* should keep apart.
## Robustness
The repair avoids `experimental::autorefine_and_remove_self_intersections()` and corefinement, which can crash on
messy input, and uses only steps whose failures it can detect. A step that fails keeps its input. CGAL precondition
failures surface as `repair_mesh()` returning false with the message as the error. The output is written in float,
as every mesh in the application is.
The result does not depend on thread scheduling. `libslic3r_cgal` is built with `CGAL_LINKED_WITH_TBB`. Units and
shells are processed in parallel, but each on its own data, and their results are gathered in a fixed order;
sorts compare complete keys, and the detected self-intersections are put in order before they are used. Snapping
stays sequential, as its parallel version gives different results from run to run. Holes are filled with the full
search wherever it is affordable, because the search among Delaunay triangles can choose between equally good fills
differently from run to run, so only non-planar holes of more than 100 edges may still vary. On some inputs
`experimental::remove_self_intersections()` itself places a few vertices differently from run to run.
## Verification
`tests/libslic3r/test_mesh_repair.cpp` covers each kind of defect above on small meshes with known volumes.
File diff suppressed because it is too large Load Diff
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path d="M2.5,2.5h11v11h-11z" style="fill:none;stroke:#949494;stroke-linecap:round;stroke-linejoin:round"/><path d="M8,2.5v11M2.5,8h11" style="fill:none;stroke:#949494;stroke-dasharray:1.5,1.5"/><path d="M4.5,11.5l3.5-6l3.5,6z" style="fill:#009688"/></svg>

Before

Width:  |  Height:  |  Size: 340 B

+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "Bambulab",
"url": "http://www.bambulab.com/Parameters/vendor/BBL.json",
"version": "02.08.00.14",
"version": "02.08.00.15",
"force_update": "0",
"description": "the initial version of BBL configurations",
"machine_model_list": [
File diff suppressed because one or more lines are too long
@@ -72,17 +72,21 @@ varying float weight;
varying float island_active;
varying vec2 vertex_uv;
// The cylinder's own frame, built exactly as libslic3r's project_cylindrical() builds it - including
// the handedness, which comes out left-handed for an axis of +Z. Copied rather than "corrected", so
// the preview wraps the texture the same way round as the bake.
// The cylinder's own frame, built exactly as libslic3r's project_cylindrical() builds it - right
// handed, so the angle taken from it grows anticlockwise about the axis, which seen from outside the
// cylinder is to the viewer's right rather than mirrored.
void cylinder_frame(out vec3 up, out vec3 right, out vec3 fwd)
{
up = (length(patch_axis) > 1e-8) ? normalize(patch_axis) : vec3(0.0, 0.0, 1.0);
vec3 arbitrary = (abs(up.z) < 0.9) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
right = normalize(cross(up, arbitrary));
fwd = normalize(cross(right, up));
fwd = normalize(cross(up, right));
}
// Which side of a world plane a face is on, with zero counting as the positive side. Not GLSL's own
// sign(), which returns 0 there and would collapse the coordinate onto a line.
float box_face_sign(float n) { return n >= 0.0 ? 1.0 : -1.0; }
// The raw, millimetre-valued projection of `p` (a position in the texture frame), before the layer's
// tiling/rotation/aspect/offset - a term-for-term transcription of libslic3r's project_planar(),
// project_cylindrical() and project_spherical(). `n` is read by the planar mode only.
@@ -94,7 +98,7 @@ vec2 projection_raw(vec3 p, vec3 n)
vec3 rel = p - patch_center;
float x = dot(rel, right);
float y = dot(rel, fwd);
return vec2(atan(y, x) * sqrt(x * x + y * y), dot(rel, up));
return vec2(atan(y, x) * sqrt(x * x + y * y), -dot(rel, up));
}
if (projection_mode == 2) { // Spherical: (longitude, latitude) * radius
vec3 rel = p - patch_center;
@@ -102,10 +106,18 @@ vec2 projection_raw(vec3 p, vec3 n)
if (radius < 1e-8)
return vec2(0.0);
vec3 dir = rel / radius;
return vec2(atan(dir.y, dir.x), asin(clamp(dir.z, -1.0, 1.0))) * radius;
return vec2(atan(dir.y, dir.x), -asin(clamp(dir.z, -1.0, 1.0))) * radius;
}
vec3 an = abs(n); // Triplanar: drop the dominant normal axis
return (an.x >= an.y && an.x >= an.z) ? p.yz : ((an.y >= an.x && an.y >= an.z) ? p.xz : p.xy);
// Triplanar: drop the dominant normal axis. v is negated so the image's first pixel row (v = 0)
// sits at the top of the model instead of upside down, and u is flipped on the far side of each
// plane so the two faces sharing it are not mirror images. libslic3r's box_plane_yz() and its two
// siblings, term for term.
vec3 an = abs(n);
if (an.x >= an.y && an.x >= an.z)
return vec2(box_face_sign(n.x) * p.y, -p.z);
if (an.y >= an.x && an.y >= an.z)
return vec2(-box_face_sign(n.y) * p.x, -p.z);
return vec2(box_face_sign(n.z) * p.x, -p.y);
}
// The two surface directions projection_raw()'s u and v run along at `p`, plus how many raw units one
@@ -124,7 +136,7 @@ void projection_axes(vec3 p, vec3 n, out vec3 t, out vec3 b, out vec2 units_per_
vec2 xy = vec2(dot(rel, right), dot(rel, fwd));
float r = length(xy);
t = (r > 1e-6) ? (fwd * xy.x - right * xy.y) / r : right; // circumferential: u runs along it
b = up; // v is the distance along the axis
b = -up; // v is the distance *against* the axis
return;
}
if (projection_mode == 2) {
@@ -133,20 +145,20 @@ void projection_axes(vec3 p, vec3 n, out vec3 t, out vec3 b, out vec2 units_per_
vec3 dir = (r > 1e-8) ? rel / r : vec3(0.0, 0.0, 1.0);
float c = length(dir.xy); // cos(latitude)
t = (c > 1e-6) ? vec3(-dir.y, dir.x, 0.0) / c : vec3(1.0, 0.0, 0.0);
b = cross(dir, t); // increasing latitude, unit length
b = -cross(dir, t); // v grows away from the pole, unit length
units_per_mm = vec2(1.0 / max(c, 1e-3), 1.0);
return;
}
vec3 an = abs(n);
if (an.x >= an.y && an.x >= an.z) { // planar = p.yz
t = vec3(0.0, 1.0, 0.0);
b = vec3(0.0, 0.0, 1.0);
} else if (an.y >= an.x && an.y >= an.z) { // planar = p.xz
t = vec3(1.0, 0.0, 0.0);
b = vec3(0.0, 0.0, 1.0);
} else { // planar = p.xy
t = vec3(1.0, 0.0, 0.0);
b = vec3(0.0, 1.0, 0.0);
vec3 an = abs(n); // the same signed basis projection_raw() uses
if (an.x >= an.y && an.x >= an.z) { // planar = (+-y, -z)
t = vec3(0.0, box_face_sign(n.x), 0.0);
b = vec3(0.0, 0.0, -1.0);
} else if (an.y >= an.x && an.y >= an.z) { // planar = (+-x, -z)
t = vec3(-box_face_sign(n.y), 0.0, 0.0);
b = vec3(0.0, 0.0, -1.0);
} else { // planar = (+-x, -y)
t = vec3(box_face_sign(n.z), 0.0, 0.0);
b = vec3(0.0, -1.0, 0.0);
}
}
@@ -36,14 +36,20 @@ varying vec4 world_pos;
varying float distortion;
varying vec2 vertex_uv;
// Right handed (up x right), like libslic3r's project_cylindrical(), so the angle taken from it grows
// anticlockwise about the axis - to the viewer's right when seen from outside the cylinder.
void cylinder_frame(out vec3 up, out vec3 right, out vec3 fwd)
{
up = (length(patch_axis) > 1e-8) ? normalize(patch_axis) : vec3(0.0, 0.0, 1.0);
vec3 arbitrary = (abs(up.z) < 0.9) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
right = normalize(cross(up, arbitrary));
fwd = normalize(cross(right, up));
fwd = normalize(cross(up, right));
}
// Which side of a world plane a face is on, with zero counting as the positive side. Not GLSL's own
// sign(), which returns 0 there and would collapse the coordinate onto a line.
float box_face_sign(float n) { return n >= 0.0 ? 1.0 : -1.0; }
// Term for term libslic3r's project_planar() / project_cylindrical() / project_spherical(), in mm.
vec2 projection_raw(vec3 p, vec3 n)
{
@@ -53,7 +59,7 @@ vec2 projection_raw(vec3 p, vec3 n)
vec3 rel = p - patch_center;
float x = dot(rel, right);
float y = dot(rel, fwd);
return vec2(atan(y, x) * sqrt(x * x + y * y), dot(rel, up));
return vec2(atan(y, x) * sqrt(x * x + y * y), -dot(rel, up));
}
if (projection_mode == 2) {
vec3 rel = p - patch_center;
@@ -61,10 +67,16 @@ vec2 projection_raw(vec3 p, vec3 n)
if (radius < 1e-8)
return vec2(0.0);
vec3 dir = rel / radius;
return vec2(atan(dir.y, dir.x), asin(clamp(dir.z, -1.0, 1.0))) * radius;
return vec2(atan(dir.y, dir.x), -asin(clamp(dir.z, -1.0, 1.0))) * radius;
}
// v negated so the image's first pixel row sits at the top of the model, u flipped on the far side
// of each plane so the two faces sharing it are not mirror images - see libslic3r's box_plane_yz().
vec3 an = abs(n);
return (an.x >= an.y && an.x >= an.z) ? p.yz : ((an.y >= an.x && an.y >= an.z) ? p.xz : p.xy);
if (an.x >= an.y && an.x >= an.z)
return vec2(box_face_sign(n.x) * p.y, -p.z);
if (an.y >= an.x && an.y >= an.z)
return vec2(-box_face_sign(n.y) * p.x, -p.z);
return vec2(box_face_sign(n.z) * p.x, -p.y);
}
vec2 project_uv(vec3 p, vec3 n)
@@ -138,17 +138,21 @@ in vec2 vertex_uv;
out vec4 out_color;
// The cylinder's own frame, built exactly as libslic3r's project_cylindrical() builds it - including
// the handedness, which comes out left-handed for an axis of +Z. Copied rather than "corrected", so
// the preview wraps the texture the same way round as the bake.
// The cylinder's own frame, built exactly as libslic3r's project_cylindrical() builds it - right
// handed, so the angle taken from it grows anticlockwise about the axis, which seen from outside the
// cylinder is to the viewer's right rather than mirrored.
void cylinder_frame(out vec3 up, out vec3 right, out vec3 fwd)
{
up = (length(patch_axis) > 1e-8) ? normalize(patch_axis) : vec3(0.0, 0.0, 1.0);
vec3 arbitrary = (abs(up.z) < 0.9) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
right = normalize(cross(up, arbitrary));
fwd = normalize(cross(right, up));
fwd = normalize(cross(up, right));
}
// Which side of a world plane a face is on, with zero counting as the positive side. Not GLSL's own
// sign(), which returns 0 there and would collapse the coordinate onto a line.
float box_face_sign(float n) { return n >= 0.0 ? 1.0 : -1.0; }
// The raw, millimetre-valued projection of `p` (a position in the texture frame), before the layer's
// tiling/rotation/aspect/offset - a term-for-term transcription of libslic3r's project_planar(),
// project_cylindrical() and project_spherical(). `n` is read by the planar mode only.
@@ -160,7 +164,7 @@ vec2 projection_raw(vec3 p, vec3 n)
vec3 rel = p - patch_center;
float x = dot(rel, right);
float y = dot(rel, fwd);
return vec2(atan(y, x) * sqrt(x * x + y * y), dot(rel, up));
return vec2(atan(y, x) * sqrt(x * x + y * y), -dot(rel, up));
}
if (projection_mode == 2) { // Spherical: (longitude, latitude) * radius
vec3 rel = p - patch_center;
@@ -168,10 +172,18 @@ vec2 projection_raw(vec3 p, vec3 n)
if (radius < 1e-8)
return vec2(0.0);
vec3 dir = rel / radius;
return vec2(atan(dir.y, dir.x), asin(clamp(dir.z, -1.0, 1.0))) * radius;
return vec2(atan(dir.y, dir.x), -asin(clamp(dir.z, -1.0, 1.0))) * radius;
}
vec3 an = abs(n); // Triplanar: drop the dominant normal axis
return (an.x >= an.y && an.x >= an.z) ? p.yz : ((an.y >= an.x && an.y >= an.z) ? p.xz : p.xy);
// Triplanar: drop the dominant normal axis. v is negated so the image's first pixel row (v = 0)
// sits at the top of the model instead of upside down, and u is flipped on the far side of each
// plane so the two faces sharing it are not mirror images. libslic3r's box_plane_yz() and its two
// siblings, term for term.
vec3 an = abs(n);
if (an.x >= an.y && an.x >= an.z)
return vec2(box_face_sign(n.x) * p.y, -p.z);
if (an.y >= an.x && an.y >= an.z)
return vec2(-box_face_sign(n.y) * p.x, -p.z);
return vec2(box_face_sign(n.z) * p.x, -p.y);
}
// The two surface directions projection_raw()'s u and v run along at `p`, plus how many raw units one
@@ -190,7 +202,7 @@ void projection_axes(vec3 p, vec3 n, out vec3 t, out vec3 b, out vec2 units_per_
vec2 xy = vec2(dot(rel, right), dot(rel, fwd));
float r = length(xy);
t = (r > 1e-6) ? (fwd * xy.x - right * xy.y) / r : right; // circumferential: u runs along it
b = up; // v is the distance along the axis
b = -up; // v is the distance *against* the axis
return;
}
if (projection_mode == 2) {
@@ -199,20 +211,20 @@ void projection_axes(vec3 p, vec3 n, out vec3 t, out vec3 b, out vec2 units_per_
vec3 dir = (r > 1e-8) ? rel / r : vec3(0.0, 0.0, 1.0);
float c = length(dir.xy); // cos(latitude)
t = (c > 1e-6) ? vec3(-dir.y, dir.x, 0.0) / c : vec3(1.0, 0.0, 0.0);
b = cross(dir, t); // increasing latitude, unit length
b = -cross(dir, t); // v grows away from the pole, unit length
units_per_mm = vec2(1.0 / max(c, 1e-3), 1.0);
return;
}
vec3 an = abs(n);
if (an.x >= an.y && an.x >= an.z) { // planar = p.yz
t = vec3(0.0, 1.0, 0.0);
b = vec3(0.0, 0.0, 1.0);
} else if (an.y >= an.x && an.y >= an.z) { // planar = p.xz
t = vec3(1.0, 0.0, 0.0);
b = vec3(0.0, 0.0, 1.0);
} else { // planar = p.xy
t = vec3(1.0, 0.0, 0.0);
b = vec3(0.0, 1.0, 0.0);
vec3 an = abs(n); // the same signed basis projection_raw() uses
if (an.x >= an.y && an.x >= an.z) { // planar = (+-y, -z)
t = vec3(0.0, box_face_sign(n.x), 0.0);
b = vec3(0.0, 0.0, -1.0);
} else if (an.y >= an.x && an.y >= an.z) { // planar = (+-x, -z)
t = vec3(-box_face_sign(n.y), 0.0, 0.0);
b = vec3(0.0, 0.0, -1.0);
} else { // planar = (+-x, -y)
t = vec3(box_face_sign(n.z), 0.0, 0.0);
b = vec3(0.0, -1.0, 0.0);
}
}
@@ -47,14 +47,20 @@ in vec2 vertex_uv;
out vec4 out_color;
// Right handed (up x right), like libslic3r's project_cylindrical(), so the angle taken from it grows
// anticlockwise about the axis - to the viewer's right when seen from outside the cylinder.
void cylinder_frame(out vec3 up, out vec3 right, out vec3 fwd)
{
up = (length(patch_axis) > 1e-8) ? normalize(patch_axis) : vec3(0.0, 0.0, 1.0);
vec3 arbitrary = (abs(up.z) < 0.9) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
right = normalize(cross(up, arbitrary));
fwd = normalize(cross(right, up));
fwd = normalize(cross(up, right));
}
// Which side of a world plane a face is on, with zero counting as the positive side. Not GLSL's own
// sign(), which returns 0 there and would collapse the coordinate onto a line.
float box_face_sign(float n) { return n >= 0.0 ? 1.0 : -1.0; }
// Term for term libslic3r's project_planar() / project_cylindrical() / project_spherical(), in mm.
vec2 projection_raw(vec3 p, vec3 n)
{
@@ -64,7 +70,7 @@ vec2 projection_raw(vec3 p, vec3 n)
vec3 rel = p - patch_center;
float x = dot(rel, right);
float y = dot(rel, fwd);
return vec2(atan(y, x) * sqrt(x * x + y * y), dot(rel, up));
return vec2(atan(y, x) * sqrt(x * x + y * y), -dot(rel, up));
}
if (projection_mode == 2) {
vec3 rel = p - patch_center;
@@ -72,10 +78,16 @@ vec2 projection_raw(vec3 p, vec3 n)
if (radius < 1e-8)
return vec2(0.0);
vec3 dir = rel / radius;
return vec2(atan(dir.y, dir.x), asin(clamp(dir.z, -1.0, 1.0))) * radius;
return vec2(atan(dir.y, dir.x), -asin(clamp(dir.z, -1.0, 1.0))) * radius;
}
// v negated so the image's first pixel row sits at the top of the model, u flipped on the far side
// of each plane so the two faces sharing it are not mirror images - see libslic3r's box_plane_yz().
vec3 an = abs(n);
return (an.x >= an.y && an.x >= an.z) ? p.yz : ((an.y >= an.x && an.y >= an.z) ? p.xz : p.xy);
if (an.x >= an.y && an.x >= an.z)
return vec2(box_face_sign(n.x) * p.y, -p.z);
if (an.y >= an.x && an.y >= an.z)
return vec2(-box_face_sign(n.y) * p.x, -p.z);
return vec2(box_face_sign(n.z) * p.x, -p.y);
}
vec2 project_uv(vec3 p, vec3 n)
+43 -17
View File
@@ -1,21 +1,27 @@
#!/usr/bin/env bash
# Lets a pull request's macOS deps build wait for a push build of the base
# branch that builds the same deps, from a Linux job. `check` runs after a cache
# miss and names a queued or running base build with the same deps/ and .github/
# to wait for, unless the pull request changes either. `wait` waits until that
# build saves KEY. actions/cache then confirms the entry can be restored.
# Lets a pull request's macOS deps build, or its clang-tidy job, wait for a
# build that saves the deps cache it needs, from a Linux job. `check` runs after
# a cache miss and names a queued or running push build of the base branch with
# the same deps/ and .github/ to wait for, unless the pull request changes either.
# `own` names the pull request's own build instead, for clang-tidy when the pull
# request changes deps/. `wait` waits until that build saves KEY under CACHE_REF,
# or its deps job fails. actions/cache then confirms the entry can be restored.
#
# Environment: GH_TOKEN, REPO, WORKFLOW_REF and BASE_REF, plus KEY_INPUTS,
# WAIT_FOR, WAIT_SINCE, WAIT_MINUTES, KEY and ARCH for `wait`.
# Environment: GH_TOKEN, REPO, WORKFLOW_REF (or WORKFLOW, the build workflow's
# file name) and BASE_REF, plus HEAD_SHA for `own`, and KEY_INPUTS, WAIT_FOR,
# WAIT_SINCE, WAIT_MINUTES, KEY, CACHE_REF (default the base branch) and ARCH
# (or JOB, the matrix job's name) for `wait`.
# Writes key-inputs, wait-for and wait-since to $GITHUB_OUTPUT.
set -uo pipefail
workflow=${WORKFLOW_REF%%@*}
workflow=${workflow##*/}
workflow=${WORKFLOW_REF:-}
workflow=${workflow%%@*}
workflow=${WORKFLOW:-${workflow##*/}}
# Must match the job names in build_all.yml, build_check_cache.yml and build_deps.yml.
check_job_name="build_macos_arch (${ARCH:-}) / Check Cache"
deps_job_name="build_macos_arch (${ARCH:-}) / Build Deps / Build Deps"
job=${JOB:-build_macos_arch (${ARCH:-})}
check_job_name="$job / Check Cache"
deps_job_name="$job / Build Deps / Build Deps"
out() { echo "$1" >> "${GITHUB_OUTPUT:-/dev/stdout}"; }
@@ -63,8 +69,27 @@ check() {
fi
}
own() {
out "key-inputs=$(local_key_inputs HEAD)"
local id
# The build can be created a moment after this job.
for _ in 1 2 3 4 5; do
id=$(gh api -X GET "repos/$REPO/actions/workflows/$workflow/runs" \
-f head_sha="$HEAD_SHA" -f event=pull_request -f per_page=1 --jq '.workflow_runs[0].id // empty' < /dev/null)
[ -n "$id" ] && break
sleep 30
done
if [ -n "$id" ]; then
echo "Waiting for the deps cache of build $id of this pull request."
out "wait-for=$id"
out "wait-since=$(date +%s)"
else
echo "No build of this pull request is building its deps."
fi
}
key_saved() {
gh cache list -R "$REPO" --ref "refs/heads/$BASE_REF" --key "$KEY" --json key < /dev/null \
gh cache list -R "$REPO" --ref "${CACHE_REF:-refs/heads/$BASE_REF}" --key "$KEY" --json key < /dev/null \
| jq -e --arg key "$KEY" 'any(.[]; .key == $key)' > /dev/null
}
@@ -87,11 +112,11 @@ wait_for() {
key_saved && { echo "Found $KEY."; return; }
sleep 20
done
echo "Build $id of $BASE_REF finished its deps without saving $KEY."
echo "Build $id finished its deps without saving $KEY."
return ;;
"completed cancelled") ;;
completed*)
echo "The deps job of build $id of $BASE_REF did not succeed."
echo "The deps job of build $id did not succeed."
return ;;
# The deps job exists only once the build's cache check has succeeded.
"")
@@ -100,7 +125,7 @@ wait_for() {
completed*)
check=$(jq -r --arg name "$check_job_name" 'first(.jobs[] | select(.name == $name) | .conclusion) // ""' <<< "$jobs")
if [ -z "$warned" ] && { [ -z "$check" ] || [ "$check" = success ]; }; then
echo "::warning title=Deps wait::Build $id of $BASE_REF has no job named \"$deps_job_name\". If the build jobs were renamed, update scripts/ci_deps_cache.sh. This does not affect this pull request."
echo "::warning title=Deps wait::Build $id has no job named \"$deps_job_name\". If the build jobs were renamed, update scripts/ci_deps_cache.sh. This does not affect this pull request."
warned=1
fi ;;
*)
@@ -118,11 +143,12 @@ wait_for() {
seen="$seen $id"
echo "Following build $id of $BASE_REF."
done
echo "No build of $BASE_REF saved $KEY."
echo "No build saved $KEY."
}
case "${1:-}" in
check) check ;;
own) own ;;
wait) wait_for ;;
*) echo "usage: $0 check|wait" >&2; exit 2 ;;
*) echo "usage: $0 check|own|wait" >&2; exit 2 ;;
esac
+28 -6
View File
@@ -99,6 +99,7 @@
#include "libslic3r/Preset.hpp"
#include "libslic3r/Geometry.hpp"
#include "libslic3r/GCode.hpp"
#include "libslic3r/MeshRepair.hpp"
#include "libslic3r/Model.hpp"
#include "libslic3r/ModelArrange.hpp"
#include "libslic3r/Platform.hpp"
@@ -206,7 +207,7 @@ std::map<int, std::string> cli_errors = {
{CLI_OBJECT_ORIENT_FAILED, "An error occurred when auto-orienting object(s)."},
{CLI_MODIFIED_PARAMS_TO_PRINTER, "Found modified parameter in printer preset in the 3mf file, which should not be changed."},
{CLI_FILE_VERSION_NOT_SUPPORTED, "Unsupported 3MF version. Please make sure the 3MF file was created with the official version of Bambu Studio, not a beta version."},
{CLI_NO_SUITABLE_OBJECTS, "One of the plate is empty or has no object fully inside it. Please check that the 3mf contains no empty plate in Orca Slicer before uploading."},
{CLI_NO_SUITABLE_OBJECTS, "The plate has nothing to slice: it is empty, or no object on it is both printable and fully inside the print volume."},
{CLI_VALIDATE_ERROR, "There are some incorrect slicing parameters in the 3mf. Please verify the slicing of all plates in Orca Slicer before uploading."},
{CLI_OBJECTS_PARTLY_INSIDE, "Some objects are located over the boundary of the heated bed."},
{CLI_EXPORT_CACHE_DIRECTORY_CREATE_FAILED, "Failed creating directory when exporting cache data."},
@@ -1463,7 +1464,7 @@ int CLI::run(int argc, char **argv)
//int arrange_option;
int plate_to_slice = 0, filament_count = 0, duplicate_count = 0, real_duplicate_count = 0, current_extruder_count = 1, new_extruder_count = 1, current_printer_variant_count = 1, current_print_variant_count = 1, new_printer_variant_count = 1;
bool first_file = true, is_bbl_3mf = false, need_arrange = true, has_thumbnails = false, up_config_to_date = false, normative_check = true, duplicate_single_object = false, use_first_fila_as_default = false, minimum_save = false, enable_timelapse = false;
bool allow_rotations = true, skip_modified_gcodes = false, avoid_extrusion_cali_region = false, skip_useless_pick = false, allow_newer_file = false, current_is_multi_extruder = false, new_is_multi_extruder = false, allow_mix_temp = false, enable_wrapping_detect = false;
bool allow_rotations = false, skip_modified_gcodes = false, avoid_extrusion_cali_region = false, skip_useless_pick = false, allow_newer_file = false, current_is_multi_extruder = false, new_is_multi_extruder = false, allow_mix_temp = false, enable_wrapping_detect = false;
Semver file_version;
std::map<size_t, bool> orients_requirement;
std::vector<Preset*> project_presets;
@@ -5130,9 +5131,19 @@ int CLI::run(int argc, char **argv)
}
}
} else if (opt_key == "repair") {
// Models are repaired by default.
//for (auto &model : m_models)
// model.repair();
if (m_config.opt_bool(opt_key))
for (Model &model : m_models)
for (ModelObject *object : model.objects) {
for (ModelVolume *volume : object->volumes) {
MeshRepairStats stats;
std::string error;
if (!volume->repair(true, &stats, &error))
BOOST_LOG_TRIVIAL(warning) << "repair of " << object->name << " / " << volume->name << " failed: " << error;
else if (stats.modified)
BOOST_LOG_TRIVIAL(info) << "repaired " << object->name << " / " << volume->name;
}
object->invalidate_bounding_box();
}
} else {
boost::nowide::cerr << "error: option not implemented yet: " << opt_key << std::endl;
record_exit_reson(outfile_dir, CLI_UNSUPPORTED_OPERATION, 0, cli_errors[CLI_UNSUPPORTED_OPERATION], sliced_info);
@@ -5142,6 +5153,7 @@ int CLI::run(int argc, char **argv)
BOOST_LOG_TRIVIAL(info) << "finished model pre-process commands\n";
bool oriented_or_arranged = false;
bool arranged_without_rotations = false;
//BBS: add orient and arrange logic here
for (auto& model : m_models)
{
@@ -5409,6 +5421,7 @@ int CLI::run(int argc, char **argv)
BOOST_LOG_TRIVIAL(info) << boost::format("start plate %1%'s arranging...") % (i + 1);
arrangement::arrange(selected, unselected, beds, arrange_cfg);
//arrangement::arrange(unprintable, {}, beds, arrange_cfg);
arranged_without_rotations |= !arrange_cfg.allow_rotations;
BOOST_LOG_TRIVIAL(info) << boost::format("finished plate %1%'s arranging") % (i + 1);
//step-4: postprocess the bed index and result
@@ -5881,6 +5894,7 @@ int CLI::run(int argc, char **argv)
BOOST_LOG_TRIVIAL(info) << boost::format("start %1% th arranging...")%arrange_count;
arrangement::arrange(selected, unselected, beds, arrange_cfg);
arrangement::arrange(unprintable, {}, beds, arrange_cfg);
arranged_without_rotations |= !arrange_cfg.allow_rotations;
BOOST_LOG_TRIVIAL(info) << boost::format("finished %1% th arranging...")%arrange_count;
//Step-4:postprocess by partplate list&&apply the result
@@ -6425,7 +6439,15 @@ int CLI::run(int argc, char **argv)
if (count == 0) {
BOOST_LOG_TRIVIAL(error) << "plate "<< index+1<< ": Nothing to be sliced, Either the print is empty or no object is fully inside the print volume before apply." << std::endl;
record_exit_reson(outfile_dir, CLI_NO_SUITABLE_OBJECTS, index+1, cli_errors[CLI_NO_SUITABLE_OBJECTS], sliced_info);
std::string no_objects_reason = cli_errors[CLI_NO_SUITABLE_OBJECTS];
if (arranged_without_rotations) {
//ORCA: result.json is only written on Linux, so also print the reason to stderr.
no_objects_reason = "No object is fully inside the print volume. Arrange ran without rotations."
" If an object only fits the bed when rotated, pass --allow-rotations."
" Otherwise the plate is empty or an object is larger than the printable area or height.";
boost::nowide::cerr << "plate " << index+1 << ": " << no_objects_reason << std::endl;
}
record_exit_reson(outfile_dir, CLI_NO_SUITABLE_OBJECTS, index+1, no_objects_reason, sliced_info);
flush_and_exit(CLI_NO_SUITABLE_OBJECTS);
}
else if ((plate_to_slice != 0) || pre_check) {
+4 -1
View File
@@ -625,6 +625,7 @@ add_library(libslic3r_cgal STATIC
CutSurface.hpp CutSurface.cpp
IntersectionPoints.hpp IntersectionPoints.cpp
MeshBoolean.hpp MeshBoolean.cpp
MeshRepair.hpp MeshRepair.cpp
TryCatchSignal.hpp TryCatchSignal.cpp
Triangulation.hpp Triangulation.cpp
)
@@ -652,7 +653,9 @@ if (IS_CLANG_CL)
target_compile_options(libslic3r_cgal PRIVATE -Wno-overriding-option)
endif ()
target_link_libraries(libslic3r_cgal PRIVATE ${_cgal_tgt} admesh libigl mcut boost_libs)
# Lets CGAL algorithms given CGAL::Parallel_if_available_tag run on TBB.
target_compile_definitions(libslic3r_cgal PRIVATE CGAL_LINKED_WITH_TBB)
target_link_libraries(libslic3r_cgal PRIVATE ${_cgal_tgt} admesh libigl mcut boost_libs TBB::tbb)
if (MSVC AND "${CMAKE_SIZEOF_VOID_P}" STREQUAL "4") # 32 bit MSVC workaround
target_compile_definitions(libslic3r_cgal PRIVATE CGAL_DO_NOT_USE_MPZF)
+15 -5
View File
@@ -236,19 +236,29 @@ static void getNamedSolids(const TopLoc_Location& location,
int i = 0;
switch (shape_type) {
case TopAbs_COMPOUND:
if (!isSplitCompound) {
namedSolids.emplace_back(TopoDS::Compound(transform.Shape()), fullName);
break;
}
case TopAbs_COMPSOLID:
if (!isSplitCompound) {
namedSolids.emplace_back(TopoDS::CompSolid(transform.Shape()), fullName);
namedSolids.emplace_back(transform.Shape(), fullName);
} else {
for (explorer.Init(transform.Shape(), TopAbs_SOLID); explorer.More(); explorer.Next()) {
i++;
const TopoDS_Shape& currentShape = explorer.Current();
namedSolids.emplace_back(TopoDS::Solid(currentShape), fullName + "-SOLID-" + std::to_string(i));
}
// Surface models have no solids: each shell outside a solid is a part, and loose faces stay together.
i = 0;
for (explorer.Init(transform.Shape(), TopAbs_SHELL, TopAbs_SOLID); explorer.More(); explorer.Next())
namedSolids.emplace_back(explorer.Current(), fullName + "-SHELL-" + std::to_string(++i));
TopoDS_Compound loose_faces;
TopoDS_Builder builder;
builder.MakeCompound(loose_faces);
bool has_loose_faces = false;
for (explorer.Init(transform.Shape(), TopAbs_FACE, TopAbs_SHELL); explorer.More(); explorer.Next()) {
builder.Add(loose_faces, explorer.Current());
has_loose_faces = true;
}
if (has_loose_faces)
namedSolids.emplace_back(loose_faces, fullName);
}
break;
case TopAbs_SOLID:
+15 -2
View File
@@ -1033,6 +1033,15 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
return buf;
}
// FanMover consumes these markers (and drops them) to avoid splitting a G1 inside custom gcode.
// Only written when FanMover runs, the same gate as its construction in GCode::process_layers.
static std::string wrap_custom_gcode_for_fan_mover(const FullPrintConfig &config, const std::string &gcode)
{
if (config.fan_speedup_time.value == 0 && config.fan_kickstart.value <= 0)
return gcode;
return ";_FAN_MOVER_SKIP_START\n" + gcode + ";_FAN_MOVER_SKIP_END\n";
}
std::string WipeTowerIntegration::append_tcr(GCode& gcodegen, const WipeTower::ToolChangeResult& tcr, int new_filament_id, double z) const
{
if (new_filament_id != -1 && new_filament_id != tcr.new_tool)
@@ -1384,6 +1393,9 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
toolchange_gcode_str = gcodegen.placeholder_parser_process("change_filament_gcode", change_filament_gcode, new_filament_id, &config);
check_add_eol(toolchange_gcode_str);
// Type1 wipe tower path (every BBL printer): bracket the same way set_extruder() does,
// so FanMover doesn't split a G1 inside this custom gcode either.
toolchange_gcode_str = wrap_custom_gcode_for_fan_mover(gcodegen.config(), toolchange_gcode_str);
//BBS
{
@@ -4250,7 +4262,7 @@ void GCode::_do_export(Print& print, GCodeOutputStream &file, ThumbnailsGenerato
config.set_key_value("nozzle_diameter_at_nozzle_id", new ConfigOptionFloats(get_nozzle_diameters_by_nozzle_id(group_result.get())));
config.set_key_value("nozzle_volume_types", new ConfigOptionStrings(get_nozzle_volume_types_by_nozzle_id(group_result.get())));
config.set_key_value("layer_num", new ConfigOptionInt(m_layer_index));
std::string filament_start_gcode = this->placeholder_parser_process("filament_start_gcode", print.config().filament_start_gcode.values.at(initial_non_support_extruder_id), initial_non_support_extruder_id,&config);
std::string filament_start_gcode = this->placeholder_parser_process("filament_start_gcode", print.config().filament_start_gcode.get_at(initial_non_support_extruder_id), initial_non_support_extruder_id,&config);
file.writeln(filament_start_gcode);
// Mark the first filament used in print. Multi-nozzle printers (H2C) get ";VT%d H%d" where
// H = dynamic ? nozzle_id : -1; existing single-nozzle printers keep the bare ";VT%d" so their
@@ -10895,7 +10907,8 @@ std::string GCode::set_extruder(unsigned int new_filament_id, double print_z, bo
toolchange_gcode_parsed = placeholder_parser_process("change_filament_gcode", change_filament_gcode, new_filament_id, &dyn_config);
check_add_eol(toolchange_gcode_parsed);
gcode += toolchange_gcode_parsed;
// toolchange_gcode_parsed is still read below (get_last_z_from_gcode, custom_gcode_changes_tool).
gcode += wrap_custom_gcode_for_fan_mover(m_config, toolchange_gcode_parsed);
//BBS
{
+5
View File
@@ -445,6 +445,11 @@ void FanMover::_process_gcode_line(GCodeReader& reader, const GCodeReader::GCode
std::string extrusion_string = line.raw().substr(6, line.raw().size() - 6);
current_role = ExtrusionEntity::string_to_role(extrusion_string);
}
if (line.raw().rfind(";_FAN_MOVER_SKIP_", 0) == 0) {
// Internal markers: read here, then dropped from the output.
m_is_custom_gcode = line.raw().rfind(";_FAN_MOVER_SKIP_START", 0) == 0;
time = -1;
}
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)
+7 -2
View File
@@ -2602,12 +2602,13 @@ void GCodeProcessorResult::reset() {
//BBS: add mutex for protection of gcode result
lock();
moves.clear();
// moves and lines_ends grow with the print: free them, as no reset result reuses the capacity.
clear_and_shrink(moves);
plate_mass = {};
object_masses.clear();
body_masses.clear();
support_masses.clear();
lines_ends.clear();
clear_and_shrink(lines_ends);
printable_area = Pointfs();
//BBS: add bed exclude area
bed_exclude_area = Pointfs();
@@ -3598,6 +3599,10 @@ void GCodeProcessor::apply_config(const DynamicPrintConfig& config)
if (has_scarf_joint_seam != nullptr)
m_detect_layer_based_on_tag = m_detect_layer_based_on_tag || has_scarf_joint_seam->value;
const ConfigOptionBool* manual_filament_change = config.option<ConfigOptionBool>("manual_filament_change");
if (manual_filament_change != nullptr)
m_manual_filament_change = manual_filament_change->value;
const ConfigOptionEnumGeneric *bed_type = config.option<ConfigOptionEnumGeneric>("curr_bed_type");
if (bed_type != nullptr)
m_result.bed_type = (BedType)bed_type->value;
+1 -1
View File
@@ -1228,7 +1228,7 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f;
// m_result.nozzle_group_result, which is handed over only after the stream for the
// pre-heat injector's second pass and gates the richer change-time model.
std::shared_ptr<MultiNozzleUtils::NozzleGroupResultBase> m_nozzle_group_result;
bool m_manual_filament_change;
bool m_manual_filament_change{ false };
//BBS: x, y offset for gcode generated
double m_x_offset{ 0 };
-88
View File
@@ -29,8 +29,6 @@
#include <CGAL/Polygon_mesh_processing/triangulate_hole.h>
#include <CGAL/Polygon_mesh_processing/stitch_borders.h>
#include <CGAL/Polygon_mesh_processing/polygon_soup_to_polygon_mesh.h>
#include <CGAL/Polygon_mesh_processing/repair_degeneracies.h>
#include <CGAL/Polygon_mesh_processing/manifoldness.h>
#include <cstdint>
#include <map>
#include <algorithm>
@@ -50,7 +48,6 @@
#include <CGAL/Polygon_mesh_processing/orient_polygon_soup.h>
#include <CGAL/Polygon_mesh_processing/repair.h>
#include <CGAL/Polygon_mesh_processing/remesh.h>
#include <CGAL/Polygon_mesh_processing/repair_polygon_soup.h>
#include <CGAL/Polygon_mesh_processing/orientation.h>
// BBS: for segment
#include <CGAL/mesh_segmentation.h>
@@ -658,91 +655,6 @@ bool empty(const CGALMesh &mesh)
return mesh.m.is_empty();
}
bool repair(TriangleMesh& mesh, RepairedMeshErrors* repaired_errors, std::string* error)
{
namespace PMP = CGAL::Polygon_mesh_processing;
if (mesh.empty())
return true;
try {
// 1) Convert to polygon soup
std::vector<_EpicMesh::Point> points;
std::vector<std::vector<std::size_t>> polygons;
points.reserve(mesh.its.vertices.size());
polygons.reserve(mesh.its.indices.size());
for (const auto& v : mesh.its.vertices)
points.emplace_back(v.x(), v.y(), v.z());
for (const auto& f : mesh.its.indices)
polygons.push_back({size_t(f[0]), size_t(f[1]), size_t(f[2])});
// 2) Aggressive soup cleanup
PMP::repair_polygon_soup(points, polygons);
// 3) Convert soup → mesh
_EpicMesh cgal_mesh;
PMP::polygon_soup_to_polygon_mesh(points, polygons, cgal_mesh);
// 4) Remove degenerate geometry
PMP::remove_degenerate_faces(cgal_mesh);
PMP::remove_isolated_vertices(cgal_mesh);
// 5) Fix remaining non-manifold vertices
PMP::duplicate_non_manifold_vertices(cgal_mesh);
// 6) Boolean union (keeps only outer shell)
_EpicMesh tmp;
if (PMP::corefine_and_compute_union(cgal_mesh, cgal_mesh, tmp)) {
cgal_mesh = std::move(tmp);
}
// If it fails, continue anyway with previous mesh
// 7) Fill holes
if (!CGAL::is_closed(cgal_mesh)) {
using halfedge_descriptor = boost::graph_traits<_EpicMesh>::halfedge_descriptor;
std::vector<halfedge_descriptor> borders;
CGAL::extract_boundary_cycles(cgal_mesh, std::back_inserter(borders));
for (halfedge_descriptor h : borders) {
PMP::triangulate_and_refine_hole(cgal_mesh, h);
}
}
// 8) Final validity check
if (!CGAL::is_closed(cgal_mesh)) {
if (error)
*error = "Repair failed: mesh still open after hole filling.";
return false;
}
// 9) Ensure outward orientation
if (!PMP::does_bound_a_volume(cgal_mesh))
PMP::orient_to_bound_a_volume(cgal_mesh);
// 10) Convert back
indexed_triangle_set its = cgal_to_indexed_triangle_set(cgal_mesh);
RepairedMeshErrors errs{};
errs.facets_removed = 0;
errs.edges_fixed = 0;
mesh = TriangleMesh(std::move(its), errs);
if (repaired_errors)
*repaired_errors = errs;
return true;
} catch (const std::exception& e) {
if (error)
*error = e.what();
return false;
}
}
CGALMeshPtr clone(const CGALMesh &m)
{
return CGALMeshPtr{new CGALMesh{m}};
-3
View File
@@ -77,9 +77,6 @@ TriangleMesh merge(std::vector<TriangleMesh> meshes);
bool does_bound_a_volume(const CGALMesh &mesh);
bool empty(const CGALMesh &mesh);
// Repair a mesh using CGAL. Returns true on success. Optionally returns a summary of repairs and an error string.
bool repair(TriangleMesh &mesh, RepairedMeshErrors *repaired_errors = nullptr, std::string *error = nullptr);
// Real UV unwrap of an open mesh patch via CGAL's LSCM (Least Squares Conformal Maps) surface
// parameterization. Returns one UV coordinate per input vertex (same indexing as `mesh.vertices`),
// or nullopt if `mesh` isn't a single topological disk -- LSCM needs exactly one connected
File diff suppressed because it is too large Load Diff
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include <cstddef>
#include <functional>
#include <string>
namespace Slic3r {
class TriangleMesh;
struct MeshRepairStats
{
std::size_t welded_vertices = 0;
std::size_t removed_triangles = 0;
std::size_t reversed_shells = 0;
std::size_t filled_holes = 0;
std::size_t removed_shells = 0;
std::size_t self_intersections = 0;
// False when the input already was closed, consistently oriented and free of self-intersections.
bool modified = false;
};
// Returns false, leaving the mesh untouched, if no solid can be built. progress gets the percentage done and may
// throw to cancel. See docs/HLSD/mesh-repair.md.
bool repair_mesh(TriangleMesh &mesh, MeshRepairStats *stats = nullptr, std::string *error = nullptr,
const std::function<void(int)> &progress = {});
} // namespace Slic3r
+39 -44
View File
@@ -29,6 +29,7 @@
#include "TriangleMeshSlicer.hpp"
#include "TriangleSelector.hpp"
#include "MaterialType.hpp"
#include "MeshRepair.hpp"
#include "Format/AMF.hpp"
#include "Format/svg.hpp"
@@ -353,24 +354,6 @@ Model Model::read_from_file(const std::string&
ObjInfo obj_info;
ObjParser::MtlData mtl_data;
result = load_obj(input_file.c_str(), &model, obj_info, message, nullptr, &mtl_data);
// Keep the model's own UV channel on the volume, whatever the colour import then does with
// the mesh: it is what TextureProjectionMethod::ModelUV maps a texture-displacement layer
// through, so a model that arrives with a UV layout is textured on that layout instead of on
// a fresh unwrap. load_obj() fills obj_info.uvs per face of the mesh it built, in the same
// order (and only when every face named a known material, hence the size check). V is flipped
// on the way in, to the convention DecodedHeightTexture samples in - the same flip
// obj_to_textured_mesh() does for the colour importer.
if (result && !obj_info.uvs.empty() && !model.objects.empty() && !model.objects.back()->volumes.empty()) {
ModelVolume &volume = *model.objects.back()->volumes[0];
const indexed_triangle_set &its = volume.mesh().its;
if (obj_info.uvs.size() == its.indices.size()) {
volume.texture_uv.resize(its.indices.size() * 3);
for (size_t fi = 0; fi < obj_info.uvs.size(); ++fi)
for (int k = 0; k < 3; ++k)
volume.texture_uv[fi * 3 + size_t(k)] =
Vec2f(obj_info.uvs[fi][size_t(k)].x(), 1.f - obj_info.uvs[fi][size_t(k)].y());
}
}
if (result && obj_info.has_uv_png && !obj_info.uvs.empty() && !model.objects.empty()) {
// Textured OBJ: hand the mesh + materials to the texture-to-color importer
// instead of the flat per-face colour dialog.
@@ -2151,10 +2134,6 @@ void ModelVolume::reset_extra_facets()
// than left referring to a mesh that no longer matches it.
for (int i = 0; i < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++i)
this->texture_displacement_facet(i).reset();
// Same reasoning for the model's own UV channel: it is indexed by triangle, so against a mesh
// this no longer matches it would map the texture by another mesh's triangle numbering. A caller
// that can carry it across - see transfer_uv_channel() - puts it back after this.
this->reset_texture_uv();
}
std::optional<TriangleSelector::SavedPainting> ModelVolume::save_painting() const
@@ -2968,6 +2947,18 @@ size_t ModelVolume::split(unsigned int max_extruders, bool remap_paint)
if (text_configuration.has_value())
text_configuration.reset();
// Parts without a convex hull enclose no volume; drop them here, as deleting volumes later could delete this one.
std::vector<std::unique_ptr<ModelVolume>> parts;
for (TriangleMesh &mesh : meshes)
if (!mesh.empty()) {
std::unique_ptr<ModelVolume> part(new ModelVolume(object, *this, std::move(mesh)));
if (const std::shared_ptr<const TriangleMesh> &hull = part->get_convex_hull_shared_ptr();
hull != nullptr && !hull->its.vertices.empty() && !hull->its.indices.empty())
parts.emplace_back(std::move(part));
}
if (parts.empty())
return 1;
std::optional<TriangleSelector::SavedPainting> saved_painting = remap_paint ? save_painting() :
std::optional<TriangleSelector::SavedPainting>{};
@@ -2978,26 +2969,22 @@ size_t ModelVolume::split(unsigned int max_extruders, bool remap_paint)
unsigned int extruder_counter = 0;
const Vec3d offset = this->get_offset();
for (TriangleMesh &mesh : meshes) {
if (mesh.empty())
// Repair may have removed unconnected triangles, thus emptying the mesh.
continue;
for (std::unique_ptr<ModelVolume> &part : parts) {
if (idx == 0) {
this->set_mesh(std::move(mesh));
this->calculate_convex_hull();
this->set_mesh(part->m_mesh);
m_convex_hull = part->m_convex_hull;
this->invalidate_convex_hull_2d();
// Assign a new unique ID, so that a new GLVolume will be generated.
this->set_new_unique_id();
// reset the source to disable reload from disk
this->source = ModelVolume::Source();
// BBS: reset facet annotations
this->reset_extra_facets();
}
else
this->object->volumes.insert(this->object->volumes.begin() + (++ivolume), new ModelVolume(object, *this, std::move(mesh)));
this->object->volumes.insert(this->object->volumes.begin() + (++ivolume), part.release());
// reset the source to disable reload from disk
this->object->volumes[ivolume]->source = ModelVolume::Source();
this->object->volumes[ivolume]->set_offset(Vec3d::Zero());
this->object->volumes[ivolume]->center_geometry_after_creation();
this->object->volumes[ivolume]->translate(offset);
@@ -3011,21 +2998,29 @@ size_t ModelVolume::split(unsigned int max_extruders, bool remap_paint)
++ idx;
}
// discard volumes for which the convex hull was not generated or is degenerate
size_t i = 0;
while (i < this->object->volumes.size()) {
const std::shared_ptr<const TriangleMesh> &hull = this->object->volumes[i]->get_convex_hull_shared_ptr();
if (hull == nullptr || hull->its.vertices.empty() || hull->its.indices.empty()) {
this->object->delete_volume(i);
--idx;
--i;
}
++i;
}
return idx;
}
bool ModelVolume::repair(bool keep_painting, MeshRepairStats *stats_out, std::string *error, const std::function<void(int)> &progress)
{
TriangleMesh mesh = this->mesh();
MeshRepairStats stats;
const bool ok = repair_mesh(mesh, &stats, error, progress);
if (stats_out)
*stats_out = stats;
if (!ok || !stats.modified)
return ok;
const std::optional<TriangleSelector::SavedPainting> saved_painting = keep_painting ? save_painting() : std::nullopt;
this->set_mesh(std::move(mesh));
this->calculate_convex_hull();
this->invalidate_convex_hull_2d();
// Assign a new unique ID, so that a new GLVolume will be generated.
this->set_new_unique_id();
this->restore_painting(saved_painting);
return true;
}
void ModelVolume::translate(const Vec3d& displacement)
{
set_offset(get_offset() + displacement);
+13 -30
View File
@@ -77,6 +77,7 @@ class Preset;
class BBLProject;
class KeyStore;
struct MeshRepairStats;
namespace UndoRedo {
class StackImpl;
@@ -887,13 +888,13 @@ public:
// The triangular model.
const TriangleMesh& mesh() const { return *m_mesh.get(); }
std::shared_ptr<const TriangleMesh> mesh_ptr() const { return m_mesh; }
void set_mesh(const TriangleMesh &mesh) { m_mesh = std::make_shared<const TriangleMesh>(mesh); }
void set_mesh(TriangleMesh &&mesh) { m_mesh = std::make_shared<const TriangleMesh>(std::move(mesh)); }
void set_mesh(const indexed_triangle_set &mesh) { m_mesh = std::make_shared<const TriangleMesh>(mesh); }
void set_mesh(indexed_triangle_set &&mesh) { m_mesh = std::make_shared<const TriangleMesh>(std::move(mesh)); }
void set_mesh(std::shared_ptr<const TriangleMesh> &mesh) { m_mesh = mesh; }
void set_mesh(std::unique_ptr<const TriangleMesh> &&mesh) { m_mesh = std::move(mesh); }
void reset_mesh() { m_mesh = std::make_shared<const TriangleMesh>(); }
void set_mesh(const TriangleMesh &mesh) { m_mesh = std::make_shared<const TriangleMesh>(mesh); m_is_splittable = -1; }
void set_mesh(TriangleMesh &&mesh) { m_mesh = std::make_shared<const TriangleMesh>(std::move(mesh)); m_is_splittable = -1; }
void set_mesh(const indexed_triangle_set &mesh) { m_mesh = std::make_shared<const TriangleMesh>(mesh); m_is_splittable = -1; }
void set_mesh(indexed_triangle_set &&mesh) { m_mesh = std::make_shared<const TriangleMesh>(std::move(mesh)); m_is_splittable = -1; }
void set_mesh(std::shared_ptr<const TriangleMesh> &mesh) { m_mesh = mesh; m_is_splittable = -1; }
void set_mesh(std::unique_ptr<const TriangleMesh> &&mesh) { m_mesh = std::move(mesh); m_is_splittable = -1; }
void reset_mesh() { m_mesh = std::make_shared<const TriangleMesh>(); m_is_splittable = -1; }
const std::shared_ptr<const TriangleMesh>& get_mesh_shared_ptr() const { return m_mesh; }
// Configuration parameters specific to an object model geometry or a modifier volume,
// overriding the global Slic3r settings and the ModelObject settings.
@@ -974,26 +975,6 @@ public:
// they are not a property of any single layer.
TextureDisplacementOptions texture_displacement_options;
// The model's own texture coordinates, as the file it was imported from carried them: three per
// triangle of mesh().its, in its triangle order (corner k of triangle i at 3i+k), V already
// flipped to the sampling convention (V = 0 is the image's top row). Empty when the source had
// none, which is every STL and every 3mf - only a textured OBJ brings one in today.
//
// Per corner rather than per vertex because that is what a UV layout is: the two sides of a seam
// are the same vertex with two different coordinates, and collapsing them would smear the texture
// across every island boundary. TextureProjectionMethod::ModelUV maps through it, which is what
// lets a model that already carries a UV channel be textured on the artist's own layout instead
// of on a fresh unwrap.
//
// Indexed by triangle, so anything that *replaces* the mesh has to bring it across (or drop it):
// see transfer_uv_channel(), and reset_texture_uv() for the cases that cannot.
std::vector<Vec2f> texture_uv;
bool has_texture_uv() const { return !texture_uv.empty() && texture_uv.size() == mesh().its.indices.size() * 3; }
// Forgets the channel. For a mesh change that nothing can carry it across - a split, a boolean -
// where leaving it would map the texture by another mesh's triangle numbering.
void reset_texture_uv() { texture_uv.clear(); }
// Save painting data before reset_extra_facets() discards it.
// Used for replacing mesh without losing painting data.
// Only for model parts (not modifiers/connectors).
@@ -1063,6 +1044,9 @@ public:
// Return the number of volumes created from this one.
// This is useful to assign different materials to different volumes of an object.
size_t split(unsigned int max_extruders, bool remap_paint);
// Replaces the mesh by its repair_mesh() result if that changed it. False if no solid can be built.
bool repair(bool keep_painting, MeshRepairStats *stats = nullptr, std::string *error = nullptr,
const std::function<void(int)> &progress = {});
void translate(double x, double y, double z) { translate(Vec3d(x, y, z)); }
void translate(const Vec3d& displacement);
void scale(const Vec3d& scaling_factors);
@@ -1256,7 +1240,6 @@ private:
texture_displacement_facets_6(other.texture_displacement_facets_6), texture_displacement_facets_7(other.texture_displacement_facets_7),
texture_displacement_layers(other.texture_displacement_layers),
texture_displacement_options(other.texture_displacement_options),
texture_uv(other.texture_uv),
cut_info(other.cut_info), text_configuration(other.text_configuration), emboss_shape(other.emboss_shape)
{
assert(this->id().valid());
@@ -1355,7 +1338,7 @@ private:
cereal::load_by_value(ar, f);
mesh_changed |= tf != f.timestamp();
}
ar(texture_displacement_layers, texture_displacement_options, texture_uv);
ar(texture_displacement_layers, texture_displacement_options);
cereal::load_by_value(ar, config);
cereal::load(ar, text_configuration);
cereal::load(ar, emboss_shape);
@@ -1379,7 +1362,7 @@ private:
cereal::save_by_value(ar, fuzzy_skin_facets);
for (int i = 0; i < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++i)
cereal::save_by_value(ar, texture_displacement_facet(i));
ar(texture_displacement_layers, texture_displacement_options, texture_uv);
ar(texture_displacement_layers, texture_displacement_options);
cereal::save_by_value(ar, config);
cereal::save(ar, text_configuration);
cereal::save(ar, emboss_shape);
+35 -6
View File
@@ -2164,6 +2164,16 @@ int PresetCollection::get_differed_values_to_update(Preset& preset, std::map<std
DynamicPrintConfig temp_config;
std::vector<std::string> dirty_options = preset.config.diff(parent_preset->config);
// Send the variant layout even when it matches the parent's, as the local save does: the loader
// sizes the per-variant values by it and would otherwise keep only the first one.
std::string extruder_id_name, extruder_variant_name;
std::set<std::string> *key_set1 = nullptr, *key_set2 = nullptr;
Preset::get_extruder_names_and_keysets(m_type, extruder_id_name, extruder_variant_name, &key_set1, &key_set2);
if (!extruder_id_name.empty())
dirty_options.emplace_back(extruder_id_name);
if (!extruder_variant_name.empty())
dirty_options.emplace_back(extruder_variant_name);
for (auto option: dirty_options)
{
ConfigOption *opt_src = preset.config.option(option);
@@ -2628,15 +2638,34 @@ bool PresetCollection::load_user_preset(std::string name, std::map<std::string,
new_config = default_preset.config;
}
std::string extruder_id_name, extruder_variant_name;
std::set<std::string> *key_set1 = nullptr, *key_set2 = nullptr;
Preset::get_extruder_names_and_keysets(m_type, extruder_id_name, extruder_variant_name, &key_set1, &key_set2);
// Older uploads left out a variant layout equal to the parent's but still sent one value per
// parent variant. Read those values against the parent's layout instead of cutting them to one.
if (inherit_preset && !cloud_config.has(extruder_variant_name)) {
const auto *parent_variants = inherit_preset->config.option<ConfigOptionStrings>(extruder_variant_name);
const size_t variant_count = parent_variants ? parent_variants->size() : 0;
bool values_per_variant = false;
for (const std::string &key : cloud_config.keys()) {
const size_t stride = key_set2->count(key) ? 2 : key_set1->count(key) ? 1 : 0;
const auto *values = dynamic_cast<const ConfigOptionVectorBase *>(cloud_config.option(key));
if (stride > 0 && key != extruder_id_name && values && variant_count > 1 && values->size() == variant_count * stride) {
values_per_variant = true;
break;
}
}
if (values_per_variant)
for (const std::string &key : {extruder_id_name, extruder_variant_name})
if (!key.empty() && !cloud_config.has(key) && inherit_preset->config.has(key))
cloud_config.set_key_value(key, inherit_preset->config.option(key)->clone());
}
extend_default_config_length(cloud_config, false, {});
if (inherit_preset) {
std::string extruder_id_name, extruder_variant_name;
std::set<std::string> *key_set1 = nullptr, *key_set2 = nullptr;
Preset::get_extruder_names_and_keysets(m_type, extruder_id_name, extruder_variant_name, &key_set1, &key_set2);
if (inherit_preset)
new_config.update_diff_values_to_child_config(cloud_config, extruder_id_name, extruder_variant_name, *key_set1, *key_set2);
}
else{
new_config.apply(std::move(cloud_config));
extend_default_config_length(new_config, true, default_preset.config);
+9
View File
@@ -2991,6 +2991,15 @@ void PrintObject::clear_shared_object()
void PrintObject::copy_layers_from_shared_object()
{
if (m_shared_object) {
// Orca: Print::process() calls this once per slice for each sharing object, after clear_shared_object() has
// emptied any earlier alias, so the vectors hold only layers this object sliced itself before it started sharing
// (or nothing). Free them here, as clear_support_layers() / clear_layers() would; those skip deletion while
// m_shared_object is set. The belt-only data they also free is always empty here, because belt printers never
// share layers.
for (SupportLayer *layer : m_support_layers)
delete layer;
for (Layer *layer : m_layers)
delete layer;
m_layers.clear();
m_support_layers.clear();
+5 -4
View File
@@ -12866,10 +12866,11 @@ CLITransformConfigDef::CLITransformConfigDef()
//def->cli = "orient|o";
def->set_default_value(new ConfigOptionInt(0));
/*def = this->add("repair", coBool);
def = this->add("repair", coBool);
def->label = L("Repair");
def->tooltip = L("Repair the model's meshes if it is non-manifold mesh.");
def->set_default_value(new ConfigOptionBool(false));*/
def->tooltip = L("Repair the meshes of the models as Fix Model does: close holes and cracks, orient them outward and "
"remove self-intersections.");
def->set_default_value(new ConfigOptionBool(false));
def = this->add("rotate", coFloat);
def->label = L("Rotate");
@@ -13085,7 +13086,7 @@ CLIMiscConfigDef::CLIMiscConfigDef()
def = this->add("allow_rotations", coBool);
def->label = L("Allow rotation when arranging");
def->tooltip = L("If enabled, Arrange will allow rotation when placing objects.");
def->set_default_value(new ConfigOptionBool(true));
def->set_default_value(new ConfigOptionBool(false));
def = this->add("align_to_y_axis", coBool);
def->label = L("Align to Y axis when arranging");
+3
View File
@@ -982,6 +982,9 @@ void PrintObject::generate_support_material(bool with_belt_brim)
this->_generate_support_material();
m_print->throw_if_canceled();
}
// Orca: the tree support collision/avoidance caches and support nodes are only used while this step runs
// (detect_overhangs() rebuilds them from scratch), so don't keep them resident until the next slice.
this->clear_tree_support_preview_cache();
// Belt brim rides here rather than in the brim step because its apron
// prologue introduces print_z values below the object's first layer, and
// those must exist before ToolOrdering is built at psWipeTower - one step
+1 -1
View File
@@ -1532,7 +1532,7 @@ void PrintObject::slice_volumes()
if (min_growth < 0.f || elfoot > 0.f) {
// Apply the negative XY compensation. (the ones that is <0)
ExPolygons trimming;
static const float eps = float(scale_(m_config.slice_closing_radius.value) * 1.5);
const float eps = float(scale_(m_config.slice_closing_radius.value) * 1.5);
if (elfoot > 0.f) {
ExPolygons expolygons_to_compensate = offset_ex(layer->merged(eps), -eps);
lslices_elfoot_uncompensated[layer_id] = expolygons_to_compensate;
+13 -30
View File
@@ -1976,37 +1976,15 @@ coordf_t TreeSupport::get_radius(const SupportNode* node)
return node->radius;
}
ExPolygons TreeSupport::get_avoidance(coordf_t radius, size_t obj_layer_nr)
// Orca: drop_nodes() calls these several times per node per layer, so they return a reference into the
// TreeSupportData cache. The cache only ever inserts, so its entries never move while nodes drop in parallel.
const ExPolygons& TreeSupport::get_avoidance(coordf_t radius, size_t obj_layer_nr)
{
#if USE_SUPPORT_3D
if (m_model_volumes) {
bool on_build_plate = m_object_config->support_on_build_plate_only.value;
const Polygons& avoid_polys = m_model_volumes->getAvoidance(radius, obj_layer_nr, TreeSupport3D::TreeModelVolumes::AvoidanceType::FastSafe, on_build_plate, true);
ExPolygons expolys;
for (auto& poly : avoid_polys)
expolys.emplace_back(std::move(poly));
return expolys;
}
return ExPolygons();
#else
return m_ts_data->get_avoidance(radius, obj_layer_nr);
#endif
}
ExPolygons TreeSupport::get_collision(coordf_t radius, size_t layer_nr)
const ExPolygons& TreeSupport::get_collision(coordf_t radius, size_t layer_nr)
{
#if USE_SUPPORT_3D
if (m_model_volumes) {
bool on_build_plate = m_object_config->support_on_build_plate_only.value;
const Polygons& collision_polys = m_model_volumes->getCollision(radius, layer_nr, true);
ExPolygons expolys;
for (auto& poly : collision_polys)
expolys.emplace_back(std::move(poly));
return expolys;
}
#else
return m_ts_data->get_collision(radius, layer_nr);
#endif
return ExPolygons();
}
Polygons TreeSupport::get_collision_polys(coordf_t radius, size_t layer_nr)
{
@@ -2827,7 +2805,12 @@ void TreeSupport::draw_circles()
#endif // SUPPORT_TREE_DEBUG_TO_SVG
SupportLayerPtrs& ts_layers = m_object->support_layers();
auto iter = std::remove_if(ts_layers.begin(), ts_layers.end(), [](SupportLayer* ts_layer) { return ts_layer->height < EPSILON; });
// Orca: the vector owns its layers, so the dropped ones are deleted before they are erased.
// std::stable_partition (unlike std::remove_if) leaves exactly the dropped layers in the tail.
// Only heights below EPSILON are dropped; written as !(height < EPSILON), a NaN height is kept.
auto iter = std::stable_partition(ts_layers.begin(), ts_layers.end(), [](SupportLayer* ts_layer) { return !(ts_layer->height < EPSILON); });
for (auto it = iter; it != ts_layers.end(); ++it)
delete *it;
ts_layers.erase(iter, ts_layers.end());
for (int layer_nr = 0; layer_nr < ts_layers.size(); layer_nr++) {
ts_layers[layer_nr]->upper_layer = layer_nr != ts_layers.size() - 1 ? ts_layers[layer_nr + 1] : nullptr;
@@ -3071,7 +3054,7 @@ void TreeSupport::drop_nodes()
//Insert a completely new node and let both original nodes fade.
Point next_position = (node.position + neighbours[0]) / 2; //Average position of the two nodes.
coordf_t next_radius = calc_radius(node.dist_mm_to_top+height_next);
auto avoid_layer = get_avoidance(next_radius, obj_layer_nr_next);
const ExPolygons& avoid_layer = get_avoidance(next_radius, obj_layer_nr_next);
if (group_index == 0)
{
//Avoid collisions.
@@ -3275,7 +3258,7 @@ void TreeSupport::drop_nodes()
}
#endif
coordf_t next_radius = calc_radius(node.dist_mm_to_top + height_next);
auto avoidance_next = get_avoidance(next_radius, obj_layer_nr_next);
const ExPolygons& avoidance_next = get_avoidance(next_radius, obj_layer_nr_next);
Point to_outside = projection_onto(avoidance_next, node.position);
Point direction_to_outer = to_outside - node.position;
@@ -3337,7 +3320,7 @@ void TreeSupport::drop_nodes()
p_node->to_buildplate = false;
return; // from parallel_for_each lambda
}
auto next_collision = get_collision(0, obj_layer_nr_next);
const ExPolygons& next_collision = get_collision(0, obj_layer_nr_next);
const bool to_buildplate = !is_inside_ex(m_ts_data->m_layer_outlines[obj_layer_nr_next], next_layer_vertex);
// don't increase radius if next node will collide partially with the object (STUDIO-7883)
to_outside = projection_onto(next_collision, next_layer_vertex);
+2 -2
View File
@@ -536,9 +536,9 @@ private:
coordf_t calc_branch_radius(coordf_t base_radius, coordf_t mm_to_top, double diameter_angle_scale_factor, bool use_min_distance=true);
coordf_t calc_radius(coordf_t mm_to_top);
coordf_t get_radius(const SupportNode* node);
ExPolygons get_avoidance(coordf_t radius, size_t obj_layer_nr);
const ExPolygons& get_avoidance(coordf_t radius, size_t obj_layer_nr);
// layer's expolygon expanded by radius+m_xy_distance
ExPolygons get_collision(coordf_t radius, size_t layer_nr);
const ExPolygons& get_collision(coordf_t radius, size_t layer_nr);
// get Polygons instead of ExPolygons
Polygons get_collision_polys(coordf_t radius, size_t layer_nr);
File diff suppressed because it is too large Load Diff
+95 -118
View File
@@ -86,17 +86,6 @@ enum class TextureProjectionMethod : int
// that is inherent to view projection and is the user's call, not a bug. The projector's two
// in-plane axes live in TextureDisplacementLayer::view_project_right/up.
ViewProjected = 4,
// The model's own texture coordinates, as the file it was imported from carried them (see
// ModelVolume::texture_uv). Nothing is unwrapped or projected: the artist's layout *is* the
// placement, so a texture authored against that layout - the model's own albedo map, say - lands
// exactly where it was painted. Automatically picked for a new layer on a volume that has a UV
// channel, since re-unwrapping a model that already carries one can only be worse than using it.
//
// The uv is already normalized, so unlike every method above it is not measured in millimetres:
// "Tile size" and the non-square aspect correction do not apply to it (the layer's rotation and
// offset still do). Falls back to Triplanar when the volume has no channel, exactly as LSCM falls
// back when a patch cannot be flattened.
ModelUV = 5,
};
// Dihedral angle (degrees) above which an edge between two painted triangles becomes a chart seam
@@ -132,11 +121,6 @@ enum class TextureBlendMode : int
Subtract = 1, // acc - value (carve this layer's relief out of the layers below)
Multiply = 2, // acc * (value / 1mm) (mask/modulate the layers below by this layer)
Divide = 3, // acc / (value / 1mm) (inverse mask; guarded against a zero/near-zero divisor)
// acc = value: this layer replaces what is under it instead of combining with it, so where it is
// painted only its own relief remains. The image editor's "Normal" mode, under the name the panel
// uses. Note the stack's *colour* already behaves this way - a higher slot's colour overwrites a
// lower one's where they overlap - so this is what makes the displacement agree with it.
Override = 4,
};
// Combines one layer's signed displacement `value` (mm) into `accumulated` (mm) per `mode`.
@@ -170,6 +154,38 @@ struct TextureIsland
// chart to its true mm area, so a freshly unwrapped patch has uniform texel density to begin with.
void average_island_scales(std::vector<TextureIsland> &islands);
// Photo-style adjustments to a layer's source image, as the gizmo's image-adjustment panel sets them.
//
// These are *not* layer parameters: nothing here is stored on TextureDisplacementLayer and nothing here is
// re-applied at bake time. The panel applies them once, to the image, and the result becomes the layer's
// image - so the adjusted pixels feed the colour and the displacement together, and a brightness change
// really does change the relief. That is the intended behaviour: one image, one source of truth, rather
// than a second set of knobs the bake would have to replay in the right order.
//
// Contrast with TextureDisplacementLayer::smoothing, which *is* a layer parameter applied on every decode:
// `blur` here is a destructive edit of the image, `smoothing` is a live low-pass over whatever the image is.
struct TextureAdjustments
{
float brightness = 0.f; // [-1, 1]; 0 unchanged, -1 black, +1 white
float contrast = 0.f; // [-1, 1]; 0 unchanged, -1 flat mid-grey, +1 hard threshold
float sharpness = 0.f; // [0, 1]; 0 unchanged. Unsharp-mask amount
float blur = 0.f; // [0, 1]; 0 unchanged. Fraction of SOURCE_BLUR_SPAN, as `smoothing` is
float hue_deg = 0.f; // [-180, 180]; 0 unchanged. No effect on a grayscale image - grey has no hue
bool identity() const
{
return brightness == 0.f && contrast == 0.f && sharpness == 0.f && blur == 0.f && hue_deg == 0.f;
}
// Exact equality, which is what is wanted: these come straight off sliders, and the question asked of
// them is "is this still the value the preview on screen was computed from", not "are these close".
bool operator==(const TextureAdjustments &o) const
{
return brightness == o.brightness && contrast == o.contrast && sharpness == o.sharpness &&
blur == o.blur && hue_deg == o.hue_deg;
}
bool operator!=(const TextureAdjustments &o) const { return !(*this == o); }
};
// One texture asset plus its projection/displacement parameters. Several layers may be painted
// onto overlapping areas of the same volume: their displacements are combined per vertex, in slot
// order, each layer folding into the total via its own TextureBlendMode (see
@@ -293,6 +309,18 @@ struct TextureDisplacementLayer
// - zero or positive: a mesh vertex, every unwrapped copy of it (how edits were stored before).
std::vector<std::pair<int, Vec2f>> lscm_uv_overrides;
// Live, unsaved image adjustments from the gizmo's image-adjustment panel, applied by
// decode_height_texture() on top of the decoded image - so while the panel is open the relief, the
// colour, the thumbnails and the bake all see the adjusted image, and moving a slider really does
// change the displacement. See TextureAdjustments.
//
// Deliberately *not* serialized, by either save()/load() here or the .3mf: it is the state of an open
// editor, not a property of the layer. The panel resets it when it closes, and "Save as copy" resolves
// it by writing a new image and pointing the layer at that - which is the only way an adjustment
// becomes permanent. A project saved mid-adjustment therefore stores the unadjusted image, which is
// the honest answer: nothing was committed.
TextureAdjustments preview_adjust;
// How this layer folds into the displacement accumulated by the layers below it. Ignored for
// the lowest-slot painted layer, which has nothing beneath it to combine with (the GUI shows
// it as the "Base" layer and hides the control).
@@ -520,6 +548,36 @@ struct DecodedHeightTexture
bool texel_tap(const Vec2f &uv, bool tile_enabled, TextureTileMethod tile_method, TexelTap &out) const;
};
// Applies `adj` to `src` and returns the result; `src` is left alone. An empty `src`, or an identity
// `adj`, gives back a copy.
//
// Order is tonal, then spatial: brightness, contrast and hue per texel first, then blur, then sharpness.
// Sharpness last is what lets the two spatial knobs be used together - blur to kill speckle, then
// sharpness to put the real edges back - instead of the blur simply undoing the sharpen.
//
// Grayscale in, grayscale out (`rgb` stays empty): promoting a grey image to RGB would hand the layer's
// colour feature a row of identical greys to "colour" the model with, and triple the stored PNG for it.
// For a colour image the height is recomputed as the luminance of the *adjusted* colour, with
// decode_height_texture()'s own coefficients, so the relief and the colour can never drift apart.
DecodedHeightTexture apply_texture_adjustments(const DecodedHeightTexture &src, const TextureAdjustments &adj);
// Blur radius, in texels, that TextureAdjustments::blur == 1 means on a `min(width, height)`-sized image:
// the same 5%-of-the-short-side span the Smoothing slider uses, under the same 48-texel cost cap, so the
// two controls bite at the same rate and a user moving between them is not surprised.
float adjustment_blur_radius(float blur, int width, int height);
// Box-filters `src` down so neither side exceeds `max_px`, preserving aspect; never upscales, and
// returns a copy when it already fits. Colour and height are filtered the same way, and the height
// stays the height - it is not recomputed from the filtered colour, because a box filter is linear and
// luminance is linear in the channels, so the two agree already.
//
// This is what lets the adjustment panel's live preview cost depend on the size of the box it is drawn
// in rather than on the size of the image: adjusting a downscaled copy per slider frame, and the
// full-size image only once, on commit. A box filter (rather than a plain decimation) is the point -
// these textures are high-frequency by nature, and dropping texels would alias the preview into
// showing detail the adjustment is not actually producing.
DecodedHeightTexture downscale_height_texture(const DecodedHeightTexture &src, int max_px);
// Decode a layer's raw image bytes into sampleable height data, plus colour when the source has any.
// Both 8-bit grayscale PNGs (the shipped library, and anything imported before colour was kept) and
// colour PNGs are accepted; for a colour source the height is its luminance, using the same
@@ -567,11 +625,24 @@ struct TextureColorSettings
bool empty() const { return palette.empty(); }
};
// The two world directions the box projection takes its u and v along on a face whose outward
// normal is `normal`: the plane is the one that normal is closest to, and the pair is oriented as a
// viewer standing outside the model sees it - u to their right, v *down* the image, which is the
// direction v runs in the texture (v = 0 is the image's first pixel row, see
// DecodedHeightTexture::sample()). So an image comes out the way it looks in a file manager rather
// than upside down, and it is not mirrored on the three faces facing the other way.
//
// Exposed because the GUI needs the same basis for the on-canvas "adjust texture placement" gizmo
// (its ring's zero angle and its offset handle's plane), and it must not be a second, drifting copy
// of the table.
void box_projection_axes(const Vec3f &normal, Vec3f &u_axis, Vec3f &v_axis);
// Raw dominant-axis planar projection of `position` (in mm, not yet scaled/rotated/offset by any
// layer), dropping the axis position that best aligns with `normal`. Exposed on its own (rather
// than only inline inside project_texture_displacement_uv()) so GUI code - the on-canvas
// "adjust texture placement" gizmo - can map a dragged 3D point into the exact same 2D space
// tiling_scale/rotation_deg/offset operate in, without duplicating the axis-selection logic.
// layer), dropping the axis position that best aligns with `normal`. Equivalent to projecting onto
// box_projection_axes()' pair. Exposed on its own (rather than only inline inside
// project_texture_displacement_uv()) so GUI code - the on-canvas "adjust texture placement" gizmo -
// can map a dragged 3D point into the exact same 2D space tiling_scale/rotation_deg/offset operate
// in, without duplicating the axis-selection logic.
Vec2f project_planar(const Vec3f &position, const Vec3f &normal);
// Applies a layer's tiling_scale/rotation_deg/offset to an already-projected planar coordinate
@@ -584,13 +655,7 @@ Vec2f project_planar(const Vec3f &position, const Vec3f &normal);
// squeezed into a square tile: `tiling_scale` is the tile's size along u, and the tile is
// `tiling_scale * height / width` mm along v, which keeps texels square. 1 (the default) is the
// square case and leaves the coordinate exactly as it always was.
//
// `normalized_uv` says the coordinate is already a uv rather than a millimetre measurement on the
// model - which is what TextureProjectionMethod::ModelUV hands in. Then neither the tiling scale (mm
// per tile is meaningless for it) nor the aspect correction (the artist's layout already accounts for
// the image's proportions) applies, and only the rotation and offset are left.
Vec2f apply_uv_transform(const Vec2f &planar, const TextureDisplacementLayer &layer, float aspect = 1.f,
bool normalized_uv = false);
Vec2f apply_uv_transform(const Vec2f &planar, const TextureDisplacementLayer &layer, float aspect = 1.f);
// Applies a row-major 3x4 projective matrix (see TextureDisplacementLayer::view_project_matrix) to a
// local-space point, writing the resulting texture uv. Returns false - and leaves `uv` untouched -
@@ -627,31 +692,6 @@ bool sample_layer_color(const DecodedHeightTexture &texture, const TextureDispla
const Vec3f &patch_center = Vec3f::Zero(), const Vec3f &patch_axis = Vec3f::UnitZ(),
const Vec2f *lscm_uv = nullptr);
// Carries a per-facet paint annotation - the colour paint above all - from a mesh onto the mesh a
// bake produced from it: every triangle of `dst_mesh` takes the state painted at its own foot point on
// `src_mesh`, i.e. on the nearest point of the surface it was built from. Returned as one
// EnforcerBlockerType per `dst_mesh` triangle, 0 (NONE) where that foot point carried no paint.
//
// ModelVolume::restore_painting() cannot do this. Its remap pairs a source paint triangle with a
// target triangle that *overlaps* it to within 0.01 mm, which is right for a remesh or a
// simplification - they leave the surface where it was - and useless after a bake, which moves the
// surface by the relief depth. Measured on a model displaced by a tenth of its own size, that remap
// kept a quarter of the colour and left the rest unpainted; this keeps essentially all of it, because
// a foot point is exactly as far away as the relief is deep and the lookup does not care how far that
// is.
//
// The source's *sub*-triangles are what is looked up, not its triangles, so the part of a triangle a
// brush stroke only clipped a corner off keeps its own state rather than rounding to the whole
// triangle's. No distance limit is needed or wanted: the nearest point on the source surface is where
// a baked triangle came from however far the relief carried it, and an unpainted origin reports NONE
// on its own.
//
// Returns an empty vector when `src_paint` is empty or either mesh is - the caller then has nothing to
// carry, which is not the same as "carry nothing".
std::vector<uint8_t> transfer_facet_paint(const indexed_triangle_set &src_mesh,
const TriangleSelector::TriangleSplittingData &src_paint,
const indexed_triangle_set &dst_mesh);
// Area-weighted centroid and average normal of a layer's currently painted patch, in mesh-local
// coordinates - the same measurements build_texture_displacement() uses to pick its dominant
// projection axis. Used by the GUI to anchor the on-canvas "adjust texture placement" gizmo to
@@ -765,55 +805,6 @@ std::vector<Vec2f> compute_lscm_uvs(const indexed_triangle_set &patch, const Tex
// Returns an empty vector if the patch has no triangles or the unwrap carries no source_face map.
std::vector<Vec2f> compute_lscm_corner_uvs(const indexed_triangle_set &patch, const TextureDisplacementLayer &layer);
// Three UVs per patch triangle, read out of the model's *own* UV channel - the
// TextureProjectionMethod::ModelUV counterpart of compute_lscm_corner_uvs(), and laid out the same way
// (corner k of triangle i at index 3i+k).
//
// `model_uv` is the volume's channel: three uvs per triangle of `base_mesh`, in its triangle order
// (see ModelVolume::texture_uv). `patch_source` maps each patch triangle back to the base-mesh
// triangle it was cut from - TriangleSelector::get_facets_strict()'s out_source. A patch triangle is
// always a piece of exactly one base triangle, so each of its corners is interpolated barycentrically
// inside that triangle's three uvs. That is what keeps a sub-triangle the brush split (whose corners
// are not base-mesh vertices at all) on the texture, and what keeps the two sides of a UV seam
// reading from their own island instead of from one averaged coordinate.
//
// Returns an empty vector when the channel does not match `base_mesh`, when `patch_source` does not
// match `patch`, or when either is empty - the callers treat that as "no placement" and fall back,
// exactly as they do for an unwrap that failed.
std::vector<Vec2f> compute_model_corner_uvs(const indexed_triangle_set &base_mesh,
const std::vector<Vec2f> &model_uv,
const indexed_triangle_set &patch,
const std::vector<int> &patch_source);
// One UV per patch vertex, collapsed from a per-corner array: the first corner to reach a vertex wins.
// This is the per-corner/per-vertex split compute_lscm_uvs() documents, applied to any corner array -
// displacement is per-vertex, so a vertex on a seam has to settle on one of its copies.
// Returns an empty vector if `corner` is not three per patch triangle.
std::vector<Vec2f> collapse_corner_uvs(const indexed_triangle_set &patch, const std::vector<Vec2f> &corner);
// Resamples a per-corner UV channel from `src_mesh` onto `dst_mesh`, for when something replaces a
// volume's mesh and the model's own UV channel has to come along: the colour import's painted mesh,
// the gizmo's remesh/subdivide, the default bake pipeline's rebuild. Each destination corner takes the
// uv of its closest point on the source surface, interpolated barycentrically inside the source
// triangle it lands on - the same transfer LscmLookup does per point, run over every corner.
//
// Exact wherever the two meshes describe the same surface, which is the case for every caller here
// (they subdivide, repair or displace it, they do not reshape it). A corner that lands nowhere near
// the source - farther than `max_distance` (negative: no limit) - takes (0, 0).
//
// One thing a positional transfer cannot reproduce: a *seam* vertex, where one position carries a
// different uv in each island that meets there. Position alone does not say which island a corner
// belongs to, so corners on a seam all take whichever island the nearest-triangle lookup lands on,
// and the texture can be off by up to one triangle in a band along the island borders. Doing better
// needs a triangle-to-triangle correspondence, which only some of the stages that replace a mesh
// have (a remesh has none at all).
//
// Returns an empty vector when `src_uv` is not three per source triangle, or when either mesh is empty.
std::vector<Vec2f> transfer_uv_channel(const indexed_triangle_set &src_mesh,
const std::vector<Vec2f> &src_uv,
const indexed_triangle_set &dst_mesh,
float max_distance = -1.f);
// The TextureDisplacementLayer::lscm_uv_overrides key for one unwrapped vertex (an index into PatchUnwrap::uvs).
inline int lscm_uv_override_key(int unwrapped_vertex) { return -(unwrapped_vertex + 1); }
@@ -872,10 +863,6 @@ using TextureDisplacementFacetsData = std::array<TriangleSelector::TriangleSplit
//
// `color`, when given, also reports which filament each triangle should print in - see
// TextureColorRequest.
//
// `model_uv`, when given, is the volume's own UV channel (three uvs per base-mesh triangle, see
// ModelVolume::texture_uv) and is what a TextureProjectionMethod::ModelUV layer maps through. A layer
// set to ModelUV without it falls back to Triplanar.
struct TextureColorRequest
{
// RGB -> palette index. Supplied by the GUI, which owns both the perceptual matching and the list
@@ -950,9 +937,7 @@ indexed_triangle_set build_texture_displacement(const indexed_triangle_set
// stage, already brought back into `base_mesh`'s frame.
BakeStageRecorder *debug = nullptr,
// When given, receives what the bake spent.
TextureBakeStats *stats = nullptr,
// The model's own UV channel; see above.
const std::vector<Vec2f> *model_uv = nullptr);
TextureBakeStats *stats = nullptr);
// `volume`'s mesh coordinates -> world millimetres: its first instance's transform times its own.
// The mesh is shared by every instance, so a multi-instance object can only be baked for one of
@@ -1027,15 +1012,11 @@ ColorFieldSampler make_combined_color_sampler(const indexed_triangle_set
const std::vector<TextureDisplacementLayer> &layers,
const TextureDisplacementFacetsData &facets_data,
ColorQuantizeFn quantize,
ColorQuantizeFn quantize_pure = nullptr,
// The model's own UV channel, for ModelUV layers; see
// build_texture_displacement().
const std::vector<Vec2f> *model_uv = nullptr);
ColorQuantizeFn quantize_pure = nullptr);
HeightFieldSampler make_combined_displacement_sampler(const indexed_triangle_set &base_mesh,
const std::vector<TextureDisplacementLayer> &layers,
const TextureDisplacementFacetsData &facets_data,
const std::vector<Vec2f> *model_uv = nullptr);
const TextureDisplacementFacetsData &facets_data);
// Uniformly subdivides `mesh` (every triangle recursively split into 4 via edge midpoints, using a
// shared cache so a midpoint is computed once and reused by both triangles on either side of that
@@ -1240,10 +1221,6 @@ struct TextureDisplacementPrepareResult
{
indexed_triangle_set mesh;
TextureDisplacementFacetsData masks;
// The model's own UV channel, resampled onto `mesh` (see transfer_uv_channel()). Empty when the
// volume had none. Like the masks it is handed back rather than left to the caller to recompute,
// because only the run itself knows which stages replaced the mesh.
std::vector<Vec2f> uv;
// The remesh landed but no layer's paint survived being carried onto it. Nothing is committed:
// everything downstream is driven by that paint, so baking on would bake a flat mesh.
bool paint_lost = false;
-21
View File
@@ -25,7 +25,6 @@
#include "TextureToColor/ColorUtils.hpp"
#include "Model.hpp"
#include "TextureDisplacement.hpp"
#include "TextureToColor/TriMesh.hpp"
#include "TriangleMesh.hpp"
#include "TriangleSelector.hpp"
@@ -555,29 +554,9 @@ bool apply_painted_mesh_to_volume(
<< ", unit_scale=" << unit_scale << ")";
}
// The model's own UV channel is indexed by triangle, and this replaces the triangles, so it has
// to be resampled onto them. Kept rather than dropped because it is the layout the model was
// authored against: a texture-displacement layer set to ModelUV maps through it, and the colour
// import is exactly the path a model that carries one arrives by.
const indexed_triangle_set old_its = volume.has_texture_uv() ? volume.mesh().its : indexed_triangle_set{};
const std::vector<Vec2f> old_uv = volume.texture_uv;
volume.set_mesh(std::move(new_mesh));
volume.calculate_convex_hull();
// Resampled here and not further down, while the two meshes still share a frame: the painted mesh
// was just shifted by the same source.mesh_offset the old one was centred by, so the only thing
// between them is whatever drift the repair introduced. The re-centering below translates the mesh
// again, and a translation is exactly what a closest-point transfer cannot see through - it would
// read every uv off a point that far away. A uv is a coordinate in the texture, so it does not care
// about either shift; it just has to be read before the second one happens.
if (!old_its.indices.empty())
volume.texture_uv = transfer_uv_channel(old_its, old_uv, volume.mesh().its);
else
// No channel to carry, so make sure none is left behind either: a leftover of the right length
// would read as a valid channel against a mesh it was never measured on.
volume.reset_texture_uv();
// Re-center the replaced mesh so its bbox center sits at the origin,
// matching what center_geometry_after_creation did for the original mesh.
// CGAL repair / subdivision may shift the bbox center (drift); without
@@ -673,14 +673,14 @@ static bool repair_cluster_smooth(
[&]() { return cancelled(); }, &repair_error);
if (repaired) {
if (cancelled()) return false;
BOOST_LOG_TRIVIAL(info) << log_prefix << ": Windows 3D mesh repair finished.";
BOOST_LOG_TRIVIAL(info) << log_prefix << ": mesh repair finished.";
if (!resample_face_colors(TriMesh(std::move(repaired_its))))
return false;
} else {
BOOST_LOG_TRIVIAL(warning) << log_prefix << ": Windows 3D mesh repair failed: " << repair_error;
BOOST_LOG_TRIVIAL(warning) << log_prefix << ": mesh repair failed: " << repair_error;
}
} else {
BOOST_LOG_TRIVIAL(info) << log_prefix << ": importing mesh without Windows 3D repair.";
BOOST_LOG_TRIVIAL(info) << log_prefix << ": importing mesh without repair.";
}
}
}
+6 -4
View File
@@ -21,7 +21,9 @@ namespace libvgcode {
// the triangles that share it: the shader runs 8 times per segment instead of 24.
static constexpr const std::array<uint8_t, 8> VERTEX_DATA = { 0, 1, 2, 3, 4, 5, 6, 7 };
static constexpr const std::array<uint8_t, 24> INDEX_DATA = {
// 16-bit indices: GCN 1/2 GPUs have no 8-bit index support, and some of their drivers
// emulate it wrongly in instanced draws.
static constexpr const std::array<uint16_t, 24> INDEX_DATA = {
0, 1, 2, // front spike
0, 2, 3, // front spike
0, 3, 4, // right/bottom body
@@ -37,7 +39,7 @@ void SegmentTemplate::init()
if (m_vao_id != 0)
return;
m_size_in_bytes_gpu += (VERTEX_DATA.size() + INDEX_DATA.size()) * sizeof(uint8_t);
m_size_in_bytes_gpu += VERTEX_DATA.size() * sizeof(uint8_t) + INDEX_DATA.size() * sizeof(uint16_t);
int curr_vertex_array;
glsafe(glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &curr_vertex_array));
@@ -61,7 +63,7 @@ void SegmentTemplate::init()
// and restored together with the vao.
glsafe(glGenBuffers(1, &m_ibo_id));
glsafe(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo_id));
glsafe(glBufferData(GL_ELEMENT_ARRAY_BUFFER, INDEX_DATA.size() * sizeof(uint8_t), INDEX_DATA.data(), GL_STATIC_DRAW));
glsafe(glBufferData(GL_ELEMENT_ARRAY_BUFFER, INDEX_DATA.size() * sizeof(uint16_t), INDEX_DATA.data(), GL_STATIC_DRAW));
glsafe(glBindBuffer(GL_ARRAY_BUFFER, curr_array_buffer));
glsafe(glBindVertexArray(curr_vertex_array));
@@ -94,7 +96,7 @@ void SegmentTemplate::render(size_t count)
glsafe(glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &curr_vertex_array));
glsafe(glBindVertexArray(m_vao_id));
glsafe(glDrawElementsInstanced(GL_TRIANGLES, static_cast<GLsizei>(INDEX_DATA.size()), GL_UNSIGNED_BYTE,
glsafe(glDrawElementsInstanced(GL_TRIANGLES, static_cast<GLsizei>(INDEX_DATA.size()), GL_UNSIGNED_SHORT,
nullptr, static_cast<GLsizei>(count)));
glsafe(glBindVertexArray(curr_vertex_array));
}
+6 -3
View File
@@ -927,15 +927,17 @@ void ViewerImpl::reset()
m_used_extruders.clear();
m_total_time = { 0.0f, 0.0f };
m_travels_time = { 0.0f, 0.0f };
m_vertices.clear();
m_vertices_colors.clear();
// swap rather than clear: these are sized by the print, and a reset means the memory
// should go back, not sit reserved until the next load
std::vector<PathVertex>().swap(m_vertices);
std::vector<float>().swap(m_vertices_colors);
for (std::vector<float>& times : m_layer_start_times)
std::vector<float>().swap(times);
std::vector<uint32_t>().swap(m_layer_first_vertex);
m_layers_in_vertex_order = false;
m_valid_lines_bitset.clear();
// BitSet::clear() only zeroes the bits, it keeps the blocks allocated; load() builds a new
// bitset anyway and it is never read while m_vertices is empty
m_valid_lines_bitset = BitSet<>();
#if VGCODE_ENABLE_COG_AND_TOOL_MARKERS
m_cog_marker.reset();
#endif // VGCODE_ENABLE_COG_AND_TOOL_MARKERS
@@ -1834,6 +1836,7 @@ size_t ViewerImpl::get_used_cpu_memory() const
ret += sizeof(m_extrusion_roles_colors);
ret += sizeof(m_options_colors);
ret += STDVEC_MEMSIZE(m_vertices, PathVertex);
ret += STDVEC_MEMSIZE(m_vertices_colors, float);
for (const std::vector<float>& times : m_layer_start_times)
ret += STDVEC_MEMSIZE(times, float);
ret += STDVEC_MEMSIZE(m_layer_first_vertex, uint32_t);
+4
View File
@@ -1105,6 +1105,10 @@ void ConfigManipulation::toggle_print_fff_options(DynamicPrintConfig *config, in
toggle_field("support_filament", have_support_material || have_skirt);
toggle_line("raft_contact_distance", have_raft && !have_support_soluble);
// Orca:Hide raft expansion when raft is not enabled
toggle_line("raft_expansion", have_raft);
// Orca: Slim, Strong and Hybrid tree supports size their raft by first layer expansion only.
toggle_field("raft_expansion", !(is_tree(support_type) && (support_style == smsTreeSlim || support_style == smsTreeStrong || support_style == smsTreeHybrid)));
// Orca: First-layer density is available for supports broadly.
toggle_field("raft_first_layer_density", have_support_material);
+22 -3
View File
@@ -1514,6 +1514,8 @@ wxDEFINE_EVENT(EVT_GLCANVAS_PRINTABLE, SimpleEvent);
const double GLCanvas3D::DefaultCameraZoomToBoxMarginFactor = 1.25;
const double GLCanvas3D::DefaultCameraZoomToBedMarginFactor = 2.00;
const double GLCanvas3D::DefaultCameraZoomToPlateMarginFactor = 1.25;
// Main-thread only: _render_frame never runs off it, so no atomic is needed.
int GLCanvas3D::s_frames_in_progress = 0;
void GLCanvas3D::load_arrange_settings()
{
@@ -2468,7 +2470,8 @@ void GLCanvas3D::_render_frame(bool scene_dirty, bool only_init)
}
m_in_render = true;
Slic3r::ScopeGuard in_render_guard([this]() { m_in_render = false; });
++s_frames_in_progress;
Slic3r::ScopeGuard in_render_guard([this]() { m_in_render = false; --s_frames_in_progress; });
(void)in_render_guard;
if (m_canvas == nullptr)
@@ -2713,15 +2716,31 @@ void GLCanvas3D::_render_frame(bool scene_dirty, bool only_init)
// On Wayland, eglSwapBuffers blocks when the canvas is hidden or
// occluded. Skip the swap to avoid stalling the render loop.
if (m_canvas->IsShownOnScreen()) {
// Code run from inside this frame - a modal dialog a gizmo opened from its ImGui panel, a
// synchronous paint of another canvas - may have made a different surface current. Bind this one
// again before presenting, so the swap is not issued against a window the context no longer
// belongs to: on Mesa/X11 that is a fatal BadMatch, not the no-op it is on other platforms. Draws
// already issued before this point cannot be redirected - only this swap is protected.
if (m_canvas->IsShownOnScreen() && _set_current()) {
m_canvas->SwapBuffers();
m_frame_profiler.mark("swap");
if (!overlay_tick)
m_render_stats.increment_fps_counter();
m_presented_signature = signature;
}
else
else {
if (m_canvas->IsShownOnScreen()) {
// Logged once: if the rebind fails it does so every frame, and a warning per frame would
// bury everything else.
static bool rebind_failure_logged = false;
if (!rebind_failure_logged) {
rebind_failure_logged = true;
BOOST_LOG_TRIVIAL(warning) << "GLCanvas3D: could not rebind the GL context to this canvas before "
"SwapBuffers(); the frame is not presented";
}
}
m_presented_signature.reset();
}
}
// Everything drawn into the 3D scene, from the clear to the post processing passes, ending in the
+7
View File
@@ -643,6 +643,8 @@ private:
#endif
unsigned int m_last_w, m_last_h;
bool m_in_render;
// How many canvases are inside _render_frame() right now - see is_frame_in_progress().
static int s_frames_in_progress;
wxTimer m_timer;
wxTimer m_timer_set_color;
// Armed by each frame that draws the FPS overlay; its tick requests an overlay-only frame.
@@ -974,6 +976,11 @@ public:
void on_change_color_mode(bool is_dark, bool reinit = true);
const bool get_dark_mode_status() { return m_is_dark; }
void set_as_dirty() { m_dirty = true; }
// True while any GLCanvas3D is inside _render_frame(). The other surfaces that share the app's one
// GL context (the UV editor canvas) check this before making themselves current: a frame interrupted
// by another surface finishes drawing into that surface and then presents a window the context no
// longer belongs to, which on Mesa/X11 is a fatal X error (BadMatch) rather than a no-op.
static bool is_frame_in_progress() { return s_frames_in_progress > 0; }
void requires_check_outside_state() { m_requires_check_outside_state = true; }
unsigned int get_volumes_count() const { return (unsigned int)m_volumes.volumes.size(); }
-4
View File
@@ -719,9 +719,6 @@ void GLTexture::render_sub_texture(unsigned int tex_id, float left, float right,
// does not treat anti-aliased icon edges as window transparency.
glsafe(::glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA));
glsafe(::glEnable(GL_TEXTURE_2D));
glsafe(::glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE));
glsafe(::glBindTexture(GL_TEXTURE_2D, (GLuint)tex_id));
GLModel::Geometry init_data;
@@ -753,7 +750,6 @@ void GLTexture::render_sub_texture(unsigned int tex_id, float left, float right,
glsafe(::glBindTexture(GL_TEXTURE_2D, 0));
glsafe(::glDisable(GL_TEXTURE_2D));
glsafe(::glDisable(GL_BLEND));
}
+10
View File
@@ -1952,6 +1952,16 @@ void MenuFactory::create_plate_menu()
},
"", nullptr, []() { return !plater()->get_partplate_list().get_selected_plate()->get_objects().empty(); }, m_parent);
// fix objects on current plate
append_menu_item(menu, wxID_ANY, _L("Fix All"), _L("Fix all models on the current plate"),
[](wxCommandEvent&) { obj_list()->fix_all_through_cgal(false); }, "", nullptr,
[]() { return !plater()->get_partplate_list().get_selected_plate()->empty(); }, m_parent);
// fix objects on all plates
append_menu_item(menu, wxID_ANY, _L("Fix All Plates"), _L("Fix all models on all plates"),
[](wxCommandEvent&) { obj_list()->fix_all_through_cgal(true); }, "", nullptr,
[]() { return !plater()->model().objects.empty(); }, m_parent);
// orient objects on current plate
append_menu_item(menu, wxID_ANY, _L("Auto Rotate"), _L("Auto rotate current plate"),
[](wxCommandEvent&) {
+65 -55
View File
@@ -6297,30 +6297,44 @@ void ObjectList::rename_item()
}
void ObjectList::fix_through_cgal()
{
std::vector<int> obj_idxs, vol_idxs;
get_selection_indexes(obj_idxs, vol_idxs);
fix_through_cgal(obj_idxs, vol_idxs);
}
void ObjectList::fix_all_through_cgal(bool all_plates)
{
std::vector<int> obj_idxs;
if (all_plates) {
for (int obj_idx = 0; obj_idx < int(m_objects->size()); ++obj_idx)
obj_idxs.push_back(obj_idx);
} else {
for (const ModelObject *mo : wxGetApp().plater()->get_partplate_list().get_selected_plate()->get_objects_on_this_plate())
obj_idxs.push_back(int(std::find(m_objects->begin(), m_objects->end(), mo) - m_objects->begin()));
std::sort(obj_idxs.begin(), obj_idxs.end());
obj_idxs.erase(std::unique(obj_idxs.begin(), obj_idxs.end()), obj_idxs.end());
}
fix_through_cgal(obj_idxs, {});
}
void ObjectList::fix_through_cgal(const std::vector<int> &obj_idxs, const std::vector<int> &vol_idxs)
{
// Do not fix anything when a gizmo is open. There might be issues with updates
// and what is worse, the snapshot time would refer to the internal stack.
if (!wxGetApp().plater()->get_view3D_canvas3D()->get_gizmos_manager().check_gizmos_closed_except(GLGizmosManager::Undefined))
if (obj_idxs.empty() || !wxGetApp().plater()->get_view3D_canvas3D()->get_gizmos_manager().check_gizmos_closed_except(GLGizmosManager::Undefined))
return;
// model_name
std::vector<std::string> succes_models;
// model_name failing reason
std::vector<std::pair<std::string, std::string>> failed_models;
std::vector<int> obj_idxs, vol_idxs;
get_selection_indexes(obj_idxs, vol_idxs);
size_t unchanged_models = 0;
bool painting_removed = false;
std::vector<std::string> model_names;
// clear selections from the non-broken models if any exists
// and than fill names of models to repairing
if (vol_idxs.empty()) {
#if !FIX_THROUGH_CGAL_ALWAYS
for (int i = int(obj_idxs.size())-1; i >= 0; --i)
if (object(obj_idxs[i])->get_repaired_errors_count() == 0)
obj_idxs.erase(obj_idxs.begin()+i);
#endif // FIX_THROUGH_CGAL_ALWAYS
for (int obj_idx : obj_idxs)
if (object(obj_idx))
model_names.push_back(object(obj_idx)->name);
@@ -6328,31 +6342,26 @@ void ObjectList::fix_through_cgal()
else {
ModelObject* obj = object(obj_idxs.front());
if (obj) {
#if !FIX_THROUGH_CGAL_ALWAYS
for (int i = int(vol_idxs.size()) - 1; i >= 0; --i)
if (obj->get_repaired_errors_count(vol_idxs[i]) == 0)
vol_idxs.erase(vol_idxs.begin() + i);
#endif // FIX_THROUGH_CGAL_ALWAYS
for (int vol_idx : vol_idxs)
model_names.push_back(obj->volumes[vol_idx]->name);
}
}
auto plater = wxGetApp().plater();
const bool keep_painting = GUI::wxGetApp().app_config->get_bool("keep_painting");
auto fix_and_update_progress = [this, plater, model_names](const int obj_idx, const int vol_idx,
int model_idx,
ProgressDialog& progress_dlg,
std::vector<std::string>& succes_models,
std::vector<std::pair<std::string, std::string>>& failed_models)
auto fix_and_update_progress = [&](const int obj_idx, const int vol_idx, int model_idx, ProgressDialog& progress_dlg)
{
if (!object(obj_idx))
ModelObject *mo = object(obj_idx);
if (!mo)
return false;
const std::string& model_name = model_names[model_idx];
wxString msg = _L("Repairing model object");
if (model_names.size() == 1)
msg += ": " + from_u8(model_name) + "\n";
else if (model_names.size() > 10)
msg += ": " + from_u8(model_name) + wxString::Format(" (%d/%d)", model_idx + 1, int(model_names.size())) + "\n";
else {
msg += ":\n";
for (int i = 0; i < int(model_names.size()); ++i)
@@ -6360,33 +6369,29 @@ void ObjectList::fix_through_cgal()
msg += "\n";
}
const bool keep_painting = GUI::wxGetApp().app_config->get_bool("keep_painting");
if (!keep_painting) {
plater->clear_before_change_mesh(obj_idx);
}
const size_t volumes_before = object(obj_idx)->volumes.size();
auto count_painted = [mo]() { return std::count_if(mo->volumes.begin(), mo->volumes.end(), [](const ModelVolume *mv) { return mv->is_any_painted(); }); };
const auto painted_before = count_painted();
std::string res;
if (!fix_model_with_cgal_gui(*(object(obj_idx)), vol_idx, progress_dlg, msg, res, keep_painting))
bool modified = false;
if (!fix_model_with_cgal_gui(*mo, vol_idx, progress_dlg, msg, res, keep_painting, &modified))
return false;
//wxGetApp().plater()->changed_mesh(obj_idx);
object(obj_idx)->ensure_on_bed();
plater->changed_mesh(obj_idx);
const size_t volumes_after = object(obj_idx)->volumes.size();
if (volumes_after != volumes_before)
add_volumes_to_object_in_list(obj_idx);
if (modified) {
painting_removed = painting_removed || count_painted() < painted_before;
mo->ensure_on_bed();
plater->changed_mesh(obj_idx);
plater->get_partplate_list().notify_instance_update(obj_idx, 0);
plater->sidebar().obj_list()->update_plate_values_for_items();
update_item_error_icon(obj_idx, vol_idx);
update_info_items(obj_idx);
}
plater->get_partplate_list().notify_instance_update(obj_idx, 0);
plater->sidebar().obj_list()->update_plate_values_for_items();
if (res.empty())
if (!res.empty())
failed_models.push_back({ model_name, res });
else if (modified)
succes_models.push_back(model_name);
else
failed_models.push_back({ model_name, res });
update_item_error_icon(obj_idx, vol_idx);
update_info_items(obj_idx);
++unchanged_models;
return true;
};
@@ -6399,11 +6404,7 @@ void ObjectList::fix_through_cgal()
if (vol_idxs.empty()) {
int vol_idx{ -1 };
for (int obj_idx : obj_idxs) {
#if !FIX_THROUGH_CGAL_ALWAYS
if (object(obj_idx)->get_repaired_errors_count(vol_idx) == 0)
continue;
#endif // FIX_THROUGH_CGAL_ALWAYS
if (!fix_and_update_progress(obj_idx, vol_idx, model_idx, progress_dlg, succes_models, failed_models))
if (!fix_and_update_progress(obj_idx, vol_idx, model_idx, progress_dlg))
break;
model_idx++;
}
@@ -6411,7 +6412,7 @@ void ObjectList::fix_through_cgal()
else {
int obj_idx{ obj_idxs.front() };
for (int vol_idx : vol_idxs) {
if (!fix_and_update_progress(obj_idx, vol_idx, model_idx, progress_dlg, succes_models, failed_models))
if (!fix_and_update_progress(obj_idx, vol_idx, model_idx, progress_dlg))
break;
model_idx++;
}
@@ -6419,20 +6420,29 @@ void ObjectList::fix_through_cgal()
// Close the progress dialog
progress_dlg.Update(100, "");
if (painting_removed)
plater->notify_painting_removed();
// Show info notification
wxString msg;
std::vector<wxString> blocks;
wxString bullet_suf = "\n - ";
if (!succes_models.empty()) {
msg = _L_PLURAL("The following model object has been repaired", "The following model objects have been repaired", succes_models.size()) + ":";
wxString block = _L_PLURAL("The following model object has been repaired", "The following model objects have been repaired", succes_models.size()) + ":";
for (auto& model : succes_models)
msg += bullet_suf + from_u8(model);
msg += "\n\n";
block += bullet_suf + from_u8(model);
blocks.push_back(block);
}
if (!failed_models.empty()) {
msg += _L_PLURAL("Failed to repair the following model object", "Failed to repair the following model objects", failed_models.size()) + ":\n";
wxString block = _L_PLURAL("Failed to repair the following model object", "Failed to repair the following model objects", failed_models.size()) + ":";
for (auto& model : failed_models)
msg += bullet_suf + from_u8(model.first) + ": " + _(model.second);
block += bullet_suf + from_u8(model.first) + ": " + _(model.second);
blocks.push_back(block);
}
if (unchanged_models > 0)
blocks.push_back(format_wxstr(_L_PLURAL("%1$d model object needed no repair.", "%1$d model objects needed no repair.", unchanged_models), unchanged_models));
wxString msg;
for (const wxString &block : blocks)
msg += (msg.IsEmpty() ? "" : "\n\n") + block;
if (msg.IsEmpty())
msg = _L("Repairing was canceled");
plater->get_notification_manager()->push_notification(NotificationType::CgalFinished, NotificationManager::NotificationLevel::PrintInfoShortNotificationLevel, into_u8(msg));
+3 -3
View File
@@ -47,9 +47,6 @@ typedef double coordf_t;
typedef std::pair<coordf_t, coordf_t> t_layer_height_range;
typedef std::map<t_layer_height_range, ModelConfig> t_layer_config_ranges;
// Manifold mesh may contain self-intersections, so we want to always allow fixing the mesh.
#define FIX_THROUGH_CGAL_ALWAYS 1
namespace GUI {
enum class Shortcut : uint8_t;
@@ -463,6 +460,9 @@ public:
void split_instances();
void rename_item();
void fix_through_cgal();
// Fixes every object on the selected plate, or on all plates.
void fix_all_through_cgal(bool all_plates);
void fix_through_cgal(const std::vector<int> &obj_idxs, const std::vector<int> &vol_idxs);
void simplify();
void smooth_mesh();
void update_item_error_icon(const int obj_idx, int vol_idx) const ;
@@ -1036,6 +1036,11 @@ bool GLGizmoPainterBase::on_mouse(const wxMouseEvent &mouse_event)
Vec2d mouse_pos = mouse_coord.cast<double>();
if (mouse_event.Moving()) {
// No button is down, yet a stroke is still open: its release went elsewhere, as a paint drag does not
// capture the mouse. End the stroke as that release would have.
if (m_button_down != Button::None)
gizmo_event(m_button_down == Button::Left ? SLAGizmoEventType::LeftUp : SLAGizmoEventType::RightUp, mouse_pos,
mouse_event.ShiftDown(), mouse_event.AltDown(), false);
gizmo_event(SLAGizmoEventType::Moving, mouse_pos, mouse_event.ShiftDown(), mouse_event.AltDown(), false);
return false;
}
@@ -1205,6 +1210,10 @@ void GLGizmoPainterBase::on_set_state()
m_old_mo_id = -1;
//m_iva.release_geometry();
m_triangle_selectors.clear();
// A stroke still open goes with the selectors. Its state must not carry into the next session, where the
// first move would end it as if released and the first press would paint a line from its last position.
m_button_down = Button::None;
m_last_mouse_click = Vec2d::Zero();
//Camera& camera = wxGetApp().plater()->get_camera();
//camera.look_at(camera.get_position(), m_previous_target, Vec3d::UnitZ());
File diff suppressed because it is too large Load Diff
@@ -23,6 +23,7 @@
#include "libslic3r/Point.hpp"
#include <imgui.h>
#include <map>
#include <future>
#include <memory>
#include <optional>
#include "slic3r/GUI/Gizmos/GLGizmoBase.hpp"
@@ -61,12 +62,6 @@ public:
static TextureDisplacementPrepareResult prepare_mesh(const indexed_triangle_set &base,
const TextureDisplacementFacetsData &masks,
const std::vector<TextureDisplacementLayer> &layers,
// `base`'s own UV channel, when it has one
// (ModelVolume::texture_uv). Resampled onto
// the result and reported back in it, and fed
// to the samplers so a ModelUV layer drives
// the refinement through its own layout.
const std::vector<Vec2f> &model_uv,
const TextureDisplacementPrepareParams &params,
const TextureColorSettings &color_settings,
const DisplacementProgressFn &progress,
@@ -203,6 +198,27 @@ public:
};
static PaintedColors painted_colors(const TriangleMesh &mesh, const TriangleSelector::TriangleSplittingData &paint);
// The view while the UV editor's selected islands are highlighted on the model. The highlight lies on the
// undisplaced surface, so the Normal view's relief hides it wherever it rises: Normal gives way to Fast
// while islands are selected and comes back once none are. A view the user clicks in the View row is
// theirs - the pane's background buttons are not a pick, Height only meaning "the texture view".
struct IslandViewFollow
{
bool shown = false; // the highlight, as of the last step()
bool switched = false; // Fast was switched on for the highlight, so Normal comes back once it is gone
bool keep_normal = false; // the user picked Normal in the View row while the highlight was shown
// The view to apply this frame (0 Normal, 1 Fast), or -1 for none. `view` is the one on screen, numbered as
// apply_view_mode() takes it; `debug_open` a debug stage on screen, which holds Normal itself.
int step(bool shown_now, int view, bool debug_open);
// A View row button clicked, the active one included. The row is drawn after step() in the same frame,
// so `shown` is this frame's.
void picked(int view)
{
switched = false;
keep_normal = shown && view == 0;
}
};
void render_painter_gizmo() override;
// Intercepts mouse input while "Adjust Texture" mode is on (dragging the on-canvas offset/
@@ -420,6 +436,71 @@ private:
std::string m_slider_type_request;
int m_slider_type_request_frame = 0;
// ---- The image-adjustment panel ----
//
// Brightness/contrast/sharpness/blur/hue over one layer's image, shown on the image itself and
// updating as the sliders move. What it produces is not a set of layer parameters: it replaces the
// layer's *image*, so the adjusted pixels feed the colour and the displacement together and a
// brightness change moves the relief too (see TextureAdjustments).
//
// An ordinary floating window rather than a popup, and deliberately so. A popup dims the canvas
// behind it and closes on any click outside itself, which between them make it impossible to watch the
// relief change on the model - which is the whole point of adjusting the image here rather than in an
// image editor. A window leaves the 3D view live, clickable and orbitable while the panel is open.
void render_image_adjust_window(const ImVec2 &panel_min, const ImVec2 &panel_max);
// Opens the panel for `layer`, decoding its image into m_adjust_source. Sliders never re-decode
// the PNG.
void open_image_adjust(const TextureDisplacementLayer &layer);
// Reads `layer`'s stored image into the panel's source buffers and records which image it came from.
// Called when the panel opens and again whenever the layer's image is swapped under it, which is why
// it leaves the slider values alone. False when the image cannot be decoded.
bool load_image_adjust_source(const TextureDisplacementLayer &layer);
// Resolves the panel: writes the adjusted image into the user's texture library as a new file and
// points `layer` at it, which is the only way an adjustment becomes permanent. Closes the panel.
void commit_image_adjust(TextureDisplacementLayer &layer);
// Closes the panel and reverts the layer's live preview_adjust to identity, so every exit that is not
// a commit - Cancel, the window's close button, the gizmo closing - leaves the layer as it was found.
void close_image_adjust();
// Collects a finished preview and starts one for the current slider values. One at a time, so a drag
// coalesces into "whatever the sliders last said" instead of a queue of superseded frames.
void update_image_adjust_preview();
int m_adjust_slot = -1; // the layer the panel is open for; -1 when closed
TextureAdjustments m_adjust; // what the sliders currently say
// What the layer's live preview_adjust was last set from, so a slider move can be told from a frame in
// which nothing happened and only the former asks the displacement to be recomputed.
TextureAdjustments m_adjust_applied;
// The layer's image as it was when the panel opened, and a small copy of it. The sliders are applied
// to the small copy for the live preview and to the full-size one exactly once, on commit. Measured on
// a 1024x1024 with every knob engaged, a full-size pass costs 13-19 ms grayscale and 40-60 ms in
// colour (130-190 ms at 2048 in colour) - far too much to repeat per slider frame. The same pass on a
// 384 px copy is 3-4 ms / 9-12 ms, and that is all the preview box can show anyway.
DecodedHeightTexture m_adjust_source;
DecodedHeightTexture m_adjust_preview_source;
// Which image_data the two buffers above were decoded from, so the panel can notice the layer's image
// being swapped from the texture picker while it is open and re-read it. Compared, never dereferenced.
const void *m_adjust_source_image = nullptr;
// And which volume the panel was opened on. Slot numbers are per volume, so without this a change of
// selection would silently rebind the open panel to whichever layer happens to hold the same slot on
// the newly selected object - a different image, under a panel the user opened for this one.
size_t m_adjust_volume_id = 0;
// The preview image on screen, re-uploaded whenever a background pass finishes.
std::unique_ptr<GLTexture> m_adjust_preview_tex;
// The live preview runs on its own thread rather than on the UI thread or on the plater's job
// worker. Not the UI thread because even the small pass is milliseconds and this runs while a slider
// is being dragged; not the job worker because that is a single FIFO shared with Bake and the
// displacement preview (see queue_preview_job()), where a per-frame image filter would sit behind -
// and delay - multi-second mesh work.
std::future<DecodedHeightTexture> m_adjust_preview_job;
TextureAdjustments m_adjust_preview_running; // what the in-flight pass is computing
TextureAdjustments m_adjust_preview_shown; // what m_adjust_preview_tex holds
bool m_adjust_preview_valid = false;
// Drops the GPU copies of the layer's image so the next frame rebuilds them from the decode, which
// is where the live adjustment is applied. Called whenever the panel moves or reverts it.
void invalidate_adjust_textures();
// "Adjust Texture" mode: instead of painting, dragging an on-canvas handle changes the active
// layer's offset. The handle is a flat panel lying in the paint patch's own tangent plane
// (a "pan" - drag anywhere on it for free 2D movement), plus two arrows along the patch's
@@ -438,8 +519,8 @@ private:
// obvious whether the next stroke adds paint (default) or erases it (Shift). Uses ImGui's
// foreground draw list, so it must be called from inside the gizmo's ImGui frame.
void render_paint_cursor_hint();
// Mesh-local tangent-plane basis at m_adjust_anchor_normal, matching project_planar()'s
// dominant-axis convention so dragging on-canvas maps consistently onto offset.
// Mesh-local tangent-plane basis at m_adjust_anchor_normal: box_projection_axes(), so dragging
// on-canvas maps consistently onto offset whichever face the anchor is on.
void adjust_tangent_basis(Vec3f &u_axis, Vec3f &v_axis) const;
// The plane a drag is measured against: the paint patch's anchor, lifted clear of the surface.
@@ -519,6 +600,11 @@ private:
// The panel's view modes: 0 Normal, 1 Fast, 2 Checker, 3 Distortion. Shared by the View row and the pane's
// background buttons, so both switch views the same way.
void apply_view_mode(int mode);
// The view on screen, numbered as apply_view_mode() takes it.
int view_mode() const;
// Run once a frame, after the pane's commands: switches the view as m_island_view says.
void follow_island_highlight();
IslandViewFollow m_island_view;
// The pane header's thumbnail of the active layer's texture, rebuilt only when its image changes.
static constexpr int UV_THUMB_PX = 64;
const void *m_uv_thumb_source = nullptr;
@@ -750,6 +836,8 @@ private:
// in place. Rebuilt whenever the pane's selection differs from the one it was built for.
GLModel m_island_overlay_glmodel;
std::vector<int> m_island_overlay_selection;
// The pane's selection while the overlay applies - the pane open over an unwrapped LSCM layer - else null.
const std::vector<int> *island_highlight_selection();
void rebuild_island_overlay(const std::vector<int> &selection);
void render_island_overlay();
// Set on every paint event, cleared when the overlay is rebuilt in render_painter_gizmo(). Kept
@@ -833,31 +921,18 @@ private:
// Merges chart `b`'s join group into chart `a`'s (materialising `groups` to `chart_count` first).
static void join_island_groups(std::vector<int> &groups, int a, int b, int chart_count);
// Final per-vertex texture uv for the projections the shader can't reconstruct itself - LSCM (an
// unwrap), ModelUV (the model's own channel) and ViewProjected (a projector plane the shader
// doesn't know). One entry per patch/base vertex, already through apply_uv_transform(). Empty for
// Triplanar/Cylindrical/Spherical, which the shader projects on its own. Shared by the shaded
// preview and the UV-check overlay.
//
// `patch_source` maps each patch triangle back to its base-mesh triangle
// (TriangleSelector::get_facets_strict()'s out_source). Only ModelUV needs it - its channel is per
// base triangle - and without it a ModelUV layer reports no uvs and the preview falls back.
// unwrap) and ViewProjected (a projector plane the shader doesn't know). One entry per patch/base
// vertex, already through apply_uv_transform(). Empty for Triplanar/Cylindrical/Spherical, which
// the shader projects on its own. Shared by the shaded preview and the UV-check overlay.
std::vector<Vec2f> compute_layer_vertex_uvs(const indexed_triangle_set &patch,
const TextureDisplacementLayer &layer,
const std::vector<int> *patch_source = nullptr) const;
const TextureDisplacementLayer &layer) const;
// The same, but three UVs per patch triangle (corner 0..2 of triangle i at 3i..3i+2). This is what
// the flat, unshared-vertex preview meshes actually want: under LSCM a seam vertex has a different
// UV in each island it borders, so collapsing to one per vertex handed a triangle at an unjoined
// seam its neighbour's placement - one visibly skewed triangle per face. Every other projection is
// single-valued per point, so there a corner's UV is just its vertex's.
std::vector<Vec2f> compute_layer_corner_uvs(const indexed_triangle_set &patch,
const TextureDisplacementLayer &layer,
const std::vector<int> *patch_source = nullptr) const;
// The model's own channel over `local_patch`, already through apply_uv_transform() - three per
// patch triangle. Empty when the volume has no channel, or when `patch_source` is missing. Shared
// by the two functions above so the per-vertex and per-corner forms can never disagree.
std::vector<Vec2f> model_uv_corners(const indexed_triangle_set &local_patch,
const TextureDisplacementLayer &layer,
const std::vector<int> *patch_source) const;
const TextureDisplacementLayer &layer) const;
// The in-shader projection for `layer` (0 Triplanar, 1 Cylindrical, 2 Spherical) plus, for the two
// wrapping ones, the patch centroid and cylinder axis they wrap around - in the texture frame the
// shaders project in. Taken from the bake's own texture_displacement_patch_frame(), so a preview
@@ -906,6 +981,7 @@ private:
enum class UVBackground { None, Height, Checker };
UVBackground m_uv_editor_bg = UVBackground::None;
float m_uv_editor_bg_smoothing = -1.f; // smoothing the height backdrop was uploaded at
TextureAdjustments m_uv_editor_bg_adjust; // and the live image adjustment it was uploaded at
const void *m_uv_editor_bg_image = nullptr; // the layer image it was uploaded from
// Per-chart distortion heatmap colour for the UV pane (#7/#14), computed once when the unwrap is
// re-solved (relative stretch doesn't change when islands are merely moved), fed to the canvas only
@@ -943,25 +1019,26 @@ private:
bool m_preview_job_pending = false;
void queue_preview_job();
// Per-slot GPU thumbnail cache for the layer list panel, keyed by the image_data pointer that
// was current the last time each thumbnail was built (see get_layer_thumbnail()).
std::array<std::unique_ptr<GLTexture>, TEXTURE_DISPLACEMENT_MAX_LAYERS> m_thumbnails;
std::array<const void *, TEXTURE_DISPLACEMENT_MAX_LAYERS> m_thumbnail_source{};
// Per-slot GPU thumbnail cache for the layer list panel, each keyed by the image_data it was built from
// (see get_layer_thumbnail()). Held weakly rather than by address, as decode_height_texture()'s cache is:
// an image freed and replaced by another at the same address must not pass for it.
std::array<std::unique_ptr<GLTexture>, TEXTURE_DISPLACEMENT_MAX_LAYERS> m_thumbnails;
std::array<std::weak_ptr<const std::vector<unsigned char>>, TEXTURE_DISPLACEMENT_MAX_LAYERS> m_thumbnail_source;
// The smoothing each cached thumbnail was built at, so a smoothing change re-uploads it.
std::array<float, TEXTURE_DISPLACEMENT_MAX_LAYERS> m_thumbnail_smoothing{};
std::array<float, TEXTURE_DISPLACEMENT_MAX_LAYERS> m_thumbnail_smoothing{};
// Full-resolution height texture for the preview shader, keyed the same way (see
// get_layer_height_texture()). A smoothing change re-uploads it, so the fast preview shows the
// blur the bake will apply.
std::unique_ptr<GLTexture> m_height_tex;
const void *m_height_tex_source = nullptr;
float m_height_tex_smoothing = -1.f;
std::unique_ptr<GLTexture> m_height_tex;
std::weak_ptr<const std::vector<unsigned char>> m_height_tex_source;
float m_height_tex_smoothing = -1.f;
// The same, for the layer's *colour*, which the fast preview quantizes per fragment so it shows
// the image at texel resolution rather than at the mesh's. Null for a grayscale texture.
std::unique_ptr<GLTexture> m_color_tex;
const void *m_color_tex_source = nullptr;
float m_color_tex_smoothing = -1.f;
std::unique_ptr<GLTexture> m_color_tex;
std::weak_ptr<const std::vector<unsigned char>> m_color_tex_source;
float m_color_tex_smoothing = -1.f;
// Library textures the picker has shown at least once, keyed by file path (see LibraryTexture).
std::map<std::string, LibraryTexture> m_library_textures;
+13 -5
View File
@@ -420,7 +420,10 @@ void GLGizmosManager::refresh_on_off_state()
void GLGizmosManager::reset_all_states()
{
if (! m_enabled || m_serializing)
// The restore/new-project event can run before deferred OpenGL resource
// loading has populated the gizmo list. There is nothing to reset until
// initialization completes.
if (! m_enabled || m_serializing || m_gizmos.empty())
return;
const EType current = get_current_type();
@@ -435,6 +438,9 @@ void GLGizmosManager::reset_all_states()
bool GLGizmosManager::open_gizmo(EType type)
{
if (m_gizmos.empty())
return false;
int idx = static_cast<int>(type);
// re-open same type cause closing
@@ -522,7 +528,7 @@ bool GLGizmosManager::is_running() const
bool GLGizmosManager::open_gizmo_by_shortcut(Shortcut shortcut)
{
if (!m_enabled)
if (!m_enabled || m_gizmos.empty())
return false;
// The text tool opens without a selection because it creates its own object.
@@ -1427,10 +1433,12 @@ void GLGizmosManager::update_hover_state(const EType &type)
bool GLGizmosManager::activate_gizmo(EType type)
{
assert(!m_gizmos.empty());
// already activated
if (m_current == type) return true;
if (m_current == type)
return true;
if (m_gizmos.empty())
return false;
if (m_current != Undefined) {
// clean up previous gizmo
@@ -925,8 +925,9 @@ void GizmoObjectManipulation::do_render_move_window(ImGuiWrapper *imgui_wrapper,
m_last_active_item = current_active_id;
last_move_input_window_width = ImGui::GetWindowWidth();
ImGui::PopStyleVar();
imgui_wrapper->end();
ImGui::PopStyleVar(2);
ImGui::PopStyleVar();
ImGuiWrapper::pop_toolbar_style();
}
@@ -1131,10 +1132,11 @@ void GizmoObjectManipulation::do_render_rotate_window(ImGuiWrapper *imgui_wrappe
m_last_active_item = current_active_id;
last_rotate_input_window_width = ImGui::GetWindowWidth();
ImGui::PopStyleVar();
imgui_wrapper->end();
// BBS
ImGui::PopStyleVar(2);
ImGui::PopStyleVar();
ImGuiWrapper::pop_toolbar_style();
}
@@ -8,7 +8,6 @@
#include "libslic3r/TextureDisplacement.hpp"
#include <exception>
#include <cstddef>
#include <cstdint>
#include "slic3r/GUI/Jobs/Worker.hpp"
#include <memory>
@@ -27,7 +26,6 @@
#include "slic3r/Utils/UndoRedo.hpp"
#include "libslic3r/ObjectID.hpp"
#include "libslic3r/TriangleMesh.hpp"
#include <array>
namespace Slic3r::GUI {
@@ -76,8 +74,7 @@ void TextureDisplacementBakeJob::process(Ctl &ctl)
}
return true;
},
color, m_input.volume_to_world, nullptr, &m_stats,
m_input.model_uv.empty() ? nullptr : &m_input.model_uv));
color, m_input.volume_to_world, nullptr, &m_stats));
// Always finish at 100: this is what closes the notification. Reported even on cancel, where
// build_texture_displacement() returns an empty mesh and finalize() commits nothing.
@@ -129,71 +126,16 @@ void TextureDisplacementBakeJob::finalize(bool canceled, std::exception_ptr &ept
{ mix.a_percent(), 100 - mix.a_percent() });
});
// Whether the bake replaced the triangles or only moved the vertices it was given. The classic
// path is topology-preserving by contract, so every per-triangle annotation on the volume still
// means what it did; the default pipeline refines, cuts and simplifies, so none of them do.
// Both are checked: the flag is what the bake promised, the count is what it delivered. Only
// the triangles matter - the annotations are per facet and reference no vertex index - so a
// vertex count that changed on its own (the bake compacts unreferenced vertices away) is not a
// reason to remap anything.
const bool topology_changed = m_input.options.pipeline_v2 ||
m_result.its.indices.size() != m_input.base_mesh.indices.size();
// Carry the volume's existing paint - the model's own colours above all - across that rebuild.
// Without it a bake left the mmu_segmentation_facets bitstream pointing at a triangle set that
// no longer existed, which is what scrambled the colours of an imported coloured model even
// with colour switched off on every layer and nothing in the bake that was meant to touch them.
//
// transfer_facet_paint() rather than ModelVolume::restore_painting(): the latter's remap wants
// a target triangle overlapping the source paint to within 0.01 mm, which the baked surface is
// nowhere near - it has moved by the relief depth. Nothing to do when the topology is intact:
// triangle i is still triangle i, so the paint is already exactly right and carrying it at all
// could only lose detail.
std::array<TriangleSelector::TriangleSplittingData, 4> before;
if (topology_changed) {
before[0] = volume->supported_facets.get_data();
before[1] = volume->seam_facets.get_data();
before[2] = volume->mmu_segmentation_facets.get_data();
before[3] = volume->fuzzy_skin_facets.get_data();
}
volume->set_mesh(std::move(m_result));
volume->set_new_unique_id();
volume->calculate_convex_hull();
if (topology_changed) {
const std::array<FacetsAnnotation *, 4> target{ &volume->supported_facets, &volume->seam_facets,
&volume->mmu_segmentation_facets,
&volume->fuzzy_skin_facets };
for (size_t ch = 0; ch < target.size(); ++ch) {
const std::vector<uint8_t> state =
transfer_facet_paint(m_input.base_mesh, before[ch], volume->mesh().its);
// Nothing was painted in this channel, or there is nothing to paint it onto: either
// way the annotation must not keep describing the mesh that is gone.
if (state.empty()) {
target[ch]->reset();
continue;
}
TriangleSelector selector(volume->mesh());
bool any = false;
for (size_t i = 0; i < state.size(); ++i)
if (state[i] != 0) {
selector.set_facet(int(i), EnforcerBlockerType(state[i]));
any = true;
}
if (any)
target[ch]->set(selector);
else
target[ch]->reset();
}
}
// Colour lands in mmu_segmentation_facets, merged *over* whatever is already painted there
// rather than replacing it: a triangle the texture does not colour keeps its existing filament,
// and one the user never painted at all stays at NONE, which already means "the volume's own
// filament". That is what confines the effect to the painted area without having to invent a
// colour for everything outside it. What was already painted is whatever the transfer above
// left in the annotation, so this bake's colour lands on top of it rather than instead of it.
// colour for everything outside it. Safe to index straight onto the new mesh - the bake is
// topology-preserving, so triangle i is still triangle i.
if (!m_triangle_color.empty() && m_triangle_color.size() == volume->mesh().its.indices.size()) {
TriangleSelector selector(volume->mesh());
const TriangleSelector::TriangleSplittingData &existing = volume->mmu_segmentation_facets.get_data();
@@ -217,6 +159,7 @@ void TextureDisplacementBakeJob::finalize(bool canceled, std::exception_ptr &ept
// pipeline, which rebuilds and then simplifies the mesh. A mask left behind against the old
// topology is exactly what makes the gizmo reload an empty selector over a non-empty mask and
// then erase it on the next flush - see GLGizmoTextureDisplacement::update_from_model_object().
const bool topology_changed = m_input.base_mesh.indices.size() != volume->mesh().its.indices.size();
for (int slot = 0; slot < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++slot) {
const auto it = std::find_if(m_input.layers.begin(), m_input.layers.end(),
[slot](const TextureDisplacementLayer &l) { return l.slot == slot; });
@@ -224,14 +167,6 @@ void TextureDisplacementBakeJob::finalize(bool canceled, std::exception_ptr &ept
volume->texture_displacement_facet(slot).reset();
}
// The model's own UV channel. Resampled onto a rebuilt mesh from the surface the bake started
// from: a displaced vertex came from its foot point on that surface, which is the position its
// uv belongs to - so no distance limit, the relief depth is exactly how far it has moved.
if (!m_input.model_uv.empty())
volume->texture_uv = topology_changed ? transfer_uv_channel(m_input.base_mesh, m_input.model_uv,
volume->mesh().its) :
m_input.model_uv;
ModelObject *object = volume->get_object();
if (object == nullptr)
return;
@@ -284,8 +219,6 @@ void queue_texture_displacement_bake(const ModelVolume &volume, const TextureCol
input.take_snapshot = take_snapshot;
input.volume_id = volume.id();
input.base_mesh = volume.mesh().its;
if (volume.has_texture_uv())
input.model_uv = volume.texture_uv;
input.layers = volume.texture_displacement_layers;
input.options = volume.texture_displacement_options;
input.volume_to_world = texture_displacement_volume_to_world(volume);
@@ -34,9 +34,6 @@ struct TextureDisplacementBakeInput
// writes the volume's mmu_segmentation_facets - the same per-triangle filament assignment the MMU
// paint gizmo writes - alongside the displaced geometry.
TextureColorSettings color;
// The volume's own UV channel (ModelVolume::texture_uv), empty when it has none: what a ModelUV
// layer maps through, and what the commit puts back on the baked mesh.
std::vector<Vec2f> model_uv;
// Whether this job pushes its own undo step when it commits. False when the caller has already
// taken one that is meant to cover the displacement as well - Standard mode's Bake, which remeshes
// and subdivides first and has to undo as a single action.
@@ -17,7 +17,6 @@
#include "slic3r/GUI/Jobs/Worker.hpp"
#include <memory>
#include "libslic3r/ObjectID.hpp"
#include "libslic3r/Point.hpp"
#include "libslic3r/TriangleMesh.hpp"
namespace Slic3r::GUI {
@@ -53,14 +52,13 @@ void TextureDisplacementDebugJob::process(Ctl &ctl)
indexed_triangle_set mesh = m_input.base_mesh;
TextureDisplacementFacetsData masks = m_input.facets_data;
std::vector<Vec2f> uv = m_input.model_uv;
// The default pipeline can only move vertices the mesh already has, so its recipe starts with the
// preparation - which is where "first it remeshes, then it refines" actually happens. The
// experimental pipeline refines as part of the bake and has nothing to prepare.
if (m_input.run_prepare && !m_input.options.pipeline_v2) {
const TextureDisplacementPrepareResult prepared =
GLGizmoTextureDisplacement::prepare_mesh(mesh, masks, m_input.layers, uv, m_input.prepare_params,
GLGizmoTextureDisplacement::prepare_mesh(mesh, masks, m_input.layers, m_input.prepare_params,
m_input.color,
// Preparation is roughly half the run; the bake
// takes the progress bar from there.
@@ -79,14 +77,12 @@ void TextureDisplacementDebugJob::process(Ctl &ctl)
if (!prepared.mesh.indices.empty()) {
mesh = prepared.mesh;
masks = prepared.masks;
uv = prepared.uv; // resampled onto the prepared mesh, as the prepare commit stores it
}
}
build_texture_displacement(mesh, m_input.layers, masks, m_input.options,
[&report](int pct) { return report(50 + pct / 2); },
/* color */ nullptr, m_input.volume_to_world, &recorder, /* stats */ nullptr,
uv.empty() ? nullptr : &uv);
/* color */ nullptr, m_input.volume_to_world, &recorder);
m_stages = recorder.take();
ctl.update_status(100, status); // always finish at 100: this is what closes the notification
@@ -119,8 +115,6 @@ void queue_texture_displacement_debug(const ModelVolume &volume, const TextureCo
input.check_topology = check_topology;
input.color = color;
input.volume_to_world = texture_displacement_volume_to_world(volume);
if (volume.has_texture_uv())
input.model_uv = volume.texture_uv;
for (int i = 0; i < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++i)
input.facets_data[size_t(i)] = volume.texture_displacement_facet(i).get_data();
@@ -47,9 +47,6 @@ struct TextureDisplacementDebugInput
// Only the quantizer is used, and only by the refinement's colour criterion - the debug run
// produces no colour of its own.
TextureColorSettings color;
// The volume's own UV channel (ModelVolume::texture_uv), so the recipe captured here is the one a
// ModelUV layer actually bakes through. Empty when the volume has none.
std::vector<Vec2f> model_uv;
// The edge scan behind the open / non-manifold counts is a sort over every half-edge, which on a
// multi-million triangle stage costs more than the stage did. On by default because a stage that
@@ -46,7 +46,7 @@ void TextureDisplacementPrepareJob::process(Ctl &ctl)
// idle loop.
int last_reported = 1;
m_result = GLGizmoTextureDisplacement::prepare_mesh(m_input.base_mesh, m_input.masks, m_input.layers,
m_input.model_uv, m_input.params, m_input.color,
m_input.params, m_input.color,
[&ctl, &status, &last_reported](int percent) {
if (ctl.was_canceled())
return false;
@@ -106,10 +106,6 @@ void TextureDisplacementPrepareJob::finalize(bool canceled, std::exception_ptr &
volume->restore_painting(saved_painting);
for (int i = 0; i < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++i)
volume->texture_displacement_facet(i).set_data(std::move(m_result.masks[size_t(i)]));
// The model's own UV channel, resampled onto the new mesh by the run. Also put back after
// restore_painting(), which resets it along with the extra facets for the same reason: it is
// indexed by triangle and the triangles have changed.
volume->texture_uv = std::move(m_result.uv);
if (ObjectList *obj_list = wxGetApp().obj_list()) {
const ModelObjectPtrs &objs = plater->model().objects;
@@ -9,7 +9,6 @@
#include "Job.hpp"
#include "libslic3r/ObjectID.hpp"
#include "libslic3r/Point.hpp"
#include "libslic3r/TextureDisplacement.hpp"
namespace Slic3r {
@@ -48,10 +47,6 @@ struct TextureDisplacementPrepareInput
// skips the colour criterion entirely. Only the *quantizer* is used here: refinement follows
// perceived colour, never the interleaving that realises a mix.
TextureColorSettings color;
// The volume's own UV channel (ModelVolume::texture_uv), empty when it has none. prepare_mesh()
// resamples it onto the mesh it produces, and the commit puts it back - like the masks, it is
// indexed by triangle and so cannot survive the stages on its own.
std::vector<Vec2f> model_uv;
// The undo step the commit opens. Standard mode's Bake names it after the bake, because the
// displacement job that follows commits into this same step rather than pushing its own.
std::string snapshot_name;
@@ -48,8 +48,7 @@ void TextureDisplacementPreviewJob::process(Ctl &ctl)
(!m_current_generation ||
m_current_generation->load() == m_generation);
},
color, m_input.volume_to_world, nullptr, nullptr,
m_input.model_uv.empty() ? nullptr : &m_input.model_uv);
color, m_input.volume_to_world);
}
void TextureDisplacementPreviewJob::finalize(bool canceled, std::exception_ptr &eptr)
@@ -29,9 +29,6 @@ struct TextureDisplacementPreviewInput
// Empty unless a layer is colouring, in which case the preview reports the palette entry per
// triangle alongside the mesh, so the Normal view shows the colours the bake will produce.
TextureColorSettings color;
// The volume's own UV channel (ModelVolume::texture_uv), so a ModelUV layer previews through the
// same layout it will bake through. Empty when the volume has none.
std::vector<Vec2f> model_uv;
};
// A preview result: the displaced mesh, and - when the input carried a palette - one palette entry per
-7
View File
@@ -1880,13 +1880,6 @@ void PartPlate::render_exclude_area(bool force_default_color) {
// draw exclude area
glsafe(::glDepthMask(GL_FALSE));
if (m_selected) {
glsafe(::glColor4fv(select_color.data()));
}
else {
glsafe(::glColor4fv(unselect_color.data()));
}
m_exclude_triangles.set_color(m_selected ? select_color : unselect_color);
m_exclude_triangles.render();
glsafe(::glDepthMask(GL_TRUE));
+11 -24
View File
@@ -14984,24 +14984,8 @@ bool Plater::priv::can_fix_through_cgal() const
std::vector<int> obj_idxs, vol_idxs;
sidebar->obj_list()->get_selection_indexes(obj_idxs, vol_idxs);
#if FIX_THROUGH_CGAL_ALWAYS
// Fixing always.
// A closed mesh may still self-intersect, so fixing is always allowed.
return ! obj_idxs.empty() || ! vol_idxs.empty();
#else // FIX_THROUGH_CGAL_ALWAYS
// Fixing only if the model is not manifold.
if (vol_idxs.empty()) {
for (auto obj_idx : obj_idxs)
if (model.objects[obj_idx]->get_repaired_errors_count() > 0)
return true;
return false;
}
int obj_idx = obj_idxs.front();
for (auto vol_idx : vol_idxs)
if (model.objects[obj_idx]->get_repaired_errors_count(vol_idx) > 0)
return true;
return false;
#endif // FIX_THROUGH_CGAL_ALWAYS
}
bool Plater::priv::can_simplify() const
@@ -22041,13 +22025,16 @@ void Plater::clear_before_change_mesh(int obj_idx)
mv->mmu_segmentation_facets.reset();
mv->fuzzy_skin_facets.reset();
}
if (paint_removed) {
// snapshot_time is captured by copy so the lambda knows where to undo/redo to.
get_notification_manager()->push_notification(
NotificationType::CustomSupportsAndSeamRemovedAfterRepair,
NotificationManager::NotificationLevel::PrintInfoNotificationLevel,
_u8L("Custom supports and color painting were removed before repairing."));
}
if (paint_removed)
notify_painting_removed();
}
void Plater::notify_painting_removed()
{
get_notification_manager()->push_notification(
NotificationType::CustomSupportsAndSeamRemovedAfterRepair,
NotificationManager::NotificationLevel::PrintInfoNotificationLevel,
_u8L("Custom supports and color painting were removed before repairing."));
}
void Plater::changed_mesh(int obj_idx)
+1
View File
@@ -599,6 +599,7 @@ public:
void reslice_SLA_until_step(SLAPrintObjectStep step, const ModelObject &object, bool postpone_error_messages = false);
void clear_before_change_mesh(int obj_idx);
void notify_painting_removed();
void changed_mesh(int obj_idx);
void changed_object(ModelObject &object);
+1
View File
@@ -3098,6 +3098,7 @@ void TabPrint::build()
optgroup = page->new_optgroup(L("Raft"), L"param_raft");
optgroup->append_single_option_line("raft_layers", "support_settings_raft");
optgroup->append_single_option_line("raft_contact_distance", "support_settings_raft");
optgroup->append_single_option_line("raft_expansion", "support_settings_raft");
optgroup = page->new_optgroup(L("Filament for Supports"), L"param_support_filament");
optgroup->append_single_option_line("support_filament", "support_settings_filament#base");
+17 -26
View File
@@ -14,7 +14,7 @@
#include "Widgets/StateColor.hpp"
#include "Widgets/StaticLine.hpp"
#include "libslic3r/ColorDecomposeRecipe.hpp"
#include "libslic3r/MeshBoolean.hpp"
#include "libslic3r/MeshRepair.hpp"
#include "libslic3r/TriangleSelector.hpp"
#include <utility>
@@ -2436,25 +2436,25 @@ void TextureImportDialog::start_computation(bool auto_color, bool initial)
settings.target_colors_num = auto_color ? 0 : (size_t)m_param_color_count;
settings.smooth_weight = m_param_smooth / 10.0;
settings.mesh_repair_decision = m_mesh_repair_decision;
// BBS repairs the mesh through the Windows 3D SDK, which is only available on Windows
// builds that ship the SDK. Orca's CGAL-based repair (MeshBoolean::cgal::repair) works
// on all three platforms, so use that instead.
settings.mesh_repair_callback = [](const indexed_triangle_set& mesh,
indexed_triangle_set& repaired_mesh,
std::function<void(const char*, unsigned)> progress_callback,
std::function<bool()> cancel_callback,
std::string* error_message) -> bool {
if (cancel_callback && cancel_callback())
return false;
if (progress_callback)
progress_callback(_u8L("Repairing mesh").c_str(), 0);
struct Canceled {};
TriangleMesh tm(mesh);
if (!MeshBoolean::cgal::repair(tm, nullptr, error_message))
return false;
if (cancel_callback && cancel_callback())
try {
if (!repair_mesh(tm, nullptr, error_message, [&cancel_callback](int) {
if (cancel_callback && cancel_callback())
throw Canceled();
}))
return false;
} catch (const Canceled &) {
return false;
}
repaired_mesh = tm.its;
if (progress_callback)
progress_callback(_u8L("Repairing mesh").c_str(), 100);
@@ -2683,12 +2683,12 @@ void TextureImportDialog::on_mesh_repair_decision_required(wxCommandEvent&)
m_progress_dlg = nullptr;
}
#ifdef HAS_WIN10SDK
Slic3r::GUI::MessageDialog dlg(initial ? GetParent() : this,
_L("The mesh has non-manifold geometry or open boundaries. You can import it as-is or repair it with Windows 3D repair service before importing."),
_L("Mesh repair"), wxYES_NO | wxICON_WARNING | wxYES_DEFAULT);
_L("The mesh has non-manifold geometry or open boundaries. You can import it as-is or repair it before importing."),
_L("Mesh repair"), wxYES_NO | wxCANCEL | wxICON_WARNING | wxYES_DEFAULT);
dlg.SetButtonLabel(wxID_YES, _L("Import without repair"));
dlg.SetButtonLabel(wxID_NO, _L("Repair and import"), true);
dlg.SetButtonLabel(wxID_CANCEL, _L("Cancel"));
// "Repair and import" is the recommended action here, so the accent moves off the default YES
// button onto NO. MsgDialog::add_button already styled both as ButtonType::Choice, so restyling
// with the same type swaps only the palette and leaves the geometry alone.
@@ -2704,17 +2704,7 @@ void TextureImportDialog::on_mesh_repair_decision_required(wxCommandEvent&)
dlg.Fit();
dlg.CenterOnParent();
int ret = dlg.ShowModal();
m_mesh_repair_decision = (ret == wxID_NO)
? Slic3r::TexturePaintingSettings::MeshRepairDecision::RepairAndImport
: Slic3r::TexturePaintingSettings::MeshRepairDecision::ImportWithoutRepair;
#else
Slic3r::GUI::MessageDialog dlg(initial ? GetParent() : this,
_L("Please note that the mesh has non-manifold geometry or open boundaries."),
_L("Mesh issue"), wxOK | wxCANCEL | wxICON_WARNING | wxOK_DEFAULT);
dlg.SetButtonLabel(wxID_OK, _L("Continue"), true);
dlg.SetButtonLabel(wxID_CANCEL, _L("Cancel"));
int ret = dlg.ShowModal();
if (ret != wxID_OK) {
if (ret == wxID_CANCEL) {
m_cancel_flag = true;
if (initial) {
m_initial_computation_cancelled = true;
@@ -2727,8 +2717,9 @@ void TextureImportDialog::on_mesh_repair_decision_required(wxCommandEvent&)
}
return;
}
m_mesh_repair_decision = Slic3r::TexturePaintingSettings::MeshRepairDecision::ImportWithoutRepair;
#endif
m_mesh_repair_decision = (ret == wxID_NO)
? Slic3r::TexturePaintingSettings::MeshRepairDecision::RepairAndImport
: Slic3r::TexturePaintingSettings::MeshRepairDecision::ImportWithoutRepair;
start_computation(auto_color, initial);
}
+77 -30
View File
@@ -27,6 +27,7 @@
#include <wx/mstream.h>
#include "libslic3r/PNGReadWrite.hpp"
#include "libslic3r/TextureDisplacement.hpp"
#include "libslic3r/Utils.hpp"
#include "libslic3r/AppConfig.hpp"
@@ -158,6 +159,28 @@ bool encode_png_bytes(const wxImage &image, std::vector<unsigned char> &out, std
: encode_gray_png_bytes(image, out, error);
}
// A wxImage over decoded pixels, so the encoders above can be reached from an in-memory image as well as
// from a file. Grayscale is expanded to the three equal channels wxImage always stores, which is what
// image_has_color() then reads as "no colour" - so a grey image still encodes as a grayscale PNG.
//
// `scratch` holds the pixel buffer: the wxImage is constructed over it without taking ownership, so it
// has to outlive every use of the returned image.
wxImage image_from_decoded(const DecodedHeightTexture &image, std::vector<unsigned char> &scratch)
{
if (image.empty())
return wxImage();
const size_t n = size_t(image.width) * size_t(image.height);
scratch.resize(n * 3);
if (image.has_color())
scratch.assign(image.rgb.begin(), image.rgb.end());
else
for (size_t i = 0; i < n; ++i)
scratch[i * 3] = scratch[i * 3 + 1] = scratch[i * 3 + 2] = image.pixels[i];
return wxImage(image.width, image.height, scratch.data(), /* static_data */ true);
}
std::vector<unsigned char> read_file_bytes(const std::string &path)
{
std::ifstream ifs(path, std::ios::binary);
@@ -186,6 +209,42 @@ bool is_supported_height_map(const std::vector<unsigned char> &bytes)
std::vector<TextureLibraryEntry> g_library;
bool g_library_scanned = false;
// Writes `bytes` into the user's own texture folder as `stem`.png, uniquified so an existing texture -
// shipped-name collision, or a second edit of the same source - is never overwritten. Returns the new
// file's library entry. Shared by import_texture_to_library() and save_texture_to_library(), which
// differ only in where their bytes came from.
std::optional<TextureLibraryEntry> write_user_texture(const std::vector<unsigned char> &bytes, const std::string &stem,
std::string &error)
{
const std::string user_dir = user_texture_dir();
if (user_dir.empty()) {
error = _u8L("Could not create the folder for imported textures.");
return std::nullopt;
}
boost::filesystem::path dest = boost::filesystem::path(user_dir) / (stem + ".png");
for (int i = 2; boost::filesystem::exists(dest); ++i)
dest = boost::filesystem::path(user_dir) / (stem + " (" + std::to_string(i) + ").png");
{
boost::nowide::ofstream ofs(dest.string(), std::ios::binary);
ofs.write(reinterpret_cast<const char *>(bytes.data()), std::streamsize(bytes.size()));
if (!ofs.good()) {
error = _u8L("Failed to save the imported texture.");
return std::nullopt;
}
}
texture_library(true); // pick the new file up
const std::string dest_str = dest.string();
for (const TextureLibraryEntry &e : g_library)
if (e.path == dest_str)
return e;
error = _u8L("Failed to save the imported texture.");
return std::nullopt;
}
// The user's own textures, most recently used first, kept in the app config. File names are stored rather
// than paths so the order survives a moved data directory; '/' separates them because no platform allows
// it inside a file name. Bounded so a long-lived config does not grow a line without end.
@@ -317,12 +376,6 @@ bool remove_user_texture(const std::string &path, std::string &error)
std::optional<TextureLibraryEntry> import_texture_to_library(const std::string &source_path, std::string &error)
{
const std::string user_dir = user_texture_dir();
if (user_dir.empty()) {
error = _u8L("Could not create the folder for imported textures.");
return std::nullopt;
}
wxImage image;
if (!image.LoadFile(from_u8(source_path)) || !image.IsOk()) {
error = _u8L("Could not load the selected image.");
@@ -333,30 +386,7 @@ std::optional<TextureLibraryEntry> import_texture_to_library(const std::string &
if (!encode_png_bytes(image, bytes, error))
return std::nullopt;
// Never overwrite an existing texture (the user's or, if they picked the same name twice, their
// own earlier import) - uniquify instead.
const std::string stem = boost::filesystem::path(source_path).stem().string();
boost::filesystem::path dest = boost::filesystem::path(user_dir) / (stem + ".png");
for (int i = 2; boost::filesystem::exists(dest); ++i)
dest = boost::filesystem::path(user_dir) / (stem + " (" + std::to_string(i) + ").png");
{
boost::nowide::ofstream ofs(dest.string(), std::ios::binary);
ofs.write(reinterpret_cast<const char *>(bytes.data()), std::streamsize(bytes.size()));
if (!ofs.good()) {
error = _u8L("Failed to save the imported texture.");
return std::nullopt;
}
}
texture_library(true); // pick the new file up
const std::string dest_str = dest.string();
for (const TextureLibraryEntry &e : g_library)
if (e.path == dest_str)
return e;
error = _u8L("Failed to save the imported texture.");
return std::nullopt;
return write_user_texture(bytes, boost::filesystem::path(source_path).stem().string(), error);
}
std::shared_ptr<std::vector<unsigned char>> load_texture_image_data(const std::string &path, std::string &error)
@@ -382,4 +412,21 @@ std::shared_ptr<std::vector<unsigned char>> load_texture_image_data(const std::s
return std::make_shared<std::vector<unsigned char>>(std::move(converted));
}
std::optional<TextureLibraryEntry> save_texture_to_library(const DecodedHeightTexture &image, const std::string &stem,
std::string &error)
{
std::vector<unsigned char> scratch;
const wxImage wx = image_from_decoded(image, scratch);
if (!wx.IsOk()) {
error = _u8L("The selected image is empty.");
return std::nullopt;
}
std::vector<unsigned char> bytes;
if (!encode_png_bytes(wx, bytes, error))
return std::nullopt;
return write_user_texture(bytes, stem.empty() ? std::string("texture") : stem, error);
}
} // namespace Slic3r::GUI
+10
View File
@@ -6,6 +6,8 @@
#include <string>
#include <vector>
#include "libslic3r/TextureDisplacement.hpp"
namespace Slic3r::GUI {
// One selectable height-map texture in the texture-displacement gizmo's texture picker.
@@ -57,6 +59,14 @@ std::optional<TextureLibraryEntry> import_texture_to_library(const std::string &
// Returns nullptr with `error` set if the file cannot be read or decoded at all.
std::shared_ptr<std::vector<unsigned char>> load_texture_image_data(const std::string &path, std::string &error);
// Writes `image` into user_texture_dir() as a new PNG named after `stem` (uniquified if taken, so an
// existing texture is never overwritten) and returns its library entry. The in-memory counterpart of
// import_texture_to_library(), for an image that was edited rather than read off disk.
//
// Returns nullopt with `error` set on failure.
std::optional<TextureLibraryEntry> save_texture_to_library(const DecodedHeightTexture &image, const std::string &stem,
std::string &error);
} // namespace Slic3r::GUI
#endif // slic3r_TextureLibrary_hpp_
+23 -2
View File
@@ -36,6 +36,7 @@
#include "3DScene.hpp"
#include "BitmapCache.hpp"
#include "GLCanvas3D.hpp"
#include "GLShader.hpp"
#include "GUI_App.hpp"
#include "I18N.hpp"
@@ -939,7 +940,8 @@ void UVEditorCanvas::on_mouse(wxMouseEvent &evt)
m_active_edge = (hit.first >= 0 && is_edge_selected(hit)) ? hit : std::pair<int, int>{ -1, -1 };
m_gesture = (m_active_edge.first >= 0) ? Gesture::MoveEdge : Gesture::Pan;
} else {
const int hit = island_at(uv);
const std::vector<int> selection_before = m_selection;
const int hit = island_at(uv);
if (hit >= 0) {
if (evt.ShiftDown()) {
// Shift adds to the selection (and makes the clicked one the new primary).
@@ -969,6 +971,10 @@ void UVEditorCanvas::on_mouse(wxMouseEvent &evt)
m_selected_island = -1;
}
m_gesture = (m_selected_island >= 0) ? Gesture::MoveIsland : Gesture::Pan;
// The owner shows the selection on the model and would not hear of this click otherwise in time: a
// click that clears the selection starts no gesture, and one that sets it reports only on release.
if (m_selection != selection_before)
run_command(Command::SelectionChanged);
}
grab_mouse();
Refresh();
@@ -1319,8 +1325,13 @@ void UVEditorCanvas::on_size(wxSizeEvent &evt)
// Update() flushes it immediately - still through the normal paint path (unlike calling
// render() directly), which matters because this canvas shares the app's one GL context with
// the 3D view and must not hijack it outside its own paint.
// Not while a 3D canvas frame is in progress, though: wxGTK delivers this size event synchronously
// when the texture displacement gizmo relays out the pane from its ImGui panel, i.e. from inside
// that frame, and flushing the paint there would take the shared context away from it. The Refresh()
// then runs the paint once the frame is over.
Refresh();
Update();
if (!GLCanvas3D::is_frame_in_progress())
Update();
}
void UVEditorCanvas::on_leave(wxMouseEvent &evt)
@@ -1341,6 +1352,16 @@ void UVEditorCanvas::render()
{
if (m_context == nullptr || !IsShownOnScreen())
return;
// Painted from inside a 3D canvas frame - a modal dialog the gizmo opened from its ImGui panel runs
// this paint, as does any other synchronous event raised there. Making this surface current now
// would take the shared context away from that canvas mid-frame: its remaining draws would land
// here and, on Mesa/X11, its SwapBuffers() would be a fatal BadMatch. Skip, but ask for another
// paint so the skipped one is not simply lost. The pane stays stale for as long as a nested modal
// loop keeps a frame on the stack, which is behind the dialog anyway.
if (GLCanvas3D::is_frame_in_progress()) {
Refresh();
return;
}
// wxGLCanvas::SetCurrent() genuinely fails (returns false) on a canvas that isn't shown on
// screen, and can also fail on a pixel-format mismatch with the context - and every GL call
+3 -1
View File
@@ -108,10 +108,12 @@ public:
// the command callback - the canvas has the selection and the view, the gizmo has the layer.
// `value` carries the new setting for the Set* commands (an angle, a flag as 0/1, or an index into
// SelectMode / Background) and is 0 otherwise.
// SelectionChanged is sent by the canvas itself when a click changes the island selection. It carries
// nothing: the owner reads selected_islands() back, and only needs telling that it should look.
enum class Command {
FrameAll, ToggleSnap, AverageScale, CutSelectedIsland, ProjectFromView, JoinSelected, UnjoinSelected,
Unwrap, SetSeamAngle, SetConnectIslands, SetSelectMode, SetMarkSeams, SetSeamPath, ClearSeams, ClearUVEdits,
SetBackground, PickTexture, PaneClosed
SetBackground, PickTexture, PaneClosed, SelectionChanged
};
void run_command(Command cmd, float value = 0.f);
using CommandFn = std::function<void(Command, float)>;
+60 -185
View File
@@ -3,240 +3,115 @@
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include "libslic3r/TriangleMesh.hpp"
#include "libslic3r/BoundingBox.hpp"
#include "libslic3r/Point.hpp"
#include "libslic3r/libslic3r.h"
#include <exception>
#include <cstddef>
#include "libslic3r/Exception.hpp"
#include <limits>
#include <exception>
#include <mutex>
#include "slic3r/GUI/Widgets/ProgressDialog.hpp"
#include <optional>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include <wx/string.h>
#include "libslic3r/MeshBoolean.hpp"
#include "libslic3r/Model.hpp"
#include "libslic3r/Format/bbs_3mf.hpp"
#include "libslic3r/format.hpp"
#include "libslic3r/MeshRepair.hpp"
#include "libslic3r/Model.hpp"
#include "libslic3r/Thread.hpp"
#include "../GUI/I18N.hpp"
#include "libslic3r/TriangleSelector.hpp"
// Orca: This file provides utilities for repairing 3D model meshes using the CGAL library, handling mesh splitting, merging, and boolean operations.
#include "slic3r/GUI/I18N.hpp"
#include "slic3r/GUI/Widgets/ProgressDialog.hpp"
namespace Slic3r {
namespace {
// Orca: Helper functions for analyzing mesh properties and transformations.
bool is_not_3dimensional_part(const TriangleMesh &mesh)
class RepairCanceledException : public std::exception
{
// Orca: Determines if a mesh is degenerate or represents a non-3dimensional part by checking volume and bounding box dimensions.
if (mesh.its.indices.empty())
return true;
indexed_triangle_set tmp = mesh.its;
its_remove_degenerate_faces(tmp, true);
if (tmp.indices.empty())
return true;
const BoundingBoxf3 bbox = mesh.bounding_box();
const Vec3d size = bbox.size();
const double min_dim = std::min(size.x(), std::min(size.y(), size.z()));
const double max_dim = std::max(size.x(), std::max(size.y(), size.z()));
if (min_dim <= EPSILON)
return true;
const double volume = std::abs(its_volume(mesh.its));
const double bbox_volume = size.x() * size.y() * size.z();
if (volume <= EPSILON)
return true;
const double min_relative_thickness = 1e-6;
const double min_volume_ratio = 1e-6;
if (min_dim / max_dim <= min_relative_thickness)
return true;
if (bbox_volume > 0.0 && volume / bbox_volume <= min_volume_ratio)
return true;
return false;
}
public:
const char *what() const noexcept override { return "Model repair has been canceled"; }
};
} // namespace
// Orca: Exception class for handling user-initiated cancellation of model repair operations.
class RepairCanceledException : public std::exception {
public:
const char* what() const noexcept override { return "Model repair has been canceled"; }
};
// Orca: Main function to repair model objects using CGAL, with progress dialog and cancellation support.
// Returns false if fixing was canceled. fix_result contains error message if failed.
bool fix_model_with_cgal_gui(ModelObject &model_object, int volume_idx, GUI::ProgressDialog &progress_dialog, const wxString &msg_header, std::string &fix_result, bool keep_painting)
bool fix_model_with_cgal_gui(ModelObject &model_object, int volume_idx, GUI::ProgressDialog &progress_dialog, const wxString &msg_header, std::string &fix_result, bool keep_painting,
bool *modified)
{
// Hold SaveObjectGaurd to prevent backup manager from racing concurrent mesh mutations (use-after-free).
// Keeps the backup manager from reading a mesh while the worker replaces it.
SaveObjectGaurd backup_gaurd(model_object);
// Orca: Synchronization primitives for progress updates between worker thread and GUI.
std::mutex mtx;
std::condition_variable condition;
struct Progress {
std::string message;
int percent = 0;
bool updated = false;
} progress;
std::vector<ModelVolume *> volumes;
if (volume_idx < 0)
volumes = model_object.volumes;
else if (std::size_t(volume_idx) < model_object.volumes.size())
volumes.push_back(model_object.volumes[volume_idx]);
std::mutex mtx;
std::condition_variable condition;
struct Progress
{
std::string message;
int percent = 0;
bool updated = false;
} progress;
std::atomic<bool> canceled = false;
std::atomic<bool> finished = false;
bool any_modified = false;
std::string errors;
bool success = false;
size_t ivolume = 0;
// Orca: Lambda for updating progress from worker thread.
auto on_progress = [&mtx, &condition, &ivolume, &model_object, &progress](const std::string &msg, unsigned prcnt) {
std::unique_lock<std::mutex> lock(mtx);
auto on_progress = [&mtx, &condition, &progress](const std::string &msg, int percent) {
std::lock_guard<std::mutex> lock(mtx);
progress.message = msg;
const size_t total = std::max<size_t>(1, model_object.volumes.size());
progress.percent = int(std::floor((float(prcnt) + float(ivolume) * 100.f) / float(total)));
progress.percent = percent;
progress.updated = true;
condition.notify_all();
};
// Orca: Worker thread that performs the actual model repair operations.
auto worker_thread = std::thread([&model_object, volume_idx, &ivolume, on_progress, &success, &canceled, &finished, &fix_result, keep_painting]() {
auto worker_thread = std::thread([&]() {
set_current_thread_name("cgal_fix_model");
try {
set_current_thread_name("cgal_fix_model");
for (std::size_t i = 0; i < volumes.size(); ++i) {
ModelVolume *volume = volumes[i];
const std::string name = volumes.size() > 1 ? volume->name : std::string();
const auto report = [&](int percent) {
if (canceled)
throw RepairCanceledException();
on_progress(name, int((100 * i + std::size_t(percent)) / volumes.size()));
};
report(0);
size_t start_volume = volume_idx == -1 ? 0 : size_t(volume_idx);
size_t end_volume = volume_idx == -1 ? std::numeric_limits<size_t>::max() : size_t(volume_idx);
for (ivolume = start_volume; ivolume < model_object.volumes.size(); ++ivolume) {
if (volume_idx != -1 && ivolume > end_volume)
break;
if (canceled)
throw RepairCanceledException();
on_progress(_u8L("Repairing model object"), 10);
ModelVolume *volume = model_object.volumes[ivolume];
// Orca: Split splittable volumes into parts for individual processing.
size_t parts_count = 1;
if (volume->is_splittable()) {
parts_count = volume->split(1, keep_painting);
if (parts_count > 1) {
const std::string msg = Slic3r::format(L("Split into %1% parts"), parts_count);
on_progress(msg, 10);
}
}
size_t part_end = std::min(ivolume + parts_count - 1, model_object.volumes.size() - 1);
if (volume_idx != -1)
end_volume = part_end;
size_t removed_parts = 0;
for (size_t idx = part_end + 1; idx > ivolume; --idx) {
const size_t part_idx = idx - 1;
const ModelVolume *part_volume = model_object.volumes[part_idx];
if (!is_not_3dimensional_part(part_volume->mesh()))
continue;
model_object.delete_volume(part_idx);
++removed_parts;
if (part_end > 0)
--part_end;
else
part_end = 0;
if (volume_idx != -1)
end_volume = part_end;
}
if (removed_parts >= parts_count) {
ivolume = part_end;
on_progress(_u8L("Repair finished"), 100);
continue;
}
for (size_t part_idx = ivolume; part_idx <= part_end && part_idx < model_object.volumes.size(); ++part_idx) {
ModelVolume *part_volume = model_object.volumes[part_idx];
TriangleMesh mesh = part_volume->mesh();
if (its_num_open_edges(mesh.its) != 0) {
// Save painting for later remap
const std::optional<TriangleSelector::SavedPainting> saved_painting = keep_painting ?
part_volume->save_painting() :
std::optional<TriangleSelector::SavedPainting>{};
std::string error;
if (!MeshBoolean::cgal::repair(mesh, nullptr, &error))
throw Slic3r::RuntimeError(error.empty() ? _u8L("Repair failed") : error);
part_volume->set_mesh(std::move(mesh));
part_volume->calculate_convex_hull();
part_volume->invalidate_convex_hull_2d();
part_volume->set_new_unique_id();
// Remap paint back
part_volume->restore_painting(saved_painting);
}
}
ivolume = part_end;
on_progress(_u8L("Repair finished"), 100);
MeshRepairStats stats;
std::string error;
if (!volume->repair(keep_painting, &stats, &error, report))
errors += (errors.empty() ? "" : "\n") + (volumes.size() > 1 ? volume->name + ": " : std::string()) + error;
any_modified = any_modified || stats.modified;
}
model_object.invalidate_bounding_box();
if (ivolume > 0)
--ivolume;
on_progress(_u8L("Repair finished"), 100);
success = true;
finished = true;
} catch (RepairCanceledException &) {
} catch (const RepairCanceledException &) {
canceled = true;
finished = true;
on_progress(_u8L("Repair canceled"), 100);
} catch (std::exception &ex) {
success = false;
finished = true;
fix_result = ex.what();
on_progress(ex.what(), 100);
} catch (const std::exception &ex) {
errors += (errors.empty() ? "" : "\n") + std::string(ex.what());
}
// Volumes repaired before a cancel or an error keep their new mesh.
model_object.invalidate_bounding_box();
finished = true;
on_progress(_u8L("Repair finished"), 100);
});
// Orca: Main GUI loop to update progress dialog and handle cancellation.
while (!finished) {
std::unique_lock<std::mutex> lock(mtx);
condition.wait_for(lock, std::chrono::milliseconds(250), [&progress]{ return progress.updated; });
// Decrease progress percent slightly to avoid auto-closing.
if (!progress_dialog.Update(progress.percent - 1, msg_header + _(progress.message)))
condition.wait_for(lock, std::chrono::milliseconds(250), [&progress] { return progress.updated; });
// One percent short of the maximum, so that the dialog does not close itself.
if (!progress_dialog.Update(std::max(0, progress.percent - 1), msg_header + wxString::FromUTF8(progress.message)))
canceled = true;
else
progress_dialog.Fit();
progress.updated = false;
}
if (canceled) {
// Nothing to show.
} else if (success) {
fix_result.clear();
}
if (worker_thread.joinable())
worker_thread.join();
fix_result = canceled ? std::string() : errors;
if (modified)
*modified = any_modified;
return !canceled;
}
+3 -2
View File
@@ -12,8 +12,9 @@ class Model;
class ModelObject;
class Print;
// Return false if fixing was canceled. fix_result is empty on success.
extern bool fix_model_with_cgal_gui(ModelObject &model_object, int volume_idx, GUI::ProgressDialog &progress_dlg, const wxString &msg_header, std::string &fix_result, bool keep_painting);
// Return false if fixing was canceled. fix_result is empty on success; modified tells whether any mesh changed.
extern bool fix_model_with_cgal_gui(ModelObject &model_object, int volume_idx, GUI::ProgressDialog &progress_dlg, const wxString &msg_header, std::string &fix_result, bool keep_painting,
bool *modified = nullptr);
} // namespace Slic3r
+16
View File
@@ -31,6 +31,22 @@ set_tests_properties(cli_project_missing_keys PROPERTIES
SKIP_RETURN_CODE 77
TIMEOUT 900)
add_test(NAME cli_arrange_rotations
COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/test_cli_arrange_rotations.sh $<TARGET_FILE:OrcaSlicer> ${ORCA_CLI_TEST_PYTHON}
${CMAKE_SOURCE_DIR}/resources/profiles/BBL)
set_tests_properties(cli_arrange_rotations PROPERTIES
LABELS "CLI;RequiresApp"
SKIP_RETURN_CODE 77
TIMEOUT 900)
add_test(NAME cli_no_suitable_objects
COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/test_cli_no_suitable_objects.sh $<TARGET_FILE:OrcaSlicer> ${ORCA_CLI_TEST_PYTHON}
${CMAKE_SOURCE_DIR}/resources/profiles/BBL)
set_tests_properties(cli_no_suitable_objects PROPERTIES
LABELS "CLI;RequiresApp"
SKIP_RETURN_CODE 77
TIMEOUT 900)
add_test(NAME cli_malformed_input
COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/test_cli_malformed_input.sh $<TARGET_FILE:OrcaSlicer> ${ORCA_CLI_TEST_PYTHON})
set_tests_properties(cli_malformed_input PROPERTIES
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env bash
# End-to-end check of the CLI's arrange rotation policy.
#
# Arrange is translate-only unless --allow-rotations is passed, so a bar that fits the bed only
# diagonally is not placed and the plate ends up with nothing fully inside the print volume. The
# run must then say that rotations were off, on stderr as well as in result.json, because
# result.json is written on Linux only. Passing the flag must place the same bar and slice it, and
# an object that fits axis-aligned must be unaffected by the default.
#
# usage: test_cli_arrange_rotations.sh <orca-slicer binary> <python3> <resources/profiles/BBL>
set -u
BIN="${1:-}"
PY="${2:-python3}"
PROFILES="${3:-}"
# 77 is the test's SKIP_RETURN_CODE.
[ -x "$BIN" ] || { echo "SKIP: orca-slicer binary not found: $BIN"; exit 77; }
[ -d "$PROFILES" ] || { echo "FAIL: profiles directory not found: $PROFILES"; exit 1; }
WORK="$(mktemp -d "${TMPDIR:-/tmp}/orca-cli-arrange-rotations.XXXXXX")"
trap 'rm -rf "$WORK"' EXIT
# box <file> <x> <y> <z>: an ASCII STL box, so the test needs no fixture.
box() {
"$PY" - "$@" <<'EOF'
import sys
out, sx, sy, sz = sys.argv[1], float(sys.argv[2]), float(sys.argv[3]), float(sys.argv[4])
v = [(x, y, z) for z in (0, sz) for y in (0, sy) for x in (0, sx)]
with open(out, "w") as f:
f.write("solid box\n")
for a, b, c, d in ((0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)):
for tri in ((v[a], v[b], v[c]), (v[a], v[c], v[d])):
f.write("facet normal 0 0 0\nouter loop\n")
for p in tri:
f.write("vertex %g %g %g\n" % p)
f.write("endloop\nendfacet\n")
f.write("endsolid box\n")
EOF
}
# Longer than the 256 mm bed edge, shorter than its 362 mm diagonal: it fits only turned.
box "$WORK/bar.stl" 300 10 5
# Fits axis-aligned, so the default must not change anything for it.
box "$WORK/cube.stl" 10 10 10
# slice <tag> <input> [option...] -> $WORK/<tag>/{rc,stdout,stderr,result.json}
slice() {
local out="$WORK/$1" input="$2"; shift 2
mkdir -p "$out"
timeout 300 "$BIN" --datadir "$out/datadir" \
--load-settings "$PROFILES/machine/Bambu Lab X1 Carbon 0.4 nozzle.json;$PROFILES/process/0.20mm Standard @BBL X1C.json" \
--load-defaultfila "$@" --slice 0 --outputdir "$out" "$input" \
> "$out/stdout" 2> "$out/stderr"
echo "$?" > "$out/rc"
}
# exit_code <tag>: the CLI's negative code as the shell saw it, e.g. -50 arrives as 206.
exit_code() { "$PY" -c "import sys; rc = int(open(sys.argv[1]).read()); print(rc - 256 if rc > 127 else rc)" "$WORK/$1/rc"; }
fail() { echo "FAIL: $*"; exit 1; }
# 1. Default: no flag, so no rotations, so the bar does not fit and the reason names rotation.
slice default "$WORK/bar.stl"
[ "$(exit_code default)" = "-50" ] || fail "default: expected -50, got $(exit_code default)"
grep -q "Arrange ran without rotations" "$WORK/default/stderr" \
|| fail "default: stderr does not mention rotations: $(cat "$WORK/default/stderr")"
"$PY" - "$WORK/default/result.json" <<'EOF' || exit 1
import json, sys
result = json.load(open(sys.argv[1]))
if result["return_code"] != -50:
sys.exit("FAIL: result.json return_code %s, expected -50" % result["return_code"])
if "Arrange ran without rotations" not in result["error_string"]:
sys.exit("FAIL: result.json error_string does not mention rotations: %s" % result["error_string"])
EOF
# 2. The flag is coBool, so it takes no value: it must place the same bar and slice it.
slice rotations "$WORK/bar.stl" --allow-rotations
[ "$(exit_code rotations)" = "0" ] || fail "--allow-rotations: expected 0, got $(exit_code rotations); $(tail -n 5 "$WORK/rotations/stdout")"
[ -s "$WORK/rotations/plate_1.gcode" ] || fail "--allow-rotations: no g-code written"
# 3. An object that fits axis-aligned is unaffected by the default, and says nothing about rotation.
slice cube "$WORK/cube.stl"
[ "$(exit_code cube)" = "0" ] || fail "cube: expected 0, got $(exit_code cube); $(tail -n 5 "$WORK/cube/stdout")"
[ -s "$WORK/cube/plate_1.gcode" ] || fail "cube: no g-code written"
grep -q "Arrange ran without rotations" "$WORK/cube/stderr" && fail "cube: unexpected rotation message on a successful run"
echo "PASS: arrange rotation default, its failure message, and the opt-in flag"
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env bash
# The reason recorded for CLI_NO_SUITABLE_OBJECTS (-50) has to fit the input the CLI was given.
# Any input format is arranged and sliced, so an object larger than the bed empties the plate just
# as a 3mf with an empty plate does, and the recorded reason must not send such a caller off to
# inspect a 3mf or an upload that is not part of their run.
#
# usage: test_cli_no_suitable_objects.sh <orca-slicer binary> <python3> <resources/profiles/BBL>
set -u
BIN="${1:-}"
PY="${2:-python3}"
PROFILES="${3:-}"
# 77 is the test's SKIP_RETURN_CODE.
[ -x "$BIN" ] || { echo "SKIP: orca-slicer binary not found: $BIN"; exit 77; }
[ -d "$PROFILES" ] || { echo "FAIL: profiles directory not found: $PROFILES"; exit 1; }
WORK="$(mktemp -d "${TMPDIR:-/tmp}/orca-cli-no-suitable-objects.XXXXXX")"
trap 'rm -rf "$WORK"' EXIT
# box <file> <x> <y> <z>: an ASCII STL box, so the test needs no fixture.
box() {
"$PY" - "$@" <<'EOF'
import sys
out, sx, sy, sz = sys.argv[1], float(sys.argv[2]), float(sys.argv[3]), float(sys.argv[4])
v = [(x, y, z) for z in (0, sz) for y in (0, sy) for x in (0, sx)]
with open(out, "w") as f:
f.write("solid box\n")
for a, b, c, d in ((0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)):
for tri in ((v[a], v[b], v[c]), (v[a], v[c], v[d])):
f.write("facet normal 0 0 0\nouter loop\n")
for p in tri:
f.write("vertex %g %g %g\n" % p)
f.write("endloop\nendfacet\n")
f.write("endsolid box\n")
EOF
}
# Wider than the 256 mm bed and wider than its 362 mm diagonal, so no placement can fit it.
box "$WORK/slab.stl" 400 400 5
# Fits, so the run must succeed: proves the harness itself is sound.
box "$WORK/cube.stl" 10 10 10
# slice <tag> <input> [option...] -> $WORK/<tag>/{rc,stdout,stderr,result.json}
slice() {
local out="$WORK/$1" input="$2"; shift 2
mkdir -p "$out"
timeout 300 "$BIN" --datadir "$out/datadir" \
--load-settings "$PROFILES/machine/Bambu Lab X1 Carbon 0.4 nozzle.json;$PROFILES/process/0.20mm Standard @BBL X1C.json" \
"$@" --slice 0 --outputdir "$out" "$input" \
> "$out/stdout" 2> "$out/stderr"
echo "$?" > "$out/rc"
}
# exit_code <tag>: the CLI's negative code as the shell saw it, e.g. -50 arrives as 206.
exit_code() { "$PY" -c "import sys; rc = int(open(sys.argv[1]).read()); print(rc - 256 if rc > 127 else rc)" "$WORK/$1/rc"; }
fail() { echo "FAIL: $*"; exit 1; }
# --allow-rotations keeps this on the generic reason: a translate-only arrange has its own,
# more specific one. The slab is wider than the 362 mm bed diagonal, so rotation cannot place it.
slice slab "$WORK/slab.stl" --allow-rotations
[ "$(exit_code slab)" = "-50" ] || fail "slab: expected -50, got $(exit_code slab); $(tail -n 5 "$WORK/slab/stdout")"
"$PY" - "$WORK/slab/result.json" <<'EOF' || exit 1
import json, sys
result = json.load(open(sys.argv[1]))
if result["return_code"] != -50:
sys.exit("FAIL: result.json return_code %s, expected -50" % result["return_code"])
reason = result["error_string"]
if not reason.strip():
sys.exit("FAIL: result.json carries no error_string")
# The run was handed an STL and asked for g-code: neither a 3mf nor an upload exists to check.
for word in ("3mf", "3MF", "upload"):
if word in reason:
sys.exit("FAIL: error_string mentions %r for an STL run: %s" % (word, reason))
EOF
slice cube "$WORK/cube.stl"
[ "$(exit_code cube)" = "0" ] || fail "cube: expected 0, got $(exit_code cube); $(tail -n 5 "$WORK/cube/stdout")"
[ -s "$WORK/cube/plate_1.gcode" ] || fail "cube: no g-code written"
echo "PASS: the no-suitable-objects reason fits a non-3mf run"
@@ -0,0 +1,35 @@
ISO-10303-21;
HEADER;
FILE_DESCRIPTION((''),'2;1');
FILE_NAME('surface_model_geometric_set','2026-10-12T00:00:00',(''),(''),'','','');
FILE_SCHEMA(('CONFIG_CONTROL_DESIGN'));
ENDSEC;
DATA;
#1=APPLICATION_CONTEXT('configuration controlled 3d designs of mechanical parts and assemblies');
#2=APPLICATION_PROTOCOL_DEFINITION('international standard','config_control_design',1994,#1);
#3=MECHANICAL_CONTEXT('',#1,'mechanical');
#4=PRODUCT('surfaces','surfaces','',(#3));
#5=PRODUCT_DEFINITION_FORMATION_WITH_SPECIFIED_SOURCE('','',#4,.NOT_KNOWN.);
#6=DESIGN_CONTEXT('',#1,'design');
#7=PRODUCT_DEFINITION('','',#5,#6);
#8=PRODUCT_DEFINITION_SHAPE('','',#7);
#9=SHAPE_DEFINITION_REPRESENTATION(#8,#20);
#10=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));
#11=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.));
#12=(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT());
#13=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-6),#10,'distance_accuracy_value','');
#14=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#13))GLOBAL_UNIT_ASSIGNED_CONTEXT((#10,#11,#12))REPRESENTATION_CONTEXT('',''));
#15=CARTESIAN_POINT('',(0.,0.,0.));
#16=DIRECTION('',(0.,0.,1.));
#17=DIRECTION('',(1.,0.,0.));
#18=AXIS2_PLACEMENT_3D('',#15,#16,#17);
#19=GEOMETRIC_SET('',(#30,#40));
#20=GEOMETRICALLY_BOUNDED_SURFACE_SHAPE_REPRESENTATION('',(#18,#19),#14);
#30=RECTANGULAR_TRIMMED_SURFACE('',#31,0.,10.,0.,10.,.T.,.T.);
#31=PLANE('',#18);
#40=RECTANGULAR_TRIMMED_SURFACE('',#41,0.,10.,0.,10.,.T.,.T.);
#41=PLANE('',#42);
#42=AXIS2_PLACEMENT_3D('',#43,#16,#17);
#43=CARTESIAN_POINT('',(0.,0.,10.));
ENDSEC;
END-ISO-10303-21;
+55
View File
@@ -178,6 +178,61 @@ bool is_block_move(const GCodeProcessorResult::MoveVertex &move)
} // namespace
TEST_CASE("Loaded manual tool change comments switch subsequent moves when enabled", "[GCodeProcessor][Regression]")
{
const bool manual_filament_change = GENERATE(false, true);
CAPTURE(manual_filament_change);
const DynamicPrintConfig config = Test::multifilament_config(2, {
{ "gcode_flavor", "marlin" },
{ "filament_type", "PLA;PETG" },
{ "manual_filament_change", manual_filament_change },
});
const bool was_bbl_printer = GCodeProcessor::s_IsBBLPrinter;
const ScopeGuard restore_bbl_printer([was_bbl_printer] { GCodeProcessor::s_IsBBLPrinter = was_bbl_printer; });
GCodeProcessor::s_IsBBLPrinter = false;
ScopedTemporaryFile temp(".gcode");
{
std::ofstream out(temp.string());
REQUIRE(out.is_open());
out << "; generated by OrcaSlicer\n"
<< "G90\nM83\nT0\n"
<< "G1 X10 Y10 Z0.2 F3000\n"
<< "G1 X20 E1\n"
<< "; MANUAL_TOOL_CHANGE T1\n"
<< "G1 X30\nG1 X40 E1\nG1 X50\nG1 X60 E1\n";
// Let process_file load the embedded DynamicPrintConfig, as the standalone viewer does.
out << "; CONFIG_BLOCK_START\n";
for (const std::string &key : config.keys())
out << "; " << key << " = " << config.opt_serialize(key) << '\n';
out << "; CONFIG_BLOCK_END\n";
REQUIRE(out.good());
}
GCodeProcessor processor;
processor.process_file(temp.string());
const auto &result = processor.get_result();
REQUIRE(result.filaments_count == 2);
constexpr unsigned int tool_change_line = 7;
size_t before = 0;
size_t after = 0;
for (const auto &move : result.moves) {
if (!is_block_move(move))
continue;
CAPTURE(move.gcode_id, move.type);
if (move.gcode_id < tool_change_line) {
++before;
CHECK(move.extruder_id == 0);
} else if (move.gcode_id > tool_change_line) {
++after;
CHECK(move.extruder_id == (manual_filament_change ? 1 : 0));
}
}
REQUIRE(before > 0);
REQUIRE(after > 0);
}
TEST_CASE("Actual speed moves are inserted on their block's segment just before its move", "[GCodeProcessor]")
{
// 60 squares take several planner passes, which remap the blocks kept between passes.
+26
View File
@@ -1748,3 +1748,29 @@ TEST_CASE("Percent accelerations resolve against the option they are a percentag
REQUIRE(accelerations_by_role[role_name] == std::set<int>{ value });
}
}
TEST_CASE("Initial filament start G-code tolerates a list shorter than the filament count", "[GCodeWriter]")
{
// Two filaments but only one filament_start_gcode entry, and the only object prints on
// filament 2, so the BBL export starts on a filament past the end of the list.
DynamicPrintConfig config = multifilament_config(2);
config.set_key_value("filament_start_gcode", new ConfigOptionStrings({"; filament start"}));
Model model;
auto *obj = model.add_object();
obj->add_volume(cube(20));
obj->add_instance();
obj->config.set_key_value("extruder", new ConfigOptionInt(2));
Print print;
print.is_BBL_printer() = true;
arrange_objects_on_test_bed(model, config);
for (auto *mo : model.objects) {
mo->ensure_on_bed();
print.auto_assign_extruders(mo);
}
print.apply(model, config);
print.validate();
REQUIRE_NOTHROW(Slic3r::Test::gcode(print));
}
+4 -1
View File
@@ -223,7 +223,10 @@ DynamicPrintConfig multifilament_config(unsigned int filaments, std::initializer
// These are read by filament id during export but absent from filament_option_keys(),
// so set_num_filaments leaves them size 1; size them too, else out-of-range access.
const auto &defaults = FullPrintConfig::defaults();
for (const char *key : { "filament_type", "filament_vendor", "filament_start_gcode" })
for (const char *key : { "filament_type", "filament_vendor", "filament_start_gcode", "filament_change_length", "filament_change_length_nc",
"filament_ramming_travel_time", "filament_ramming_travel_time_nc",
"filament_ramming_volumetric_speed", "filament_ramming_volumetric_speed_nc",
"nozzle_temperature", "nozzle_temperature_initial_layer" })
static_cast<ConfigOptionVectorBase *>(config.option(key, true))->resize(filaments, defaults.option(key));
// flush_volumes_matrix must be sized filaments*filaments or export rejects it.
+73
View File
@@ -315,6 +315,79 @@ TEST_CASE("Per-object wall filament override is honored", "[MultiFilament]")
CHECK(tools_for_role(gcode, "infill") == std::set<int>{ 0 }); // infill not overridden: stays on F1
}
// FanMover's guard against splitting a G1 inside custom gcode keys off the ";_FAN_MOVER_SKIP_START/END"
// markers GCode::set_extruder() must emit around change_filament_gcode's output. Direct
// toolchanges and Type2's wipe-tower toolchange (append_tcr2() calls set_extruder()) both go
// through it; Type1's wipe-tower toolchange (WipeTowerIntegration::append_tcr(), append_tcr2's only
// sibling caller of change_filament_gcode) needs the same bracketing of its own.
TEST_CASE("Toolchange gcode is bracketed against FanMover splitting its moves", "[MultiFilament]")
{
const std::string custom_gcode = "; fan full\nM106 P1 S255\nM400 S3\nG1 X77 F5000\nG1 X91 F3000\n";
// "direct": no prime tower, GCode::set_extruder() runs the toolchange. By-object sequencing
// with a per-object filament override is what makes one happen at all without a tower.
// "type1": a Type1 prime tower routes the toolchange through WipeTowerIntegration::append_tcr()
// instead (append_tcr2, Type2's equivalent, itself calls set_extruder() - so Type2 needs no
// separate case here).
const std::string path = GENERATE(as<std::string>{}, "direct", "type1");
CAPTURE(path);
std::string gcode_str;
if (path == "direct") {
const std::vector<std::vector<Slic3r::ConfigBase::SetDeserializeItem>> per_object_overrides = {
{}, { { "outer_wall_filament_id", "2" }, { "inner_wall_filament_id", "2" } }
};
DynamicPrintConfig config = multifilament_config(2, {
{ "skirt_loops", 0 },
{ "brim_type", "no_brim" },
{ "print_sequence", "by object" },
{ "change_filament_gcode", custom_gcode },
{ "fan_speedup_time", 0.5 },
{ "fan_kickstart", 0.1 },
});
gcode_str = slice_with_object_overrides({ cube(20), cube(20) }, config, per_object_overrides);
} else {
const std::vector<std::vector<Slic3r::ConfigBase::SetDeserializeItem>> per_object_overrides = {
{ { "extruder", "1" } }, { { "extruder", "2" } }
};
DynamicPrintConfig config = multifilament_config(2, {
{ "change_filament_gcode", custom_gcode },
{ "fan_speedup_time", 0.5 },
{ "fan_kickstart", 0.1 },
{ "enable_prime_tower", true },
{ "wipe_tower_type", "type1" },
{ "prime_tower_width", 35 },
{ "wipe_tower_x", 120 },
{ "wipe_tower_y", 120 },
{ "printable_area", "0x0,200x0,200x200,0x200" },
{ "skirt_loops", 0 },
{ "brim_type", "no_brim" },
});
gcode_str = slice_with_object_overrides({ cube(20), cube(20) }, config, per_object_overrides);
}
// The resolved-settings config footer echoes "change_filament_gcode = ..." with its value
// escaped, so drop it before counting or its own copy of "G1 X77 F5000" is miscounted.
const size_t footer_start = gcode_str.find("; CONFIG_BLOCK_START");
REQUIRE(footer_start != std::string::npos);
gcode_str.erase(footer_start);
auto count_occurrences = [](const std::string &haystack, const std::string &needle) {
size_t count = 0, pos = 0;
while ((pos = haystack.find(needle, pos)) != std::string::npos) {
++count;
pos += needle.size();
}
return count;
};
const size_t total_waypoints = count_occurrences(gcode_str, "G1 X77 F5000");
const size_t bracketed = count_occurrences(gcode_str, "M400 S3\nG1 X77 F5000");
REQUIRE(total_waypoints > 0);
CHECK(bracketed == total_waypoints);
// FanMover drops its own markers; only the start-of-print toolchange, which it never processes, keeps them.
CHECK(count_occurrences(gcode_str, ";_FAN_MOVER_SKIP_START") <= 1);
}
// With wait_for_temp_on_wipe_tower the blocking M109 moves from right after the Tn command to
// a stop point parked beside the wipe tower (heat-up drool falls next to the tower, not onto
// its top): tagged with _WAIT_FOR_TEMP_ON_WIPE_TOWER, after the toolchange and before the
+76
View File
@@ -43,6 +43,7 @@
#include "libslic3r/GCode/GCodeProcessor.hpp"
#include "libslic3r/Exception.hpp"
#include "libslic3r/LifecycleEvents.hpp"
#include "libslic3r/Utils.hpp"
#include "test_helpers.hpp"
#include "test_utils.hpp"
@@ -156,6 +157,81 @@ SCENARIO("Changing the number of solid shell layers does not make all surfaces i
}
}
// Two copies of one object share a single slice. When a copy that has sliced itself becomes identical to an
// earlier object, it keeps its own layers while that object slices and only then takes the shared layers over.
TEST_CASE("An object that starts sharing another object's slices keeps its own layers until it takes them over", "[Print][Regression]")
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "layer_height", 0.2 },
{ "initial_layer_print_height", 0.2 },
{ "raft_layers", 1 }, // each object gets support layers of its own
{ "sparse_infill_density", "20%" }, // object_a's override below differs from this
});
// Activates the slicing-pipeline hook installed for the second slice below.
config.set_key_value("slicing_pipeline_plugin", new ConfigOptionStrings({"probe"}));
Print print;
Model model;
init_print({cube(20)}, print, model, config);
ModelObject *object_a = model.objects.front();
// add_object() gives the copy extruder 1, and objects only share slices when their configs match.
object_a->config.set_key_value("extruder", new ConfigOptionInt(1));
ModelObject *object_b = model.add_object(*object_a); // shares object_a's mesh
for (ModelInstance *instance : object_b->instances)
instance->set_offset(instance->get_offset() + Vec3d(40., 0., 0.));
// A per-object override makes the objects differ, so each slices itself.
object_a->config.set_key_value("sparse_infill_density", new ConfigOptionPercent(40));
print.apply(model, config);
print.process();
REQUIRE(print.objects().size() == 2);
// The non-const accessors hand out the layer vectors themselves, which the checks below compare.
PrintObject *print_b = print.get_object(1);
REQUIRE(print_b->model_object()->id() == object_b->id()); // Print slices its own copy of the model
REQUIRE(print_b->get_shared_object() == nullptr);
const LayerPtrs own_layers = print_b->layers();
const SupportLayerPtrs own_support_layers = print_b->support_layers();
REQUIRE(!own_layers.empty());
REQUIRE(!own_support_layers.empty());
// Without the override the objects are identical again: print_a redoes the steps the setting invalidated,
// and print_b shares it.
object_a->config.erase("sparse_infill_density");
print.apply(model, config);
REQUIRE(print.objects().size() == 2);
PrintObject *print_a = print.get_object(0);
// Erasing the override invalidates print_a's posPrepareInfill and the steps after it. Its hook is the first one
// print_a fires, and it runs after print_b starts sharing but before print_b takes the shared layers over.
bool hook_fired = false;
bool shared_while_a_runs = false;
bool kept_layers = false;
bool kept_support_layers = false;
{
Print::set_slicing_pipeline_hook_fn([&](Print &, const PrintObject *object, SlicingPipelineStepPlugin) {
if (object != print_a || hook_fired)
return;
hook_fired = true;
shared_while_a_runs = print_b->get_shared_object() == print_a;
kept_layers = print_b->layers() == own_layers;
kept_support_layers = print_b->support_layers() == own_support_layers;
});
const ScopeGuard reset_hook([] { Print::set_slicing_pipeline_hook_fn(nullptr); });
print.process();
}
REQUIRE(hook_fired);
CHECK(print.objects()[1] == print_b);
CHECK(shared_while_a_runs);
CHECK(kept_layers);
CHECK(kept_support_layers);
CHECK(print_b->get_shared_object() == print_a);
REQUIRE(!print_a->layers().empty());
CHECK(print_b->layers() == print_a->layers());
CHECK(print_b->support_layers() == print_a->support_layers());
}
// ---------------------------------------------------------------------------
// Print::validate() warning collection
//
+1
View File
@@ -53,6 +53,7 @@ add_executable(${_TEST_NAME}_tests
test_stl.cpp
test_triangle_selector.cpp
test_meshboolean.cpp
test_mesh_repair.cpp
test_trianglemesh_slicer.cpp
test_marchingsquares.cpp
test_lay_on_face.cpp
+255
View File
@@ -0,0 +1,255 @@
#include <catch2/catch_test_macros.hpp>
#include <catch2/matchers/catch_matchers.hpp>
#include <catch2/matchers/catch_matchers_floating_point.hpp>
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <string>
#include <utility>
#include <vector>
#include <libslic3r/MeshBoolean.hpp>
#include <libslic3r/MeshRepair.hpp>
#include <libslic3r/Point.hpp>
#include <libslic3r/libslic3r.h>
#include <libslic3r/TriangleMesh.hpp>
using namespace Slic3r;
using Catch::Matchers::WithinRel;
namespace {
indexed_triangle_set cube(double size, const Vec3d &offset = Vec3d::Zero())
{
TriangleMesh mesh = make_cube(size, size, size);
mesh.translate(offset.cast<float>());
return mesh.its;
}
indexed_triangle_set merged(const std::vector<indexed_triangle_set> &parts)
{
indexed_triangle_set out;
for (const indexed_triangle_set &part : parts)
its_merge(out, part);
return out;
}
// Every triangle with its own three vertices, as some exporters write meshes.
indexed_triangle_set soup(const indexed_triangle_set &its)
{
indexed_triangle_set out;
for (const stl_triangle_vertex_indices &f : its.indices) {
const int first = int(out.vertices.size());
for (int k = 0; k < 3; ++k)
out.vertices.push_back(its.vertices[f[k]]);
out.indices.emplace_back(first, first + 1, first + 2);
}
return out;
}
double regular_polygon_area(int sides, double radius) { return 0.5 * sides * radius * radius * std::sin(2. * PI / sides); }
// Closed by vertex indices, outward oriented and free of self-intersections.
void check_solid(const TriangleMesh &mesh, double volume)
{
CHECK(its_num_open_edges(mesh.its) == 0);
CHECK_THAT(its_volume(mesh.its), WithinRel(volume, 1e-4));
CHECK_FALSE(MeshBoolean::cgal::does_self_intersect(mesh));
}
} // namespace
TEST_CASE("A triangle soup repairs into the solid it describes", "[MeshRepair]")
{
TriangleMesh mesh(soup(cube(20.)));
MeshRepairStats stats;
REQUIRE(repair_mesh(mesh, &stats));
CHECK(stats.modified);
check_solid(mesh, 20. * 20. * 20.);
CHECK(mesh.its.vertices.size() == 8);
}
TEST_CASE("Flipped triangles take the orientation of their neighbours", "[MeshRepair]")
{
indexed_triangle_set its = cube(20.);
std::swap(its.indices[1][1], its.indices[1][2]);
std::swap(its.indices[5][1], its.indices[5][2]);
TriangleMesh mesh(std::move(its));
REQUIRE(repair_mesh(mesh));
check_solid(mesh, 20. * 20. * 20.);
}
TEST_CASE("An inside-out mesh is turned outward", "[MeshRepair]")
{
indexed_triangle_set its = cube(20.);
its_flip_triangles(its);
TriangleMesh mesh(std::move(its));
REQUIRE(repair_mesh(mesh));
check_solid(mesh, 20. * 20. * 20.);
}
TEST_CASE("Holes are filled", "[MeshRepair]")
{
indexed_triangle_set its = cube(20.);
its.indices.erase(its.indices.begin(), its.indices.begin() + 3);
TriangleMesh mesh(std::move(its));
MeshRepairStats stats;
REQUIRE(repair_mesh(mesh, &stats));
CHECK(stats.filled_holes > 0);
check_solid(mesh, 20. * 20. * 20.);
}
TEST_CASE("Cracks between triangles that should share corners are closed", "[MeshRepair]")
{
indexed_triangle_set its = soup(cube(20.));
// Shift the corners of two triangles by far less than a micron, as float rounding in an exporter would.
for (std::size_t v = 0; v < 6; ++v)
its.vertices[v] += Vec3f(1e-5f, -1e-5f, 1e-5f);
TriangleMesh mesh(std::move(its));
MeshRepairStats stats;
REQUIRE(repair_mesh(mesh, &stats));
CHECK(stats.welded_vertices > 0);
check_solid(mesh, 20. * 20. * 20.);
}
TEST_CASE("A T-junction is closed", "[MeshRepair]")
{
// The top of the cube is split at the middle of its front edge, which the front side does not share.
indexed_triangle_set its;
its.vertices = {{0, 0, 0}, {20, 0, 0}, {20, 20, 0}, {0, 20, 0}, {0, 0, 20}, {20, 0, 20}, {20, 20, 20}, {0, 20, 20}, {10, 0, 20}};
its.indices = {{0, 2, 1}, {0, 3, 2}, {4, 8, 7}, {8, 6, 7}, {8, 5, 6}, {0, 1, 5}, {0, 5, 4},
{1, 2, 6}, {1, 6, 5}, {2, 3, 7}, {2, 7, 6}, {3, 0, 4}, {3, 4, 7}};
TriangleMesh mesh(std::move(its));
REQUIRE(repair_mesh(mesh));
check_solid(mesh, 20. * 20. * 20.);
}
TEST_CASE("Crossing shells stay separate parts and are made solid", "[MeshRepair]")
{
indexed_triangle_set inside_out = cube(20., {10., 10., 10.});
its_flip_triangles(inside_out);
TriangleMesh mesh(merged({cube(20.), inside_out}));
MeshRepairStats stats;
REQUIRE(repair_mesh(mesh, &stats));
CHECK(stats.reversed_shells == 1);
CHECK(its_num_open_edges(mesh.its) == 0);
CHECK_THAT(its_volume(mesh.its), WithinRel(2 * 8000., 1e-4));
CHECK(mesh.split().size() == 2);
}
TEST_CASE("Solids touching face to face in a soup lose the wall between them", "[MeshRepair]")
{
// The mirrored copy shares the wall at x = 10 with exactly the same triangles, reversed.
TriangleMesh right = make_cube(10., 10., 10.);
right.mirror(X);
right.translate(20.f, 0.f, 0.f);
TriangleMesh mesh(soup(merged({cube(10.), right.its})));
REQUIRE(repair_mesh(mesh));
check_solid(mesh, 2 * 1000.);
CHECK(mesh.split().size() == 1);
}
TEST_CASE("A shell inside a solid follows the nonzero winding rule of slicing", "[MeshRepair]")
{
SECTION("Oriented like the outer shell, it adds nothing and is removed")
{
TriangleMesh mesh(merged({cube(20.), cube(10., {5., 5., 5.})}));
REQUIRE(repair_mesh(mesh));
check_solid(mesh, 8000.);
CHECK(mesh.its.indices.size() == 12);
}
SECTION("Oriented inward, it is a cavity and stays")
{
indexed_triangle_set cavity = cube(10., {5., 5., 5.});
its_flip_triangles(cavity);
TriangleMesh mesh(merged({cube(20.), cavity}));
MeshRepairStats stats;
REQUIRE(repair_mesh(mesh, &stats));
CHECK_FALSE(stats.modified);
CHECK_THAT(its_volume(mesh.its), WithinRel(8000. - 1000., 1e-4));
}
}
TEST_CASE("A pipe missing its end caps gets annular caps", "[MeshRepair]")
{
const int n = 64;
const double h = 20., r_out = 10., r_in = 7.;
indexed_triangle_set its;
for (const double r : {r_out, r_in})
for (int k = 0; k < n; ++k) {
const double a = 2. * PI * k / n;
its.vertices.emplace_back(float(r * std::cos(a)), float(r * std::sin(a)), 0.f);
its.vertices.emplace_back(float(r * std::cos(a)), float(r * std::sin(a)), float(h));
}
for (int k = 0; k < n; ++k) {
const int a0 = 2 * k, b0 = a0 + 1, a1 = 2 * ((k + 1) % n), b1 = a1 + 1;
its.indices.emplace_back(a0, a1, b1);
its.indices.emplace_back(a0, b1, b0);
its.indices.emplace_back(2 * n + a0, 2 * n + b1, 2 * n + a1);
its.indices.emplace_back(2 * n + a0, 2 * n + b0, 2 * n + b1);
}
TriangleMesh mesh(std::move(its));
REQUIRE(repair_mesh(mesh));
check_solid(mesh, h * (regular_polygon_area(n, r_out) - regular_polygon_area(n, r_in)));
}
TEST_CASE("A stray flat triangle is dropped", "[MeshRepair]")
{
indexed_triangle_set its = cube(20.);
its.vertices.insert(its.vertices.end(), {{30, 0, 0}, {40, 0, 0}, {30, 10, 0}});
its.indices.emplace_back(8, 9, 10);
TriangleMesh mesh(std::move(its));
MeshRepairStats stats;
REQUIRE(repair_mesh(mesh, &stats));
CHECK(stats.removed_shells == 1);
check_solid(mesh, 8000.);
}
TEST_CASE("A two-sided export keeps one side of each triangle", "[MeshRepair]")
{
indexed_triangle_set back = cube(20.);
its_flip_triangles(back);
TriangleMesh mesh(soup(merged({cube(20.), back})));
REQUIRE(repair_mesh(mesh));
check_solid(mesh, 8000.);
}
TEST_CASE("A valid mesh is left untouched", "[MeshRepair]")
{
TriangleMesh mesh = make_sphere(10., 2. * PI / 36.);
const TriangleMesh original = mesh;
MeshRepairStats stats;
REQUIRE(repair_mesh(mesh, &stats));
CHECK_FALSE(stats.modified);
CHECK(mesh.its.vertices == original.its.vertices);
CHECK(mesh.its.indices == original.its.indices);
}
TEST_CASE("A mesh enclosing no volume is reported and left untouched", "[MeshRepair]")
{
indexed_triangle_set its;
its.vertices = {{0, 0, 0}, {10, 0, 0}, {10, 10, 0}, {0, 10, 0}};
its.indices = {{0, 1, 2}, {0, 2, 3}};
TriangleMesh mesh(its);
std::string error;
CHECK_FALSE(repair_mesh(mesh, nullptr, &error));
CHECK_FALSE(error.empty());
CHECK(mesh.its.indices.size() == 2);
}
TEST_CASE("Progress is reported in order and throwing from it cancels the repair", "[MeshRepair]")
{
TriangleMesh mesh(soup(cube(20.)));
std::vector<int> reported;
REQUIRE(repair_mesh(mesh, nullptr, nullptr, [&reported](int percent) { reported.push_back(percent); }));
CHECK_FALSE(reported.empty());
CHECK(std::is_sorted(reported.begin(), reported.end()));
struct Canceled {};
TriangleMesh canceled(soup(cube(20.)));
const TriangleMesh original = canceled;
CHECK_THROWS_AS(repair_mesh(canceled, nullptr, nullptr, [](int) { throw Canceled(); }), Canceled);
CHECK(canceled.its.vertices == original.its.vertices);
CHECK(canceled.its.indices == original.its.indices);
}
+103
View File
@@ -12,7 +12,9 @@
#include <catch2/generators/catch_generators.hpp>
#include <catch2/matchers/catch_matchers.hpp>
#include <catch2/matchers/catch_matchers_floating_point.hpp>
#include "libslic3r/MeshRepair.hpp"
#include "libslic3r/Model.hpp"
#include "libslic3r/ObjectID.hpp"
#include "libslic3r/Geometry.hpp"
#include "libslic3r/libslic3r.h"
@@ -97,3 +99,104 @@ TEST_CASE("An instance added from another's scale, rotation and mirror matches i
original->get_rotation(), original->get_mirror());
CHECK(copy->get_matrix().linear().isApprox(original->get_matrix().linear(), 1e-9));
}
namespace {
// A flat triangle first, then a cube for each offset, all in one mesh.
TriangleMesh flat_triangle_then_cubes(const std::vector<double> &cube_offsets)
{
indexed_triangle_set its;
its.vertices = {{-20.f, 0.f, 0.f}, {-10.f, 0.f, 0.f}, {-15.f, 5.f, 0.f}};
its.indices = {{0, 1, 2}};
for (double offset : cube_offsets) {
TriangleMesh cube = make_cube(10, 10, 10);
cube.translate(float(offset), 0.f, 0.f);
its_merge(its, cube.its);
}
return TriangleMesh(its);
}
} // namespace
TEST_CASE("Splitting a part drops pieces enclosing no volume and keeps the part itself", "[Model]")
{
Model model;
ModelObject *object = model.add_object();
ModelVolume *volume = object->add_volume(flat_triangle_then_cubes({0., 30.}), ModelVolumeType::MODEL_PART, false);
REQUIRE(volume->is_splittable());
CHECK(volume->split(1, false) == 2);
REQUIRE(object->volumes.size() == 2);
CHECK(std::find(object->volumes.begin(), object->volumes.end(), volume) != object->volumes.end());
for (const ModelVolume *part : object->volumes) {
CHECK(part->mesh().facets_count() == 12);
CHECK_FALSE(part->is_splittable());
}
}
TEST_CASE("Splitting a part with a single solid piece keeps just that piece", "[Model]")
{
Model model;
ModelObject *object = model.add_object();
ModelVolume *volume = object->add_volume(flat_triangle_then_cubes({0.}), ModelVolumeType::MODEL_PART, false);
CHECK(volume->split(1, false) == 1);
REQUIRE(object->volumes.size() == 1);
CHECK(object->volumes.front() == volume);
CHECK(volume->mesh().facets_count() == 12);
}
TEST_CASE("Splitting a part made only of pieces enclosing no volume leaves it whole", "[Model]")
{
Model model;
ModelObject *object = model.add_object();
indexed_triangle_set its;
its.vertices = {{0.f, 0.f, 0.f}, {10.f, 0.f, 0.f}, {5.f, 5.f, 0.f}, {20.f, 0.f, 0.f}, {30.f, 0.f, 0.f}, {25.f, 5.f, 0.f}};
its.indices = {{0, 1, 2}, {3, 4, 5}};
ModelVolume *volume = object->add_volume(TriangleMesh(its), ModelVolumeType::MODEL_PART, false);
CHECK(volume->split(1, false) == 1);
REQUIRE(object->volumes.size() == 1);
CHECK(object->volumes.front() == volume);
CHECK(volume->mesh().facets_count() == 2);
}
TEST_CASE("Replacing a part's mesh updates whether it can be split", "[Model]")
{
Model model;
ModelObject *object = model.add_object();
TriangleMesh two_cubes = make_cube(10, 10, 10);
TriangleMesh second = make_cube(10, 10, 10);
second.translate(30.f, 0.f, 0.f);
two_cubes.merge(second);
ModelVolume *volume = object->add_volume(std::move(two_cubes), ModelVolumeType::MODEL_PART, false);
REQUIRE(volume->is_splittable());
volume->set_mesh(make_cube(10, 10, 10));
CHECK_FALSE(volume->is_splittable());
}
TEST_CASE("Repairing a part replaces its mesh only when the repair changes it", "[Model]")
{
Model model;
ModelObject *object = model.add_object();
TriangleMesh flipped = make_cube(10, 10, 10);
std::swap(flipped.its.indices.front()[1], flipped.its.indices.front()[2]);
ModelVolume *broken = object->add_volume(std::move(flipped), ModelVolumeType::MODEL_PART, false);
TriangleMesh cube = make_cube(10, 10, 10);
cube.translate(30.f, 0.f, 0.f);
ModelVolume *valid = object->add_volume(std::move(cube), ModelVolumeType::MODEL_PART, false);
const ObjectID broken_id = broken->id();
const ObjectID valid_id = valid->id();
MeshRepairStats stats;
REQUIRE(broken->repair(false, &stats));
CHECK(stats.modified);
CHECK(broken->id() != broken_id);
CHECK_THAT(its_volume(broken->mesh().its), Catch::Matchers::WithinRel(1000., 1e-6));
CHECK_FALSE(broken->get_convex_hull().empty());
REQUIRE(valid->repair(false, &stats));
CHECK_FALSE(stats.modified);
CHECK(valid->id() == valid_id);
}
@@ -37,6 +37,7 @@
#include <utility>
#include "libslic3r/Config.hpp"
#include <map>
#include <memory>
#include "libslic3r/libslic3r.h"
#include "libslic3r/PublishSettings.hpp"
#include <set>
@@ -333,6 +334,105 @@ TEST_CASE("A directory of user presets loads with each one resolved against its
}
}
TEST_CASE("A user preset synced to the cloud and back keeps its values on every nozzle variant", "[Preset][Bundle]")
{
// Two extruders with a Standard and a High Flow variant each, as on a dual-nozzle printer.
auto add_parent = [](PresetCollection &coll) {
Preset &parent = add_inmemory_preset(coll, "Parent Process");
parent.config.set_key_value("print_extruder_variant",
new ConfigOptionStrings({"Direct Drive Standard", "Direct Drive High Flow", "Direct Drive Standard", "Direct Drive High Flow"}));
parent.config.set_key_value("print_extruder_id", new ConfigOptionInts({1, 1, 2, 2}));
parent.config.set_deserialize_strict("outer_wall_speed", "50,50,50,50");
parent.is_system = true;
parent.setting_id = "parent-id";
return parent.config;
};
RenameTestCollection local;
const DynamicPrintConfig parent_config = add_parent(local);
Preset &child = add_inmemory_preset(local, "User Process", "Parent Process");
child.config.apply_only(parent_config, {"print_extruder_variant", "print_extruder_id"});
child.config.set_deserialize_strict("outer_wall_speed", "11,12,21,22");
child.version = Semver(1, 0, 0);
std::map<std::string, std::string> uploaded;
REQUIRE(local.get_differed_values_to_update(child, uploaded) == 0);
uploaded[BBL_JSON_KEY_SETTING_ID] = "child-id";
uploaded[BBL_JSON_KEY_USER_ID] = "user";
// A cloud copy stored before uploads carried the variant layout holds the values alone.
std::map<std::string, std::string> stored_without_layout = uploaded;
stored_without_layout.erase("print_extruder_variant");
stored_without_layout.erase("print_extruder_id");
// One saved while the parent had a single variant covers the first extruder only.
std::map<std::string, std::string> stored_single_value = stored_without_layout;
stored_single_value["outer_wall_speed"] = "11";
struct Case { const char *label; std::map<std::string, std::string> values; const char *expected; };
for (const Case &c : {Case{"current upload", uploaded, "11,12,21,22"},
Case{"stored without layout", stored_without_layout, "11,12,21,22"},
Case{"stored with a single value", stored_single_value, "11,11,50,50"}}) {
DYNAMIC_SECTION(c.label) {
RenameTestCollection downloaded;
PresetsConfigSubstitutions substitutions;
add_parent(downloaded);
REQUIRE(downloaded.load_user_preset("User Process", c.values, substitutions, ForwardCompatibilitySubstitutionRule::Disable));
const Preset *synced = downloaded.find_preset("User Process");
REQUIRE(synced != nullptr);
CHECK(synced->config.opt_serialize("outer_wall_speed") == c.expected);
}
}
}
TEST_CASE("A user filament synced to the cloud and back keeps its values and unset overrides on every variant", "[Preset][Bundle]")
{
auto add_parent = [](PresetCollection &coll) {
Preset &parent = add_inmemory_preset(coll, "Parent Filament");
parent.config.set_key_value("filament_extruder_variant",
new ConfigOptionStrings({"Direct Drive Standard", "Direct Drive High Flow"}));
parent.config.set_deserialize_strict("nozzle_temperature", "220,220");
parent.config.set_deserialize_strict("filament_retraction_length", "nil,nil");
parent.is_system = true;
parent.setting_id = "parent-id";
return parent.config;
};
auto make_collection = [] {
return std::make_unique<PresetCollection>(Preset::TYPE_FILAMENT, Preset::filament_options(),
static_cast<const PrintRegionConfig &>(FullPrintConfig::defaults()));
};
auto local = make_collection();
add_parent(*local);
Preset &child = add_inmemory_preset(*local, "User Filament", "Parent Filament");
child.config.apply_only(add_parent(*make_collection()), {"filament_extruder_variant"});
child.config.set_deserialize_strict("nozzle_temperature", "200,210");
child.config.set_deserialize_strict("filament_retraction_length", "1.2,nil");
child.version = Semver(1, 0, 0);
std::map<std::string, std::string> uploaded;
REQUIRE(local->get_differed_values_to_update(child, uploaded) == 0);
uploaded[BBL_JSON_KEY_SETTING_ID] = "child-id";
uploaded[BBL_JSON_KEY_USER_ID] = "user";
std::map<std::string, std::string> stored_without_layout = uploaded;
stored_without_layout.erase("filament_extruder_variant");
for (const auto &[label, values] : {std::make_pair("current upload", uploaded),
std::make_pair("stored without layout", stored_without_layout)}) {
DYNAMIC_SECTION(label) {
auto downloaded = make_collection();
PresetsConfigSubstitutions substitutions;
add_parent(*downloaded);
REQUIRE(downloaded->load_user_preset("User Filament", values, substitutions, ForwardCompatibilitySubstitutionRule::Disable));
const Preset *synced = downloaded->find_preset("User Filament");
REQUIRE(synced != nullptr);
CHECK(synced->config.opt_serialize("nozzle_temperature") == "200,210");
CHECK(synced->config.opt_serialize("filament_retraction_length") == "1.2,nil");
}
}
}
TEST_CASE("Repeated loads of a user preset directory produce the same presets", "[Preset][Bundle]")
{
ScopedTemporaryDir temp_dir;
+21
View File
@@ -4,6 +4,7 @@
#include <string>
#include <ios>
#include <catch2/catch_message.hpp>
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include "libslic3r/Model.hpp"
@@ -91,6 +92,26 @@ TEST_CASE("A cone with a slightly tilted seam imports as a closed mesh", "[Step]
CHECK(its_num_open_edges(model.objects.front()->volumes.front()->mesh().its) == 0);
}
// The fixture holds two trimmed planes in a geometric set and no shells or solids, as some CAD exporters write
// surface models, so OCCT reads it as a compound of loose faces.
TEST_CASE("A surface model imports whether or not compounds are split", "[Step]")
{
const std::string path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR "surface_model_geometric_set.step";
const bool split = GENERATE(false, true);
CAPTURE(split);
Model model;
bool cancel = false;
Step step(path);
REQUIRE(step.load() == Step::Step_Status::LOAD_SUCCESS);
REQUIRE(step.mesh(&model, cancel, split) == Step::Step_Status::MESH_SUCCESS);
REQUIRE(model.objects.size() == 1);
REQUIRE(model.objects.front()->volumes.size() == 1);
CHECK(model.objects.front()->volumes.front()->mesh().facets_count() > 0);
}
TEST_CASE("isUtf8 recognises two, three and four byte sequences", "[Step]")
{
CHECK(StepPreProcessor::isUtf8("\xC3\xA9")); // U+00E9
+604 -350
View File
@@ -28,6 +28,7 @@
#include <algorithm>
#include <array>
#include <functional>
#include <cmath>
#include <fstream>
#include <limits>
@@ -1301,6 +1302,294 @@ TEST_CASE("TextureDisplacement: the step cutter only cuts inside the region", "[
}
}
// ---- Image adjustments (the gizmo's image-adjustment panel) ----------------------------------------
// A grayscale ramp 0..255 across the width, so every input level is present exactly once per row and a
// tonal curve can be read straight off the output.
static DecodedHeightTexture make_gray_ramp(int w = 256, int h = 4)
{
DecodedHeightTexture t;
t.width = w;
t.height = h;
t.pixels.resize(size_t(w) * size_t(h));
for (int y = 0; y < h; ++y)
for (int x = 0; x < w; ++x)
t.pixels[size_t(y) * size_t(w) + size_t(x)] = uint8_t(x * 255 / std::max(1, w - 1));
return t;
}
// A one-texel checkerboard of 0 and 255 - the highest spatial frequency the grid can hold, which is what
// a blur has to remove and a downscale has to average rather than drop.
static DecodedHeightTexture make_gray_checkerboard(int w = 16, int h = 16)
{
DecodedHeightTexture t;
t.width = w;
t.height = h;
t.pixels.resize(size_t(w) * size_t(h));
for (int y = 0; y < h; ++y)
for (int x = 0; x < w; ++x)
t.pixels[size_t(y) * size_t(w) + size_t(x)] = ((x + y) % 2 == 0) ? 0 : 255;
return t;
}
static DecodedHeightTexture make_rgb_flat(uint8_t r, uint8_t g, uint8_t b, int w = 8, int h = 8)
{
DecodedHeightTexture t;
t.width = w;
t.height = h;
t.pixels.resize(size_t(w) * size_t(h));
t.rgb.resize(size_t(w) * size_t(h) * 3);
for (size_t i = 0; i < size_t(w) * size_t(h); ++i) {
t.rgb[i * 3] = r;
t.rgb[i * 3 + 1] = g;
t.rgb[i * 3 + 2] = b;
t.pixels[i] = uint8_t(std::lround(0.299 * r + 0.587 * g + 0.114 * b));
}
return t;
}
TEST_CASE("an adjustment that moves no slider returns the image unchanged", "[TextureDisplacement]")
{
const DecodedHeightTexture src = make_gray_ramp();
const DecodedHeightTexture out = apply_texture_adjustments(src, TextureAdjustments{});
CHECK(out.width == src.width);
CHECK(out.height == src.height);
CHECK(out.pixels == src.pixels);
CHECK(TextureAdjustments{}.identity());
}
TEST_CASE("brightness reaches pure white and pure black only at the ends of its range", "[TextureDisplacement]")
{
const DecodedHeightTexture src = make_gray_ramp();
TextureAdjustments up;
up.brightness = 1.f;
const DecodedHeightTexture white = apply_texture_adjustments(src, up);
CHECK(std::all_of(white.pixels.begin(), white.pixels.end(), [](uint8_t v) { return v == 255; }));
TextureAdjustments down;
down.brightness = -1.f;
const DecodedHeightTexture black = apply_texture_adjustments(src, down);
CHECK(std::all_of(black.pixels.begin(), black.pixels.end(), [](uint8_t v) { return v == 0; }));
}
TEST_CASE("brightness lifts the image without flattening it into a clipped plateau", "[TextureDisplacement]")
{
// The reason brightness is a lift toward white rather than an additive offset: an offset would drive
// everything above mid-grey to a flat 255, and since this image is also the height map that region
// would bake as flat relief. Half a stop up must leave almost nothing at pure white.
const DecodedHeightTexture src = make_gray_ramp();
TextureAdjustments adj;
adj.brightness = 0.5f;
const DecodedHeightTexture out = apply_texture_adjustments(src, adj);
REQUIRE(out.pixels.size() == src.pixels.size());
const size_t clipped = size_t(std::count(out.pixels.begin(), out.pixels.end(), uint8_t(255)));
CHECK(clipped * 100 < out.pixels.size()); // under 1%; an additive shift would clip half the ramp
// Every texel got brighter, and the curve stays ordered: brighter in means brighter out.
for (size_t i = 0; i < out.pixels.size(); ++i)
REQUIRE(out.pixels[i] >= src.pixels[i]);
for (int x = 1; x < out.width; ++x)
REQUIRE(out.pixels[size_t(x)] >= out.pixels[size_t(x - 1)]);
}
TEST_CASE("contrast at its lowest flattens the image to mid-grey and at its highest spreads it apart",
"[TextureDisplacement]")
{
const DecodedHeightTexture src = make_gray_ramp();
TextureAdjustments flat;
flat.contrast = -1.f;
const DecodedHeightTexture grey = apply_texture_adjustments(src, flat);
// One value everywhere - the pivot. Which exact level that rounds to is not the point.
CHECK(std::adjacent_find(grey.pixels.begin(), grey.pixels.end(), std::not_equal_to<uint8_t>()) ==
grey.pixels.end());
TextureAdjustments hard;
hard.contrast = 1.f;
const DecodedHeightTexture split = apply_texture_adjustments(src, hard);
// A threshold about the pivot: the dark end of the ramp goes to black, the light end to white.
CHECK(split.pixels[0] == 0);
CHECK(split.pixels[size_t(split.width - 1)] == 255);
}
TEST_CASE("blur removes the finest detail and sharpness exaggerates an edge", "[TextureDisplacement]")
{
// Blur: a one-texel checkerboard is the highest frequency the grid holds, so a blur has to collapse it
// toward its own mean. Measured as mean absolute deviation, which needs no assumption about the mean.
const DecodedHeightTexture checker = make_gray_checkerboard(32, 32);
const auto deviation = [](const DecodedHeightTexture &t) {
double mean = 0.;
for (uint8_t v : t.pixels)
mean += double(v);
mean /= double(t.pixels.size());
double dev = 0.;
for (uint8_t v : t.pixels)
dev += std::abs(double(v) - mean);
return dev / double(t.pixels.size());
};
TextureAdjustments blur;
blur.blur = 1.f;
CHECK(deviation(apply_texture_adjustments(checker, blur)) < 0.25 * deviation(checker));
// Sharpness: an unsharp mask pushes each side of a step further from the other, so the step
// overshoots - darker than the dark side just inside it, brighter than the bright side just inside.
DecodedHeightTexture step;
step.width = 64;
step.height = 8;
step.pixels.assign(size_t(step.width) * size_t(step.height), 100);
for (int y = 0; y < step.height; ++y)
for (int x = step.width / 2; x < step.width; ++x)
step.pixels[size_t(y) * size_t(step.width) + size_t(x)] = 150;
TextureAdjustments sharp;
sharp.sharpness = 1.f;
const DecodedHeightTexture sharpened = apply_texture_adjustments(step, sharp);
const size_t row = size_t(step.height / 2) * size_t(step.width);
const size_t mid = size_t(step.width / 2);
CHECK(sharpened.pixels[row + mid - 1] < 100); // undershoot on the dark side of the step
CHECK(sharpened.pixels[row + mid] > 150); // overshoot on the light side
}
TEST_CASE("a grayscale image stays grayscale and its hue slider does nothing", "[TextureDisplacement]")
{
const DecodedHeightTexture src = make_gray_ramp();
REQUIRE_FALSE(src.has_color());
TextureAdjustments hue;
hue.hue_deg = 120.f;
const DecodedHeightTexture out = apply_texture_adjustments(src, hue);
// Not promoted to RGB: a grey image has no colour to offer the layer's colour feature, and storing it
// as RGB would triple the PNG for a row of identical greys.
CHECK_FALSE(out.has_color());
CHECK(out.rgb.empty());
CHECK(out.pixels == src.pixels);
}
TEST_CASE("a colour image's height stays the luminance of its adjusted colour", "[TextureDisplacement]")
{
// The invariant that keeps the relief and the colour from drifting apart: whatever the adjustment did
// to the channels, the height is recomputed from the channels that came out.
const DecodedHeightTexture src = make_rgb_flat(200, 60, 30);
REQUIRE(src.has_color());
TextureAdjustments adj;
adj.brightness = 0.2f;
adj.contrast = 0.3f;
adj.hue_deg = 75.f;
const DecodedHeightTexture out = apply_texture_adjustments(src, adj);
REQUIRE(out.has_color());
for (size_t i = 0; i < out.pixels.size(); ++i) {
const long expect = std::lround(0.299 * out.rgb[i * 3] + 0.587 * out.rgb[i * 3 + 1] +
0.114 * out.rgb[i * 3 + 2]);
REQUIRE(long(out.pixels[i]) == expect);
}
// The hue turn actually moved the colour, so the check above is not passing on an unchanged image.
CHECK(out.rgb != src.rgb);
}
TEST_CASE("a full turn of the hue leaves a colour where it started", "[TextureDisplacement]")
{
const DecodedHeightTexture src = make_rgb_flat(200, 60, 30);
TextureAdjustments adj;
adj.hue_deg = 360.f;
const DecodedHeightTexture out = apply_texture_adjustments(src, adj);
REQUIRE(out.has_color());
// Rounding through 8-bit channels, so a level or two of slack rather than exact equality.
for (size_t i = 0; i < out.rgb.size(); ++i)
REQUIRE(std::abs(int(out.rgb[i]) - int(src.rgb[i])) <= 2);
}
TEST_CASE("the adjustment blur radius ramps from zero and stays under its cost cap", "[TextureDisplacement]")
{
CHECK_THAT(adjustment_blur_radius(0.f, 512, 512), Catch::Matchers::WithinAbs(0.f, 1e-6f));
// 5% of the short side, as the Smoothing slider uses.
CHECK_THAT(adjustment_blur_radius(1.f, 512, 512), Catch::Matchers::WithinAbs(25.6f, 1e-3f));
CHECK_THAT(adjustment_blur_radius(0.5f, 512, 512), Catch::Matchers::WithinAbs(12.8f, 1e-3f));
// Capped, so a large image at the top of the slider cannot cost without bound.
CHECK_THAT(adjustment_blur_radius(1.f, 8192, 8192), Catch::Matchers::WithinAbs(48.f, 1e-3f));
// Sized off the short side, not the long one.
CHECK_THAT(adjustment_blur_radius(1.f, 4096, 200), Catch::Matchers::WithinAbs(10.f, 1e-3f));
}
TEST_CASE("downscaling a height texture averages the texels it drops and never upscales",
"[TextureDisplacement]")
{
// Averaging, not decimation: a one-texel checkerboard halved must come out uniformly mid-grey. Picking
// one texel per block would instead come out all black or all white - detail the adjustment never
// produced, shown in the preview.
const DecodedHeightTexture small = downscale_height_texture(make_gray_checkerboard(16, 16), 8);
CHECK(small.width == 8);
CHECK(small.height == 8);
CHECK(std::all_of(small.pixels.begin(), small.pixels.end(), [](uint8_t v) { return v == 127; }));
// Already within the limit: handed back as it is.
const DecodedHeightTexture ramp = make_gray_ramp(64, 4);
const DecodedHeightTexture same = downscale_height_texture(ramp, 256);
CHECK(same.width == ramp.width);
CHECK(same.height == ramp.height);
CHECK(same.pixels == ramp.pixels);
// Aspect preserved, and a colour source keeps its colour.
const DecodedHeightTexture wide = downscale_height_texture(make_rgb_flat(200, 60, 30, 400, 100), 100);
CHECK(wide.width == 100);
CHECK(wide.height == 25);
CHECK(wide.has_color());
}
TEST_CASE("a layer's live image adjustment reaches its decode", "[TextureDisplacement]")
{
// This is what makes the image-adjustment panel's sliders move the relief: decode_height_texture()
// applies the layer's preview_adjust, so everything downstream of the decode - the displacement, the
// colour, the thumbnails, the bake - sees the adjusted image without being told about the panel.
TextureDisplacementLayer layer;
layer.image_data = make_checkerboard_png(32, 32);
const DecodedHeightTexture raw = decode_height_texture(layer);
REQUIRE_FALSE(raw.empty());
// An untouched panel, and a closed one, cost nothing and change nothing.
layer.preview_adjust = TextureAdjustments{};
CHECK(decode_height_texture(layer).pixels == raw.pixels);
layer.preview_adjust.brightness = 0.5f;
const DecodedHeightTexture bright = decode_height_texture(layer);
CHECK(bright.pixels != raw.pixels);
CHECK(bright.pixels == apply_texture_adjustments(raw, layer.preview_adjust).pixels);
// Back to identity gives the stored image back, so closing the panel really does revert the layer.
layer.preview_adjust = TextureAdjustments{};
CHECK(decode_height_texture(layer).pixels == raw.pixels);
}
TEST_CASE("changing a live adjustment is not served the previous one from cache", "[TextureDisplacement]")
{
// The decode caches by the image_data pointer, which does not change while a slider moves - so the
// adjustment has to be part of the key or every slider move past the first would redraw the same
// pixels. Same for the smoothed copy, which is computed on top of the adjusted one.
TextureDisplacementLayer layer;
layer.image_data = make_checkerboard_png(32, 32);
const DecodedHeightTexture raw = decode_height_texture(layer);
REQUIRE_FALSE(raw.empty());
layer.preview_adjust.brightness = 0.5f;
const std::vector<uint8_t> bright = decode_height_texture(layer).pixels;
layer.preview_adjust.brightness = -0.5f;
const std::vector<uint8_t> dark = decode_height_texture(layer).pixels;
CHECK(bright != dark);
CHECK(dark == apply_texture_adjustments(raw, layer.preview_adjust).pixels);
// The same question again with smoothing on, which is cached separately and keyed by both.
layer.smoothing = 0.5f;
layer.preview_adjust.brightness = 0.5f;
const std::vector<uint8_t> smooth_bright = decode_height_texture(layer).pixels;
layer.preview_adjust.brightness = -0.5f;
const std::vector<uint8_t> smooth_dark = decode_height_texture(layer).pixels;
CHECK(smooth_bright != smooth_dark);
}
// ---------------------------------------------------------------------------------------------
// Texture smoothing
// ---------------------------------------------------------------------------------------------
@@ -1653,6 +1942,321 @@ TEST_CASE("Per-corner LSCM UVs give each triangle its own island's placement", "
CHECK(differs);
}
// ---------------------------------------------------------------------------------------------
// UV orientation: which way up a texture lands on the model.
//
// v = 0 is the height map's *first* pixel row, i.e. its top (DecodedHeightTexture::sample(), and
// the UV editor negates Y on screen for the same reason). So "the image is the right way up" is the
// statement that the row a point samples gets *lower* as the point moves up the face, and "it is
// not left-right mirrored" is that the column gets higher as the point moves to the right of a
// viewer standing outside the model. Both are measured below by sampling a ramp whose value says
// which row (or column) it came from, which settles the question without having to reason about the
// uv transform at all.
static constexpr int RAMP_N = 64; // the ramp texture's size, in texels
static constexpr float RAMP_TILING = 40.f; // mm per tile
static constexpr float CUBE_HALF = 5.f; // half extent of the cube the probes walk over
// How far a probe steps off a face centre. Short on purpose: the cylindrical and spherical u is an
// arc length (angle * radius), so a long step also changes the radius, and that term swamps the
// angular one. It is symmetric about the face centre, so at a short step it cancels between the two
// readings a check compares.
static constexpr float RAMP_STEP = 1.f;
// What one step's worth of travel is in ramp rows: 2 * RAMP_STEP mm of separation, RAMP_N texels per
// RAMP_TILING mm. Halved as the margin a check demands, so "flat" cannot pass as either direction.
static constexpr double RAMP_MARGIN = RAMP_N * RAMP_STEP / RAMP_TILING;
// A height map whose rows (or columns) carry a linear ramp: row r holds 3 + 4r, so the sampled
// height identifies the row. Built directly rather than through a PNG because these tests are about
// the projection, not the decoder - decode_height_texture() has its own tests.
static DecodedHeightTexture ramp_texture(bool by_row)
{
DecodedHeightTexture t;
t.width = t.height = RAMP_N;
t.pixels.resize(size_t(RAMP_N) * size_t(RAMP_N));
for (int y = 0; y < RAMP_N; ++y)
for (int x = 0; x < RAMP_N; ++x)
t.pixels[size_t(y) * size_t(RAMP_N) + size_t(x)] = uint8_t(3 + 4 * (by_row ? y : x));
return t;
}
// uv 0.5 at the cube's centre, and a tile wide enough that every point the probes visit stays well
// inside the one tile - so no reading is a wrapped-around neighbour of the one it is compared with.
static TextureDisplacementLayer ramp_layer(TextureProjectionMethod method)
{
TextureDisplacementLayer layer;
layer.projection_method = method;
layer.tiling_scale = RAMP_TILING;
layer.offset = Vec2f(0.5f, 0.5f);
layer.depth_mm = 1.f;
return layer;
}
// Which row (or column) of `ramp` the layer reads at `p`. Fractional, because a point between two
// texels reads the ramp between them; only the direction it moves in matters here.
static double ramp_index(const DecodedHeightTexture &ramp, const TextureDisplacementLayer &layer, const Vec3f &p,
const Vec3f &n, const Vec3f &center = Vec3f(Vec3f::Zero()),
const Vec3f &axis = Vec3f(Vec3f::UnitZ()))
{
return (double(sample_layer_height(ramp, layer, p, n, center, axis, nullptr)) * 255.0 - 3.0) / 4.0;
}
// How a viewer standing outside the model sees a face: their right, and their up. Up is world +Z on
// the four upright faces; on the top and bottom, where +Z is edge on, it is world +Y.
static void outside_viewer_frame(const Vec3f &n, Vec3f &right, Vec3f &up)
{
up = (std::abs(n.z()) < 0.9f) ? Vec3f(0.f, 0.f, 1.f) : Vec3f(0.f, 1.f, 0.f);
right = Vec3f((-n).cross(up).normalized());
}
static const std::array<std::pair<const char *, Vec3f>, 6> CUBE_FACES = { {
{ "+X", Vec3f(1.f, 0.f, 0.f) },
{ "-X", Vec3f(-1.f, 0.f, 0.f) },
{ "+Y", Vec3f(0.f, 1.f, 0.f) },
{ "-Y", Vec3f(0.f, -1.f, 0.f) },
{ "+Z", Vec3f(0.f, 0.f, 1.f) },
{ "-Z", Vec3f(0.f, 0.f, -1.f) },
} };
TEST_CASE("the box projection lands a texture upright and unmirrored on all six faces of a cube",
"[TextureDisplacement]")
{
const DecodedHeightTexture rows = ramp_texture(true);
const DecodedHeightTexture cols = ramp_texture(false);
const TextureDisplacementLayer layer = ramp_layer(TextureProjectionMethod::Triplanar);
for (const auto &[name, n] : CUBE_FACES) {
DYNAMIC_SECTION("face " << name)
{
Vec3f right, up;
outside_viewer_frame(n, right, up);
const Vec3f centre = n * CUBE_HALF;
// Upright: the row read near the top of the face is nearer the image's first row.
const double row_up = ramp_index(rows, layer, centre + up * RAMP_STEP, n);
const double row_down = ramp_index(rows, layer, centre - up * RAMP_STEP, n);
INFO("row at the top of the face " << row_up << ", at the bottom " << row_down);
CHECK(row_down - row_up > RAMP_MARGIN);
// Unmirrored: the column read to the viewer's right is further into the image. Without a
// per-side sign this fails on exactly the three faces facing away - -X, +Y and -Z - which
// is the mirroring a bare v flip leaves behind.
const double col_left = ramp_index(cols, layer, centre - right * RAMP_STEP, n);
const double col_right = ramp_index(cols, layer, centre + right * RAMP_STEP, n);
INFO("column at the left of the face " << col_left << ", at the right " << col_right);
CHECK(col_right - col_left > RAMP_MARGIN);
}
}
}
TEST_CASE("every projection method lands a texture upright on an upright face", "[TextureDisplacement]")
{
const DecodedHeightTexture rows = ramp_texture(true);
// ViewProjected is one flat projection from the captured camera rather than a per-face map, so its
// "up" is the projector's own (view_project_up), which the default capture puts at +Y.
const auto method = GENERATE(TextureProjectionMethod::Triplanar, TextureProjectionMethod::Cylindrical,
TextureProjectionMethod::Spherical, TextureProjectionMethod::ViewProjected);
const TextureDisplacementLayer layer = ramp_layer(method);
for (const auto &[name, n] : CUBE_FACES) {
// Only the four upright faces: on the top and bottom a cylinder's v is constant (they are its
// caps) and a sphere's is at an extremum (they are its poles), so neither says anything about
// which way up the image is.
if (std::abs(n.z()) > 0.9f)
continue;
DYNAMIC_SECTION("method " << int(method) << ", face " << name)
{
const Vec3f up = (method == TextureProjectionMethod::ViewProjected) ? layer.view_project_up :
Vec3f(0.f, 0.f, 1.f);
const Vec3f centre = n * CUBE_HALF;
const double row_up = ramp_index(rows, layer, centre + up * RAMP_STEP, n);
const double row_down = ramp_index(rows, layer, centre - up * RAMP_STEP, n);
INFO("row at the top " << row_up << ", at the bottom " << row_down);
CHECK(row_down - row_up > RAMP_MARGIN);
}
}
}
TEST_CASE("the cylindrical and spherical wraps run left to right as seen from outside", "[TextureDisplacement]")
{
const DecodedHeightTexture cols = ramp_texture(false);
const auto method = GENERATE(TextureProjectionMethod::Cylindrical, TextureProjectionMethod::Spherical);
const TextureDisplacementLayer layer = ramp_layer(method);
for (const auto &[name, n] : CUBE_FACES) {
// The caps and poles are out, as above - u is undefined on the axis. So is whichever face the
// atan2 branch cut runs through, where u jumps from +pi to -pi: that is a real seam in both
// projections, and a reading taken across it compares two opposite sides of the model.
if (std::abs(n.z()) > 0.9f)
continue;
const bool on_the_cut = (method == TextureProjectionMethod::Cylindrical) ? (n.y() < -0.9f) : (n.x() < -0.9f);
if (on_the_cut)
continue;
DYNAMIC_SECTION("method " << int(method) << ", face " << name)
{
Vec3f right, up;
outside_viewer_frame(n, right, up);
const Vec3f centre = n * CUBE_HALF;
const double col_left = ramp_index(cols, layer, centre - right * RAMP_STEP, n);
const double col_right = ramp_index(cols, layer, centre + right * RAMP_STEP, n);
INFO("column at the left " << col_left << ", at the right " << col_right);
CHECK(col_right - col_left > RAMP_MARGIN);
}
}
}
TEST_CASE("an unwrapped cube's flat charts are laid out the right way up", "[TextureDisplacement]")
{
indexed_triangle_set cube = its_make_cube(2. * CUBE_HALF, 2. * CUBE_HALF, 2. * CUBE_HALF);
for (Vec3f &v : cube.vertices)
v -= Vec3f(CUBE_HALF, CUBE_HALF, CUBE_HALF);
const PatchUnwrap unwrap = compute_patch_unwrap(cube, LSCM_DEFAULT_SEAM_ANGLE_DEG);
REQUIRE_FALSE(unwrap.empty());
REQUIRE(unwrap.chart_count == 6); // one flat chart per face, cut at the 90-degree edges
// Each chart carries one face. The four upright ones span world Z, and their v has to grow
// downwards like every other projection's - whatever the packing then did with the island.
int upright_charts = 0;
for (int c = 0; c < unwrap.chart_count; ++c) {
int top = -1, bottom = -1;
for (size_t i = 0; i < unwrap.uvs.size(); ++i) {
if (unwrap.vertex_chart[i] != c)
continue;
const float z = cube.vertices[size_t(unwrap.source_vertex[i])].z();
if (top < 0 || z > cube.vertices[size_t(unwrap.source_vertex[size_t(top)])].z())
top = int(i);
if (bottom < 0 || z < cube.vertices[size_t(unwrap.source_vertex[size_t(bottom)])].z())
bottom = int(i);
}
REQUIRE(top >= 0);
REQUIRE(bottom >= 0);
const float v_top = unwrap.uvs[size_t(top)].y(), v_bottom = unwrap.uvs[size_t(bottom)].y();
if (std::abs(v_top - v_bottom) < 1e-3f)
continue; // a cap: the whole chart is at one height, so it has no up
++upright_charts;
DYNAMIC_SECTION("chart " << c)
{
INFO("v at the chart's topmost vertex " << v_top << ", at its bottommost " << v_bottom);
CHECK(v_bottom - v_top > 1.f);
}
}
CHECK(upright_charts == 4); // the four sides; the top and bottom faces are the caps skipped above
}
TEST_CASE("project_planar agrees with the box projection's own axes", "[TextureDisplacement]")
{
// The two express the same table in different shapes - one a pair of world axes for the GUI, the
// other the closed form the bake's hot path uses - so they are checked against each other here
// rather than left to drift apart.
const Vec3f p(2.f, -3.f, 7.f);
for (const auto &[name, n] : CUBE_FACES) {
DYNAMIC_SECTION("face " << name)
{
Vec3f u_axis, v_axis;
box_projection_axes(n, u_axis, v_axis);
const Vec2f planar = project_planar(p, n);
CHECK_THAT(planar.x(), WithinAbs(p.dot(u_axis), 1e-5f));
CHECK_THAT(planar.y(), WithinAbs(p.dot(v_axis), 1e-5f));
// Right-handed for a viewer outside the model: u to their right, v down, so u x v points
// into the surface. Getting this wrong is exactly what mirrors a face.
CHECK_THAT(u_axis.cross(v_axis).dot(n), WithinAbs(-1.f, 1e-5f));
}
}
}
// An image with a different value in each quadrant, so one bake says both which way up it landed
// and whether it came out mirrored. Distinct enough that a wrong quadrant cannot be mistaken for the
// right one: top-left 255, top-right 170, bottom-left 85, bottom-right 0.
static std::shared_ptr<std::vector<unsigned char>> make_quadrant_marker_png(size_t w = 32, size_t h = 32)
{
std::vector<uint8_t> pixels(w * h);
for (size_t y = 0; y < h; ++y)
for (size_t x = 0; x < w; ++x)
pixels[y * w + x] = (y < h / 2) ? ((x < w / 2) ? 255 : 170) : ((x < w / 2) ? 85 : 0);
const boost::filesystem::path tmp_path = boost::filesystem::temp_directory_path()
/ boost::filesystem::unique_path("texdisp_test_%%%%%%%%.png");
REQUIRE(Slic3r::png::write_gray_to_file(tmp_path.string(), w, h, pixels));
std::vector<unsigned char> bytes;
{
std::ifstream ifs(tmp_path.string(), std::ios::binary);
bytes.assign(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
}
boost::system::error_code ec;
boost::filesystem::remove(tmp_path, ec);
REQUIRE_FALSE(bytes.empty());
return std::make_shared<std::vector<unsigned char>>(std::move(bytes));
}
TEST_CASE("baking an asymmetric image puts the top of the image at the top of the model", "[TextureDisplacement]")
{
// An upright wall in the plane y = 0, facing -Y, tessellated so that each of the image's four
// quadrants gets a vertex at its centre. A flat sheet rather than a cube because every vertex
// normal is then exactly the face normal, which is what makes the expected depth below an exact
// number instead of a tri-planar blend of three of them.
constexpr int STEPS = 4; // cells per side, so 5x5 vertices
constexpr float SPAN = 20.f; // mm, the wall's width and height
indexed_triangle_set wall;
for (int j = 0; j <= STEPS; ++j)
for (int i = 0; i <= STEPS; ++i)
wall.vertices.emplace_back(-SPAN / 2.f + SPAN * float(i) / float(STEPS), 0.f,
SPAN * float(j) / float(STEPS));
const auto at = [](int i, int j) { return j * (STEPS + 1) + i; };
for (int j = 0; j < STEPS; ++j)
for (int i = 0; i < STEPS; ++i) {
// Wound so that (+x) x (+z) = -y: the wall faces -Y, away from the origin.
wall.indices.emplace_back(at(i, j), at(i + 1, j), at(i + 1, j + 1));
wall.indices.emplace_back(at(i, j), at(i + 1, j + 1), at(i, j + 1));
}
TextureDisplacementFacetsData facets{};
facets[0] = paint_whole_mesh(wall);
TextureDisplacementLayer layer;
layer.slot = 0;
layer.projection_method = TextureProjectionMethod::Triplanar;
layer.image_data = make_quadrant_marker_png();
layer.depth_mm = 2.f;
// The wall is 20 mm across and one tile is 40 mm, so it covers the middle half of the image in
// both axes: the quadrant boundaries land on x = 0 and z = 10, and the probed vertices sit a
// whole number of texels away from both.
layer.tiling_scale = 40.f;
layer.offset = Vec2f(0.5f, 0.75f);
// A single decal rather than a repeat, so that getting the orientation wrong cannot be masked by
// the wrap bringing the flipped coordinate back into the image at a plausible-looking row. With
// tiling off, uv stays inside [0.25, 0.75] in both axes only while v runs the right way.
layer.tile_enabled = false;
const indexed_triangle_set result = build_texture_displacement(wall, { layer }, facets, classic_options());
REQUIRE(result.vertices.size() == wall.vertices.size());
// Seen from outside this face the viewer's right is +X and their up is +Z, so the image's
// top-left quadrant has to land at low x and high z. Each entry: the vertex, and the image value
// whose quadrant it must have read.
const std::array<std::tuple<const char *, int, int, int>, 4> expected = { {
{ "top-left (255)", 1, 3, 255 },
{ "top-right (170)", 3, 3, 170 },
{ "bottom-left (85)", 1, 1, 85 },
{ "bottom-right (0)", 3, 1, 0 },
} };
for (const auto &[name, i, j, value] : expected) {
DYNAMIC_SECTION("quadrant " << name)
{
const size_t vi = size_t(at(i, j));
// The whole displacement is along -Y, so this is the relief's height at that vertex.
const float raised = wall.vertices[vi].y() - result.vertices[vi].y();
INFO("vertex at " << wall.vertices[vi].x() << ", " << wall.vertices[vi].z());
CHECK_THAT(raised, WithinAbs(layer.depth_mm * float(value) / 255.f, 1e-3f));
// Nothing moved sideways or vertically: a mirrored or rotated basis would still have
// displaced along the normal, so this is here to catch the relief leaning instead.
CHECK_THAT(result.vertices[vi].x(), WithinAbs(wall.vertices[vi].x(), 1e-4f));
CHECK_THAT(result.vertices[vi].z(), WithinAbs(wall.vertices[vi].z(), 1e-4f));
}
}
}
TEST_CASE("The Cylindrical/Spherical patch frame is the bake's own, so a preview can share it", "[TextureDisplacement]")
{
// The fast preview reconstructs these two projections in the fragment shader and needs the very
@@ -2346,353 +2950,3 @@ TEST_CASE("whether a layer's texture has colour agrees with its decode", "[Textu
CHECK_FALSE(height_texture_has_color(TextureDisplacementLayer{}));
}
// ---------------------------------------------------------------------------------------------
// The model's own UV channel, and the Override blend mode
// ---------------------------------------------------------------------------------------------
// A grayscale image that is black in its left half and white in its right half, so where a sample
// lands along u is readable straight off the height it comes back with.
static std::shared_ptr<std::vector<unsigned char>> make_left_right_split_png(size_t w = 16, size_t h = 16)
{
std::vector<uint8_t> pixels(w * h);
for (size_t y = 0; y < h; ++y)
for (size_t x = 0; x < w; ++x)
pixels[y * w + x] = (x < w / 2) ? 0 : 255;
const boost::filesystem::path tmp_path = boost::filesystem::temp_directory_path()
/ boost::filesystem::unique_path("texdisp_test_%%%%%%%%.png");
REQUIRE(Slic3r::png::write_gray_to_file(tmp_path.string(), w, h, pixels));
std::vector<unsigned char> bytes;
{
std::ifstream ifs(tmp_path.string(), std::ios::binary);
bytes.assign(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
}
boost::system::error_code ec;
boost::filesystem::remove(tmp_path, ec);
REQUIRE_FALSE(bytes.empty());
return std::make_shared<std::vector<unsigned char>>(std::move(bytes));
}
// Where a sheet coordinate lands in uv: across [UV_LO, UV_LO + UV_SPAN] rather than the full [0, 1].
// The inset keeps the tests off the exact edge of an untiled placement, where there is deliberately no
// texture at all rather than its border texel (see DecodedHeightTexture::sample()) - a real model's
// channel does reach 1.0, and a vertex sitting exactly there displaces by nothing on purpose.
static constexpr float UV_LO = 0.1f;
static constexpr float UV_SPAN = 0.8f;
static float sheet_uv_at(float coord, float size, bool mirror = false)
{
const float t = coord / size;
return UV_LO + UV_SPAN * (mirror ? 1.f - t : t);
}
// One UV per triangle corner: u follows x, v follows y. `mirror_u` mirrors u, which is what the tests
// use to show the bake is really reading the channel rather than projecting the position.
static std::vector<Vec2f> sheet_uv_channel(const indexed_triangle_set &sheet, float size, bool mirror_u = false)
{
std::vector<Vec2f> uv(sheet.indices.size() * 3);
for (size_t f = 0; f < sheet.indices.size(); ++f)
for (int k = 0; k < 3; ++k) {
const Vec3f &p = sheet.vertices[size_t(sheet.indices[f][k])];
uv[f * 3 + size_t(k)] = Vec2f(sheet_uv_at(p.x(), size, mirror_u), sheet_uv_at(p.y(), size));
}
return uv;
}
TEST_CASE("Override blend replaces the displacement under it instead of combining with it",
"[TextureDisplacement]")
{
CHECK_THAT(blend_displacement(3.f, 1.f, TextureBlendMode::Override), WithinAbs(1.f, 1e-6f));
// Nothing underneath yet is still just the value, so an Override layer at the bottom of the
// stack behaves exactly like the Add the bake forces there.
CHECK_THAT(blend_displacement(0.f, 1.f, TextureBlendMode::Override), WithinAbs(1.f, 1e-6f));
// The sign carries, and a zero sample really does flatten what is under it - that is the point.
CHECK_THAT(blend_displacement(3.f, -1.f, TextureBlendMode::Override), WithinAbs(-1.f, 1e-6f));
CHECK_THAT(blend_displacement(3.f, 0.f, TextureBlendMode::Override), WithinAbs(0.f, 1e-6f));
}
TEST_CASE("an Override layer leaves only its own relief where two layers overlap", "[TextureDisplacement]")
{
const indexed_triangle_set cube = its_make_cube(10., 10., 10.);
TextureDisplacementLayer base;
base.slot = 0;
base.depth_mm = 2.0f;
base.tiling_scale = 5.0f;
base.image_data = make_flat_gray_png(255); // full depth everywhere
TextureDisplacementLayer second = base;
second.slot = 1;
second.depth_mm = 0.5f;
second.blend_mode = TextureBlendMode::Override;
TextureDisplacementFacetsData facets{};
facets[0] = paint_whole_mesh(cube);
facets[1] = facets[0];
const indexed_triangle_set overridden = build_texture_displacement(cube, {base, second}, facets, classic_options());
REQUIRE(overridden.vertices.size() == cube.vertices.size());
// Add would have piled the two up to 2.5 mm; Override keeps the upper layer's 0.5 mm alone.
TextureDisplacementLayer added = second;
added.blend_mode = TextureBlendMode::Add;
const indexed_triangle_set summed = build_texture_displacement(cube, {base, added}, facets, classic_options());
REQUIRE(summed.vertices.size() == cube.vertices.size());
for (size_t i = 0; i < cube.vertices.size(); ++i) {
if (!above_resting_plane(cube, i))
continue;
CHECK_THAT((overridden.vertices[i] - cube.vertices[i]).norm(), WithinAbs(0.5f, 1e-3f));
CHECK_THAT((summed.vertices[i] - cube.vertices[i]).norm(), WithinAbs(2.5f, 1e-3f));
}
}
TEST_CASE("the ModelUV mapping displaces through the model's own UV channel", "[TextureDisplacement]")
{
constexpr float size = 10.f;
const indexed_triangle_set sheet = make_flat_sheet(size, 1.f);
TextureDisplacementLayer layer;
layer.slot = 0;
layer.depth_mm = 1.0f;
layer.image_data = make_left_right_split_png();
layer.tile_enabled = false; // the layout is the placement; nothing should repeat
layer.projection_method = TextureProjectionMethod::ModelUV;
TextureDisplacementFacetsData facets{};
facets[0] = paint_whole_mesh(sheet);
const std::vector<Vec2f> uv = sheet_uv_channel(sheet, size);
const std::vector<Vec2f> flipped = sheet_uv_channel(sheet, size, /* mirror_u */ true);
const indexed_triangle_set out = build_texture_displacement(sheet, {layer}, facets, classic_options(), {}, nullptr,
Transform3d::Identity(), nullptr, nullptr, &uv);
REQUIRE(out.vertices.size() == sheet.vertices.size());
// The image is black for u < 0.5 and white above it, and the channel's u rises with x across the
// sheet, so it comes out flat on its left half and raised by the full depth on its right.
size_t low = 0, high = 0;
for (size_t i = 0; i < sheet.vertices.size(); ++i) {
const float x = sheet.vertices[i].x();
const float dz = out.vertices[i].z() - sheet.vertices[i].z();
if (x < 0.4f * size) {
CHECK_THAT(dz, WithinAbs(0.f, 1e-3f));
++low;
} else if (x > 0.6f * size) {
CHECK_THAT(dz, WithinAbs(layer.depth_mm, 1e-3f));
++high;
}
}
REQUIRE(low > 0);
REQUIRE(high > 0);
// Mirroring the channel mirrors the relief: the mapping really is the channel's, not a planar
// projection of the position (which would be unchanged by it).
const indexed_triangle_set mirrored = build_texture_displacement(sheet, {layer}, facets, classic_options(), {},
nullptr, Transform3d::Identity(), nullptr, nullptr,
&flipped);
REQUIRE(mirrored.vertices.size() == sheet.vertices.size());
for (size_t i = 0; i < sheet.vertices.size(); ++i) {
const float x = sheet.vertices[i].x();
if (x < 0.4f * size)
CHECK_THAT(mirrored.vertices[i].z() - sheet.vertices[i].z(), WithinAbs(layer.depth_mm, 1e-3f));
else if (x > 0.6f * size)
CHECK_THAT(mirrored.vertices[i].z() - sheet.vertices[i].z(), WithinAbs(0.f, 1e-3f));
}
}
TEST_CASE("a ModelUV layer falls back to Triplanar when the volume carries no UV channel",
"[TextureDisplacement]")
{
constexpr float size = 10.f;
const indexed_triangle_set sheet = make_flat_sheet(size, 2.f);
TextureDisplacementLayer layer;
layer.slot = 0;
layer.depth_mm = 1.0f;
layer.tiling_scale = 5.0f;
layer.image_data = make_flat_gray_png(255);
TextureDisplacementFacetsData facets{};
facets[0] = paint_whole_mesh(sheet);
layer.projection_method = TextureProjectionMethod::Triplanar;
const indexed_triangle_set as_triplanar = build_texture_displacement(sheet, {layer}, facets, classic_options());
layer.projection_method = TextureProjectionMethod::ModelUV;
const indexed_triangle_set no_channel = build_texture_displacement(sheet, {layer}, facets, classic_options());
REQUIRE(no_channel.vertices.size() == as_triplanar.vertices.size());
for (size_t i = 0; i < as_triplanar.vertices.size(); ++i)
CHECK_THAT((no_channel.vertices[i] - as_triplanar.vertices[i]).norm(), WithinAbs(0.f, 1e-5f));
}
TEST_CASE("a bake with colour off on every layer reports no colour at all", "[TextureDisplacement]")
{
const indexed_triangle_set cube = its_make_cube(10., 10., 10.);
TextureDisplacementLayer layer;
layer.slot = 0;
layer.depth_mm = 1.0f;
layer.tiling_scale = 5.0f;
layer.image_data = make_flat_rgb_png(200, 40, 10); // has colour to give...
layer.color_enabled = false; // ...but is not asked for it
TextureDisplacementFacetsData facets{};
facets[0] = paint_whole_mesh(cube);
std::vector<uint8_t> triangle_color;
TextureColorRequest request;
request.quantize = [](const Vec3f &) { return 0; }; // would colour everything, if asked
request.out_triangle = &triangle_color;
const indexed_triangle_set out = build_texture_displacement(cube, {layer}, facets, classic_options(), {}, &request);
REQUIRE_FALSE(out.vertices.empty());
// Every entry 0 ("this triangle takes no colour from the texture"), so the commit leaves whatever
// the model was already painted with exactly as it was.
for (const uint8_t entry : triangle_color)
CHECK(entry == 0);
}
TEST_CASE("transfer_uv_channel resamples a UV channel onto a subdivided copy of the same surface",
"[TextureDisplacement]")
{
constexpr float size = 10.f;
const indexed_triangle_set coarse = make_flat_sheet(size, 5.f);
const indexed_triangle_set fine = make_flat_sheet(size, 1.f);
const std::vector<Vec2f> uv = sheet_uv_channel(coarse, size);
const std::vector<Vec2f> moved = transfer_uv_channel(coarse, uv, fine);
REQUIRE(moved.size() == fine.indices.size() * 3);
// The channel is affine in position here (u = x/size, v = y/size), so a correct transfer
// reproduces it exactly at every corner of the finer mesh.
for (size_t f = 0; f < fine.indices.size(); ++f)
for (int k = 0; k < 3; ++k) {
const Vec3f &p = fine.vertices[size_t(fine.indices[f][k])];
CHECK_THAT(moved[f * 3 + size_t(k)].x(), WithinAbs(sheet_uv_at(p.x(), size), 1e-4f));
CHECK_THAT(moved[f * 3 + size_t(k)].y(), WithinAbs(sheet_uv_at(p.y(), size), 1e-4f));
}
// A mismatched channel is refused rather than read past its end.
CHECK(transfer_uv_channel(coarse, {Vec2f::Zero()}, fine).empty());
CHECK(transfer_uv_channel(coarse, uv, indexed_triangle_set{}).empty());
}
TEST_CASE("the model's per-corner UVs survive a brush split and collapse to one per vertex",
"[TextureDisplacement]")
{
constexpr float size = 10.f;
const indexed_triangle_set sheet = make_flat_sheet(size, 5.f);
const std::vector<Vec2f> uv = sheet_uv_channel(sheet, size);
// The whole sheet as a patch, with the source map the channel is read through.
const TriangleMesh tm(sheet);
TriangleSelector selector(tm);
for (int f = 0; f < int(sheet.indices.size()); ++f)
selector.set_facet(f, EnforcerBlockerType::ENFORCER);
std::vector<int> source;
const indexed_triangle_set patch = selector.get_facets_strict(EnforcerBlockerType::ENFORCER, &source);
REQUIRE(patch.indices.size() == source.size());
const std::vector<Vec2f> corner = compute_model_corner_uvs(sheet, uv, patch, source);
REQUIRE(corner.size() == patch.indices.size() * 3);
// An unsplit patch triangle *is* its source triangle, so its corners reproduce the channel.
for (size_t f = 0; f < patch.indices.size(); ++f)
for (int k = 0; k < 3; ++k) {
const Vec3f &p = patch.vertices[size_t(patch.indices[f][k])];
CHECK_THAT(corner[f * 3 + size_t(k)].x(), WithinAbs(sheet_uv_at(p.x(), size), 1e-4f));
CHECK_THAT(corner[f * 3 + size_t(k)].y(), WithinAbs(sheet_uv_at(p.y(), size), 1e-4f));
}
const std::vector<Vec2f> per_vertex = collapse_corner_uvs(patch, corner);
REQUIRE(per_vertex.size() == patch.vertices.size());
for (size_t i = 0; i < patch.vertices.size(); ++i) {
CHECK_THAT(per_vertex[i].x(), WithinAbs(sheet_uv_at(patch.vertices[i].x(), size), 1e-4f));
CHECK_THAT(per_vertex[i].y(), WithinAbs(sheet_uv_at(patch.vertices[i].y(), size), 1e-4f));
}
// Mismatched inputs report nothing rather than guessing.
CHECK(compute_model_corner_uvs(sheet, {Vec2f::Zero()}, patch, source).empty());
CHECK(compute_model_corner_uvs(sheet, uv, patch, {}).empty());
CHECK(collapse_corner_uvs(patch, {Vec2f::Zero()}).empty());
}
TEST_CASE("facet paint is carried onto a rebuilt mesh by each facet's foot point", "[TextureDisplacement]")
{
constexpr float size = 10.f;
const indexed_triangle_set coarse = make_flat_sheet(size, 2.5f);
// Two filaments, split down the middle - the pattern the transfer has to reproduce.
const TriangleMesh coarse_mesh(coarse);
TriangleSelector painter(coarse_mesh);
for (size_t t = 0; t < coarse.indices.size(); ++t) {
const stl_triangle_vertex_indices &tri = coarse.indices[t];
const float x = (coarse.vertices[size_t(tri[0])].x() + coarse.vertices[size_t(tri[1])].x() +
coarse.vertices[size_t(tri[2])].x()) / 3.f;
painter.set_facet(int(t), x < 0.5f * size ? EnforcerBlockerType::Extruder1 : EnforcerBlockerType::Extruder2);
}
const TriangleSelector::TriangleSplittingData paint = painter.serialize();
// A finer mesh, lifted clear of the original surface the way a bake's relief lifts it. This is
// what ModelVolume::restore_painting()'s 0.01 mm overlap remap cannot follow.
indexed_triangle_set lifted = make_flat_sheet(size, 1.f);
for (Vec3f &v : lifted.vertices)
v.z() += 0.5f;
const std::vector<uint8_t> state = transfer_facet_paint(coarse, paint, lifted);
REQUIRE(state.size() == lifted.indices.size());
size_t left = 0, right = 0;
for (size_t t = 0; t < lifted.indices.size(); ++t) {
const stl_triangle_vertex_indices &tri = lifted.indices[t];
const float x = (lifted.vertices[size_t(tri[0])].x() + lifted.vertices[size_t(tri[1])].x() +
lifted.vertices[size_t(tri[2])].x()) / 3.f;
// Only away from the split: a facet straddling it may legitimately land on either side.
if (x < 0.4f * size) {
CHECK(state[t] == uint8_t(EnforcerBlockerType::Extruder1));
++left;
} else if (x > 0.6f * size) {
CHECK(state[t] == uint8_t(EnforcerBlockerType::Extruder2));
++right;
}
}
REQUIRE(left > 0);
REQUIRE(right > 0);
// An unpainted source has nothing to carry, which is not the same as carrying NONE everywhere:
// the caller has to tell those apart to decide between resetting the annotation and writing one.
CHECK(transfer_facet_paint(coarse, TriangleSelector::TriangleSplittingData{}, lifted).empty());
CHECK(transfer_facet_paint(coarse, paint, indexed_triangle_set{}).empty());
}
TEST_CASE("an unpainted part of the source carries no paint onto the rebuilt mesh", "[TextureDisplacement]")
{
constexpr float size = 10.f;
const indexed_triangle_set coarse = make_flat_sheet(size, 2.5f);
// Only the left half is painted at all; the right half must come back NONE rather than borrowing
// the nearest painted colour from across the model.
const TriangleMesh coarse_mesh(coarse);
TriangleSelector painter(coarse_mesh);
for (size_t t = 0; t < coarse.indices.size(); ++t) {
const stl_triangle_vertex_indices &tri = coarse.indices[t];
const float x = (coarse.vertices[size_t(tri[0])].x() + coarse.vertices[size_t(tri[1])].x() +
coarse.vertices[size_t(tri[2])].x()) / 3.f;
if (x < 0.5f * size)
painter.set_facet(int(t), EnforcerBlockerType::Extruder3);
}
const std::vector<uint8_t> state = transfer_facet_paint(coarse, painter.serialize(), coarse);
REQUIRE(state.size() == coarse.indices.size());
for (size_t t = 0; t < coarse.indices.size(); ++t) {
const stl_triangle_vertex_indices &tri = coarse.indices[t];
const float x = (coarse.vertices[size_t(tri[0])].x() + coarse.vertices[size_t(tri[1])].x() +
coarse.vertices[size_t(tri[2])].x()) / 3.f;
if (x < 0.4f * size)
CHECK(state[t] == uint8_t(EnforcerBlockerType::Extruder3));
else if (x > 0.6f * size)
CHECK(state[t] == uint8_t(EnforcerBlockerType::NONE));
}
}
+1
View File
@@ -37,6 +37,7 @@ add_executable(${_TEST_NAME}_tests
test_plugin_json_depth.cpp
test_shortcuts.cpp
test_texture_color_palette.cpp
test_texture_island_view.cpp
test_file_url.cpp
test_user_manager.cpp
../fff_print/test_helpers.cpp
@@ -0,0 +1,99 @@
// How the texture displacement gizmo's view follows the UV editor's island highlight. The rules live in
// libslic3r_gui; this is the suite that links it. Same Windows include prologue as
// test_texture_color_palette.cpp (wx pulls in <windows.h>; keep WIN32_LEAN_AND_MEAN / NOMINMAX ahead of it).
#ifdef WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <Windows.h>
#endif
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include "slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp"
using Follow = Slic3r::GUI::GLGizmoTextureDisplacement::IslandViewFollow;
namespace {
// The View row's indices, and step()'s "apply nothing".
constexpr int NORMAL = 0, FAST = 1, CHECKER = 2, DISTORTION = 3, NONE = -1;
} // namespace
TEST_CASE("a Normal view gives way to Fast while islands are selected and comes back once none are", "[TextureIslandView][TextureDisplacement]")
{
Follow f;
CHECK(f.step(false, NORMAL, false) == NONE);
CHECK(f.step(true, NORMAL, false) == FAST);
CHECK(f.step(true, FAST, false) == NONE);
CHECK(f.step(false, FAST, false) == NORMAL);
CHECK(f.step(false, NORMAL, false) == NONE);
}
TEST_CASE("a Fast, Checker or Distortion view is left alone by the island highlight", "[TextureIslandView][TextureDisplacement]")
{
const int view = GENERATE(FAST, CHECKER, DISTORTION);
Follow f;
CHECK(f.step(true, view, false) == NONE);
CHECK(f.step(false, view, false) == NONE);
}
TEST_CASE("arriving in Normal with islands already selected switches to Fast", "[TextureIslandView][TextureDisplacement]")
{
// The pane's Height button over Checker lands in Normal with the islands still selected.
Follow f;
CHECK(f.step(true, CHECKER, false) == NONE);
CHECK(f.step(true, NORMAL, false) == FAST);
CHECK(f.step(false, FAST, false) == NORMAL);
}
TEST_CASE("Normal picked while islands are selected stays until they are deselected", "[TextureIslandView][TextureDisplacement]")
{
Follow f;
REQUIRE(f.step(true, NORMAL, false) == FAST);
f.picked(NORMAL);
CHECK(f.step(true, NORMAL, false) == NONE);
// A debug stage opening and closing over it changes nothing.
CHECK(f.step(true, NORMAL, true) == NONE);
CHECK(f.step(true, NORMAL, false) == NONE);
CHECK(f.step(false, NORMAL, false) == NONE);
CHECK(f.step(true, NORMAL, false) == FAST);
}
TEST_CASE("Fast picked while it was switched on stays after deselecting", "[TextureIslandView][TextureDisplacement]")
{
Follow f;
REQUIRE(f.step(true, NORMAL, false) == FAST);
f.picked(FAST);
CHECK(f.step(false, FAST, false) == NONE);
}
TEST_CASE("Normal picked with nothing selected does not hold off the next switch", "[TextureIslandView][TextureDisplacement]")
{
Follow f;
CHECK(f.step(false, NORMAL, false) == NONE);
f.picked(NORMAL);
CHECK(f.step(true, NORMAL, false) == FAST);
}
TEST_CASE("a debug stage holds Normal while it is open, and the switch follows once it closes", "[TextureIslandView][TextureDisplacement]")
{
Follow f;
REQUIRE(f.step(true, NORMAL, false) == FAST);
// The stage takes Normal itself, with the islands still selected.
CHECK(f.step(true, NORMAL, true) == NONE);
CHECK(f.step(true, NORMAL, false) == FAST);
}
TEST_CASE("islands deselected while a debug stage is open apply no view over it", "[TextureIslandView][TextureDisplacement]")
{
Follow f;
REQUIRE(f.step(true, NORMAL, false) == FAST);
CHECK(f.step(false, NORMAL, true) == NONE);
CHECK(f.step(false, NORMAL, false) == NONE);
}