diff --git a/.claude/skills/orca-wxwidgets/references/mouse-keyboard-focus.md b/.claude/skills/orca-wxwidgets/references/mouse-keyboard-focus.md index 48646134d8..679d69cb30 100644 --- a/.claude/skills/orca-wxwidgets/references/mouse-keyboard-focus.md +++ b/.claude/skills/orca-wxwidgets/references/mouse-keyboard-focus.md @@ -867,6 +867,8 @@ append_shortcut_item(export_menu, Shortcut::ExportSlicedFile, true, _L("Export p itself; never keep a raw pointer (`interface/wx/tipwin.h:20-110`). - `wxRichToolTip` is not a window: each `ShowFor()` creates a new one, and the native MSW version only applies to text controls (`interface/wx/richtooltip.h:70-192`). +- On Wayland, a GTK tooltip of a widget inside a shown popup maps as a grabbing `xdg_popup` and takes the + keyboard focus from the toplevel, which reports a deactivation → `references/popups-menus.md` §9. | Static [source] | MSW | GTK | macOS | |---|---|---|---| diff --git a/.claude/skills/orca-wxwidgets/references/platforms.md b/.claude/skills/orca-wxwidgets/references/platforms.md index 673f58357f..882a7dc59c 100644 --- a/.claude/skills/orca-wxwidgets/references/platforms.md +++ b/.claude/skills/orca-wxwidgets/references/platforms.md @@ -372,7 +372,9 @@ form a chain of parents. Window icons come from the `.desktop` file. The full li `references/mouse-keyboard-focus.md`; - GL blending must keep destination alpha at 1 (d8369e5f75); - GL post-init must retry until the surface is committed (d2c24fdabb) → - `references/webview-gl-aui-media.md`. + `references/webview-gl-aui-media.md`; +- a shown GTK tooltip is the topmost `xdg_popup`, so it must be hidden before a popup maps + (`PopupWindow::Show`) → `references/popups-menus.md` §9. ### XWayland (GTK3 X11 backend inside a Wayland session) @@ -409,7 +411,8 @@ start there when looking for prior art. The sites below are exemplars, cited by (`focus_left_popup(...)`) instead of hit-testing `wxGetMousePosition()`. - `PopupWindow::Create`: on GTK it binds the top-level `wxEVT_ACTIVATE` to `topWindowActiavate` → `DismissAndNotify()`, gated by the virtual `ShouldDismissOnTopWindowDeactivate()`, which `DropDown` - overrides for Wayland popup chains. On `__WXOSX__` with `wxPU_CONTAINS_CONTROLS`, + overrides for Wayland popup chains. `PopupWindow::Show` (GTK) hides visible GTK tooltips before mapping + on Wayland. On `__WXOSX__` with `wxPU_CONTAINS_CONTROLS`, `PopupWindow::OnMouseEvent2` hit-tests children, re-dispatches mouse events and synthesises enter/leave. - `SidePopup::Popup` (`Widgets/SideMenuPopup.cpp`): on `__APPLE__` the menu is anchored flush against @@ -633,7 +636,7 @@ headers. Rows marked [source] or "protocol" come from the implementation or from | `wxBitmap(const wxCursor&)` | creates an invalid bitmap | `interface/wx/bitmap.h:393-395` | — | | OpenGL | only EGL; `PreferGLX()` has no effect. Without EGL in the build, wxGTK's `wxGLCanvas` shows a fatal message and refuses to work [source: `src/gtk/glcanvas.cpp` `IsAvailable`]. The EGL surface is a subsurface over the canvas, ready only after map and a frame callback [source: `src/unix/glegl.cpp`] | `interface/wx/glcanvas.h:1094-1095` | `CLI::run` forces X11 when wx lacks EGL; overlays are drawn in GL/ImGui, never as wx children over the canvas → `references/webview-gl-aui-media.md` | | AUI | the doc note "live resize is always used … for wxOSX and wxGTK3 when using Wayland" is obsolete: "As of wxWidgets 3.3.0 this function always returns false", and `wxAUI_MGR_LIVE_RESIZE` is in the default flags. Floating panes need global positions | `interface/wx/aui/framemanager.h:336-345` | `Plater::priv::priv` clears `wxAUI_MGR_ALLOW_FLOATING`; `sanitize_window_layout_for_wayland` strips floating state from the saved layout → `references/webview-gl-aui-media.md` §wxAuiManager | -| Popups | a GTK popup is an `xdg_popup` only for COMBO/DROPDOWN/POPUP_MENU hints, so wx creates popups with `GDK_WINDOW_TYPE_HINT_COMBO` [source]. A chained popup's parent must be the mapped popup, and mapping it with a grab deactivates the toplevel (Orca's comments in `DropDown::mouseMove`, `DropDown::ShouldDismissOnTopWindowDeactivate`) | `src/gtk/popupwin.cpp:110-114` | `DropDown` transient-for chain, `ShouldDismissOnTopWindowDeactivate` → `references/popups-menus.md` | +| Popups | a GTK popup is an `xdg_popup` only for COMBO/DROPDOWN/POPUP_MENU hints, so wx creates popups with `GDK_WINDOW_TYPE_HINT_COMBO` [source]. A chained popup's parent must be the mapped popup, and mapping it with a grab deactivates the toplevel (Orca's comments in `DropDown::mouseMove`, `DropDown::ShouldDismissOnTopWindowDeactivate`). A GTK tooltip of a widget in a shown popup maps as that popup's grabbing child and deactivates the toplevel the same way | `src/gtk/popupwin.cpp:110-114` | `DropDown` transient-for chain, `ShouldDismissOnTopWindowDeactivate`, the tooltip check in `PopupWindow::topWindowActiavate` → `references/popups-menus.md` | | Fractional scale | arrives as an integer GDK scale | `docs/doxygen/overviews/high_dpi.md:348-351` | → `references/dpi-bitmaps-fonts.md` | | Window decorations | some desktop environments draw a title bar on undecorated windows anyway | — | [Undecorated windows](#wayland-undecorated-top-level-windows-splash) | | `wxWebViewChromium` | X11 only | `interface/wx/webview_chromium.h:133-146` | not built (`wxUSE_WEBVIEW_CHROMIUM` OFF) | diff --git a/.claude/skills/orca-wxwidgets/references/popups-menus.md b/.claude/skills/orca-wxwidgets/references/popups-menus.md index 1ad6a09271..d165ceff0a 100644 --- a/.claude/skills/orca-wxwidgets/references/popups-menus.md +++ b/.claude/skills/orca-wxwidgets/references/popups-menus.md @@ -73,6 +73,14 @@ Contents: [Rules](#rules) · [1. Choosing the window kind](#1-choosing-the-windo 27. Build `MenuFactory` menus once. Pass `parent` to `append_menu_item` only for items that persist. (§16) 28. macOS: bind `wxID_EXIT` on `OSXGetAppleMenu()` to `Close()`, only insert into the Apple menu, and always `Skip()` a frame's `wxEVT_ACTIVATE`. (§15) +29. On Wayland, a popup that can open while a GTK tooltip is shown hides every visible tooltip window before + it maps. `PopupWindow::Show` does it for every Orca popup; a popup outside `PopupWindow` opened from a + widget with a GTK tooltip must do it itself. Only a popup that cannot map while a GTK tooltip is visible, + such as one opened from the GL canvas (whose tooltips are ImGui), needs nothing. (§9) +30. On Wayland, a hook that dismisses a popup when its toplevel deactivates ignores the deactivation while a GTK + tooltip of a widget in that popup, or in a popup opened from it, is on screen: the tooltip has taken the + keyboard while the user is still on the popup. `PopupWindow::topWindowActiavate` does it for every Orca popup; + a popup outside `PopupWindow` with such a hook must do it itself. (§9) ## 1. Choosing the window kind @@ -390,6 +398,10 @@ compensates for (§6). on older GTK and GTK2. On hide: `gdk_seat_ungrab` + `gtk_grab_remove` (`popupcmn.cpp:335-403`). `gdk_seat_ungrab` releases the *seat's* grab, whichever popup took it, so hiding a sub-popup also drops the parent popup's pointer grab. +- The window is mapped before the grab is taken (`wxPopupWindow::Show` at `popupcmn.cpp:370`, the grab from + 375). Under Wayland the popup itself therefore maps as an `xdg_popup` without an explicit grab, while GDK + records the grab seat on its window, and a popup mapped later as its transient child (a sub-dropdown, a GTK + tooltip of a widget inside it) inherits that seat and maps with `xdg_popup.grab` (§9). - An outside press arrives at the grab widget. `gtk_popup_button_press` sends `wxEVT_KILL_FOCUS` to the popup and **consumes the click** (`return TRUE`, `src/gtk/popupwin.cpp:28-58`). Presses older than the popup's creation time are ignored (33-34). @@ -439,6 +451,9 @@ class PopupWindow : public wxPopupTransientWindow { public: PopupWindow(wxWindow* parent, int style = wxBORDER_NONE); bool Create(wxWindow* parent, int flags = wxBORDER_NONE); +#ifdef __WXGTK__ + bool Show(bool show = true) override; // hides GTK tooltips first on Wayland (§9) +#endif #ifdef __WXMSW__ void BindUnfocusEvent(); // opt-in #endif @@ -451,7 +466,7 @@ What it adds per platform: | Port | Behaviour | |---|---| -| GTK | `Create` binds `wxEVT_ACTIVATE` on `GetTopParent(parent)`. `topWindowActiavate` calls `event.Skip()`, then `DismissAndNotify()` if the toplevel deactivated, the popup is shown and `ShouldDismissOnTopWindowDeactivate()` returns true. This supplies the app/toplevel deactivation dismissal that stock wxGTK lacks. | +| GTK | `Create` binds `wxEVT_ACTIVATE` on `GetTopParent(parent)`. `topWindowActiavate` calls `event.Skip()`, then `DismissAndNotify()` if the toplevel deactivated, the popup is shown, `ShouldDismissOnTopWindowDeactivate()` returns true and, under Wayland, no GTK tooltip of the popup's own is on screen (§9). This supplies the app/toplevel deactivation dismissal that stock wxGTK lacks. Under Wayland, `Show(true)` on a hidden popup first hides every visible GTK tooltip window (§9). | | MSW | Nothing automatic. `BindUnfocusEvent()` binds the toplevel's `wxEVT_ACTIVATE`/`wxEVT_ICONIZE`/`wxEVT_SHOW` to `Dismiss()` (no `OnDismiss`). It is for default-style popups: they are desktop children that Windows does not hide with the frame, and stock wx closes them on deactivation or minimizing only if a focus message reaches a wx window (§4, §5). `topWindowActivate` does **not** `Skip()`, so while the popup lives it swallows the frame's `wxEVT_ACTIVATE`, and with it `wxTopLevelWindowMSW::OnActivate`'s focus save and restore (`src/msw/toplevel.cpp:1326-1360`). | | macOS | Only with `wxPU_CONTAINS_CONTROLS`: `OnMouseEvent2`, bound on the popup for `LEFT_DOWN/UP/DCLICK`, `MOTION` and `MOUSEWHEEL`, hit-tests the children (static `HitTest`) and re-dispatches the event to the deepest child under the cursor with `ProcessEventLocally`. On `MOTION` it synthesizes `ENTER`/`LEAVE` for the hovered target. This compensates for the capture rerouting in §5. | @@ -721,6 +736,85 @@ fights the grab and focus model (§10). Two more [source] facts: `DropDown::Popup`, applied when `!mainDropDown && m_widget`). - **Rule:** Don't open a grabbing popup on hover on Linux if the opener must stay clickable. Cite: `MainFrame` slice-button hover handlers (`#ifndef __linux__`). +- **Rule:** On Wayland, hide every visible GTK tooltip window right before mapping a popup that can open + while one is shown. + **Why:** A GTK3 tooltip is a `GTK_WINDOW_POPUP` with the `tooltip` type hint, placed with + `gdk_window_move_to_rect` (`gtktooltip.c:974-983`), so GDK Wayland maps it as an `xdg_popup` of the + hovered widget's toplevel (`should_map_as_popup`, `gdkwindow-wayland.c:3198-3199`). GDK refuses to map a + popup whose parent is not the last popup it mapped, warning "Tried to map a popup with a non-top most + parent" (`gdkwindow-wayland.c:3040-3046`), and the window stays invisible while wx believes it is shown. + GTK hides the tooltip on a button or key press, but only after the event has been propagated to the + widgets (`gtkmain.c:1949-1961`, `_gtk_tooltip_handle_event`). A dropdown opened from the click is therefore + mapped while the opener's tooltip is still up, and the click that opens it after the tooltip delay does + nothing. The same holds for a sub-dropdown opened on hover while the main dropdown shows an item tooltip. + GTK hides the current tooltip the same way before mapping its own menus (`gtk_menu_popup_internal`, + `gtkmenu.c:1837`), but through the private `_gtk_tooltip_hide_in_display` (`gtktooltip.c:1297`); apps have + no public call, so hide the window: `gtk_widget_hide` unmaps the `xdg_popup` at once, and GtkTooltip treats + the tooltip as no longer visible (`GTK_TOOLTIP_VISIBLE`, `gtktooltip.c:135`). Its own hide on the press + then returns early, before it times out browse mode (`gtk_tooltip_hide_tooltip`, `gtktooltip.c:1078`, + 1092), so the next tooltip shows after the 60 ms browse delay instead of 500 ms. A tooltip GTK tries to + show while a popup is open fails to map with the same warning and stays hidden, unless its widget is in + the topmost popup (a dropdown's own item tooltip maps as that popup's child); that happens with or without + this step and is harmless. X11 has no popup stacking rule, so the step is gated on + `is_running_on_wayland()`. (Line numbers are GTK 3.24.52.) + ```cpp + // Wrong: map the popup with the opener's tooltip still on top + drop.Popup(&drop); + // Right (wxGTK, Wayland): PopupWindow::Show does this before every map + GList* toplevels = gtk_window_list_toplevels(); + for (GList* l = toplevels; l; l = l->next) + if (gtk_window_get_type_hint(GTK_WINDOW(l->data)) == GDK_WINDOW_TYPE_HINT_TOOLTIP && gtk_widget_get_visible(GTK_WIDGET(l->data))) + gtk_widget_hide(GTK_WIDGET(l->data)); + g_list_free(toplevels); + ``` + Cite: `PopupWindow::Show` (#16595). + +- **Rule:** On Wayland, don't dismiss a shown popup on a toplevel deactivation while a GTK tooltip of one of its + widgets is on screen. + **Why:** GTK makes a tooltip transient for the toplevel of the widget it describes (`gtktooltip.c:974`), which + for a widget inside a popup, or the popup itself (`DropDown` sets its item tooltips on itself), is the popup's + own `GtkWindow`. The popup's window holds the seat grab (§5), and `find_grab_input_seat` walks the transient + parents to it (`gdkwindow-wayland.c:3142-3147`), so GDK maps the tooltip with an explicit `xdg_popup.grab` + (3100); the walk passes through every popup in a chain, so a tooltip in a popup opened from inside another + popup grabs too. The compositor gives the keyboard to the topmost grabbing popup: KWin sends `wl_keyboard.leave` + for the main window and `enter` for the tooltip (observed with `WAYLAND_DEBUG=client`). wxGTK turns the + toplevel's focus-out into `wxEVT_ACTIVATE(false)` (`src/gtk/toplevel.cpp:192-205`), so a deactivation hook closes + the popup as the tooltip appears, and GDK warns "Tried to unmap the parent of a popup" + (`gdkwindow-wayland.c:3429`) because the tooltip is still mapped as its child. The focus returns to the toplevel + when the tooltip hides. Ask GDK whether the tooltip is mapped (`gdk_window_is_visible`): when the compositor + dismisses a tooltip, `xdg_popup_done` hides only its `GdkWindow` (`gdkwindow-wayland.c:2289`, + `gdkwindow.c:5684-5690`), and `gtk_widget_get_visible` stays TRUE until GTK hides the tooltip itself. Alt+Tab with + a tooltip showing still closes the popup (observed): the Alt press reaches the app, which hides the tooltip after + handling the key (`gtkmain.c:1949-1961`). X11 tooltips never take the focus, so the check is gated on + `is_running_on_wayland()`. (Line numbers are GTK 3.24.52.) + **Limit:** wxGTK sends `wxEVT_ACTIVATE(false)` only while it holds an active frame and then clears it + (`g_activeFrame`, `src/gtk/toplevel.cpp:196-202`), so a deactivation ignored this way is never repeated. If the + app loses the focus while the tooltip holds it, without Orca seeing a key or the pointer leave first (another + app's window taking the focus, a gesture), the popup stays open until the user returns, and the first click + closes it (observed with a dialog from another app). Closing that gap means waiting for the compositor to + reactivate the toplevel, which takes a timer or a blocking round trip. + ```cpp + // Wrong: every toplevel deactivation dismisses, including the one the popup's own tooltip causes + if (!event.GetActive() && IsShown() && ShouldDismissOnTopWindowDeactivate()) + DismissAndNotify(); + // Right (wxGTK): Wayland only, skip it while a tooltip of this popup or of a popup opened from it is mapped + static bool own_tooltip_mapped(GtkWindow *popup) + { + bool mapped = false; + for_each_tooltip_window([popup, &mapped](GtkWindow *win) { // GDK_WINDOW_TYPE_HINT_TOOLTIP toplevels + GdkWindow *gdk_win = gtk_widget_get_window(GTK_WIDGET(win)); + if (!gdk_win || !gdk_window_is_visible(gdk_win)) + return; + for (GtkWindow *w = gtk_window_get_transient_for(win); w && !mapped; w = gtk_window_get_transient_for(w)) + mapped = w == popup; + }); + return mapped; + } + if (!event.GetActive() && IsShown() && ShouldDismissOnTopWindowDeactivate() && + !(Slic3r::GUI::is_running_on_wayland() && own_tooltip_mapped(GTK_WINDOW(m_widget)))) + DismissAndNotify(); + ``` + Cite: `PopupWindow::topWindowActiavate` (#16800). ## 10. Frameless dialog instead of a popup diff --git a/.github/workflows/pr-label-bot.yml b/.github/workflows/pr-label-bot.yml index f323d0e400..2fa6c2598d 100644 --- a/.github/workflows/pr-label-bot.yml +++ b/.github/workflows/pr-label-bot.yml @@ -50,6 +50,12 @@ jobs: 'documentation' ]; const pr = context.payload.pull_request; + // First-time contributors also get a link to the contributing guide + const greeting = ['FIRST_TIME_CONTRIBUTOR', 'FIRST_TIMER'].includes(pr.author_association) + ? `Hi @${pr.user.login}, thanks for contributing to OrcaSlicer! ` + + `[How to Contribute](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute) explains what reviewers need from a PR.\n\n` + + `You can` + : `Hi @${pr.user.login}, you can`; const labelsList = `${allowedLabels .slice(0, -1) .map((label) => `\`${label}\``) @@ -72,7 +78,7 @@ jobs: repo: context.repo.repo, issue_number: pr.number, body: - `Hi @${pr.user.login}, you can manage the labels for this PR by \`/bot add-label\` and \`/bot remove-label\`\n\n` + + `${greeting} manage the labels for this PR by \`/bot add-label\` and \`/bot remove-label\`.\n\n` + `Allowed labels are:\n${labelsList}\n\n` + `Examples:\n${examplesText}` }); diff --git a/AGENTS.md b/AGENTS.md index b682caa1ba..99c888ee89 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,6 +58,10 @@ ctest --test-dir ./tests/fff_print -C Release - Profile/format changes need version migration handling - Dependencies built separately in `deps/build/`, then linked to main app +## Pull requests + +Before opening a pull request or posting on GitHub, read [CONTRIBUTING.md](CONTRIBUTING.md), including its "If you are an AI agent" section. + ## Code review focus areas - Changes must not cause regressions in existing functionality, defaults, profiles, or project compatibility. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000..7639ce8f3e --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,105 @@ +# Contributing to OrcaSlicer + +Thanks for wanting to help! OrcaSlicer is built by volunteers. + +Review is the slowest part of getting a PR merged. A small group of reviewers works through hundreds of open PRs in their spare time. If a PR has what they need, it is reviewed sooner and is more likely to be merged. [How to Contribute](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute) on the wiki has the details for each kind of PR. + +For questions about using OrcaSlicer, please ask on [Discord](https://discord.gg/P4VE9UY9gJ) or in [Discussions](https://github.com/OrcaSlicer/OrcaSlicer/discussions), not in an issue or PR. + +Opening an issue? See [Opening an Issue](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#opening-an-issue). + +## The short version + +- Search open PRs and issues before you start. Someone may already be working on it. +- Keep each PR to one topic. Put changes that belong together in one PR, and unrelated changes in separate PRs. Focused PRs are reviewed and merged much faster. +- Don't open many PRs at once. If you already have several open, wait until some are merged. +- Explain why the change is needed, and show how you tested it. Add an automated test when the code can be tested. +- AI tools are welcome. You are still responsible for the change, so test it and make sure you understand it. +- Keep your PR up to date and reply to review comments. + +## Write a description reviewers can use + +Use the [PR template](.github/pull_request_template.md), and keep its "How to Download Pull Requests Artifacts" link as the last line. Testers use that link. In the template, answer these questions: + +- **What does this change, and why is it needed?** If it fixes an issue, write `Fixes #1234` in the description, so GitHub closes the issue when the PR is merged. If it fixes only part of an issue, mention `#1234` without `Fixes`, so the issue stays open. +- **Are there related PRs or issues?** If another PR touches the same code or bug, explain how yours is different. +- **How did you test it?** Give the OS, the printer profile and the steps. Attach a project file if the result depends on a model or settings. Name any automated tests you added. The best test fails without your change and passes with it. See [tests/AGENTS.md](tests/AGENTS.md) for where a test goes. +- **What could you not test?** For example another OS, or a printer you don't own. + +Use short, plain sentences, because many reviewers read English as a second language. Your own English is fine, and so is a translation tool. + +## What each kind of PR needs + +| Kind of PR | Label | Reviewers need to see | +|---|---|---| +| [Bug fix](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#bug-fixes) | `bug-fix`, `crash` | The cause, before and after, a test if possible | +| [Security fix](SECURITY.md) | `SECURITY` | A private report to the maintainers first | +| [New feature or setting](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#new-features-and-settings) | `enhancement`, `QoL` | Why users need it, that it is off by default, real results | +| [Performance](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#performance) | `optimization` | Measurements, and proof the output did not change | +| [Refactor](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#refactors) | `optimization` | That behavior and output did not change | +| [GUI change](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#gui-changes) | `UI/UX` | Screenshots before and after, on each platform you tested | +| [Printer profile](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#printer-profiles) | `profile` | The validator passing, the version bump, real print results | +| [Translation](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#translations) | `Localization` | Glossary terms used, placeholders unchanged | +| [Build, CI or dependencies](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#build-ci-and-dependencies) | `build`, `dependencies` | Which platforms you built on | +| [Tests](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#tests) | `test` | That the test fails when the behavior breaks | +| [Documentation](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#documentation) | `documentation` | That it matches the current code | + +## Rules that are easy to miss + +- **Don't reformat existing code or make unrelated edits.** `.clang-format` is for new files. In existing files, match the code around your change. +- **Include what you use.** Because of the precompiled header, a local build can succeed with a missing include. Run `scripts/run_clang_tidy.sh` (or `.ps1`) before you push. +- **New behavior is off by default.** When the new option is off, existing output must not change. +- **Keep old projects and profiles working.** Never change what an existing setting means. Add a new key, and convert old values in `handle_legacy`. +- **Write each UI message as one translatable string** with placeholders, never as joined fragments. See "Writing translatable strings in the source" in [AGENTS.md](AGENTS.md). +- **Only edit `msgstr` in translations.** Keep every placeholder and `\n` exactly as in the `msgid`. +- **Bump the vendor version when you change profiles.** Change `version` in `resources/profiles/.json` for every vendor you change, and run `scripts/check_profile.sh` (or `.bat`). + +The code style and the full list of what reviewers check are in [AGENTS.md](AGENTS.md). + +## Using AI tools + +AI tools are welcome here, and many contributors and maintainers use them. Reviewers can only spend time on PRs that a person has already tested. + +- **You are responsible for the change.** Before you ask for review, build the change, run it, and confirm that it works. Be ready to explain each change and why it is needed. +- **Keep it short and true.** AI tools tend to write long descriptions, and sometimes describe tests that never ran. Remove generated code that isn't needed, too. A short description of what you actually did helps more. +- **Read what you post.** Please don't paste a review comment into an AI tool and post its answer without checking it. +- **Don't let an agent open PRs or post comments on its own.** Read everything before it is posted. +- **Use the repository's skills.** `.claude/skills/` (also reachable as `.agents/skills/`) has instructions for AI tools on parts of OrcaSlicer. The top of each skill's `SKILL.md` describes when to use it. Some tools load them automatically. With others, point the tool to the skill that matches your change. + +### If you are an AI agent + +If you are an AI agent working for a contributor, please follow these steps: + +1. Show the contributor this guide before you open a PR or post a comment. +2. Search open PRs for the same change before you start. +3. If the contributor already has several open PRs, wait until some are merged before you open another. +4. Before you change code, check `.claude/skills/` for a skill that matches the change, and follow it. +5. If the code can be tested, add an automated test, and check that it fails without the change and passes with it. +6. Ask the contributor to test the change by hand. For a bug fix, they should build the code without the change and reproduce the bug. Then they should build the branch and check that the bug is gone. +7. Write the PR description in the [PR template](.github/pull_request_template.md). A body passed with `gh pr create --body` replaces the template, so start from the template's text. +8. If you couldn't build or run something, say so in the PR. + +## After you open the PR + +- **Add labels.** A bot will comment with instructions. Reply with the labels from the table above, for example `/bot add-label bug-fix, UI/UX`. +- **Leave "Allow edits by maintainers" turned on**, so a reviewer can push small fixes directly. +- **Mark the PR ready for review when it's finished.** Draft PRs are not merged. +- **Push new commits to the same PR.** Please don't open a new PR for the same change. +- **Don't force-push once a reviewer has commented.** Add new commits instead, so reviewers can see what changed since they last looked. To fix merge conflicts, merge `main` into your branch. PRs are usually squash-merged, so extra commits are fine. +- **Reply to every review comment**, including automated ones. You don't have to agree, but please say why. + +Reviewers are volunteers, and a first response can take a while. If you already have several PRs open, please wait until some are merged before you open more. Review comments on one PR often apply to the others too. While you wait, there are [other ways to help](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#other-ways-to-help). + +## If your PR is closed + +There are more PRs than reviewers can handle, so we may close a PR that doesn't meet this guide. For example, it may have no explanation of how it was tested, duplicate another PR, or look generated and untested. When we close a PR, we'll say why in a comment. + +You're welcome to open a new PR once the change meets this guide. Please link the old PR in the description, so reviewers can see the earlier discussion. Thank you for the time you put into it. + +## Security issues + +Please don't report security problems in a public issue. See [SECURITY.md](SECURITY.md). + +## Thank you + +Thanks again for helping. We're glad you're here. diff --git a/build_release_macos.sh b/build_release_macos.sh index 9eca2e7f40..c5fd2b9a7c 100755 --- a/build_release_macos.sh +++ b/build_release_macos.sh @@ -54,7 +54,7 @@ while getopts ":dpa:snt:xbc:i:j:Tuh" opt; do echo " -u: Build universal app only (requires existing arm64 and x86_64 app bundles)" echo " -n: Nightly build" echo " -t: Specify minimum version of the target platform, default is 12.0" - echo " -x: Use Ninja Multi-Config CMake generator, default is Xcode" + echo " -x: Use Ninja Multi-Config CMake generator, default is Xcode (requires ninja; install with 'brew install ninja')" echo " -b: Build without reconfiguring CMake" echo " -c: Set CMake build configuration, default is Release" echo " -i: Add a prefix to ignore during CMake dependency discovery (repeatable), defaults to /opt/local:/usr/local:/opt/homebrew" @@ -122,6 +122,12 @@ if [ -z "$CMAKE_IGNORE_PREFIX_PATH" ]; then export CMAKE_IGNORE_PREFIX_PATH="/opt/local:/usr/local:/opt/homebrew" fi +if [[ "$SLICER_CMAKE_GENERATOR" == Ninja* || "$DEPS_CMAKE_GENERATOR" == Ninja* ]] && ! command -v ninja >/dev/null 2>&1; then + echo "Error: Ninja is required when using the -x generator option." + echo "Install it with Homebrew: brew install ninja" + exit 1 +fi + CMAKE_VERSION=$(cmake --version | head -1 | sed 's/[^0-9]*\([0-9]*\).*/\1/') if [ "$CMAKE_VERSION" -ge 4 ] 2>/dev/null; then export CMAKE_POLICY_VERSION_MINIMUM=3.10 diff --git a/docs/HLSD/seam-alignment.md b/docs/HLSD/seam-alignment.md new file mode 100644 index 0000000000..8dfbda1a2f --- /dev/null +++ b/docs/HLSD/seam-alignment.md @@ -0,0 +1,280 @@ +# Seam alignment on the loop — High Level Design + +## Purpose and scope + +SeamPlacer selects candidates, connects neighboring layers into strings, fits each string and +places the resulting seam on its own contour. Painted ranges are reconstructed separately for +green enforcers and red blockers. These stages do not alter candidate ranking. +String construction and fitting apply to Aligned, Aligned Back and Back (`spRear`). +Nearest and Random bypass this stage, but share the paint reconstruction rules. + +## Concepts + +- **Candidate (C).** The seam candidate chosen for a perimeter in a string. Candidates are the + polygon vertices plus points inserted near paint (see Painted ranges), so the chosen candidate + can move in discrete steps from layer to layer. +- **Fitted point (F).** The value of the string's fitted curve at the layer height. It need not + lie on the loop: where the loop size changes quickly between layers, as near the bottom of a + sphere, it lies up to a few millimeters off it. +- **Measured angle.** `local_ccw_angle` of a candidate. It is measured at polygon vertices on arms + at least one nozzle diameter long; inserted points have angle 0. +- **Blend.** `target = t·C + (1 − t)·F`. The angle weight `t = min(1, (|angle C| / 55°)^3)` pulls + the seam onto sharp corners; at 55° and above the seam is the candidate itself. +- **Enforced run.** The maximal sequence of consecutive Enforced candidates of the perimeter that + contains C, or the whole loop when every candidate is Enforced. With exact painted ranges it + follows its geometric bounds and surface proximity; otherwise it approximates the painted area with the candidate spacing. + +## Painted ranges + +The paint is a set of small triangles on the model surface. Its **contour** is the set of their +edges that belong to one painted triangle only, taken from the painted triangles with their T-joints +split (`get_facets_strict`), so that edges inside the painted area pair up. Each contour edge keeps +the direction from it into the paint. The contour is built once per object and stored in an AABB +tree. + +Green and red paint use separate instances of the same contour and interval reconstruction. +An interval bounds paint membership but does not establish it: every classified candidate must +also lie within one line width of a triangle of the corresponding paint. A contour can leave the +painted surface between projected endpoints, especially at concavities and nearby surface folds. +The same proximity check used by the fallback prevents such a detour from acquiring synthetic +paint; exact interval bounds still exclude the fringe beyond the projected ends. +Red ranges classify candidates as Blocked, including the boundary itself (1 µm membership +tolerance), overriding green paint at an overlap. Inserted samples include both red ends, a +range midpoint, a gap midpoint and permitted guard samples up to 2 µm outside the red ends. +The guard distance is reduced to one quarter of a shorter gap; gaps at or below the membership +tolerance can remain closed. Candidate marks closer than 1 µm merge. +These adjacent permitted samples limit fitted and optimized movement to the geometric red +edge, with the small outward guard, rather than to a distant original gray vertex. Red ranges add +no penalty and do not change candidate ranking. Precise Seam modifiers apply after paint +classification and take priority over it. + +Random placement samples an outgoing edge of its selected candidate. On loops with exact +green ranges, an Enforced candidate followed by a non-Enforced candidate contributes no outgoing +edge length: the endpoint belongs to the paint, but the following segment leaves the permitted run. +This also respects weak modifiers that retype part of a painted run as Blocked or Neutral. +On loops with exact red ranges, a permitted candidate followed by a Blocked candidate contributes no outgoing +edge length, so Random cannot sample toward the closed red boundary. A zero-length selected +edge keeps the candidate position. +The cumulative-length selection stops at the last viable edge and clamps its +remaining distance to that edge, preventing float rounding from overrunning the +candidate list or the permitted segment. + +Exact green and red ends bound the seam center position without expanding the painted range +along the contour by the line width. A seam can therefore reach a red edge with no line-width +clearance. Paint can be extended to request a larger clearance; the boundary does not +guarantee that the finite-width extrusion or a seam blemish stays entirely outside red paint. + +If boundary crossings cannot be paired, the corresponding color falls back to the line-width +proximity classification, including its possible fringe beyond the paint edge. The fallback is +independent for each color and loop. For red this includes paint not crossing the layer, +ambiguous contours and a completely red surface without boundary crossings. In the all-blocked case +best-effort placement still produces a seam; red paint does not suppress extrusion. +An exact red reconstruction does not suppress proximity-based green oversampling when green +boundaries remain uncertain. + +On a layer, the contour edges crossing the slicing plane give the exact ends of the painted band. +Each crossing within the line width of the loop is moved to its closest loop point; the direction +into the paint, against the loop direction there, tells whether paint lies ahead or behind. At a +vertex the loop direction is the mean of the two edges, skipping edges shorter than 1 µm such as +the repeated closing point and the shared ends of extrusion paths, so the result does not depend on +where the loop starts. Along the loop, ends where paint begins and ends must alternate; each +pair bounds a **painted range**. Such a loop has **exact ends**: + +- a vertex is Enforced if it lies in a range (within 1 µm); +- points are inserted at the range ends, at the range middle and every 0.2 mm from the range begin, + and one in the middle of each gap between ranges, so that ranges with no vertex between them stay + separate patches; +- the central candidate of the longest patch is the middle of its range, unless the patch has a + sharp corner, which keeps priority. + +Before generating candidates, a fully painted closed surface is treated like an unpainted surface: +it imposes no choice of seam position. A loop on a partly painted object can also be normalized when +there are no exact range ends, no active Precise Seam modifier, no non-green facet bounding box in +the loop's XY box expanded by line width and its Z slab of the same reach, and every entire loop edge +is proven within paint reach. Neutral and blocked facets both prevent this local proof. Segment +coverage uses the triangle inequality at its midpoint and at most eight bisections; failure retains +the ordinary conservative paint treatment. This is a sufficient test, not a claim to recognize every +fully covered contour near unrelated surfaces. + +A normalized loop keeps the original candidates, without paint oversampling, Enforced status, +central enforcer, extra fitting or positional weights, painted-corner blending or paint fixation. Sharp-angle and Precise Seam rules remain authoritative. Whole-surface painting and no +painting therefore feed identical candidates into alignment. + +Otherwise, which includes paint not crossing the layer (a dot between layers, the top and bottom of +a band), ends that do not alternate and a contour running along the +loop, a point is Enforced if paint lies within the line width of it, and edges near paint get points +every 0.2 mm from their start vertex. Such a run reaches past the paint by up to the line width, +depending on the vertices, and its central candidate is the middle one by count; on a smooth band +both shift the seam off the middle of the paint. + +## Seam strings + +A string starts at a seam and is extended upward layer by layer while the next layer has a seam +within reach. After the upward search ends, the downward search begins at the layer immediately +below the start. This keeps a matching neighboring seam in the same aligned string. + +## Geometric contour continuation + +Seam strings resolve the next layer's boundary before comparing seam preferences. +Each perimeter retains whether it bounds material or a hole, its layer-local index, +and immutable candidate geometry. Occupancy does not participate in correspondence: the radius search skips occupied +members of the permitted set without expanding it to unrelated walls. + +Each layer builds an AABB tree of contour bounds once. Nearby-contour queries, +fast bounds matching, material containment and boundary proximity use this index +before applying their exact predicates. Query results are sorted by the +original contour index, preserving deterministic tie-breaking. Index construction +checks cancellation between layers. The index avoids scanning unrelated contours +for each seed; overlapping global bounds can still require many exact checks. + +Only closed extrusion loops provide a reliable boundary role. Open paths and +collection fallbacks retain unknown geometry rather than deriving a physical role +from an artificial closing edge. An unknown source, or an unknown path whose +bounding box intersects the local query box in either layer, leaves the radius +search unrestricted. This conservative box test also covers the material probes; +it may disable the filter even when the path's segments are farther away. +Reverse confirmation applies only to candidates that pass the applicable distance +and normal checks, plus material checks on the local path outside the noise band. +Unknown geometry encountered around such a candidate's foot during reverse confirmation +also leaves the entire radius search unrestricted, rather than discarding only +that candidate. A reliable reverse rejection still excludes the candidate. +Unknown paths outside these query boxes do not disable reliable correspondence. + +Bounding-box extents within one nozzle diameter plus a quarter-diameter reserve +identify a potential fast match of the same boundary type. Acceptance also requires +a closest segment within one eighth of the source line width, consistent air-facing +normals, no competing near-coincident local boundary, and a reverse set containing +the source. Thus the inexpensive path certifies only a near-coincident wall, rather +than treating global bounds and the full search radius as sufficient evidence. + +The fallback uses the caller's KD search radius, normally four seed-line widths, +for nearby boundaries of either type. With unchanged boundary type it finds the +nearest segment whose air-facing normal is compatible with the source, so the +opposite side of a thin contour cannot hide its facing side. Across a type change +the closest patch itself must agree; choosing another side can confuse translated annuli. +An open exterior wall can become a hole when a slit closes; boundary type alone +cannot reject that physical continuation. It checks air-facing +normals within 60 degrees and samples the connector between closest boundary points. +Away from boundary noise, the connector must lie in material of exactly one adjacent +layer, representing a swept wall rather than a crossing through shared material or +air. Three samples are a bounded heuristic, not a topological proof. + +Each local candidate must map back to a set containing the source boundary. A candidate +is discarded only if another has both a distance advantage of at least a quarter of +the source line width and a normal-angle advantage of at least five degrees. Equal or +conflicting criteria retain multiple candidates; seam preferences choose within +this set. Air-facing normals and material checks distinguish wall sides without imposing +an invariant exterior/hole label across topology changes. They are geometric gates, +not numerical preference weights. + +If no geometric candidate survives, the radius search is left unrestricted. Continuation +then follows seam preferences alone and can switch walls where geometry cannot resolve +the case. A nonempty geometric set is never +expanded because its contours are occupied or fail later seam preference checks. + +Correspondence queries are cached per source vertex, direction and search radius +for alternative string starts. Geometry construction and the seed loop check +cancellation to keep large multi-island objects interruptible. Correspondence does not alter candidate +preference weights or their tolerance. + +## Final position + +For each member of a string: + +1. **Sharp candidate** (`t = 1`): the seam is C. This is the cheapest check and comes first. +2. **Painted corner pull** (Enforced C only): `t = max(t, 0.4·k)` with the corner influence + `k ∈ [0, 1]` below. Retaining the pull near measured corners protects corners; fading it on + smooth contours reduces transmission of discrete candidate steps into the seam. If C's own angle + reaches `A1`, `k = 1` without a search. +3. **Place on the loop.** The target is mapped onto the loop, within the allowed arc around C. + +### Corner influence + +`k` is the largest contribution `a_j · w_j` among candidates `j` of the same perimeter within `R1` +of C along the loop, `d_j` being the distance along the loop: + +- `a_j` rises smoothly from 0 at a measured angle of `A0` to 1 at `A1`, so weak bends count partly + and smooth contours not at all; +- `w_j` is 1 up to `R0` and falls smoothly to 0 at `R1`, so a corner entering or leaving the + neighborhood does not switch `t` abruptly. + +`R0` is the larger of the perimeter's line width and the largest configured nozzle diameter: the +measured angle of a vertex reflects geometry within at least one nozzle diameter, so a candidate +inserted next to a corner usually still sees that corner. Within `R0` of a corner of at least +`A1`, `t` and the target are the same as with a fixed minimum of 0.4. + +### Placing the target on the loop + +The target is generally off the loop. Its closest loop point is a polygon vertex over a whole range +of target positions, so it snaps to vertices and steps between layers when the vertices differ from +layer to layer. + +Instead the loop gets a continuous normal field. Each vertex has the normalized sum of the normals +of its two edges, taken to the nearest points at a different position, so that duplicated points +(shared ends of extrusion paths, a repeated closing point) get one normal. Along an edge the normal +blends linearly between its vertex normals. A **solution** is a loop point whose normal line passes +through the target; on each edge this is a quadratic equation in the edge parameter. + +The seam is the solution closest to the target over the whole loop. If it lies outside the allowed +arc, the seam is the end of that arc closer to the solution, so a solution leaving the arc stays at +the end it leaves through. Without any solution, which takes a degenerate loop, the seam is C. + +The search walks outward from C on both sides, the shorter walked side first. An edge farther from +the target than the best solution so far is skipped without solving. + +Properties: + +- On a regular polygon every normal line passes through the center. For a target other than the + center, the closest solution is the nearer of the two intersections of the loop with the line + through the center and the target, wherever the vertices are; the seam equals it when it lies + inside the allowed arc. With an even number of vertices the two intersections are symmetric about + the center, so the nearer one is on the ray from the center through the target. +- When the closest solution is unique and lies inside the allowed arc, the result depends on the + target and that arc only, not on which candidate inside the arc was chosen. A candidate step + therefore does not pass into the seam directly. At an exact distance tie, the first solution found + from C is kept. +- A selected solution varies continuously while its root branch remains nondegenerate, and so does + the seam when the solution leaves or enters the allowed arc. The seam may jump when the closest + solution changes (two solutions equally close, or the closest one disappearing together with + another where the target crosses the curve of centers of the normal field), or when a solution + outside the arc becomes equally close to both arc ends. Changes of the candidate types between + layers change the allowed arc. + +### Allowed arc + +- For an Enforced C on a loop with exact ends: the Enforced run itself, which ends at the paint. +- For another Enforced C: the Enforced run, extended past each open end by the oversampling distance + (0.2 mm) but never into a Blocked candidate. The run ends sit on candidates and move in sampling + steps between layers, and Rear tends to choose the candidate right at an end; without the + extension a target just past an end would copy those steps into the seam. +- For another C: the part of the loop between the Blocked candidates around it. +- For a Blocked C, or a loop with no limiting candidate: the whole loop. + +## Numerical constants + +| Constant | Value | Meaning | +| --- | --- | --- | +| Blend minimum near corners | 0.4 | Pull toward C on a painted corner | +| `A0`, `A1` | 15°, 30° | Measured angle where corner contribution starts and becomes full | +| `R0` | max(line width, largest nozzle diameter); 0.5 mm if both are zero | Full corner protection along the loop | +| `R1` | 2·`R0` | Corner influence ends | +| Run extension | 0.2 mm (`enforcer_oversampling_distance`); 0 with exact ends | How far the seam may go past an end of the Enforced run | +| Painted range tolerance | 1 µm (`enforced_end_tolerance`) | Loop positions this close are one point | +| Range end reach | line width | How far from the loop a contour crossing may lie | +| Coverage proof depth | 8 bisections per edge | Finite conservative proof for complete paint on a partly painted object | +| Solver threshold | 1e-12 | Absolute threshold on the equation coefficients that tells degenerate equations apart; not a distance tolerance | + +## Constraints + +Strong Precise Seam coordinates remain immutable. Angles of at least 55 degrees retain the +selected candidate. Ambiguous paint boundaries use the proximity fallback; an entirely +blocked perimeter still needs a printed seam. Mesh topology and candidate sampling can change +which first-approximation string is selected. Painting a verified complete perimeter introduces +no artificial center preference. + +## Implementation and verification + +`SeamPlacer.cpp` implements paint reconstruction, candidate selection, string traversal, fitting +and contour placement. `test_seam_placer.cpp` covers geometry, paint, string traversal and strong +Precise Seam invariants. `tests/libslic3r/test_seam_contour.cpp` independently checks +geometric correspondence, ambiguity and search-radius behavior. diff --git a/docs/HLSD/translucent-filaments.md b/docs/HLSD/translucent-filaments.md new file mode 100644 index 0000000000..a72d058221 --- /dev/null +++ b/docs/HLSD/translucent-filaments.md @@ -0,0 +1,159 @@ +# Translucent filaments + +## Purpose + +A filament color can carry an opacity (`#RRGGBBAA`, see [color-picker.md](color-picker.md)). Prepare +draws the parts of such a filament see-through, and Preview their toolpaths, so the inside of a +translucent part and whatever lies behind it show through. Both tabs aim at the same look: the +opacity of the plastic the view ray crosses, matte without realistic view and glossy with it. + +## Where the opacity applies + +- Only the views that color toolpaths by filament: Filament, Summary and Tool. The other views + color by feature or by a value, and stay opaque. +- Only extrusions. Travels, wipes and option markers stay opaque, and so do the layers that hold a + pause or a custom G-code, which these views draw grey. +- A filament keeps its color down to 10% opacity, the floor `adjust_color_for_rendering()` gives it in + Prepare too, so that a fully clear filament is still drawn. A near-black filament is lifted to a grey + that rises with its transparency: a dark translucent surface shows nothing through itself, so without + the lift its layers blend into one flat black. +- The "Translucent filaments" preference (`preview_translucent_filaments`, on by default) turns all + of it off: every filament is then drawn opaque, the legend swatches included. It applies to the + loaded preview at once, through `Viewer::set_translucent_filaments()`. +- The legend swatches carry the same opacity, drawn over the white and grey checkerboard of the + sidebar's clear filament swatch so that they read on the dark legend. +- The opacity is that of 0.4 mm of the filament. Each translucent segment raises it to the length + of the view ray through the centre of its diamond section, `1 - (1 - a)^(path / 0.4)`, so thin + layers stacked under the camera add up as one thick layer would, and a wall seen side on keeps + about the filament's opacity whatever the layer height. + +## Data + +`libvgcode::convert_filament_colors()` decodes the filament color strings into a +`libvgcode::PaletteWithAlpha`. libvgcode keeps one RGBA8 color per vertex, in a `GL_RGBA8` texture +buffer, or in RGBA8 2D textures on OpenGL ES. The color depends on the view type, while the alpha +comes from the filament alone. The viewer also notes whether any vertex is translucent. + +## Rendering + +A segment takes the alpha of its first vertex. While any vertex is translucent, +`update_enabled_entities()` sorts the enabled segments by opacity, the opaque ones first, keeping +the print order within each group; on OpenGL ES, each texture of the list is sorted on its own. +Each pass draws its own group, from an offset into the list. Without a translucent vertex, the list +is not sorted and the second pass is skipped, so the first draws exactly what it drew before. + +1. The opaque segments, with depth writes. +2. The option markers. +3. The translucent segments, in premultiplied color blended with `GL_ONE, GL_ONE_MINUS_SRC_ALPHA`, + depth tested but without depth writes. Opaque toolpaths and objects hide the translucent ones + behind them, and a translucent segment hides nothing. Drawing the markers first keeps those + inside a translucent part behind its surface, instead of on top of it. + +`Viewer::render()` draws the first two; `Viewer::render_translucent()` draws the third, which +`GLCanvas3D::_render_gcode_translucent()` calls after the SSAO pass. Drawn that late, the pass turns the +depth test on itself, as the passes before it may leave it off. The occlusion that pass reads +from depth would otherwise shade a translucent surface as the surface behind it, as it would the +centre of mass marker. FXAA still comes after. The sequential view markers and the IDEX/IQEX +toolhead boxes, which `GCodeViewer::render_scene()` draws after the toolpaths, are translucent but +write depth, so while there are translucent toolpaths they wait for them, in +`GCodeViewer::render_translucent_toolpaths()`. Drawn before, they would hide the translucent toolpaths +behind them, and the print would show a hole around the tool position. + +A translucent segment takes its diffuse light in its own color, scaled by its opacity. In +realistic view, whatever its other options, with its "Glossy toolpaths" setting on, every segment, +opaque or translucent, takes instead of the tinted highlight of the default shading an untinted one +computed per fragment, not scaled by the opacity, so that the filaments look alike and a clear one +keeps its gloss instead of fading into the background. `GLCanvas3D::_render_gcode()` switches it +with `Viewer::set_gloss()`. Without realistic view, or with the setting off, a translucent filament +is matte and an opaque one keeps the default shading. The +highlight takes the normal of the rounded extrusion a segment stands for, an ellipse of its height +and width around its centre line, rather than that of its facets: it then runs smoothly across a +joint, where the facets of two segments would catch it apart, and it fades out towards the tip of a +path end, whose normal runs along the extrusion. There +is no Fresnel term: an extrusion seen end-on would turn into a bright opaque stripe. + +Each segment reaches half a line width past its ends, to fill the outside of a turn or round off a +path end, so two segments of a path overlap at their joint. Depth hides that between opaque ones, +but blending would draw the joint twice, and the highlight of realistic view shows the caps sticking +out of an opaque one. A translucent segment, and a glossy one, is therefore cut in the fragment +shader at the bisector plane of each joint of its path, keeping 0.02 mm past it: the +faces each segment turns to the camera do not quite meet without their caps. A vertex where two +segments of a path meet carries 0.5 on top of its layer in the w of its position, which the shaders +otherwise read as an int. That includes the joints across the vertex repeated in place that starts +a new path wherever the flow, acceleration or jerk changes (`starts_path()` in +`LibVGCodeWrapper.cpp`), which real G-code has at most of its joints: the shader then takes the +neighbour one vertex further, and the caps the angle of the joint, which the vertex data leaves at 0 +there. + +The translucent segments are not sorted by depth. The opaque pass draws the last printed segments +first when looking down, to cut overdraw. The direct translucent pass, which only some cases fall +back to (see below), draws them the other way round, so the farthest layers blend first. + +## Order independent blending + +Blended in print order, the order shows even with a single translucent color, since its surfaces are +shaded apart. A layer's infill, printed after its walls, blends over the walls in front of it: seen +from the side, the dark bridge under a deck draws a sawtooth over the hull's outer wall, as if a piece +of it were missing. So on desktop OpenGL the translucent segments blend order independently, in +`ViewerImpl::render_translucent_segments()`. The nearest +translucent surface of each pixel is drawn over a weighted blended order independent transparency +(McGuire and Bavoil, 2013) of the others. The mean alone would not do: the walls of a painted object +lie a fraction of a millimetre apart, so its depth weights barely differ, and the more opaque and more +numerous surfaces of one filament would hide the other filament's outer wall in front of them. + +1. The depth of the scene drawn so far is copied into a texture. The fragment shader discards a + translucent fragment behind it, as there is no depth buffer to test against. +2. The translucent segments are drawn once into an `R32F` target cleared to 1, keeping with `GL_MIN` + the `gl_FragCoord.z` of the nearest. The segments shaders draw it built with `DEPTH_ONLY`, the same + geometry and joint cut without the shading and its varyings, so the nearest fragment of the next + pass finds its own depth there exactly. +3. They are drawn again. The nearest fragment of a pixel goes, premultiplied, to an `RGBA16F` target + of its own. Every other one adds its premultiplied color, times a weight, to an `RGBA16F` target, + and `-log(1 - alpha)` to an `R16F` target, with `GL_ONE, GL_ONE`. The weight is the opacity times + `max((1 - z)^3, 0.01)`, z being the depth across the extrusions' bounding box, so nearer surfaces + count more. Its ceiling keeps thousands of stacked surfaces within half float range, and its floor + keeps far ones out of the subnormals. A translucent segment's opacity stays below 1, else the + shader would take it for an opaque one and add it unweighted. +4. A full screen pass draws the nearest surface over the weighted mean color of the others, with + their coverage `1 - exp(-sum)`, over the scene. + +Swapping the drawing order changes the result by at most 2 levels out of 255, against up to 246 in +the direct pass. The targets are single-sampled whatever the canvas, about 26 bytes per pixel. +Multisampled ones would take twice the time and four times the memory for edges FXAA can smooth, and +against a single-sampled depth pass an edge sample could miss its nearest depth and count twice. +OpenGL ES, whose float targets are optional, takes the direct pass, as does a multisampled framebuffer +object, whose depth cannot be copied into a texture. + +## Cost and side effects + +Without depth writes, every translucent surface on screen is shaded, so the cost of the second +pass grows with the number of translucent surfaces stacked on screen. Order independent blending +draws the translucent segments twice and writes 18 bytes of float data per pixel instead of 4, between +a tenth and two fifths more than the direct pass. + +In realistic view, a translucent segment casts into a share of the shadow map texels as large as +its opacity, in an ordered 4x4 pattern that the 5x5 filter of the receivers reads as a lighter +shadow. The pattern shifts with the segment, so layers stacked along the light add up: a 1 mm +translucent box at 35% casts a shadow about 60% as dark as an opaque one, a 10 mm box nearly a full +one. + +## Prepare + +Prepare draws a part as a closed mesh, which would show a single surface at the filament's opacity, +far fainter and darker than the print of that part in Preview. The object shaders therefore shade a +visible model part whose filament color is translucent as the view ray crossing two shells of the +part, the front and the back one, of two 0.45 mm walls each, with the opacity rule of Preview: +`1 - (1 - a)^(1.8 / 0.4 / cos)`, cos being that of the angle between the view and the normal, +floored at 0.25. A filament at 35% is then about 86% opaque face on, and nearly opaque at the +silhouette, where the ray grazes the walls. See `translucent_filament_color()` in `gouraud.fs` and +`phong.fs`. + +Such a part is drawn in premultiplied color, blended with `GL_ONE, GL_ONE_MINUS_SRC_ALPHA`, so that +in realistic view its highlight is not dimmed by its opacity; without realistic view it takes no +highlight. `GLVolumeCollection::render()` switches this per volume, and only with a shader that has +the `translucent_filament` uniform, the GLSL 1.40 ones: with the GLSL 1.10 and ES shaders, such a +part blends as a plain transparent volume. Modifiers, negative volumes and opaque parts are drawn as +they were. + +The wireframe overlay draws translucent filament parts too, with blending off, so their lines stay +solid. diff --git a/localization/i18n/eu/OrcaSlicer_eu.po b/localization/i18n/eu/OrcaSlicer_eu.po index ae0c510186..dc53326e7a 100644 --- a/localization/i18n/eu/OrcaSlicer_eu.po +++ b/localization/i18n/eu/OrcaSlicer_eu.po @@ -8,7 +8,7 @@ msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2026-10-19 09:48-0300\n" -"PO-Revision-Date: 2026-07-20 13:33+0200\n" +"PO-Revision-Date: 2026-10-19 18:56+0200\n" "Last-Translator: Manu Goiogana \n" "Language-Team: \n" "Language: eu\n" @@ -16,7 +16,7 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" -"X-Generator: Poedit 3.9\n" +"X-Generator: Poedit 3.10\n" # AI Translated msgid "Main Extruder" @@ -32,15 +32,15 @@ msgstr "estrusore nagusia" # AI Translated msgid "Auxiliary Extruder" -msgstr "Estrusore lagungarria" +msgstr "Estrusore laguntzailea" # AI Translated msgid "Auxiliary extruder" -msgstr "Estrusore lagungarria" +msgstr "Estrusore laguntzailea" # AI Translated msgid "auxiliary extruder" -msgstr "estrusore lagungarria" +msgstr "estrusore laguntzailea" msgid "Left Extruder" msgstr "Ezkerreko estrusorea" @@ -74,15 +74,15 @@ msgstr "pita nagusia" # AI Translated msgid "Auxiliary Nozzle" -msgstr "Pita lagungarria" +msgstr "Pita laguntzailea" # AI Translated msgid "Auxiliary nozzle" -msgstr "Pita lagungarria" +msgstr "Pita laguntzailea" # AI Translated msgid "auxiliary nozzle" -msgstr "pita lagungarria" +msgstr "pita laguntzailea" msgid "Left Nozzle" msgstr "Ezkerreko pita" @@ -117,15 +117,15 @@ msgstr "hotend nagusia" # AI Translated msgid "Auxiliary Hotend" -msgstr "Hotend lagungarria" +msgstr "Hotend laguntzailea" # AI Translated msgid "Auxiliary hotend" -msgstr "Hotend lagungarria" +msgstr "Hotend laguntzailea" # AI Translated msgid "auxiliary hotend" -msgstr "hotend lagungarria" +msgstr "hotend laguntzailea" # AI Translated msgid "Left Hotend" @@ -157,7 +157,7 @@ msgstr "nagusia" # AI Translated msgid "auxiliary" -msgstr "lagungarria" +msgstr "laguntzailea" # AI Translated msgid "Main" @@ -165,7 +165,7 @@ msgstr "Nagusia" # AI Translated msgid "Auxiliary" -msgstr "Lagungarria" +msgstr "Laguntzailea" msgid "left" msgstr "ezkerra" @@ -776,7 +776,7 @@ msgstr "Lerrokatu ezkerrean" # AI Translated msgid "Align left-right center" -msgstr "Lerrokatu erdian ezker-eskuin norabidean" +msgstr "Lerrokatu erdian X norabidean" # AI Translated msgid "Align right" @@ -789,7 +789,7 @@ msgstr "Lerrokatu aurrean" # AI Translated # Needs human review: Object menu item that aligns object centers on the plate's front-back (Y) axis; check that the 'aurre-atze' compound reads naturally. msgid "Align front-back center" -msgstr "Lerrokatu erdian aurre-atze norabidean" +msgstr "Lerrokatu erdian Y norabidean" # AI Translated msgid "Align back" @@ -802,7 +802,7 @@ msgstr "Lerrokatu behean" # AI Translated # Needs human review: Object menu item that aligns object centers on the vertical (Z) axis; check that the 'goi-behe' compound reads naturally. msgid "Align top-bottom center" -msgstr "Lerrokatu erdian goi-behe norabidean" +msgstr "Lerrokatu erdian Z norabidean" # AI Translated msgid "Align top" @@ -810,24 +810,24 @@ msgstr "Lerrokatu goian" # AI Translated msgid "Distribute left-right" -msgstr "Banatu ezker-eskuin norabidean" +msgstr "Berdinbanatu X norabidean" # AI Translated # Needs human review: Object menu item that spaces objects evenly along the plate's front-back (Y) axis; check that the 'aurre-atze' compound reads naturally. msgid "Distribute front-back" -msgstr "Banatu aurre-atze norabidean" +msgstr "Berdinbanatu Y norabidean" # AI Translated # Needs human review: Object menu item that spaces objects evenly along the vertical (Z) axis; check that the 'goi-behe' compound reads naturally. msgid "Distribute top-bottom" -msgstr "Banatu goi-behe norabidean" +msgstr "Berdinbanatu Z norabidean" msgid "Drop" msgstr "Askatu" # AI Translated msgid "Move the selection along Z so that its lowest point touches the bed." -msgstr "Mugitu hautapena Z ardatzean, bere punturik baxuenak ohea ukitu dezan." +msgstr "Mugitu hautaketa Z ardatzean, bere punturik baxuenak ohea ukitu dezan." msgid "Absolute" msgstr "Absolutua" @@ -12086,7 +12086,7 @@ msgid "It can't be deleted or modified." msgstr "Ezin da ezabatu edo aldatu." msgid "Any modifications should be saved as a new preset inherited from this one." -msgstr "Aldaketa guztiak honetatik herentzian hartutako aurrezarpen berri gisa gorde behar dira.." +msgstr "Aldaketa guztiak honetatik herentzian hartutako aurrezarpen berri gisa gorde behar lirateke." msgid "To do that please specify a new name for the preset." msgstr "Horretarako, zehaztu aurrezarpenaren izen berri bat." @@ -13197,11 +13197,11 @@ msgstr "Pertsonalizatua" # AI Translated msgid "Welcome to Orca Slicer" -msgstr "Ongi etorri Orca Slicer-era" +msgstr "Ongi etorri OrcaSlicer-era" # AI Translated msgid "Orca Slicer will be set up in several steps. Let's start!" -msgstr "Orca Slicer hainbat urratsetan konfiguratuko da. Has gaitezen!" +msgstr "OrcaSlicer hainbat urratsetan konfiguratuko da. Has gaitezen!" # AI Translated msgid "Get Started" @@ -13535,7 +13535,7 @@ msgstr "Sareko pluginaren eguneratzea" # AI Translated msgid "Click OK to update the Network plug-in now. If a file is in use, the update will be applied the next time Orca Slicer launches." -msgstr "Egin klik Ados botoian Sareko plugina orain eguneratzeko. Fitxategiren bat erabiltzen ari bada, eguneraketa Orca Slicer hurrengoan abiaraztean aplikatuko da." +msgstr "Egin klik Ados botoian Sareko plugina orain eguneratzeko. Fitxategiren bat erabiltzen ari bada, eguneraketa OrcaSlicer hurrengoan abiaraztean aplikatuko da." # AI Translated msgid "A new Network plug-in is available. Do you want to install it?" @@ -14917,7 +14917,7 @@ msgid "" "If set to 0, the line width will match the Internal solid infill width, or the nozzle diameter for thick bridges." msgstr "" "Zubiaren lerro-zabalera. % gisa adierazten bada, pitaren diametroaren arabera kalkulatuko da.\n" -"Zubien dentsitate handiagoarekin edo zubien fluxu-ratio handiagoarekin erabiltzea gomendatzen da.\n" +"Zubiaren dentsitate handiagoarekin edo zubiaren fluxu-ratio handiagoarekin erabiltzea gomendatzen da.\n" "\n" "Gehieneko balioa %100 edo pitaren diametroa da.\n" "0 ezartzen bada, lerro-zabalera barruko betegarri solidoaren zabalerarekin bat etorriko da, edo pitaren diametroarekin zubi lodietan." @@ -17140,7 +17140,7 @@ msgid "Best auto arranging position in range [0,1] w.r.t. bed shape." msgstr "Ohearen formarekiko [0,1] tartean automatikoki antolatzeko posizio onena." msgid "Enable this option if machine has auxiliary part cooling fan. G-code command: M106 P2 S(0-255)." -msgstr "Gaitu aukera hau makinak piezaren hozterako haizagailu lagungarria badu. G-code komandoa: M106 P2 S(0-255)." +msgstr "Gaitu aukera hau makinak piezaren hozterako haizagailu laguntzailea badu. G-code komandoa: M106 P2 S(0-255)." msgid "Fan direction" msgstr "Haizagailuaren norabidea" @@ -17246,7 +17246,7 @@ msgstr "Saltatu G-code-aren konfigurazio-blokea" # AI Translated msgid "Do not write the CONFIG_BLOCK (slicer configuration key/value pairs) into the G-code file. This can help with printers whose firmware crashes when parsing these comment lines (e.g. Anycubic go-klipper). Note: the G-code file will no longer contain slicer settings, so importing it back into OrcaSlicer will not restore the configuration." -msgstr "Ez idatzi CONFIG_BLOCK (xerragailuaren konfigurazioko gako/balio bikoteak) G-code fitxategian. Lagungarria izan daiteke firmwareak iruzkin-lerro horiek prozesatzean huts egiten duen inprimagailuetan (adib. Anycubic go-klipper). Oharra: G-code fitxategiak ez ditu jada xerragailuaren ezarpenak edukiko; beraz, OrcaSlicer-era berriro inportatzeak ez du konfigurazioa berreskuratuko." +msgstr "Ez idatzi CONFIG_BLOCK (xerratzailearen konfigurazioko gako/balio bikoteak) G-code fitxategian. Lagungarria izan daiteke firmwareak iruzkin-lerro horiek prozesatzean huts egiten duen inprimagailuetan (adib. Anycubic go-klipper). Oharra: G-code fitxategiak ez ditu jada xerratzailearen ezarpenak edukiko; beraz, OrcaSlicer-era berriro inportatzeak ez du konfigurazioa berreskuratuko." msgid "Pellet Modded Printer" msgstr "Pelletekin moldatutako inprimagailua" @@ -18025,7 +18025,7 @@ msgid "" "Speed of auxiliary part cooling fan. Auxiliary fan will run at this speed during printing except the first several layers which is defined by no cooling layers.\n" "Please enable auxiliary_fan in printer settings to use this feature. G-code command: M106 P2 S(0-255)" msgstr "" -"Piezaren hozte-haizagailu lagungarriaren abiadura. Haizagailu lagungarria abiadura honetan ibiliko da inprimatzean, hozterik gabeko geruzek definitutako lehen geruzetan izan ezik.\n" +"Piezaren hozte-haizagailu laguntzailearen abiadura. Haizagailu laguntzailea abiadura honetan ibiliko da inprimatzean, hozterik gabeko geruzek definitutako lehen geruzetan izan ezik.\n" "Gaitu auxiliary_fan inprimagailuaren ezarpenetan ezaugarri hau erabiltzeko. G-code komandoa: M106 P2 S(0-255)" msgid "For the first" @@ -25278,7 +25278,7 @@ msgstr "Sortu lehenik ebakitzeko gorputz solido bat" # AI Translated msgid "Cut — needs a solid body to slice" -msgstr "Ebaki — gorputz solido bat behar du zatitzeko" +msgstr "Ebaki — gorputz solido bat behar du xerratzeko" # AI Translated msgid "Color — set the selected body's display color" @@ -30069,7 +30069,7 @@ msgstr "Modeloaren irudiak" # AI Translated msgid "Auxiliaries" -msgstr "Lagungarriak" +msgstr "Laguntzaileak" # AI Translated msgid "Belt Purge Tower" @@ -30615,7 +30615,7 @@ msgstr "Altzairu-urdina" # AI Translated # Needs human review: Flower name not known in Basque; rendered as Lore-urdina (flower blue), check for a proper name. msgid "Cornflower blue" -msgstr "Lore-urdina" +msgstr "Urdin bizia" # AI Translated msgid "Royal blue" @@ -30807,7 +30807,7 @@ msgstr "Uhin-egurra" # AI Translated # Needs human review: Plant name (Hippophae); check the Basque name and whether a color-only name reads better. msgid "Sea buckthorn" -msgstr "Itsas elorri-zuria" +msgstr "Elorri horia" # AI Translated msgid "Sunset reef" @@ -31052,7 +31052,7 @@ msgstr "Okre-horia" # AI Translated # Needs human review: Source name looks like a RAL variant; check the rendering. msgid "Traffic orange yellow" -msgstr "Trafiko-laranja horixka" +msgstr "Trafikoko laranja-horixka" # AI Translated msgid "Curry" @@ -32310,7 +32310,7 @@ msgstr "OrcaCloud irekitzen du Hasiera orrian, pluginak arakatzeko." # AI Translated msgid "Import your own image as a height map. It is converted to the format the slicer bakes from and saved to your personal texture folder, kept separate from the textures shipped with OrcaSlicer." -msgstr "Inportatu zure irudi propioa altuera-mapa gisa. Xerragailuak finkatzeko erabiltzen duen formatura bihurtzen da eta zure testura-karpeta pertsonalean gordetzen da, OrcaSlicer-ekin datozen testuretatik bereizita." +msgstr "Inportatu zure irudi propioa altuera-mapa gisa. Xerratzaileak finkatzeko erabiltzen duen formatura bihurtzen da eta zure testura-karpeta pertsonalean gordetzen da, OrcaSlicer-ekin datozen testuretatik bereizita." # AI Translated msgid "PNG, JPG or BMP - converted to a height map on import. Hover one of yours to remove it." @@ -33266,7 +33266,7 @@ msgstr "Garbitu triangelu meheak" # AI Translated msgid "Collapse the thin triangles refinement inherits from the model's own tessellation, before displacement samples them. A sliver's three corners land on three unrelated parts of the texture, which is what makes the relief look jagged." -msgstr "Desegin fintzeak modeloaren teselaziotik heredatzen dituen triangelu meheak, desplazamenduak laginak hartu aurretik. Triangelu mehe baten hiru erpinak testuraren hiru zati desberdinetan erortzen dira, eta horregatik ikusten da erliebea zerratua." +msgstr "Desplazamendu-laginketa gertatu baino lehen, kendu errefinamenduak modeloaren jatorrizko teselaziotik jasotzen dituen triangelu meheak. Triangelu mehe baten hiru erpinak testuraren hiru zati desberdinetan erortzen dira, eta horregatik ikusten da erliebea zerratua." # AI Translated msgid "On: the resolution follows the size of the model and the budget is left at its default. Untick to set both yourself - worth doing for a texture much finer or much coarser than the part it sits on." @@ -36068,8 +36068,7 @@ msgstr "" "Banatu inprimaketak plaketan\n" "Ba al zenekien pieza asko dituen modelo bat inprimatzeko prest dauden plaka banatan bana dezakezula? Horrek pieza guztien jarraipena egitea erraztuko du." -#: resources/data/hints.ini: [hint:Speed up your print with Adaptive Layer -#: Height] +#: resources/data/hints.ini: [hint:Speed up your print with Adaptive Layer Height] msgid "" "Speed up your print with Adaptive Layer Height\n" "Did you know that you can print a model even faster by using the Adaptive Layer Height option? Check it out!" @@ -36141,8 +36140,7 @@ msgstr "" "Hobetu erresistentzia\n" "Ba al zenekien horma-begizta gehiago eta dentsitate baxuko betegarriaren dentsitate handiagoa erabil ditzakezula modeloaren erresistentzia hobetzeko?" -#: resources/data/hints.ini: [hint:When do you need to print with the printer -#: door opened] +#: resources/data/hints.ini: [hint:When do you need to print with the printer door opened] msgid "" "When do you need to print with the printer door opened?\n" "Did you know that opening the printer door can reduce the probability of extruder/hotend clogging when printing lower temperature filament with a higher enclosure temperature? There is more info about this in the Wiki." diff --git a/localization/i18n/pt_BR/OrcaSlicer_pt_BR.po b/localization/i18n/pt_BR/OrcaSlicer_pt_BR.po index 1fb4d894ec..d2491b3d4c 100644 --- a/localization/i18n/pt_BR/OrcaSlicer_pt_BR.po +++ b/localization/i18n/pt_BR/OrcaSlicer_pt_BR.po @@ -4,7 +4,7 @@ msgstr "" "Project-Id-Version: Orca Slicer\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2026-10-19 09:48-0300\n" -"PO-Revision-Date: 2026-10-17 10:38-0300\n" +"PO-Revision-Date: 2026-10-21 19:32-0300\n" "Last-Translator: Alexandre Folle de Menezes\n" "Language-Team: Portuguese, Brazilian\n" "Language: pt_BR\n" @@ -354,7 +354,7 @@ msgstr "Por favor, aguarde" #. TRN %d/%d is the hotend being read and the number of hotends to read. #, c-format, boost-format msgid "Induction Hotend Rack: Reading %d/%d" -msgstr "Suporte para Hotend por Indução: lendo %d/%d" +msgstr "Suporte para Hotend por Indução: Lendo %d/%d" msgid "Running..." msgstr "Executando…" @@ -505,7 +505,6 @@ msgstr "Gizmo-Posicionar na face" msgid "Lay on Face" msgstr "Apoiar na Face" -# AI Translated #, boost-format msgid "Filament count exceeds the maximum number that painting tool supports. Only the first %1% filament will be available in painting tool." msgid_plural "Filament count exceeds the maximum number that painting tool supports. Only the first %1% filaments will be available in painting tool." @@ -561,7 +560,6 @@ msgctxt "Keyboard Shortcut" msgid "Enter" msgstr "Enter" -# AI Translated #, c-format, boost-format msgid "Shortcut Key %d" msgstr "Tecla de atalho %d" @@ -725,74 +723,57 @@ msgstr "Seleção" msgid "Plate" msgstr "Placa" -# AI Translated -# Needs human review: Glossary has no pt_BR rendering for Distribute; check it matches the Align/Distribute menu msgid "Distribute" msgstr "Distribuir" msgid "Coordinate system used for transform actions." msgstr "Sistema de coordenadas usado para ações de transformação." -# AI Translated msgid "Reference for alignment" msgstr "Referência para o alinhamento" -# AI Translated msgid "Select at least 3 parts or objects" msgstr "Selecione pelo menos 3 peças ou objetos" -# AI Translated msgid "Align left" msgstr "Alinhar à esquerda" -# AI Translated msgid "Align left-right center" msgstr "Alinhar ao centro esquerda-direita" -# AI Translated msgid "Align right" msgstr "Alinhar à direita" -# AI Translated msgid "Align front" msgstr "Alinhar à frente" -# AI Translated msgid "Align front-back center" msgstr "Alinhar ao centro frente-trás" -# AI Translated msgid "Align back" msgstr "Alinhar atrás" -# AI Translated msgid "Align bottom" msgstr "Alinhar embaixo" -# AI Translated msgid "Align top-bottom center" msgstr "Alinhar ao centro cima-baixo" -# AI Translated msgid "Align top" msgstr "Alinhar em cima" -# AI Translated msgid "Distribute left-right" msgstr "Distribuir esquerda-direita" -# AI Translated msgid "Distribute front-back" msgstr "Distribuir frente-trás" -# AI Translated msgid "Distribute top-bottom" msgstr "Distribuir cima-baixo" msgid "Drop" msgstr "Descartar" -# AI Translated msgid "Move the selection along Z so that its lowest point touches the bed." msgstr "Move a seleção ao longo de Z para que seu ponto mais baixo toque a mesa." @@ -1065,7 +1046,6 @@ msgstr "Plano de corte com cavidade é inválido" msgid "Connector" msgstr "Conector" -# AI Translated #, boost-format msgid "" "Object (%1%) has duplicated connectors. Some connectors may be missing in slicing result.\n" @@ -1145,7 +1125,6 @@ msgstr "Baixo" msgid "Extra low" msgstr "Extra baixo" -# AI Translated #, boost-format msgid "%1% triangle" msgid_plural "%1% triangles" @@ -1161,16 +1140,14 @@ msgstr "Não é possível aplicar quando a pré-visualização está em processa msgid "Operation already cancelling. Please wait a few seconds." msgstr "Operação já está sendo cancelada. Por favor, aguarde alguns segundos." -# AI Translated msgid "Model simplification has been canceled" msgstr "A simplificação do modelo foi cancelada" msgid "Wiki Guide" msgstr "Guia Wiki" -# AI Translated msgid "Video Guide" -msgstr "Guia em vídeo" +msgstr "Guia em Vídeo" msgid "Enforce seam" msgstr "Forçar costura" @@ -1222,11 +1199,9 @@ msgstr "Posição na superfície" msgid "Emboss" msgstr "Relevo" -# AI Translated msgid "No active font in style. Select correct one." msgstr "Nenhuma fonte ativa no estilo. Selecione a correta." -# AI Translated msgid "WxFont is not loaded properly." msgstr "A WxFont não foi carregada corretamente." @@ -1873,23 +1848,18 @@ msgstr "Diâmetro" msgid "Length" msgstr "Comprimento" -# AI Translated msgid "Face 1 (Fixed)" msgstr "Face 1 (Fixa)" -# AI Translated msgid "Face 2 (Moving)" msgstr "Face 2 (Movendo)" -# AI Translated msgid "Point 1 (Fixed)" msgstr "Ponto 1 (Fixo)" -# AI Translated msgid "Point 2 (Moving)" msgstr "Ponto 2 (Movendo)" -# AI Translated msgid "Selection 1" msgstr "Seleção 1" @@ -1907,7 +1877,6 @@ msgstr "" "Selecione 2 pontos ou círculos em objetos\n" "e especifique a distância entre eles." -# AI Translated msgid "Selection 2" msgstr "Seleção 2" @@ -2006,19 +1975,15 @@ msgstr "Entrando no gizmo de Montagem" msgid "Leaving Assembly gizmo" msgstr "Saindo do gizmo de Montagem" -# AI Translated msgid "Parts of a cut object cannot be moved" msgstr "As peças de um objeto cortado não podem ser movidas" -# AI Translated msgid "Aligning to the plate is available in X and Y only" msgstr "O alinhamento à placa está disponível apenas em X e Y" -# AI Translated msgid "Turn off Auto-Drop for the selected objects to move them in Z" msgstr "Desative a Soltura Automática dos objetos selecionados para movê-los em Z" -# AI Translated msgid "All selected objects must be on the same plate" msgstr "Todos os objetos selecionados devem estar na mesma placa" @@ -2063,7 +2028,6 @@ msgstr "O pacote de configuração foi carregado, mas alguns valores não foram msgid "The configuration file “%1%” was loaded, but some values were not recognized." msgstr "O arquivo de configuração \"%1%\" foi carregado, mas alguns valores não foram reconhecidos." -# AI Translated #, c-format, boost-format msgid "" "\"%s\" is not a plain document, image or model file. Opening it may run it as a program or script on this computer.\n" @@ -2195,7 +2159,6 @@ msgstr "" msgid "WebView2 Runtime" msgstr "Tempo de execução WebView2" -# AI Translated #, boost-format msgid "" "The Microsoft WebView2 Runtime could not be installed.\n" @@ -2204,7 +2167,7 @@ msgid "" msgstr "" "Não foi possível instalar o Microsoft WebView2 Runtime.\n" "Alguns recursos, incluindo o assistente de configuração, podem aparecer em branco até que ele seja instalado.\n" -"Instale-o manualmente a partir de %1% e reinicie o Orca Slicer." +"Instale-o manualmente a partir de %1% e reinicie o OrcaSlicer." #, c-format, boost-format msgid "Resources path does not exist or is not a directory: %s" @@ -2422,15 +2385,12 @@ msgstr "Restrição de Plug-in de Rede" msgid "Privacy Policy Update" msgstr "Atualização da Política de Privacidade" -# AI Translated msgid "All your filament presets are available on the printers they were made for." msgstr "Todas as suas predefinições de filamento estão disponíveis nas impressoras para as quais foram criadas." -# AI Translated msgid "Migrate Filament Presets" msgstr "Migrar Predefinições de Filamento" -# AI Translated msgid "" "OrcaSlicer 2.5.0 restructured many system filament presets to fix incorrect profiles and prepare for future features. As a result, the presets below no longer show on some printers they were made for. Sorry for the trouble; this is a one-time fix.\n" "\n" @@ -2438,9 +2398,8 @@ msgid "" msgstr "" "O OrcaSlicer 2.5.0 reestruturou muitas predefinições de filamento do sistema para corrigir perfis incorretos e preparar recursos futuros. Como resultado, as predefinições abaixo não aparecem mais em algumas das impressoras para as quais foram criadas. Pedimos desculpas pelo transtorno; esta é uma correção única.\n" "\n" -"Adicionar essas impressoras de volta às suas predefinições agora? É feito um backup das suas predefinições antes. Você também pode fazer isso mais tarde em Ajuda > Migrar Predefinições de Filamento." +"Adicionar essas impressoras de volta às suas predefinições agora? Será feito um backup das suas predefinições antes. Você também pode fazer isso mais tarde em Ajuda > Migrar Predefinições de Filamento." -# AI Translated #, boost-format msgid "%1% (based on %2%)" msgstr "%1% (baseado em %2%)" @@ -2448,15 +2407,12 @@ msgstr "%1% (baseado em %2%)" msgid "Don't remind me again" msgstr "Não me avise novamente" -# AI Translated msgid "Your presets could not be backed up, so they were not migrated." msgstr "Não foi possível fazer backup das suas predefinições, então elas não foram migradas." -# AI Translated msgid "The user presets folder could not be locked, so nothing was migrated. Another OrcaSlicer instance may be saving presets; try again later from Help > Migrate Filament Presets." -msgstr "Não foi possível bloquear a pasta de predefinições do usuário, então nada foi migrado. Outra instância do OrcaSlicer pode estar salvando predefinições; tente novamente mais tarde em Ajuda > Migrar Predefinições de Filamento." +msgstr "Não foi possível travar a pasta de predefinições do usuário, então nada foi migrado. Outra instância do OrcaSlicer pode estar salvando predefinições; tente novamente mais tarde em Ajuda > Migrar Predefinições de Filamento." -# AI Translated #, boost-format msgid "" "Your filament presets could not be migrated. A backup of your presets was saved to:\n" @@ -2478,7 +2434,6 @@ msgstr "" "Um backup das suas predefinições foi salvo em:\n" "%1%" -# AI Translated msgid "These presets could not be migrated:" msgstr "Não foi possível migrar estas predefinições:" @@ -2554,7 +2509,6 @@ msgstr "%s foi removido." msgid "Switching Orca Slicer to language %s failed." msgstr "Falha ao mudar o idioma do OrcaSlicer para %s." -# AI Translated msgid "" "\n" "You may need to reconfigure the missing locales, likely by running the \"locale-gen\" and \"dpkg-reconfigure locales\" commands.\n" @@ -2562,7 +2516,6 @@ msgstr "" "\n" "Você pode precisar reconfigurar as localidades ausentes, provavelmente executando os comandos \"locale-gen\" e \"dpkg-reconfigure locales\".\n" -# AI Translated msgid "Application will close." msgstr "O aplicativo será fechado." @@ -2586,7 +2539,6 @@ msgstr "" msgid "Failed to open the Plugins dialog (unknown error)." msgstr "Falha ao abrir a caixa de diálogo de Plugins (erro desconhecido)." -# AI Translated msgid "Plugins refreshed." msgstr "Plugins atualizados." @@ -2600,7 +2552,6 @@ msgstr "Erro desconhecido" msgid "Select plugin package" msgstr "Selecione o pacote de plugins" -# AI Translated msgid "Plugin files (*.py;*.whl)|*.py;*.whl" msgstr "Arquivos de plugin (*.py;*.whl)|*.py;*.whl" @@ -2722,9 +2673,8 @@ msgstr "Adicionar Bloqueador de Suporte" msgid "Add Support Enforcer" msgstr "Adicionar Reforço de Suporte" -# AI Translated msgid "Add Precise Seam" -msgstr "Adicionar costura precisa" +msgstr "Adicionar Costura Precisa" msgid "Add text" msgstr "Adicionar texto" @@ -2846,9 +2796,8 @@ msgstr "Bloqueador de Suporte" msgid "Support Enforcer" msgstr "Reforço de Suporte" -# AI Translated msgid "Precise Seam" -msgstr "Costura precisa" +msgstr "Costura Precisa" msgid "Change part type" msgstr "Mudar tipo de peça" @@ -2992,33 +2941,26 @@ msgstr "Espelhar ao longo do Eixo Z" msgid "Mirror object" msgstr "Espelhar objeto" -# AI Translated msgid "Precise Seam Type" -msgstr "Tipo de costura precisa" +msgstr "Tipo de Costura Precisa" -# AI Translated msgid "Seam Center" -msgstr "Costura no centro" +msgstr "Costura no Centro" -# AI Translated msgid "Seam Left" -msgstr "Costura à esquerda" +msgstr "Costura à Esquerda" -# AI Translated msgid "Seam Right" -msgstr "Costura à direita" +msgstr "Costura à Direita" -# AI Translated msgid "Seam Enforced" -msgstr "Costura forçada" +msgstr "Costura Forçada" -# AI Translated msgid "Seam Blocked" -msgstr "Costura bloqueada" +msgstr "Costura Bloqueada" -# AI Translated msgid "Seam Neutral" -msgstr "Costura neutra" +msgstr "Costura Neutra" # AI Translated msgid "Choose precise seam subtype" @@ -3117,19 +3059,15 @@ msgstr "Recarregar Tudo" msgid "Reload all from disk" msgstr "Recarregar tudo do disco" -# AI Translated msgid "Fix All" msgstr "Corrigir Tudo" -# AI Translated msgid "Fix all models on the current plate" msgstr "Corrigir todos os modelos na placa atual" -# AI Translated msgid "Fix All Plates" msgstr "Corrigir Todas as Placas" -# AI Translated msgid "Fix all models on all plates" msgstr "Corrigir todos os modelos em todas as placas" @@ -3184,11 +3122,9 @@ msgstr "(Cor perdida)" msgid "Center" msgstr "Centralizar" -# AI Translated msgid "Align/Distribute" msgstr "Alinhar/Distribuir" -# AI Translated msgid "Align and distribute objects" msgstr "Alinhar e distribuir objetos" @@ -3282,7 +3218,6 @@ msgstr "Renomear Peça" msgid "Paste settings" msgstr "Colar configurações" -# AI Translated msgid "Shift objects to bed" msgstr "Deslocar objetos para a mesa" @@ -3387,7 +3322,6 @@ msgstr "Montagem" msgid "Merge parts to an object" msgstr "Mesclar peças com um objeto" -# AI Translated msgid "Using variable layer height together with mixed color sublayer may result in poor color mixing quality." msgstr "Usar altura de camada variável junto com a subcamada de cor mista pode resultar em uma mistura de cores de baixa qualidade." @@ -3448,9 +3382,8 @@ msgstr "Tipo:" msgid "Choose part type" msgstr "Escolha o tipo de peça" -# AI Translated msgid "Instances to Separated Objects" -msgstr "Instâncias para objetos separados" +msgstr "Instâncias para Objetos Separados" msgid "Enter new name" msgstr "Digite um novo nome" @@ -3468,7 +3401,6 @@ msgid_plural "Failed to repair the following model objects" msgstr[0] "Falha ao reparar o seguinte objeto modelo" msgstr[1] "Falha ao reparar os seguintes objetos modelo" -# AI Translated #, c-format, boost-format msgid "%1$d model object needed no repair." msgid_plural "%1$d model objects needed no repair." @@ -3714,7 +3646,6 @@ msgstr "Mudar Mesmo Assim" msgid "Off" msgstr "Desligado" -# AI Translated msgctxt "air_duct" msgid "Filter" msgstr "Filtro" @@ -3828,12 +3759,10 @@ msgstr "Confirmar extrusão" msgid "Check filament location" msgstr "Verificar localização do filamento" -# AI Translated msgctxt "Verb" msgid "Pause" msgstr "Pausar" -# AI Translated #. TRN Filament change step: the printer switches to the other extruder. msgid "Switch extruder" msgstr "Trocar extrusora" @@ -3846,7 +3775,6 @@ msgstr "Trocar hotend" msgid "Wait for AMS cooling" msgstr "Aguardar resfriamento do AMS" -# AI Translated msgid "Switch current filament at Filament Track Switch" msgstr "Trocar o filamento atual no Filament Track Switch" @@ -3854,22 +3782,18 @@ msgstr "Trocar o filamento atual no Filament Track Switch" msgid "Pull back current filament at Filament Track Switch" msgstr "Recuar o filamento atual no Filament Track Switch" -# AI Translated msgid "Switch track at Filament Track Switch" msgstr "Trocar de trilha no Filament Track Switch" -# AI Translated #. TRN AMS unit number, then slot number #, c-format, boost-format msgid "AMS-%d-%d Slot" msgstr "Espaço AMS-%d-%d" -# AI Translated #, c-format, boost-format msgid "The maximum temperature cannot exceed %d" msgstr "A temperatura máxima não pode exceder %d" -# AI Translated #, c-format, boost-format msgid "The minimum temperature should not be less than %d" msgstr "A temperatura mínima não pode ser menor do que %d" @@ -3972,7 +3896,6 @@ msgstr "Sua impressora tem diferentes bico instalados. Selecione um bico para e msgid "Ignore" msgstr "Ignorar" -# AI Translated msgid "unknown" msgstr "desconhecido" @@ -3999,7 +3922,6 @@ msgstr "" msgid "Arranging..." msgstr "Organizando…" -# AI Translated #, c-format, boost-format msgid "Object %s has zero size and can't be arranged." msgstr "O objeto %s tem tamanho zero e não pode ser organizado." @@ -4007,7 +3929,6 @@ msgstr "O objeto %s tem tamanho zero e não pode ser organizado." msgid "Arranging" msgstr "Organizando" -# AI Translated #. TRN Progress status. %1% is the name of the object being arranged. #, boost-format msgid "Arranging %1%" @@ -4050,7 +3971,6 @@ msgstr "" msgid "Orienting..." msgstr "Orientando…" -# AI Translated #. TRN Progress status. %1% is the name of the object being oriented. #, boost-format msgid "Orienting %1%" @@ -4062,7 +3982,6 @@ msgstr "Orientação cancelada." msgid "Filling" msgstr "Preenchendo" -# AI Translated #. TRN Progress status of Fill bed. %1% is the name of the object being copied. #, boost-format msgid "Filling %1%" @@ -4083,20 +4002,16 @@ msgstr "Busca de orientação cancelada." msgid "Orientation found." msgstr "Orientação encontrada." -# AI Translated msgid "Best surface quality" msgstr "Melhor qualidade de superfície" -# AI Translated msgid "Optimize object rotation for best surface quality." msgstr "Otimiza a rotação do objeto para a melhor qualidade de superfície." -# AI Translated # Needs human review: Option name in the Optimize Rotation menu (RotoptimizeJob); check it reads as a choice next to the other options. msgid "Reduced overhang slopes" msgstr "Inclinações de saliência reduzidas" -# AI Translated msgid "" "Optimize object rotation to have minimum amount of overhangs needing support structures.\n" "Note that this method will try to find the best surface of the object for touching the print bed if no elevation is set." @@ -4104,11 +4019,9 @@ msgstr "" "Otimiza a rotação do objeto para ter a mínima quantidade de saliências que precisam de estruturas de suporte.\n" "Observe que este método tentará encontrar a melhor superfície do objeto para tocar a mesa se nenhuma elevação estiver definida." -# AI Translated msgid "Lowest Z height" msgstr "Menor altura Z" -# AI Translated msgid "Rotate the model to have the lowest z height for faster print time." msgstr "Gira o modelo para obter a menor altura Z e um tempo de impressão menor." @@ -4224,14 +4137,12 @@ msgstr "O Armazenamento na impressora está anormal. Substitua-o por um Armazena msgid "The Storage in the printer is read-only. Please replace it with a normal Storage before sending to printer." msgstr "O Armazenamento na impressora é somente para leitura. Substitua-o por um Armazenamento normal antes de enviar para a impressora." -# AI Translated msgid "Can't create empty volume." msgstr "Não é possível criar um volume vazio." msgid "Bad input data for EmbossCreateObjectJob." msgstr "Dados de entrada inválidos para EmbossCreateObjectJob." -# AI Translated msgid "Can't create empty object." msgstr "Não é possível criar um objeto vazio." @@ -4250,11 +4161,9 @@ msgstr "Dados de entrada inválidos para CreateSurfaceVolumeJob." msgid "Bad input data for UseSurfaceJob." msgstr "Dados de entrada inválidos para UseSurfaceJob." -# AI Translated msgid "It is used default volume for embossed text, try to change text or font to fix it." msgstr "Foi usado o volume padrão para o texto em relevo; tente alterar o texto ou a fonte para corrigir isso." -# AI Translated msgid "Empty mesh can't be created." msgstr "Não é possível criar uma malha vazia." @@ -4263,7 +4172,6 @@ msgstr "Não é possível criar uma malha vazia." msgid "Emboss attribute change" msgstr "Alteração do atributo de relevo" -# AI Translated msgid "Bad object to create volume." msgstr "Objeto inválido para criar o volume." @@ -4362,7 +4270,6 @@ msgstr "Este software utiliza componentes open source cujos direitos autorais e msgid "About %s" msgstr "Sobre %s" -# AI Translated #. TRN %s is the commit the application was built from #, c-format, boost-format msgid "Build %s" @@ -4377,15 +4284,12 @@ msgstr "O OrcaSlicer começou com esse mesmo espírito, inspirando-se no PrusaSl msgid "Today, OrcaSlicer is the most widely used and actively developed open-source slicer in the 3D printing community. Many of its innovations have been adopted by other slicers, making it a driving force for the entire industry." msgstr "Atualmente, o OrcaSlicer é o fatiador de código aberto mais utilizado e ativamente desenvolvido na comunidade de impressão 3D. Muitas de suas inovações foram adotadas por outros fatiadores, tornando-o uma força motriz para toda a indústria." -# AI Translated msgid "Copyright(C) 2026 OrcaSlicer Pte Ltd All Rights Reserved" msgstr "Copyright(C) 2026 OrcaSlicer Pte Ltd Todos os direitos reservados" -# AI Translated msgid "Script plugin skipped." msgstr "Plugin de script ignorado." -# AI Translated msgid "Script plugin finished." msgstr "Plugin de script concluído." @@ -4462,11 +4366,9 @@ msgstr "Por favor insira um valor válido (K entre %.1f~%.1f)" msgid "Please input a valid value (K in %.1f~%.1f, N in %.1f~%.1f)" msgstr "Por favor insira um valor válido (K entre %.1f~%.1f, N entre %.1f~%.1f)" -# AI Translated msgid "Favorite filaments" msgstr "Filamentos favoritos" -# AI Translated msgid "All filaments" msgstr "Todos os filamentos" @@ -4607,22 +4509,18 @@ msgstr "AMS Direito" msgid "Printing with the current nozzle may produce an extra %0.2f g of waste." msgstr "Impressão com o bico atual pode produzir um desperdício extra de %0.2f g." -# AI Translated #, c-format, boost-format msgid "Tips: the filament type(%s) does not match with the filament type(%s) in the slicing file. If you want to use this slot, you can install %s instead of %s and change slot information on the 'Device' page." msgstr "Dicas: o tipo de filamento(%s) não corresponde ao tipo de filamento(%s) no arquivo de fatiamento. Se você quiser usar este slot, pode instalar %s em vez de %s e alterar as informações do slot na página 'Dispositivo'." -# AI Translated #, c-format, boost-format msgid "Cannot select: the filament type(%s) does not match with the filament type(%s) in the slicing file. If you want to use this slot, you can install %s instead of %s and change slot information on the 'Device' page." msgstr "Não é possível selecionar: o tipo de filamento(%s) não corresponde ao tipo de filamento(%s) no arquivo de fatiamento. Se você quiser usar este slot, pode instalar %s em vez de %s e alterar as informações do slot na página 'Dispositivo'." -# AI Translated #, c-format, boost-format msgid "Cannot select: the slot is empty or undefined. If you want to use this slot, you can install %s and change slot information on the 'Device' page." msgstr "Não é possível selecionar: o slot está vazio ou indefinido. Se você quiser usar este slot, pode instalar %s e alterar as informações do slot na página 'Dispositivo'." -# AI Translated msgid "Cannot select: No filament loaded in current slot." msgstr "Não é possível selecionar: nenhum filamento carregado no slot atual." @@ -4785,7 +4683,6 @@ msgstr "O plug-in de rede foi instalado, mas não pôde ser carregado. Reinicie msgid "Restart Required" msgstr "Reinicialização Necessária" -# AI Translated #. TRN %1% marks where the Home button icon is drawn; keep it in the translation. #, boost-format msgid "Please home all axes (click %1%) to locate the toolhead's position. This prevents device moving beyond the printable boundary and causing equipment wear." @@ -4804,7 +4701,6 @@ msgstr "Ocorreu um erro fatal: \"%1%\"" msgid "Please save your project and restart the application." msgstr "Por favor, salve seu projeto e reinicie a aplicação." -# AI Translated msgid "Unknown C++ exception." msgstr "Exceção C++ desconhecida." @@ -5010,16 +4906,13 @@ msgstr "A temperatura da câmara atual está mais alta do que a temperatura segu msgid "The minimal chamber temperature (%d℃) is higher than the target chamber temperature (%d℃). The minimal value is the threshold at which printing starts while the chamber keeps heating toward the target, so it should not exceed it. It will be clamped to the target." msgstr "A temperatura mínima da câmara (%d℃) é superior à temperatura alvo da câmara (%d℃). O valor mínimo é o limite no qual a impressão começa enquanto a câmara continua aquecendo em direção ao alvo; portanto, não deve execedê-lo. O valor será limitado ao alvo." -# AI Translated #, c-format, boost-format msgid "Layer height is too small. It will be set to the minimum (%g mm)." msgstr "A altura da camada é muito pequena. Ela será definida para o mínimo (%g mm)." -# AI Translated msgid "Layer height is outside the limits set in Printer Settings -> Extruder -> Layer height limits, this may cause printing quality issues." msgstr "A altura da camada está fora dos limites definidos em Configurações da Impressora -> Extrusora -> Limites de altura da camada, isso pode causar problemas de qualidade de impressão." -# AI Translated #, c-format, boost-format msgid "Adjust it to the limit (%g mm) automatically?" msgstr "Ajustar automaticamente para o limite (%g mm)?" @@ -6059,31 +5952,24 @@ msgstr "Aumentar/diminuir área de edição" msgid "Sequence" msgstr "Sequência" -# AI Translated msgid "Plate center of mass" msgstr "Centro de massa da placa" -# AI Translated msgid "Part center of mass" msgstr "Centro de massa da peça" -# AI Translated msgid "Support center of mass" msgstr "Centro de massa do suporte" -# AI Translated msgid "Assembly center of mass" msgstr "Centro de massa da montagem" -# AI Translated msgid "Object center of mass" msgstr "Centro de massa do objeto" -# AI Translated msgid "Finished print" msgstr "Impressão concluída" -# AI Translated #, boost-format msgid "Printed up to layer %1%" msgstr "Impresso até a camada %1%" @@ -6094,22 +5980,18 @@ msgstr "Peso" msgid "Volume" msgstr "Volume" -# AI Translated msgid "Center in bounding box" msgstr "Centro na caixa delimitadora" -# AI Translated msgid "Bounding box size" msgstr "Tamanho da caixa delimitadora" -# AI Translated msgid "Moment of inertia" msgstr "Momento de inércia" msgid "Object selection" msgstr "Seleção de objeto" -# AI Translated msgid "1~16 number keys" msgstr "1~16 teclas numéricas" @@ -6313,10 +6195,8 @@ msgstr "Eixos" msgid "Gridlines" msgstr "Linhas da Grade" -# AI Translated -# Needs human review: Glossary has no pt_BR rendering for Focus mode; context-menu item of the 3D canvas (plate switcher) msgid "Focus mode" -msgstr "Modo de foco" +msgstr "Modo focado" msgid "Labels" msgstr "Etiquetas" @@ -6884,9 +6764,8 @@ msgstr "Editar" msgid "View" msgstr "Visualizar" -# AI Translated msgid "Open Speed Dial" -msgstr "Abrir o Menu rápido" +msgstr "Abrir o Menu Rápido" msgid "Preset Bundle" msgstr "Pacote de Predefinições" @@ -7241,7 +7120,7 @@ msgid "Failed to parse model information." msgstr "Falha ao processar a informação do modelo." msgid "The .gcode.3mf file contains no G-code data. Please slice it with Orca Slicer and export a new .gcode.3mf file." -msgstr "O arquivo .gcode.3mf não contém dados de G-code. Por favor, fatie com Orca Slicer e exporte um novo arquivo .gcode.3mf." +msgstr "O arquivo .gcode.3mf não contém dados de G-code. Por favor, fatie com OrcaSlicer e exporte um novo arquivo .gcode.3mf." #, c-format, boost-format msgid "File '%s' was lost! Please download it again." @@ -9709,8 +9588,6 @@ msgstr "Europa" msgid "North America" msgstr "América do Norte" -# AI Translated -# Needs human review: Region dropdown in Preferences (after Asia-Pacific, China, Europe, North America): feminine 'Outras' agrees with 'regiões'; the generic 'Others' in the catalog is 'Outros'. msgctxt "Region" msgid "Others" msgstr "Outras" @@ -10012,32 +9889,25 @@ msgstr "Gerenciamento de multi dispositivos" msgid "With this option enabled, you can send a task to multiple devices at the same time and manage multiple devices." msgstr "Com esta opção habilitada, você pode enviar uma tarefa para vários dispositivos ao mesmo tempo e gerenciar vários dispositivos." -# AI Translated msgid "Open the Speed Dial from the keyboard" -msgstr "Abrir o Menu rápido pelo teclado" +msgstr "Abrir o Menu Rápido pelo teclado" -# AI Translated msgid "When enabled, the Speed Dial keyboard shortcut (Space by default) opens the action search from any page." -msgstr "Quando ativado, o atalho de teclado do Menu rápido (Espaço por padrão) abre a busca de ações em qualquer página." +msgstr "Quando ativado, o atalho de teclado do Menu Rápido (Espaço por padrão) abre a busca de ações em qualquer página." -# AI Translated msgid "Recent actions" msgstr "Ações recentes" -# AI Translated #. TRN Unit shown after the number of recent actions, as in "5 actions". msgid "actions" msgstr "ações" -# AI Translated msgid "How many recently launched actions to show at the top of the Speed Dial. Set to 0 to hide recent actions." -msgstr "Quantas ações executadas recentemente mostrar no topo do Menu rápido. Defina como 0 para ocultar as ações recentes." +msgstr "Quantas ações executadas recentemente mostrar no topo do Menu Rápido. Defina como 0 para ocultar as ações recentes." -# AI Translated msgid "CAD feature (experimental)" msgstr "Recurso CAD (experimental)" -# AI Translated msgid "With this option enabled, the Design tab is shown, where models can be built and edited parametrically. This feature is experimental and still under development." msgstr "Com esta opção ativada, a aba Design é exibida, onde os modelos podem ser criados e editados parametricamente. Este recurso é experimental e ainda está em desenvolvimento." @@ -12994,10 +12864,10 @@ msgid "Custom" msgstr "Personalizado" msgid "Welcome to Orca Slicer" -msgstr "Bem-vindo ao Orca Slicer" +msgstr "Bem-vindo ao OrcaSlicer" msgid "Orca Slicer will be set up in several steps. Let's start!" -msgstr "Orca Slicer será configurado em várias etapas. Vamos começar!" +msgstr "O OrcaSlicer será configurado em várias etapas. Vamos começar!" msgid "Get Started" msgstr "Vamos Começar" @@ -13286,7 +13156,7 @@ msgid "Network plug-in update" msgstr "Atualização do plug-in de rede" msgid "Click OK to update the Network plug-in now. If a file is in use, the update will be applied the next time Orca Slicer launches." -msgstr "Clique em OK para atualizar o plug-in de Rede agora. Se um arquivo estiver em uso, a atualização será aplicada na próxima vez que o Orca Slicer for iniciado." +msgstr "Clique em OK para atualizar o plug-in de Rede agora. Se um arquivo estiver em uso, a atualização será aplicada na próxima vez que o OrcaSlicer for iniciado." msgid "A new Network plug-in is available. Do you want to install it?" msgstr "Um novo plug-in de Rede está disponível. Deseja instalá-lo?" @@ -19085,44 +18955,32 @@ msgstr "Ângulo de inclinação do referencial da máquina" msgid "Tilt angle (degrees) used to derive the machine-frame shear (cot) and scale (1/|sin|) applied to G-code. Only used when 'Decouple machine-frame tilt' is enabled; otherwise the belt tilt angle is used." msgstr "Ângulo de inclinação (graus) usado para derivar o cisalhamento (cot) e a escala (1/|sin|) do referencial da máquina aplicados ao G-code. Usado somente quando 'Desacoplar a inclinação do referencial da máquina' está ativado; caso contrário, é usado o ângulo de inclinação da esteira." -# AI Translated msgid "+X" msgstr "+X" -# AI Translated msgid "+Y" msgstr "+Y" -# AI Translated msgid "+Z" msgstr "+Z" -# AI Translated msgid "-X" msgstr "-X" -# AI Translated msgid "-Y" msgstr "-Y" -# AI Translated msgid "-Z" msgstr "-Z" -# AI Translated -# Needs human review: Dropdown option of the belt G-code remap: 'Rev' is the reversed axis (max - position), distinct from the negated '-X' next to it; check the two read as different options. msgid "Rev X" -msgstr "X invertido" +msgstr "X reverso" -# AI Translated -# Needs human review: Dropdown option of the belt G-code remap: 'Rev' is the reversed axis (max - position), distinct from the negated '-Y' next to it; check the two read as different options. msgid "Rev Y" -msgstr "Y invertido" +msgstr "Y reverso" -# AI Translated -# Needs human review: Dropdown option of the belt G-code remap: 'Rev' is the reversed axis (max - position), distinct from the negated '-Z' next to it; check the two read as different options. msgid "Rev Z" -msgstr "Z invertido" +msgstr "Z reverso" # AI Translated msgid "G-code remap X" @@ -20271,8 +20129,7 @@ msgstr "Na zona de detecção de enrolamento da cabeça da ferramenta" msgid "Indicates if the first layer overlaps with the head wrap zone." msgstr "Indica se a primeira camada se sobrepõe à zona de enrolamento da cabeça da ferramenta." -# AI Translated -# Needs human review: Glossary says Bed = Mesa, but the catalog's established label 'Bed type' is 'Tipo de placa'; kept that wording so the placeholder matches the setting name. +# Glossary says Bed = Mesa, but the catalog's established label 'Bed type' is 'Tipo de placa'; kept that wording so the placeholder matches the setting name. msgid "Current bed type" msgstr "Tipo de placa atual" @@ -21180,11 +21037,11 @@ msgstr "A duplicação deste tipo de variável vetorial não é suportada" # AI Translated msgid "parameter of empty() is not a vector variable" -msgstr "O parâmetro de empty() não é uma variável vetorial" +msgstr "o parâmetro de empty() não é uma variável vetorial" # AI Translated msgid "parameter of size() is not a vector variable" -msgstr "O parâmetro de size() não é uma variável vetorial" +msgstr "o parâmetro de size() não é uma variável vetorial" # AI Translated msgid "Non-integer index is not allowed to address a vector variable." @@ -23547,8 +23404,6 @@ msgstr "Falha na Impressão" msgid "Printing Pause" msgstr "Pausa de Impressão" -# AI Translated -# Needs human review: Printer device status list in the multi-machine view (Idle, Printing, Prepare...); check the gerund reads right next to the other statuses. msgctxt "Device status" msgid "Prepare" msgstr "Preparando" @@ -24022,36 +23877,27 @@ msgstr "Se ativado, os valores acima são armazenados como os padrões usados pa msgid "PresetBundle" msgstr "PresetBundle" -# AI Translated msgid "Export Presets" msgstr "Exportar Predefinições" -# AI Translated msgid "Show in folder" msgstr "Mostrar na pasta" -# AI Translated msgid "Delete bundle" msgstr "Excluir pacote" -# AI Translated msgid "Unsubscribe bundle" -msgstr "Cancelar inscrição do pacote" +msgstr "Desinscrever do pacote" -# AI Translated msgid "Update available" msgstr "Atualização disponível" -# AI Translated msgid "Unauthorized bundle" msgstr "Pacote não autorizado" -# AI Translated msgid "Open this bundle in your browser" msgstr "Abrir este pacote no seu navegador" -# AI Translated -# Needs human review: Shared label: the type of a preset bundle (Preset Bundle dialog) and the source of a plugin (Plugins dialog); check the masculine singular fits both columns. msgid "Subscribed" msgstr "Inscrito" @@ -24078,16 +23924,16 @@ msgid "Remove Bundle" msgstr "Remover pacote" msgid "Unsubscribe bundle?" -msgstr "Cancelar a inscrição do pacote?" +msgstr "Desinscrever do pacote?" msgid "UnsubscribeBundle" msgstr "UnsubscribeBundle" msgid "Failed to unsubscribe bundle." -msgstr "Falha ao cancelar a inscrição do pacote." +msgstr "Falha ao desinscrever do pacote." msgid "Unsubscribe Bundle" -msgstr "Cancelar inscrição do Pacote" +msgstr "Desinscrever do Pacote" msgid "ExportPresetBundle" msgstr "ExportPresetBundle" @@ -26532,36 +26378,29 @@ msgstr "Posicionamento: A e B devem ser sistemas de coordenadas diferentes" msgid "Mate rejected" msgstr "Posicionamento rejeitado" -# AI Translated msgid "Interference needs at least two bodies" msgstr "A verificação de interferência precisa de pelo menos dois corpos" -# AI Translated msgid "No interference found" msgstr "Nenhuma interferência encontrada" -# AI Translated #, c-format, boost-format msgid "Body %d" msgstr "Corpo %d" -# AI Translated #, c-format, boost-format msgid "%s ↔ %s %.2f mm³" msgstr "%s ↔ %s %.2f mm³" -# AI Translated #, c-format msgid "%zu overlapping pair: %s" msgid_plural "%zu overlapping pairs: %s" msgstr[0] "%zu par de corpos sobrepostos: %s" msgstr[1] "%zu pares de corpos sobrepostos: %s" -# AI Translated msgid "Select a body to measure it" msgstr "Selecione um corpo para medi-lo" -# AI Translated msgid "This body could not be measured" msgstr "Não foi possível medir este corpo" @@ -26570,7 +26409,6 @@ msgstr "Não foi possível medir este corpo" msgid "%s: sheet body, area %.2f mm², no volume — thicken it to get one" msgstr "%s: corpo de superfície, área %.2f mm², sem volume — espesse-o para obter um" -# AI Translated #, c-format, boost-format msgid "%s: volume %.2f mm³, area %.2f mm²" msgstr "%s: volume %.2f mm³, área %.2f mm²" @@ -26587,12 +26425,10 @@ msgstr "A operação booleana precisa de dois corpos — adicione ou importe um msgid "Cut needs a solid body — add or import one first" msgstr "O corte precisa de um corpo sólido — adicione ou importe um primeiro" -# AI Translated #, c-format, boost-format msgid "Picked face (Body %d)" msgstr "Face selecionada (Corpo %d)" -# AI Translated msgid "Picked face" msgstr "Face selecionada" @@ -26604,11 +26440,9 @@ msgstr "não foi possível unir a nova forma ao corpo" msgid "the new shape could not be cut from the body" msgstr "não foi possível subtrair a nova forma do corpo" -# AI Translated msgid "the shapes could not be intersected" msgstr "não foi possível intersectar as formas" -# AI Translated msgid "nothing in the history makes a solid yet" msgstr "nada no histórico produz um sólido ainda" @@ -26616,7 +26450,6 @@ msgstr "nada no histórico produz um sólido ainda" msgid "the sketch profile is not a clean closed loop" msgstr "o perfil do esboço não é um laço fechado válido" -# AI Translated msgid "the tool does not touch the body" msgstr "a ferramenta não toca o corpo" @@ -26624,19 +26457,16 @@ msgstr "a ferramenta não toca o corpo" msgid "an expression uses a variable that does not exist" msgstr "uma expressão usa uma variável que não existe" -# AI Translated msgid "an expression divides by zero" msgstr "uma expressão divide por zero" -# AI Translated msgid "two variables are defined in terms of each other" -msgstr "duas variáveis são definidas uma em função da outra" +msgstr "duas variáveis são definidas uma em função uma da outra" # AI Translated msgid "a geometry operation failed" msgstr "uma operação geométrica falhou" -# AI Translated #. TRN Appended to a sketch tool prompt; %d is the number of picked entities. #, c-format, boost-format msgid " · %d picked" @@ -28748,25 +28578,21 @@ msgstr "Alternar entre Preparar/Pré-visualizar" msgid "Collapse/Expand the sidebar" msgstr "Recolher/Expandir a barra lateral" -# AI Translated msgid "Reload the device page" msgstr "Recarregar a página do dispositivo" msgid "Show keyboard shortcuts list" msgstr "Mostrar lista de atalhos de teclado" -# AI Translated msgid "Open the Speed Dial" -msgstr "Abrir o Menu rápido" +msgstr "Abrir o Menu Rápido" -# AI Translated msgid "Slicing and printing" msgstr "Fatiamento e impressão" msgid "Editing" msgstr "Edição" -# AI Translated msgid "Placement" msgstr "Colocação" @@ -28774,82 +28600,65 @@ msgstr "Colocação" msgid "Gizmos" msgstr "Gizmos" -# AI Translated msgid "Sliders" msgstr "Controles deslizantes" -# AI Translated msgid "Painting tools" msgstr "Ferramentas de pintura" msgid "Application" msgstr "Aplicação" -# AI Translated msgid "Speed Dial" -msgstr "Menu rápido" +msgstr "Menu Rápido" -# AI Translated msgid "helix radius must be > 0" -msgstr "o raio da hélice deve ser > 0" +msgstr "raio da hélice deve ser > 0" -# AI Translated msgid "helix pitch must be > 0" -msgstr "o passo da hélice deve ser > 0" +msgstr "passo da hélice deve ser > 0" -# AI Translated msgid "helix height must be >= 0" -msgstr "a altura da hélice deve ser >= 0" +msgstr "altura da hélice deve ser >= 0" -# AI Translated msgid "helix height of 0 (flat spiral) is not supported" msgstr "altura de hélice 0 (espiral plana) não é suportada" -# AI Translated msgid "helix turn count exceeds limit (10000)" -msgstr "o número de voltas da hélice excede o limite (10000)" +msgstr "número de voltas da hélice excede o limite (10000)" # AI Translated msgid "helix taper drives radius negative before reaching height" msgstr "a conicidade da hélice torna o raio negativo antes de atingir a altura" -# AI Translated msgid "bad character in expression" msgstr "caractere inválido na expressão" -# AI Translated msgid "mismatched parentheses" msgstr "parênteses não correspondentes" -# AI Translated #, boost-format msgid "unknown identifier: %1%" msgstr "identificador desconhecido: %1%" -# AI Translated msgid "missing operand for unary minus" msgstr "operando ausente para o menos unário" -# AI Translated #, boost-format msgid "not enough operands for '%1%'" msgstr "operandos insuficientes para '%1%'" -# AI Translated msgid "division by zero" msgstr "divisão por zero" -# AI Translated #, boost-format msgid "not enough arguments for %1%()" msgstr "argumentos insuficientes para %1%()" -# AI Translated #, boost-format msgid "unknown function: %1%" msgstr "função desconhecida: %1%" -# AI Translated msgid "invalid expression" msgstr "expressão inválida" @@ -28858,7 +28667,6 @@ msgstr "expressão inválida" msgid "variable cycle: %1%" msgstr "ciclo de variáveis: %1%" -# AI Translated #, boost-format msgid "unknown parameter: %1%" msgstr "parâmetro desconhecido: %1%" @@ -29640,8 +29448,6 @@ msgstr "Verde" msgid "Blue" msgstr "Azul" -# AI Translated -# Needs human review: Reordered to filament type then color (e.g. 'PLA Basic Ciano') as Portuguese adjectives follow the noun; check it reads right in the color list. #. TRN %1% is a color name such as "Cyan", %2% is a filament type such as "PLA Basic" #, boost-format msgctxt "Color and filament type" @@ -29782,8 +29588,6 @@ msgstr "Rosa nebuloso" msgid "Light yellow" msgstr "Amarelo claro" -# AI Translated -# Needs human review: Color name of uncertain Portuguese rendering; check the shade it names msgid "Lemon chiffon" msgstr "Chiffon limão" @@ -30741,22 +30545,18 @@ msgstr "Azul pombo" msgid "Traffic blue" msgstr "Azul trânsito" -# AI Translated msgid "Turquoise blue" msgstr "Azul turquesa" -# AI Translated msgid "Capri blue" msgstr "Azul Capri" msgid "Ocean blue" msgstr "Azul marinho" -# AI Translated msgid "Water blue" msgstr "Azul água" -# AI Translated msgid "Night blue" msgstr "Azul noite" @@ -30928,11 +30728,9 @@ msgstr "Cinza ferro" msgid "Basalt grey" msgstr "Cinza basalto" -# AI Translated msgid "Brown grey" msgstr "Cinza marrom" -# AI Translated msgid "Slate grey" msgstr "Cinza ardósia" @@ -30940,36 +30738,27 @@ msgstr "Cinza ardósia" msgid "Anthracite grey" msgstr "Cinza antracite" -# AI Translated msgid "Light grey" msgstr "Cinza claro" -# AI Translated -# Needs human review: Color name of uncertain Portuguese rendering; check the shade it names msgid "Umber grey" msgstr "Cinza umbra" -# AI Translated msgid "Concrete grey" msgstr "Cinza concreto" -# AI Translated msgid "Graphite grey" msgstr "Cinza grafite" -# AI Translated msgid "Granite grey" msgstr "Cinza granito" -# AI Translated msgid "Stone grey" msgstr "Cinza pedra" -# AI Translated msgid "Pebble grey" msgstr "Cinza seixo" -# AI Translated msgid "Cement grey" msgstr "Cinza cimento" @@ -30977,19 +30766,15 @@ msgstr "Cinza cimento" msgid "Yellow grey" msgstr "Cinza amarelo" -# AI Translated msgid "Platinum grey" msgstr "Cinza platina" -# AI Translated msgid "Dusty grey" msgstr "Cinza poeira" -# AI Translated msgid "Agate grey" msgstr "Cinza ágata" -# AI Translated msgid "Quartz grey" msgstr "Cinza quartzo" @@ -31015,10 +30800,12 @@ msgid "Telegrey 1" msgstr "Telecinza 1" # AI Translated +# Needs human review: Color name of uncertain Portuguese rendering; check the shade it names msgid "Telegrey 2" msgstr "Telecinza 2" # AI Translated +# Needs human review: Color name of uncertain Portuguese rendering; check the shade it names msgid "Telegrey 4" msgstr "Telecinza 4" @@ -32020,13 +31807,9 @@ msgstr "Mapeada pelo layout UV do próprio modelo, que já é o posicionamento - msgid "How wide one copy of the texture is on the model. Smaller repeats the pattern more often and makes its detail finer; with Tile off, this is the size of the single copy." msgstr "Largura de uma cópia da textura no modelo. Valores menores repetem o padrão mais vezes e deixam seus detalhes mais finos; com Ladrilho desativado, este é o tamanho da cópia única." -# AI Translated -# Needs human review: Caption under an image comparing tile sizes in the texture gizmo; check plural/gender fits what is shown msgid "Larger" msgstr "Maiores" -# AI Translated -# Needs human review: Caption under an image comparing tile sizes in the texture gizmo; check plural/gender fits what is shown msgid "Smaller" msgstr "Menores" @@ -32096,7 +31879,6 @@ msgstr "Misturar filamentos" msgid "Interleaves two filaments to fake the colors in between, so a handful of filaments can cover a photo or a gradient. An image of flat colors prints the same either way. Off uses one filament per area." msgstr "Intercala dois filamentos para simular as cores intermediárias, de modo que poucos filamentos consigam cobrir uma foto ou um degradê. Uma imagem de cores chapadas é impressa da mesma forma em ambos os casos. Desativado, usa um filamento por área." -# AI Translated msgid "Mixed colors" msgstr "Cores mistas" @@ -32104,13 +31886,9 @@ msgstr "Cores mistas" msgid "The most mixed filaments a bake may add. They are picked from the texture's colors, and only the ones the bake actually uses are created." msgstr "O número máximo de filamentos mistos que um assamento pode adicionar. Eles são escolhidos a partir das cores da textura, e somente os que o assamento realmente usa são criados." -# AI Translated -# Needs human review: Caption of the mixed-colors illustration; check gender fits (cores) msgid "Few" msgstr "Poucas" -# AI Translated -# Needs human review: Caption of the mixed-colors illustration; check gender fits (cores) msgid "Many" msgstr "Muitas" @@ -32893,9 +32671,8 @@ msgstr "A interface de configuração do plugin não pôde ser carregada (%1%). msgid "Delete Plugin" msgstr "Excluir Plugin" -# AI Translated msgid "Unsubscribe" -msgstr "Cancelar inscrição" +msgstr "Desinscrever" # AI Translated msgid "Overwrite Plugin" @@ -33377,39 +33154,32 @@ msgstr "\"%s\" excluído." msgid "Deleting plugin" msgstr "Excluindo plugin" -# AI Translated msgid "Deleting plugin..." msgstr "Excluindo plugin..." -# AI Translated #, c-format, boost-format msgid "" "Unsubscribe plugin \"%s\"?\n" "\n" "This will stop tracking the plugin and delete any local plugin files." msgstr "" -"Cancelar a inscrição do plugin \"%s\"?\n" +"Desinscrever do plugin \"%s\"?\n" "\n" "Isso deixará de acompanhar o plugin e excluirá todos os arquivos locais do plugin." -# AI Translated msgid "Failed to unsubscribe plugin." -msgstr "Falha ao cancelar a inscrição do plugin." +msgstr "Falha ao desinscrever do plugin." -# AI Translated #, c-format, boost-format msgid "Unsubscribed \"%s\"." msgstr "Inscrição de \"%s\" cancelada." -# AI Translated msgid "Unsubscribing plugin" -msgstr "Cancelando a inscrição do plugin" +msgstr "Desinscrevendo do plugin" -# AI Translated msgid "Deleting local files and unsubscribing plugin..." -msgstr "Excluindo arquivos locais e cancelando a inscrição do plugin..." +msgstr "Excluindo arquivos locais e desinscrevendo do plugin..." -# AI Translated msgid "Plugin not found." msgstr "Plugin não encontrado." @@ -33951,8 +33721,6 @@ msgstr "Pressione Desdobrar primeiro - ainda não há ilhas para trabalhar." msgid "Click an island on the canvas first, in Island mode." msgstr "Primeiro clique em uma ilha na tela, no modo Ilha." -# AI Translated -# Needs human review: Short badge for a published project (about three letters); kept as PUB, abbreviation of 'Publicado'. Check it fits the badge. #. TRN Short badge on a recent project that was published (a published 3MF). Keep it about three letters long. msgid "PUB" msgstr "PUB" @@ -34320,11 +34088,9 @@ msgstr "Falha na instalação do plugin: %1%" msgid "%1%: installed plugin was not found in the catalog." msgstr "%1%: o plugin instalado não foi encontrado no catálogo." -# AI Translated msgid "Cloud plugin key is missing UUID." msgstr "A chave do plugin na nuvem não tem UUID." -# AI Translated msgid "Failed to subscribe to cloud plugin, see logs for more info." msgstr "Falha ao se inscrever no plugin na nuvem; consulte os logs para mais informações." @@ -34332,9 +34098,8 @@ msgstr "Falha ao se inscrever no plugin na nuvem; consulte os logs para mais inf msgid "Only cloud plugins can be unsubscribed." msgstr "Somente plugins na nuvem podem ter a inscrição cancelada." -# AI Translated msgid "Failed to unsubscribe plugin, see logs for more info." -msgstr "Falha ao cancelar a inscrição do plugin; consulte os logs para mais informações." +msgstr "Falha ao desinscrever do plugin; consulte os logs para mais informações." # AI Translated #. TRN %1% is the numeric result code returned by the cloud service. @@ -34657,23 +34422,18 @@ msgstr "Não é possível manter o plugin local: a chave de plugin local já exi msgid "Failed to update plugin install state: %1%" msgstr "Falha ao atualizar o estado de instalação do plugin: %1%" -# AI Translated msgid "Cannot unsubscribe your own plugins." -msgstr "Não é possível cancelar a inscrição dos seus próprios plugins." +msgstr "Não é possível desinscrever dos seus próprios plugins." -# AI Translated msgid "Only cloud plugins can be deleted and unsubscribed." msgstr "Somente plugins na nuvem podem ser excluídos e ter a inscrição cancelada." -# AI Translated msgid "Cannot unsubscribe your own plugins. Use Delete to remove the local files." -msgstr "Não é possível cancelar a inscrição dos seus próprios plugins. Use Excluir para remover os arquivos locais." +msgstr "Não é possível desinscrever dos seus próprios plugins. Use Excluir para remover os arquivos locais." -# AI Translated msgid "Plugin filesystem read permission request denied" msgstr "Solicitação de permissão de leitura do sistema de arquivos pelo plugin negada" -# AI Translated msgid "Profile has fewer than 2 points" msgstr "O perfil tem menos de 2 pontos" @@ -34681,15 +34441,12 @@ msgstr "O perfil tem menos de 2 pontos" msgid "Failed to build wire from profile" msgstr "Falha ao construir o contorno a partir do perfil" -# AI Translated msgid "extrude depth is zero" msgstr "a profundidade de extrusão é zero" -# AI Translated msgid "extrude failed" msgstr "falha na extrusão" -# AI Translated msgid "Fuse failed" msgstr "Falha na fusão" @@ -34697,19 +34454,15 @@ msgstr "Falha na fusão" msgid "Failed to make face from wire" msgstr "Falha ao criar a face a partir do contorno" -# AI Translated msgid "two-sided extrude fuse failed" msgstr "falha na fusão da extrusão de dois lados" -# AI Translated msgid "imported regions produced no extrudable geometry" msgstr "as regiões importadas não produziram geometria extrudável" -# AI Translated msgid "the profile crosses the revolve axis — it must lie on one side of it" msgstr "o perfil cruza o eixo de revolução — ele deve ficar de um lado do eixo" -# AI Translated msgid "Failed to revolve" msgstr "Falha na revolução" @@ -34737,201 +34490,157 @@ msgstr "o loft não produziu sólido" msgid "loft produced no shape" msgstr "o loft não produziu forma" -# AI Translated msgid "Pocket face failed" msgstr "Falha na face da cavidade" -# AI Translated msgid "Pocket cut failed" msgstr "Falha no corte da cavidade" -# AI Translated msgid "the profile crosses or folds back on itself, so it does not bound one region" msgstr "o perfil se cruza ou se dobra sobre si mesmo, então não delimita uma única região" -# AI Translated msgid "sketch has no closed loop" msgstr "o esboço não tem laço fechado" -# AI Translated msgid "sketch loop does not bound a face" msgstr "o laço do esboço não delimita uma face" -# AI Translated msgid "sketch has two disjoint regions; put each in its own sketch" msgstr "o esboço tem duas regiões separadas; coloque cada uma em seu próprio esboço" -# AI Translated msgid "cannot read STEP file" msgstr "não é possível ler o arquivo STEP" -# AI Translated msgid "STEP file has no geometry" msgstr "o arquivo STEP não tem geometria" -# AI Translated msgid "OCCT failed to read STEP" msgstr "o OCCT não conseguiu ler o STEP" -# AI Translated msgid "mesh_to_brep: mesh has no triangles" msgstr "mesh_to_brep: a malha não tem triângulos" -# AI Translated msgid "mesh_to_brep: every triangle was rejected as degenerate (try a smaller tolerance)" msgstr "mesh_to_brep: todos os triângulos foram rejeitados como degenerados (tente uma tolerância menor)" -# AI Translated msgid "the fillet radius must be greater than 0" msgstr "o raio do filete deve ser maior que 0" -# AI Translated msgid "no edges to fillet in that group" msgstr "nenhuma aresta para filetar nesse grupo" -# AI Translated msgid "fillet radius too large for this geometry" msgstr "raio do filete grande demais para esta geometria" -# AI Translated msgid "the chamfer distance must be greater than 0" msgstr "a distância do chanfro deve ser maior que 0" -# AI Translated msgid "no edges to chamfer in that group" msgstr "nenhuma aresta para chanfrar nesse grupo" -# AI Translated msgid "chamfer distance too large for this geometry" msgstr "distância do chanfro grande demais para esta geometria" -# AI Translated msgid "apply_fillet: OCCT fillet failed" msgstr "apply_fillet: falha no filete do OCCT" -# AI Translated msgid "apply_chamfer: OCCT chamfer failed" msgstr "apply_chamfer: falha no chanfro do OCCT" -# AI Translated msgid "empty component list" msgstr "lista de componentes vazia" -# AI Translated msgid "empty component index" msgstr "índice de componente vazio" -# AI Translated #, boost-format msgid "component index must be >= 1 (got %1%)" msgstr "o índice do componente deve ser >= 1 (recebido %1%)" -# AI Translated #, boost-format msgid "invalid component index \"%1%\"" msgstr "índice de componente inválido \"%1%\"" -# AI Translated #, boost-format msgid "at least 2 components required (got %1%)" msgstr "são necessários pelo menos 2 componentes (recebido %1%)" -# AI Translated #, boost-format msgid "duplicate component index %1%" msgstr "índice de componente duplicado %1%" -# AI Translated msgid "empty ratio value" msgstr "valor de proporção vazio" -# AI Translated #, boost-format msgid "ratio must be positive (got %1%)" msgstr "a proporção deve ser positiva (recebido %1%)" -# AI Translated #, boost-format msgid "invalid ratio \"%1%\"" msgstr "proporção inválida \"%1%\"" -# AI Translated #. TRN %1% is the expected number of ratios, %2% the number found. #, boost-format msgid "the ratio count must match the component count: expected %1%, got %2%" msgstr "a quantidade de proporções deve corresponder à quantidade de componentes: esperado %1%, recebido %2%" -# AI Translated msgid "expected two comma-separated floats, e.g. \"0.10,0.90\"" msgstr "esperados dois floats separados por vírgula, por exemplo \"0.10,0.90\"" -# AI Translated msgid "start and end ratios must be in (0, 1)" msgstr "as proporções inicial e final devem estar em (0, 1)" -# AI Translated #, boost-format msgid "array size %1% does not match filament slot count %2%" msgstr "o tamanho do array %1% não corresponde à quantidade de espaços de filamento %2%" -# AI Translated msgid "must be set when mixed filament parameters are specified" msgstr "deve ser definido quando parâmetros de filamento misto são especificados" -# AI Translated #. TRN Mixed filament validation error. %1% is the filament slot number, %2% the reason. #, boost-format msgid "slot %1%: %2%" msgstr "espaço %1%: %2%" -# AI Translated #, boost-format msgid "slot %1%: component %2% out of range (max physical filament index is %3%)" msgstr "espaço %1%: componente %2% fora do intervalo (o índice máximo de filamento físico é %3%)" -# AI Translated #, boost-format msgid "slot %1%: cannot reference itself as a component" msgstr "espaço %1%: não pode referenciar a si mesmo como componente" -# AI Translated #, boost-format msgid "slot %1%: component %2% references a mixed filament slot" msgstr "espaço %1%: o componente %2% referencia um espaço de filamento misto" -# AI Translated #, boost-format msgid "slot %1%: gradient requires exactly 2 components" -msgstr "espaço %1%: o degradê exige exatamente 2 componentes" +msgstr "espaço %1%: o degradê requer exatamente 2 componentes" -# AI Translated #, boost-format msgid "slot %1%: invalid curve (need at least 2 valid control points)" msgstr "espaço %1%: curva inválida (são necessários pelo menos 2 pontos de controle válidos)" -# AI Translated #, boost-format msgid "Failed loading configuration file \"%1%\": %2%" msgstr "Falha ao carregar o arquivo de configuração \"%1%\": %2%" -# AI Translated #. TRN %1% is the application name. #, boost-format msgid "Not a G-code file generated by %1%." msgstr "Não é um arquivo G-code gerado pelo %1%." -# AI Translated #. TRN %1% is a tag in the G-code file that must not be translated. #, boost-format msgid "Config tag \"%1%\" not found" msgstr "Tag de configuração \"%1%\" não encontrada" -# AI Translated #, boost-format msgid "Suspiciously low number of configuration values extracted from %1%: %2%" msgstr "Número suspeitamente baixo de valores de configuração extraídos de %1%: %2%" -# AI Translated msgid "" "Load step file failed.\n" "Cannot open file for reading.\n" @@ -34939,68 +34648,53 @@ msgstr "" "Falha ao carregar o arquivo STEP.\n" "Não foi possível abrir o arquivo para leitura.\n" -# AI Translated msgid "import svg failed: could not open svg." -msgstr "falha ao importar o svg: não foi possível abrir o svg." +msgstr "falha ao importar o SVG: não foi possível abrir o SVG." -# AI Translated msgid "import svg failed: could not parse imported svg data." -msgstr "falha ao importar o svg: não foi possível analisar os dados do svg importado." +msgstr "falha ao importar o SVG: não foi possível analisar os dados do SVG importado." -# AI Translated msgid "Custom G-code reports negative z_retracted." msgstr "O G-code personalizado informa z_retracted negativo." -# AI Translated msgid "Custom G-code reports negative z_restart_extra." msgstr "O G-code personalizado informa z_restart_extra negativo." -# AI Translated #, boost-format msgid "Copying directory %1% to %2% failed: %3%" msgstr "Falha ao copiar o diretório %1% para %2%: %3%" -# AI Translated msgid "Authentication complete" msgstr "Autenticação concluída" -# AI Translated msgid "Authentication failed" msgstr "Falha na autenticação" -# AI Translated msgid "You can return to OrcaSlicer. This window will close automatically." msgstr "Você pode voltar ao OrcaSlicer. Esta janela será fechada automaticamente." -# AI Translated msgid "Something went wrong. Please return to OrcaSlicer and try again." msgstr "Algo deu errado. Volte ao OrcaSlicer e tente novamente." -# AI Translated msgid "You can return to OrcaSlicer. If your browser does not redirect automatically, use the button below." msgstr "Você pode voltar ao OrcaSlicer. Se o seu navegador não redirecionar automaticamente, use o botão abaixo." -# AI Translated #, boost-format msgid "Failed starting the script %1%, Win32 error: %2%" msgstr "Falha ao iniciar o script %1%, erro Win32: %2%" -# AI Translated #, boost-format msgid "Post processing script %1% on file %2% failed. CommandLineToArgvW() refused to parse the command line path." msgstr "O script de pós-processamento %1% no arquivo %2% falhou. CommandLineToArgvW() se recusou a analisar o caminho da linha de comando." -# AI Translated #, boost-format msgid "The configured post-processing script does not exist: %1%" msgstr "O script de pós-processamento configurado não existe: %1%" -# AI Translated #, boost-format msgid "Perl interpreter %1% does not exist." msgstr "O interpretador Perl %1% não existe." -# AI Translated #, boost-format msgid "" "Post-processing plugin %1% raised an exception.\n" @@ -35009,7 +34703,6 @@ msgstr "" "O plugin de pós-processamento %1% gerou uma exceção.\n" "Erro: %2%" -# AI Translated #, boost-format msgid "" "Post-processing plugin %1% failed.\n" @@ -35302,8 +34995,7 @@ msgstr "" "Divida suas impressões em placas\n" "Você sabia que pode dividir um modelo que tem diversas peças em placas individuais distintas prontas para imprimir? Isso simplifica o processo de manter o controle de todas as peças." -#: resources/data/hints.ini: [hint:Speed up your print with Adaptive Layer -#: Height] +#: resources/data/hints.ini: [hint:Speed up your print with Adaptive Layer Height] msgid "" "Speed up your print with Adaptive Layer Height\n" "Did you know that you can print a model even faster by using the Adaptive Layer Height option? Check it out!" @@ -35375,8 +35067,7 @@ msgstr "" "Melhorar a resistência\n" "Você sabia que pode usar mais voltas de parede e maior densidade de preenchimento esparso mais alta para melhorar a resistência do modelo?" -#: resources/data/hints.ini: [hint:When do you need to print with the printer -#: door opened] +#: resources/data/hints.ini: [hint:When do you need to print with the printer door opened] msgid "" "When do you need to print with the printer door opened?\n" "Did you know that opening the printer door can reduce the probability of extruder/hotend clogging when printing lower temperature filament with a higher enclosure temperature? There is more info about this in the Wiki." @@ -35392,20 +35083,6 @@ msgstr "" "Evitar empenamento\n" "Você sabia que ao imprimir materiais propensos ao empenamento como ABS, aumentar adequadamente a temperatura da mesa aquecida pode reduzir a probabilidade de empenamento?" -# AI Translated -#~ msgid "Dalmatian yellow" -#~ msgstr "Amarelo dálmata" - -# AI Translated -# Needs human review: Color name of uncertain Portuguese rendering; check the shade it names -#~ msgid "Capsanthin violet" -#~ msgstr "Violeta capsantina" - -# AI Translated -# Needs human review: Color name of uncertain Portuguese rendering; check the shade it names -#~ msgid "Olivestone" -#~ msgstr "Pedra oliva" - #~ msgid "Available anywhere in the window, even while typing in a text field." #~ msgstr "Disponível em qualquer lugar da janela, mesmo ao digitar em um campo de texto." @@ -35418,53 +35095,6 @@ msgstr "" #~ msgid "Please choose the filament color" #~ msgstr "Escolha a cor do filamento" -# AI Translated -#~ msgid "" -#~ "Line width of the Bridge. If expressed as a %, it will be computed over the nozzle diameter.\n" -#~ "Recommended to use with a higher Bridge density or Bridge flow ratio.\n" -#~ "\n" -#~ "The maximum value is 100% or the nozzle diameter.\n" -#~ "If set to 0, the line width will match the Internal solid infill width." -#~ msgstr "" -#~ "Largura de linha da Ponte. Se expressa como %, será calculada sobre o diâmetro do bico.\n" -#~ "Recomendado usar com uma densidade de Ponte ou taxa de fluxo de Ponte mais alta.\n" -#~ "\n" -#~ "O valor máximo é 100% ou o diâmetro do bico.\n" -#~ "Se definido como 0, a largura de linha corresponderá à largura do preenchimento sólido interno." - -# AI Translated -#, no-c-format, no-boost-format -#~ msgid "" -#~ "Enable this option to slow down printing in areas where perimeters may have curled upwards.\n" -#~ "For example, additional slowdown will be applied when printing overhangs on sharp corners like the front of the Benchy hull, reducing curling which compounds over multiple layers.\n" -#~ "\n" -#~ "It is generally recommended to have this option switched on unless your printer cooling is powerful enough or the print speed is slow enough that perimeter curling does not happen. \n" -#~ "If printing with a high external perimeter speed, this parameter may introduce wall artifacts when slowing down, due to the potentially large variance in print speeds causing the extruder to be unable to keep up with the requested flow change.\n" -#~ "Root cause of these artifacts is most likely PA tuning being slightly off, especially when combined with a high PA smooth time.\n" -#~ "\n" -#~ "Recommendations when enabling this option:\n" -#~ "1. Reduce Pressure Advance smooth time to 0.015 - 0.02 so the extruder reacts quickly to the speed changes.\n" -#~ "2. Increase the minimum print speeds to limit the magnitude of the slowdown and reduce the variance between fast and slow segments.\n" -#~ "3. If artifacts still appear, enable Extrusion Rate Smoothing (ERS) to further smooth the flow transitions.\n" -#~ "\n" -#~ "Note: When this option is enabled, overhang perimeters are treated like overhangs, meaning the overhang speed is applied even if the overhanging perimeter is part of a bridge.\n" -#~ "For example, when the perimeters are 100% overhanging, with no wall supporting them from underneath, the 100% overhang speed will be applied." -#~ msgstr "" -#~ "Ative esta opção para reduzir a velocidade de impressão em áreas onde os perímetros podem ter se enrolado para cima.\n" -#~ "Por exemplo, uma desaceleração adicional será aplicada ao imprimir saliências em cantos vivos, como a frente do casco do Benchy, reduzindo o enrolamento que se acumula ao longo de várias camadas.\n" -#~ "\n" -#~ "Geralmente, recomenda-se manter esta opção ativada, a menos que o resfriamento da sua impressora seja potente o suficiente ou a velocidade de impressão seja lenta o suficiente para que o enrolamento dos perímetros não ocorra. \n" -#~ "Se imprimir com uma velocidade alta de perímetro externo, este parâmetro pode introduzir artefatos na parede ao desacelerar, devido à variação potencialmente grande nas velocidades de impressão que faz com que a extrusora não consiga acompanhar a mudança de fluxo solicitada.\n" -#~ "A causa raiz desses artefatos é provavelmente um ajuste de PA ligeiramente incorreto, especialmente quando combinado com um alto tempo de suavização de PA.\n" -#~ "\n" -#~ "Recomendações ao ativar esta opção:\n" -#~ "1. Reduza o tempo de suavização do Pressure Advance para 0,015 - 0,02 para que a extrusora reaja rapidamente às mudanças de velocidade.\n" -#~ "2. Aumente as velocidades mínimas de impressão para limitar a magnitude da desaceleração e reduzir a variação entre os segmentos rápidos e lentos.\n" -#~ "3. Se os artefatos ainda aparecerem, ative a Suavização da Taxa de Extrusão (ERS) para suavizar ainda mais as transições de fluxo.\n" -#~ "\n" -#~ "Nota: quando esta opção está ativada, os perímetros de saliência são tratados como saliências, o que significa que a velocidade de saliência é aplicada mesmo que o perímetro em saliência faça parte de uma ponte.\n" -#~ "Por exemplo, quando os perímetros estão 100% em saliência, sem nenhuma parede os sustentando por baixo, a velocidade de saliência de 100% será aplicada." - #~ msgid "" #~ "Speed of the externally visible bridge extrusions.\n" #~ "\n" @@ -35581,43 +35211,12 @@ msgstr "" #~ "\n" #~ "NOTA: As superfícies inferior e superior não serão afetadas por este valor para evitar lacunas visuais no exterior do modelo. Ajuste o 'Limiar de uma parede' nas configurações avançadas abaixo para ajustar a sensibilidade do que é considerado uma superfície superior. 'Limiar de uma parede' só é visível se esta configuração estiver acima do valor padrão de 0,5, ou se superfícies superiores de uma única parede estiverem habilitadas." -# AI Translated -#, boost-format -#~ msgid "Split into %1% part" -#~ msgid_plural "Split into %1% parts" -#~ msgstr[0] "Dividir em %1% peça" -#~ msgstr[1] "Dividir em %1% peças" - #~ msgid "Repair failed" #~ msgstr "Reparo falhou" #~ msgid "Repair canceled" #~ msgstr "Reparo cancelado" -# AI Translated -#~ msgid "What this layer does where it overlaps the ones below. Add and Subtract pile relief on or carve it away. Multiply and Divide scale what is underneath, which turns this layer into a mask over it - there, Depth acts as a strength, and 1 mm leaves white areas untouched." -#~ msgstr "O que esta camada faz onde se sobrepõe às de baixo. Adicionar e Subtrair acumulam relevo ou o retiram. Multiplicar e Dividir escalam o que está embaixo, o que transforma esta camada em uma máscara sobre ele - ali, Profundidade age como intensidade, e 1 mm deixa as áreas brancas intactas." - -# AI Translated -#~ msgid "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." -#~ msgstr "A malha tem geometria não-manifold ou bordas abertas. Você pode importá-la como está ou repará-la com o serviço de reparo 3D do Windows antes de importar." - -# AI Translated -#~ msgid "Please note that the mesh has non-manifold geometry or open boundaries." -#~ msgstr "Observe que a malha tem geometria não-manifold ou bordas abertas." - -# AI Translated -#~ msgid "Mesh issue" -#~ msgstr "Problema na malha" - -# AI Translated -#~ msgid "Repair failed: mesh still open after hole filling." -#~ msgstr "Falha no reparo: a malha ainda está aberta após o preenchimento de buracos." - -# AI Translated -#~ msgid "Cannot apply logical operation to non-boolean operators." -#~ msgstr "Não é possível aplicar uma operação lógica a operadores não booleanos." - #~ msgid "Reading" #~ msgstr "Lendo" @@ -35657,10 +35256,6 @@ msgstr "" #~ msgid "hotend" #~ msgstr "hotend" -# AI Translated -#~ msgid "Arranging " -#~ msgstr "Organizando " - #~ msgid "Orienting" #~ msgstr "Orientando" @@ -35749,11 +35344,6 @@ msgstr "" #~ "\n" #~ "Gostaria de ser redirecionado para a página da web para avaliar?" -# AI Translated -#, boost-format -#~ msgid " (process preset: %1%)" -#~ msgstr " (predefinição de processo: %1%)" - #, c-format, boost-format #~ msgid "The %s nozzle can not print %s." #~ msgstr "O bico %s não pode imprimir %s." @@ -35769,30 +35359,15 @@ msgstr "" #~ msgid " plate %1%:" #~ msgstr " placa %1%:" -# AI Translated -#, boost-format -#~ msgid "Remove all %1% mixed filaments?" -#~ msgstr "Remover todos os %1% filamentos mistos?" - #~ msgid "Do you want to replace it" #~ msgstr "Deseja substituí-lo" -# AI Translated -#, c-format, boost-format -#~ msgid "Bed temperature conflict: T%d (%s) sets the bed to %d°C — T%d (%s) requires %d°C. The primary tool controls the bed; secondary tools print at whatever temperature it sets." -#~ msgstr "Conflito de temperatura da mesa: T%d (%s) define a mesa em %d°C — T%d (%s) requer %d°C. A ferramenta principal controla a mesa; as ferramentas secundárias imprimem na temperatura que ela definir." - #~ msgid "No accelerations provided for calibration. Use default acceleration value " #~ msgstr "Nenhuma aceleração fornecida para calibração. Usar o valor de aceleração padrão " #~ msgid "No speeds provided for calibration. Use default optimal speed " #~ msgstr "Nenhuma velocidade fornecida para calibração. Usar a velocidade padrão " -# AI Translated -#, boost-format -#~ msgid "No belt temperature tower is available for the range %1% to %2% °C. Use a range the tower models cover, for example 230 to 190." -#~ msgstr "Nenhuma torre de temperatura para esteira está disponível para a faixa de %1% a %2% °C. Use uma faixa coberta pelos modelos de torre, por exemplo, 230 a 190." - #~ msgid "The selected file" #~ msgstr "O arquivo selecionado" @@ -35806,10 +35381,6 @@ msgstr "" #~ msgid "Cost %dg filament and %d changes more than optimal grouping." #~ msgstr "O custo de %dg de filamento e %d muda mais do que o agrupamento ideal." -# AI Translated -#~ msgid "Parameters with this icon can be configurable per nozzle." -#~ msgstr "Parâmetros com este ícone podem ser configurados por bico." - #~ msgid "Reserved keywords found" #~ msgstr "Palavras-chave reservadas encontradas" @@ -35830,11 +35401,6 @@ msgstr "" #~ msgid "Are you sure you want to %1% the selected preset?" #~ msgstr "Tem certeza de que quer %1% a predefinição selecionada?" -# AI Translated -#, c-format, boost-format -#~ msgid "%s %s" -#~ msgstr "%s %s" - #, boost-format #~ msgid "Split into %1% parts" #~ msgstr "Dividir em %1% peças" @@ -35845,16 +35411,6 @@ msgstr "" #~ msgid "Failed to download vendor profile(s): " #~ msgstr "Falha ao baixar o(s) perfil(is) de fornecedor: " -# AI Translated -#, boost-format -#~ msgid "In this Span mode only %1% print colors, but filament %2% isn't routed to any tool. Use filaments routed to %1%, or switch this plate to Primary mode." -#~ msgstr "Neste modo Span, as cores só são impressas por %1%, mas o filamento %2% não está direcionado a nenhuma ferramenta. Use filamentos direcionados a %1% ou mude esta placa para o modo Principal." - -# AI Translated -#, boost-format -#~ msgid "In this Span mode only %1% print colors, but filament %2% is routed to T%3%. Use filaments routed to %1%, or switch this plate to Primary mode." -#~ msgstr "Neste modo Span, as cores só são impressas por %1%, mas o filamento %2% está direcionado a T%3%. Use filamentos direcionados a %1% ou mude esta placa para o modo Principal." - #~ msgid " is too close to exclusion area, there may be collisions when printing." #~ msgstr " está muito perto da área de exclusão, pode haver colisões durante a impressão." @@ -35891,10 +35447,6 @@ msgstr "" #~ msgid "Python plugin(s) invoked at each slicing pipeline step to read and modify intermediate slicing data, including a final G-code post-processing step. Research/experimental." #~ msgstr "Plugin(s) Python invocado(s) em cada etapa do pipeline de fatiamento para ler e modificar dados intermediários de fatiamento, incluindo uma etapa final de pós-processamento do G-code. Pesquisa/experimental." -# AI Translated -#~ msgid "Per-plate override mapping physical heads to filament slots (1-based). Empty means use pem-inversion defaults." -#~ msgstr "Substituição por placa que mapeia as cabeças físicas para os espaços de filamento (começando em 1). Vazio significa usar os padrões da inversão do pem." - #~ msgid " not in range " #~ msgstr " fora do intervalo " @@ -35922,10 +35474,6 @@ msgstr "" #~ msgid "This machine type can only hold %d historical results per nozzle." #~ msgstr "Este tipo de máquina só pode manter %d resultados históricos por bico." -# AI Translated -#~ msgid "Overhang" -#~ msgstr "Saliência" - #~ msgid "Start / End" #~ msgstr "Inicial / Final" @@ -35962,111 +35510,10 @@ msgstr "" #~ msgid "Skipping %d objects." #~ msgstr "Ignorando %d objetos." -# AI Translated -#~ msgid "Open folder in explorer" -#~ msgstr "Abrir pasta no explorador de arquivos" - -# AI Translated -#, c-format, boost-format -#~ msgid "Click center then a vertex — %d sides, %s" -#~ msgstr "Clique no centro e depois em um vértice — %d lados, %s" - -# AI Translated -#~ msgid "circumscribed" -#~ msgstr "circunscrito" - -# AI Translated -#~ msgid "inscribed" -#~ msgstr "inscrito" - -# AI Translated -#, c-format -#~ msgid "Sketch created (%zu driving dims) — select it, then right-click to Extrude" -#~ msgstr "Esboço criado (%zu cotas motrizes) — selecione-o e clique com o botão direito para extrudar" - -# AI Translated -#, c-format -#~ msgid "OK — %zu triangles" -#~ msgstr "OK — %zu triângulos" - -# AI Translated -#, c-format, boost-format -#~ msgid "" -#~ "This mesh has %d triangles. Every triangle becomes a B-rep face before coplanar merging, so importing it may take a long time and leave a body that is slow to edit. Decimating the mesh first is usually better.\n" -#~ "\n" -#~ "Import anyway?" -#~ msgstr "" -#~ "Esta malha tem %d triângulos. Cada triângulo se torna uma face B-rep antes da mesclagem de faces coplanares, então importá-la pode levar muito tempo e deixar um corpo lento para editar. Geralmente é melhor decimar a malha primeiro.\n" -#~ "\n" -#~ "Importar mesmo assim?" - -# AI Translated -#, c-format, boost-format -#~ msgid "Imported solid — %d triangles → %d faces, volume %.2f mm³. Pick a face or edge, then Fillet / Cut / Shell to modify" -#~ msgstr "Sólido importado — %d triângulos → %d faces, volume %.2f mm³. Selecione uma face ou aresta e depois Filete / Cortar / Casca para modificar" - -# AI Translated -#~ msgid " — drag to place/size, then Confirm" -#~ msgstr " — arraste para colocar/dimensionar e depois confirme" - -# AI Translated -#, c-format, boost-format -#~ msgid "%d sketch entities" -#~ msgstr "%d entidades de esboço" - -# AI Translated -#~ msgid " — type a value, press Enter (or Confirm)" -#~ msgstr " — digite um valor e pressione Enter (ou Confirmar)" - -# AI Translated -#, c-format -#~ msgid "Preview — %zu triangles" -#~ msgstr "Pré-visualização — %zu triângulos" - -# AI Translated -#, boost-format -#~ msgid "%1% constraint(s) cannot act on this geometry (an ellipse or spline curve, or a zero-size circle) and are ignored" -#~ msgstr "Restrições ignoradas por não poderem atuar sobre esta geometria (uma elipse ou curva spline, ou um círculo de tamanho zero): %1%" - -# AI Translated -#, boost-format -#~ msgid "%1% constraint(s) the fillet/chamfer invalidated were removed" -#~ msgstr "Restrições invalidadas pelo filete/chanfro e removidas: %1%" - -# AI Translated -#, boost-format -#~ msgid "%1% constraint(s) released by the transform" -#~ msgstr "Restrições liberadas pela transformação: %1%" - -# AI Translated -#, boost-format -#~ msgid "...and %1% more open end(s)" -#~ msgstr "...e mais %1% extremidade(s) aberta(s)" - -# AI Translated -#, boost-format -#~ msgid "The material list supports at most %1% colors. After %2% decomposition, the material count would exceed %1%. Please delete unused filaments on the main screen before decomposing." -#~ msgstr "A lista de materiais suporta no máximo %1% cores. Após a decomposição de %2%, a quantidade de materiais excederia %1%. Exclua os filamentos não utilizados na tela principal antes de decompor." - #, boost-format #~ msgid "%1% printable colors from %2% filaments" #~ msgstr "%1% cores imprimíveis a partir de %2% filamentos" -# AI Translated -#, boost-format -#~ msgid "%1% islands" -#~ msgstr "%1% ilhas" - -# AI Translated -#, boost-format -#~ msgid "All %1% layers used" -#~ msgstr "Todas as %1% camadas usadas" - -# AI Translated -#, boost-format -#~ msgid "Preview: %1% triangles" -#~ msgstr "Pré-visualização: %1% triângulos" - #, boost-format #~ msgid "Model: %1% triangles - the bake refines to the resolution above, up to its budget" #~ msgstr "Modelo: %1% triângulos - o assamento refina até a resolução acima, dentro do seu orçamento" @@ -36079,90 +35526,6 @@ msgstr "" #~ msgid "Bake result up to ~%1% k triangles" #~ msgstr "Resultado do assamento até ~%1% k triângulos" -# AI Translated -#, boost-format -#~ msgid "%1% layers not painted, skipped" -#~ msgstr "%1% camadas sem pintura ignoradas" - -# AI Translated -#, c-format, boost-format -#~ msgid "The project supports up to %d filaments. Extra filaments will be discarded." -#~ msgstr "O projeto suporta até %d filamentos. Os filamentos extras serão descartados." - -# AI Translated -#, c-format, boost-format -#~ msgid "%d vertices selected | drag = move together, Shift/Ctrl click = add/remove" -#~ msgstr "%d vértices selecionados | arrastar = mover juntos, Shift/Ctrl clique = adicionar/remover" - -# AI Translated -#, c-format, boost-format -#~ msgid "%d edges selected | drag = move together, Shift/Ctrl click = add/remove" -#~ msgstr "%d arestas selecionadas | arrastar = mover juntas, Shift/Ctrl clique = adicionar/remover" - -# AI Translated -#, c-format, boost-format -#~ msgid "%d islands selected | drag = move together, Shift/Ctrl click = add/remove, R/S = rotate/scale primary" -#~ msgstr "%d ilhas selecionadas | arrastar = mover juntas, Shift/Ctrl clique = adicionar/remover, R/S = girar/escalar a principal" - -# AI Translated -# Needs human review: Source says 'Change it with Tiling', but the texture layer's controls are labeled 'Tile' (Ladrilho) and 'Tile size' (Tamanho do ladrilho); check which control is meant and quote its label. -#~ msgid "The active layer's tile size: how much of the model one repeat of the texture covers. The canvas is measured in tiles, so one grid cell is one repeat. Change it with Tiling in the layer's settings." -#~ msgstr "O tamanho do ladrilho da camada ativa: quanto do modelo uma repetição da textura cobre. A tela é medida em ladrilhos, então uma célula da grade é uma repetição. Altere-o no ladrilhamento das configurações da camada." - -# AI Translated -#, c-format, boost-format -#~ msgid "%d islands, %s faces" -#~ msgstr "%d ilhas, %s faces" - -# AI Translated -#, c-format, boost-format -#~ msgid "" -#~ "Plugin \"%s\" is requesting to read the following file(s):\n" -#~ "%s" -#~ msgstr "" -#~ "O plugin \"%s\" está solicitando a leitura do(s) seguinte(s) arquivo(s):\n" -#~ "%s" - -# AI Translated -#, c-format, boost-format -#~ msgid "" -#~ "Plugin \"%s\" is requesting to read/write the following file(s):\n" -#~ "%s" -#~ msgstr "" -#~ "O plugin \"%s\" está solicitando a leitura/gravação do(s) seguinte(s) arquivo(s):\n" -#~ "%s" - -# AI Translated -#, c-format, boost-format -#~ msgid "" -#~ "Plugin \"%s\" is requesting to create the following file(s):\n" -#~ "%s" -#~ msgstr "" -#~ "O plugin \"%s\" está solicitando a criação do(s) seguinte(s) arquivo(s):\n" -#~ "%s" - -# AI Translated -#, c-format, boost-format -#~ msgid "" -#~ "Plugin \"%s\" is requesting to delete the following file(s):\n" -#~ "%s" -#~ msgstr "" -#~ "O plugin \"%s\" está solicitando a exclusão do(s) seguinte(s) arquivo(s):\n" -#~ "%s" - -# AI Translated -#, c-format, boost-format -#~ msgid "" -#~ "Plugin \"%s\" is requesting to run the following command(s):\n" -#~ "%s" -#~ msgstr "" -#~ "O plugin \"%s\" está solicitando executar o(s) seguinte(s) comando(s):\n" -#~ "%s" - -# AI Translated -#~ msgid "Plugin installation failed" -#~ msgstr "Falha na instalação do plugin" - #~ msgid "" #~ "The Microsoft WebView2 Runtime could not be installed.\n" #~ "Some features, including the setup wizard, may appear blank until it is installed.\n" @@ -36581,9 +35944,6 @@ msgstr "" #~ msgid "Print time (seconds)" #~ msgstr "Tempo de impressão (segundos)" -#~ msgid "Open actions speed dial" -#~ msgstr "Abrir menu rápido de ações" - #~ msgid "Left: " #~ msgstr "Esquerda: " diff --git a/resources/profiles/Qidi.json b/resources/profiles/Qidi.json index dcb39ee957..075b9f7c54 100644 --- a/resources/profiles/Qidi.json +++ b/resources/profiles/Qidi.json @@ -1,6 +1,6 @@ { "name": "Qidi", - "version": "02.04.00.17", + "version": "02.04.00.18", "force_update": "0", "description": "Qidi configurations", "machine_model_list": [ diff --git a/resources/profiles/Qidi/process/0.12mm High Quality @X-Plus 5.json b/resources/profiles/Qidi/process/0.12mm High Quality @X-Plus 5.json index d2b490a4b1..ea753045ff 100644 --- a/resources/profiles/Qidi/process/0.12mm High Quality @X-Plus 5.json +++ b/resources/profiles/Qidi/process/0.12mm High Quality @X-Plus 5.json @@ -57,7 +57,7 @@ "support_bottom_z_distance": "0.12", "support_threshold_angle": "20", "support_top_z_distance": "0.12", - "top_color_penetration_layers": "7", + "top_color_penetration_layers": "5", "top_shell_layers": "5", "top_shell_thickness": "0.6", "top_surface_speed": [ diff --git a/resources/profiles/Snapmaker.json b/resources/profiles/Snapmaker.json index 4abf624a41..b702a02de3 100644 --- a/resources/profiles/Snapmaker.json +++ b/resources/profiles/Snapmaker.json @@ -1,6 +1,6 @@ { "name": "Snapmaker", - "version": "02.04.00.18", + "version": "02.04.00.19", "force_update": "0", "description": "Snapmaker configurations", "machine_model_list": [ diff --git a/resources/profiles/Snapmaker/process/0.06 High Quality @Snapmaker U1 (0.2 nozzle).json b/resources/profiles/Snapmaker/process/0.06 High Quality @Snapmaker U1 (0.2 nozzle).json index 357aeda830..861ef8c87e 100644 --- a/resources/profiles/Snapmaker/process/0.06 High Quality @Snapmaker U1 (0.2 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.06 High Quality @Snapmaker U1 (0.2 nozzle).json @@ -112,5 +112,7 @@ "600", "100", "600" - ] + ], + "top_color_penetration_layers": "7", + "bottom_color_penetration_layers": "5" } diff --git a/resources/profiles/Snapmaker/process/0.06 Standard @Snapmaker (0.2 nozzle).json b/resources/profiles/Snapmaker/process/0.06 Standard @Snapmaker (0.2 nozzle).json index f9c88f0fd6..4c036f678f 100644 --- a/resources/profiles/Snapmaker/process/0.06 Standard @Snapmaker (0.2 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.06 Standard @Snapmaker (0.2 nozzle).json @@ -24,6 +24,7 @@ "Snapmaker A350 Dual QS+B Kit (0.2 nozzle)" ], "bottom_shell_layers": "5", + "bottom_color_penetration_layers": "3", "bridge_flow": "1", "initial_layer_line_width": "0.25", "initial_layer_print_height": "0.1", @@ -35,6 +36,7 @@ "sparse_infill_line_width": "0.22", "support_line_width": "0.22", "top_shell_layers": "7", + "top_color_penetration_layers": "5", "top_surface_line_width": "0.22", "wall_loops": "4", "initial_layer_speed": "40", diff --git a/resources/profiles/Snapmaker/process/0.06 Standard @Snapmaker Artisan (0.2 nozzle).json b/resources/profiles/Snapmaker/process/0.06 Standard @Snapmaker Artisan (0.2 nozzle).json index 2f9d2d3d04..9c900f5f23 100644 --- a/resources/profiles/Snapmaker/process/0.06 Standard @Snapmaker Artisan (0.2 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.06 Standard @Snapmaker Artisan (0.2 nozzle).json @@ -8,6 +8,7 @@ "Snapmaker Artisan (0.2 nozzle)" ], "bottom_shell_layers": "4", + "bottom_color_penetration_layers": "3", "bridge_flow": "1", "initial_layer_line_width": "0.25", "initial_layer_print_height": "0.1", @@ -19,6 +20,7 @@ "sparse_infill_line_width": "0.22", "support_line_width": "0.22", "top_shell_layers": "5", + "top_color_penetration_layers": "5", "top_surface_line_width": "0.22", "wall_loops": "4", "initial_layer_infill_speed": "70", diff --git a/resources/profiles/Snapmaker/process/0.06 Standard @Snapmaker J1 (0.2 nozzle).json b/resources/profiles/Snapmaker/process/0.06 Standard @Snapmaker J1 (0.2 nozzle).json index 11e667b0f1..cd5c9c379e 100644 --- a/resources/profiles/Snapmaker/process/0.06 Standard @Snapmaker J1 (0.2 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.06 Standard @Snapmaker J1 (0.2 nozzle).json @@ -9,6 +9,7 @@ "Snapmaker J1 (0.2 nozzle)" ], "bottom_shell_layers": "4", + "bottom_color_penetration_layers": "3", "bridge_flow": "1", "initial_layer_line_width": "0.25", "initial_layer_print_height": "0.1", @@ -20,6 +21,7 @@ "sparse_infill_line_width": "0.22", "support_line_width": "0.22", "top_shell_layers": "5", + "top_color_penetration_layers": "5", "top_surface_line_width": "0.22", "wall_loops": "4", "initial_layer_infill_speed": "80", diff --git a/resources/profiles/Snapmaker/process/0.06 Standard @Snapmaker U1 (0.2 nozzle).json b/resources/profiles/Snapmaker/process/0.06 Standard @Snapmaker U1 (0.2 nozzle).json index 88bc187c8e..fa3e13fb67 100644 --- a/resources/profiles/Snapmaker/process/0.06 Standard @Snapmaker U1 (0.2 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.06 Standard @Snapmaker U1 (0.2 nozzle).json @@ -91,5 +91,7 @@ "500", "120", "500" - ] + ], + "top_color_penetration_layers": "7", + "bottom_color_penetration_layers": "5" } diff --git a/resources/profiles/Snapmaker/process/0.08 Extra Fine @Snapmaker (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.08 Extra Fine @Snapmaker (0.4 nozzle).json index 1158054b03..eb952a16d1 100644 --- a/resources/profiles/Snapmaker/process/0.08 Extra Fine @Snapmaker (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.08 Extra Fine @Snapmaker (0.4 nozzle).json @@ -24,6 +24,7 @@ "Snapmaker A350 Dual QS+B Kit (0.4 nozzle)" ], "bottom_shell_layers": "7", + "bottom_color_penetration_layers": "3", "bridge_flow": "1", "elefant_foot_compensation": "0.15", "ironing_flow": "8%", @@ -31,6 +32,7 @@ "initial_layer_print_height": "0.1", "support_threshold_angle": "15", "top_shell_layers": "9", + "top_color_penetration_layers": "5", "gap_infill_speed": "85", "initial_layer_infill_speed": "65", "inner_wall_speed": "120", diff --git a/resources/profiles/Snapmaker/process/0.08 Extra Fine @Snapmaker Artisan (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.08 Extra Fine @Snapmaker Artisan (0.4 nozzle).json index adf8ae30d1..21b20814d8 100644 --- a/resources/profiles/Snapmaker/process/0.08 Extra Fine @Snapmaker Artisan (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.08 Extra Fine @Snapmaker Artisan (0.4 nozzle).json @@ -9,6 +9,7 @@ "Snapmaker Artisan (0.4 nozzle)" ], "bottom_shell_layers": "4", + "bottom_color_penetration_layers": "3", "bridge_flow": "1", "elefant_foot_compensation": "0.15", "ironing_flow": "8%", @@ -16,6 +17,7 @@ "initial_layer_print_height": "0.1", "support_threshold_angle": "15", "top_shell_layers": "5", + "top_color_penetration_layers": "5", "initial_layer_infill_speed": "80", "inner_wall_speed": "145", "internal_solid_infill_speed": "150" diff --git a/resources/profiles/Snapmaker/process/0.08 Extra Fine @Snapmaker J1 (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.08 Extra Fine @Snapmaker J1 (0.4 nozzle).json index 890b8a4dad..eec06cf341 100644 --- a/resources/profiles/Snapmaker/process/0.08 Extra Fine @Snapmaker J1 (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.08 Extra Fine @Snapmaker J1 (0.4 nozzle).json @@ -9,6 +9,7 @@ "Snapmaker J1 (0.4 nozzle)" ], "bottom_shell_layers": "4", + "bottom_color_penetration_layers": "3", "bridge_flow": "1", "elefant_foot_compensation": "0.15", "ironing_flow": "8%", @@ -16,6 +17,7 @@ "initial_layer_print_height": "0.1", "support_threshold_angle": "15", "top_shell_layers": "5", + "top_color_penetration_layers": "5", "initial_layer_infill_speed": "80", "inner_wall_speed": "145", "internal_solid_infill_speed": "150" diff --git a/resources/profiles/Snapmaker/process/0.08 Extra Fine @Snapmaker U1 (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.08 Extra Fine @Snapmaker U1 (0.4 nozzle).json index d102118041..5c31ac5c5b 100644 --- a/resources/profiles/Snapmaker/process/0.08 Extra Fine @Snapmaker U1 (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.08 Extra Fine @Snapmaker U1 (0.4 nozzle).json @@ -93,5 +93,7 @@ "600", "450", "600" - ] + ], + "top_color_penetration_layers": "8", + "bottom_color_penetration_layers": "6" } diff --git a/resources/profiles/Snapmaker/process/0.08 High Quality @Snapmaker U1 (0.2 nozzle).json b/resources/profiles/Snapmaker/process/0.08 High Quality @Snapmaker U1 (0.2 nozzle).json index b5d2ade0a4..20a5ae8d4d 100644 --- a/resources/profiles/Snapmaker/process/0.08 High Quality @Snapmaker U1 (0.2 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.08 High Quality @Snapmaker U1 (0.2 nozzle).json @@ -112,5 +112,7 @@ "600", "100", "600" - ] + ], + "top_color_penetration_layers": "7", + "bottom_color_penetration_layers": "5" } diff --git a/resources/profiles/Snapmaker/process/0.08 High Quality @Snapmaker U1 (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.08 High Quality @Snapmaker U1 (0.4 nozzle).json index 81b775fb9d..f83a45df08 100644 --- a/resources/profiles/Snapmaker/process/0.08 High Quality @Snapmaker U1 (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.08 High Quality @Snapmaker U1 (0.4 nozzle).json @@ -134,5 +134,7 @@ "Direct Drive High Flow", "Direct Drive Standard", "Direct Drive High Flow" - ] + ], + "top_color_penetration_layers": "8", + "bottom_color_penetration_layers": "6" } diff --git a/resources/profiles/Snapmaker/process/0.08 Standard @Snapmaker U1 (0.2 nozzle).json b/resources/profiles/Snapmaker/process/0.08 Standard @Snapmaker U1 (0.2 nozzle).json index 16f85b3466..1787be7916 100644 --- a/resources/profiles/Snapmaker/process/0.08 Standard @Snapmaker U1 (0.2 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.08 Standard @Snapmaker U1 (0.2 nozzle).json @@ -91,5 +91,7 @@ "500", "120", "500" - ] + ], + "top_color_penetration_layers": "7", + "bottom_color_penetration_layers": "5" } diff --git a/resources/profiles/Snapmaker/process/0.10 High Quality @Snapmaker U1 (0.2 nozzle).json b/resources/profiles/Snapmaker/process/0.10 High Quality @Snapmaker U1 (0.2 nozzle).json index 95719fcc46..5a213b709a 100644 --- a/resources/profiles/Snapmaker/process/0.10 High Quality @Snapmaker U1 (0.2 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.10 High Quality @Snapmaker U1 (0.2 nozzle).json @@ -112,5 +112,7 @@ "600", "100", "600" - ] + ], + "top_color_penetration_layers": "7", + "bottom_color_penetration_layers": "5" } diff --git a/resources/profiles/Snapmaker/process/0.10 Standard @Snapmaker (0.2 nozzle).json b/resources/profiles/Snapmaker/process/0.10 Standard @Snapmaker (0.2 nozzle).json index 581909f3a7..f9b570dbe3 100644 --- a/resources/profiles/Snapmaker/process/0.10 Standard @Snapmaker (0.2 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.10 Standard @Snapmaker (0.2 nozzle).json @@ -27,7 +27,9 @@ "initial_layer_print_height": "0.1", "wall_loops": "4", "bottom_shell_layers": "5", + "bottom_color_penetration_layers": "3", "top_shell_layers": "7", + "top_color_penetration_layers": "5", "bridge_flow": "1", "line_width": "0.22", "outer_wall_line_width": "0.22", diff --git a/resources/profiles/Snapmaker/process/0.10 Standard @Snapmaker Artisan (0.2 nozzle).json b/resources/profiles/Snapmaker/process/0.10 Standard @Snapmaker Artisan (0.2 nozzle).json index 4664301284..d195277ba7 100644 --- a/resources/profiles/Snapmaker/process/0.10 Standard @Snapmaker Artisan (0.2 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.10 Standard @Snapmaker Artisan (0.2 nozzle).json @@ -12,7 +12,9 @@ "initial_layer_print_height": "0.1", "wall_loops": "4", "bottom_shell_layers": "5", + "bottom_color_penetration_layers": "3", "top_shell_layers": "7", + "top_color_penetration_layers": "5", "bridge_flow": "1", "line_width": "0.22", "outer_wall_line_width": "0.22", diff --git a/resources/profiles/Snapmaker/process/0.10 Standard @Snapmaker J1 (0.2 nozzle).json b/resources/profiles/Snapmaker/process/0.10 Standard @Snapmaker J1 (0.2 nozzle).json index 050a0d217d..2f38278dd6 100644 --- a/resources/profiles/Snapmaker/process/0.10 Standard @Snapmaker J1 (0.2 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.10 Standard @Snapmaker J1 (0.2 nozzle).json @@ -12,7 +12,9 @@ "initial_layer_print_height": "0.1", "wall_loops": "4", "bottom_shell_layers": "5", + "bottom_color_penetration_layers": "3", "top_shell_layers": "7", + "top_color_penetration_layers": "5", "bridge_flow": "1", "line_width": "0.22", "outer_wall_line_width": "0.22", diff --git a/resources/profiles/Snapmaker/process/0.10 Standard @Snapmaker U1 (0.2 nozzle).json b/resources/profiles/Snapmaker/process/0.10 Standard @Snapmaker U1 (0.2 nozzle).json index d654bca839..4bcad523e3 100644 --- a/resources/profiles/Snapmaker/process/0.10 Standard @Snapmaker U1 (0.2 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.10 Standard @Snapmaker U1 (0.2 nozzle).json @@ -93,5 +93,7 @@ "500", "120", "500" - ] + ], + "top_color_penetration_layers": "7", + "bottom_color_penetration_layers": "5" } diff --git a/resources/profiles/Snapmaker/process/0.12 Fine @Snapmaker (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.12 Fine @Snapmaker (0.4 nozzle).json index 0096cf3d9f..e1f9458945 100644 --- a/resources/profiles/Snapmaker/process/0.12 Fine @Snapmaker (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.12 Fine @Snapmaker (0.4 nozzle).json @@ -26,8 +26,10 @@ "layer_height": "0.12", "initial_layer_print_height": "0.2", "bottom_shell_layers": "5", + "bottom_color_penetration_layers": "3", "elefant_foot_compensation": "0.15", "top_shell_layers": "5", + "top_color_penetration_layers": "5", "top_shell_thickness": "0.6", "bridge_flow": "1", "support_threshold_angle": "20", diff --git a/resources/profiles/Snapmaker/process/0.12 Fine @Snapmaker Artisan (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.12 Fine @Snapmaker Artisan (0.4 nozzle).json index 855369306e..02c78abaf8 100644 --- a/resources/profiles/Snapmaker/process/0.12 Fine @Snapmaker Artisan (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.12 Fine @Snapmaker Artisan (0.4 nozzle).json @@ -10,8 +10,10 @@ ], "layer_height": "0.12", "bottom_shell_layers": "5", + "bottom_color_penetration_layers": "3", "elefant_foot_compensation": "0.15", "top_shell_layers": "5", + "top_color_penetration_layers": "5", "top_shell_thickness": "0.6", "bridge_flow": "1", "support_threshold_angle": "20", diff --git a/resources/profiles/Snapmaker/process/0.12 Fine @Snapmaker J1 (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.12 Fine @Snapmaker J1 (0.4 nozzle).json index c0a6a4d0e5..dcb4096e68 100644 --- a/resources/profiles/Snapmaker/process/0.12 Fine @Snapmaker J1 (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.12 Fine @Snapmaker J1 (0.4 nozzle).json @@ -10,8 +10,10 @@ ], "layer_height": "0.12", "bottom_shell_layers": "5", + "bottom_color_penetration_layers": "3", "elefant_foot_compensation": "0.15", "top_shell_layers": "5", + "top_color_penetration_layers": "5", "top_shell_thickness": "0.6", "bridge_flow": "1", "support_threshold_angle": "20", diff --git a/resources/profiles/Snapmaker/process/0.12 Fine @Snapmaker U1 (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.12 Fine @Snapmaker U1 (0.4 nozzle).json index 7552908319..bbbaa6a1b1 100644 --- a/resources/profiles/Snapmaker/process/0.12 Fine @Snapmaker U1 (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.12 Fine @Snapmaker U1 (0.4 nozzle).json @@ -94,5 +94,7 @@ "500", "200", "500" - ] + ], + "top_color_penetration_layers": "8", + "bottom_color_penetration_layers": "6" } diff --git a/resources/profiles/Snapmaker/process/0.12 High Quality @Snapmaker U1 (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.12 High Quality @Snapmaker U1 (0.4 nozzle).json index 7e473aeb2c..6eefec9d02 100644 --- a/resources/profiles/Snapmaker/process/0.12 High Quality @Snapmaker U1 (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.12 High Quality @Snapmaker U1 (0.4 nozzle).json @@ -135,5 +135,7 @@ "Direct Drive High Flow", "Direct Drive Standard", "Direct Drive High Flow" - ] + ], + "top_color_penetration_layers": "8", + "bottom_color_penetration_layers": "6" } diff --git a/resources/profiles/Snapmaker/process/0.12 Standard @Snapmaker U1 (0.2 nozzle).json b/resources/profiles/Snapmaker/process/0.12 Standard @Snapmaker U1 (0.2 nozzle).json index d6038972a6..3aff903e9e 100644 --- a/resources/profiles/Snapmaker/process/0.12 Standard @Snapmaker U1 (0.2 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.12 Standard @Snapmaker U1 (0.2 nozzle).json @@ -91,5 +91,7 @@ "500", "120", "500" - ] + ], + "top_color_penetration_layers": "6", + "bottom_color_penetration_layers": "4" } diff --git a/resources/profiles/Snapmaker/process/0.14 Standard @Snapmaker (0.2 nozzle).json b/resources/profiles/Snapmaker/process/0.14 Standard @Snapmaker (0.2 nozzle).json index b07c8f4758..b04c7c0c2c 100644 --- a/resources/profiles/Snapmaker/process/0.14 Standard @Snapmaker (0.2 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.14 Standard @Snapmaker (0.2 nozzle).json @@ -27,7 +27,9 @@ "initial_layer_print_height": "0.2", "wall_loops": "4", "bottom_shell_layers": "5", + "bottom_color_penetration_layers": "3", "top_shell_layers": "7", + "top_color_penetration_layers": "5", "bridge_flow": "1", "line_width": "0.22", "outer_wall_line_width": "0.22", diff --git a/resources/profiles/Snapmaker/process/0.14 Standard @Snapmaker Artisan (0.2 nozzle).json b/resources/profiles/Snapmaker/process/0.14 Standard @Snapmaker Artisan (0.2 nozzle).json index e63fd634d4..3ab37fd7fc 100644 --- a/resources/profiles/Snapmaker/process/0.14 Standard @Snapmaker Artisan (0.2 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.14 Standard @Snapmaker Artisan (0.2 nozzle).json @@ -11,7 +11,9 @@ "layer_height": "0.14", "wall_loops": "4", "bottom_shell_layers": "4", + "bottom_color_penetration_layers": "3", "top_shell_layers": "5", + "top_color_penetration_layers": "5", "bridge_flow": "1", "line_width": "0.22", "outer_wall_line_width": "0.22", diff --git a/resources/profiles/Snapmaker/process/0.14 Standard @Snapmaker J1 (0.2 nozzle).json b/resources/profiles/Snapmaker/process/0.14 Standard @Snapmaker J1 (0.2 nozzle).json index c9c285e7e2..13aaa274bd 100644 --- a/resources/profiles/Snapmaker/process/0.14 Standard @Snapmaker J1 (0.2 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.14 Standard @Snapmaker J1 (0.2 nozzle).json @@ -11,7 +11,9 @@ "layer_height": "0.14", "wall_loops": "4", "bottom_shell_layers": "4", + "bottom_color_penetration_layers": "3", "top_shell_layers": "5", + "top_color_penetration_layers": "5", "bridge_flow": "1", "line_width": "0.22", "outer_wall_line_width": "0.22", diff --git a/resources/profiles/Snapmaker/process/0.14 Standard @Snapmaker U1 (0.2 nozzle).json b/resources/profiles/Snapmaker/process/0.14 Standard @Snapmaker U1 (0.2 nozzle).json index 0bc45246f0..bcab59ed53 100644 --- a/resources/profiles/Snapmaker/process/0.14 Standard @Snapmaker U1 (0.2 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.14 Standard @Snapmaker U1 (0.2 nozzle).json @@ -91,5 +91,7 @@ "500", "120", "500" - ] + ], + "top_color_penetration_layers": "6", + "bottom_color_penetration_layers": "4" } diff --git a/resources/profiles/Snapmaker/process/0.16 High Quality @Snapmaker U1 (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.16 High Quality @Snapmaker U1 (0.4 nozzle).json index ef1d0be7c0..64fa5326ce 100644 --- a/resources/profiles/Snapmaker/process/0.16 High Quality @Snapmaker U1 (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.16 High Quality @Snapmaker U1 (0.4 nozzle).json @@ -135,5 +135,7 @@ "Direct Drive High Flow", "Direct Drive Standard", "Direct Drive High Flow" - ] + ], + "top_color_penetration_layers": "6", + "bottom_color_penetration_layers": "4" } diff --git a/resources/profiles/Snapmaker/process/0.16 Optimal @Snapmaker (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.16 Optimal @Snapmaker (0.4 nozzle).json index c77a8dbfb6..4c77cb1ead 100644 --- a/resources/profiles/Snapmaker/process/0.16 Optimal @Snapmaker (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.16 Optimal @Snapmaker (0.4 nozzle).json @@ -27,6 +27,7 @@ "initial_layer_print_height": "0.2", "elefant_foot_compensation": "0.15", "bottom_shell_layers": "4", + "bottom_color_penetration_layers": "3", "top_shell_thickness": "0.6", "bridge_flow": "1", "support_threshold_angle": "25", @@ -41,5 +42,6 @@ "overhang_2_4_speed": "30", "overhang_3_4_speed": "10", "ironing_speed": "30", - "support_speed": "100" + "support_speed": "100", + "top_color_penetration_layers": "4" } diff --git a/resources/profiles/Snapmaker/process/0.16 Optimal @Snapmaker Artisan (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.16 Optimal @Snapmaker Artisan (0.4 nozzle).json index 67fc4c5c17..3df04e4021 100644 --- a/resources/profiles/Snapmaker/process/0.16 Optimal @Snapmaker Artisan (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.16 Optimal @Snapmaker Artisan (0.4 nozzle).json @@ -11,7 +11,9 @@ "layer_height": "0.16", "elefant_foot_compensation": "0.15", "bottom_shell_layers": "4", + "bottom_color_penetration_layers": "3", "top_shell_layers": "5", + "top_color_penetration_layers": "5", "top_shell_thickness": "0.6", "bridge_flow": "1", "support_threshold_angle": "25", diff --git a/resources/profiles/Snapmaker/process/0.16 Optimal @Snapmaker J1 (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.16 Optimal @Snapmaker J1 (0.4 nozzle).json index 983fdfc1f2..500e7cd5fc 100644 --- a/resources/profiles/Snapmaker/process/0.16 Optimal @Snapmaker J1 (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.16 Optimal @Snapmaker J1 (0.4 nozzle).json @@ -11,7 +11,9 @@ "layer_height": "0.16", "elefant_foot_compensation": "0.15", "bottom_shell_layers": "4", + "bottom_color_penetration_layers": "3", "top_shell_layers": "5", + "top_color_penetration_layers": "5", "top_shell_thickness": "0.6", "bridge_flow": "1", "support_threshold_angle": "25", diff --git a/resources/profiles/Snapmaker/process/0.16 Optimal @Snapmaker U1 (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.16 Optimal @Snapmaker U1 (0.4 nozzle).json index 79c1ad6f8f..cd6425d883 100644 --- a/resources/profiles/Snapmaker/process/0.16 Optimal @Snapmaker U1 (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.16 Optimal @Snapmaker U1 (0.4 nozzle).json @@ -93,5 +93,7 @@ "500", "200", "500" - ] + ], + "top_color_penetration_layers": "6", + "bottom_color_penetration_layers": "4" } diff --git a/resources/profiles/Snapmaker/process/0.18 Standard @Snapmaker (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.18 Standard @Snapmaker (0.6 nozzle).json index 58ba1f433e..f3a6274866 100644 --- a/resources/profiles/Snapmaker/process/0.18 Standard @Snapmaker (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.18 Standard @Snapmaker (0.6 nozzle).json @@ -27,6 +27,7 @@ "initial_layer_print_height": "0.2", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_flow": "1", "line_width": "0.62", "outer_wall_line_width": "0.62", @@ -46,5 +47,6 @@ "overhang_2_4_speed": "50", "ironing_speed": "30", "support_interface_speed": "35", - "support_speed": "100" + "support_speed": "100", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.18 Standard @Snapmaker Artisan (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.18 Standard @Snapmaker Artisan (0.6 nozzle).json index 571da9803b..5dcb62be15 100644 --- a/resources/profiles/Snapmaker/process/0.18 Standard @Snapmaker Artisan (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.18 Standard @Snapmaker Artisan (0.6 nozzle).json @@ -18,5 +18,7 @@ "inner_wall_line_width": "0.62", "internal_solid_infill_line_width": "0.62", "support_line_width": "0.62", - "top_surface_line_width": "0.62" + "top_surface_line_width": "0.62", + "top_color_penetration_layers": "4", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.18 Standard @Snapmaker J1 (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.18 Standard @Snapmaker J1 (0.6 nozzle).json index 65113d6de1..f7c1415ee5 100644 --- a/resources/profiles/Snapmaker/process/0.18 Standard @Snapmaker J1 (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.18 Standard @Snapmaker J1 (0.6 nozzle).json @@ -20,5 +20,7 @@ "support_line_width": "0.62", "top_surface_line_width": "0.62", "inner_wall_speed": "145", - "internal_solid_infill_speed": "150" + "internal_solid_infill_speed": "150", + "top_color_penetration_layers": "4", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.18 Standard @Snapmaker U1 (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.18 Standard @Snapmaker U1 (0.6 nozzle).json index cbe81ad191..8f82c85f5d 100644 --- a/resources/profiles/Snapmaker/process/0.18 Standard @Snapmaker U1 (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.18 Standard @Snapmaker U1 (0.6 nozzle).json @@ -105,5 +105,6 @@ "500", "120", "500" - ] + ], + "top_color_penetration_layers": "5" } diff --git a/resources/profiles/Snapmaker/process/0.20 Standard @Snapmaker (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.20 Standard @Snapmaker (0.4 nozzle).json index 8f007e2a34..96e55587c2 100644 --- a/resources/profiles/Snapmaker/process/0.20 Standard @Snapmaker (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.20 Standard @Snapmaker (0.4 nozzle).json @@ -33,5 +33,7 @@ "ironing_speed": "30", "overhang_1_4_speed": "40", "overhang_2_4_speed": "20", - "overhang_3_4_speed": "10" + "overhang_3_4_speed": "10", + "top_color_penetration_layers": "4", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.20 Standard @Snapmaker Artisan (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.20 Standard @Snapmaker Artisan (0.4 nozzle).json index 1b40cd1f2a..7e3e4e04e6 100644 --- a/resources/profiles/Snapmaker/process/0.20 Standard @Snapmaker Artisan (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.20 Standard @Snapmaker Artisan (0.4 nozzle).json @@ -8,5 +8,7 @@ "compatible_printers": [ "Snapmaker Artisan (0.4 nozzle)" ], - "elefant_foot_compensation": "0.15" + "elefant_foot_compensation": "0.15", + "top_color_penetration_layers": "4", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.20 Standard @Snapmaker J1 (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.20 Standard @Snapmaker J1 (0.4 nozzle).json index f81b4247e3..ee1ea602e7 100644 --- a/resources/profiles/Snapmaker/process/0.20 Standard @Snapmaker J1 (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.20 Standard @Snapmaker J1 (0.4 nozzle).json @@ -8,5 +8,7 @@ "compatible_printers": [ "Snapmaker J1 (0.4 nozzle)" ], - "elefant_foot_compensation": "0.15" + "elefant_foot_compensation": "0.15", + "top_color_penetration_layers": "4", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.20 Strength @Snapmaker (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.20 Strength @Snapmaker (0.4 nozzle).json index 453c35a65c..72e7d8ba9b 100644 --- a/resources/profiles/Snapmaker/process/0.20 Strength @Snapmaker (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.20 Strength @Snapmaker (0.4 nozzle).json @@ -37,5 +37,7 @@ "top_surface_speed": "70", "overhang_1_4_speed": "55", "overhang_2_4_speed": "30", - "overhang_3_4_speed": "10" + "overhang_3_4_speed": "10", + "top_color_penetration_layers": "4", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.20 Strength @Snapmaker Artisan (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.20 Strength @Snapmaker Artisan (0.4 nozzle).json index 4098850307..5a4675ae00 100644 --- a/resources/profiles/Snapmaker/process/0.20 Strength @Snapmaker Artisan (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.20 Strength @Snapmaker Artisan (0.4 nozzle).json @@ -11,5 +11,7 @@ "elefant_foot_compensation": "0.15", "wall_loops": "6", "bottom_shell_layers": "4", - "sparse_infill_density": "25%" + "bottom_color_penetration_layers": "3", + "sparse_infill_density": "25%", + "top_color_penetration_layers": "4" } diff --git a/resources/profiles/Snapmaker/process/0.20 Strength @Snapmaker J1 (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.20 Strength @Snapmaker J1 (0.4 nozzle).json index d6349b8dec..636cfbd010 100644 --- a/resources/profiles/Snapmaker/process/0.20 Strength @Snapmaker J1 (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.20 Strength @Snapmaker J1 (0.4 nozzle).json @@ -11,5 +11,7 @@ "elefant_foot_compensation": "0.15", "wall_loops": "6", "bottom_shell_layers": "4", - "sparse_infill_density": "25%" + "bottom_color_penetration_layers": "3", + "sparse_infill_density": "25%", + "top_color_penetration_layers": "4" } diff --git a/resources/profiles/Snapmaker/process/0.24 Draft @Snapmaker (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.24 Draft @Snapmaker (0.4 nozzle).json index 25abfea922..0e1f06d651 100644 --- a/resources/profiles/Snapmaker/process/0.24 Draft @Snapmaker (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.24 Draft @Snapmaker (0.4 nozzle).json @@ -27,6 +27,7 @@ "elefant_foot_compensation": "0.15", "top_surface_line_width": "0.45", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "top_shell_thickness": "0.6", "support_threshold_angle": "35", "initial_layer_infill_speed": "65", @@ -39,5 +40,6 @@ "support_speed": "100", "overhang_1_4_speed": "55", "overhang_2_4_speed": "30", - "overhang_3_4_speed": "10" + "overhang_3_4_speed": "10", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.24 Draft @Snapmaker Artisan (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.24 Draft @Snapmaker Artisan (0.4 nozzle).json index 17fe35c5d6..70b4e00f06 100644 --- a/resources/profiles/Snapmaker/process/0.24 Draft @Snapmaker Artisan (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.24 Draft @Snapmaker Artisan (0.4 nozzle).json @@ -12,7 +12,9 @@ "elefant_foot_compensation": "0.15", "top_surface_line_width": "0.45", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "top_shell_thickness": "0.6", "support_threshold_angle": "35", - "initial_layer_infill_speed": "65" + "initial_layer_infill_speed": "65", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.24 Draft @Snapmaker J1 (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.24 Draft @Snapmaker J1 (0.4 nozzle).json index 5f5199f7ec..f9f36ae985 100644 --- a/resources/profiles/Snapmaker/process/0.24 Draft @Snapmaker J1 (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.24 Draft @Snapmaker J1 (0.4 nozzle).json @@ -12,7 +12,9 @@ "elefant_foot_compensation": "0.15", "top_surface_line_width": "0.45", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "top_shell_thickness": "0.6", "support_threshold_angle": "35", - "initial_layer_infill_speed": "65" + "initial_layer_infill_speed": "65", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker (0.6 nozzle).json index 3fa8e9b3db..63c16a319d 100644 --- a/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker (0.6 nozzle).json @@ -26,6 +26,7 @@ "layer_height": "0.24", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "line_width": "0.62", "outer_wall_line_width": "0.62", "initial_layer_line_width": "0.62", @@ -44,5 +45,6 @@ "overhang_2_4_speed": "50", "ironing_speed": "30", "support_interface_speed": "35", - "support_speed": "100" + "support_speed": "100", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker (0.8 nozzle).json b/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker (0.8 nozzle).json index 9fdeff863a..64b7a40361 100644 --- a/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker (0.8 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker (0.8 nozzle).json @@ -26,6 +26,7 @@ "layer_height": "0.24", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "line_width": "0.82", "outer_wall_line_width": "0.82", "initial_layer_line_width": "0.82", @@ -46,5 +47,6 @@ "overhang_4_4_speed": "5", "ironing_speed": "30", "support_interface_speed": "35", - "support_speed": "100" + "support_speed": "100", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker Artisan (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker Artisan (0.6 nozzle).json index e90dd34c1d..0f7ace584f 100644 --- a/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker Artisan (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker Artisan (0.6 nozzle).json @@ -11,6 +11,7 @@ "layer_height": "0.24", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "line_width": "0.62", "outer_wall_line_width": "0.62", "initial_layer_line_width": "0.62", @@ -18,5 +19,6 @@ "inner_wall_line_width": "0.62", "internal_solid_infill_line_width": "0.62", "support_line_width": "0.62", - "top_surface_line_width": "0.62" + "top_surface_line_width": "0.62", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker Artisan (0.8 nozzle).json b/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker Artisan (0.8 nozzle).json index 4615647a66..a7c6d8027e 100644 --- a/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker Artisan (0.8 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker Artisan (0.8 nozzle).json @@ -12,6 +12,7 @@ "initial_layer_print_height": "0.3", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "line_width": "0.82", "outer_wall_line_width": "0.82", "initial_layer_line_width": "0.82", @@ -19,5 +20,6 @@ "inner_wall_line_width": "0.82", "internal_solid_infill_line_width": "0.82", "support_line_width": "0.82", - "top_surface_line_width": "0.82" + "top_surface_line_width": "0.82", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker J1 (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker J1 (0.6 nozzle).json index c3c6d46268..7f637b0c7d 100644 --- a/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker J1 (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker J1 (0.6 nozzle).json @@ -11,6 +11,7 @@ "layer_height": "0.24", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "line_width": "0.62", "outer_wall_line_width": "0.62", "initial_layer_line_width": "0.62", @@ -18,5 +19,6 @@ "inner_wall_line_width": "0.62", "internal_solid_infill_line_width": "0.62", "support_line_width": "0.62", - "top_surface_line_width": "0.62" + "top_surface_line_width": "0.62", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker J1 (0.8 nozzle).json b/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker J1 (0.8 nozzle).json index 8aa8de9223..a7bac0ac16 100644 --- a/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker J1 (0.8 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker J1 (0.8 nozzle).json @@ -12,6 +12,7 @@ "initial_layer_print_height": "0.3", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "line_width": "0.82", "outer_wall_line_width": "0.82", "initial_layer_line_width": "0.82", @@ -19,5 +20,6 @@ "inner_wall_line_width": "0.82", "internal_solid_infill_line_width": "0.82", "support_line_width": "0.82", - "top_surface_line_width": "0.82" + "top_surface_line_width": "0.82", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker U1 (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker U1 (0.6 nozzle).json index d5f4513a58..6d654e923a 100644 --- a/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker U1 (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker U1 (0.6 nozzle).json @@ -105,5 +105,6 @@ "500", "120", "500" - ] + ], + "top_color_penetration_layers": "4" } diff --git a/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker U1 (0.8 nozzle).json b/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker U1 (0.8 nozzle).json index 1865821910..0b4018dc1e 100644 --- a/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker U1 (0.8 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.24 Standard @Snapmaker U1 (0.8 nozzle).json @@ -105,5 +105,6 @@ "500", "120", "500" - ] + ], + "top_color_penetration_layers": "4" } diff --git a/resources/profiles/Snapmaker/process/0.25 Benchy @Snapmaker Artisan (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.25 Benchy @Snapmaker Artisan (0.4 nozzle).json index 2a0f1ae009..9b5ba0627f 100644 --- a/resources/profiles/Snapmaker/process/0.25 Benchy @Snapmaker Artisan (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.25 Benchy @Snapmaker Artisan (0.4 nozzle).json @@ -10,6 +10,7 @@ ], "elefant_foot_compensation": "0.15", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "top_shell_thickness": "0.5", "initial_layer_speed": "100", "initial_layer_infill_speed": "180", @@ -46,6 +47,7 @@ "sparse_infill_line_width": "0.5", "top_surface_line_width": "0.5", "bottom_shell_layers": "2", + "bottom_color_penetration_layers": "2", "initial_layer_travel_speed": "100%", "bridge_acceleration": "3000", "bridge_speed": "100", diff --git a/resources/profiles/Snapmaker/process/0.25 Benchy @Snapmaker J1 (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.25 Benchy @Snapmaker J1 (0.4 nozzle).json index a38c31b2fd..57d1f1e724 100644 --- a/resources/profiles/Snapmaker/process/0.25 Benchy @Snapmaker J1 (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.25 Benchy @Snapmaker J1 (0.4 nozzle).json @@ -10,6 +10,7 @@ ], "elefant_foot_compensation": "0.15", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "top_shell_thickness": "0.5", "initial_layer_speed": "120", "initial_layer_infill_speed": "200", @@ -45,6 +46,7 @@ "sparse_infill_line_width": "0.5", "top_surface_line_width": "0.5", "bottom_shell_layers": "2", + "bottom_color_penetration_layers": "2", "initial_layer_travel_speed": "100%", "bridge_acceleration": "3000", "bridge_speed": "180", diff --git a/resources/profiles/Snapmaker/process/0.25 Benchy @Snapmaker U1 (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.25 Benchy @Snapmaker U1 (0.4 nozzle).json index 0b012c715a..03fba2f160 100644 --- a/resources/profiles/Snapmaker/process/0.25 Benchy @Snapmaker U1 (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.25 Benchy @Snapmaker U1 (0.4 nozzle).json @@ -11,6 +11,7 @@ ], "elefant_foot_compensation": "0.15", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "top_shell_thickness": "0.5", "initial_layer_speed": [ "100", @@ -155,6 +156,7 @@ "sparse_infill_line_width": "0.5", "top_surface_line_width": "0.5", "bottom_shell_layers": "2", + "bottom_color_penetration_layers": "2", "initial_layer_travel_speed": [ "100%", "100%", diff --git a/resources/profiles/Snapmaker/process/0.28 Extra Draft @Snapmaker (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.28 Extra Draft @Snapmaker (0.4 nozzle).json index f8d31d6c3d..e3aeb98f99 100644 --- a/resources/profiles/Snapmaker/process/0.28 Extra Draft @Snapmaker (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.28 Extra Draft @Snapmaker (0.4 nozzle).json @@ -27,6 +27,7 @@ "elefant_foot_compensation": "0.15", "top_surface_line_width": "0.45", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "top_shell_thickness": "0.6", "support_threshold_angle": "40", "wall_loops": "2", @@ -41,5 +42,6 @@ "support_speed": "100", "overhang_1_4_speed": "55", "overhang_2_4_speed": "30", - "overhang_3_4_speed": "10" + "overhang_3_4_speed": "10", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.28 Extra Draft @Snapmaker Artisan (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.28 Extra Draft @Snapmaker Artisan (0.4 nozzle).json index e89e5148ee..560bf770d8 100644 --- a/resources/profiles/Snapmaker/process/0.28 Extra Draft @Snapmaker Artisan (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.28 Extra Draft @Snapmaker Artisan (0.4 nozzle).json @@ -12,8 +12,10 @@ "elefant_foot_compensation": "0.15", "top_surface_line_width": "0.45", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "top_shell_thickness": "0.6", "support_threshold_angle": "40", "wall_loops": "2", - "initial_layer_infill_speed": "65" + "initial_layer_infill_speed": "65", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.28 Extra Draft @Snapmaker J1 (0.4 nozzle).json b/resources/profiles/Snapmaker/process/0.28 Extra Draft @Snapmaker J1 (0.4 nozzle).json index b472f8b73c..6ed0a6d391 100644 --- a/resources/profiles/Snapmaker/process/0.28 Extra Draft @Snapmaker J1 (0.4 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.28 Extra Draft @Snapmaker J1 (0.4 nozzle).json @@ -12,8 +12,10 @@ "elefant_foot_compensation": "0.15", "top_surface_line_width": "0.45", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "top_shell_thickness": "0.6", "support_threshold_angle": "40", "wall_loops": "2", - "initial_layer_infill_speed": "65" + "initial_layer_infill_speed": "65", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.30 Standard @Snapmaker (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.30 Standard @Snapmaker (0.6 nozzle).json index 71ca1a7364..da67937cfc 100644 --- a/resources/profiles/Snapmaker/process/0.30 Standard @Snapmaker (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.30 Standard @Snapmaker (0.6 nozzle).json @@ -25,6 +25,7 @@ ], "layer_height": "0.3", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.62", "outer_wall_line_width": "0.62", @@ -46,5 +47,6 @@ "overhang_2_4_speed": "50", "ironing_speed": "30", "support_interface_speed": "35", - "support_speed": "100" + "support_speed": "100", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.30 Standard @Snapmaker Artisan (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.30 Standard @Snapmaker Artisan (0.6 nozzle).json index 740b764a6b..f79be0d7ab 100644 --- a/resources/profiles/Snapmaker/process/0.30 Standard @Snapmaker Artisan (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.30 Standard @Snapmaker Artisan (0.6 nozzle).json @@ -10,6 +10,7 @@ ], "layer_height": "0.3", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.62", "outer_wall_line_width": "0.62", @@ -21,5 +22,6 @@ "top_surface_line_width": "0.62", "wall_loops": "2", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.30 Standard @Snapmaker J1 (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.30 Standard @Snapmaker J1 (0.6 nozzle).json index 82e876cd59..539fbdf7c8 100644 --- a/resources/profiles/Snapmaker/process/0.30 Standard @Snapmaker J1 (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.30 Standard @Snapmaker J1 (0.6 nozzle).json @@ -10,6 +10,7 @@ ], "layer_height": "0.3", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.62", "outer_wall_line_width": "0.62", @@ -21,5 +22,6 @@ "top_surface_line_width": "0.62", "wall_loops": "2", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.30 Standard @Snapmaker U1 (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.30 Standard @Snapmaker U1 (0.6 nozzle).json index 4cc91537ee..f7c8c5b87b 100644 --- a/resources/profiles/Snapmaker/process/0.30 Standard @Snapmaker U1 (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.30 Standard @Snapmaker U1 (0.6 nozzle).json @@ -104,5 +104,6 @@ "500", "120", "500" - ] + ], + "top_color_penetration_layers": "4" } diff --git a/resources/profiles/Snapmaker/process/0.30 Strength @Snapmaker (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.30 Strength @Snapmaker (0.6 nozzle).json index 69c56f442d..091680c54b 100644 --- a/resources/profiles/Snapmaker/process/0.30 Strength @Snapmaker (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.30 Strength @Snapmaker (0.6 nozzle).json @@ -25,6 +25,7 @@ ], "layer_height": "0.3", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.62", "outer_wall_line_width": "0.62", @@ -47,5 +48,6 @@ "overhang_2_4_speed": "50", "ironing_speed": "30", "support_interface_speed": "35", - "support_speed": "100" + "support_speed": "100", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.30 Strength @Snapmaker Artisan (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.30 Strength @Snapmaker Artisan (0.6 nozzle).json index 6cd6ab07e6..37fc0c9b1e 100644 --- a/resources/profiles/Snapmaker/process/0.30 Strength @Snapmaker Artisan (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.30 Strength @Snapmaker Artisan (0.6 nozzle).json @@ -10,6 +10,7 @@ ], "layer_height": "0.3", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.62", "outer_wall_line_width": "0.62", @@ -22,5 +23,6 @@ "wall_loops": "5", "sparse_infill_density": "25%", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.30 Strength @Snapmaker J1 (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.30 Strength @Snapmaker J1 (0.6 nozzle).json index 27945ce986..d1f9f9b101 100644 --- a/resources/profiles/Snapmaker/process/0.30 Strength @Snapmaker J1 (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.30 Strength @Snapmaker J1 (0.6 nozzle).json @@ -10,6 +10,7 @@ ], "layer_height": "0.3", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.62", "outer_wall_line_width": "0.62", @@ -22,5 +23,6 @@ "wall_loops": "5", "sparse_infill_density": "25%", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.30 Strength @Snapmaker U1 (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.30 Strength @Snapmaker U1 (0.6 nozzle).json index fe96840a26..6e2f19423d 100644 --- a/resources/profiles/Snapmaker/process/0.30 Strength @Snapmaker U1 (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.30 Strength @Snapmaker U1 (0.6 nozzle).json @@ -106,5 +106,6 @@ "500", "120", "500" - ] + ], + "top_color_penetration_layers": "4" } diff --git a/resources/profiles/Snapmaker/process/0.32 Standard @Snapmaker (0.8 nozzle).json b/resources/profiles/Snapmaker/process/0.32 Standard @Snapmaker (0.8 nozzle).json index ce2b7b3f83..12edce9985 100644 --- a/resources/profiles/Snapmaker/process/0.32 Standard @Snapmaker (0.8 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.32 Standard @Snapmaker (0.8 nozzle).json @@ -26,6 +26,7 @@ "layer_height": "0.32", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -48,5 +49,6 @@ "overhang_4_4_speed": "5", "ironing_speed": "30", "support_interface_speed": "35", - "support_speed": "100" + "support_speed": "100", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.32 Standard @Snapmaker Artisan (0.8 nozzle).json b/resources/profiles/Snapmaker/process/0.32 Standard @Snapmaker Artisan (0.8 nozzle).json index b599d87fc9..236b357fd6 100644 --- a/resources/profiles/Snapmaker/process/0.32 Standard @Snapmaker Artisan (0.8 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.32 Standard @Snapmaker Artisan (0.8 nozzle).json @@ -11,6 +11,7 @@ "layer_height": "0.32", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -21,5 +22,6 @@ "support_line_width": "0.82", "top_surface_line_width": "0.82", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.32 Standard @Snapmaker J1 (0.8 nozzle).json b/resources/profiles/Snapmaker/process/0.32 Standard @Snapmaker J1 (0.8 nozzle).json index 986296cbd6..771fafa9c3 100644 --- a/resources/profiles/Snapmaker/process/0.32 Standard @Snapmaker J1 (0.8 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.32 Standard @Snapmaker J1 (0.8 nozzle).json @@ -11,6 +11,7 @@ "layer_height": "0.32", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -21,5 +22,6 @@ "support_line_width": "0.82", "top_surface_line_width": "0.82", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.32 Standard @Snapmaker U1 (0.8 nozzle).json b/resources/profiles/Snapmaker/process/0.32 Standard @Snapmaker U1 (0.8 nozzle).json index 4804264bba..acfa080b98 100644 --- a/resources/profiles/Snapmaker/process/0.32 Standard @Snapmaker U1 (0.8 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.32 Standard @Snapmaker U1 (0.8 nozzle).json @@ -107,5 +107,6 @@ "500", "120", "500" - ] + ], + "top_color_penetration_layers": "4" } diff --git a/resources/profiles/Snapmaker/process/0.34 Standard @Snapmaker (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.34 Standard @Snapmaker (0.6 nozzle).json index 5c4ad7a5d5..790f8be105 100644 --- a/resources/profiles/Snapmaker/process/0.34 Standard @Snapmaker (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.34 Standard @Snapmaker (0.6 nozzle).json @@ -26,6 +26,7 @@ "layer_height": "0.34", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -47,5 +48,6 @@ "support_speed": "100", "travel_speed": "110", "overhang_1_4_speed": "0", - "overhang_2_4_speed": "50" + "overhang_2_4_speed": "50", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.34 Standard @Snapmaker Artisan (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.34 Standard @Snapmaker Artisan (0.6 nozzle).json index 352f0b751f..ece3699a4d 100644 --- a/resources/profiles/Snapmaker/process/0.34 Standard @Snapmaker Artisan (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.34 Standard @Snapmaker Artisan (0.6 nozzle).json @@ -11,6 +11,7 @@ "layer_height": "0.34", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -21,5 +22,6 @@ "support_line_width": "0.82", "top_surface_line_width": "0.82", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.34 Standard @Snapmaker J1 (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.34 Standard @Snapmaker J1 (0.6 nozzle).json index 8686fac739..aca67c2ca1 100644 --- a/resources/profiles/Snapmaker/process/0.34 Standard @Snapmaker J1 (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.34 Standard @Snapmaker J1 (0.6 nozzle).json @@ -11,6 +11,7 @@ "layer_height": "0.34", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -21,5 +22,6 @@ "support_line_width": "0.82", "top_surface_line_width": "0.82", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.36 Standard @Snapmaker (0.8 nozzle).json b/resources/profiles/Snapmaker/process/0.36 Standard @Snapmaker (0.8 nozzle).json index 9e9cb83680..19c77ca822 100644 --- a/resources/profiles/Snapmaker/process/0.36 Standard @Snapmaker (0.8 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.36 Standard @Snapmaker (0.8 nozzle).json @@ -26,6 +26,7 @@ "layer_height": "0.36", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -48,5 +49,6 @@ "overhang_1_4_speed": "0", "overhang_2_4_speed": "50", "overhang_3_4_speed": "25", - "overhang_4_4_speed": "5" + "overhang_4_4_speed": "5", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.36 Standard @Snapmaker Artisan (0.8 nozzle).json b/resources/profiles/Snapmaker/process/0.36 Standard @Snapmaker Artisan (0.8 nozzle).json index 4357e58d05..9f254f8006 100644 --- a/resources/profiles/Snapmaker/process/0.36 Standard @Snapmaker Artisan (0.8 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.36 Standard @Snapmaker Artisan (0.8 nozzle).json @@ -11,6 +11,7 @@ "layer_height": "0.36", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -21,5 +22,6 @@ "support_line_width": "0.82", "top_surface_line_width": "0.82", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.36 Standard @Snapmaker J1 (0.8 nozzle).json b/resources/profiles/Snapmaker/process/0.36 Standard @Snapmaker J1 (0.8 nozzle).json index bedb42aed1..5becfb6916 100644 --- a/resources/profiles/Snapmaker/process/0.36 Standard @Snapmaker J1 (0.8 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.36 Standard @Snapmaker J1 (0.8 nozzle).json @@ -11,6 +11,7 @@ "layer_height": "0.36", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -21,5 +22,6 @@ "support_line_width": "0.82", "top_surface_line_width": "0.82", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.36 Standard @Snapmaker U1 (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.36 Standard @Snapmaker U1 (0.6 nozzle).json index b8231f6dd1..e8b6f5931a 100644 --- a/resources/profiles/Snapmaker/process/0.36 Standard @Snapmaker U1 (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.36 Standard @Snapmaker U1 (0.6 nozzle).json @@ -105,5 +105,6 @@ "500", "120", "500" - ] + ], + "top_color_penetration_layers": "4" } diff --git a/resources/profiles/Snapmaker/process/0.38 Standard @Snapmaker (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.38 Standard @Snapmaker (0.6 nozzle).json index 79d8086f1a..cbe561d7a5 100644 --- a/resources/profiles/Snapmaker/process/0.38 Standard @Snapmaker (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.38 Standard @Snapmaker (0.6 nozzle).json @@ -26,6 +26,7 @@ "layer_height": "0.38", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -46,5 +47,6 @@ "support_interface_speed": "35", "support_speed": "100", "overhang_1_4_speed": "0", - "overhang_2_4_speed": "50" + "overhang_2_4_speed": "50", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.38 Standard @Snapmaker Artisan (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.38 Standard @Snapmaker Artisan (0.6 nozzle).json index e65f9dd631..422d997295 100644 --- a/resources/profiles/Snapmaker/process/0.38 Standard @Snapmaker Artisan (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.38 Standard @Snapmaker Artisan (0.6 nozzle).json @@ -11,6 +11,7 @@ "layer_height": "0.38", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -21,5 +22,6 @@ "support_line_width": "0.82", "top_surface_line_width": "0.82", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.38 Standard @Snapmaker J1 (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.38 Standard @Snapmaker J1 (0.6 nozzle).json index 198a83b1fd..a5f683f629 100644 --- a/resources/profiles/Snapmaker/process/0.38 Standard @Snapmaker J1 (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.38 Standard @Snapmaker J1 (0.6 nozzle).json @@ -11,6 +11,7 @@ "layer_height": "0.38", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -21,5 +22,6 @@ "support_line_width": "0.82", "top_surface_line_width": "0.82", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.40 Standard @Snapmaker (0.8 nozzle).json b/resources/profiles/Snapmaker/process/0.40 Standard @Snapmaker (0.8 nozzle).json index 05205f3a8e..d67e80cf53 100644 --- a/resources/profiles/Snapmaker/process/0.40 Standard @Snapmaker (0.8 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.40 Standard @Snapmaker (0.8 nozzle).json @@ -25,6 +25,7 @@ ], "layer_height": "0.4", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -48,5 +49,6 @@ "overhang_4_4_speed": "5", "ironing_speed": "30", "support_interface_speed": "35", - "support_speed": "100" + "support_speed": "100", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.40 Standard @Snapmaker Artisan (0.8 nozzle).json b/resources/profiles/Snapmaker/process/0.40 Standard @Snapmaker Artisan (0.8 nozzle).json index d90fa0aaad..0d7655407a 100644 --- a/resources/profiles/Snapmaker/process/0.40 Standard @Snapmaker Artisan (0.8 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.40 Standard @Snapmaker Artisan (0.8 nozzle).json @@ -10,6 +10,7 @@ ], "layer_height": "0.4", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -21,5 +22,6 @@ "top_surface_line_width": "0.82", "wall_loops": "2", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.40 Standard @Snapmaker J1 (0.8 nozzle).json b/resources/profiles/Snapmaker/process/0.40 Standard @Snapmaker J1 (0.8 nozzle).json index cb3557bc22..6fd267e41c 100644 --- a/resources/profiles/Snapmaker/process/0.40 Standard @Snapmaker J1 (0.8 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.40 Standard @Snapmaker J1 (0.8 nozzle).json @@ -10,6 +10,7 @@ ], "layer_height": "0.4", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -21,5 +22,6 @@ "top_surface_line_width": "0.82", "wall_loops": "2", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.42 Draft @Snapmaker (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.42 Draft @Snapmaker (0.6 nozzle).json index 64c0394ee6..ea5c6b965d 100644 --- a/resources/profiles/Snapmaker/process/0.42 Draft @Snapmaker (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.42 Draft @Snapmaker (0.6 nozzle).json @@ -26,6 +26,7 @@ "layer_height": "0.42", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.62", "outer_wall_line_width": "0.62", @@ -46,5 +47,6 @@ "overhang_2_4_speed": "50", "ironing_speed": "30", "support_interface_speed": "35", - "support_speed": "100" + "support_speed": "100", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.42 Draft @Snapmaker Artisan (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.42 Draft @Snapmaker Artisan (0.6 nozzle).json index 372be18eb8..f76579de23 100644 --- a/resources/profiles/Snapmaker/process/0.42 Draft @Snapmaker Artisan (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.42 Draft @Snapmaker Artisan (0.6 nozzle).json @@ -11,6 +11,7 @@ "layer_height": "0.42", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.62", "outer_wall_line_width": "0.62", @@ -21,5 +22,6 @@ "support_line_width": "0.62", "top_surface_line_width": "0.62", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.42 Draft @Snapmaker J1 (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.42 Draft @Snapmaker J1 (0.6 nozzle).json index 4b8949cc9e..482aba7afe 100644 --- a/resources/profiles/Snapmaker/process/0.42 Draft @Snapmaker J1 (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.42 Draft @Snapmaker J1 (0.6 nozzle).json @@ -11,6 +11,7 @@ "layer_height": "0.42", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.62", "outer_wall_line_width": "0.62", @@ -21,5 +22,6 @@ "support_line_width": "0.62", "top_surface_line_width": "0.62", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.42 Standard @Snapmaker U1 (0.6 nozzle).json b/resources/profiles/Snapmaker/process/0.42 Standard @Snapmaker U1 (0.6 nozzle).json index 3c6d1e38f5..2617a330ef 100644 --- a/resources/profiles/Snapmaker/process/0.42 Standard @Snapmaker U1 (0.6 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.42 Standard @Snapmaker U1 (0.6 nozzle).json @@ -105,5 +105,6 @@ "500", "120", "500" - ] + ], + "top_color_penetration_layers": "4" } diff --git a/resources/profiles/Snapmaker/process/0.48 Draft @Snapmaker (0.8 nozzle).json b/resources/profiles/Snapmaker/process/0.48 Draft @Snapmaker (0.8 nozzle).json index 9407cacd15..1ab3010d2a 100644 --- a/resources/profiles/Snapmaker/process/0.48 Draft @Snapmaker (0.8 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.48 Draft @Snapmaker (0.8 nozzle).json @@ -27,6 +27,7 @@ "initial_layer_print_height": "0.4", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -49,5 +50,6 @@ "overhang_4_4_speed": "5", "ironing_speed": "30", "support_interface_speed": "35", - "support_speed": "100" + "support_speed": "100", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.48 Draft @Snapmaker Artisan (0.8 nozzle).json b/resources/profiles/Snapmaker/process/0.48 Draft @Snapmaker Artisan (0.8 nozzle).json index 55a73e7e6c..1e7c5c5f93 100644 --- a/resources/profiles/Snapmaker/process/0.48 Draft @Snapmaker Artisan (0.8 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.48 Draft @Snapmaker Artisan (0.8 nozzle).json @@ -12,6 +12,7 @@ "initial_layer_print_height": "0.4", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -22,5 +23,6 @@ "support_line_width": "0.82", "top_surface_line_width": "0.82", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/0.48 Draft @Snapmaker J1 (0.8 nozzle).json b/resources/profiles/Snapmaker/process/0.48 Draft @Snapmaker J1 (0.8 nozzle).json index 7eb2426f70..0d4c86bf24 100644 --- a/resources/profiles/Snapmaker/process/0.48 Draft @Snapmaker J1 (0.8 nozzle).json +++ b/resources/profiles/Snapmaker/process/0.48 Draft @Snapmaker J1 (0.8 nozzle).json @@ -12,6 +12,7 @@ "initial_layer_print_height": "0.4", "wall_loops": "2", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "bridge_speed": "30", "line_width": "0.82", "outer_wall_line_width": "0.82", @@ -22,5 +23,6 @@ "support_line_width": "0.82", "top_surface_line_width": "0.82", "initial_layer_infill_speed": "55", - "initial_layer_speed": "40" + "initial_layer_speed": "40", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1.json b/resources/profiles/Snapmaker/process/fdm_process_U1.json index 4e0d7bf6e6..dde062b62f 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1.json @@ -65,5 +65,7 @@ "prime_tower_width": "60", "xy_hole_compensation": "0", "xy_contour_compensation": "0", - "compatible_printers": [] + "compatible_printers": [], + "top_color_penetration_layers": "4", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.06_nozzle_0.2.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.06_nozzle_0.2.json index 240fd4f425..3ed77c4829 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.06_nozzle_0.2.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.06_nozzle_0.2.json @@ -8,7 +8,9 @@ "initial_layer_print_height": "0.1", "wall_loops": "4", "bottom_shell_layers": "5", + "bottom_color_penetration_layers": "3", "top_shell_layers": "7", + "top_color_penetration_layers": "5", "bridge_flow": "1", "line_width": "0.22", "outer_wall_line_width": "0.22", diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.08.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.08.json index d3a81f35f4..414a60b000 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.08.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.08.json @@ -7,7 +7,9 @@ "layer_height": "0.08", "elefant_foot_compensation": "0.15", "bottom_shell_layers": "7", + "bottom_color_penetration_layers": "3", "top_shell_layers": "9", + "top_color_penetration_layers": "5", "bridge_flow": "1", "ironing_flow": "8%", "initial_layer_speed": "50", diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.08_nozzle_0.2.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.08_nozzle_0.2.json index 41a824fa3a..521555211e 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.08_nozzle_0.2.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.08_nozzle_0.2.json @@ -8,7 +8,9 @@ "initial_layer_print_height": "0.1", "wall_loops": "4", "bottom_shell_layers": "5", + "bottom_color_penetration_layers": "3", "top_shell_layers": "7", + "top_color_penetration_layers": "5", "bridge_flow": "1", "line_width": "0.22", "outer_wall_line_width": "0.22", diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.10_nozzle_0.2.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.10_nozzle_0.2.json index 5ca58d7bd1..316d46e6f0 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.10_nozzle_0.2.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.10_nozzle_0.2.json @@ -8,7 +8,9 @@ "initial_layer_print_height": "0.1", "wall_loops": "4", "bottom_shell_layers": "5", + "bottom_color_penetration_layers": "3", "top_shell_layers": "7", + "top_color_penetration_layers": "5", "bridge_flow": "1", "line_width": "0.22", "outer_wall_line_width": "0.22", diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.12.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.12.json index 117198bfbe..0ecde2d1aa 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.12.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.12.json @@ -6,8 +6,10 @@ "instantiation": "false", "layer_height": "0.12", "bottom_shell_layers": "5", + "bottom_color_penetration_layers": "3", "elefant_foot_compensation": "0.15", "top_shell_layers": "5", + "top_color_penetration_layers": "5", "top_shell_thickness": "0.6", "bridge_flow": "1", "initial_layer_speed": "50", diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.12_nozzle_0.2.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.12_nozzle_0.2.json index 8c70dd9dee..79b929ec24 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.12_nozzle_0.2.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.12_nozzle_0.2.json @@ -8,7 +8,9 @@ "initial_layer_print_height": "0.1", "wall_loops": "4", "bottom_shell_layers": "5", + "bottom_color_penetration_layers": "3", "top_shell_layers": "7", + "top_color_penetration_layers": "5", "bridge_flow": "1", "line_width": "0.22", "outer_wall_line_width": "0.22", diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.14_nozzle_0.2.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.14_nozzle_0.2.json index 1ac42c9ffa..c9aaa108d4 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.14_nozzle_0.2.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.14_nozzle_0.2.json @@ -8,7 +8,9 @@ "initial_layer_print_height": "0.1", "wall_loops": "4", "bottom_shell_layers": "5", + "bottom_color_penetration_layers": "3", "top_shell_layers": "7", + "top_color_penetration_layers": "5", "bridge_flow": "1", "line_width": "0.22", "outer_wall_line_width": "0.22", diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.16.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.16.json index a93ca21a57..038823aaca 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.16.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.16.json @@ -7,7 +7,9 @@ "layer_height": "0.16", "elefant_foot_compensation": "0.15", "bottom_shell_layers": "4", + "bottom_color_penetration_layers": "3", "top_shell_layers": "6", + "top_color_penetration_layers": "5", "top_shell_thickness": "1.0", "bridge_flow": "1", "initial_layer_speed": "50", diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.18_nozzle_0.6.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.18_nozzle_0.6.json index f4725a73c7..9ddf4fa333 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.18_nozzle_0.6.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.18_nozzle_0.6.json @@ -22,5 +22,7 @@ "bridge_speed": "30", "overhang_3_4_speed": "15", "support_top_z_distance": "0.18", - "support_bottom_z_distance": "0.18" + "support_bottom_z_distance": "0.18", + "top_color_penetration_layers": "3", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.20.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.20.json index 34a8212b3f..f7f85a53b6 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.20.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.20.json @@ -14,5 +14,7 @@ "sparse_infill_speed": "270", "internal_solid_infill_speed": "250", "gap_infill_speed": "250", - "top_shell_layers": "5" + "top_shell_layers": "5", + "top_color_penetration_layers": "5", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.24.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.24.json index 03c817db34..ccbcb8ebd2 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.24.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.24.json @@ -17,5 +17,7 @@ "internal_solid_infill_speed": "230", "gap_infill_speed": "230", "support_threshold_angle": "35", - "top_shell_layers": "4" + "top_shell_layers": "4", + "top_color_penetration_layers": "4", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.24_nozzle_0.6.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.24_nozzle_0.6.json index a014a375b3..43dc7830c2 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.24_nozzle_0.6.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.24_nozzle_0.6.json @@ -20,5 +20,7 @@ "sparse_infill_speed": "100", "top_surface_speed": "150", "bridge_speed": "30", - "overhang_3_4_speed": "15" + "overhang_3_4_speed": "15", + "top_color_penetration_layers": "3", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.24_nozzle_0.8.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.24_nozzle_0.8.json index e958e9a2ee..f6787070a9 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.24_nozzle_0.8.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.24_nozzle_0.8.json @@ -22,5 +22,7 @@ "top_surface_speed": "150", "bridge_speed": "30", "overhang_3_4_speed": "25", - "overhang_4_4_speed": "5" + "overhang_4_4_speed": "5", + "top_color_penetration_layers": "3", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.28.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.28.json index acd52db1be..8058c779cc 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.28.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.28.json @@ -17,5 +17,7 @@ "internal_solid_infill_speed": "200", "gap_infill_speed": "200", "support_threshold_angle": "40", - "top_shell_layers": "4" + "top_shell_layers": "4", + "top_color_penetration_layers": "4", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.30_nozzle_0.6.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.30_nozzle_0.6.json index a44a9ca05a..c5aea43483 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.30_nozzle_0.6.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.30_nozzle_0.6.json @@ -20,5 +20,7 @@ "sparse_infill_speed": "100", "top_surface_speed": "150", "bridge_speed": "30", - "overhang_3_4_speed": "15" + "overhang_3_4_speed": "15", + "top_color_penetration_layers": "3", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.32_nozzle_0.8.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.32_nozzle_0.8.json index 67d9ecdb62..c3e843e98c 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.32_nozzle_0.8.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.32_nozzle_0.8.json @@ -22,5 +22,7 @@ "top_surface_speed": "150", "bridge_speed": "30", "overhang_3_4_speed": "25", - "overhang_4_4_speed": "5" + "overhang_4_4_speed": "5", + "top_color_penetration_layers": "3", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.36_nozzle_0.6.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.36_nozzle_0.6.json index 314965b603..2b7688f659 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.36_nozzle_0.6.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.36_nozzle_0.6.json @@ -20,5 +20,7 @@ "sparse_infill_speed": "100", "top_surface_speed": "150", "bridge_speed": "30", - "overhang_3_4_speed": "15" + "overhang_3_4_speed": "15", + "top_color_penetration_layers": "3", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.40_nozzle_0.8.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.40_nozzle_0.8.json index ec19b56fa5..8dcad4e2e6 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.40_nozzle_0.8.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.40_nozzle_0.8.json @@ -22,5 +22,7 @@ "top_surface_speed": "150", "bridge_speed": "30", "overhang_3_4_speed": "25", - "overhang_4_4_speed": "5" + "overhang_4_4_speed": "5", + "top_color_penetration_layers": "3", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.42_nozzle_0.6.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.42_nozzle_0.6.json index 18c1e7d79b..1836edeb73 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.42_nozzle_0.6.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.42_nozzle_0.6.json @@ -20,5 +20,7 @@ "sparse_infill_speed": "100", "top_surface_speed": "150", "bridge_speed": "30", - "overhang_3_4_speed": "15" + "overhang_3_4_speed": "15", + "top_color_penetration_layers": "3", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.48_nozzle_0.8.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.48_nozzle_0.8.json index 8d5632b790..c5bf5c6457 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.48_nozzle_0.8.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.48_nozzle_0.8.json @@ -22,5 +22,7 @@ "top_surface_speed": "150", "bridge_speed": "30", "overhang_3_4_speed": "25", - "overhang_4_4_speed": "5" + "overhang_4_4_speed": "5", + "top_color_penetration_layers": "3", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_0.56_nozzle_0.8.json b/resources/profiles/Snapmaker/process/fdm_process_U1_0.56_nozzle_0.8.json index 7a5c92932d..16e949c0e4 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_0.56_nozzle_0.8.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_0.56_nozzle_0.8.json @@ -22,5 +22,7 @@ "top_surface_speed": "150", "bridge_speed": "30", "overhang_3_4_speed": "25", - "overhang_4_4_speed": "5" + "overhang_4_4_speed": "5", + "top_color_penetration_layers": "3", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/fdm_process_U1_common.json b/resources/profiles/Snapmaker/process/fdm_process_U1_common.json index 3fbacd5f4f..e0270d1989 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_U1_common.json +++ b/resources/profiles/Snapmaker/process/fdm_process_U1_common.json @@ -7,6 +7,7 @@ "max_travel_detour_distance": "0", "bottom_surface_pattern": "monotonic", "bottom_shell_layers": "3", + "bottom_color_penetration_layers": "3", "bottom_shell_thickness": "0", "bridge_speed": "50", "brim_object_gap": "0.1", @@ -62,6 +63,7 @@ "top_surface_acceleration": "2000", "top_surface_speed": "200", "top_shell_layers": "3", + "top_color_penetration_layers": "3", "top_shell_thickness": "0.8", "travel_speed": "500", "enable_prime_tower": "1", diff --git a/resources/profiles/Snapmaker/process/fdm_process_a400.json b/resources/profiles/Snapmaker/process/fdm_process_a400.json index f8ca481f9f..8e6ea65ee0 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_a400.json +++ b/resources/profiles/Snapmaker/process/fdm_process_a400.json @@ -32,5 +32,7 @@ "support_interface_top_layers": "3", "support_interface_pattern": "rectilinear", "small_perimeter_threshold": "0", - "support_material_synchronize_layers": "1" + "support_material_synchronize_layers": "1", + "top_color_penetration_layers": "4", + "bottom_color_penetration_layers": "3" } diff --git a/resources/profiles/Snapmaker/process/fdm_process_common.json b/resources/profiles/Snapmaker/process/fdm_process_common.json index 13e5825ebd..86c3ded508 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_common.json +++ b/resources/profiles/Snapmaker/process/fdm_process_common.json @@ -57,9 +57,11 @@ "detect_thin_wall": "0", "top_surface_pattern": "monotonic", "top_shell_layers": "4", + "top_color_penetration_layers": "4", "top_shell_thickness": "0.8", "bottom_surface_pattern": "monotonic", "bottom_shell_layers": "3", + "bottom_color_penetration_layers": "3", "bottom_shell_thickness": "0", "sparse_infill_density": "15%", "sparse_infill_pattern": "cubic", diff --git a/resources/profiles/Snapmaker/process/fdm_process_idex.json b/resources/profiles/Snapmaker/process/fdm_process_idex.json index 6aeabfdaa7..5e30212c97 100644 --- a/resources/profiles/Snapmaker/process/fdm_process_idex.json +++ b/resources/profiles/Snapmaker/process/fdm_process_idex.json @@ -38,5 +38,7 @@ "preheat_time": "90", "filename_format": "{input_filename_base}_{layer_height}mm_{print_time}_J1.gcode", "small_perimeter_threshold": "0", - "support_material_synchronize_layers": "1" + "support_material_synchronize_layers": "1", + "top_color_penetration_layers": "4", + "bottom_color_penetration_layers": "3" } diff --git a/resources/shaders/140/gouraud.fs b/resources/shaders/140/gouraud.fs index f609495597..0c9011d634 100644 --- a/resources/shaders/140/gouraud.fs +++ b/resources/shaders/140/gouraud.fs @@ -40,6 +40,10 @@ uniform SlopeDetection slope; //BBS: add outline_color uniform bool is_outline; +// ORCA: a part of a translucent filament, drawn as its print would show in premultiplied color, see +// GLVolumeCollection::render(). It catches a highlight only with translucent_gloss, in realistic view. +uniform bool translucent_filament; +uniform bool translucent_gloss; // The outline is a per-fragment discard mask, which the framebuffer MSAA cannot smooth, so the // silhouette is resolved per sample from a multisample copy of the outlined model's depth buffer. #ifdef GL_ARB_texture_multisample @@ -224,6 +228,14 @@ float shadow_shade() return 1.0 - shadow_intensity * (sum / 25.0); } +// ORCA: the view ray crosses two shells of the part, the front and the back one, of two 0.45 mm walls each, +// longer at grazing angles, and the opacity of the filament is that of 0.4 mm of it, as in the G-code preview. +vec4 translucent_filament_color(vec3 diffuse, float alpha, vec3 highlight, float cos_view) +{ + float a = 1.0 - pow(1.0 - alpha, 2.0 * 0.9 / 0.4 / max(cos_view, 0.25)); + return vec4(diffuse * a + highlight, a); +} + out vec4 out_color; void main() @@ -285,11 +297,16 @@ void main() if (s < 0.01) discard; out_color = vec4(mix(color.rgb, getBackfaceColor(color.rgb), s), color.a); + if (translucent_filament) + out_color.rgb *= out_color.a; } #ifdef ENABLE_ENVIRONMENT_MAP else if (use_environment_tex) out_color = vec4((0.45 * texture(environment_tex, normalize(eye_normal).xy * 0.5 + 0.5).xyz + 0.8 * color.rgb * intensity.x) * shade, color.a); #endif + else if (translucent_filament) + out_color = translucent_filament_color(color.rgb * intensity.x * shade, color.a, + translucent_gloss ? vec3(intensity.y * shade) : ZERO, abs(normalize(eye_normal).z)); else out_color = vec4((vec3(intensity.y) + color.rgb * intensity.x) * shade, color.a); } \ No newline at end of file diff --git a/resources/shaders/140/phong.fs b/resources/shaders/140/phong.fs index 4cfae1e03e..c0cbc1c144 100644 --- a/resources/shaders/140/phong.fs +++ b/resources/shaders/140/phong.fs @@ -55,6 +55,10 @@ uniform SlopeDetection slope; //BBS: add outline_color uniform bool is_outline; +// ORCA: a part of a translucent filament, drawn as its print would show in premultiplied color, see +// GLVolumeCollection::render(). It catches a highlight only with translucent_gloss, in realistic view. +uniform bool translucent_filament; +uniform bool translucent_gloss; // The outline is a per-fragment discard mask, which the framebuffer MSAA cannot smooth, so the // silhouette is resolved per sample from a multisample copy of the outlined model's depth buffer. #ifdef GL_ARB_texture_multisample @@ -98,6 +102,14 @@ in float world_normal_z; in vec3 eye_normal; in vec3 eye_position; +// ORCA: the view ray crosses two shells of the part, the front and the back one, of two 0.45 mm walls each, +// longer at grazing angles, and the opacity of the filament is that of 0.4 mm of it, as in the G-code preview. +vec4 translucent_filament_color(vec3 diffuse, float alpha, vec3 highlight, float cos_view) +{ + float a = 1.0 - pow(1.0 - alpha, 2.0 * 0.9 / 0.4 / max(cos_view, 0.25)); + return vec4(diffuse * a + highlight, a); +} + out vec4 out_color; vec3 getBackfaceColor(vec3 fill) { @@ -359,11 +371,17 @@ void main() if (s < 0.01) discard; out_color = vec4(mix(shaded_color.rgb, getBackfaceColor(shaded_color.rgb), s), shaded_color.a); + if (translucent_filament) + out_color.rgb *= out_color.a; } #ifdef ENABLE_ENVIRONMENT_MAP else if (use_environment_tex) out_color = vec4(clamp((0.45 * texture(environment_tex, normalize(eye_normal).xy * 0.5 + 0.5).xyz + window_reflection + 0.8 * color.rgb * diffuse) * PHONG_BRIGHTNESS * shade, vec3(0.0), vec3(1.0)), color.a); #endif + else if (translucent_filament) + out_color = translucent_filament_color(clamp(color.rgb * diffuse * PHONG_BRIGHTNESS * shade, vec3(0.0), vec3(1.0)), color.a, + translucent_gloss ? (vec3(specular) + window_reflection) * PHONG_BRIGHTNESS * shade : ZERO, + abs(dot(normal, view_dir))); else out_color = vec4(clamp(lit * shade, vec3(0.0), vec3(1.0)), color.a); } \ No newline at end of file diff --git a/scripts/flatpak/entrypoint b/scripts/flatpak/entrypoint index 7137c3798d..172b66c1f0 100644 --- a/scripts/flatpak/entrypoint +++ b/scripts/flatpak/entrypoint @@ -8,4 +8,38 @@ # while preserving the user's language/locale for translations. export LC_NUMERIC=C +# The runtime only has the locales of the languages Flatpak installs for it +# (flatpak config languages / extra-languages), while the session can name +# others, e.g. per-category regional formats. OrcaSlicer cannot start when any +# category names a missing locale, so drop just the variables that do: a +# category then follows LANG, and LANG falls back to C.UTF-8. An environment +# whose locales all exist is left as it is. +locale_missing() { + # glibc's locale reports each category it cannot set; LANGUAGE=C keeps the + # message untranslated. Without the tool nothing is reported. + env LANGUAGE=C "$@" locale 2>&1 >/dev/null | grep -q "Cannot set LC_" +} +repair_locale() { + # libstdc++ also accepts a composite LC_ALL ("LC_CTYPE=...;LC_NUMERIC=..."), + # which glibc and so the check reject; leave such a setup alone. + case ${LC_ALL-} in *=*) return ;; esac + locale_missing || return + languages= + for var in LC_ALL LANG LC_CTYPE LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES \ + LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT LC_IDENTIFICATION; do + eval "value=\${$var-}" + [ -n "$value" ] && locale_missing LC_ALL="$value" || continue + unset "$var" 2>/dev/null + echo "OrcaSlicer: $var=$value is not available in the Flatpak runtime and is ignored." >&2 + # The hint names the language, e.g. "de" for de_DE.UTF-8. + lang=${value%%[_.@]*} + case $lang in [a-z][a-z]|[a-z][a-z][a-z]) ;; *) continue ;; esac + case ";$languages;" in *";$lang;"*) ;; *) languages="${languages:+$languages;}$lang" ;; esac + done + [ -n "${LANG-}" ] || export LANG=C.UTF-8 + [ -z "$languages" ] || echo "OrcaSlicer: to install it, add \"$languages\" to Flatpak's extra-languages" \ + "(or to languages, if set) with 'flatpak config' (--user for a per-user install), then run 'flatpak update'." >&2 +} +repair_locale + exec /app/bin/orca-slicer "$@" diff --git a/src/OrcaSlicer.cpp b/src/OrcaSlicer.cpp index 67ee7c8ec4..2bf5cb4825 100644 --- a/src/OrcaSlicer.cpp +++ b/src/OrcaSlicer.cpp @@ -2730,10 +2730,24 @@ int CLI::run(int argc, char **argv) fetch_compatible_values = true; } + // A project whose different_settings_to_system is missing or empty in every entry does not say which of its + // values were changed: the GUI saves it that way when its presets match their parents, but also when it cannot + // find those parents. Only --uptodate then replaces the stored values with system ones. + const bool refresh_unlisted = up_config_to_date || std::any_of(current_different_settings.begin(), current_different_settings.end(), + [](const std::string &keys) { return !keys.empty(); }); + // Refresh every project filament no loaded filament replaces from its current system preset, as the GUI // does when it loads the project; the filament merge below keeps the keys the project lists as changed. + // Without refresh_unlisted it keeps every key the project has except filament_extruder_variant, whose + // system layout the kept values are mapped onto. // Entries stay in slot order, which the merge's variant bookkeeping relies on. std::vector load_filaments_refresh(load_filaments_config.size(), false); + std::set project_keys; + if (!refresh_unlisted) { + for (const std::string &key : m_print_config.keys()) + project_keys.insert(key); + project_keys.erase("filament_extruder_variant"); + } if (is_bbl_3mf && new_printer_name.empty()) { const ConfigOptionStrings *project_filament_ids = m_print_config.option("filament_ids"); for (size_t index = 0; index < current_filaments_system_name.size(); index++) { @@ -3107,8 +3121,8 @@ int CLI::run(int argc, char **argv) // Load the project's printer and process settings as the GUI loads its presets: over the default preset, // with every key the project does not list as changed, including keys saved before an option existed, - // taken from its current system preset. - auto load_project_preset = [this, &ensure_system_preset_resolver, ¤t_different_settings, filament_count](const std::string &system_name, Preset::Type type) { + // taken from its current system preset. Without refresh_unlisted the project only gets the keys it lacks. + auto load_project_preset = [this, &ensure_system_preset_resolver, ¤t_different_settings, refresh_unlisted, filament_count](const std::string &system_name, Preset::Type type) { if (system_name.empty()) return; // Preset bookkeeping the CLI keeps in its own groups, e.g. inherits_group and print_compatible_printers. @@ -3131,7 +3145,7 @@ int CLI::run(int argc, char **argv) for (const std::string &key : keys) { const ConfigOption *opt = config.option(key); const ConfigOption *old = m_print_config.option(key); - if (bookkeeping_keys.count(key) != 0 || opt == nullptr || (old != nullptr && *old == *opt)) + if (bookkeeping_keys.count(key) != 0 || opt == nullptr || (old != nullptr && (!refresh_unlisted || *old == *opt))) continue; BOOST_LOG_TRIVIAL(info) << boost::format("CLI: %1% from '%2%': %3% -> %4%") % key % system_name % (old ? old->serialize() : std::string("(missing)")) % opt->serialize(); m_print_config.set_key_value(key, opt->clone()); @@ -3517,6 +3531,8 @@ int CLI::run(int argc, char **argv) int filament_index = load_filaments_index[index]; // A filament given with --load-filaments replaces the slot; a refreshed one keeps the project's changed keys. const bool loaded = load_filament_count > 0 && !load_filaments_refresh[index]; + // A refreshed filament of a project that lists no changed settings keeps every key it has. + const bool keep_project = load_filaments_refresh[index] && !refresh_unlisted; std::vector different_keys; //ORCA: diff before load_default_gcodes_to_config, the way the process and machine @@ -3544,6 +3560,8 @@ int CLI::run(int argc, char **argv) different_settings[filament_index] = filament_different_settings; inherits_group[filament_index] = load_filaments_inherit[index]; } + else if (keep_project) + different_keys.assign(project_keys.begin(), project_keys.end()); else { std::string diff_settings; @@ -3637,7 +3655,8 @@ int CLI::run(int argc, char **argv) // destination to the filament's slot first (set_with_restore_2 only restores). if (opt_vec_src->size() > 0 && opt_vec_dst->size() < size_t(old_start_indice[filament_index - 1] + old_variant_count)) opt_vec_dst->resize(size_t(old_start_indice[filament_index - 1] + old_variant_count), opt_vec_src); - opt_vec_dst->set_with_restore_2(opt_vec_src, new_variant_indice, old_start_indice[filament_index - 1], old_variant_count); + // A kept key is padded like a refreshed one below rather than failing the run. + opt_vec_dst->set_with_restore_2(opt_vec_src, new_variant_indice, old_start_indice[filament_index - 1], old_variant_count, keep_project); } catch (const std::exception &ex) { // Was an uncaught abort BOOST_LOG_TRIVIAL(error) << boost::format("filament %1%: option %2% could not be applied: %3%") % filament_index % opt_key % ex.what(); boost::nowide::cerr << "filament " << filament_index << ": option " << opt_key << " could not be applied: " << ex.what() << std::endl; @@ -3740,7 +3759,7 @@ int CLI::run(int argc, char **argv) } } - if (diff_keys_size != different_keys_set.size()) { + if (!keep_project && diff_keys_size != different_keys_set.size()) { //changed different_keys.clear(); @@ -3756,8 +3775,21 @@ int CLI::run(int argc, char **argv) for (size_t index = 0; index < load_filaments_config.size(); index++) if (load_filaments_index[index] >= 1 && load_filaments_index[index] <= filament_count) filament_configs[load_filaments_index[index] - 1] = &load_filaments_config[index]; - if (std::find(filament_configs.begin(), filament_configs.end(), nullptr) == filament_configs.end()) - set_filament_dev_options(m_print_config, filament_configs); + // Without refresh_unlisted and with no filament loaded from a file, only the keys the project lacks are + // filled, with the option defaults for a filament that has no system preset. A loaded filament still + // replaces them all. + if (refresh_unlisted || std::find(load_filaments_refresh.begin(), load_filaments_refresh.end(), false) != load_filaments_refresh.end()) { + if (std::find(filament_configs.begin(), filament_configs.end(), nullptr) == filament_configs.end()) + set_filament_dev_options(m_print_config, filament_configs); + } else { + const DynamicPrintConfig no_preset; + std::replace(filament_configs.begin(), filament_configs.end(), static_cast(nullptr), &no_preset); + DynamicPrintConfig dev_config; + set_filament_dev_options(dev_config, filament_configs); + for (const std::string &key : dev_config.keys()) + if (project_keys.count(key) == 0) + m_print_config.set_key_value(key, dev_config.option(key)->clone()); + } if (m_print_config.option("filament_extruder_variant")) { std::vector& filament_self_indice = m_print_config.option("filament_self_index", true)->values; diff --git a/src/libslic3r/AppConfig.cpp b/src/libslic3r/AppConfig.cpp index 0d62d6c553..5ec97c347a 100644 --- a/src/libslic3r/AppConfig.cpp +++ b/src/libslic3r/AppConfig.cpp @@ -242,6 +242,14 @@ void AppConfig::set_defaults() set("preview_dim_previous_layers_brightness", std::to_string(std::max(0, std::min(brightness, 99)))); } + // ORCA: whether the G-code preview keeps the opacity of the filament colors + if (get("preview_translucent_filaments").empty()) + set_bool("preview_translucent_filaments", true); + + // ORCA: whether realistic view gives the opaque toolpaths a glossy highlight + if (get(SETTING_OPENGL_REALISTIC_GLOSS).empty()) + set_bool(SETTING_OPENGL_REALISTIC_GLOSS, true); + // ORCA: view type the G-code preview opens with. "auto" keeps the automatic choice (Filament for // multi material prints, Line Type for single material ones), "last" restores the view type the user // picked last, any other value is a fixed view type name, see GCodeViewer::view_type_to_config_name(). diff --git a/src/libslic3r/AppConfig.hpp b/src/libslic3r/AppConfig.hpp index 61dceda87a..1e35df6999 100644 --- a/src/libslic3r/AppConfig.hpp +++ b/src/libslic3r/AppConfig.hpp @@ -48,6 +48,7 @@ #define SETTING_OPENGL_PHONG_SSAO "opengl_phong_ssao" #define SETTING_OPENGL_PHONG_SMOOTH_NORMALS "opengl_phong_smooth_normals" #define SETTING_OPENGL_REALISTIC_PREVIEW "opengl_realistic_preview" +#define SETTING_OPENGL_REALISTIC_GLOSS "opengl_realistic_gloss" #define SETTING_PLUGIN_PAGES_VISIBLE_COUNT "plugin_pages_visible_count" #define PLUGIN_PAGES_VISIBLE_COUNT_MIN 1 diff --git a/src/libslic3r/CMakeLists.txt b/src/libslic3r/CMakeLists.txt index f9866cf09f..fd89ad78dc 100644 --- a/src/libslic3r/CMakeLists.txt +++ b/src/libslic3r/CMakeLists.txt @@ -287,6 +287,8 @@ set(lisbslic3r_sources GCode/RetractWhenCrossingPerimeters.hpp GCode/SeamPlacer.cpp GCode/SeamPlacer.hpp + GCode/SeamContour.cpp + GCode/SeamContour.hpp GCode/PreciseSeam.cpp GCode/PreciseSeam.hpp GCode/PreciseSeamInternal.hpp diff --git a/src/libslic3r/ExtrusionEntity.hpp b/src/libslic3r/ExtrusionEntity.hpp index d7dac99364..73e06d7d45 100644 --- a/src/libslic3r/ExtrusionEntity.hpp +++ b/src/libslic3r/ExtrusionEntity.hpp @@ -156,13 +156,19 @@ public: virtual double length() const = 0; virtual double total_volume() const = 0; - // Orca: Used for inner/outer/inner mode - classic perimeter generator + // Orca: Wall index set by the perimeter generators, 0 for the outer wall, -1 if unset int inset_idx = -1; static std::string role_to_string(ExtrusionRole role); static ExtrusionRole string_to_role(const std::string_view role); }; +// Orca: Overhang paths share one role on every wall, so the inset index tells inner walls apart where set. +inline bool is_inner_wall(const ExtrusionEntity &entity) +{ + return entity.inset_idx >= 0 ? entity.inset_idx > 0 : entity.role() == erPerimeter; +} + typedef std::vector ExtrusionEntitiesPtr; class ExtrusionPath : public ExtrusionEntity @@ -395,21 +401,23 @@ public: ExtrusionPaths paths; ExtrusionMultiPath() {} - ExtrusionMultiPath(const ExtrusionMultiPath &rhs) : paths(rhs.paths), m_can_reverse(rhs.m_can_reverse) {} - ExtrusionMultiPath(ExtrusionMultiPath &&rhs) : paths(std::move(rhs.paths)), m_can_reverse(rhs.m_can_reverse) {} + ExtrusionMultiPath(const ExtrusionMultiPath &rhs) : ExtrusionEntity(rhs), paths(rhs.paths), m_can_reverse(rhs.m_can_reverse) {} + ExtrusionMultiPath(ExtrusionMultiPath &&rhs) : ExtrusionEntity(rhs), paths(std::move(rhs.paths)), m_can_reverse(rhs.m_can_reverse) {} ExtrusionMultiPath(const ExtrusionPaths &paths) : paths(paths) {} ExtrusionMultiPath(const ExtrusionPath &path) {this->paths.push_back(path); m_can_reverse = path.can_reverse(); } ExtrusionMultiPath &operator=(const ExtrusionMultiPath &rhs) { - this->paths = rhs.paths; - m_can_reverse = rhs.m_can_reverse; + this->paths = rhs.paths; + m_can_reverse = rhs.m_can_reverse; + this->inset_idx = rhs.inset_idx; return *this; } ExtrusionMultiPath &operator=(ExtrusionMultiPath &&rhs) { - this->paths = std::move(rhs.paths); - m_can_reverse = rhs.m_can_reverse; + this->paths = std::move(rhs.paths); + m_can_reverse = rhs.m_can_reverse; + this->inset_idx = rhs.inset_idx; return *this; } diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index 158e92cf0a..780a7035e0 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -7187,30 +7187,23 @@ LayerResult GCode::process_layer( } }; + const auto is_inner = [](const ExtrusionEntity *entity) { return is_inner_wall(*entity); }; + const size_t inner_count = entity_type == ObjectByExtruder::Island::Region::PERIMETERS ? + std::count_if(extrusions->entities.begin(), extrusions->entities.end(), is_inner) : 0; bool split_mixed_perimeters = - entity_type == ObjectByExtruder::Island::Region::PERIMETERS && region.config().outer_wall_filament_id.value != region.config().inner_wall_filament_id.value && - extrusions->role() == erMixed; + inner_count > 0 && inner_count < extrusions->entities.size(); if (split_mixed_perimeters) { auto outer_perimeters = std::make_unique(); auto inner_perimeters = std::make_unique(); - for (const ExtrusionEntity *entity : extrusions->entities) { - const ExtrusionRole role = entity->role(); - if (role == erExternalPerimeter || role == erOverhangPerimeter) - outer_perimeters->append(*entity); - else if (role == erPerimeter) - inner_perimeters->append(*entity); - } + for (const ExtrusionEntity *entity : extrusions->entities) + (is_inner(entity) ? inner_perimeters : outer_perimeters)->append(*entity); - if (!outer_perimeters->entities.empty()) { - split_perimeter_storage.emplace_back(std::move(outer_perimeters)); - process_extrusions(split_perimeter_storage.back().get(), nullptr, false); - } - if (!inner_perimeters->entities.empty()) { - split_perimeter_storage.emplace_back(std::move(inner_perimeters)); - process_extrusions(split_perimeter_storage.back().get(), nullptr, false); - } + split_perimeter_storage.emplace_back(std::move(outer_perimeters)); + process_extrusions(split_perimeter_storage.back().get(), nullptr, false); + split_perimeter_storage.emplace_back(std::move(inner_perimeters)); + process_extrusions(split_perimeter_storage.back().get(), nullptr, false); } else { process_extrusions(extrusions, extrusions, true); } diff --git a/src/libslic3r/GCode/SeamContour.cpp b/src/libslic3r/GCode/SeamContour.cpp new file mode 100644 index 0000000000..56be005178 --- /dev/null +++ b/src/libslic3r/GCode/SeamContour.cpp @@ -0,0 +1,261 @@ +#include "SeamContour.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/AABBTreeIndirect.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r::SeamContour { +namespace { +struct Foot { + Vec2d point = Vec2d::Zero(); + double distance = std::numeric_limits::infinity(); +}; +struct Witness { + size_t contour; + double distance; + double angle_degrees; +}; +struct BoxEntry { + size_t index; + AABBTreeIndirect::Tree2d::BoundingBox box; + size_t idx() const { return index; } + const AABBTreeIndirect::Tree2d::BoundingBox &bbox() const { return box; } + Vec2d centroid() const { return box.center(); } +}; + +double box_distance(const Contour &c, const Vec2d &p) { + return ((c.min - p).cwiseMax(Vec2d::Zero()) + (p - c.max).cwiseMax(Vec2d::Zero())).norm(); +} + +Foot closest(const Contour &c, const Vec2d &p, double stop = -1.0, + const std::vector *source_normals = nullptr, double normal_cosine = 0.0) { + Foot result; + if (stop >= 0.0 && !source_normals) + for (const Vec2d &vertex : c.points) + if ((vertex - p).norm() <= stop) return {vertex, (vertex - p).norm()}; + for (size_t i = 0; i < c.points.size(); ++i) { + const Vec2d &a = c.points[i]; + const Vec2d d = c.points[(i + 1) % c.points.size()] - a; + const double length2 = d.squaredNorm(); + if (source_normals) { + if (length2 <= 1e-18) continue; + const Vec2d normal = (c.hole ? -1.0 : 1.0) * Vec2d(d.y(), -d.x()) / std::sqrt(length2); + // A thin contour's nearest opposite side must not hide its slightly farther facing side. + if (std::none_of(source_normals->begin(), source_normals->end(), [&](const Vec2d &n) { + return n.dot(normal) >= normal_cosine; + })) continue; + } + const double t = length2 > 0.0 ? std::clamp((p - a).dot(d) / length2, 0.0, 1.0) : 0.0; + const Vec2d q = a + t * d; + const double distance = (q - p).norm(); + if (distance < result.distance) result = {q, distance}; + if (result.distance <= stop) break; // A proximity certificate needs no exact closest point. + } + return result; +} + +std::vector normals(const Contour &c, const Vec2d &p) { + std::vector result; + for (size_t i = 0; i < c.points.size(); ++i) { + const Vec2d &a = c.points[i]; + const Vec2d d = c.points[(i + 1) % c.points.size()] - a; + if (d.squaredNorm() <= 1e-18) continue; + const double t = std::clamp((p - a).dot(d) / d.squaredNorm(), 0.0, 1.0); + // Every caller supplies a vertex or closest foot on this boundary; avoid a second full search. + if ((a + t * d - p).norm() <= 1e-6) { + // Candidate polygons are CCW; a hole has material on their opposite side. + const Vec2d n(d.y(), -d.x()); + result.push_back((c.hole ? -1.0 : 1.0) * n.normalized()); + } + } + return result; +} + +} // namespace + +std::vector Resolver::query(size_t layer, const Vec2d &p, double reach) const { + std::vector result; + const Vec2d margin = Vec2d::Constant(reach); + AABBTreeIndirect::traverse(m_indices[layer], + AABBTreeIndirect::intersecting(AABBTreeIndirect::Tree2d::BoundingBox(p - margin, p + margin)), + [&](const auto &node) { result.push_back(node.idx); return true; }); + // Tree traversal order must not alter tie-breaking in the existing contour predicates. + std::sort(result.begin(), result.end()); + return result; +} + +bool Resolver::in_material(size_t layer, const Vec2d &p) const { + bool inside = false; + for (size_t index : query(layer, p, 0.0)) { + const Contour &c = m_layers[layer][index]; + if (!c.reliable) continue; // select() already falls back wherever unknown geometry can affect a probe. + if ((p.array() < c.min.array()).any() || (p.array() > c.max.array()).any()) continue; + for (size_t i = 0; i < c.points.size(); ++i) { + const Vec2d &a = c.points[i], &b = c.points[(i + 1) % c.points.size()]; + if ((a.y() > p.y()) != (b.y() > p.y()) && + p.x() < a.x() + (p.y() - a.y()) * (b.x() - a.x()) / (b.y() - a.y())) + inside = !inside; + } + } + return inside; +} + +bool Resolver::near_boundary(size_t layer, const Vec2d &p, double noise) const { + for (size_t index : query(layer, p, noise)) { + const Contour &c = m_layers[layer][index]; + if (box_distance(c, p) <= noise && closest(c, p, noise).distance <= noise) return true; + } + return false; +} + +Resolver::Resolver(Layers layers, Options options, std::function throw_if_canceled) : + m_layers(std::move(layers)), m_options(options) { + m_indices.resize(m_layers.size()); + for (size_t i = 0; i < m_layers.size(); ++i) { + if (throw_if_canceled) throw_if_canceled(); // Index construction on dense objects remains cancellable. + std::vector boxes; + for (size_t j = 0; j < m_layers[i].size(); ++j) { + Contour &c = m_layers[i][j]; + c.min = Vec2d::Constant(std::numeric_limits::infinity()); + c.max = -c.min; + for (const Vec2d &p : c.points) { c.min = c.min.cwiseMin(p); c.max = c.max.cwiseMax(p); } + if (!c.points.empty()) boxes.push_back({j, AABBTreeIndirect::Tree2d::BoundingBox(c.min, c.max)}); + } + // Build once per layer; all seeds, reverse matches and material probes reuse the boxes. + m_indices[i].build(std::move(boxes)); + } +} + +Result Resolver::select(size_t layer, size_t contour, const Vec2d &p, int direction, double radius, + bool check_reverse) const { + const size_t target = size_t(ptrdiff_t(layer) + direction); + const Contour &source = m_layers[layer][contour]; + const auto &next = m_layers[target]; + const double bounds = source.nozzle * m_options.bounds_nozzle_factor; + const double noise = source.width * m_options.noise_width_factor; + const double reach = std::max({radius, bounds, noise}); + const auto candidates = query(target, p, reach); + // An open path near either end or a material probe makes the geometric restriction uncertain. + for (size_t i : query(layer, p, reach)) + if (!m_layers[layer][i].reliable) return {Outcome::None, Method::Local, {}, true}; + for (size_t i : candidates) + if (!next[i].reliable) return {Outcome::None, Method::Local, {}, true}; + std::vector fast, nearby; + for (size_t i : candidates) { + const Contour &c = next[i]; + if (c.points.size() < 3) continue; + // A wall can become a hole when an opening closes; local geometry decides that continuation. + if (box_distance(c, p) <= radius) nearby.push_back(i); + if (c.hole == source.hole && (c.min - source.min).cwiseAbs().maxCoeff() <= bounds && + (c.max - source.max).cwiseAbs().maxCoeff() <= bounds) fast.push_back(i); + } + const auto source_normals = normals(source, p); + const auto compatible_foot = [&](const Contour &c) { + // Across a type change, use the closest patch itself: another side can mimic a shifted annulus. + return closest(c, p, -1.0, c.hole == source.hole ? &source_normals : nullptr, + m_options.normal_cosine); + }; + const auto normal_agreement = [&](const Contour &c, const Vec2d &foot) { + double agreement = -1.0; + const auto target_normals = normals(c, foot); + for (const Vec2d &a : source_normals) + for (const Vec2d &b : target_normals) agreement = std::max(agreement, a.dot(b)); + return agreement; + }; + if (fast.size() == 1) { + const size_t index = fast.front(); + const Foot foot = compatible_foot(next[index]); + // Bounds alone cannot certify a wall: only a near-coincident, consistently oriented patch can. + if (foot.distance <= noise && normal_agreement(next[index], foot.point) >= m_options.normal_cosine) { + bool competing = false; + for (size_t other : nearby) { + if (other == index || box_distance(next[other], p) > noise) continue; + const Foot alternative = compatible_foot(next[other]); + if (alternative.distance <= noise && + normal_agreement(next[other], alternative.point) >= m_options.normal_cosine) { + competing = true; + break; + } + } + // A competing local wall or failed reverse match must reach the full fallback. + if (!competing) { + if (!check_reverse) return {Outcome::Unique, Method::Bounds, {index}}; + const Result back = select(target, index, foot.point, -direction, radius, false); + // An uncertain certificate must leave the entire legacy candidate set unrestricted. + if (back.uncertain) return back; + if (std::find(back.contours.begin(), back.contours.end(), contour) != back.contours.end()) + return {Outcome::Unique, Method::Bounds, {index}}; + } + } + } + std::vector witnessed; + for (size_t i : nearby) { + const Foot foot = compatible_foot(next[i]); + if (foot.distance > radius) continue; + const double agreement = normal_agreement(next[i], foot.point); + if (agreement < m_options.normal_cosine) continue; + bool band = true; + if (foot.distance > noise) { + // Three witnesses reject connectors through material (or air) shared by both layers. + for (double t : std::array{0.25, 0.5, 0.75}) { + const Vec2d probe = p + t * (foot.point - p); + if (in_material(layer, probe) == in_material(target, probe) && + !near_boundary(layer, probe, noise) && !near_boundary(target, probe, noise)) { + band = false; + break; + } + } + } + if (!band) continue; + if (check_reverse) { + const Result back = select(target, i, foot.point, -direction, radius, false); + if (back.uncertain) return back; + // Several reverse continuations are valid if they still include the source wall. + if (std::find(back.contours.begin(), back.contours.end(), contour) == back.contours.end()) continue; + } + witnessed.push_back({i, foot.distance, std::acos(std::clamp(agreement, -1.0, 1.0)) * + 180.0 / std::acos(-1.0)}); + } + Result result; + const double distance_margin = std::max(1e-6, source.width * m_options.dominance_width_factor); + const double angle_margin = std::max(1e-6, m_options.dominance_angle_degrees); + for (const Witness &candidate : witnessed) { + // A contour is discarded only with a meaningful advantage in every scored criterion. + const bool dominated = std::any_of(witnessed.begin(), witnessed.end(), [&](const Witness &other) { + return other.distance + distance_margin <= candidate.distance && + other.angle_degrees + angle_margin <= candidate.angle_degrees; + }); + if (!dominated) result.contours.push_back(candidate.contour); + } + result.outcome = result.contours.empty() ? Outcome::None : + result.contours.size() == 1 ? Outcome::Unique : Outcome::Multiple; + return result; +} + +Result Resolver::resolve(size_t layer, size_t contour, size_t vertex, int direction, double radius) const { + Result result; + if (direction != -1 && direction != 1) return result; + const Contour &source = m_layers.at(layer).at(contour); + if (!source.reliable) return {Outcome::None, Method::Local, {}, true}; + if (radius < 0.0) radius = source.width * m_options.radius_width_factor; + if (!std::isfinite(radius)) return result; + // Alternative seeds may have different widths; their actual KD search radii cannot share a cache entry. + const Key key(layer, contour, vertex, direction, radius); + const auto cached = m_cache.find(key); + if (cached != m_cache.end()) return cached->second; + const ptrdiff_t target = ptrdiff_t(layer) + direction; + if (target >= 0 && size_t(target) < m_layers.size() && source.points.size() >= 3) { + const Vec2d &p = source.points.at(vertex); + result = select(layer, contour, p, direction, radius, true); + } + m_cache.emplace(key, result); + return result; +} + +} // namespace Slic3r::SeamContour diff --git a/src/libslic3r/GCode/SeamContour.hpp b/src/libslic3r/GCode/SeamContour.hpp new file mode 100644 index 0000000000..032a8b20c6 --- /dev/null +++ b/src/libslic3r/GCode/SeamContour.hpp @@ -0,0 +1,61 @@ +#pragma once + +#include "libslic3r/Point.hpp" +#include "libslic3r/AABBTreeIndirect.hpp" +#include +#include +#include +#include +#include + +namespace Slic3r::SeamContour { + +// Geometry is immutable during string construction; finalized state is deliberately absent. +struct Contour { + std::vector points; + bool hole = false; + bool reliable = true; // Only closed extrusion loops provide a trustworthy boundary role. + double width = 0.4; + double nozzle = 0.4; + Vec2d min = Vec2d::Zero(); + Vec2d max = Vec2d::Zero(); +}; +using Layers = std::vector>; + +struct Options { + double bounds_nozzle_factor = 1.25; // One nozzle diameter plus a quarter-diameter reserve. + double radius_width_factor = 4.0; // Preserve the existing continuation radius. + double noise_width_factor = 0.125; + double normal_cosine = 0.5; // Up to 60 degrees for geometric admissibility. + double dominance_width_factor = 0.25; // Distance advantage required to discard another contour. + double dominance_angle_degrees = 5.0; // Normal agreement must also improve by this margin. +}; + +enum class Outcome { Unique, None, Multiple }; +enum class Method { Bounds, Local }; +struct Result { + Outcome outcome = Outcome::None; + Method method = Method::Local; + std::vector contours; // Empty means no geometric restriction on the legacy search. + bool uncertain = false; // Reverse checks must propagate unknown geometry, not reject one candidate. +}; + +class Resolver { +public: + explicit Resolver(Layers layers, Options options = {}, std::function throw_if_canceled = {}); + Result resolve(size_t layer, size_t contour, size_t vertex, int direction, double radius = -1.0) const; +private: + // Alternative string starts reuse the same geometric queries in both directions. + using Key = std::tuple; + Layers m_layers; + std::vector m_indices; + Options m_options; + mutable std::map m_cache; + std::vector query(size_t layer, const Vec2d &point, double reach) const; + bool in_material(size_t layer, const Vec2d &point) const; + bool near_boundary(size_t layer, const Vec2d &point, double noise) const; + Result select(size_t layer, size_t contour, const Vec2d &point, int direction, double radius, + bool check_reverse) const; +}; + +} // namespace Slic3r::SeamContour diff --git a/src/libslic3r/GCode/SeamPlacer.cpp b/src/libslic3r/GCode/SeamPlacer.cpp index c318f4f5d7..2de6be1df4 100644 --- a/src/libslic3r/GCode/SeamPlacer.cpp +++ b/src/libslic3r/GCode/SeamPlacer.cpp @@ -1,4 +1,5 @@ #include "SeamPlacer.hpp" +#include "SeamContour.hpp" #include "libslic3r/Point.hpp" #include "libslic3r/AABBTreeIndirect.hpp" @@ -16,9 +17,11 @@ #include "tbb/blocked_range.h" #include "tbb/parallel_reduce.h" #include +#include #include #include #include +#include #include #include #include @@ -318,6 +321,28 @@ struct CoordinateFunctor { } }; +// A paint boundary uses the same geometry for green preferences and red exclusions. +struct PaintedContour { + std::vector edges; + std::vector inward; + AABBTreeIndirect::Tree<3, double> tree; + + std::vector> crossings(double z, const Vec2d &min, const Vec2d &max) const { + std::vector> result; + const Eigen::AlignedBox box(Vec3d(min.x(), min.y(), z), Vec3d(max.x(), max.y(), z)); + AABBTreeIndirect::traverse(tree, AABBTreeIndirect::intersecting(box), [&](const auto &node) { + const Linef3 &edge = edges[node.idx]; + // Half-open in z counts a contour vertex on the plane once. + if ((edge.a.z() < z) != (edge.b.z() < z)) { + const Vec3d p = edge.intersect_plane(z); + result.emplace_back(p.head<2>(), inward[node.idx].template head<2>()); + } + return true; + }); + return result; + } +}; + // structure to store global information about the model - occlusion hits, enforcers, blockers struct GlobalModelInfo { TriangleSetSamples mesh_samples; @@ -328,8 +353,15 @@ struct GlobalModelInfo { indexed_triangle_set enforcers; indexed_triangle_set blockers; + // Non-green surface proves that missing paint ends do not mean full coverage. + indexed_triangle_set non_enforcers; AABBTreeIndirect::Tree<3, float> enforcers_tree; AABBTreeIndirect::Tree<3, float> blockers_tree; + AABBTreeIndirect::Tree<3, float> non_enforcers_tree; + // Contour of the painted enforcer region: edges of one enforcer triangle only, with the unit direction from + // each edge into the paint. + PaintedContour enforcer_contour; + PaintedContour blocker_contour; // Precise Seam modifiers: strong modifiers (CENTER/LEFT/RIGHT) determine exact seam placement std::vector precise_seam_strong_volumes; @@ -440,11 +472,17 @@ struct GlobalModelInfo { //Extract perimeter polygons of the given layer Polygons extract_perimeter_polygons(const Layer *layer, std::vector &corresponding_regions_out, + std::vector> &boundary_types_out, bool has_precise_seam_modifiers) { Polygons polygons; + const auto boundary_type = [](const ExtrusionEntity *entity) -> std::optional { + if (!entity->is_loop()) return std::nullopt; + return (static_cast(entity)->loop_role() & elrHole) != 0; + }; for (const LayerRegion *layer_region : layer->regions()) { for (const ExtrusionEntity *ex_entity : layer_region->perimeters.entities) { if (ex_entity->is_collection()) { //collection of inner, outer, and overhang perimeters + const size_t collection_begin = polygons.size(); // The fallback below applies per collection, not per layer. for (const ExtrusionEntity *perimeter : static_cast(ex_entity)->entities) { ExtrusionRole role = perimeter->role(); if (perimeter->is_loop()) { @@ -453,6 +491,9 @@ Polygons extract_perimeter_polygons(const Layer *layer, std::vectorinset_idx == 0) + role = ExtrusionRole::erExternalPerimeter; } if (role == ExtrusionRole::erExternalPerimeter) { @@ -460,19 +501,22 @@ Polygons extract_perimeter_polygons(const Layer *layer, std::vectorcollect_points(p); polygons.emplace_back(std::move(p)); corresponding_regions_out.push_back(layer_region); + boundary_types_out.push_back(boundary_type(perimeter)); } } - if (polygons.empty()) { + if (polygons.size() == collection_begin) { Points p; ex_entity->collect_points(p); polygons.emplace_back(std::move(p)); corresponding_regions_out.push_back(layer_region); + boundary_types_out.push_back(boundary_type(ex_entity)); } } else { Points p; ex_entity->collect_points(p); polygons.emplace_back(std::move(p)); corresponding_regions_out.push_back(layer_region); + boundary_types_out.push_back(boundary_type(ex_entity)); } } } @@ -493,18 +537,143 @@ Polygons extract_perimeter_polygons(const Layer *layer, std::vector &loop, double z, double reach, const GlobalModelInfo &info) { + if (loop.size() < 3 || info.enforcers.empty()) + return false; + if (info.non_enforcers.empty()) + return true; // Every relevant model surface is green, so paint adds no seam information. + if (reach <= enforced_end_tolerance) + return false; + Vec2d min = loop.front(), max = loop.front(); + for (const Vec2d &point : loop) { + min = min.cwiseMin(point); + max = max.cwiseMax(point); + } + // A conservative box also rejects tiny gaps and a nearby opposite unpainted wall. + const Eigen::AlignedBox box(Vec3f(float(min.x() - reach), float(min.y() - reach), float(z - reach)), + Vec3f(float(max.x() + reach), float(max.y() + reach), float(z + reach))); + bool non_green_nearby = false; + AABBTreeIndirect::traverse(info.non_enforcers_tree, AABBTreeIndirect::intersecting(box), [&](const auto &) { + non_green_nearby = true; + return false; // Stop on the first uncertain surface rather than infer a full painted ring. + }); + if (non_green_nearby) + return false; + const auto covered = [&](const auto &self, const Vec3d &a, const Vec3d &b, unsigned depth) -> bool { + const Vec3d middle = 0.5 * (a + b); + // A paint point this close to the midpoint covers the entire segment by the triangle inequality. + const double radius = reach - 0.5 * (b - a).norm() - enforced_end_tolerance; + if (radius > 0.0 && info.is_enforced(middle.cast(), float(radius))) + return true; + if (depth == 8) + return false; // A bounded proof failure preserves the existing conservative paint behavior. + return self(self, a, middle, depth + 1) && self(self, middle, b, depth + 1); + }; + for (size_t i = 0; i < loop.size(); ++i) { + const Vec2d &a = loop[i], &b = loop[(i + 1) % loop.size()]; + if (!covered(covered, Vec3d(a.x(), a.y(), z), Vec3d(b.x(), b.y(), z), 0)) + return false; + } + return true; +} + +// Painted ranges of a counterclockwise loop at height z, bounded exactly where the paint contour crosses the +// layer: each crossing within `reach` of the loop is moved to its closest loop point, and paint lies ahead of +// it or behind it along the loop. `arc` holds the length from the first vertex to each vertex, the loop length +// last. Empty if the contour does not cross near the loop or its crossings do not pair up into ranges. +std::vector exact_painted_intervals(const std::vector &loop, const std::vector &arc, + double z, double reach, const PaintedContour &contour) { + const size_t count = loop.size(); + if (count < 3 || contour.edges.empty()) + return {}; + Vec2d min = loop.front(), max = loop.front(); + for (const Vec2d &p : loop) { + min = min.cwiseMin(p); + max = max.cwiseMax(p); + } + const auto crossings = contour.crossings(z, min - Vec2d(reach, reach), max + Vec2d(reach, reach)); + // Direction of the first edge from edge i on, forward or backward, that is longer than the tolerance: loops + // repeat their first point and the shared ends of their paths. + const auto direction = [&](size_t i, bool forward) { + for (size_t step = 0; step < count; ++step, i = forward ? (i + 1) % count : (i + count - 1) % count) { + const Vec2d d = loop[(i + 1) % count] - loop[i]; + if (d.norm() >= enforced_end_tolerance) + return Vec2d(d.normalized()); + } + return Vec2d(Vec2d::Zero()); + }; + std::vector> ends; // Position along the loop; true if paint lies ahead. + for (const auto &[point, inward] : crossings) { + double best = std::numeric_limits::max(), position = 0.0; + Vec2d tangent = Vec2d::Zero(); + for (size_t i = 0; i < count; ++i) { + const Vec2d a = loop[i], ab = loop[(i + 1) % count] - a; + const double length2 = ab.squaredNorm(); + const double t = length2 > 0.0 ? std::clamp((point - a).dot(ab) / length2, 0.0, 1.0) : 0.0; + const double distance2 = (a + t * ab - point).squaredNorm(); + if (distance2 < best) { + best = distance2; + const double along = t * (arc[i + 1] - arc[i]); + position = arc[i] + along; + // At a vertex the loop turns, so its direction there is the mean of the two edges; a crossing at a + // corner may land a rounding error off the vertex, on either edge. + const size_t vertex = along < enforced_end_tolerance ? i : + arc[i + 1] - position < enforced_end_tolerance ? (i + 1) % count : + count; + tangent = vertex < count ? direction((vertex + count - 1) % count, false) + direction(vertex, true) : + direction(i, true); + } + } + if (best > reach * reach) + continue; + const double side = inward.dot(tangent); + if (std::abs(side) < 1e-6) + return {}; // The contour runs along the loop here: no clear end. + ends.emplace_back(position, side > 0.0); + } + if (ends.empty() || ends.size() % 2 != 0) + return {}; + std::sort(ends.begin(), ends.end()); + for (size_t i = 0; i < ends.size(); ++i) + if (ends[i].second == ends[(i + 1) % ends.size()].second) + return {}; // Paint must start and stop in turn along the loop. + const size_t first = ends.front().second ? 0 : 1; + std::vector intervals; + for (size_t i = first; i < first + ends.size(); i += 2) { + const double begin = ends[i % ends.size()].first; + double end = ends[(i + 1) % ends.size()].first; + if (end < begin) + end += arc.back(); + intervals.push_back({begin, end}); + } + return intervals; +} + // Build SeamCandidates for each vertex of the perimeter polygon and attach them to a shared Perimeter. // For each vertex: computes position, angle, and type (Enforcer / Blocker / Neutral). // When Precise Seam modifiers are present: inserts strong seam point, // oversamples enforcer edges, applies weak modifiers, marks one enforced point as central for alignment. void process_perimeter_polygon(const Polygon &orig_polygon, float z_coord, const LayerRegion *region, const GlobalModelInfo &global_model_info, PrintObjectSeamData::LayerSeams &result, - PreciseSeam::PreciseSeamWarnings* warnings = nullptr) { + PreciseSeam::PreciseSeamWarnings* warnings = nullptr, + std::optional boundary_hole = std::nullopt) { if (orig_polygon.size() == 0) { return; } @@ -550,6 +719,10 @@ void process_perimeter_polygon(const Polygon &orig_polygon, float z_coord, const result.perimeters.push_back( { }); Perimeter &perimeter = result.perimeters.back(); + // The loop role is independent of the configured printing direction. + perimeter.is_hole = boundary_hole.value_or(was_clockwise); + perimeter.contour_reliable = boundary_hole.has_value(); // Keep unknown roles out of geometric matching. + perimeter.contour_index = result.perimeters.size() - 1; std::queue orig_polygon_points { }; for (size_t index = 0; index < polygon.size(); ++index) { @@ -561,44 +734,144 @@ void process_perimeter_polygon(const Polygon &orig_polygon, float z_coord, const size_t orig_angle_index = 0; perimeter.start_index = result.points.size(); perimeter.flow_width = region != nullptr ? region->flow(FlowRole::frExternalPerimeter).width() : 0.0f; + + // Painted ranges bounded exactly by the paint contour crossing this layer; without them, points within + // flow_width of paint are Enforced. + std::vector loop_xy; + std::vector loop_arc { 0.0 }; + for (const Point &point : polygon.points) + loop_xy.push_back(unscale(point)); + for (size_t i = 0; i < loop_xy.size(); ++i) + loop_arc.push_back(loop_arc.back() + (loop_xy[(i + 1) % loop_xy.size()] - loop_xy[i]).norm()); + const double loop_length = loop_arc.back(); + const auto intervals = exact_painted_intervals(loop_xy, loop_arc, z_coord, perimeter.flow_width, + global_model_info.enforcer_contour); + const auto blocked_intervals = exact_painted_intervals(loop_xy, loop_arc, z_coord, perimeter.flow_width, + global_model_info.blocker_contour); + perimeter.exact_blocked_ends = !blocked_intervals.empty(); + const bool exact_marks = !intervals.empty() || perimeter.exact_blocked_ends; + // Keep active Precise Seam modifiers authoritative; normalize ordinary full paint only. + const bool ignore_full_paint = intervals.empty() && !inserted_seam_position && weak_segments.empty() && + fully_enforced_loop(loop_xy, z_coord, perimeter.flow_width, global_model_info); + if (ignore_full_paint) + BOOST_LOG_TRIVIAL(debug) << "[SeamPaint] full_perimeter z=" << z_coord << " normalized=true"; + perimeter.exact_enforced_ends = !intervals.empty(); + const auto in_interval = [&](double at, const std::vector &ranges) { + for (const PaintedInterval &interval : ranges) + for (const double s : { at, at + loop_length }) + if (s >= interval.begin - enforced_end_tolerance && s <= interval.end + enforced_end_tolerance) + return true; + return false; + }; + const auto point_at = [&](double s) { + const size_t i = std::min(size_t(std::upper_bound(loop_arc.begin(), loop_arc.end(), s) - loop_arc.begin()), + loop_xy.size()) - 1; + const double length = loop_arc[i + 1] - loop_arc[i]; + const Vec2d p = loop_xy[i] + (length > 0.0 ? (s - loop_arc[i]) / length : 0.0) * + (loop_xy[(i + 1) % loop_xy.size()] - loop_xy[i]); + return Vec3f(float(p.x()), float(p.y()), z_coord); + }; + // Green paint without exact ends: an edge whose start is within the edge length of paint gets a point every + // enforcer_oversampling_distance, passed to emit as its distance from the start. + const auto oversample_green = [&](const Vec3f &start, float length, const auto &emit) { + if (ignore_full_paint || !global_model_info.is_enforced(start, length)) + return; + for (float step = SeamPlacer::enforcer_oversampling_distance; step < length; + step += SeamPlacer::enforcer_oversampling_distance) + emit(step); + }; + // Points to insert: the range ends, middles and every enforcer_oversampling_distance from their begin, and the + // middle of each gap between ranges, which keeps neighboring ranges apart as patches; as sorted loop positions + // in [0, loop_length). + std::vector marks; + std::vector> interval_middles; // Middle point and length of each range. + for (size_t k = 0; k < intervals.size(); ++k) { + const PaintedInterval &interval = intervals[k]; + const double middle = 0.5 * (interval.begin + interval.end); + // Ranges come in loop order from the first vertex. + const double next_begin = k + 1 < intervals.size() ? intervals[k + 1].begin : intervals.front().begin + loop_length; + marks.insert(marks.end(), { interval.begin, interval.end, middle, 0.5 * (interval.end + next_begin) }); + for (double s = interval.begin + SeamPlacer::enforcer_oversampling_distance; s < interval.end - enforced_end_tolerance; + s += SeamPlacer::enforcer_oversampling_distance) + marks.push_back(s); + interval_middles.emplace_back(point_at(std::fmod(middle, loop_length)), interval.end - interval.begin); + } + for (size_t k = 0; k < blocked_intervals.size(); ++k) { + const auto &interval = blocked_intervals[k]; + const double next_begin = k + 1 < blocked_intervals.size() ? blocked_intervals[k + 1].begin : + blocked_intervals.front().begin + loop_length; + const double gap = next_begin - interval.end; + // Keep the boundary itself blocked, with a permitted sample just outside it. Both alignment and + // the iterative solvers stop at these samples, within 2 um of the geometric paint edge. + const double guard = std::min(2.0 * enforced_end_tolerance, 0.25 * gap); + marks.insert(marks.end(), {interval.begin, interval.end, 0.5 * (interval.begin + interval.end), + interval.end + guard, next_begin - guard, 0.5 * (interval.end + next_begin)}); + } + if (perimeter.exact_blocked_ends && !perimeter.exact_enforced_ends) { + // Red marks must not suppress legacy green oversampling when its boundary is uncertain. + for (size_t i = 0; i < loop_xy.size(); ++i) + oversample_green(point_at(loop_arc[i]), float(loop_arc[i + 1] - loop_arc[i]), + [&](float step) { marks.push_back(loop_arc[i] + step); }); + } + for (double &s : marks) + s = std::fmod(s, loop_length); + std::sort(marks.begin(), marks.end()); + // A mark closer than the tolerance to the last one kept is the same point. + size_t kept = 0; + for (size_t i = 0; i < marks.size(); ++i) + if (kept == 0 || marks[i] - marks[kept - 1] >= enforced_end_tolerance) + marks[kept++] = marks[i]; + marks.resize(kept); + + std::queue oversampled_arcs { }; // Loop positions of the inserted points with exact ranges. bool some_point_enforced = false; while (!orig_polygon_points.empty() || !oversampled_points.empty()) { EnforcedBlockedSeamPoint type = EnforcedBlockedSeamPoint::Neutral; Vec3f position; float local_ccw_angle = 0; bool orig_point = false; + double at = 0.0; // Loop position, used with exact ranges. if (!oversampled_points.empty()) { position = oversampled_points.front(); oversampled_points.pop(); + if (exact_marks) { + at = oversampled_arcs.front(); + oversampled_arcs.pop(); + } } else { position = orig_polygon_points.front(); orig_polygon_points.pop(); local_ccw_angle = was_clockwise ? -polygon_angles[orig_angle_index] : polygon_angles[orig_angle_index]; + at = loop_arc[orig_angle_index]; orig_angle_index++; orig_point = true; } - if (global_model_info.is_enforced(position, perimeter.flow_width)) { + // Projected ends bound paint but cannot prove that a detour between them stays near its surface. + if (!ignore_full_paint && (!perimeter.exact_enforced_ends || in_interval(at, intervals)) && + global_model_info.is_enforced(position, perimeter.flow_width)) { type = EnforcedBlockedSeamPoint::Enforced; } - if (global_model_info.is_blocked(position, perimeter.flow_width)) { + if ((!perimeter.exact_blocked_ends || in_interval(at, blocked_intervals)) && + global_model_info.is_blocked(position, perimeter.flow_width)) { type = EnforcedBlockedSeamPoint::Blocked; } some_point_enforced = some_point_enforced || type == EnforcedBlockedSeamPoint::Enforced; - if (orig_point) { - Vec3f pos_of_next = orig_polygon_points.empty() ? first : orig_polygon_points.front(); - float distance_to_next = (position - pos_of_next).norm(); - if (global_model_info.is_enforced(position, distance_to_next)) { - Vec3f vec_to_next = (pos_of_next - position).normalized(); - float step_size = SeamPlacer::enforcer_oversampling_distance; - float step = step_size; - while (step < distance_to_next) { - oversampled_points.push(position + vec_to_next * step); - step += step_size; - } + if (orig_point && exact_marks) { + // Marks strictly inside the edge from this vertex; one at a vertex is the vertex itself. + const double from = loop_arc[orig_angle_index - 1], to = loop_arc[orig_angle_index]; + for (auto it = std::upper_bound(marks.begin(), marks.end(), from + enforced_end_tolerance); + it != marks.end() && *it < to - enforced_end_tolerance; ++it) { + oversampled_points.push(point_at(*it)); + oversampled_arcs.push(*it); } + } else if (orig_point) { + const Vec3f pos_of_next = orig_polygon_points.empty() ? first : orig_polygon_points.front(); + const Vec3f vec_to_next = (pos_of_next - position).normalized(); + oversample_green(position, (position - pos_of_next).norm(), + [&](float step) { oversampled_points.push(position + vec_to_next * step); }); } result.points.emplace_back(position, perimeter, local_ccw_angle, type); @@ -673,6 +946,14 @@ void process_perimeter_polygon(const Polygon &orig_polygon, float z_coord, const assert(viable_points_indices.size() > 0); if (large_angle_points_indices.empty()) { size_t central_idx = viable_points_indices[viable_points_indices.size() / 2]; + // With exact ranges, the middle of the longest range in the patch. + double longest = -1.0; + for (const size_t idx : viable_points_indices) + for (const auto &[middle, length] : interval_middles) + if (length > longest && (result.points[idx].position - middle).norm() <= enforced_end_tolerance) { + central_idx = idx; + longest = length; + } result.points[central_idx].central_enforcer = true; } else { size_t central_idx = large_angle_points_indices.size() / 2; @@ -793,12 +1074,35 @@ void compute_global_occlusion(GlobalModelInfo &result, const PrintObject *po, #endif } +// Appends the contour of painted triangles without T-joints (shared vertices): their edges used by one +// triangle only. Paint lies to the left of an edge in the triangle's counterclockwise order. +void append_painted_contour(PaintedContour &result, const indexed_triangle_set &painted) { + const auto edge_key = [](int a, int b) { return (uint64_t(std::min(a, b)) << 32) | uint64_t(std::max(a, b)); }; + std::unordered_map uses; + for (const stl_triangle_vertex_indices &face : painted.indices) + for (int i = 0; i < 3; ++i) + ++uses[edge_key(face[i], face[(i + 1) % 3])]; + for (const stl_triangle_vertex_indices &face : painted.indices) { + const Vec3d v[3] = {painted.vertices[face[0]].cast(), painted.vertices[face[1]].cast(), + painted.vertices[face[2]].cast()}; + const Vec3d normal = (v[1] - v[0]).cross(v[2] - v[0]); + for (int i = 0; i < 3; ++i) { + const Vec3d inward = normal.cross(v[(i + 1) % 3] - v[i]); + if (uses[edge_key(face[i], face[(i + 1) % 3])] == 1 && inward.squaredNorm() > 0.0) { + result.edges.emplace_back(v[i], v[(i + 1) % 3]); + result.inward.emplace_back(inward.normalized()); + } + } + } +} + void gather_enforcers_blockers(GlobalModelInfo &result, const PrintObject *po) { BOOST_LOG_TRIVIAL(debug) << "SeamPlacer: build AABB trees for raycasting enforcers/blockers: start"; auto obj_transform = po->trafo_sliced(); + indexed_triangle_set painted_non_green; // Used only if the object has green paint. for (const ModelVolume *mv : po->model_object()->volumes) { // Collect painting only from model parts (what the gizmo edits) and negative volumes (the only way // to paint a hole's wall); painting left on modifiers and helpers after a type change is ignored. @@ -806,25 +1110,55 @@ void gather_enforcers_blockers(GlobalModelInfo &result, const PrintObject *po) { // making it editable also needs model_custom_seam_data_changed() to track it. if (!mv->is_model_part() && !mv->is_negative_volume()) continue; + const auto model_transformation = obj_transform * mv->get_matrix(); if (mv->is_seam_painted()) { - auto model_transformation = obj_transform * mv->get_matrix(); - - indexed_triangle_set enforcers = mv->seam_facets.get_facets(*mv, EnforcerBlockerType::ENFORCER); + // One selector serves every paint state; each FacetsAnnotation query would rebuild it from the mesh. + TriangleSelector selector(mv->mesh()); + selector.deserialize(mv->seam_facets.get_data(), false); + indexed_triangle_set enforcers = selector.get_facets(EnforcerBlockerType::ENFORCER); // ORCA fix (not related to Precise Seam): fix winding for mirrored transforms its_transform(enforcers, model_transformation, true); its_merge(result.enforcers, enforcers); - indexed_triangle_set blockers = mv->seam_facets.get_facets(*mv, EnforcerBlockerType::BLOCKER); + indexed_triangle_set painted = selector.get_facets_strict(EnforcerBlockerType::ENFORCER); + its_transform(painted, model_transformation, true); + append_painted_contour(result.enforcer_contour, painted); + + indexed_triangle_set blockers = selector.get_facets(EnforcerBlockerType::BLOCKER); // ORCA fix (not related to Precise Seam): fix winding for mirrored transforms its_transform(blockers, model_transformation, true); its_merge(result.blockers, blockers); + painted = selector.get_facets_strict(EnforcerBlockerType::BLOCKER); + its_transform(painted, model_transformation, true); + append_painted_contour(result.blocker_contour, painted); + + indexed_triangle_set non_green = selector.get_facets(EnforcerBlockerType::NONE); + its_transform(non_green, model_transformation, true); + its_merge(painted_non_green, non_green); } } + // Unpainted objects need no extra surface copy or tree; only green paint requires a coverage proof. + if (!result.enforcers.empty()) { + result.non_enforcers = std::move(painted_non_green); + for (const ModelVolume *mv : po->model_object()->volumes) { + if ((!mv->is_model_part() && !mv->is_negative_volume()) || mv->is_seam_painted()) + continue; + indexed_triangle_set non_green = mv->mesh().its; + its_transform(non_green, obj_transform * mv->get_matrix(), true); + its_merge(result.non_enforcers, non_green); + } + its_merge(result.non_enforcers, result.blockers); // Red paint must also prevent full-green normalization. + result.non_enforcers_tree = AABBTreeIndirect::build_aabb_tree_over_indexed_triangle_set(result.non_enforcers.vertices, + result.non_enforcers.indices); + } + result.enforcers_tree = AABBTreeIndirect::build_aabb_tree_over_indexed_triangle_set(result.enforcers.vertices, result.enforcers.indices); result.blockers_tree = AABBTreeIndirect::build_aabb_tree_over_indexed_triangle_set(result.blockers.vertices, result.blockers.indices); + result.enforcer_contour.tree = AABBTreeLines::build_aabb_tree_over_indexed_lines(result.enforcer_contour.edges); + result.blocker_contour.tree = AABBTreeLines::build_aabb_tree_over_indexed_lines(result.blocker_contour.edges); BOOST_LOG_TRIVIAL(debug) << "SeamPlacer: build AABB trees for raycasting enforcers/blockers: end"; @@ -1048,6 +1382,21 @@ void pick_random_seam_point(const std::vector &perimeter_points, }; std::vector viables; + const auto edge_from = [&](size_t index) -> Vec3f { + const size_t next = index == end_index - 1 ? start_index : index + 1; + // The exact green endpoint is Enforced, but its outgoing edge leaves the permitted painted run. + if (perimeter_points[index].perimeter.exact_enforced_ends && + perimeter_points[index].type == EnforcedBlockedSeamPoint::Enforced && + perimeter_points[next].type != EnforcedBlockedSeamPoint::Enforced) + return Vec3f::Zero(); + // Random samples the outgoing edge, not just the candidate; do not sample toward a closed red boundary. + if (perimeter_points[index].perimeter.exact_blocked_ends && + perimeter_points[index].type != EnforcedBlockedSeamPoint::Blocked && + perimeter_points[next].type == EnforcedBlockedSeamPoint::Blocked) + return Vec3f::Zero(); + return perimeter_points[next].position - perimeter_points[index].position; + }; + const Vec3f pseudornd_seed = perimeter_points[viable_example_index].position; float rand = std::abs(sin(pseudornd_seed.dot(Vec3f(12.9898f,78.233f, 133.3333f))) * 43758.5453f); rand = rand - (int) rand; @@ -1055,8 +1404,7 @@ void pick_random_seam_point(const std::vector &perimeter_points, for (size_t index = start_index; index < end_index; ++index) { if (comparator.are_similar(perimeter_points[index], perimeter_points[viable_example_index])) { // index ok, push info into viables - Vec3f edge_to_next { perimeter_points[index == end_index - 1 ? start_index : index + 1].position - - perimeter_points[index].position }; + Vec3f edge_to_next = edge_from(index); float dist_to_next = edge_to_next.norm(); viables.push_back( { index, dist_to_next, edge_to_next }); } else if (comparator.is_first_not_much_worse(perimeter_points[viable_example_index], @@ -1068,8 +1416,7 @@ void pick_random_seam_point(const std::vector &perimeter_points, viable_example_index = index; viables.clear(); - Vec3f edge_to_next = (perimeter_points[index == end_index - 1 ? start_index : index + 1].position - - perimeter_points[index].position); + Vec3f edge_to_next = edge_from(index); float dist_to_next = edge_to_next.norm(); viables.push_back( { index, dist_to_next, edge_to_next }); } @@ -1082,18 +1429,204 @@ void pick_random_seam_point(const std::vector &perimeter_points, float picked_len = len_sum * rand; size_t point_idx = 0; - while (picked_len - viables[point_idx].edge_length > 0) { + // Float accumulation can leave a positive residual after the final edge, including a zero-length edge. + while (point_idx + 1 < viables.size() && picked_len - viables[point_idx].edge_length > 0) { picked_len = picked_len - viables[point_idx].edge_length; point_idx++; } + picked_len = std::clamp(picked_len, 0.0f, viables[point_idx].edge_length); Perimeter &perimeter = perimeter_points[start_index].perimeter; perimeter.seam_index = viables[point_idx].index; perimeter.final_seam_position = perimeter_points[perimeter.seam_index].position - + viables[point_idx].edge.normalized() * picked_len; + + (viables[point_idx].edge_length > 0.f ? + Vec3f(viables[point_idx].edge.normalized() * picked_len) : Vec3f::Zero()); perimeter.finalized = true; } +// Seam alignment on the loop, see docs/HLSD/seam-alignment.md. +// A painted seam keeps its pull (t >= 0.4) toward the discrete candidate only near a measured corner; +// on a smooth contour that pull makes the seam jump between candidates from layer to layer. +constexpr float enforced_corner_angle_min = 15.0f * float(PI) / 180.0f; +constexpr float enforced_corner_angle_max = 30.0f * float(PI) / 180.0f; +// The corner influence fades out along the perimeter between R0 and this multiple of R0. +constexpr float enforced_corner_fade_factor = 2.0f; + +float smoothstep01(float x) { + x = std::clamp(x, 0.0f, 1.0f); + return x * x * (3.0f - 2.0f * x); +} + +// Strength in [0, 1] of the measured corners around the candidate: a corner of at least +// enforced_corner_angle_max within `protect` along the perimeter counts fully, then fades out by `fade_end`. +float enforced_corner_influence(const std::vector &points, size_t index, float protect, float fade_end) { + const Perimeter &perimeter = points[index].perimeter; + const size_t start = perimeter.start_index; + const size_t count = perimeter.end_index - start; + const auto contribution = [&](size_t i, float distance) { + const float corner = smoothstep01((std::abs(points[i].local_ccw_angle) - enforced_corner_angle_min) / + (enforced_corner_angle_max - enforced_corner_angle_min)); + const float weight = distance <= protect ? 1.0f : 1.0f - smoothstep01((distance - protect) / (fade_end - protect)); + return corner * weight; + }; + float influence = contribution(index, 0.0f); + for (const bool forward : { false, true }) { + size_t i = index; + float distance = 0.0f; + // At most count - 1 steps per direction, so short loops and zero-length edges terminate. + for (size_t step = 1; step < count && influence < 1.0f; ++step) { + const size_t j = start + (forward ? next_idx_modulo(i - start, count) : prev_idx_modulo(i - start, count)); + distance += (points[j].position - points[i].position).head<2>().norm(); + if (distance >= fade_end) + break; + influence = std::max(influence, contribution(j, distance)); + i = j; + } + } + return influence; +} + +// Unit normal of the edge from a to b, zero for a zero-length edge. +Vec2d edge_normal(const Vec2d &a, const Vec2d &b) { + const Vec2d d = b - a; + const double length = d.norm(); + return length > 0.0 ? Vec2d(-d.y() / length, d.x() / length) : Vec2d::Zero(); +} + +// Seam position on the loop for a `target`: the closest loop point to it whose normal passes through it, +// or, if that lies outside the arc allowed around the candidate at `index`, the arc end closer to that point. +Vec3f place_on_loop(const std::vector &points, size_t index, const Vec3f &target) { + const Perimeter &perimeter = points[index].perimeter; + const size_t start = perimeter.start_index; + const size_t count = perimeter.end_index - start; + if (count < 2) + return points[index].position; + const auto next = [&](size_t i) { return start + next_idx_modulo(i - start, count); }; + const auto prev = [&](size_t i) { return start + prev_idx_modulo(i - start, count); }; + const auto xy = [&](size_t i) { return Vec2d(points[i].position.head<2>().cast()); }; + // Nearest neighbor at a different position, so that duplicated points share one normal. + const auto distinct = [&](size_t i, bool forward) { + size_t j = i; + for (size_t step = 1; step < count; ++step) { + j = forward ? next(j) : prev(j); + if (xy(j) != xy(i)) + return j; + } + return i; + }; + const auto vertex_normal = [&](size_t i) { + const Vec2d sum = edge_normal(xy(distinct(i, false)), xy(i)) + edge_normal(xy(i), xy(distinct(i, true))); + return sum.squaredNorm() > 0.0 ? Vec2d(sum.normalized()) : Vec2d::Zero(); + }; + const auto cross = [](const Vec2d &a, const Vec2d &b) { return a.x() * b.y() - a.y() * b.x(); }; + + // Allowed arc on one side: the Enforced run for an Enforced candidate, plus the oversampling distance unless + // the run ends exactly at the paint; up to a Blocked candidate otherwise. Returns its length and end point; + // infinite length if unlimited. + const bool enforced = points[index].type == EnforcedBlockedSeamPoint::Enforced; + const bool blocked = points[index].type == EnforcedBlockedSeamPoint::Blocked; + const auto allowed_arc = [&](bool forward) { + double arc = 0.0; + double extension = enforced && !perimeter.exact_enforced_ends ? SeamPlacer::enforcer_oversampling_distance : 0.0; + bool in_run = true; + size_t i = index; + // All count edges, the closing one back to the candidate included, before the arc is unlimited. + for (size_t visited = 1; visited <= count; ++visited) { + const size_t j = forward ? next(i) : prev(i); + const EnforcedBlockedSeamPoint type = points[j].type; + if (in_run && (enforced ? type != EnforcedBlockedSeamPoint::Enforced : + !blocked && type == EnforcedBlockedSeamPoint::Blocked)) + in_run = false; + if (!in_run && (!enforced || type == EnforcedBlockedSeamPoint::Blocked)) + return std::make_pair(arc, xy(i)); // Only an Enforced run is extended, and never into a Blocked candidate. + const double length = (xy(j) - xy(i)).norm(); + if (!in_run) { + const double reach = std::min(length, extension); + extension -= reach; + if (reach < length) + return std::make_pair(arc + reach, Vec2d(xy(i) + (reach / length) * (xy(j) - xy(i)))); + } + arc += length; + i = j; + } + return std::make_pair(std::numeric_limits::infinity(), xy(index)); + }; + + // Closest solution over the whole loop, walking outward on the shorter side first so that solutions near + // the candidate prune the edges farther from the target than them. + const Vec2d p = target.head<2>().cast(); + std::optional best; + double best_distance = std::numeric_limits::infinity(); + bool best_forward = true; + double best_arc = 0.0; + double arc[2] = { 0.0, 0.0 }; // Walked arc behind and ahead of the candidate. + size_t cursor[2] = { index, index }; + for (size_t visited = 0; visited < count; ++visited) { + const bool forward = arc[1] <= arc[0]; + const size_t i = cursor[forward]; + const size_t j = forward ? next(i) : prev(i); + // The edge in index order; P(u) = xy(a) + u * d. + const size_t a = forward ? i : j; + const size_t b = forward ? j : i; + const Vec2d d = xy(b) - xy(a); + const double length = d.norm(); + const Vec2d g = p - xy(a); + const double u_closest = length > 0.0 ? std::clamp(g.dot(d) / (length * length), 0.0, 1.0) : 0.0; + if (length > 0.0 && (g - u_closest * d).squaredNorm() < best_distance) { + // Solve cross(p - P(u), N(u)) = 0 with the normal N blended linearly between the vertex normals. + Vec2d na = vertex_normal(a); + Vec2d nb = vertex_normal(b); + if (na.squaredNorm() == 0.0 || nb.squaredNorm() == 0.0) + na = nb = edge_normal(xy(a), xy(b)); + const Vec2d m = nb - na; + const double c0 = cross(g, na); + const double c1 = cross(g, m) - cross(d, na); + const double c2 = -cross(d, m); + const auto consider = [&](double u) { + if (u < 0.0 || u > 1.0) + return; + const double distance = (g - u * d).squaredNorm(); + if (distance < best_distance) { + best = Vec2d(xy(a) + u * d); + best_distance = distance; + best_forward = forward; + best_arc = arc[forward] + (forward ? u : 1.0 - u) * length; + } + }; + // Absolute threshold on the coefficients (mm), only to tell the degenerate equations apart. + constexpr double eps = 1e-12; + if (std::abs(c2) < eps && std::abs(c1) < eps) { + if (std::abs(c0) < eps) + consider(u_closest); // Every point is a solution. + } else if (std::abs(c2) < eps) { + consider(-c0 / c1); + } else { + const double discriminant = c1 * c1 - 4.0 * c2 * c0; + if (discriminant >= 0.0) { + const double root = std::sqrt(discriminant); + consider((-c1 - root) / (2.0 * c2)); + consider((-c1 + root) / (2.0 * c2)); + } + } + } + arc[forward] += length; + cursor[forward] = j; + } + if (!best) + return points[index].position; + + // A solution outside the allowed arc gives way to the arc end closer to it, so that a solution leaving + // the arc stays at the end it left through. + Vec2d result = *best; + const double loop_length = arc[0] + arc[1]; + const double ahead = best_forward ? best_arc : loop_length - best_arc; + const auto [ahead_limit, ahead_end] = allowed_arc(true); + const auto [behind_limit, behind_end] = allowed_arc(false); + if (ahead > ahead_limit && loop_length - ahead > behind_limit) + result = (ahead_end - *best).squaredNorm() <= (behind_end - *best).squaredNorm() ? ahead_end : behind_end; + return to_3d(Vec2f(result.cast()), points[index].position.z()); +} + } // namespace SeamPlacerImpl // Parallel process and extract each perimeter polygon of the given print object. @@ -1113,14 +1646,15 @@ void SeamPlacer::gather_seam_candidates(const PrintObject *po, const SeamPlacerI const Layer *layer = po->get_layer(layer_idx); auto unscaled_z = layer->slice_z; std::vector regions; + std::vector> boundary_types; //NOTE corresponding region ptr may be null, if the layer has zero perimeters const bool has_precise_seam_modifiers = !global_model_info.precise_seam_strong_volumes.empty() || !global_model_info.precise_seam_weak_volumes.empty(); - Polygons polygons = extract_perimeter_polygons(layer, regions, has_precise_seam_modifiers); + Polygons polygons = extract_perimeter_polygons(layer, regions, boundary_types, has_precise_seam_modifiers); for (size_t poly_index = 0; poly_index < polygons.size(); ++poly_index) { process_perimeter_polygon(polygons[poly_index], unscaled_z, regions[poly_index], global_model_info, layer_seams, - warnings); + warnings, boundary_types[poly_index]); } auto functor = SeamCandidateCoordinateFunctor { layer_seams.points }; seam_data.layers[layer_idx].points_tree = @@ -1206,16 +1740,33 @@ std::optional> SeamPlacer::find_next_seam_in_layer( const std::vector &layers, const Vec3f &projected_position, const size_t layer_idx, const float max_distance, - const SeamPlacerImpl::SeamComparator &comparator) const { + const SeamPlacerImpl::SeamComparator &comparator, + const SeamContour::Resolver *contours, + std::pair previous) const { using namespace SeamPlacerImpl; + // Contours of the geometric continuation. Empty when there is no geometric match, which preserves the legacy radius + // search; occupancy never expands a known set. + std::vector continuation; + if (contours) { + const Perimeter &source = layers[previous.first].points[previous.second].perimeter; + const int direction = layer_idx > previous.first ? 1 : -1; + continuation = contours->resolve(previous.first, source.contour_index, + previous.second - source.start_index, direction, max_distance).contours; + } + // Find the best nearby point and the nearest one. A layer of a fine relief has tens of thousands of candidates within // the radius, so they are looked at as the search finds them rather than collected into a vector first. constexpr size_t none = std::numeric_limits::max(); size_t best_nearby_point_index = none; size_t nearest_point_index = none; visit_nearby_points(*layers[layer_idx].points_tree, projected_position, max_distance, - [&layers, &comparator, &projected_position, layer_idx, &best_nearby_point_index, &nearest_point_index] - (size_t nearby_point_index) { + [&layers, &comparator, &projected_position, &continuation, layer_idx, &best_nearby_point_index, + &nearest_point_index](size_t nearby_point_index) { + // Points off the continuation are skipped before the first point is taken, as they were removed before the scan. + if (!continuation.empty() && + std::find(continuation.begin(), continuation.end(), + layers[layer_idx].points[nearby_point_index].perimeter.contour_index) == continuation.end()) + return; if (best_nearby_point_index == none) { // The first point found starts both, as the first of the collected ones did. best_nearby_point_index = nearest_point_index = nearby_point_index; @@ -1271,7 +1822,8 @@ std::optional> SeamPlacer::find_next_seam_in_layer( } std::vector> SeamPlacer::find_seam_string(const PrintObject *po, - std::pair start_seam, const SeamPlacerImpl::SeamComparator &comparator) const { + std::pair start_seam, const SeamPlacerImpl::SeamComparator &comparator, + const SeamContour::Resolver *contours) const { const std::vector &layers = m_seam_per_object.find(po)->second.layers; int layer_idx = start_seam.first; @@ -1302,7 +1854,7 @@ std::vector> SeamPlacer::find_seam_string(const PrintO std::optional> maybe_next_seam = find_next_seam_in_layer(layers, projected_position, next_layer, - max_distance, comparator); + max_distance, comparator, contours, prev_point_index); if (maybe_next_seam.has_value()) { // For old macOS (pre 10.14), std::optional does not have .value() method, so the code is using operator*() instead. @@ -1311,10 +1863,9 @@ std::vector> SeamPlacer::find_seam_string(const PrintO //String added, prev_point_index updated } else { if (step == 1) { + // Continue right below the start seam; stepping now would skip that layer. reverse_lookup_direction(); - if (next_layer < 0) { - break; - } + continue; } else { break; } @@ -1328,8 +1879,9 @@ std::vector> SeamPlacer::find_seam_string(const PrintO // aligns the strings via polynomial fit // Does not change the positions of the SeamCandidates themselves, instead stores // the new aligned position into the shared Perimeter structure of each perimeter -// Note that this position does not necesarilly lay on the perimeter. -void SeamPlacer::align_seam_points(const PrintObject *po, const SeamPlacerImpl::SeamComparator &comparator) { +// This position lies on the perimeter polygon; placement on the printed loop may still move it. +void SeamPlacer::align_seam_points(const PrintObject *po, const SeamPlacerImpl::SeamComparator &comparator, + const std::function &throw_if_canceled) { using namespace SeamPlacerImpl; // Prepares Debug files for writing. @@ -1353,6 +1905,29 @@ void SeamPlacer::align_seam_points(const PrintObject *po, const SeamPlacerImpl:: //gather vector of all seams on the print_object - pair of layer_index and seam__index within that layer const std::vector &layers = m_seam_per_object[po].layers; + // Share the largest nozzle diameter between contour bounds and corner protection. + double max_nozzle_diameter = 0.0; + for (double diameter : po->print()->config().nozzle_diameter.values) + max_nozzle_diameter = std::max(max_nozzle_diameter, diameter); + // Reuse immutable contour geometry across all alternative string starts. + std::unique_ptr contour_resolver; + { + SeamContour::Layers geometry(layers.size()); + for (size_t i = 0; i < layers.size(); ++i) { + throw_if_canceled(); // Geometry copies on dense multi-island objects must remain interruptible. + for (const Perimeter &perimeter : layers[i].perimeters) { + SeamContour::Contour contour; + contour.hole = perimeter.is_hole; + contour.reliable = perimeter.contour_reliable; + contour.width = perimeter.flow_width; + contour.nozzle = max_nozzle_diameter; + for (size_t j = perimeter.start_index; j < perimeter.end_index; ++j) + contour.points.push_back(layers[i].points[j].position.head<2>().cast()); + geometry[i].push_back(std::move(contour)); + } + } + contour_resolver = std::make_unique(std::move(geometry), SeamContour::Options{}, throw_if_canceled); + } std::vector> seams; for (size_t layer_idx = 0; layer_idx < layers.size(); ++layer_idx) { const std::vector &layer_perimeter_points = layers[layer_idx].points; @@ -1382,6 +1957,7 @@ void SeamPlacer::align_seam_points(const PrintObject *po, const SeamPlacerImpl:: int global_index = 0; while (global_index < int(seams.size())) { + throw_if_canceled(); size_t layer_idx = seams[global_index].first; size_t seam_index = seams[global_index].second; global_index++; @@ -1390,14 +1966,16 @@ void SeamPlacer::align_seam_points(const PrintObject *po, const SeamPlacerImpl:: // This perimeter is already aligned, skip seam continue; } else { - seam_string = this->find_seam_string(po, { layer_idx, seam_index }, comparator); + seam_string = this->find_seam_string(po, { layer_idx, seam_index }, comparator, contour_resolver.get()); size_t step_size = 1 + seam_string.size() / 20; for (size_t alternative_start = 0; alternative_start < seam_string.size(); alternative_start += step_size) { + throw_if_canceled(); size_t start_layer_idx = seam_string[alternative_start].first; size_t seam_idx = layers[start_layer_idx].points[seam_string[alternative_start].second].perimeter.seam_index; alternative_seam_string = this->find_seam_string(po, - std::pair(start_layer_idx, seam_idx), comparator); + std::pair(start_layer_idx, seam_idx), comparator, + contour_resolver.get()); if (alternative_seam_string.size() > seam_string.size()) { seam_string = std::move(alternative_seam_string); } @@ -1469,17 +2047,32 @@ void SeamPlacer::align_seam_points(const PrintObject *po, const SeamPlacerImpl:: // Perimeter structure of the point; also set flag aligned to true for (size_t index = 0; index < seam_string.size(); ++index) { const auto &pair = seam_string[index]; - float t = std::min(1.0f, std::pow(std::abs(layers[pair.first].points[pair.second].local_ccw_angle) + const std::vector &points = layers[pair.first].points; + const SeamCandidate &candidate = points[pair.second]; + float t = std::min(1.0f, std::pow(std::abs(candidate.local_ccw_angle) / SeamPlacer::sharp_angle_snapping_threshold, 3.0f)); - if (layers[pair.first].points[pair.second].type == EnforcedBlockedSeamPoint::Enforced){ - t = std::max(0.4f, t); - } - Vec3f current_pos = layers[pair.first].points[pair.second].position; + Vec3f current_pos = candidate.position; Vec2f fitted_pos = curve.get_fitted_value(current_pos.z()); //interpolate between current and fitted position, prefer current pos for large weights. - Vec3f final_position = t * current_pos + (1.0f - t) * to_3d(fitted_pos, current_pos.z()); + Vec3f final_position; + if (candidate.type != EnforcedBlockedSeamPoint::Enforced) { + final_position = t >= 1.0f ? current_pos : + place_on_loop(points, pair.second, t * current_pos + (1.0f - t) * to_3d(fitted_pos, current_pos.z())); + } else if (t >= 1.0f) { + final_position = current_pos; + } else { + // Keep the 0.4 pull toward the candidate near a measured corner only, then keep the seam on the paint. + float protect = std::max(candidate.perimeter.flow_width, float(max_nozzle_diameter)); + if (protect <= 0.0f) + protect = 0.5f; + const float corner = std::abs(candidate.local_ccw_angle) >= enforced_corner_angle_max ? + 1.0f : enforced_corner_influence(points, pair.second, protect, enforced_corner_fade_factor * protect); + t = std::max(t, 0.4f * corner); + final_position = place_on_loop(points, pair.second, + t * current_pos + (1.0f - t) * to_3d(fitted_pos, current_pos.z())); + } Perimeter &perimeter = layers[pair.first].points[pair.second].perimeter; perimeter.seam_index = pair.second; @@ -1604,7 +2197,7 @@ void SeamPlacer::init(const Print &print, std::function throw_if_can if (configured_seam_preference == spAligned || configured_seam_preference == spRear || configured_seam_preference == spAlignedBack) { BOOST_LOG_TRIVIAL(debug) << "SeamPlacer: align_seam_points : start"; - align_seam_points(po, comparator); + align_seam_points(po, comparator, throw_if_canceled_func); BOOST_LOG_TRIVIAL(debug) << "SeamPlacer: align_seam_points : end"; } diff --git a/src/libslic3r/GCode/SeamPlacer.hpp b/src/libslic3r/GCode/SeamPlacer.hpp index 1c989cf155..779e333374 100644 --- a/src/libslic3r/GCode/SeamPlacer.hpp +++ b/src/libslic3r/GCode/SeamPlacer.hpp @@ -19,6 +19,7 @@ namespace Slic3r { class PrintObject; +namespace SeamContour { class Resolver; } namespace PreciseSeam { struct PreciseSeamWarnings; } class ExtrusionLoop; class Print; @@ -42,14 +43,21 @@ enum class EnforcedBlockedSeamPoint { // struct representing single perimeter loop struct Perimeter { + bool is_hole = false; // Preserve boundary type before candidate polygons become CCW. + bool contour_reliable = false; // Open paths must retain the legacy continuation search. + size_t contour_index = 0; size_t start_index{}; size_t end_index{}; //exclusive (one-past-the-end) size_t seam_index{}; float flow_width{}; + // Enforced candidates span the painted ranges exactly, their ends included, instead of reaching flow_width + // around the paint. + bool exact_enforced_ends = false; + // Red paint is reconstructed on the contour; its edge samples remain Blocked. + bool exact_blocked_ends = false; - // During alignment, a final position may be stored here. In that case, finalized is set to true. - // Note that final seam position is not limited to points of the perimeter loop. In theory it can be any position - // Random position also uses this flexibility to set final seam point position + // Alignment and Random may store a final position here, then set finalized. It lies on the perimeter polygon, + // though not necessarily at a candidate point. bool finalized = false; Vec3f final_seam_position = Vec3f::Zero(); @@ -91,6 +99,10 @@ struct SeamCandidateCoordinateFunctor { return seam_candidates[index].position[dim]; } }; + +// Seam alignment helpers, declared here for the tests. +float enforced_corner_influence(const std::vector &points, size_t index, float protect, float fade_end); +Vec3f place_on_loop(const std::vector &points, size_t index, const Vec3f &target); } // namespace SeamPlacerImpl struct PrintObjectSeamData @@ -165,15 +177,19 @@ private: void calculate_candidates_visibility(const PrintObject *po, const SeamPlacerImpl::GlobalModelInfo &global_model_info); void calculate_overhangs_and_layer_embedding(const PrintObject *po); - void align_seam_points(const PrintObject *po, const SeamPlacerImpl::SeamComparator &comparator); + void align_seam_points(const PrintObject *po, const SeamPlacerImpl::SeamComparator &comparator, + const std::function &throw_if_canceled); std::vector> find_seam_string(const PrintObject *po, std::pair start_seam, - const SeamPlacerImpl::SeamComparator &comparator) const; + const SeamPlacerImpl::SeamComparator &comparator, + const SeamContour::Resolver *contours = nullptr) const; std::optional> find_next_seam_in_layer( const std::vector &layers, const Vec3f& projected_position, const size_t layer_idx, const float max_distance, - const SeamPlacerImpl::SeamComparator &comparator) const; + const SeamPlacerImpl::SeamComparator &comparator, + const SeamContour::Resolver *contours = nullptr, + std::pair previous = {}) const; }; } // namespace Slic3r diff --git a/src/libslic3r/GCode/ToolOrdering.cpp b/src/libslic3r/GCode/ToolOrdering.cpp index 2ea34aef90..64b2151221 100644 --- a/src/libslic3r/GCode/ToolOrdering.cpp +++ b/src/libslic3r/GCode/ToolOrdering.cpp @@ -140,6 +140,29 @@ unsigned int LayerTools::internal_solid_filament_id(const PrintRegion ®ion) c return resolve_mixed(result); } +// 1 based filament of an island's extrusions; the tool ordering and the G-code export must agree on it. +static unsigned int region_filament(const ExtrusionEntityCollection &extrusions, const PrintRegionConfig &config) +{ + if (extrusions.has_infill()) { + if (!extrusions.has_solid_infill()) + return config.sparse_infill_filament_id.value; + // Orca: Gap fill takes the filament of the surface it fills. + ExtrusionRole role = erNone; + for (const ExtrusionEntity *ee : extrusions.entities) + if (const ExtrusionRole er = ee->role(); er != erGapFill) + role = (role == erNone || role == er) ? er : erMixed; + if (role == erTopSolidInfill || role == erIroning) + return config.top_surface_filament_id.value; + if (role == erBottomSurface) + return config.bottom_surface_filament_id.value; + return config.internal_solid_filament_id.value; + } + // Walls, and the gap fill between them. + const ExtrusionEntitiesPtr &walls = extrusions.entities; + return !walls.empty() && std::all_of(walls.begin(), walls.end(), [](const ExtrusionEntity *ee) { return is_inner_wall(*ee); }) ? + config.inner_wall_filament_id.value : config.outer_wall_filament_id.value; +} + // Returns a zero based extruder this eec should be printed with, according to PrintRegion config or extruder_override if overriden. unsigned int LayerTools::extruder(const ExtrusionEntityCollection &extrusions, const PrintRegion ®ion) const { @@ -149,30 +172,7 @@ unsigned int LayerTools::extruder(const ExtrusionEntityCollection &extrusions, c assert(region.config().top_surface_filament_id.value > 0); assert(region.config().bottom_surface_filament_id.value > 0); // 1 based extruder ID. - unsigned int extruder = 1; - if (this->extruder_override == 0) { - if (extrusions.has_infill()) { - if (extrusions.has_solid_infill()) { - ExtrusionRole role = extrusions.role(); - if (role == erTopSolidInfill || role == erIroning) - extruder = region.config().top_surface_filament_id; - else if (role == erBottomSurface) - extruder = region.config().bottom_surface_filament_id; - else - extruder = region.config().internal_solid_filament_id; - } else { - extruder = region.config().sparse_infill_filament_id; - } - } else { - const ExtrusionRole role = extrusions.role(); - if (role == erPerimeter) - extruder = region.config().inner_wall_filament_id.value; - else - extruder = region.config().outer_wall_filament_id.value; - } - } else - extruder = this->extruder_override; - + const unsigned int extruder = this->extruder_override == 0 ? region_filament(extrusions, region.config()) : this->extruder_override; unsigned int result = (extruder == 0) ? 0 : extruder - 1; return resolve_mixed(result); } @@ -855,7 +855,12 @@ void ToolOrdering::collect_extruders(const PrintObject &object, const std::vecto if (something_nonoverriddable){ layer_tools.extruders.emplace_back((extruder_override == 0) ? region.config().outer_wall_filament_id.value : extruder_override); - if (extruder_override == 0 && region.config().wall_loops.value > 1) + const ExtrusionEntitiesPtr &islands = layerm->perimeters.entities; + const bool has_inner_wall = std::any_of(islands.begin(), islands.end(), [](const ExtrusionEntity *island) { + const ExtrusionEntitiesPtr &walls = static_cast(island)->entities; + return std::any_of(walls.begin(), walls.end(), [](const ExtrusionEntity *ee) { return is_inner_wall(*ee); }); + }); + if (extruder_override == 0 && region.config().wall_loops.value > 1 && has_inner_wall) layer_tools.extruders.emplace_back(region.config().inner_wall_filament_id.value); if (layerCount == 0) { firstLayerExtruders.emplace_back((extruder_override == 0) ? region.config().outer_wall_filament_id.value : extruder_override); @@ -865,23 +870,13 @@ void ToolOrdering::collect_extruders(const PrintObject &object, const std::vecto layer_tools.has_object = true; } - bool has_infill = false; - bool has_internal_solid = false; - bool has_top_solid_surface = false; - bool has_bottom_surface = false; + std::vector fill_filaments; bool something_nonoverriddable = false; for (const ExtrusionEntity *ee : layerm->fills.entities) { // fill represents infill extrusions of a single island. const auto *fill = dynamic_cast(ee); - ExtrusionRole role = fill->entities.empty() ? erNone : fill->entities.front()->role(); - if (role == erTopSolidInfill || role == erIroning) - has_top_solid_surface = true; - else if (role == erBottomSurface) - has_bottom_surface = true; - else if (is_solid_infill(role)) - has_internal_solid = true; - else if (role != erNone) - has_infill = true; + if (! fill->entities.empty()) + fill_filaments.emplace_back(region_filament(*fill, region.config())); if (m_print_config_ptr) { if (! layer_tools.wiping_extrusions().is_overriddable_and_mark(*fill, *m_print_config_ptr, object, region)) @@ -890,19 +885,12 @@ void ToolOrdering::collect_extruders(const PrintObject &object, const std::vecto } if (something_nonoverriddable || !m_print_config_ptr) { - if (extruder_override == 0) { - if (has_internal_solid) - layer_tools.extruders.emplace_back(region.config().internal_solid_filament_id); - if (has_top_solid_surface) - layer_tools.extruders.emplace_back(region.config().top_surface_filament_id); - if (has_bottom_surface) - layer_tools.extruders.emplace_back(region.config().bottom_surface_filament_id); - if (has_infill) - layer_tools.extruders.emplace_back(region.config().sparse_infill_filament_id); - } else if (has_internal_solid || has_top_solid_surface || has_bottom_surface || has_infill) + if (extruder_override == 0) + append(layer_tools.extruders, fill_filaments); + else if (! fill_filaments.empty()) layer_tools.extruders.emplace_back(extruder_override); } - if (has_internal_solid || has_top_solid_surface || has_bottom_surface || has_infill) + if (! fill_filaments.empty()) layer_tools.has_object = true; } diff --git a/src/libslic3r/MultiMaterialSegmentation.cpp b/src/libslic3r/MultiMaterialSegmentation.cpp index 4c32c7380a..651d815144 100644 --- a/src/libslic3r/MultiMaterialSegmentation.cpp +++ b/src/libslic3r/MultiMaterialSegmentation.cpp @@ -1237,6 +1237,12 @@ double resolve_outer_wall_line_width(const PrintRegionConfig ®ion_config, con return width.get_abs_value(nozzle_diameter); } +// Layers a painted top or bottom surface colors; 0 follows the shell layer count. +static int color_penetration_layers(const ConfigOptionInt &penetration_layers, const ConfigOptionInt &shell_layers) +{ + return penetration_layers.value > 0 ? penetration_layers.value : shell_layers.value; +} + // Returns segmentation of top and bottom layers based on painting in segmentation gizmos. static inline std::vector> segmentation_top_and_bottom_layers(const PrintObject &print_object, const std::vector &input_expolygons, @@ -1252,8 +1258,8 @@ static inline std::vector> segmentation_top_and_bottom_l int max_bottom_layers = 0; for (size_t i = 0; i < print_object.num_printing_regions(); ++ i) { const PrintRegionConfig &config = print_object.printing_region(i).config(); - max_top_layers = std::max(max_top_layers, config.top_shell_layers.value); - max_bottom_layers = std::max(max_bottom_layers, config.bottom_shell_layers.value); + max_top_layers = std::max(max_top_layers, color_penetration_layers(config.top_color_penetration_layers, config.top_shell_layers)); + max_bottom_layers = std::max(max_bottom_layers, color_penetration_layers(config.bottom_color_penetration_layers, config.bottom_shell_layers)); } // Project upwards pointing painted triangles over top surfaces, @@ -1289,8 +1295,8 @@ static inline std::vector> segmentation_top_and_bottom_l slicing_params.trafo = volume_trafo; Polygons bottom_slice = slice_mesh(painted, zs[0], slicing_params); - // Only the requested projections exist: with - // top_shell_layers = 0 `top` is empty and erasing its begin() was + // Only the requested projections exist: with no top + // penetration layers `top` is empty and erasing its begin() was // undefined (found by fuzzing: a sunk, painted object crashed here). if (! top.empty()) top.erase(top.begin()); @@ -1402,9 +1408,9 @@ static inline std::vector> segmentation_top_and_bottom_l // Minimum radius of a region to be printable. Used to filter regions by morphological opening. float small_region_threshold { 0.f }; // Maximum number of top layers for a queried color. - int top_shell_layers { 0 }; + int top_penetration_layers { 0 }; // Maximum number of bottom layers for a queried color. - int bottom_shell_layers { 0 }; + int bottom_penetration_layers { 0 }; //BBS: spacing according to width and layer height float extrusion_spacing{ 0.f }; }; @@ -1419,8 +1425,8 @@ static inline std::vector> segmentation_top_and_bottom_l //BBS: the extrusion line width is outer wall rather than inner wall double outer_wall_line_width = resolve_outer_wall_line_width(config, print_object.config(), print_object.print()->config()); out.extrusion_width = std::max(out.extrusion_width, outer_wall_line_width); - out.top_shell_layers = std::max(out.top_shell_layers, config.top_shell_layers); - out.bottom_shell_layers = std::max(out.bottom_shell_layers, config.bottom_shell_layers); + out.top_penetration_layers = std::max(out.top_penetration_layers, color_penetration_layers(config.top_color_penetration_layers, config.top_shell_layers)); + out.bottom_penetration_layers = std::max(out.bottom_penetration_layers, color_penetration_layers(config.bottom_color_penetration_layers, config.bottom_shell_layers)); out.small_region_threshold = config.gap_infill_speed.get_at(print_object.print()->get_extruder_id(config.outer_wall_filament_id - 1)) > 0 ? // Gap fill enabled. Enable a single line of 1/2 extrusion width. 0.5f * outer_wall_line_width : @@ -1497,7 +1503,7 @@ static inline std::vector> segmentation_top_and_bottom_l if (! top_ex.empty()) { append(triangles_by_color_top[color_idx][layer_idx], top_ex); std::vector shell_layers; - for (int last_idx = int(layer_idx) - 1; last_idx > std::max(int(layer_idx - stat.top_shell_layers), int(0)); --last_idx) + for (int last_idx = int(layer_idx) - 1; last_idx > std::max(int(layer_idx - stat.top_penetration_layers), int(0)); --last_idx) shell_layers.emplace_back(size_t(last_idx)); project_to_shells(top_ex, layer_idx, shell_layers, stat, shell_triangles_by_color_top[color_idx][layer_idx]); } @@ -1509,7 +1515,7 @@ static inline std::vector> segmentation_top_and_bottom_l if (! bottom_ex.empty()) { append(triangles_by_color_bottom[color_idx][layer_idx], bottom_ex); std::vector shell_layers; - for (size_t last_idx = layer_idx + 1; last_idx < std::min(layer_idx + stat.bottom_shell_layers, num_layers); ++last_idx) + for (size_t last_idx = layer_idx + 1; last_idx < std::min(layer_idx + stat.bottom_penetration_layers, num_layers); ++last_idx) shell_layers.emplace_back(last_idx); project_to_shells(bottom_ex, layer_idx, shell_layers, stat, shell_triangles_by_color_bottom[color_idx][layer_idx]); } diff --git a/src/libslic3r/PerimeterGenerator.cpp b/src/libslic3r/PerimeterGenerator.cpp index 42963a4575..6f86022ced 100644 --- a/src/libslic3r/PerimeterGenerator.cpp +++ b/src/libslic3r/PerimeterGenerator.cpp @@ -592,12 +592,13 @@ static ExtrusionEntityCollection traverse_extrusions(const PerimeterGenerator& p assert(std::prev(it)->polyline.last_point() == it->polyline.first_point()); } ExtrusionMultiPath multi_path; + multi_path.inset_idx = extrusion->inset_idx; multi_path.paths.emplace_back(std::move(paths.front())); for (auto it_path = std::next(paths.begin()); it_path != paths.end(); ++it_path) { if (multi_path.paths.back().last_point() != it_path->first_point()) { extrusion_coll.append(ExtrusionMultiPath(std::move(multi_path))); - multi_path = ExtrusionMultiPath(); + multi_path.paths.clear(); } multi_path.paths.emplace_back(std::move(*it_path)); } diff --git a/src/libslic3r/Preset.cpp b/src/libslic3r/Preset.cpp index e643e38b95..af8a29d2d1 100644 --- a/src/libslic3r/Preset.cpp +++ b/src/libslic3r/Preset.cpp @@ -1163,10 +1163,12 @@ static std::vector s_Preset_print_options{ "slicing_mode", "top_shell_layers", "top_shell_thickness", + "top_color_penetration_layers", "top_surface_density", "bottom_surface_density", "bottom_shell_layers", "bottom_shell_thickness", + "bottom_color_penetration_layers", "extra_perimeters_on_overhangs", "ensure_vertical_shell_thickness", "reduce_crossing_wall", diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index 1e6079ff8c..ae05bde2a0 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -1541,6 +1541,17 @@ void PrintConfigDef::init_fff_params() def->min = 0; def->set_default_value(new ConfigOptionFloat(0.)); + def = this->add("bottom_color_penetration_layers", coInt); + def->label = L("Bottom paint penetration layers"); + def->category = L("Strength"); + def->sidetext = L("layers"); + def->tooltip = L("The number of layers, including the bottom surface layer, that take the color painted on a bottom surface. " + "Set to 0 to use the bottom shell layers. A value larger than the bottom shell also colors the sparse " + "infill above the painted area."); + def->min = 0; + def->mode = comAdvanced; + def->set_default_value(new ConfigOptionInt(0)); + def = this->add("gap_fill_target", coEnum); def->label = L("Apply gap fill"); def->category = L("Strength"); @@ -8134,6 +8145,17 @@ void PrintConfigDef::init_fff_params() def->min = 0; def->set_default_value(new ConfigOptionFloat(0.6)); + def = this->add("top_color_penetration_layers", coInt); + def->label = L("Top paint penetration layers"); + def->category = L("Strength"); + def->sidetext = L("layers"); + def->tooltip = L("The number of layers, including the top surface layer, that take the color painted on a top surface. " + "Set to 0 to use the top shell layers. A value larger than the top shell also colors the sparse " + "infill below the painted area."); + def->min = 0; + def->mode = comAdvanced; + def->set_default_value(new ConfigOptionInt(0)); + def = this->add("separated_infills", coBool); def->label = L("Separated infills"); def->category = L("Strength"); diff --git a/src/libslic3r/PrintConfig.hpp b/src/libslic3r/PrintConfig.hpp index 51b5640593..98082bc52c 100644 --- a/src/libslic3r/PrintConfig.hpp +++ b/src/libslic3r/PrintConfig.hpp @@ -1449,6 +1449,7 @@ PRINT_CONFIG_CLASS_DEFINE( ((ConfigOptionStrings, print_extruder_variant)) ((ConfigOptionInt, bottom_shell_layers)) ((ConfigOptionFloat, bottom_shell_thickness)) + ((ConfigOptionInt, bottom_color_penetration_layers)) ((ConfigOptionFloat, bridge_angle)) ((ConfigOptionFloat, internal_bridge_angle)) // ORCA: Internal bridge angle override ((ConfigOptionBool, relative_bridge_angle)) // ORCA: Relative bridge angle flag @@ -1557,6 +1558,7 @@ PRINT_CONFIG_CLASS_DEFINE( ((ConfigOptionFloatOrPercent, top_surface_line_width)) ((ConfigOptionInt, top_shell_layers)) ((ConfigOptionFloat, top_shell_thickness)) + ((ConfigOptionInt, top_color_penetration_layers)) ((ConfigOptionFloat, top_surface_expansion)) ((ConfigOptionFloat, top_surface_expansion_margin)) ((ConfigOptionEnum, top_surface_expansion_direction)) diff --git a/src/libslic3r/PrintObject.cpp b/src/libslic3r/PrintObject.cpp index 6dd48e530d..634d2ed291 100644 --- a/src/libslic3r/PrintObject.cpp +++ b/src/libslic3r/PrintObject.cpp @@ -1634,7 +1634,9 @@ bool PrintObject::invalidate_state_by_config_options( steps.emplace_back(posSupportMaterial); } else if ( opt_key == "bottom_shell_layers" - || opt_key == "top_shell_layers") { + || opt_key == "top_shell_layers" + || opt_key == "top_color_penetration_layers" + || opt_key == "bottom_color_penetration_layers") { steps.emplace_back(posSlice); #if (0) diff --git a/src/libvgcode/include/GCodeInputData.hpp b/src/libvgcode/include/GCodeInputData.hpp index a0057230e7..e9b0983dde 100644 --- a/src/libvgcode/include/GCodeInputData.hpp +++ b/src/libvgcode/include/GCodeInputData.hpp @@ -26,11 +26,11 @@ struct GCodeInputData // // Palette for extruders colors // - Palette tools_colors; + PaletteWithAlpha tools_colors; // // Palette for color print colors // - Palette color_print_colors; + PaletteWithAlpha color_print_colors; }; } // namespace libvgcode diff --git a/src/libvgcode/include/Types.hpp b/src/libvgcode/include/Types.hpp index 1c3b50208a..ef61af9e3a 100644 --- a/src/libvgcode/include/Types.hpp +++ b/src/libvgcode/include/Types.hpp @@ -63,6 +63,13 @@ using Color = std::array; // using Palette = std::vector; +// +// ORCA: RGB color and opacity, 255 is opaque. Filament colors can be translucent. +// [3] -> alpha +// +using ColorWithAlpha = std::array; +using PaletteWithAlpha = std::vector; + // // Axis aligned box in 3 dimensions // [0] -> { min_x, min_y, min_z } diff --git a/src/libvgcode/include/Viewer.hpp b/src/libvgcode/include/Viewer.hpp index 97b1c335f6..7343f75af7 100644 --- a/src/libvgcode/include/Viewer.hpp +++ b/src/libvgcode/include/Viewer.hpp @@ -65,6 +65,15 @@ public: // void render(const Mat4x4& view_matrix, const Mat4x4& projection_matrix); // + // ORCA: render() leaves out the toolpaths of translucent filaments, which this draws over + // the scene afterwards, so that the caller can shade the opaque scene in between. + // + void render_translucent(const Mat4x4& view_matrix, const Mat4x4& projection_matrix); + // + // ORCA: whether the last render() left out any toolpaths for render_translucent() to draw. + // + bool has_translucent_toolpaths() const; + // // ORCA: realistic view. Render the toolpaths as seen from the light, to fill the caller's // shadow map. Depth only - the caller masks colour writes and owns the framebuffer. // @@ -88,6 +97,11 @@ public: // ORCA: direction to the top light in eye space, shading the toolpaths and biasing their shadow lookup. // void set_light_top_dir(const Vec3& direction); + // + // ORCA: whether the filaments catch an untinted highlight, on by default; the caller ties it to the realistic + // view and its glossy toolpaths setting. + // + void set_gloss(bool gloss); // // ************************************************************************ @@ -129,6 +143,12 @@ public: float get_dim_previous_layers_brightness() const; void set_dim_previous_layers_brightness(float value); // + // Translucent filaments (ORCA) + // Whether the filament colors keep their opacity, or are all drawn opaque. + // + bool is_translucent_filaments() const; + void set_translucent_filaments(bool value); + // // Returns true if the given option is visible. // bool is_option_visible(EOptionType type) const; @@ -177,12 +197,12 @@ public: // Return the palette used to render the toolpaths when // the view type is EViewType::Tool. // - const Palette& get_tool_colors() const; + const PaletteWithAlpha& get_tool_colors() const; // // Set the palette used to render the toolpaths when // the view type is EViewType::Tool with the given one. // - void set_tool_colors(const Palette& colors); + void set_tool_colors(const PaletteWithAlpha& colors); // // Return the count of colors in the palette used to render // the toolpaths when the view type is EViewType::ColorPrint. @@ -192,12 +212,12 @@ public: // Return the palette used to render the toolpaths when // the view type is EViewType::ColorPrint. // - const Palette& get_color_print_colors() const; + const PaletteWithAlpha& get_color_print_colors() const; // // Set the palette used to render the toolpaths when // the view type is EViewType::ColorPrint with the given one. // - void set_color_print_colors(const Palette& colors); + void set_color_print_colors(const PaletteWithAlpha& colors); // // Get the color range for the given view type. // Valid view types are: diff --git a/src/libvgcode/src/SegmentTemplate.cpp b/src/libvgcode/src/SegmentTemplate.cpp index 3887f4128f..3e085761d5 100644 --- a/src/libvgcode/src/SegmentTemplate.cpp +++ b/src/libvgcode/src/SegmentTemplate.cpp @@ -19,7 +19,9 @@ namespace libvgcode { // The eight corners the vertex shader knows how to place. Each is sent once and // referenced by INDEX_DATA below, so the post-transform cache can reuse it across // the triangles that share it: the shader runs 8 times per segment instead of 24. -static constexpr const std::array VERTEX_DATA = { 0, 1, 2, 3, 4, 5, 6, 7 }; +// ORCA: 32-bit, as Metal takes only vertex strides that are a multiple of 4 bytes, and +// the OpenGL driver Parallels Desktop builds on it draws no segment from packed uint8 ones. +static constexpr const std::array VERTEX_DATA = { 0, 1, 2, 3, 4, 5, 6, 7 }; // 16-bit indices: GCN 1/2 GPUs have no 8-bit index support, and some of their drivers // emulate it wrongly in instanced draws. @@ -39,7 +41,7 @@ void SegmentTemplate::init() if (m_vao_id != 0) return; - m_size_in_bytes_gpu += VERTEX_DATA.size() * sizeof(uint8_t) + INDEX_DATA.size() * sizeof(uint16_t); + m_size_in_bytes_gpu += VERTEX_DATA.size() * sizeof(uint32_t) + INDEX_DATA.size() * sizeof(uint16_t); int curr_vertex_array; glsafe(glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &curr_vertex_array)); @@ -51,12 +53,12 @@ void SegmentTemplate::init() glsafe(glGenBuffers(1, &m_vbo_id)); glsafe(glBindBuffer(GL_ARRAY_BUFFER, m_vbo_id)); - glsafe(glBufferData(GL_ARRAY_BUFFER, VERTEX_DATA.size() * sizeof(uint8_t), VERTEX_DATA.data(), GL_STATIC_DRAW)); + glsafe(glBufferData(GL_ARRAY_BUFFER, VERTEX_DATA.size() * sizeof(uint32_t), VERTEX_DATA.data(), GL_STATIC_DRAW)); glsafe(glEnableVertexAttribArray(0)); #ifdef ENABLE_OPENGL_ES - glsafe(glVertexAttribPointer(0, 1, GL_UNSIGNED_BYTE, GL_FALSE, 0, (const void*)0)); + glsafe(glVertexAttribPointer(0, 1, GL_UNSIGNED_INT, GL_FALSE, 0, (const void*)0)); #else - glsafe(glVertexAttribIPointer(0, 1, GL_UNSIGNED_BYTE, 0, (const void*)0)); + glsafe(glVertexAttribIPointer(0, 1, GL_UNSIGNED_INT, 0, (const void*)0)); #endif // ENABLE_OPENGL_ES // The element buffer binding is part of the vao state, so it is left bound here diff --git a/src/libvgcode/src/Settings.hpp b/src/libvgcode/src/Settings.hpp index fe205531f2..768903759f 100644 --- a/src/libvgcode/src/Settings.hpp +++ b/src/libvgcode/src/Settings.hpp @@ -26,6 +26,8 @@ struct Settings bool dim_previous_layers{ false }; // ORCA: how bright those darkened layers are rendered, 1.0 = unchanged, 0.0 = black float dim_previous_layers_brightness{ 0.4f }; + // ORCA: when disabled, the filaments are drawn opaque whatever their color's opacity + bool translucent_filaments{ true }; bool spiral_vase_mode{ false }; // // Required update flags diff --git a/src/libvgcode/src/Shaders.hpp b/src/libvgcode/src/Shaders.hpp index eaf143f583..447ed4b76b 100644 --- a/src/libvgcode/src/Shaders.hpp +++ b/src/libvgcode/src/Shaders.hpp @@ -15,6 +15,7 @@ static const char* Segments_Vertex_Shader = "#define POINTY_CAPS\n" "#define FIX_TWISTING\n" "uniform vec3 light_top_dir;\n" +"uniform float gloss_strength;\n" "const float light_top_diffuse = 0.6 * 0.8;\n" // ORCA: the specular was 0.6 * 0.125, too faint to give the filament any sheen. "const float light_top_specular = 0.6 * 0.25;\n" @@ -23,6 +24,7 @@ static const char* Segments_Vertex_Shader = "const float light_front_diffuse = 0.6 * 0.2;\n" "const float ambient = 0.2;\n" "const float emission = 0.15;\n" +"const float REFERENCE_THICKNESS = 0.4;\n" "const vec3 UP = vec3(0, 0, 1);\n" "uniform mat4 view_matrix;\n" "uniform mat4 projection_matrix;\n" @@ -37,26 +39,36 @@ static const char* Segments_Vertex_Shader = // ORCA: section view "uniform vec4 clipping_plane;\n" "in int vertex_id;\n" +// ORCA: built with DEPTH_ONLY for the first order independent pass, the shaders keep the geometry and the joint cut +// but neither shade nor carry the colors, see ViewerImpl::render_translucent_segments() +"#ifndef DEPTH_ONLY\n" "out vec3 color;\n" "// ORCA: realistic view - the light the shadow map is able to block, kept apart from the\n" "// ambient and emissive terms in color, which a shadow does not occlude. Their sum is the\n" "// single lighting term this replaces, so shading is unchanged while shadows are off.\n" "out vec3 color_direct;\n" +"#endif\n" "// ORCA: realistic view - the fragment shader looks the fragment up in the shadow map, which\n" "// needs its world position and, for the depth bias, its eye space normal.\n" "out vec3 world_position;\n" +"#ifndef DEPTH_ONLY\n" "out vec3 shadow_normal;\n" +"#endif\n" // ORCA: section view - the segment and the light on its cut face "flat out int segment_id;\n" +"#ifndef DEPTH_ONLY\n" "out vec3 cut_color_direct;\n" +"#endif\n" +// ORCA: the opaque and the translucent segments are drawn in separate passes, see ViewerImpl::render_segments(). +"uniform int first_instance;\n" +"flat out float alpha;\n" // ORCA: the layers greyed or dimmed around the one the sliders show, see ViewerImpl::set_layer_colors(). "uniform ivec2 lit_layers;\n" "uniform int grey_below_layer;\n" "uniform float dim_brightness;\n" "uniform int kept_vertex;\n" -"vec3 decode_color(float color, int id, int layer) {\n" -" int c = int(round(color));\n" -" vec3 rgb = vec3((c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF);\n" +"vec3 decode_color(vec3 color, int id, int layer) {\n" +" vec3 rgb = round(255.0 * color);\n" " if (id != kept_vertex && layer != lit_layers.x && layer != lit_layers.y) {\n" " if (dim_brightness >= 0.0)\n" " rgb = floor(rgb * dim_brightness);\n" @@ -72,9 +84,18 @@ static const char* Segments_Vertex_Shader = " float top_specular = light_top_specular * pow(max(dot(-normalize(eye_position), reflect(-light_top_dir, eye_normal)), 0.0), light_top_shininess);\n" " return top_diffuse + front_diffuse + top_specular;\n" "}\n" +// ORCA: in realistic view, and on a translucent filament, the highlight is the fragment shader's, untinted +"float diffuse_lighting(vec3 eye_normal) {\n" +" return light_top_diffuse * max(dot(eye_normal, light_top_dir), 0.0) + light_front_diffuse * max(dot(eye_normal, light_front_dir), 0.0);\n" +"}\n" "void main() {\n" -" int instance = reverse_order ? instances_count - 1 - gl_InstanceID : gl_InstanceID;\n" +" int instance = first_instance + (reverse_order ? instances_count - 1 - gl_InstanceID : gl_InstanceID);\n" " int id_a = int(texelFetch(segment_index_tex, instance).r);\n" +"#ifdef DEPTH_ONLY\n" +" alpha = 0.0;\n" +"#else\n" +" alpha = texelFetch(color_tex, id_a).a;\n" +"#endif\n" " int id_b = id_a + 1;\n" " vec3 pos_a = texelFetch(position_tex, id_a).xyz;\n" " vec3 pos_b = texelFetch(position_tex, id_b).xyz;\n" @@ -95,6 +116,29 @@ static const char* Segments_Vertex_Shader = " else\n" " line_right_dir = normalize(cross(line_dir, UP));\n" " vec3 line_up_dir = normalize(cross(line_right_dir, line_dir));\n" +// ORCA: the direction of the path across each joint, for the caps below; the fragment shader cuts the segment at +// its joints. The w of a position carries 0.5 at a joint, see extract_pos_and_or_hwa(). +" vec3 joint_prev = vec3(0.0);\n" +" vec3 joint_next = vec3(0.0);\n" +" if (alpha < 1.0 || gloss_strength > 0.0) {\n" +" if (id_a > 0 && fract(texelFetch(position_tex, id_a).w) > 0.25) {\n" +" vec3 prev = pos_a - texelFetch(position_tex, id_a - 1).xyz;\n" +// ORCA: past the vertex repeated in place that starts a split path +" if (dot(prev, prev) < 1e-4 && id_a > 1)\n" +" prev = pos_a - texelFetch(position_tex, id_a - 2).xyz;\n" +" vec3 n = dot(prev, prev) > 1e-8 ? normalize(prev) + line_dir : vec3(0.0);\n" +" if (dot(n, n) > 1e-4)\n" +" joint_prev = prev;\n" +" }\n" +" if (id_b + 1 < textureSize(position_tex) && fract(texelFetch(position_tex, id_b).w) > 0.25) {\n" +" vec3 next = texelFetch(position_tex, id_b + 1).xyz - pos_b;\n" +" if (dot(next, next) < 1e-4 && id_b + 2 < textureSize(position_tex))\n" +" next = texelFetch(position_tex, id_b + 2).xyz - pos_b;\n" +" vec3 n = dot(next, next) > 1e-8 ? line_dir + normalize(next) : vec3(0.0);\n" +" if (dot(n, n) > 1e-4)\n" +" joint_next = next;\n" +" }\n" +" }\n" " const vec2 horizontal_vertical_view_signs_array[16] = vec2[](\n" " //horizontal view (from right)\n" " vec2(1.0, 0.0),\n" @@ -119,6 +163,14 @@ static const char* Segments_Vertex_Shader = " vec3 endpoint_pos = vertex_id < 4 ? pos_a : pos_b;\n" " vec4 hwa = texelFetch(height_width_angle_tex, id);\n" " vec3 height_width_angle = hwa.xyz;\n" +// ORCA: across the vertex repeated in place that starts a split path, a cut joint keeps no angle. The caps take +// it from the joint, to fill the outside of the turn as at any other joint. +" vec3 joint_other = vertex_id < 4 ? joint_prev : joint_next;\n" +" if (height_width_angle.z == 0.0 && dot(joint_other, joint_other) > 0.0) {\n" +" vec3 into = vertex_id < 4 ? joint_other : line;\n" +" vec3 onto = vertex_id < 4 ? line : joint_other;\n" +" height_width_angle.z = atan(into.x * onto.y - into.y * onto.x, dot(into, onto));\n" +" }\n" " // ORCA: Extract bias from w component\n" " float bias = hwa.w;\n" "#ifdef FIX_TWISTING\n" @@ -131,6 +183,15 @@ static const char* Segments_Vertex_Shader = " vec3 camera_view_dir = normalize(endpoint_pos - camera_position);\n" " vec3 diagonal_dir_border = normalize(height_width_angle.x * line_up_dir + height_width_angle.y * line_right_dir);\n" "#endif\n" +// ORCA: a filament's opacity is that of REFERENCE_THICKNESS mm of it, here the path of the view ray through the extrusion +"#ifndef DEPTH_ONLY\n" +" if (alpha < 1.0) {\n" +" vec2 hw = texelFetch(height_width_angle_tex, id_a).xy;\n" +" float path = 1.0 / max(abs(dot(camera_view_dir, line_up_dir)) / hw.x + abs(dot(camera_view_dir, line_right_dir)) / hw.y, 1e-3);\n" +// ORCA: below 1, which would take a translucent segment for an opaque one +" alpha = min(1.0 - pow(1.0 - alpha, min(path / REFERENCE_THICKNESS, 16.0)), 0.999);\n" +" }\n" +"#endif\n" " bool is_vertical_view = abs(dot(camera_view_dir, line_up_dir)) / abs(dot(diagonal_dir_border, line_up_dir)) >\n" " abs(dot(camera_view_dir, line_right_dir)) / abs(dot(diagonal_dir_border, line_right_dir));\n" " vec2 signs = horizontal_vertical_view_signs_array[vertex_id + 8 * int(is_vertical_view)];\n" @@ -163,15 +224,18 @@ static const char* Segments_Vertex_Shader = " vec3 eye_position = (view_matrix * vec4(pos, 1.0)).xyz;\n" " // ORCA: Apply bias to z-position to avoid z-fighting\n" " eye_position.z += bias;\n" -" vec3 eye_normal = (view_matrix * vec4(normalize(pos - endpoint_pos), 0.0)).xyz;\n" -" vec3 color_base = decode_color(texelFetch(color_tex, id).r, id, int(texelFetch(position_tex, id).w));\n" -" color = color_base * (ambient + emission);\n" -" color_direct = color_base * direct_lighting(eye_position, eye_normal);\n" " world_position = pos;\n" -" shadow_normal = eye_normal;\n" " segment_id = id_a;\n" +"#ifndef DEPTH_ONLY\n" +" vec3 eye_normal = (view_matrix * vec4(normalize(pos - endpoint_pos), 0.0)).xyz;\n" +" vec3 color_base = decode_color(texelFetch(color_tex, id).rgb, id, int(texelFetch(position_tex, id).w));\n" +" color = color_base * (ambient + emission);\n" +" color_direct = color_base * ((alpha < 1.0 || gloss_strength > 0.0) ? diffuse_lighting(eye_normal) : direct_lighting(eye_position, eye_normal));\n" +" shadow_normal = eye_normal;\n" " cut_color_direct = clipping_plane.xyz == vec3(0.0) ? vec3(0.0) :\n" -" color_base * direct_lighting(eye_position, mat3(view_matrix) * -clipping_plane.xyz);\n" +" color_base * ((alpha < 1.0 || gloss_strength > 0.0) ? diffuse_lighting(mat3(view_matrix) * -clipping_plane.xyz) :\n" +" direct_lighting(eye_position, mat3(view_matrix) * -clipping_plane.xyz));\n" +"#endif\n" " gl_Position = projection_matrix * vec4(eye_position, 1.0);\n" "}\n"; @@ -188,11 +252,16 @@ static const char* Segments_Shadow_Caster_Vertex_Shader = "uniform bool reverse_order;\n" "uniform int instances_count;\n" "out vec3 world_position;\n" +"uniform samplerBuffer color_tex;\n" +"flat out float alpha;\n" +"flat out int segment_id;\n" "void main() {\n" " int segment = gl_VertexID / 6;\n" " int corner = CORNERS[gl_VertexID - 6 * segment];\n" " int instance = reverse_order ? instances_count - 1 - segment : segment;\n" " int id_a = int(texelFetch(segment_index_tex, instance).r);\n" +" alpha = texelFetch(color_tex, id_a).a;\n" +" segment_id = id_a;\n" " int id = corner < 2 ? id_a : id_a + 1;\n" " vec3 pos_a = texelFetch(position_tex, id_a).xyz;\n" " vec3 pos_b = texelFetch(position_tex, id_a + 1).xyz;\n" @@ -218,9 +287,17 @@ static const char* Segments_Shadow_Caster_Fragment_Shader = "#version 150\n" "uniform vec4 clipping_plane;\n" "in vec3 world_position;\n" +"flat in float alpha;\n" +"flat in int segment_id;\n" +// ORCA: a translucent segment covers a share of the texels as large as its opacity, in an ordered pattern the +// receivers' 5x5 filter reads as a lighter shadow. The pattern moves with the segment, so stacked layers add up. +"const float BAYER[16] = float[](0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0);\n" "void main() {\n" " if (dot(vec4(world_position, 1.0), clipping_plane) < 0.0)\n" " discard;\n" +" ivec2 cell = (ivec2(gl_FragCoord.xy) + ivec2(segment_id, segment_id >> 2)) & 3;\n" +" if (alpha < 1.0 && (BAYER[4 * cell.y + cell.x] + 0.5) / 16.0 > alpha)\n" +" discard;\n" "}\n"; static const char* Segments_Fragment_Shader = @@ -248,13 +325,35 @@ static const char* Segments_Fragment_Shader = "uniform samplerBuffer height_width_angle_tex;\n" "const vec3 UP = vec3(0, 0, 1);\n" "const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);\n" +// ORCA: in realistic view every filament is glossy, with an untinted highlight a translucent one's opacity does not dim +"uniform float gloss_strength;\n" +"const float GLOSS_SHININESS = 80.0;\n" +"#ifndef DEPTH_ONLY\n" "in vec3 color;\n" "in vec3 color_direct;\n" +"#endif\n" "in vec3 world_position;\n" +"#ifndef DEPTH_ONLY\n" "in vec3 shadow_normal;\n" +"#endif\n" "flat in int segment_id;\n" +"#ifndef DEPTH_ONLY\n" "in vec3 cut_color_direct;\n" +"#endif\n" +"flat in float alpha;\n" "out vec4 fragment_color;\n" +// ORCA: order independent transparency, see ViewerImpl::render_translucent_segments(). Pass 1 finds the depth of +// the nearest translucent surface, pass 2 sets that surface apart and adds up the weighted others. +"out float oit_reveal;\n" +"out vec4 oit_front;\n" +"#ifdef DEPTH_ONLY\n" +"const int oit_pass = 1;\n" +"#else\n" +"uniform int oit_pass;\n" +"#endif\n" +"uniform sampler2D opaque_depth;\n" +"uniform sampler2D front_depth;\n" +"uniform vec2 oit_depth_range;\n" "float shadow_shade(vec3 position, vec3 normal) {\n" " if (shadow_intensity <= 0.0)\n" " return 1.0;\n" @@ -298,19 +397,126 @@ static const char* Segments_Fragment_Shader = " texelFetch(height_width_angle_tex, segment_id + 1).xy, along);\n" " return abs(dot(offset, right_dir)) / half_height_width.y + abs(dot(offset, cross(right_dir, line_dir))) / half_height_width.x <= 1.0;\n" "}\n" +// ORCA: two segments of a path overlap at their joint, which blending would draw twice and the highlight of +// realistic view shows on opaque ones too, so each is cut at the bisector plane of its joints: whether the +// fragment lies past the plane of the joint at vertex id, step being -1 for the start of the segment and 1 for +// its end, keeping 0.02 mm of overlap where the faces each segment turns to the camera would leave gaps without +// their caps. Past the vertex repeated in place that starts a split path, the neighbour is one vertex further. +"bool beyond_joint(int id, vec3 pos, vec3 line_dir, int step) {\n" +" int size = textureSize(position_tex);\n" +" if (id + step < 0 || id + step >= size || fract(texelFetch(position_tex, id).w) <= 0.25)\n" +" return false;\n" +" vec3 dir = float(step) * (texelFetch(position_tex, id + step).xyz - pos);\n" +" if (dot(dir, dir) < 1e-4 && id + 2 * step >= 0 && id + 2 * step < size)\n" +" dir = float(step) * (texelFetch(position_tex, id + 2 * step).xyz - pos);\n" +" vec3 n = dot(dir, dir) > 1e-8 ? normalize(dir) + line_dir : vec3(0.0);\n" +" return dot(n, n) > 1e-4 && float(step) * dot(normalize(n), world_position - pos) > 0.02;\n" +"}\n" "void main() {\n" -" vec3 c;\n" -" if (dot(vec4(world_position, 1.0), clipping_plane) >= 0.0)\n" -" c = color + color_direct * shadow_shade(world_position, shadow_normal);\n" -" else {\n" -" vec3 cut;\n" -" if (!find_cut(cut))\n" +" if (alpha < 1.0 || gloss_strength > 0.0) {\n" +" vec3 pos_a = texelFetch(position_tex, segment_id).xyz;\n" +" vec3 pos_b = texelFetch(position_tex, segment_id + 1).xyz;\n" +" vec3 line_dir = normalize(pos_b - pos_a);\n" +" if (beyond_joint(segment_id, pos_a, line_dir, -1) || beyond_joint(segment_id + 1, pos_b, line_dir, 1))\n" " discard;\n" -" c = color + cut_color_direct * shadow_shade(cut, mat3(view_matrix) * -clipping_plane.xyz);\n" +" }\n" +// ORCA: in the transparency passes, the opaque scene hides what lies behind it +" if (oit_pass != 0 && gl_FragCoord.z > texelFetch(opaque_depth, ivec2(gl_FragCoord.xy), 0).r)\n" +" discard;\n" +" if (oit_pass == 1) {\n" +" vec3 cut;\n" +" if (dot(vec4(world_position, 1.0), clipping_plane) < 0.0 && !find_cut(cut))\n" +" discard;\n" +" fragment_color = vec4(gl_FragCoord.z);\n" +" return;\n" +" }\n" +"#ifndef DEPTH_ONLY\n" +" vec3 c;\n" +" vec3 position = world_position;\n" +" vec3 normal = shadow_normal;\n" +" bool cut_face = false;\n" +" float shade;\n" +" if (dot(vec4(world_position, 1.0), clipping_plane) >= 0.0) {\n" +" shade = shadow_shade(position, normal);\n" +" c = color + color_direct * shade;\n" +" }\n" +" else {\n" +" if (!find_cut(position))\n" +" discard;\n" +" cut_face = true;\n" +" normal = mat3(view_matrix) * -clipping_plane.xyz;\n" +" shade = shadow_shade(position, normal);\n" +" c = color + cut_color_direct * shade;\n" " }\n" " c *= exposure;\n" " c = mix(vec3(dot(c, LUMA)), c, saturation);\n" -" fragment_color = vec4(clamp(c, 0.0, 1.0), 1.0);\n" +// ORCA: the highlight takes the normal of the rounded extrusion the segment stands for, an ellipse of its height +// and width around its centre line, smooth across a joint, where the facets of two segments would catch it +// apart. It fades out towards the tip of a path end, whose normal runs along the extrusion. +" float gloss = 0.0;\n" +" if (gloss_strength > 0.0) {\n" +" vec3 across = normalize(normal);\n" +" vec3 start = texelFetch(position_tex, segment_id).xyz;\n" +" vec3 line = texelFetch(position_tex, segment_id + 1).xyz - start;\n" +" float length_sq = dot(line, line);\n" +" if (!cut_face && length_sq > 1e-8) {\n" +" float t = clamp(dot(position - start, line) / length_sq, 0.0, 1.0);\n" +" vec2 half_height_width = 0.5 * mix(texelFetch(height_width_angle_tex, segment_id).xy, texelFetch(height_width_angle_tex, segment_id + 1).xy, t);\n" +" vec3 radial = position - start - t * line;\n" +" vec3 n = vec3(radial.xy / (half_height_width.y * half_height_width.y), radial.z / (half_height_width.x * half_height_width.x));\n" +" n = dot(n, n) > 1e-12 ? normalize(n) : UP;\n" +" across = mat3(view_matrix) * (n - dot(n, line) / length_sq * line);\n" +" }\n" +" vec3 v = projection_matrix[3][3] == 1.0 ? vec3(0.0, 0.0, 1.0) : -normalize((view_matrix * vec4(position, 1.0)).xyz);\n" +" gloss = dot(across, across) > 1e-8 ? gloss_strength * dot(across, across) * pow(max(dot(v, reflect(-light_top_dir, normalize(across))), 0.0), GLOSS_SHININESS) * shade : 0.0;\n" +" }\n" +" if (alpha == 1.0) {\n" +" fragment_color = vec4(clamp(c + gloss, 0.0, 1.0), 1.0);\n" +" return;\n" +" }\n" +// ORCA: translucent, premultiplied +" fragment_color = vec4(clamp(c, 0.0, 1.0) * alpha + gloss, alpha);\n" +" if (oit_pass != 2)\n" +" return;\n" +" if (gl_FragCoord.z <= texelFetch(front_depth, ivec2(gl_FragCoord.xy), 0).r) {\n" +" oit_front = fragment_color;\n" +" fragment_color = vec4(0.0);\n" +" oit_reveal = 0.0;\n" +" return;\n" +" }\n" +" float z = clamp((-(view_matrix * vec4(position, 1.0)).z - oit_depth_range.x) / (oit_depth_range.y - oit_depth_range.x), 0.0, 1.0);\n" +" fragment_color *= alpha * max(pow(1.0 - z, 3.0), 1e-2);\n" +" oit_reveal = -log(1.0 - alpha);\n" +" oit_front = vec4(0.0);\n" +"#endif\n" +"}\n"; + +// ORCA: weighted blended order independent transparency, see ViewerImpl::render_translucent() +static const char* Translucent_Composite_Vertex_Shader = +"#version 150\n" +"void main() {\n" +" vec2 corner = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);\n" +" gl_Position = vec4(2.0 * corner - 1.0, 0.0, 1.0);\n" +"}\n"; + +static const char* Translucent_Composite_Fragment_Shader = +"#version 150\n" +"uniform sampler2D accum_tex;\n" +"uniform sampler2D reveal_tex;\n" +"uniform sampler2D front_tex;\n" +"uniform ivec2 origin;\n" +"out vec4 fragment_color;\n" +"void main() {\n" +" ivec2 coord = ivec2(gl_FragCoord.xy) - origin;\n" +" vec4 front = texelFetch(front_tex, coord, 0);\n" +" vec4 accum = texelFetch(accum_tex, coord, 0);\n" +" if (front.a <= 0.0 && accum.a <= 0.0)\n" +" discard;\n" +" float coverage = accum.a > 0.0 ? 1.0 - exp(-texelFetch(reveal_tex, coord, 0).r) : 0.0;\n" +" vec3 behind = accum.a > 0.0 ? accum.rgb / accum.a * coverage : vec3(0.0);\n" +// the nearest surface over the weighted mean of the others +" float front_alpha = min(front.a, 1.0);\n" +" fragment_color = vec4(front.rgb + (1.0 - front_alpha) * behind, 1.0 - (1.0 - front_alpha) * (1.0 - coverage));\n" "}\n"; static const char* Options_Vertex_Shader = @@ -347,9 +553,8 @@ static const char* Options_Vertex_Shader = "uniform int grey_below_layer;\n" "uniform float dim_brightness;\n" "uniform int kept_vertex;\n" -"vec3 decode_color(float color, int id, int layer) {\n" -" int c = int(round(color));\n" -" vec3 rgb = vec3((c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF);\n" +"vec3 decode_color(vec3 color, int id, int layer) {\n" +" vec3 rgb = round(255.0 * color);\n" " if (id != kept_vertex && layer != lit_layers.x && layer != lit_layers.y) {\n" " if (dim_brightness >= 0.0)\n" " rgb = floor(rgb * dim_brightness);\n" @@ -383,7 +588,7 @@ static const char* Options_Vertex_Shader = " // ORCA: Apply bias to z-position to avoid z-fighting\n" " eye_position.z += bias;\n" " vec3 eye_normal = (view_matrix * vec4(in_normal, 0.0)).xyz;\n" -" vec3 color_base = decode_color(texelFetch(color_tex, id).r, id, int(texelFetch(position_tex, id).w));\n" +" vec3 color_base = decode_color(texelFetch(color_tex, id).rgb, id, int(texelFetch(position_tex, id).w));\n" " color = color_base * lighting(eye_position, eye_normal);\n" " gl_Position = projection_matrix * vec4(eye_position, 1.0);\n" "}\n"; diff --git a/src/libvgcode/src/ShadersES.hpp b/src/libvgcode/src/ShadersES.hpp index 12871f6249..b4983ccfcc 100644 --- a/src/libvgcode/src/ShadersES.hpp +++ b/src/libvgcode/src/ShadersES.hpp @@ -16,6 +16,7 @@ static const char* Segments_Vertex_Shader_ES = "#define POINTY_CAPS\n" "#define FIX_TWISTING\n" "uniform vec3 light_top_dir;\n" +"uniform float gloss_strength;\n" "const float light_top_diffuse = 0.6 * 0.8;\n" // ORCA: the specular was 0.6 * 0.125, too faint to give the filament any sheen. "const float light_top_specular = 0.6 * 0.25;\n" @@ -24,6 +25,7 @@ static const char* Segments_Vertex_Shader_ES = "const float light_front_diffuse = 0.6 * 0.3;\n" "const float ambient = 0.3;\n" "const float emission = 0.15;\n" +"const float REFERENCE_THICKNESS = 0.4;\n" "const vec3 UP = vec3(0, 0, 1);\n" "uniform mat4 view_matrix;\n" "uniform mat4 projection_matrix;\n" @@ -50,14 +52,16 @@ static const char* Segments_Vertex_Shader_ES = // ORCA: section view - the segment and the light on its cut face "flat out int segment_id;\n" "out vec3 cut_color_direct;\n" +// ORCA: the opaque and the translucent segments are drawn in separate passes, see ViewerImpl::render_segments(). +"uniform int first_instance;\n" +"flat out float alpha;\n" // ORCA: the layers greyed or dimmed around the one the sliders show, see ViewerImpl::set_layer_colors(). "uniform ivec2 lit_layers;\n" "uniform int grey_below_layer;\n" "uniform float dim_brightness;\n" "uniform int kept_vertex;\n" -"vec3 decode_color(float color, int id, int layer) {\n" -" int c = int(round(color));\n" -" vec3 rgb = vec3((c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF);\n" +"vec3 decode_color(vec3 color, int id, int layer) {\n" +" vec3 rgb = round(255.0 * color);\n" " if (id != kept_vertex && layer != lit_layers.x && layer != lit_layers.y) {\n" " if (dim_brightness >= 0.0)\n" " rgb = floor(rgb * dim_brightness);\n" @@ -73,6 +77,10 @@ static const char* Segments_Vertex_Shader_ES = " float top_specular = light_top_specular * pow(max(dot(-normalize(eye_position), reflect(-light_top_dir, eye_normal)), 0.0), light_top_shininess);\n" " return top_diffuse + front_diffuse + top_specular;\n" "}\n" +// ORCA: in realistic view, and on a translucent filament, the highlight is the fragment shader's, untinted +"float diffuse_lighting(vec3 eye_normal) {\n" +" return light_top_diffuse * max(dot(eye_normal, light_top_dir), 0.0) + light_front_diffuse * max(dot(eye_normal, light_front_dir), 0.0);\n" +"}\n" "ivec2 tex_coord(sampler2D sampler, int id) {\n" " ivec2 tex_size = textureSize(sampler, 0);\n" " return (tex_size.y == 1) ? ivec2(id, 0) : ivec2(id % tex_size.x, id / tex_size.x);\n" @@ -83,8 +91,9 @@ static const char* Segments_Vertex_Shader_ES = "}\n" "void main() {\n" " int vertex_id = int(vertex_id_float);\n" -" int instance = reverse_order ? instances_count - 1 - gl_InstanceID : gl_InstanceID;\n" +" int instance = first_instance + (reverse_order ? instances_count - 1 - gl_InstanceID : gl_InstanceID);\n" " int id_a = int(texelFetch(segment_index_tex, tex_coord_u(segment_index_tex, instance), 0).r);\n" +" alpha = texelFetch(color_tex, tex_coord(color_tex, id_a), 0).a;\n" " int id_b = id_a + 1;\n" " vec3 pos_a = texelFetch(position_tex, tex_coord(position_tex, id_a), 0).xyz;\n" " vec3 pos_b = texelFetch(position_tex, tex_coord(position_tex, id_b), 0).xyz;\n" @@ -105,6 +114,29 @@ static const char* Segments_Vertex_Shader_ES = " else\n" " line_right_dir = normalize(cross(line_dir, UP));\n" " vec3 line_up_dir = normalize(cross(line_right_dir, line_dir));\n" +// ORCA: the direction of the path across each joint, for the caps below; the fragment shader cuts the segment at +// its joints. The w of a position carries 0.5 at a joint, see extract_pos_and_or_hwa(). +" vec3 joint_prev = vec3(0.0);\n" +" vec3 joint_next = vec3(0.0);\n" +" if (alpha < 1.0 || gloss_strength > 0.0) {\n" +" if (id_a > 0 && fract(texelFetch(position_tex, tex_coord(position_tex, id_a), 0).w) > 0.25) {\n" +" vec3 prev = pos_a - texelFetch(position_tex, tex_coord(position_tex, id_a - 1), 0).xyz;\n" +// ORCA: past the vertex repeated in place that starts a split path +" if (dot(prev, prev) < 1e-4 && id_a > 1)\n" +" prev = pos_a - texelFetch(position_tex, tex_coord(position_tex, id_a - 2), 0).xyz;\n" +" vec3 n = dot(prev, prev) > 1e-8 ? normalize(prev) + line_dir : vec3(0.0);\n" +" if (dot(n, n) > 1e-4)\n" +" joint_prev = prev;\n" +" }\n" +" if (id_b + 1 < textureSize(position_tex, 0).x * textureSize(position_tex, 0).y && fract(texelFetch(position_tex, tex_coord(position_tex, id_b), 0).w) > 0.25) {\n" +" vec3 next = texelFetch(position_tex, tex_coord(position_tex, id_b + 1), 0).xyz - pos_b;\n" +" if (dot(next, next) < 1e-4 && id_b + 2 < textureSize(position_tex, 0).x * textureSize(position_tex, 0).y)\n" +" next = texelFetch(position_tex, tex_coord(position_tex, id_b + 2), 0).xyz - pos_b;\n" +" vec3 n = dot(next, next) > 1e-8 ? line_dir + normalize(next) : vec3(0.0);\n" +" if (dot(n, n) > 1e-4)\n" +" joint_next = next;\n" +" }\n" +" }\n" " const vec2 horizontal_vertical_view_signs_array[16] = vec2[](\n" " //horizontal view (from right)\n" " vec2(1.0, 0.0),\n" @@ -128,6 +160,14 @@ static const char* Segments_Vertex_Shader_ES = " int id = vertex_id < 4 ? id_a : id_b;\n" " vec3 endpoint_pos = vertex_id < 4 ? pos_a : pos_b;\n" " vec3 height_width_angle = texelFetch(height_width_angle_tex, tex_coord(height_width_angle_tex, id), 0).xyz;\n" +// ORCA: across the vertex repeated in place that starts a split path, a cut joint keeps no angle. The caps take +// it from the joint, to fill the outside of the turn as at any other joint. +" vec3 joint_other = vertex_id < 4 ? joint_prev : joint_next;\n" +" if (height_width_angle.z == 0.0 && dot(joint_other, joint_other) > 0.0) {\n" +" vec3 into = vertex_id < 4 ? joint_other : line;\n" +" vec3 onto = vertex_id < 4 ? line : joint_other;\n" +" height_width_angle.z = atan(into.x * onto.y - into.y * onto.x, dot(into, onto));\n" +" }\n" "#ifdef FIX_TWISTING\n" " int closer_id = (dot(camera_position - pos_a, camera_position - pos_a) < dot(camera_position - pos_b, camera_position - pos_b)) ? id_a : id_b;\n" " vec3 closer_pos = (closer_id == id_a) ? pos_a : pos_b;\n" @@ -138,6 +178,13 @@ static const char* Segments_Vertex_Shader_ES = " vec3 camera_view_dir = normalize(endpoint_pos - camera_position);\n" " vec3 diagonal_dir_border = normalize(height_width_angle.x * line_up_dir + height_width_angle.y * line_right_dir);\n" "#endif\n" +// ORCA: a filament's opacity is that of REFERENCE_THICKNESS mm of it, here the path of the view ray through the extrusion +" if (alpha < 1.0) {\n" +" vec2 hw = texelFetch(height_width_angle_tex, tex_coord(height_width_angle_tex, id_a), 0).xy;\n" +" float path = 1.0 / max(abs(dot(camera_view_dir, line_up_dir)) / hw.x + abs(dot(camera_view_dir, line_right_dir)) / hw.y, 1e-3);\n" +// ORCA: below 1, which would take a translucent segment for an opaque one +" alpha = min(1.0 - pow(1.0 - alpha, min(path / REFERENCE_THICKNESS, 16.0)), 0.999);\n" +" }\n" " bool is_vertical_view = abs(dot(camera_view_dir, line_up_dir)) / abs(dot(diagonal_dir_border, line_up_dir)) >\n" " abs(dot(camera_view_dir, line_right_dir)) / abs(dot(diagonal_dir_border, line_right_dir));\n" " vec2 signs = horizontal_vertical_view_signs_array[vertex_id + 8 * int(is_vertical_view)];\n" @@ -169,14 +216,15 @@ static const char* Segments_Vertex_Shader_ES = " }\n" " vec3 eye_position = (view_matrix * vec4(pos, 1.0)).xyz;\n" " vec3 eye_normal = (view_matrix * vec4(normalize(pos - endpoint_pos), 0.0)).xyz;\n" -" vec3 color_base = decode_color(texelFetch(color_tex, tex_coord(color_tex, id), 0).r, id, int(texelFetch(position_tex, tex_coord(position_tex, id), 0).w));\n" +" vec3 color_base = decode_color(texelFetch(color_tex, tex_coord(color_tex, id), 0).rgb, id, int(texelFetch(position_tex, tex_coord(position_tex, id), 0).w));\n" " color = color_base * (ambient + emission);\n" -" color_direct = color_base * direct_lighting(eye_position, eye_normal);\n" +" color_direct = color_base * ((alpha < 1.0 || gloss_strength > 0.0) ? diffuse_lighting(eye_normal) : direct_lighting(eye_position, eye_normal));\n" " world_position = pos;\n" " shadow_normal = eye_normal;\n" " segment_id = id_a;\n" " cut_color_direct = clipping_plane.xyz == vec3(0.0) ? vec3(0.0) :\n" -" color_base * direct_lighting(eye_position, mat3(view_matrix) * -clipping_plane.xyz);\n" +" color_base * ((alpha < 1.0 || gloss_strength > 0.0) ? diffuse_lighting(mat3(view_matrix) * -clipping_plane.xyz) :\n" +" direct_lighting(eye_position, mat3(view_matrix) * -clipping_plane.xyz));\n" " gl_Position = projection_matrix * vec4(eye_position, 1.0);\n" "}\n"; @@ -194,6 +242,9 @@ static const char* Segments_Shadow_Caster_Vertex_Shader_ES = "uniform bool reverse_order;\n" "uniform int instances_count;\n" "out vec3 world_position;\n" +"uniform sampler2D color_tex;\n" +"flat out float alpha;\n" +"flat out int segment_id;\n" "ivec2 tex_coord(sampler2D sampler, int id) {\n" " ivec2 tex_size = textureSize(sampler, 0);\n" " return (tex_size.y == 1) ? ivec2(id, 0) : ivec2(id % tex_size.x, id / tex_size.x);\n" @@ -207,6 +258,8 @@ static const char* Segments_Shadow_Caster_Vertex_Shader_ES = " int corner = CORNERS[gl_VertexID - 6 * segment];\n" " int instance = reverse_order ? instances_count - 1 - segment : segment;\n" " int id_a = int(texelFetch(segment_index_tex, tex_coord_u(segment_index_tex, instance), 0).r);\n" +" alpha = texelFetch(color_tex, tex_coord(color_tex, id_a), 0).a;\n" +" segment_id = id_a;\n" " int id = corner < 2 ? id_a : id_a + 1;\n" " vec3 pos_a = texelFetch(position_tex, tex_coord(position_tex, id_a), 0).xyz;\n" " vec3 pos_b = texelFetch(position_tex, tex_coord(position_tex, id_a + 1), 0).xyz;\n" @@ -231,11 +284,20 @@ static const char* Segments_Shadow_Caster_Vertex_Shader_ES = static const char* Segments_Shadow_Caster_Fragment_Shader_ES = "#version 300 es\n" "precision highp float;\n" +"precision highp int;\n" "uniform vec4 clipping_plane;\n" "in vec3 world_position;\n" +"flat in float alpha;\n" +"flat in int segment_id;\n" +// ORCA: a translucent segment covers a share of the texels as large as its opacity, in an ordered pattern the +// receivers' 5x5 filter reads as a lighter shadow. The pattern moves with the segment, so stacked layers add up. +"const float BAYER[16] = float[](0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0);\n" "void main() {\n" " if (dot(vec4(world_position, 1.0), clipping_plane) < 0.0)\n" " discard;\n" +" ivec2 cell = (ivec2(gl_FragCoord.xy) + ivec2(segment_id, segment_id >> 2)) & 3;\n" +" if (alpha < 1.0 && (BAYER[4 * cell.y + cell.x] + 0.5) / 16.0 > alpha)\n" +" discard;\n" "}\n"; static const char* Segments_Fragment_Shader_ES = @@ -269,12 +331,16 @@ static const char* Segments_Fragment_Shader_ES = "uniform lowp sampler2D height_width_angle_tex;\n" "const vec3 UP = vec3(0, 0, 1);\n" "const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);\n" +// ORCA: in realistic view every filament is glossy, with an untinted highlight a translucent one's opacity does not dim +"uniform float gloss_strength;\n" +"const float GLOSS_SHININESS = 80.0;\n" "in vec3 color;\n" "in vec3 color_direct;\n" "in vec3 world_position;\n" "in vec3 shadow_normal;\n" "flat in int segment_id;\n" "in vec3 cut_color_direct;\n" +"flat in float alpha;\n" "out vec4 fragment_color;\n" "float shadow_shade(vec3 position, vec3 normal) {\n" " if (shadow_intensity <= 0.0)\n" @@ -323,19 +389,74 @@ static const char* Segments_Fragment_Shader_ES = " fetch(height_width_angle_tex, segment_id + 1).xy, along);\n" " return abs(dot(offset, right_dir)) / half_height_width.y + abs(dot(offset, cross(right_dir, line_dir))) / half_height_width.x <= 1.0;\n" "}\n" +// ORCA: two segments of a path overlap at their joint, which blending would draw twice and the highlight of +// realistic view shows on opaque ones too, so each is cut at the bisector plane of its joints: whether the +// fragment lies past the plane of the joint at vertex id, step being -1 for the start of the segment and 1 for +// its end, keeping 0.02 mm of overlap where the faces each segment turns to the camera would leave gaps without +// their caps. Past the vertex repeated in place that starts a split path, the neighbour is one vertex further. +"bool beyond_joint(int id, vec3 pos, vec3 line_dir, int step) {\n" +" int size = textureSize(position_tex, 0).x * textureSize(position_tex, 0).y;\n" +" if (id + step < 0 || id + step >= size || fract(fetch(position_tex, id).w) <= 0.25)\n" +" return false;\n" +" vec3 dir = float(step) * (fetch(position_tex, id + step).xyz - pos);\n" +" if (dot(dir, dir) < 1e-4 && id + 2 * step >= 0 && id + 2 * step < size)\n" +" dir = float(step) * (fetch(position_tex, id + 2 * step).xyz - pos);\n" +" vec3 n = dot(dir, dir) > 1e-8 ? normalize(dir) + line_dir : vec3(0.0);\n" +" return dot(n, n) > 1e-4 && float(step) * dot(normalize(n), world_position - pos) > 0.02;\n" +"}\n" "void main() {\n" -" vec3 c;\n" -" if (dot(vec4(world_position, 1.0), clipping_plane) >= 0.0)\n" -" c = color + color_direct * shadow_shade(world_position, shadow_normal);\n" -" else {\n" -" vec3 cut;\n" -" if (!find_cut(cut))\n" +" if (alpha < 1.0 || gloss_strength > 0.0) {\n" +" vec3 pos_a = fetch(position_tex, segment_id).xyz;\n" +" vec3 pos_b = fetch(position_tex, segment_id + 1).xyz;\n" +" vec3 line_dir = normalize(pos_b - pos_a);\n" +" if (beyond_joint(segment_id, pos_a, line_dir, -1) || beyond_joint(segment_id + 1, pos_b, line_dir, 1))\n" " discard;\n" -" c = color + cut_color_direct * shadow_shade(cut, mat3(view_matrix) * -clipping_plane.xyz);\n" +" }\n" +" vec3 c;\n" +" vec3 position = world_position;\n" +" vec3 normal = shadow_normal;\n" +" bool cut_face = false;\n" +" float shade;\n" +" if (dot(vec4(world_position, 1.0), clipping_plane) >= 0.0) {\n" +" shade = shadow_shade(position, normal);\n" +" c = color + color_direct * shade;\n" +" }\n" +" else {\n" +" if (!find_cut(position))\n" +" discard;\n" +" cut_face = true;\n" +" normal = mat3(view_matrix) * -clipping_plane.xyz;\n" +" shade = shadow_shade(position, normal);\n" +" c = color + cut_color_direct * shade;\n" " }\n" " c *= exposure;\n" " c = mix(vec3(dot(c, LUMA)), c, saturation);\n" -" fragment_color = vec4(clamp(c, 0.0, 1.0), 1.0);\n" +// ORCA: the highlight takes the normal of the rounded extrusion the segment stands for, an ellipse of its height +// and width around its centre line, smooth across a joint, where the facets of two segments would catch it +// apart. It fades out towards the tip of a path end, whose normal runs along the extrusion. +" float gloss = 0.0;\n" +" if (gloss_strength > 0.0) {\n" +" vec3 across = normalize(normal);\n" +" vec3 start = fetch(position_tex, segment_id).xyz;\n" +" vec3 line = fetch(position_tex, segment_id + 1).xyz - start;\n" +" float length_sq = dot(line, line);\n" +" if (!cut_face && length_sq > 1e-8) {\n" +" float t = clamp(dot(position - start, line) / length_sq, 0.0, 1.0);\n" +" vec2 half_height_width = 0.5 * mix(fetch(height_width_angle_tex, segment_id).xy, fetch(height_width_angle_tex, segment_id + 1).xy, t);\n" +" vec3 radial = position - start - t * line;\n" +" vec3 n = vec3(radial.xy / (half_height_width.y * half_height_width.y), radial.z / (half_height_width.x * half_height_width.x));\n" +" n = dot(n, n) > 1e-12 ? normalize(n) : UP;\n" +" across = mat3(view_matrix) * (n - dot(n, line) / length_sq * line);\n" +" }\n" +" vec3 v = projection_matrix[3][3] == 1.0 ? vec3(0.0, 0.0, 1.0) : -normalize((view_matrix * vec4(position, 1.0)).xyz);\n" +" gloss = dot(across, across) > 1e-8 ? gloss_strength * dot(across, across) * pow(max(dot(v, reflect(-light_top_dir, normalize(across))), 0.0), GLOSS_SHININESS) * shade : 0.0;\n" +" }\n" +" if (alpha == 1.0) {\n" +" fragment_color = vec4(clamp(c + gloss, 0.0, 1.0), 1.0);\n" +" return;\n" +" }\n" +// ORCA: translucent, premultiplied +" fragment_color = vec4(clamp(c, 0.0, 1.0) * alpha + gloss, alpha);\n" "}\n"; static const char* Options_Vertex_Shader_ES = @@ -367,9 +488,8 @@ static const char* Options_Vertex_Shader_ES = "uniform int grey_below_layer;\n" "uniform float dim_brightness;\n" "uniform int kept_vertex;\n" -"vec3 decode_color(float color, int id, int layer) {\n" -" int c = int(round(color));\n" -" vec3 rgb = vec3((c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF);\n" +"vec3 decode_color(vec3 color, int id, int layer) {\n" +" vec3 rgb = round(255.0 * color);\n" " if (id != kept_vertex && layer != lit_layers.x && layer != lit_layers.y) {\n" " if (dim_brightness >= 0.0)\n" " rgb = floor(rgb * dim_brightness);\n" @@ -406,7 +526,7 @@ static const char* Options_Vertex_Shader_ES = " clipping_plane_dot = dot(vec4(offset, 1.0), clipping_plane);\n" " vec3 eye_position = (view_matrix * vec4(scale_matrix * in_position + offset, 1.0)).xyz;\n" " vec3 eye_normal = (view_matrix * vec4(in_normal, 0.0)).xyz;\n" -" vec3 color_base = decode_color(texelFetch(color_tex, tex_coord(color_tex, id), 0).r, id, int(texelFetch(position_tex, tex_coord(position_tex, id), 0).w));\n" +" vec3 color_base = decode_color(texelFetch(color_tex, tex_coord(color_tex, id), 0).rgb, id, int(texelFetch(position_tex, tex_coord(position_tex, id), 0).w));\n" " color = color_base * lighting(eye_position, eye_normal);\n" " gl_Position = projection_matrix * vec4(eye_position, 1.0);\n" "}\n"; diff --git a/src/libvgcode/src/Viewer.cpp b/src/libvgcode/src/Viewer.cpp index f4690276f7..f61cd07c3e 100644 --- a/src/libvgcode/src/Viewer.cpp +++ b/src/libvgcode/src/Viewer.cpp @@ -49,6 +49,16 @@ void Viewer::render(const Mat4x4& view_matrix, const Mat4x4& projection_matrix) m_impl->render(view_matrix, projection_matrix); } +void Viewer::render_translucent(const Mat4x4& view_matrix, const Mat4x4& projection_matrix) +{ + m_impl->render_translucent(view_matrix, projection_matrix); +} + +bool Viewer::has_translucent_toolpaths() const +{ + return m_impl->has_translucent_toolpaths(); +} + void Viewer::render_shadow_casters(const Mat4x4& view_matrix, const Mat4x4& projection_matrix, const Vec3& light_position) { m_impl->render_shadow_casters(view_matrix, projection_matrix, light_position); @@ -64,6 +74,11 @@ void Viewer::set_light_top_dir(const Vec3& direction) m_impl->set_light_top_dir(direction); } +void Viewer::set_gloss(bool gloss) +{ + m_impl->set_gloss(gloss); +} + void Viewer::set_tone(float exposure, float saturation) { m_impl->set_tone(exposure, saturation); @@ -124,6 +139,16 @@ void Viewer::set_dim_previous_layers_brightness(float value) m_impl->set_dim_previous_layers_brightness(value); } +bool Viewer::is_translucent_filaments() const +{ + return m_impl->is_translucent_filaments(); +} + +void Viewer::set_translucent_filaments(bool value) +{ + m_impl->set_translucent_filaments(value); +} + bool Viewer::is_option_visible(EOptionType type) const { return m_impl->is_option_visible(type); @@ -179,12 +204,12 @@ size_t Viewer::get_tool_colors_count() const return m_impl->get_tool_colors_count(); } -const Palette& Viewer::get_tool_colors() const +const PaletteWithAlpha& Viewer::get_tool_colors() const { return m_impl->get_tool_colors(); } -void Viewer::set_tool_colors(const Palette& colors) +void Viewer::set_tool_colors(const PaletteWithAlpha& colors) { m_impl->set_tool_colors(colors); } @@ -194,12 +219,12 @@ size_t Viewer::get_color_print_colors_count() const return m_impl->get_color_print_colors_count(); } -const Palette& Viewer::get_color_print_colors() const +const PaletteWithAlpha& Viewer::get_color_print_colors() const { return m_impl->get_color_print_colors(); } -void Viewer::set_color_print_colors(const Palette& colors) +void Viewer::set_color_print_colors(const PaletteWithAlpha& colors) { m_impl->set_color_print_colors(colors); } diff --git a/src/libvgcode/src/ViewerImpl.cpp b/src/libvgcode/src/ViewerImpl.cpp index c6fcb01ace..7908fbed5b 100644 --- a/src/libvgcode/src/ViewerImpl.cpp +++ b/src/libvgcode/src/ViewerImpl.cpp @@ -231,7 +231,9 @@ std::string check_program(GLuint handle) return ret; } -unsigned int init_shader(const std::string& shader_name, const char* vertex_shader, const char* fragment_shader) +// ORCA: fragment_outputs lists the outputs of a fragment shader that writes more than one, in location order +unsigned int init_shader(const std::string& shader_name, const char* vertex_shader, const char* fragment_shader, + const std::vector& fragment_outputs = {}) { const GLuint vs_id = glCreateShader(GL_VERTEX_SHADER); glcheck(); @@ -258,6 +260,10 @@ unsigned int init_shader(const std::string& shader_name, const char* vertex_shad glcheck(); glsafe(glAttachShader(shader_id, vs_id)); glsafe(glAttachShader(shader_id, fs_id)); +#ifndef ENABLE_OPENGL_ES + for (size_t i = 0; i < fragment_outputs.size(); ++i) + glsafe(glBindFragDataLocation(shader_id, static_cast(i), fragment_outputs[i])); +#endif // ENABLE_OPENGL_ES glsafe(glLinkProgram(shader_id)); res = check_program(shader_id); if (!res.empty()) { @@ -292,6 +298,20 @@ static void delete_buffers(unsigned int& id) } } +#ifndef ENABLE_OPENGL_ES +// ORCA: the opaque depth, then the accumulated colors of the translucent segments, see render_translucent(). +// Past the units render_segments() and the shadow map take. +static constexpr int TRANSLUCENT_TEXTURE_UNIT = 5; + +// ORCA: the source with a #define after its #version line +static std::string with_define(const char* source, const char* define) +{ + const std::string src(source); + const size_t body = src.find('\n') + 1; + return src.substr(0, body) + "#define " + define + "\n" + src.substr(body); +} +#endif // ENABLE_OPENGL_ES + static const std::array DEFAULT_EXTRUSION_ROLES_COLORS = { { { 230, 179, 179 }, // None { 255, 230, 77 }, // Perimeter @@ -467,7 +487,7 @@ void ViewerImpl::TextureData::set_heights_widths_angles(const std::vector& glsafe(glPixelStorei(GL_UNPACK_ALIGNMENT, curr_unpack_alignment)); } -void ViewerImpl::TextureData::set_colors(const std::vector& colors) +void ViewerImpl::TextureData::set_colors(const std::vector& colors) { if (m_count == 0) return; @@ -501,17 +521,17 @@ void ViewerImpl::TextureData::set_colors(const std::vector& colors) glsafe(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); glsafe(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0)); if (remaining >= tex_capacity) { - glsafe(glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, static_cast(w), static_cast(h), 0, GL_RED, GL_FLOAT, &colors[offset])); + glsafe(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, static_cast(w), static_cast(h), 0, GL_RGBA, GL_UNSIGNED_BYTE, &colors[offset])); m_tex_ids[i].colors.second = w * h; } else { // the last row is only partially fitted with data, send it separately - glsafe(glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, static_cast(w), static_cast(h), 0, GL_RED, GL_FLOAT, nullptr)); - glsafe(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, static_cast(w), static_cast(h - 1), GL_RED, GL_FLOAT, &colors[offset])); - glsafe(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, static_cast(h - 1), static_cast(remaining % w), 1, GL_RED, GL_FLOAT, &colors[offset + w * (h - 1)])); + glsafe(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, static_cast(w), static_cast(h), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr)); + glsafe(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, static_cast(w), static_cast(h - 1), GL_RGBA, GL_UNSIGNED_BYTE, &colors[offset])); + glsafe(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, static_cast(h - 1), static_cast(remaining % w), 1, GL_RGBA, GL_UNSIGNED_BYTE, &colors[offset + w * (h - 1)])); m_tex_ids[i].colors.second = w * (h - 1) + remaining % w; } - m_colors_size += m_tex_ids[i].colors.second * sizeof(float); + m_colors_size += m_tex_ids[i].colors.second * sizeof(ColorWithAlpha); remaining = (remaining > tex_capacity) ? remaining - tex_capacity : 0; } @@ -520,7 +540,7 @@ void ViewerImpl::TextureData::set_colors(const std::vector& colors) glsafe(glPixelStorei(GL_UNPACK_ALIGNMENT, curr_unpack_alignment)); } -void ViewerImpl::TextureData::set_enabled_segments(const std::vector& enabled_segments) +void ViewerImpl::TextureData::set_enabled_segments(const std::vector& enabled_segments, const std::vector& colors, bool sort_by_opacity) { if (m_count == 0) return; @@ -528,6 +548,7 @@ void ViewerImpl::TextureData::set_enabled_segments(const std::vector& for (TexIds& ids : m_tex_ids) { delete_textures(ids.enabled_segments.first); ids.enabled_segments.second = 0; + ids.enabled_translucent_segments = 0; } m_enabled_segments_size = 0; @@ -551,6 +572,12 @@ void ViewerImpl::TextureData::set_enabled_segments(const std::vector& if (!new_tex) curr_segments.push_back(seg - static_cast(curr_tex_id * tex_capacity)); if (i + 1 == enabled_segments.size() || new_tex) { + if (sort_by_opacity) { + const size_t offset = curr_tex_id * tex_capacity; + const auto translucent_begin = std::stable_partition(curr_segments.begin(), curr_segments.end(), + [&colors, offset](uint32_t s) { return colors[offset + s][3] == 255; }); + m_tex_ids[curr_tex_id].enabled_translucent_segments = static_cast(std::distance(translucent_begin, curr_segments.end())); + } const auto [w, h] = width_height(curr_segments.size()); glsafe(glGenTextures(1, &m_tex_ids[curr_tex_id].enabled_segments.first)); @@ -755,6 +782,7 @@ void ViewerImpl::SegmentsUniforms::init(unsigned int shader_id) segment_index_tex = glGetUniformLocation(shader_id, "segment_index_tex"); reverse_order = glGetUniformLocation(shader_id, "reverse_order"); instances_count = glGetUniformLocation(shader_id, "instances_count"); + first_instance = glGetUniformLocation(shader_id, "first_instance"); // ORCA: section view clipping_plane = glGetUniformLocation(shader_id, "clipping_plane"); } @@ -780,7 +808,21 @@ void ViewerImpl::init(const std::string& opengl_context_version) #ifdef ENABLE_OPENGL_ES m_segments_shader_id = init_shader("segments", Segments_Vertex_Shader_ES, Segments_Fragment_Shader_ES); #else - m_segments_shader_id = init_shader("segments", Segments_Vertex_Shader, Segments_Fragment_Shader); + m_segments_shader_id = init_shader("segments", Segments_Vertex_Shader, Segments_Fragment_Shader, { "fragment_color", "oit_reveal", "oit_front" }); + m_uni_segments_oit_pass_id = glGetUniformLocation(m_segments_shader_id, "oit_pass"); + m_uni_segments_opaque_depth_id = glGetUniformLocation(m_segments_shader_id, "opaque_depth"); + m_uni_segments_front_depth_id = glGetUniformLocation(m_segments_shader_id, "front_depth"); + m_uni_segments_oit_depth_range_id = glGetUniformLocation(m_segments_shader_id, "oit_depth_range"); + m_translucent_composite_shader_id = init_shader("translucent_composite", Translucent_Composite_Vertex_Shader, Translucent_Composite_Fragment_Shader); + m_uni_translucent_composite_accum_tex_id = glGetUniformLocation(m_translucent_composite_shader_id, "accum_tex"); + m_uni_translucent_composite_reveal_tex_id = glGetUniformLocation(m_translucent_composite_shader_id, "reveal_tex"); + m_uni_translucent_composite_front_tex_id = glGetUniformLocation(m_translucent_composite_shader_id, "front_tex"); + m_uni_translucent_composite_origin_id = glGetUniformLocation(m_translucent_composite_shader_id, "origin"); + const std::string depth_vs = with_define(Segments_Vertex_Shader, "DEPTH_ONLY"); + const std::string depth_fs = with_define(Segments_Fragment_Shader, "DEPTH_ONLY"); + m_segments_depth_shader_id = init_shader("segments_depth", depth_vs.c_str(), depth_fs.c_str(), { "fragment_color", "oit_reveal", "oit_front" }); + m_uni_segments_depth.init(m_segments_depth_shader_id); + m_uni_segments_depth_opaque_depth_id = glGetUniformLocation(m_segments_depth_shader_id, "opaque_depth"); #endif // ENABLE_OPENGL_ES m_uni_segments.init(m_segments_shader_id); @@ -792,6 +834,7 @@ void ViewerImpl::init(const std::string& opengl_context_version) m_uni_segments_exposure_id = glGetUniformLocation(m_segments_shader_id, "exposure"); m_uni_segments_saturation_id = glGetUniformLocation(m_segments_shader_id, "saturation"); m_uni_segments_light_top_dir_id = glGetUniformLocation(m_segments_shader_id, "light_top_dir"); + m_uni_segments_gloss_id = glGetUniformLocation(m_segments_shader_id, "gloss_strength"); m_uni_segments_layer_colors.init(m_segments_shader_id); glcheck(); assert(m_uni_segments.view_matrix != -1 && @@ -914,6 +957,16 @@ void ViewerImpl::shutdown() glsafe(glDeleteVertexArrays(1, &m_segments_caster_vao_id)); m_segments_caster_vao_id = 0; } +#ifndef ENABLE_OPENGL_ES + if (m_translucent_composite_shader_id != 0) { + glsafe(glDeleteProgram(m_translucent_composite_shader_id)); + m_translucent_composite_shader_id = 0; + } + if (m_segments_depth_shader_id != 0) { + glsafe(glDeleteProgram(m_segments_depth_shader_id)); + m_segments_depth_shader_id = 0; + } +#endif // ENABLE_OPENGL_ES m_initialized = false; OpenGLWrapper::unload_opengl(); } @@ -930,7 +983,10 @@ void ViewerImpl::reset() // 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().swap(m_vertices); - std::vector().swap(m_vertices_colors); + std::vector().swap(m_vertices_colors); + m_has_translucent_colors = false; + m_enabled_translucent_segments_count = 0; + m_extrusions_box = { Vec3{ 0.0f, 0.0f, 0.0f }, Vec3{ 0.0f, 0.0f, 0.0f } }; for (std::vector& times : m_layer_start_times) std::vector().swap(times); std::vector().swap(m_layer_first_vertex); @@ -960,6 +1016,7 @@ void ViewerImpl::reset() delete_buffers(m_heights_widths_angles_buf_id); delete_textures(m_positions_tex_id); delete_buffers(m_positions_buf_id); + m_translucent_targets.release(); #endif // ENABLE_OPENGL_ES } @@ -969,6 +1026,25 @@ void ViewerImpl::reset() // To let all drivers be happy, we use GL_RGBA32F format, so we need to add an extra float // to position and heights_widths_angles vectors +// whether a line is drawn from vertex i to vertex i + 1 +static bool is_line(const std::vector& vertices, size_t i) +{ + return i + 1 < vertices.size() && vertices[i + 1].position != vertices[i].position && + vertices[i + 1].type == vertices[i].type && vertices[i].type != EMoveType::Seam; +} + +// ORCA: whether two lines meet at vertex i, also across the vertex repeated in place that starts a path split +// where a value the preview colors by changes, see starts_path() in LibVGCodeWrapper.cpp +static bool is_joint(const std::vector& vertices, size_t i) +{ + auto repeated = [&vertices](size_t j) { + return j + 1 < vertices.size() && vertices[j + 1].position == vertices[j].position && vertices[j + 1].type == vertices[j].type; + }; + const bool before = i > 0 && (is_line(vertices, i - 1) || (i > 1 && repeated(i - 1) && is_line(vertices, i - 2))); + const bool after = is_line(vertices, i) || (repeated(i) && is_line(vertices, i + 1)); + return before && after; +} + static void extract_pos_and_or_hwa(const std::vector& vertices, float travels_radius, float wipes_radius, BitSet<>& valid_lines_bitset, std::vector* positions = nullptr, std::vector* heights_widths_angles = nullptr, bool update_bitset = false) { static constexpr const Vec3 ZERO = { 0.0f, 0.0f, 0.0f }; @@ -988,10 +1064,7 @@ static void extract_pos_and_or_hwa(const std::vector& vertices, floa const EMoveType move_type = v.type; const bool prev_line_valid = i > 0 && valid_lines_bitset[i - 1]; const Vec3 prev_line = prev_line_valid ? v.position - vertices[i - 1].position : ZERO; - const bool this_line_valid = i + 1 < vertices.size() && - vertices[i + 1].position != v.position && - vertices[i + 1].type == move_type && - move_type != EMoveType::Seam; + const bool this_line_valid = is_line(vertices, i); const Vec3 this_line = this_line_valid ? vertices[i + 1].position - v.position : ZERO; if (this_line_valid) { @@ -1004,8 +1077,10 @@ static void extract_pos_and_or_hwa(const std::vector& vertices, floa } if (positions != nullptr) { - // ORCA: the last component, there to comply with GL_RGBA32F format, carries the layer the shaders grey and dim by - Vec4 position = { v.position[0], v.position[1], v.position[2], static_cast(v.layer_id) }; + // ORCA: the last component, there to comply with GL_RGBA32F format, carries the layer the shaders grey and dim by, + // plus 0.5 at the joint of two segments, which the shaders read as an int, see joint_a in Segments_Vertex_Shader + Vec4 position = { v.position[0], v.position[1], v.position[2], + static_cast(v.layer_id) + (is_joint(vertices, i) ? 0.5f : 0.0f) }; if (move_type == EMoveType::Extrude) // push down extrusion vertices by half height to render them at the right z position[2] -= 0.5f * v.height; @@ -1060,6 +1135,7 @@ void ViewerImpl::load(GCodeInputData&& gcode_data) m_settings.spiral_vase_mode = gcode_data.spiral_vase_mode; + m_extrusions_box = get_bounding_box({ EMoveType::Extrude }); for (size_t i = 0; i < m_vertices.size(); ++i) { const PathVertex& v = m_vertices[i]; @@ -1217,8 +1293,8 @@ void ViewerImpl::load(GCodeInputData&& gcode_data) update_view_full_range(); m_view_range.set_visible(m_view_range.get_enabled()); - update_enabled_entities(); update_colors(); + update_enabled_entities(); } void ViewerImpl::update_enabled_entities() @@ -1277,10 +1353,20 @@ void ViewerImpl::update_enabled_entities() enabled_segments.push_back(static_cast(i)); } + // ORCA: so that each pass of render() draws only its own segments, in print order + m_enabled_translucent_segments_count = 0; #ifdef ENABLE_OPENGL_ES - m_texture_data.set_enabled_segments(enabled_segments); + m_texture_data.set_enabled_segments(enabled_segments, m_vertices_colors, m_has_translucent_colors); + for (size_t i = 0; i < m_texture_data.get_count(); ++i) + m_enabled_translucent_segments_count += m_texture_data.get_enabled_translucent_segments_count(i); m_texture_data.set_enabled_options(enabled_options); #else + if (m_has_translucent_colors) { + const auto is_opaque = [this](uint32_t id) { return m_vertices_colors[id][3] == 255; }; + const auto translucent_begin = std::stable_partition(enabled_segments.begin(), enabled_segments.end(), is_opaque); + m_enabled_translucent_segments_count = static_cast(std::distance(translucent_begin, enabled_segments.end())); + } + m_enabled_segments_count = enabled_segments.size(); m_enabled_options_count = enabled_options.size(); @@ -1309,14 +1395,6 @@ void ViewerImpl::update_enabled_entities() m_settings.update_enabled_entities = false; } -static float encode_color(const Color& color) { - const int r = static_cast(color[0]); - const int g = static_cast(color[1]); - const int b = static_cast(color[2]); - const int i_color = r << 16 | g << 8 | b; - return static_cast(i_color); -} - void ViewerImpl::update_colors_texture() { #if !defined(ENABLE_OPENGL_ES) @@ -1331,11 +1409,11 @@ void ViewerImpl::update_colors_texture() // update gpu buffer for colors m_texture_data.set_colors(m_vertices_colors); #else - m_colors_tex_size = m_vertices_colors.size() * sizeof(float); + m_colors_tex_size = m_vertices_colors.size() * sizeof(ColorWithAlpha); // update gpu buffer for colors glsafe(glBindBuffer(GL_TEXTURE_BUFFER, m_colors_buf_id)); - glsafe(glBufferData(GL_TEXTURE_BUFFER, m_vertices_colors.size() * sizeof(float), m_vertices_colors.data(), GL_STATIC_DRAW)); + glsafe(glBufferData(GL_TEXTURE_BUFFER, m_colors_tex_size, m_vertices_colors.data(), GL_STATIC_DRAW)); glsafe(glBindBuffer(GL_TEXTURE_BUFFER, 0)); #endif // ENABLE_OPENGL_ES } @@ -1387,7 +1465,7 @@ void ViewerImpl::update_colors() const size_t tool_colors_size = m_tool_colors.size(); if (m_tool_colors.size() < max_used_extruder_id) { for (size_t i = 0; i < max_used_extruder_id - tool_colors_size; ++i) { - m_tool_colors.emplace_back(DUMMY_COLOR); + m_tool_colors.push_back({ DUMMY_COLOR[0], DUMMY_COLOR[1], DUMMY_COLOR[2], 255 }); } } } @@ -1398,11 +1476,21 @@ void ViewerImpl::update_colors() // If some part of the preview should be rendered in dark grey, it is taken // care of in the shaders, see set_layer_colors(). That is to avoid the need to recalculate // the "normal" color on every slider move. - for (size_t i = 0; i < m_vertices.size(); ++i) - m_vertices_colors[i] = encode_color(get_vertex_color(m_vertices[i])); - + const bool had_translucent_colors = m_has_translucent_colors; + m_has_translucent_colors = false; + for (size_t i = 0; i < m_vertices.size(); ++i) { + const Color color = get_vertex_color(m_vertices[i]); + const uint8_t alpha = get_vertex_alpha(m_vertices[i]); + m_vertices_colors[i] = { color[0], color[1], color[2], alpha }; + m_has_translucent_colors |= alpha < 255; + } + update_colors_texture(); m_settings.update_colors = false; + + // ORCA: the enabled segments are sorted by opacity + if (had_translucent_colors || m_has_translucent_colors) + m_settings.update_enabled_entities = true; } void ViewerImpl::apply_pending_updates() @@ -1410,11 +1498,12 @@ void ViewerImpl::apply_pending_updates() if (m_settings.update_view_full_range) update_view_full_range(); - if (m_settings.update_enabled_entities) - update_enabled_entities(); - + // ORCA: the colors first, which decide the order of the enabled segments if (m_settings.update_colors) update_colors(); + + if (m_settings.update_enabled_entities) + update_enabled_entities(); } void ViewerImpl::render(const Mat4x4& view_matrix, const Mat4x4& projection_matrix) @@ -1501,6 +1590,14 @@ void ViewerImpl::set_dim_previous_layers(bool value) m_settings.dim_previous_layers = value; } +void ViewerImpl::set_translucent_filaments(bool value) +{ + if (m_settings.translucent_filaments == value) + return; + m_settings.translucent_filaments = value; + m_settings.update_colors = true; +} + // ORCA: set how bright the darkened layers are rendered, 1.0 = unchanged, 0.0 = black void ViewerImpl::set_dim_previous_layers_brightness(float value) { @@ -1708,13 +1805,16 @@ Color ViewerImpl::get_vertex_color(const PathVertex& v) const case EViewType::Tool: { assert(static_cast(v.extruder_id) < m_tool_colors.size()); - return m_tool_colors[v.extruder_id]; + const ColorWithAlpha& color = m_tool_colors[v.extruder_id]; + return { color[0], color[1], color[2] }; } case EViewType::Summary: // ORCA case EViewType::ColorPrint: { - return m_layers.layer_contains_colorprint_options(static_cast(v.layer_id)) ? DUMMY_COLOR : - m_color_print_colors[static_cast(v.color_id) % m_color_print_colors.size()]; + if (m_layers.layer_contains_colorprint_options(static_cast(v.layer_id))) + return DUMMY_COLOR; + const ColorWithAlpha& color = m_color_print_colors[static_cast(v.color_id) % m_color_print_colors.size()]; + return { color[0], color[1], color[2] }; } default: { break; } } @@ -1722,13 +1822,32 @@ Color ViewerImpl::get_vertex_color(const PathVertex& v) const return DUMMY_COLOR; } -void ViewerImpl::set_tool_colors(const Palette& colors) +// ORCA: only the extrusions colored by filament can be translucent. +uint8_t ViewerImpl::get_vertex_alpha(const PathVertex& v) const +{ + if (!m_settings.translucent_filaments || !v.is_extrusion()) + return 255; + + switch (m_settings.view_type) + { + case EViewType::Tool: + return m_tool_colors[v.extruder_id][3]; + case EViewType::Summary: + case EViewType::ColorPrint: + return m_layers.layer_contains_colorprint_options(static_cast(v.layer_id)) ? 255 : + m_color_print_colors[static_cast(v.color_id) % m_color_print_colors.size()][3]; + default: + return 255; + } +} + +void ViewerImpl::set_tool_colors(const PaletteWithAlpha& colors) { m_tool_colors = colors; m_settings.update_colors = true; } -void ViewerImpl::set_color_print_colors(const Palette& colors) +void ViewerImpl::set_color_print_colors(const PaletteWithAlpha& colors) { m_color_print_colors = colors; m_settings.update_colors = true; @@ -1836,7 +1955,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); + ret += STDVEC_MEMSIZE(m_vertices_colors, ColorWithAlpha); for (const std::vector& times : m_layer_start_times) ret += STDVEC_MEMSIZE(times, float); ret += STDVEC_MEMSIZE(m_layer_first_vertex, uint32_t); @@ -1858,8 +1977,8 @@ size_t ViewerImpl::get_used_cpu_memory() const for (size_t i = 0; i < COLOR_RANGE_TYPES_COUNT; ++i) { ret += m_layer_time_range[i].size_in_bytes_cpu(); } - ret += STDVEC_MEMSIZE(m_tool_colors, Color); - ret += STDVEC_MEMSIZE(m_color_print_colors, Color); + ret += STDVEC_MEMSIZE(m_tool_colors, ColorWithAlpha); + ret += STDVEC_MEMSIZE(m_color_print_colors, ColorWithAlpha); return ret; } @@ -1880,6 +1999,7 @@ size_t ViewerImpl::get_used_gpu_memory() const ret += m_colors_tex_size; ret += m_enabled_segments_tex_size; ret += m_enabled_options_tex_size; + ret += m_translucent_targets.size_in_bytes(); #endif // ENABLE_OPENGL_ES return ret; } @@ -2095,11 +2215,18 @@ void ViewerImpl::update_heights_widths() #endif // ENABLE_OPENGL_ES } -void ViewerImpl::render_segments(const Mat4x4& view_matrix, const Mat4x4& projection_matrix, const Vec3& camera_position) +void ViewerImpl::render_segments(const Mat4x4& view_matrix, const Mat4x4& projection_matrix, const Vec3& camera_position, bool translucent) { - // ORCA: realistic view. The shadow caster pass draws depth only. + // ORCA: realistic view. The shadow caster pass draws depth only, as does the first order independent pass. +#ifndef ENABLE_OPENGL_ES + const bool depth_only = m_translucent_pass == 1; + const unsigned int shader_id = m_rendering_shadow_casters ? m_segments_caster_shader_id : depth_only ? m_segments_depth_shader_id : m_segments_shader_id; + const SegmentsUniforms& uni = m_rendering_shadow_casters ? m_uni_segments_caster : depth_only ? m_uni_segments_depth : m_uni_segments; +#else + const bool depth_only = false; const unsigned int shader_id = m_rendering_shadow_casters ? m_segments_caster_shader_id : m_segments_shader_id; const SegmentsUniforms& uni = m_rendering_shadow_casters ? m_uni_segments_caster : m_uni_segments; +#endif // ENABLE_OPENGL_ES if (shader_id == 0) return; @@ -2127,10 +2254,15 @@ void ViewerImpl::render_segments(const Mat4x4& view_matrix, const Mat4x4& projec glsafe(glUniformMatrix4fv(uni.projection_matrix, 1, GL_FALSE, projection_matrix.data())); glsafe(glUniform3fv(uni.camera_position, 1, camera_position.data())); // ORCA: view_matrix(2,2) > 0 is looking down, where the last segments printed are the nearest. - const bool reverse_order = view_matrix[10] > 0.0f; + // Blending goes the other way, from the farthest. + const bool reverse_order = (view_matrix[10] > 0.0f) != translucent; glsafe(glUniform1i(uni.reverse_order, reverse_order ? 1 : 0)); glsafe(glUniform4fv(uni.clipping_plane, 1, m_clipping_plane.data())); - if (!m_rendering_shadow_casters) { +#ifndef ENABLE_OPENGL_ES + if (depth_only) + glsafe(glUniform1i(m_uni_segments_depth_opaque_depth_id, TRANSLUCENT_TEXTURE_UNIT)); +#endif // ENABLE_OPENGL_ES + if (!m_rendering_shadow_casters && !depth_only) { // ORCA: realistic view glsafe(glUniform1i(m_uni_segments_shadow_map_id, m_shadow_map_texture_unit)); glsafe(glUniformMatrix4fv(m_uni_segments_shadow_light_vp_id, 1, GL_FALSE, m_shadow_light_vp.data())); @@ -2139,13 +2271,51 @@ void ViewerImpl::render_segments(const Mat4x4& view_matrix, const Mat4x4& projec glsafe(glUniform1f(m_uni_segments_exposure_id, m_exposure)); glsafe(glUniform1f(m_uni_segments_saturation_id, m_saturation)); glsafe(glUniform3fv(m_uni_segments_light_top_dir_id, 1, m_light_top_dir.data())); + glsafe(glUniform1f(m_uni_segments_gloss_id, m_gloss ? 0.6f : 0.0f)); set_layer_colors(m_uni_segments_layer_colors); +#ifndef ENABLE_OPENGL_ES + glsafe(glUniform1i(m_uni_segments_oit_pass_id, m_translucent_pass)); + glsafe(glUniform1i(m_uni_segments_opaque_depth_id, TRANSLUCENT_TEXTURE_UNIT)); + glsafe(glUniform1i(m_uni_segments_front_depth_id, TRANSLUCENT_TEXTURE_UNIT + 1)); + glsafe(glUniform2fv(m_uni_segments_oit_depth_range_id, 1, m_oit_depth_range.data())); +#endif // ENABLE_OPENGL_ES + } + + // ORCA: the translucent segments neither hide each other nor what is drawn after them. Drawn late in the + // frame, they cannot count on the depth test the toolpaths left on, which hides them behind opaque ones. + const bool curr_blend = glIsEnabled(GL_BLEND); + const bool curr_depth_test = glIsEnabled(GL_DEPTH_TEST); + std::array curr_blend_func = { 0, 0, 0, 0 }; + std::array curr_blend_equation = { 0, 0 }; + GLboolean curr_depth_mask = GL_TRUE; + if (translucent) { + glsafe(glEnable(GL_DEPTH_TEST)); + glsafe(glGetIntegerv(GL_BLEND_SRC_RGB, &curr_blend_func[0])); + glsafe(glGetIntegerv(GL_BLEND_DST_RGB, &curr_blend_func[1])); + glsafe(glGetIntegerv(GL_BLEND_SRC_ALPHA, &curr_blend_func[2])); + glsafe(glGetIntegerv(GL_BLEND_DST_ALPHA, &curr_blend_func[3])); + glsafe(glGetIntegerv(GL_BLEND_EQUATION_RGB, &curr_blend_equation[0])); + glsafe(glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &curr_blend_equation[1])); + glsafe(glGetBooleanv(GL_DEPTH_WRITEMASK, &curr_depth_mask)); + glsafe(glEnable(GL_BLEND)); + // premultiplied, the highlights are not scaled by the opacity; the nearest depth, then sums, + // in the passes of render_translucent_segments() + glsafe(glBlendEquation(m_translucent_pass == 1 ? GL_MIN : GL_FUNC_ADD)); + glsafe(glBlendFunc(GL_ONE, m_translucent_pass != 0 ? GL_ONE : GL_ONE_MINUS_SRC_ALPHA)); + glsafe(glDepthMask(GL_FALSE)); } glsafe(glDisable(GL_CULL_FACE)); - auto draw = [this, &uni](size_t count) { + // ORCA: of the count enabled segments, the last translucent_count are the translucent ones + auto draw = [this, &uni, translucent](size_t count, size_t translucent_count) { + const size_t first = translucent ? count - translucent_count : 0; + if (!m_rendering_shadow_casters) + count = translucent ? translucent_count : count - translucent_count; + if (count == 0) + return; glsafe(glUniform1i(uni.instances_count, static_cast(count))); + glsafe(glUniform1i(uni.first_instance, static_cast(first))); if (!m_rendering_shadow_casters) { m_segment_template.render(count); return; @@ -2176,7 +2346,7 @@ void ViewerImpl::render_segments(const Mat4x4& view_matrix, const Mat4x4& projec glsafe(glBindTexture(GL_TEXTURE_2D, m_texture_data.get_colors_tex_id(i).first)); glsafe(glActiveTexture(GL_TEXTURE3)); glsafe(glBindTexture(GL_TEXTURE_2D, id)); - draw(count); + draw(count, m_texture_data.get_enabled_translucent_segments_count(i)); } #else std::array curr_bound_texture = { 0, 0, 0, 0 }; @@ -2194,16 +2364,25 @@ void ViewerImpl::render_segments(const Mat4x4& view_matrix, const Mat4x4& projec glsafe(glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, m_heights_widths_angles_buf_id)); glsafe(glActiveTexture(GL_TEXTURE2)); glsafe(glBindTexture(GL_TEXTURE_BUFFER, m_colors_tex_id)); - glsafe(glTexBuffer(GL_TEXTURE_BUFFER, GL_R32F, m_colors_buf_id)); + glsafe(glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA8, m_colors_buf_id)); glsafe(glActiveTexture(GL_TEXTURE3)); glsafe(glBindTexture(GL_TEXTURE_BUFFER, m_enabled_segments_tex_id)); glsafe(glTexBuffer(GL_TEXTURE_BUFFER, GL_R32UI, m_enabled_segments_buf_id)); - draw(m_enabled_segments_count); + draw(m_enabled_segments_count, m_enabled_translucent_segments_count); #endif // ENABLE_OPENGL_ES if (curr_cull_face) glsafe(glEnable(GL_CULL_FACE)); + if (translucent) { + if (!curr_depth_test) + glsafe(glDisable(GL_DEPTH_TEST)); + glsafe(glDepthMask(curr_depth_mask)); + glsafe(glBlendEquationSeparate(curr_blend_equation[0], curr_blend_equation[1])); + glsafe(glBlendFuncSeparate(curr_blend_func[0], curr_blend_func[1], curr_blend_func[2], curr_blend_func[3])); + if (!curr_blend) + glsafe(glDisable(GL_BLEND)); + } glsafe(glUseProgram(curr_shader)); #ifdef ENABLE_OPENGL_ES @@ -2283,7 +2462,7 @@ void ViewerImpl::render_options(const Mat4x4& view_matrix, const Mat4x4& project glsafe(glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, m_heights_widths_angles_buf_id)); glsafe(glActiveTexture(GL_TEXTURE2)); glsafe(glBindTexture(GL_TEXTURE_BUFFER, m_colors_tex_id)); - glsafe(glTexBuffer(GL_TEXTURE_BUFFER, GL_R32F, m_colors_buf_id)); + glsafe(glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA8, m_colors_buf_id)); glsafe(glActiveTexture(GL_TEXTURE3)); glsafe(glBindTexture(GL_TEXTURE_BUFFER, m_enabled_options_tex_id)); glsafe(glTexBuffer(GL_TEXTURE_BUFFER, GL_R32UI, m_enabled_options_buf_id)); @@ -2306,6 +2485,217 @@ void ViewerImpl::render_options(const Mat4x4& view_matrix, const Mat4x4& project glsafe(glActiveTexture(curr_active_texture)); } +#ifndef ENABLE_OPENGL_ES +bool ViewerImpl::TranslucentTargets::update(int width, int height) +{ + if (unsupported || width <= 0 || height <= 0) + return false; + if (fbo != 0 && size[0] == width && size[1] == height) + return true; + + release(); + size = { width, height }; + + int curr_texture = 0; + int curr_draw_fbo = 0; + int curr_read_fbo = 0; + glsafe(glGetIntegerv(GL_TEXTURE_BINDING_2D, &curr_texture)); + glsafe(glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &curr_draw_fbo)); + glsafe(glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &curr_read_fbo)); + + auto make_texture = [width, height](unsigned int& id, GLenum internal_format, GLenum format, GLenum type) { + glsafe(glGenTextures(1, &id)); + glsafe(glBindTexture(GL_TEXTURE_2D, id)); + glsafe(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); + glsafe(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); + glsafe(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0)); + glsafe(glTexImage2D(GL_TEXTURE_2D, 0, internal_format, width, height, 0, format, type, nullptr)); + }; + const GLenum buffers[3] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 }; + + make_texture(depth_tex, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT); + make_texture(accum_tex, GL_RGBA16F, GL_RGBA, GL_FLOAT); + make_texture(reveal_tex, GL_R16F, GL_RED, GL_FLOAT); + make_texture(front_tex, GL_RGBA16F, GL_RGBA, GL_FLOAT); + make_texture(front_depth_tex, GL_R32F, GL_RED, GL_FLOAT); + glsafe(glGenFramebuffers(1, &front_depth_fbo)); + glsafe(glBindFramebuffer(GL_FRAMEBUFFER, front_depth_fbo)); + glsafe(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, front_depth_tex, 0)); + glsafe(glDrawBuffers(1, buffers)); + bool complete = glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; + glsafe(glGenFramebuffers(1, &fbo)); + glsafe(glBindFramebuffer(GL_FRAMEBUFFER, fbo)); + glsafe(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, accum_tex, 0)); + glsafe(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, reveal_tex, 0)); + glsafe(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, front_tex, 0)); + glsafe(glDrawBuffers(3, buffers)); + complete = complete && glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; + + glsafe(glBindTexture(GL_TEXTURE_2D, curr_texture)); + glsafe(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, curr_draw_fbo)); + glsafe(glBindFramebuffer(GL_READ_FRAMEBUFFER, curr_read_fbo)); + + if (!complete) { + release(); + unsupported = true; + } + return complete; +} + +void ViewerImpl::TranslucentTargets::release() +{ + for (unsigned int* id : { &fbo, &front_depth_fbo }) { + if (*id != 0) { + glsafe(glDeleteFramebuffers(1, id)); + *id = 0; + } + } + delete_textures(accum_tex); + delete_textures(reveal_tex); + delete_textures(front_tex); + delete_textures(depth_tex); + delete_textures(front_depth_tex); + size = { 0, 0 }; +} + +size_t ViewerImpl::TranslucentTargets::size_in_bytes() const +{ + // RGBA16F, R16F, RGBA16F, a 24 bit depth and R32F + return static_cast(size[0]) * static_cast(size[1]) * (8 + 2 + 8 + 4 + 4); +} +#endif // ENABLE_OPENGL_ES + +void ViewerImpl::render_translucent(const Mat4x4& view_matrix, const Mat4x4& projection_matrix) +{ + apply_pending_updates(); + if (m_enabled_translucent_segments_count == 0) + return; + + const Mat4x4 inv_view_matrix = inverse(view_matrix); + render_translucent_segments(view_matrix, projection_matrix, { inv_view_matrix[12], inv_view_matrix[13], inv_view_matrix[14] }); +} + +void ViewerImpl::render_translucent_segments(const Mat4x4& view_matrix, const Mat4x4& projection_matrix, const Vec3& camera_position) +{ +#ifndef ENABLE_OPENGL_ES + // ORCA: the order independent path, whose targets are as large as the canvas: the nearest translucent surface + // over the weighted blended order independent transparency (McGuire and Bavoil, 2013) of the others. Blended in + // print order, even one color shows the order, its surfaces being shaded apart. + std::array viewport = { 0, 0, 0, 0 }; + int draw_fbo = 0; + int read_fbo = 0; + int samples = 0; + glsafe(glGetIntegerv(GL_VIEWPORT, viewport.data())); + glsafe(glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &draw_fbo)); + glsafe(glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_fbo)); + glsafe(glGetIntegerv(GL_SAMPLES, &samples)); + // the depth of a multisampled framebuffer object cannot be copied into a texture + if ((read_fbo != 0 && samples > 0) || !m_translucent_targets.update(viewport[2], viewport[3])) { + render_segments(view_matrix, projection_matrix, camera_position, true); + return; + } + const TranslucentTargets& targets = m_translucent_targets; + const int width = viewport[2]; + const int height = viewport[3]; + + int curr_active_texture = 0; + std::array curr_textures = { 0, 0, 0 }; + glsafe(glGetIntegerv(GL_ACTIVE_TEXTURE, &curr_active_texture)); + for (int i = 0; i < 3; ++i) { + glsafe(glActiveTexture(GL_TEXTURE0 + TRANSLUCENT_TEXTURE_UNIT + i)); + glsafe(glGetIntegerv(GL_TEXTURE_BINDING_2D, &curr_textures[i])); + } + + // the opaque scene, to hide the translucent segments behind it + glsafe(glActiveTexture(GL_TEXTURE0 + TRANSLUCENT_TEXTURE_UNIT)); + glsafe(glBindTexture(GL_TEXTURE_2D, targets.depth_tex)); + glsafe(glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, viewport[0], viewport[1], width, height)); + + // the weights fall with the depth across the extrusions + float near_z = FLT_MAX; + float far_z = -FLT_MAX; + for (int i = 0; i < 8; ++i) { + const Vec3 p = { m_extrusions_box[i & 1][0], m_extrusions_box[(i >> 1) & 1][1], m_extrusions_box[(i >> 2) & 1][2] }; + const float z = -(view_matrix[2] * p[0] + view_matrix[6] * p[1] + view_matrix[10] * p[2] + view_matrix[14]); + near_z = std::min(near_z, z); + far_z = std::max(far_z, z); + } + m_oit_depth_range = { near_z, std::max(far_z, near_z + 1.0f) }; + + // the depth of the nearest translucent surface, as the fragments see it, kept by GL_MIN + const std::array zero = { 0.0f, 0.0f, 0.0f, 0.0f }; + const std::array one = { 1.0f, 1.0f, 1.0f, 1.0f }; + glsafe(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, targets.front_depth_fbo)); + glsafe(glViewport(0, 0, width, height)); + glsafe(glClearBufferfv(GL_COLOR, 0, one.data())); + m_translucent_pass = 1; + render_segments(view_matrix, projection_matrix, camera_position, true); + glsafe(glActiveTexture(GL_TEXTURE0 + TRANSLUCENT_TEXTURE_UNIT + 1)); + glsafe(glBindTexture(GL_TEXTURE_2D, targets.front_depth_tex)); + + // that surface apart, the others summed + glsafe(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, targets.fbo)); + for (int i = 0; i < 3; ++i) + glsafe(glClearBufferfv(GL_COLOR, i, zero.data())); + m_translucent_pass = 2; + render_segments(view_matrix, projection_matrix, camera_position, true); + m_translucent_pass = 0; + + glsafe(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, draw_fbo)); + glsafe(glBindFramebuffer(GL_READ_FRAMEBUFFER, read_fbo)); + glsafe(glViewport(viewport[0], viewport[1], width, height)); + + // composite over the scene + int curr_shader = 0; + int curr_vertex_array = 0; + std::array curr_blend_func = { 0, 0, 0, 0 }; + GLboolean curr_depth_mask = GL_TRUE; + const bool curr_blend = glIsEnabled(GL_BLEND); + const bool curr_depth_test = glIsEnabled(GL_DEPTH_TEST); + glsafe(glGetIntegerv(GL_CURRENT_PROGRAM, &curr_shader)); + glsafe(glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &curr_vertex_array)); + glsafe(glGetIntegerv(GL_BLEND_SRC_RGB, &curr_blend_func[0])); + glsafe(glGetIntegerv(GL_BLEND_DST_RGB, &curr_blend_func[1])); + glsafe(glGetIntegerv(GL_BLEND_SRC_ALPHA, &curr_blend_func[2])); + glsafe(glGetIntegerv(GL_BLEND_DST_ALPHA, &curr_blend_func[3])); + glsafe(glGetBooleanv(GL_DEPTH_WRITEMASK, &curr_depth_mask)); + + glsafe(glUseProgram(m_translucent_composite_shader_id)); + glsafe(glUniform1i(m_uni_translucent_composite_accum_tex_id, TRANSLUCENT_TEXTURE_UNIT)); + glsafe(glUniform1i(m_uni_translucent_composite_reveal_tex_id, TRANSLUCENT_TEXTURE_UNIT + 1)); + glsafe(glUniform1i(m_uni_translucent_composite_front_tex_id, TRANSLUCENT_TEXTURE_UNIT + 2)); + glsafe(glUniform2i(m_uni_translucent_composite_origin_id, viewport[0], viewport[1])); + glsafe(glActiveTexture(GL_TEXTURE0 + TRANSLUCENT_TEXTURE_UNIT)); + glsafe(glBindTexture(GL_TEXTURE_2D, targets.accum_tex)); + glsafe(glActiveTexture(GL_TEXTURE0 + TRANSLUCENT_TEXTURE_UNIT + 1)); + glsafe(glBindTexture(GL_TEXTURE_2D, targets.reveal_tex)); + glsafe(glActiveTexture(GL_TEXTURE0 + TRANSLUCENT_TEXTURE_UNIT + 2)); + glsafe(glBindTexture(GL_TEXTURE_2D, targets.front_tex)); + glsafe(glEnable(GL_BLEND)); + glsafe(glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA)); + glsafe(glDisable(GL_DEPTH_TEST)); + glsafe(glDepthMask(GL_FALSE)); + glsafe(glBindVertexArray(m_segments_caster_vao_id)); + glsafe(glDrawArrays(GL_TRIANGLES, 0, 3)); + + glsafe(glBindVertexArray(curr_vertex_array)); + glsafe(glDepthMask(curr_depth_mask)); + if (curr_depth_test) + glsafe(glEnable(GL_DEPTH_TEST)); + glsafe(glBlendFuncSeparate(curr_blend_func[0], curr_blend_func[1], curr_blend_func[2], curr_blend_func[3])); + if (!curr_blend) + glsafe(glDisable(GL_BLEND)); + glsafe(glUseProgram(curr_shader)); + for (int i = 0; i < 3; ++i) { + glsafe(glActiveTexture(GL_TEXTURE0 + TRANSLUCENT_TEXTURE_UNIT + i)); + glsafe(glBindTexture(GL_TEXTURE_2D, curr_textures[i])); + } + glsafe(glActiveTexture(curr_active_texture)); +#else + render_segments(view_matrix, projection_matrix, camera_position, true); +#endif // ENABLE_OPENGL_ES +} + #if VGCODE_ENABLE_COG_AND_TOOL_MARKERS void ViewerImpl::render_cog_marker(const Mat4x4& view_matrix, const Mat4x4& projection_matrix) { diff --git a/src/libvgcode/src/ViewerImpl.hpp b/src/libvgcode/src/ViewerImpl.hpp index 0877e6265b..d9394d7e21 100644 --- a/src/libvgcode/src/ViewerImpl.hpp +++ b/src/libvgcode/src/ViewerImpl.hpp @@ -77,6 +77,8 @@ public: // Render the toolpaths // void render(const Mat4x4& view_matrix, const Mat4x4& projection_matrix); + void render_translucent(const Mat4x4& view_matrix, const Mat4x4& projection_matrix); + bool has_translucent_toolpaths() const { return m_enabled_translucent_segments_count > 0; } // // ORCA: realistic view. Render the toolpaths as seen from the light, to fill the caller's // shadow map. Only depth matters here, so the caller masks colour writes; light_position @@ -98,6 +100,7 @@ public: // ORCA: section view, see Viewer::set_clipping_plane() void set_clipping_plane(const std::array& plane) { m_clipping_plane = plane; } void set_light_top_dir(const Vec3& direction) { m_light_top_dir = direction; } + void set_gloss(bool gloss) { m_gloss = gloss; } EViewType get_view_type() const { return m_settings.view_type; } void set_view_type(EViewType type); @@ -121,6 +124,10 @@ public: float get_dim_previous_layers_brightness() const { return m_settings.dim_previous_layers_brightness; } void set_dim_previous_layers_brightness(float value); + // ORCA: whether the filament colors keep their opacity, see get_vertex_alpha() + bool is_translucent_filaments() const { return m_settings.translucent_filaments; } + void set_translucent_filaments(bool value); + bool is_spiral_vase_mode() const { return m_settings.spiral_vase_mode; } std::vector get_time_modes() const; @@ -184,12 +191,12 @@ public: std::vector get_layers_estimated_times() const { return m_layers.get_times(m_settings.time_mode); } size_t get_tool_colors_count() const { return m_tool_colors.size(); } - const Palette& get_tool_colors() const { return m_tool_colors; } - void set_tool_colors(const Palette& colors); + const PaletteWithAlpha& get_tool_colors() const { return m_tool_colors; } + void set_tool_colors(const PaletteWithAlpha& colors); size_t get_color_print_colors_count() const { return m_color_print_colors.size(); } - const Palette& get_color_print_colors() const { return m_color_print_colors; } - void set_color_print_colors(const Palette& colors); + const PaletteWithAlpha& get_color_print_colors() const { return m_color_print_colors; } + void set_color_print_colors(const PaletteWithAlpha& colors); const Color& get_extrusion_role_color(EGCodeExtrusionRole role) const; void set_extrusion_role_color(EGCodeExtrusionRole role, const Color& color); @@ -324,7 +331,10 @@ private: std::vector m_vertices; // Cache for the colors to reduce the need to recalculate colors of all the vertices. - std::vector m_vertices_colors; + std::vector m_vertices_colors; + // ORCA: the enabled segments list the translucent ones last, see update_enabled_entities(). + bool m_has_translucent_colors{ false }; + size_t m_enabled_translucent_segments_count{ 0 }; // // Variables used for toolpaths visibiliity @@ -351,8 +361,8 @@ private: std::array m_layer_time_range{ ColorRange(EColorRangeType::Linear), ColorRange(EColorRangeType::Logarithmic) }; - Palette m_tool_colors; - Palette m_color_print_colors; + PaletteWithAlpha m_tool_colors; + PaletteWithAlpha m_color_print_colors; // // OpenGL shaders ids // @@ -380,6 +390,7 @@ private: int segment_index_tex{ -1 }; int reverse_order{ -1 }; int instances_count{ -1 }; + int first_instance{ -1 }; int clipping_plane{ -1 }; void init(unsigned int shader_id); @@ -393,6 +404,7 @@ private: int m_uni_segments_exposure_id{ -1 }; int m_uni_segments_saturation_id{ -1 }; int m_uni_segments_light_top_dir_id{ -1 }; + int m_uni_segments_gloss_id{ -1 }; // ORCA: the layers greyed or dimmed around the one the sliders show, in the segments and options shaders. struct LayerColorsUniforms { @@ -440,8 +452,9 @@ private: void init(size_t vertices_count); void set_positions(const std::vector& positions); void set_heights_widths_angles(const std::vector& heights_widths_angles); - void set_colors(const std::vector& colors); - void set_enabled_segments(const std::vector& enabled_segments); + void set_colors(const std::vector& colors); + // ORCA: sorted by opacity, each texture lists its opaque segments first, then its translucent ones. + void set_enabled_segments(const std::vector& enabled_segments, const std::vector& colors, bool sort_by_opacity); void set_enabled_options(const std::vector& enabled_options); void reset(); size_t get_count() const { return m_count; } @@ -449,6 +462,7 @@ private: std::pair get_heights_widths_angles_tex_id(size_t id) const; std::pair get_colors_tex_id(size_t id) const; std::pair get_enabled_segments_tex_id(size_t id) const; + size_t get_enabled_translucent_segments_count(size_t id) const { return m_tex_ids[id].enabled_translucent_segments; } std::pair get_enabled_options_tex_id(size_t id) const; size_t get_enabled_segments_count() const; @@ -497,6 +511,7 @@ private: // OpenGL texture to store enabled segments // std::pair enabled_segments{ 0, 0 }; + size_t enabled_translucent_segments{ 0 }; // // OpenGL texture to store enabled options // @@ -565,16 +580,68 @@ private: float m_saturation{ 1.0f }; // ORCA: the light the segments shader shades with, in eye space. Vec3 m_light_top_dir{ -0.4574957f, 0.4574957f, 0.7624929f }; + // ORCA: the untinted highlight of the filaments, see set_gloss() + bool m_gloss{ true }; // ORCA: section view std::array m_clipping_plane{ 0.0f, 0.0f, 0.0f, 1.0f }; + // ORCA: the depth range the weights of render_translucent_segments() span + AABox m_extrusions_box{ Vec3{ 0.0f, 0.0f, 0.0f }, Vec3{ 0.0f, 0.0f, 0.0f } }; +#ifndef ENABLE_OPENGL_ES + // + // ORCA: order independent transparency, see render_translucent_segments(). Single-sampled whatever + // the canvas, see the design doc. + // + struct TranslucentTargets + { + unsigned int fbo{ 0 }; + unsigned int accum_tex{ 0 }; + unsigned int reveal_tex{ 0 }; + // the nearest translucent surface, kept out of the weighted mean of the others + unsigned int front_tex{ 0 }; + // the depth of the opaque scene, which hides the translucent segments behind it + unsigned int depth_tex{ 0 }; + // the depth of the nearest translucent surface, in front_depth_fbo + unsigned int front_depth_tex{ 0 }; + unsigned int front_depth_fbo{ 0 }; + std::array size{ 0, 0 }; + bool unsupported{ false }; + + // false when the targets cannot be made + bool update(int width, int height); + void release(); + size_t size_in_bytes() const; + }; + TranslucentTargets m_translucent_targets; + unsigned int m_translucent_composite_shader_id{ 0 }; + int m_uni_translucent_composite_accum_tex_id{ -1 }; + int m_uni_translucent_composite_reveal_tex_id{ -1 }; + int m_uni_translucent_composite_front_tex_id{ -1 }; + int m_uni_translucent_composite_origin_id{ -1 }; + int m_uni_segments_oit_pass_id{ -1 }; + int m_uni_segments_opaque_depth_id{ -1 }; + int m_uni_segments_front_depth_id{ -1 }; + int m_uni_segments_oit_depth_range_id{ -1 }; + // the segments shaders built with DEPTH_ONLY, drawing the depth of the nearest translucent surface + unsigned int m_segments_depth_shader_id{ 0 }; + SegmentsUniforms m_uni_segments_depth; + int m_uni_segments_depth_opaque_depth_id{ -1 }; + std::array m_oit_depth_range{ 0.0f, 1.0f }; +#endif // ENABLE_OPENGL_ES + // the pass of render_translucent_segments() render_segments() draws: 1 the depth of the nearest + // translucent surface, 2 the accumulation, 0 neither + int m_translucent_pass{ 0 }; + void apply_pending_updates(); void update_view_full_range(); void update_color_ranges(); void update_heights_widths(); - void render_segments(const Mat4x4& view_matrix, const Mat4x4& projection_matrix, const Vec3& camera_position); + uint8_t get_vertex_alpha(const PathVertex& v) const; + // ORCA: translucent draws the segments whose color is translucent, otherwise the opaque ones, or all of them for the shadow casters. + void render_segments(const Mat4x4& view_matrix, const Mat4x4& projection_matrix, const Vec3& camera_position, bool translucent = false); void render_options(const Mat4x4& view_matrix, const Mat4x4& projection_matrix); + void render_translucent_segments(const Mat4x4& view_matrix, const Mat4x4& projection_matrix, const Vec3& camera_position); // ORCA: the program using uni must be current. void set_layer_colors(const LayerColorsUniforms& uni) const; #if VGCODE_ENABLE_COG_AND_TOOL_MARKERS diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 367aadaa27..71fa481732 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -890,6 +890,8 @@ if (APPLE) GUI/DeepLinkHandlerMac.mm GUI/DeepLinkHandlerMac.h GUI/GUI_UtilsMac.mm + GUI/MacIME.mm + GUI/MacIME.hpp ) FIND_LIBRARY(DISKARBITRATION_LIBRARY DiskArbitration) endif () diff --git a/src/slic3r/GUI/3DScene.cpp b/src/slic3r/GUI/3DScene.cpp index 071663b851..7dad07c9f7 100644 --- a/src/slic3r/GUI/3DScene.cpp +++ b/src/slic3r/GUI/3DScene.cpp @@ -111,14 +111,15 @@ static constexpr int OUTLINE_DEPTH_TEX_UNIT = 5; Slic3r::ColorRGBA adjust_color_for_rendering(const Slic3r::ColorRGBA &colors) { - if (colors.a() < FullyTransparentMaterialThreshold) { // completely transparent - return {1, 1, 1, FullTransparentModdifiedToFixAlpha}; + // a clear color keeps its hue, at the least opacity that still shows it + const float alpha = std::max(colors.a(), FullyTransparentMaterialThreshold); + if (colors.r() < FULL_BLACK_THRESHOLD && colors.g() < FULL_BLACK_THRESHOLD && colors.b() < FULL_BLACK_THRESHOLD) { + // black, lifted so that the shading shows, the more the more translucent: a dark translucent + // surface shows nothing through itself + const float grey = FULL_BLACK_THRESHOLD + 0.3f * (1.0f - alpha); + return {grey, grey, grey, alpha}; } - else if(colors.r() < FULL_BLACK_THRESHOLD && colors.g() < FULL_BLACK_THRESHOLD && colors.b() < FULL_BLACK_THRESHOLD) { // black - return {FULL_BLACK_THRESHOLD, FULL_BLACK_THRESHOLD, FULL_BLACK_THRESHOLD, colors.a()}; - } - else - return colors; + return {colors.r(), colors.g(), colors.b(), alpha}; } namespace Slic3r { @@ -1238,6 +1239,9 @@ void GLVolumeCollection::render(GLVolumeCollection::ERenderType type, // The outline passes below are driven by is_outline, which only the object shaders have; with an // overlay one (wireframe, x-ray) bound they would just draw the volume again. const bool shader_can_outline = shader->get_uniform_location("is_outline") >= 0; + // ORCA: the object shaders that know how draw a part of a translucent filament as its print would + // show, in premultiplied color, see translucent_filament_color() in gouraud.fs + const bool shade_translucent_filaments = type == ERenderType::Transparent && shader->get_uniform_location("translucent_filament") >= 0; // Prime depth_tex on every frame so non-outline draws do not keep the // default sampler unit 0, which can conflict with other sampler types. @@ -1343,6 +1347,11 @@ void GLVolumeCollection::render(GLVolumeCollection::ERenderType type, shader->set_uniform("projection_matrix", projection_matrix); const Matrix3d view_normal_matrix = view_matrix.matrix().block(0, 0, 3, 3) * model_matrix.matrix().block(0, 0, 3, 3).inverse().transpose(); shader->set_uniform("view_normal_matrix", view_normal_matrix); + if (shade_translucent_filaments) { + const bool translucent_filament = volume.first->visible && !volume.first->is_modifier && volume.first->color.is_transparent(); + shader->set_uniform("translucent_filament", translucent_filament); + glsafe(::glBlendFunc(translucent_filament ? GL_ONE : GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); + } if (volume.first->depth_bias) { glsafe(::glEnable(GL_POLYGON_OFFSET_FILL)); glsafe(::glPolygonOffset(1.0f, 1.0f)); @@ -1385,6 +1394,11 @@ void GLVolumeCollection::render(GLVolumeCollection::ERenderType type, if (disable_cullface) glsafe(::glEnable(GL_CULL_FACE)); + if (shade_translucent_filaments) { + // the program is shared, so leave it as the other users expect + shader->set_uniform("translucent_filament", false); + glsafe(::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); + } if (type == ERenderType::Transparent) glsafe(::glDisable(GL_BLEND)); } diff --git a/src/slic3r/GUI/GCodeViewer.cpp b/src/slic3r/GUI/GCodeViewer.cpp index fbfd44a475..84de35f0cd 100644 --- a/src/slic3r/GUI/GCodeViewer.cpp +++ b/src/slic3r/GUI/GCodeViewer.cpp @@ -126,6 +126,18 @@ namespace GUI { // _u8L("Filament") // }; +// ORCA: a translucent filament swatch goes over the checkerboard of the sidebar's clear swatch +static void add_swatch(ImDrawList* draw_list, const ImVec2& min, const ImVec2& max, const ColorRGBA& color) +{ + if (color.is_transparent()) { + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 4; ++j) + draw_list->AddRectFilled(ImLerp(min, max, ImVec2(0.25f * i, 0.25f * j)), ImLerp(min, max, ImVec2(0.25f * (i + 1), 0.25f * (j + 1))), + (i + j) % 2 == 0 ? IM_COL32_WHITE : IM_COL32(217, 217, 217, 255)); + } + draw_list->AddRectFilled(min, max, ImGuiWrapper::to_ImU32(color)); +} + static std::string get_view_type_string(libvgcode::EViewType view_type) { if (view_type == libvgcode::EViewType::Summary) @@ -1405,6 +1417,7 @@ void GCodeViewer::load_as_gcode(const GCodeProcessorResult& gcode_result, const // ORCA: darken the layers the preview layer slider is not scrubbed to m_viewer.set_dim_previous_layers(get_app_config()->get_bool("preview_dim_previous_layers")); m_viewer.set_dim_previous_layers_brightness(0.01f * std::stoi(get_app_config()->get("preview_dim_previous_layers_brightness"))); + m_viewer.set_translucent_filaments(get_app_config()->get_bool("preview_translucent_filaments")); // avoid processing if called with the same gcode_result. // On a belt printer the toolpath geometry fed to libvgcode also depends on the @@ -1415,22 +1428,8 @@ void GCodeViewer::load_as_gcode(const GCodeProcessorResult& gcode_result, const //BBS: add logs BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": the same id %1%, return directly, result %2% ") % m_last_result_id % (&gcode_result); - // collect tool colors - libvgcode::Palette tools_colors; - tools_colors.reserve(str_tool_colors.size()); - for (const std::string& color : str_tool_colors) { - tools_colors.emplace_back(libvgcode::convert(color)); - } - m_viewer.set_tool_colors(tools_colors); - - // collect color print colors - libvgcode::Palette color_print_colors; - const std::vector& str_colors = str_color_print_colors.empty() ? str_tool_colors : str_color_print_colors; - color_print_colors.reserve(str_colors.size()); - for (const std::string& color : str_colors) { - color_print_colors.emplace_back(libvgcode::convert(color)); - } - m_viewer.set_color_print_colors(color_print_colors); + m_viewer.set_tool_colors(libvgcode::convert_filament_colors(str_tool_colors)); + m_viewer.set_color_print_colors(libvgcode::convert_filament_colors(str_color_print_colors.empty() ? str_tool_colors : str_color_print_colors)); return; } @@ -2212,7 +2211,13 @@ void GCodeViewer::render_scene(int canvas_width, int canvas_height) return; render_toolpaths(); + // ORCA: the markers write depth, which would hide the translucent toolpaths behind them + if (!m_viewer.has_translucent_toolpaths()) + render_markers(canvas_width, canvas_height); +} +void GCodeViewer::render_markers(int canvas_width, int canvas_height) +{ auto current = m_viewer.get_view_visible_range(); auto endpoints = m_viewer.get_view_full_range(); m_sequential_view.m_show_marker = m_sequential_view.m_show_marker || (current.back() != endpoints.back() && !m_no_render_path); @@ -3236,6 +3241,25 @@ void GCodeViewer::load_shells(const Print& print, bool initialized, bool force_p % m_shells.print_id % m_shells.print_modify_count % object_count %m_shells.volumes.volumes.size(); } +ColorRGBA GCodeViewer::shown_filament_color(ColorRGBA color) const +{ + if (!m_viewer.is_translucent_filaments()) + color.a(1.0f); + return color; +} + +void GCodeViewer::render_translucent_toolpaths(int canvas_width, int canvas_height) +{ + if (!m_viewer.has_translucent_toolpaths()) + return; + + const Camera& camera = wxGetApp().plater()->get_camera(); + m_viewer.render_translucent(libvgcode::convert(static_cast(camera.get_view_matrix().matrix().cast())), + libvgcode::convert(static_cast(camera.get_projection_matrix().matrix().cast()))); + glsafe(::glEnable(GL_DEPTH_TEST)); + render_markers(canvas_width, canvas_height); +} + void GCodeViewer::render_toolpaths() { const Camera& camera = wxGetApp().plater()->get_camera(); @@ -3534,8 +3558,7 @@ void GCodeViewer::render_all_plates_stats(const std::vectorAddRectFilled({ pos.x + 1.0f * m_scale, pos.y + 3.0f * m_scale }, { pos.x + icon_size - 1.0f * m_scale, pos.y + icon_size + 1.0f * m_scale }, - ImGuiWrapper::to_ImU32(color)); + add_swatch(draw_list, { pos.x + 1.0f * m_scale, pos.y + 3.0f * m_scale }, { pos.x + icon_size - 1.0f * m_scale, pos.y + icon_size + 1.0f * m_scale }, color); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(20.0 * m_scale, 6.0 * m_scale)); @@ -4139,8 +4162,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv switch (type) { default: case EItemType::Rect: { - draw_list->AddRectFilled({ pos.x + 1.0f * m_scale, pos.y + 3.0f * m_scale }, { pos.x + icon_size - 1.0f * m_scale, pos.y + icon_size + 1.0f * m_scale }, - ImGuiWrapper::to_ImU32(color)); + add_swatch(draw_list, { pos.x + 1.0f * m_scale, pos.y + 3.0f * m_scale }, { pos.x + icon_size - 1.0f * m_scale, pos.y + icon_size + 1.0f * m_scale }, color); break; } case EItemType::Circle: { @@ -4932,7 +4954,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv for (uint8_t extruder_id : used_extruders_ids) { const std::string weight_text = format_compact_weight(model_used_filaments_g[i], imperial_units); ::sprintf(buf, imperial_units ? "%.2f in %s" : "%.2f m %s", model_used_filaments_m[i], weight_text.c_str()); - append_item(EItemType::Rect, libvgcode::convert(m_viewer.get_tool_colors()[extruder_id]), { { _u8L("Extruder") + " " + std::to_string(extruder_id + 1), offsets[0]}, {buf, offsets[1]} }); + append_item(EItemType::Rect, shown_filament_color(libvgcode::convert(m_viewer.get_tool_colors()[extruder_id])), { { _u8L("Extruder") + " " + std::to_string(extruder_id + 1), offsets[0]}, {buf, offsets[1]} }); // append_item(EItemType::Rect, libvgcode::convert(m_viewer.get_tool_colors()[extruder_id]), _u8L("Extruder") + " " + std::to_string(extruder_id + 1), // true, "", 0.0f, 0.0f, offsets, used_filaments_m[extruder_id], used_filaments_g[extruder_id]); i++; @@ -5028,7 +5050,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv } float checkbox_pos = std::max(predictable_icon_pos, color_print_offsets[_u8L("Display")]); // ORCA prefer predictable_icon_pos when header not reacing end - append_item(EItemType::Rect, libvgcode::convert(tool_colors[extruder_idx]), columns_offsets, false, checkbox_pos/*ORCA*/, true, []() {}); + append_item(EItemType::Rect, shown_filament_color(libvgcode::convert(tool_colors[extruder_idx])), columns_offsets, false, checkbox_pos/*ORCA*/, true, []() {}); } i++; } @@ -5138,7 +5160,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv const size_t extruders_count = get_extruders_count(); std::vector last_color(extruders_count); for (size_t i = 0; i < extruders_count; ++i) { - last_color[i] = libvgcode::convert(m_viewer.get_tool_colors()[i]); + last_color[i] = shown_filament_color(libvgcode::convert(m_viewer.get_tool_colors()[i])); } int last_extruder_id = 1; int color_change_idx = 0; @@ -5160,6 +5182,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv items.push_back({ PartialTime::EType::Print, it->extruder, last_color[it->extruder - 1], ColorRGBA::BLACK(), time_rec.second, get_used_filament_from_volume(used_filaments[color_change_idx++], it->extruder - 1) }); ColorRGBA color; decode_color(it->color, color); + color = shown_filament_color(color); items.push_back({ PartialTime::EType::ColorChange, it->extruder, last_color[it->extruder - 1], color, time_rec.second }); last_color[it->extruder - 1] = color; last_extruder_id = it->extruder; @@ -5186,11 +5209,9 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv ImVec2 pos = ImGui::GetCursorScreenPos(); pos.x -= 0.5f * ImGui::GetStyle().ItemSpacing.x; - draw_list->AddRectFilled({ pos.x + 1.0f, pos.y + 1.0f }, { pos.x + icon_size - 1.0f, pos.y + icon_size - 1.0f }, - ImGuiWrapper::to_ImU32(color1)); + add_swatch(draw_list, { pos.x + 1.0f, pos.y + 1.0f }, { pos.x + icon_size - 1.0f, pos.y + icon_size - 1.0f }, color1); pos.x += icon_size; - draw_list->AddRectFilled({ pos.x + 1.0f, pos.y + 1.0f }, { pos.x + icon_size - 1.0f, pos.y + icon_size - 1.0f }, - ImGuiWrapper::to_ImU32(color2)); + add_swatch(draw_list, { pos.x + 1.0f, pos.y + 1.0f }, { pos.x + icon_size - 1.0f, pos.y + icon_size - 1.0f }, color2); ImGui::SameLine(offsets[0]); imgui.text(short_time(get_time_dhms(times.second - times.first))); @@ -5205,8 +5226,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv ImVec2 pos = ImGui::GetCursorScreenPos(); pos.x -= 0.5f * ImGui::GetStyle().ItemSpacing.x; - draw_list->AddRectFilled({ pos.x + 1.0f, pos.y + 1.0f }, { pos.x + icon_size - 1.0f, pos.y + icon_size - 1.0f }, - ImGuiWrapper::to_ImU32(color)); + add_swatch(draw_list, { pos.x + 1.0f, pos.y + 1.0f }, { pos.x + icon_size - 1.0f, pos.y + icon_size - 1.0f }, color); ImGui::SameLine(offsets[0]); imgui.text(short_time(get_time_dhms(times.second))); diff --git a/src/slic3r/GUI/GCodeViewer.hpp b/src/slic3r/GUI/GCodeViewer.hpp index c07b063cb1..554837747b 100644 --- a/src/slic3r/GUI/GCodeViewer.hpp +++ b/src/slic3r/GUI/GCodeViewer.hpp @@ -402,6 +402,8 @@ public: //BBS: GUI refactor: add canvas width and height // Shells, toolpaths, the sequential markers and the IDEX/IQEX toolhead boxes, drawn in 3D. void render_scene(int canvas_width, int canvas_height); + // ORCA: the toolpaths of translucent filaments, blended over the scene, then the markers. render_scene() leaves both out. + void render_translucent_toolpaths(int canvas_width, int canvas_height); // Legend, sliders, the marker's position window and the G-code window, all ImGui. void render_overlay(int canvas_width, int canvas_height, int right_margin); // ORCA: realistic view. Depth-only pass drawing the toolpaths as the light sees them, into @@ -414,6 +416,8 @@ public: // ORCA: section view void set_clipping_plane(const ClippingPlane& plane); void set_light_top_dir(const Vec3d& direction); + // ORCA: the untinted highlight of the filaments, which the canvas gives them in realistic view only + void set_gloss(bool gloss) { m_viewer.set_gloss(gloss); } //BBS // void _render_calibration_thumbnail_internal(ThumbnailData& thumbnail_data, const ThumbnailsParams& thumbnail_params, PartPlateList& partplate_list, OpenGLManager& opengl_manager); // void _render_calibration_thumbnail_framebuffer(ThumbnailData& thumbnail_data, unsigned int w, unsigned int h, const ThumbnailsParams& thumbnail_params, PartPlateList& partplate_list, OpenGLManager& opengl_manager); @@ -502,6 +506,8 @@ public: // ORCA: brightness of those darkened layers, 1.0 = unchanged, 0.0 = black void set_dim_previous_layers_brightness(float value) { m_viewer.set_dim_previous_layers_brightness(value); } float get_dim_previous_layers_brightness() const { return m_viewer.get_dim_previous_layers_brightness(); } + // ORCA: draw the toolpaths of translucent filament colors translucent + void set_translucent_filaments(bool value) { m_viewer.set_translucent_filaments(value); } void set_layers_z_range(const std::array& layers_z_range); @@ -534,7 +540,11 @@ private: // Canvas height minus the room the horizontal slider takes. int sequential_view_height(int canvas_height) const; void render_toolpaths(); + // The sequential markers and the IDEX/IQEX toolhead boxes. + void render_markers(int canvas_width, int canvas_height); void render_shells(int canvas_width, int canvas_height); + // ORCA: a filament color as the toolpaths show it, opaque unless translucent filaments are shown + ColorRGBA shown_filament_color(ColorRGBA color) const; //BBS: GUI refactor: add canvas size void render_legend(float &legend_height, int canvas_width, int canvas_height, int right_margin); diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index 2f72a8e976..a005715c4f 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -120,6 +120,10 @@ #include "slic3r/Utils/RetinaHelper.hpp" #endif +#ifdef __APPLE__ +#include "MacIME.hpp" +#endif + #include #include @@ -2902,6 +2906,11 @@ void GLCanvas3D::_render_scene(const Camera& camera, const Size& cnv_size) m_frame_profiler.mark("ssao"); } + if (m_canvas_type == ECanvasType::CanvasPreview && m_render_preview) { + _render_gcode_translucent(cnv_size.get_width(), cnv_size.get_height()); + m_frame_profiler.mark("gcode translucent"); + } + // After the occlusion pass, which would shade it as the surface behind it. m_center_of_mass.render(*this); @@ -3901,6 +3910,13 @@ void GLCanvas3D::bind_event_handlers() finish_selection_edit(); release_held_modifiers(); wxGetApp().imgui()->forget_key_claims(); +#ifdef __APPLE__ + // ImGuiWrapper stops updating the view once it is no longer the IME target. + if (ImGui::GetIO().ImeWindowHandle == m_canvas->GetHandle()) { + mac_ime_set_active(m_canvas->GetHandle(), false); + ImGui::GetIO().ImeWindowHandle = nullptr; + } +#endif ImGui::SetWindowFocus(nullptr); render(); evt.Skip(); @@ -4343,6 +4359,12 @@ void GLCanvas3D::release_held_modifiers() void GLCanvas3D::on_key(wxKeyEvent& evt) { +#ifdef __APPLE__ + // A key the input method used for a composition must not also edit the text field: Esc would revert + // it, Backspace delete a character, Enter add a line. + if (evt.GetEventType() == wxEVT_KEY_DOWN && mac_ime_owns_key(m_canvas->GetHandle())) + return; +#endif auto imgui = wxGetApp().imgui(); const int keyCode = evt.GetKeyCode(); @@ -5513,6 +5535,10 @@ void GLCanvas3D::force_set_focus() { void GLCanvas3D::on_set_focus(wxFocusEvent& evt) { +#ifdef __APPLE__ + // The focused canvas is the one whose view takes input-method text (see ImGuiWrapper::end_frame()). + ImGui::GetIO().ImeWindowHandle = m_canvas->GetHandle(); +#endif m_tooltip_enabled = false; _refresh_if_shown_on_screen(); m_tooltip_enabled = true; @@ -9590,6 +9616,7 @@ void GLCanvas3D::_render_objects(GLVolumeCollection::ERenderType type, bool with // Set on every use: the program is shared, so a canvas that leaves it unset would inherit // the last canvas's choice. shader->set_uniform("lighting_model", studio ? 1 : 0); + shader->set_uniform("translucent_gloss", realistic_mode); if (studio) { const Transform3d& view = wxGetApp().plater()->get_camera().get_view_matrix(); shader->set_uniform("world_up_eye", Vec3f((view.matrix().block<3, 3>(0, 0) * Vec3d::UnitZ()).cast())); @@ -9858,7 +9885,9 @@ void GLCanvas3D::_render_wireframe_overlay() glsafe(::glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)); #endif - m_volumes.render(GLVolumeCollection::ERenderType::Opaque, false, view_matrix, proj_matrix, sz); + m_volumes.render(GLVolumeCollection::ERenderType::All, false, view_matrix, proj_matrix, sz, [](const GLVolume& volume) { + return !volume.render_color.is_transparent() || (volume.visible && !volume.is_modifier && volume.color.is_transparent()); + }); #if !SLIC3R_OPENGL_ES glsafe(::glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)); @@ -9872,13 +9901,8 @@ void GLCanvas3D::_render_gcode(int canvas_width, int canvas_height) // Realistic view: the toolpaths receive the same depth map they were rendered into by // _render_shadows, which is what gives them object-on-object and self shadows. Intensity 0 // short-circuits the lookup in the shader, so this is inert whenever the map is missing. - const bool receive_shadows = m_shadow_map_valid && m_shadow_map_texture_id != 0 && m_shadow_map_size != 0; - if (receive_shadows) { - glsafe(::glActiveTexture(GL_TEXTURE4)); - glsafe(::glBindTexture(GL_TEXTURE_2D, m_shadow_map_texture_id)); - glsafe(::glActiveTexture(GL_TEXTURE0)); + if (_bind_gcode_shadow_map(true)) m_gcode_viewer.set_shadow_map(4, m_shadow_light_vp, 0.35f, 1.0f / static_cast(m_shadow_map_size)); - } else m_gcode_viewer.set_shadow_map(4, Transform3d::Identity(), 0.0f, 0.0f); @@ -9890,14 +9914,27 @@ void GLCanvas3D::_render_gcode(int canvas_width, int canvas_height) (_shadow_mode() != EShadowMode::Off || cfg->get_bool(SETTING_OPENGL_PHONG_SSAO)); m_gcode_viewer.set_tone(lossy_passes ? 1.1f : 1.0f, 1.15f); m_gcode_viewer.set_light_top_dir(_static_light_dir_eye().value_or(Vec3d(-0.4574957, 0.4574957, 0.7624929))); + m_gcode_viewer.set_gloss(_is_realistic_view_enabled() && cfg != nullptr && cfg->get_bool(SETTING_OPENGL_REALISTIC_GLOSS)); m_gcode_viewer.render_scene(canvas_width, canvas_height); + _bind_gcode_shadow_map(false); +} - if (receive_shadows) { - glsafe(::glActiveTexture(GL_TEXTURE4)); - glsafe(::glBindTexture(GL_TEXTURE_2D, 0)); - glsafe(::glActiveTexture(GL_TEXTURE0)); - } +void GLCanvas3D::_render_gcode_translucent(int canvas_width, int canvas_height) +{ + _bind_gcode_shadow_map(true); + m_gcode_viewer.render_translucent_toolpaths(canvas_width, canvas_height); + _bind_gcode_shadow_map(false); +} + +bool GLCanvas3D::_bind_gcode_shadow_map(bool bind) const +{ + if (!m_shadow_map_valid || m_shadow_map_texture_id == 0 || m_shadow_map_size == 0) + return false; + glsafe(::glActiveTexture(GL_TEXTURE4)); + glsafe(::glBindTexture(GL_TEXTURE_2D, bind ? m_shadow_map_texture_id : 0)); + glsafe(::glActiveTexture(GL_TEXTURE0)); + return true; } void GLCanvas3D::_render_gcode_overlay(int canvas_width, int canvas_height) diff --git a/src/slic3r/GUI/GLCanvas3D.hpp b/src/slic3r/GUI/GLCanvas3D.hpp index ce537643bd..f24fff0f2b 100644 --- a/src/slic3r/GUI/GLCanvas3D.hpp +++ b/src/slic3r/GUI/GLCanvas3D.hpp @@ -1560,6 +1560,10 @@ private: void _render_xray_volumes(); //BBS: GUI refactor: add canvas size as parameters void _render_gcode(int canvas_width, int canvas_height); + // The translucent toolpaths, after the occlusion pass, which would shade them as the surface behind them. + void _render_gcode_translucent(int canvas_width, int canvas_height); + // Realistic view: binds, or unbinds, the shadow map the toolpaths read on texture unit 4. False without a map. + bool _bind_gcode_shadow_map(bool bind) const; void _render_gcode_overlay(int canvas_width, int canvas_height); //BBS: render a plane for assemble void _render_plane() const; diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index 9de8b3bee6..38f602ab65 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -4382,8 +4382,27 @@ void GUI_App::select_machine(const std::string& agent_id) const auto& preset = preset_bundle->printers.get_edited_preset(); const DynamicPrintConfig* host_cfg = &preset.config; + // Hands the machine to the Device tab's full selection flow (UI updates, callbacks, etc.). + auto select_dev = [this](const std::string& dev_id) { + if (MonitorPanel* monitor = MonitorPanel::if_built()) { + monitor->select_machine(dev_id); + BOOST_LOG_TRIVIAL(info) << "GUI_App::select_machine" << ": triggered select_machine for dev_id=" << dev_id; + } else if (m_device_manager->set_selected_machine(dev_id)) { + // The Device tab's own state is set when the tab is built. + MonitorPanel::on_machine_selected(m_device_manager->get_selected_machine()); + BOOST_LOG_TRIVIAL(info) << "GUI_App::select_machine" << ": set_selected_machine dev_id=" << dev_id; + } + }; + std::string print_host = host_cfg->opt_string("print_host"); if (print_host.empty()) { + // Orca: a printer bound from the Device tab is kept as a device of the agent rather than in + // the preset's print_host. Select it when it is the agent's only one, as + // MainFrame::load_printer_url() does; otherwise nothing is selected until the print dialog + // picks it, and filament sync has no printer to read from. + const auto machines = m_device_manager->get_my_machine_list(agent_id); + if (machines.size() == 1 && machines.begin()->second) + select_dev(machines.begin()->second->get_dev_id()); return; } std::string port = host_cfg->opt_string("printhost_port"); @@ -4430,17 +4449,7 @@ void GUI_App::select_machine(const std::string& agent_id) existing->set_access_code(access_code); } existing->local_use_ssl = boost::istarts_with(print_host, "https://"); - - // Use MonitorPanel::select_machine() to trigger full selection flow - // This reuses existing logic for machine switching (UI updates, callbacks, etc.) - if (MonitorPanel* monitor = MonitorPanel::if_built()) { - monitor->select_machine(dev_id); - BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": triggered select_machine for dev_id=" << dev_id; - } else if (m_device_manager->set_selected_machine(dev_id)) { - // The Device tab's own state is set when the tab is built. - MonitorPanel::on_machine_selected(m_device_manager->get_selected_machine()); - BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": set_selected_machine dev_id=" << dev_id; - } + select_dev(dev_id); } bool GUI_App::dark_mode() @@ -9060,7 +9069,8 @@ void GUI_App::open_preferences(PreferencesTab tab, const std::string& highlight_ // Render settings the canvas reads every frame; a change needs one redraw to show. static constexpr const char* opengl_render_setting_keys[] = { SETTING_OPENGL_FXAA_ENABLED, SETTING_OPENGL_FPS_CAP, SETTING_OPENGL_SHOW_FPS_OVERLAY, SETTING_OPENGL_SHOW_RENDER_TIMINGS, - SETTING_OPENGL_SCENE_CACHE, SETTING_OPENGL_SKIP_IDENTICAL_FRAMES, SETTING_OPENGL_REALISTIC_SHADOWS + SETTING_OPENGL_SCENE_CACHE, SETTING_OPENGL_SKIP_IDENTICAL_FRAMES, SETTING_OPENGL_REALISTIC_SHADOWS, + SETTING_OPENGL_REALISTIC_GLOSS }; std::vector previous_opengl_render_settings; for (const char* key : opengl_render_setting_keys) diff --git a/src/slic3r/GUI/GUI_Factories.cpp b/src/slic3r/GUI/GUI_Factories.cpp index ab815ad135..7cbb19440a 100644 --- a/src/slic3r/GUI/GUI_Factories.cpp +++ b/src/slic3r/GUI/GUI_Factories.cpp @@ -31,6 +31,7 @@ #include "slic3r/GUI/wxExtensions.hpp" #include #include +#include #include #include #include @@ -143,9 +144,11 @@ std::map> SettingsFactory::PART_CATE {"top_shell_layers", L("Top solid layers"), 1}, {"top_shell_thickness", L("Top minimum shell thickness"), 1}, {"top_surface_density", L("Top Surface Density"), 1}, + {"top_color_penetration_layers", "", 1}, {"bottom_shell_layers", L("Bottom solid layers"), 1}, {"bottom_shell_thickness", L("Bottom minimum shell thickness"), 1}, {"bottom_surface_density", L("Bottom Surface Density"), 1}, + {"bottom_color_penetration_layers", "", 1}, {"sparse_infill_density", "", 1}, {"fill_multiline", "", 1}, {"sparse_infill_pattern", "", 1}, @@ -554,6 +557,17 @@ std::vector MenuFactory::get_svg_volume_bitmaps() return volume_bmps; } +size_t MenuFactory::FindPositionById(wxMenu* menu, int id) +{ + const wxMenuItemList& list = menu->GetMenuItems(); + size_t idx = 0; + for (auto node = list.GetFirst(); node; node = node->GetNext(), ++idx) { + if (node->GetData()->GetId() == id) + return idx; + } + return wxNOT_FOUND; // or list.GetCount() +} + void MenuFactory::append_menu_item_set_visible(wxMenu* menu) { bool has_one_shown = false; @@ -1178,7 +1192,7 @@ void MenuFactory::append_menu_item_scale_selection_to_fit_print_volume(wxMenu* m [](wxCommandEvent&) { plater()->scale_selection_to_fit_print_volume(); }, "", menu); } -void MenuFactory::append_menu_items_flush_options(wxMenu* menu) +void MenuFactory::append_menu_items_flush_options(wxMenu* menu, size_t pos) { const wxString name = _L("Flush Options"); // Delete old menu item @@ -1260,15 +1274,7 @@ void MenuFactory::append_menu_items_flush_options(wxMenu* menu) return option->getBool(); }, m_parent); - size_t i = 0; - for (auto node = menu->GetMenuItems().GetFirst(); node; node = node->GetNext()) - { - i++; - wxMenuItem* item = node->GetData(); - if (item->GetItemLabelText() == _L("Edit in Parameter Table")) - break; - } - menu->Insert(i, wxID_ANY, _L("Flush Options"), flush_options_menu); + menu->Insert(pos, wxID_ANY, _L("Flush Options"), flush_options_menu); } void MenuFactory::append_menu_items_convert_unit(wxMenu* menu) @@ -1342,29 +1348,95 @@ void MenuFactory::append_menu_item_merge_to_single_object(wxMenu* menu) []() { return obj_list()->can_merge_to_single_object(); }, m_parent); } -void MenuFactory::append_menu_item_merge_parts_to_single_part(wxMenu* menu) +wxMenu* MenuFactory::append_menu_item_transform(wxMenu* menu, bool multi_selection, bool show_mirror, bool is_scalable) { - menu->AppendSeparator(); - append_menu_item(menu, wxID_ANY, _L("Mesh boolean"), _L("Mesh boolean operations including union and subtraction"), - [](wxCommandEvent&) { obj_list()->boolean/*merge_volumes*/(); }, "", menu, - []() { return obj_list()->can_mesh_boolean(); }, m_parent); + wxMenu* sub_menu = new wxMenu(); + + if(show_mirror){ + // Mirror + append_menu_item(sub_menu, wxID_ANY, _L("Mirror") + ":", "", [](wxCommandEvent&){}, "", menu, [](){return false;}, m_parent); + append_menu_item(sub_menu, wxID_ANY, _L("Along X Axis"), _L("Mirror along the X axis"), + [](wxCommandEvent&) { plater()->mirror(X); }, "menu_mirror_x", m_parent); + append_menu_item(sub_menu, wxID_ANY, _L("Along Y Axis"), _L("Mirror along the Y axis"), + [](wxCommandEvent&) { plater()->mirror(Y); }, "menu_mirror_y", m_parent); + append_menu_item(sub_menu, wxID_ANY, _L("Along Z Axis"), _L("Mirror along the Z axis"), + [](wxCommandEvent&) { plater()->mirror(Z); }, "menu_mirror_z", m_parent); + } + + if(is_scalable){ + if(sub_menu->GetMenuItemCount() > 0) + sub_menu->AppendSeparator(); + append_menu_item_scale_selection_to_fit_print_volume(sub_menu); + sub_menu->AppendSeparator(); // Convert units will be added later + } + + append_submenu(menu, sub_menu, wxID_ANY, _L("Transform"), "", "", [](){return true;}, m_parent); + return sub_menu; } -void MenuFactory::append_menu_items_mirror(wxMenu* menu) +wxMenu* MenuFactory::append_menu_item_modify(wxMenu* menu, bool multi_selection, bool splittable, bool is_mesh, bool mesh_boolean) { - wxMenu* mirror_menu = new wxMenu(); - if (!mirror_menu) - return; + wxMenu* sub_menu = new wxMenu(); - append_menu_item(mirror_menu, wxID_ANY, _L("Along X Axis"), _L("Mirror along the X Axis"), - [](wxCommandEvent&) { plater()->mirror(X); }, "menu_mirror_x", menu); - append_menu_item(mirror_menu, wxID_ANY, _L("Along Y Axis"), _L("Mirror along the Y Axis"), - [](wxCommandEvent&) { plater()->mirror(Y); }, "menu_mirror_y", menu); - append_menu_item(mirror_menu, wxID_ANY, _L("Along Z Axis"), _L("Mirror along the Z Axis"), - [](wxCommandEvent&) { plater()->mirror(Z); }, "menu_mirror_z", menu); + if(splittable){ + // Object Split + append_menu_item(sub_menu, wxID_ANY, _L("Split") + ":", "", [](wxCommandEvent&){}, "", menu, [](){return false;}, m_parent); + append_menu_item(sub_menu, wxID_ANY, _L("To Objects"), _L("Split the selected object into multiple objects"), + [](wxCommandEvent&) { plater()->split_object(); }, "menu_split_objects", menu, + []() { return plater()->can_split(true); }, m_parent); + append_menu_item(sub_menu, wxID_ANY, _L("To Parts"), _L("Split the selected object into multiple parts"), + [](wxCommandEvent&) { plater()->split_volume(); }, "menu_split_parts", menu, + []() { return plater()->can_split(false); }, m_parent); + } - append_submenu(menu, mirror_menu, wxID_ANY, _L("Mirror"), _L("Mirror object"), "", - []() { return plater()->can_mirror(); }, m_parent); + if(mesh_boolean){ + if(sub_menu->GetMenuItemCount() > 0) + sub_menu->AppendSeparator(); + // Mesh Boolean + append_menu_item(sub_menu, wxID_ANY, _L("Mesh boolean"), _L("Mesh boolean operations including union and subtraction"), + [](wxCommandEvent&) { obj_list()->boolean/*merge_volumes*/(); }, "", menu, + []() { return obj_list()->can_mesh_boolean(); }, m_parent); + + } + + if(is_mesh){ + if(sub_menu->GetMenuItemCount() > 0) + sub_menu->AppendSeparator(); + if(!multi_selection){ // these doesnt support multiple items + // Object Simplify + append_menu_item_simplify(sub_menu); + // Mesh Smooth / Subdivision + append_menu_item_smooth_mesh(sub_menu); + sub_menu->AppendSeparator(); + } + // Object Repair + append_menu_item_fix_through_cgal(sub_menu); + } + + append_submenu(menu, sub_menu, wxID_ANY, _L("Modify"), "", "", [](){return true;}, m_parent); + return sub_menu; +} + +wxMenu* MenuFactory::append_menu_item_more(wxMenu* menu, bool multi_selection, bool disk_op, bool export_op) +{ + wxMenu* sub_menu = new wxMenu(); + + if(disk_op){ + // Reload from disk supports multi selection too (#16589) + append_menu_item_reload_from_disk(sub_menu); + sub_menu->AppendSeparator(); + if(!multi_selection) // "Replace with STL" only works on a single item + append_menu_item_replace_with_stl(sub_menu); + append_menu_item_replace_all_with_stl(sub_menu); + } + if(export_op){ + sub_menu->AppendSeparator(); + append_menu_item_export_stl(sub_menu, multi_selection); + append_menu_item_export_drc(sub_menu, multi_selection); + } + append_submenu(menu, sub_menu, wxID_ANY, _L("More"), "", "",[](){return true;}, m_parent); + + return sub_menu; } void MenuFactory::append_menu_item_precise_seam_submenu(wxMenu* menu) @@ -1492,7 +1564,7 @@ void MenuFactory::append_menu_item_precise_seam_submenu(wxMenu* menu) insert_pos); } -void MenuFactory::append_menu_item_edit_text(wxMenu *menu) +void MenuFactory::append_menu_item_edit_text(wxMenu *menu, size_t pos) { wxString name = _L("Edit text"); @@ -1513,8 +1585,13 @@ void MenuFactory::append_menu_item_edit_text(wxMenu *menu) if (menu != &m_text_part_menu) { const int menu_item_id = menu->FindItem(name); - if (menu_item_id != wxNOT_FOUND) + if (menu_item_id != wxNOT_FOUND) { + // Delete old menu item and the separator placed right after it + const size_t item_pos = FindPositionById(menu, menu_item_id); + if (item_pos != size_t(wxNOT_FOUND) && item_pos + 1 < menu->GetMenuItemCount() && menu->FindItemByPosition(item_pos + 1)->IsSeparator()) + menu->Destroy(menu->FindItemByPosition(item_pos + 1)); menu->Destroy(menu_item_id); + } if (!can_edit_text()) return; } @@ -1527,10 +1604,14 @@ void MenuFactory::append_menu_item_edit_text(wxMenu *menu) mng.open_gizmo(GLGizmosManager::Emboss); // close() and reopen - move to be visible mng.open_gizmo(GLGizmosManager::Emboss); }; - append_menu_item(menu, wxID_ANY, name, description, open_emboss, icon, nullptr, can_edit_text, m_parent); + append_menu_item(menu, wxID_ANY, name, description, open_emboss, icon, nullptr, can_edit_text, m_parent, pos); + if (pos == size_t(wxNOT_FOUND)) + menu->AppendSeparator(); + else + menu->InsertSeparator(pos + 1); } -void MenuFactory::append_menu_item_edit_svg(wxMenu *menu) +void MenuFactory::append_menu_item_edit_svg(wxMenu *menu, size_t pos) { wxString name = _L("Edit SVG"); auto can_edit_svg = []() { @@ -1550,8 +1631,13 @@ void MenuFactory::append_menu_item_edit_svg(wxMenu *menu) if (menu != &m_svg_part_menu) { const int menu_item_id = menu->FindItem(name); - if (menu_item_id != wxNOT_FOUND) + if (menu_item_id != wxNOT_FOUND) { + // Delete old menu item and the separator placed right after it + const size_t item_pos = FindPositionById(menu, menu_item_id); + if (item_pos != size_t(wxNOT_FOUND) && item_pos + 1 < menu->GetMenuItemCount() && menu->FindItemByPosition(item_pos + 1)->IsSeparator()) + menu->Destroy(menu->FindItemByPosition(item_pos + 1)); menu->Destroy(menu_item_id); + } if (!can_edit_svg()) return; } @@ -1564,21 +1650,34 @@ void MenuFactory::append_menu_item_edit_svg(wxMenu *menu) mng.open_gizmo(GLGizmosManager::Svg); // close() and reopen - move to be visible mng.open_gizmo(GLGizmosManager::Svg); }; - append_menu_item(menu, wxID_ANY, name, description, open_svg, icon, nullptr, can_edit_svg, m_parent); + append_menu_item(menu, wxID_ANY, name, description, open_svg, icon, nullptr, can_edit_svg, m_parent, pos); + if (pos == size_t(wxNOT_FOUND)) + menu->AppendSeparator(); + else + menu->InsertSeparator(pos + 1); } -void MenuFactory::append_menu_item_invalidate_cut_info(wxMenu *menu) +void MenuFactory::append_menu_item_invalidate_cut_info(wxMenu *menu, size_t pos) { const wxString menu_name = _L("Invalidate cut info"); auto menu_item_id = menu->FindItem(menu_name); - if (menu_item_id != wxNOT_FOUND) - // Delete old menu item if selected object isn't cut + if (menu_item_id != wxNOT_FOUND) { + // Delete old menu item (and the separator placed right after it) if selected object isn't cut + const size_t item_pos = FindPositionById(menu, menu_item_id); + if (item_pos != size_t(wxNOT_FOUND) && item_pos + 1 < menu->GetMenuItemCount() && menu->FindItemByPosition(item_pos + 1)->IsSeparator()) + menu->Destroy(menu->FindItemByPosition(item_pos + 1)); menu->Destroy(menu_item_id); + } - if (obj_list()->has_selected_cut_object()) + if (obj_list()->has_selected_cut_object()) { append_menu_item(menu, wxID_ANY, menu_name, "", [](wxCommandEvent &) { obj_list()->invalidate_cut_info_for_selection(); }, - "", menu, []() { return true; }, m_parent); + "cut_", menu, []() { return true; }, m_parent, pos); + if (pos == size_t(wxNOT_FOUND)) + menu->AppendSeparator(); + else + menu->InsertSeparator(pos + 1); + } } MenuFactory::MenuFactory() @@ -1613,9 +1712,16 @@ void MenuFactory::create_default_menu() void MenuFactory::create_common_object_menu(wxMenu* menu) { append_menu_item_rename(menu); + menu->AppendSeparator(); + append_menu_items_instance_manipulation(menu); + // Object Split / Mirror / Mesh Tools + append_menu_item_transform(menu, false /*multi_selection*/, true /*mirror*/, false /*is_scalable*/); + append_menu_item_modify(menu, false /*multi_selection*/, true /*splittable*/, true /*mesh*/, false /*mesh_boolean*/); + // Delete menu was moved to be after +/- instace to make it more difficult to be selected by mistake. + menu->AppendSeparator(); append_menu_item_delete(menu); menu->AppendSeparator(); @@ -1624,28 +1730,11 @@ void MenuFactory::create_common_object_menu(wxMenu* menu) append_menu_item_export_drc(menu); // "Scale to print volume" makes a sense just for whole object append_menu_item_scale_selection_to_fit_print_volume(menu); - - append_menu_item_fix_through_cgal(menu); - append_menu_items_mirror(menu); } void MenuFactory::create_object_menu() { create_common_object_menu(&m_object_menu); - wxMenu* split_menu = new wxMenu(); - if (!split_menu) - return; - - append_menu_item(split_menu, wxID_ANY, _L("To Objects"), _L("Split the selected object into multiple objects"), - [](wxCommandEvent&) { plater()->split_object(); }, "menu_split_objects", &m_object_menu, - []() { return plater()->can_split(true); }, m_parent); - append_menu_item(split_menu, wxID_ANY, _L("To Parts"), _L("Split the selected object into multiple parts"), - [](wxCommandEvent&) { plater()->split_volume(); }, "menu_split_parts", &m_object_menu, - []() { return plater()->can_split(false); }, m_parent); - - append_submenu(&m_object_menu, split_menu, wxID_ANY, _L("Split"), _L("Split the selected object"), "", - []() { return plater()->can_split(true) || plater()->can_split(false); }, m_parent); - m_object_menu.AppendSeparator(); // BBS: remove Layers Editing m_object_menu.AppendSeparator(); @@ -1655,88 +1744,69 @@ void MenuFactory::create_object_menu() void MenuFactory::create_extra_object_menu() { - // Object instances / conversions - append_menu_items_instance_manipulation(&m_object_menu); - m_object_menu.AppendSeparator(); - append_menu_item_instance_to_object(&m_object_menu); - m_object_menu.AppendSeparator(); - //append_menu_item_fill_bed(&m_object_menu); // Object Clone append_menu_item_clone(&m_object_menu); - // Object Repair - append_menu_item_fix_through_cgal(&m_object_menu); - // Object Simplify - append_menu_item_simplify(&m_object_menu); - // Object Mesh Subdivision - append_menu_item_smooth_mesh(&m_object_menu); - // merge to single part - append_menu_item_merge_parts_to_single_part(&m_object_menu); + + // Instances + auto instances = new wxMenu(); + if (!instances) return; + append_menu_items_instance_manipulation(instances); + instances->AppendSeparator(); + append_menu_item_instance_to_object(instances); + append_submenu(&m_object_menu, instances, wxID_ANY, _L("Instances"), "", "",[](){return true;}, m_parent); + + m_object_menu.AppendSeparator(); + // Object Center append_menu_item_center(&m_object_menu); + + append_menu_item_drop(&m_object_menu); + + m_object_transform_menu = append_menu_item_transform(&m_object_menu, false /*multi_selection*/, true /*mirror*/, true /*is_scalable*/); // Object Align/Distribute append_menu_item_align_distribute(&m_object_menu); - // Object Drop - append_menu_item_drop(&m_object_menu); - // Object Split - wxMenu* split_menu = new wxMenu(); - if (!split_menu) - return; - append_menu_item(split_menu, wxID_ANY, _L("To Objects"), _L("Split the selected object into multiple objects"), - [](wxCommandEvent&) { plater()->split_object(); }, "menu_split_objects", &m_object_menu, - []() { return plater()->can_split(true); }, m_parent); - append_menu_item(split_menu, wxID_ANY, _L("To Parts"), _L("Split the selected object into multiple parts"), - [](wxCommandEvent&) { plater()->split_volume(); }, "menu_split_parts", &m_object_menu, - []() { return plater()->can_split(false); }, m_parent); - - append_submenu(&m_object_menu, split_menu, wxID_ANY, _L("Split"), _L("Split the selected object"), "", - []() { return plater()->can_split(true); }, m_parent); - - // Mirror - append_menu_items_mirror(&m_object_menu); + append_menu_item_modify(&m_object_menu, false /*multi_selection*/, true /*splittable*/, true /*mesh*/, true /*mesh_boolean*/); + m_object_geometry_pos = m_object_menu.GetMenuItemCount(); // pos for property related items // Delete + m_object_menu.AppendSeparator(); append_menu_item_delete(&m_object_menu); m_object_menu.AppendSeparator(); + // Modifier Part // BBS append_menu_items_add_volume(&m_object_menu); - m_object_menu.AppendSeparator(); + + wxMenuItem* props_marker = m_object_menu.Append(wxID_ANY, "", "", wxITEM_SEPARATOR); // AppendSeparator() not assigns an id to item + m_object_props_marker = props_marker->GetId(); + // Set filament insert menu item here // Set Printable wxMenuItem* menu_item_printable = append_menu_item_printable(&m_object_menu); - m_object_menu.AppendSeparator(); wxMenuItem* menu_item_auto_drop = append_menu_item_auto_drop(&m_object_menu); m_object_menu.AppendSeparator(); append_menu_item_per_object_process(&m_object_menu); // Enter per object parameters append_menu_item_per_object_settings(&m_object_menu); + + // ORCA Utilities menu m_object_menu.AppendSeparator(); - append_menu_item_reload_from_disk(&m_object_menu); - append_menu_item_replace_with_stl(&m_object_menu); - append_menu_item_replace_all_with_stl(&m_object_menu); - append_menu_item_export_stl(&m_object_menu); - append_menu_item_export_drc(&m_object_menu); + append_menu_item_more(&m_object_menu, false /*multi_selection*/, true /*disk_op*/, true/*export_op*/); } void MenuFactory::create_bbl_assemble_object_menu() { // Delete append_menu_item_delete(&m_assemble_object_menu); - // Object Repair - append_menu_item_fix_through_cgal(&m_assemble_object_menu); - // Object Simplify - append_menu_item_simplify(&m_assemble_object_menu); - // Object Mesh Subdivision - append_menu_item_smooth_mesh(&m_assemble_object_menu); + m_assemble_object_menu.AppendSeparator(); + + append_menu_item_modify(&m_assemble_object_menu, false /*multi_selection*/, false /*splittable*/, true /*mesh*/, false /*mesh_boolean*/); m_assemble_object_menu.AppendSeparator(); } void MenuFactory::create_sla_object_menu() { create_common_object_menu(&m_sla_object_menu); - append_menu_item(&m_sla_object_menu, wxID_ANY, _L("Split"), _L("Split the selected object into multiple objects"), - [](wxCommandEvent&) { plater()->split_object(); }, "", nullptr, - []() { return plater()->can_split(true); }, m_parent); m_sla_object_menu.AppendSeparator(); @@ -1745,49 +1815,29 @@ void MenuFactory::create_sla_object_menu() [](wxCommandEvent&) { plater()->optimize_rotation(); }); } -void MenuFactory::create_part_menu() -{ - wxMenu* menu = &m_part_menu; - append_menu_item_rename(menu); - append_menu_item_delete(menu); - append_menu_item_reload_from_disk(menu); - append_menu_item_export_stl(menu); - append_menu_item_export_drc(menu); - append_menu_item_fix_through_cgal(menu); - append_menu_items_mirror(menu); - append_menu_item_merge_parts_to_single_part(menu); - - append_menu_item(menu, wxID_ANY, _L("Split"), _L("Split the selected object into multiple parts"), - [](wxCommandEvent&) { plater()->split_volume(); }, "split_parts", nullptr, - []() { return plater()->can_split(false); }, m_parent); - - menu->AppendSeparator(); - append_menu_item_change_type(menu); - append_menu_item_precise_seam_submenu(menu); - append_menu_items_mirror(&m_part_menu); - append_menu_item(&m_part_menu, wxID_ANY, _L("Split"), _L("Split the selected object into multiple parts"), - [](wxCommandEvent&) { plater()->split_volume(); }, "split_parts", nullptr, - []() { return plater()->can_split(false); }, m_parent); - m_part_menu.AppendSeparator(); - append_menu_item_per_object_process(&m_part_menu); - append_menu_item_per_object_settings(&m_part_menu); -} - void MenuFactory::create_text_part_menu() { wxMenu* menu = &m_text_part_menu; append_menu_item_edit_text(menu); - append_menu_item_delete(menu); - append_menu_item_fix_through_cgal(menu); - append_menu_item_simplify(menu); + append_menu_item_center(menu); append_menu_item_align_distribute(menu); - append_menu_items_mirror(menu); + append_menu_item_transform(&m_text_part_menu, false /*multi_selection*/, true /*mirror*/, false /*is_scalable*/); + append_menu_item_modify(&m_text_part_menu, false /*multi_selection*/, false /*splittable*/, true /*mesh*/, false /*mesh_boolean*/); + + //m_text_geometry_pos = m_text_part_menu.GetMenuItemCount(); // pos for geometry related items + menu->AppendSeparator(); - append_menu_item_per_object_process(menu); - append_menu_item_per_object_settings(menu); + append_menu_item_delete(menu); + menu->AppendSeparator(); + append_menu_item_change_type(menu); + m_text_props_marker = menu->FindItem(_L("Change Type")); // dynamic property items are inserted after this item + menu->AppendSeparator(); + + append_menu_item_per_object_process(menu); + m_text_project_marker = menu->FindItem(_L("Paste Process Settings")); // append_menu_item_per_object_settings() is inserted after this item } void MenuFactory::create_svg_part_menu() @@ -1795,49 +1845,52 @@ void MenuFactory::create_svg_part_menu() wxMenu* menu = &m_svg_part_menu; append_menu_item_edit_svg(menu); - append_menu_item_delete(menu); - append_menu_item_fix_through_cgal(menu); - append_menu_item_simplify(menu); - append_menu_items_mirror(menu); + + append_menu_item_center(menu); + append_menu_item_align_distribute(menu); + append_menu_item_transform(&m_svg_part_menu, false /*multi_selection*/, true /*mirror*/, false /*is_scalable*/); + append_menu_item_modify(&m_svg_part_menu, false /*multi_selection*/, false /*splittable*/, true /*mesh*/, false /*mesh_boolean*/); + + //m_svg_geometry_pos = m_svg_part_menu.GetMenuItemCount(); // pos for geometry related items + menu->AppendSeparator(); - append_menu_item_per_object_process(menu); - append_menu_item_per_object_settings(menu); + append_menu_item_delete(menu); + menu->AppendSeparator(); + append_menu_item_change_type(menu); + m_svg_props_marker = menu->FindItem(_L("Change Type")); // dynamic property items are inserted after this item + menu->AppendSeparator(); + + append_menu_item_per_object_process(menu); + m_svg_project_marker = menu->FindItem(_L("Paste Process Settings")); // append_menu_item_per_object_settings() is inserted after this item } void MenuFactory::create_bbl_part_menu() { wxMenu* menu = &m_part_menu; - append_menu_item_delete(menu); - append_menu_item_edit_text(menu); - append_menu_item_fix_through_cgal(menu); - append_menu_item_simplify(menu); - append_menu_item_smooth_mesh(menu); append_menu_item_center(menu); + append_menu_item_drop(&m_part_menu); + + m_part_transform_menu = append_menu_item_transform(&m_part_menu, false /*multi_selection*/, true /*mirror*/, true /*is_scalable*/); append_menu_item_align_distribute(menu); - append_menu_item_drop(menu); - append_menu_items_mirror(menu); - wxMenu* split_menu = new wxMenu(); - if (!split_menu) - return; + append_menu_item_modify(&m_part_menu, false /*multi_selection*/, true /*splittable*/, true /*mesh*/, false /*mesh_boolean*/); + append_menu_item_edit_text(menu); + //m_part_geometry_pos = m_part_menu.GetMenuItemCount(); // pos for geometry related items - append_menu_item(split_menu, wxID_ANY, _L("To Objects"), _L("Split the selected object into multiple objects"), - [](wxCommandEvent&) { plater()->split_object(); }, "menu_split_objects", menu, - []() { return plater()->can_split(true); }, m_parent); - append_menu_item(split_menu, wxID_ANY, _L("To Parts"), _L("Split the selected object into multiple parts"), - [](wxCommandEvent&) { plater()->split_volume(); }, "menu_split_parts", menu, - []() { return plater()->can_split(false); }, m_parent); - - append_submenu(menu, split_menu, wxID_ANY, _L("Split"), _L("Split the selected object"), "", - []() { return plater()->can_split(true); }, m_parent); menu->AppendSeparator(); - append_menu_item_per_object_process(menu); - append_menu_item_per_object_settings(menu); + append_menu_item_delete(menu); + menu->AppendSeparator(); + append_menu_item_change_type(menu); - append_menu_item_reload_from_disk(menu); - append_menu_item_replace_with_stl(menu); - append_menu_item_replace_all_with_stl(menu); + m_part_props_marker = menu->FindItem(_L("Change Type")); // dynamic property items are inserted after this item + menu->AppendSeparator(); + + append_menu_item_per_object_process(menu); + m_part_project_marker = menu->FindItem(_L("Paste Process Settings")); // append_menu_item_per_object_settings() is inserted after this item + + menu->AppendSeparator(); + append_menu_item_more(&m_part_menu, false /*multi_selection*/, true /*disk_op*/, false /*export_op*/); } void MenuFactory::create_bbl_assemble_part_menu() @@ -1920,9 +1973,10 @@ void MenuFactory::create_plate_menu() [](wxCommandEvent&) { plater()->select_all(); }, "", nullptr, []() { - return !plater()->model().objects.empty(); + return !plater()->model().objects.empty() && plater()->can_delete_plate(); // also disable when only one plate exist }, m_parent); + menu->AppendSeparator(); // delete objects on current plate append_menu_item(menu, wxID_ANY, _L("Delete All"), _L("Delete all objects on the current plate"), [](wxCommandEvent&) { @@ -1933,6 +1987,8 @@ void MenuFactory::create_plate_menu() return !plate->get_objects().empty(); }, m_parent); + menu->AppendSeparator(); + // arrange objects on current plate append_menu_item(menu, wxID_ANY, _L("Arrange"), _L("Arrange current plate"), [](wxCommandEvent&) { @@ -1946,33 +2002,11 @@ void MenuFactory::create_plate_menu() }, m_parent); - // reload all objects on current plate - append_menu_item( - menu, wxID_ANY, _L("Reload All"), _L("Reload all from disk"), - [](wxCommandEvent&) { - PartPlate* plate = plater()->get_partplate_list().get_selected_plate(); - assert(plate); - plater()->set_prepare_state(Job::PREPARE_STATE_MENU); - plater()->reload_all_from_disk(); - }, - "", 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&) { PartPlate* plate = plater()->get_partplate_list().get_selected_plate(); assert(plate); - //BBS TODO call auto rotate for current plate plater()->set_prepare_state(Job::PREPARE_STATE_MENU); plater()->orient(); }, "", nullptr, @@ -1980,17 +2014,24 @@ void MenuFactory::create_plate_menu() return !plater()->get_partplate_list().get_selected_plate()->get_objects().empty(); }, m_parent); - // delete current plate -#ifdef __WINDOWS__ - append_menu_item(menu, wxID_ANY, _L("Delete Plate"), _L("Remove the selected plate"), - [](wxCommandEvent&) { plater()->delete_plate(); }, "menu_delete", nullptr, - []() { return plater()->can_delete_plate(); }, m_parent); -#else - append_menu_item(menu, wxID_ANY, _L("Delete Plate"), _L("Remove the selected plate"), - [](wxCommandEvent&) { plater()->delete_plate(); }, "", nullptr, - []() { return plater()->can_delete_plate(); }, m_parent); -#endif + wxMenu* modify_menu = new wxMenu(); + // fix objects on current plate + append_menu_item(modify_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(modify_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); + + append_submenu(menu, modify_menu, wxID_ANY, _L("Modify"), "", "", + [](){ return !plater()->model().objects.empty(); }, m_parent); + + menu->AppendSeparator(); + + m_plate_mods_pos = menu->GetMenuItemCount(); // pos for dynamic plate items (Edit Plate Name / Lock / Delete Plate) // add shapes menu->AppendSeparator(); @@ -2005,9 +2046,20 @@ void MenuFactory::create_plate_menu() [](wxCommandEvent&) { plater()->add_file(); }, "menu_add_part", menu, []() {return wxGetApp().plater()->can_add_model(); }, m_parent); + menu->AppendSeparator(); + // reload all objects on current plate + append_menu_item( + menu, wxID_ANY, _L("Reload All"), _L("Reload all from disk"), + [](wxCommandEvent&) { + PartPlate* plate = plater()->get_partplate_list().get_selected_plate(); + assert(plate); + plater()->set_prepare_state(Job::PREPARE_STATE_MENU); + plater()->reload_all_from_disk(); + }, + "", nullptr, []() { return !plater()->get_partplate_list().get_selected_plate()->get_objects().empty(); }, m_parent); + menu->AppendSeparator(); append_menu_item_replace_all_with_stl(menu); - return; } @@ -2019,7 +2071,6 @@ void MenuFactory::init(wxWindow* parent) //BBS //create_object_menu(); create_sla_object_menu(); - //create_part_menu(); create_text_part_menu(); create_svg_part_menu(); create_extra_object_menu(); @@ -2049,12 +2100,18 @@ wxMenu* MenuFactory::default_menu() wxMenu* MenuFactory::object_menu() { - append_menu_items_convert_unit(&m_object_menu); - append_menu_items_flush_options(&m_object_menu); - append_menu_item_invalidate_cut_info(&m_object_menu); - append_menu_item_edit_text(&m_object_menu); - append_menu_item_edit_svg(&m_object_menu); - append_menu_item_change_filament(&m_object_menu); + append_menu_items_convert_unit(m_object_transform_menu); + + // GEOMETRY + append_menu_item_invalidate_cut_info(&m_object_menu, 0); // inserts itself to top of menu + append_menu_item_edit_text( &m_object_menu, 0); // inserts itself to top of menu + append_menu_item_edit_svg( &m_object_menu, 0); // inserts itself to top of menu + + // PROPS > Place items above printable + size_t props_pos = FindPositionById(&m_object_menu, m_object_props_marker); // stored positions not works as expected since menu has multiple dynamic sections + append_menu_item_change_filament(&m_object_menu, props_pos + 1); + append_menu_items_flush_options (&m_object_menu, props_pos + 2); + return &m_object_menu; } @@ -2063,33 +2120,35 @@ wxMenu* MenuFactory::sla_object_menu() append_menu_items_convert_unit(&m_sla_object_menu); append_menu_item_settings(&m_sla_object_menu); //update_menu_items_instance_manipulation(mtObjectSLA); - append_menu_item_edit_text(&m_sla_object_menu); - append_menu_item_edit_svg(&m_object_menu); + append_menu_item_edit_text(&m_sla_object_menu, 0); // inserts itself to top of menu + append_menu_item_edit_svg(&m_sla_object_menu, 0); // inserts itself to top of menu return &m_sla_object_menu; } wxMenu* MenuFactory::part_menu() { - append_menu_items_convert_unit(&m_part_menu); - append_menu_item_change_filament(&m_part_menu); + append_menu_items_convert_unit(m_part_transform_menu); + + // stored positions not works as expected since menu has multiple dynamic sections + append_menu_item_per_object_settings(&m_part_menu, FindPositionById(&m_part_menu, m_part_project_marker) + 1); + append_menu_item_change_filament(&m_part_menu, FindPositionById(&m_part_menu, m_part_props_marker) + 1); append_menu_item_precise_seam_submenu(&m_part_menu); - append_menu_item_per_object_settings(&m_part_menu); return &m_part_menu; } wxMenu* MenuFactory::text_part_menu() { - append_menu_item_change_filament(&m_text_part_menu); - append_menu_item_per_object_settings(&m_text_part_menu); + append_menu_item_per_object_settings(&m_text_part_menu, FindPositionById(&m_text_part_menu, m_text_project_marker) + 1); + append_menu_item_change_filament(&m_text_part_menu, FindPositionById(&m_text_part_menu, m_text_props_marker) + 1); return &m_text_part_menu; } wxMenu *MenuFactory::svg_part_menu() { - append_menu_item_change_filament(&m_svg_part_menu); - append_menu_item_per_object_settings(&m_svg_part_menu); + append_menu_item_per_object_settings(&m_svg_part_menu, FindPositionById(&m_svg_part_menu, m_svg_project_marker) + 1); + append_menu_item_change_filament(&m_svg_part_menu, FindPositionById(&m_svg_part_menu, m_svg_props_marker) + 1); return &m_svg_part_menu; } @@ -2138,65 +2197,64 @@ wxMenu* MenuFactory::multi_selection_menu() int index = 0; if (obj_list()->can_merge_to_multipart_object()) { append_menu_item_merge_to_multipart_object(menu); + menu->AppendSeparator(); index++; } append_menu_item_center(menu); - append_menu_item_align_distribute(menu); append_menu_item_drop(menu); + + auto transform_menu = append_menu_item_transform(menu, true /*multi_selection*/, false /*mirror*/, true /*is_scalable*/); + append_menu_items_convert_unit(transform_menu); + append_menu_item_align_distribute(menu); + //ORCA switch to sub menus if new items added + //append_menu_item_modify(menu, true /*multi_selection*/, false /*splittable*/, true /*is_mesh*/, false /*mesh_boolean*/); append_menu_item_fix_through_cgal(menu); //append_menu_item_simplify(menu); + menu->AppendSeparator(); append_menu_item_delete(menu); menu->AppendSeparator(); + append_menu_item_change_filament(menu); append_menu_item_set_printable(menu); - menu->AppendSeparator(); - append_menu_item_set_auto_drop(menu); menu->AppendSeparator(); append_menu_item_per_object_process(menu); menu->AppendSeparator(); - append_menu_items_convert_unit(menu); - append_menu_item_reload_from_disk(menu); - append_menu_item_replace_all_with_stl(menu); - //BBS - append_menu_item_change_filament(menu); - menu->AppendSeparator(); - append_menu_item_export_stl(menu, true); - append_menu_item_export_drc(menu, true); + // Reload from disk / Replace all with STL / Export STL / Export DRC + append_menu_item_more(menu, true /*multi_selection*/, true /*disk_op*/, true /*export_op*/); } else { append_menu_item_center(menu); - append_menu_item_align_distribute(menu); append_menu_item_drop(menu); - append_menu_item_fix_through_cgal(menu); - //append_menu_item_simplify(menu); - append_menu_item_delete(menu); - append_menu_items_convert_unit(menu); - append_menu_item_reload_from_disk(menu); - append_menu_item_replace_all_with_stl(menu); - append_menu_item_change_filament(menu); - wxMenu* split_menu = new wxMenu(); - if (split_menu) { - append_menu_item(split_menu, wxID_ANY, _L("To Objects"), _L("Split the selected object into multiple objects"), - [](wxCommandEvent&) { plater()->split_object(); }, "menu_split_objects", menu, - []() { return plater()->can_split(true); }, m_parent); - append_menu_item(split_menu, wxID_ANY, _L("To Parts"), _L("Split the selected object into multiple parts"), - [](wxCommandEvent&) { plater()->split_volume(); }, "menu_split_parts", menu, - []() { return plater()->can_split(false); }, m_parent); - append_submenu(menu, split_menu, wxID_ANY, _L("Split"), _L("Split the selected object"), "", - []() { return plater()->can_split(true); }, m_parent); - } - append_menu_item_per_object_process(menu); + //ORCA switch to sub menus if new items added + auto transform_menu = append_menu_item_transform(menu, true /*multi_selection*/, false /*mirror*/, true /*is_scalable*/); + append_menu_item_align_distribute(menu); + append_menu_item_modify(menu, true /*multi_selection*/, true /*splittable*/, true /*is_mesh*/, false /*mesh_boolean*/); + //append_menu_item_drop(menu); + //append_menu_item_fix_through_cgal(menu); + append_menu_items_convert_unit(transform_menu); + //append_menu_item_simplify(menu); menu->AppendSeparator(); + append_menu_item_delete(menu); + menu->AppendSeparator(); + + append_menu_item_change_filament(menu); append_menu_item_change_type(menu); // Subtype picker for Precise Seam — shown only when all selected volumes are PS. // Must be paired with Change Type here (as in single-volume part_menu), otherwise // the user cannot switch PS subtypes (LEFT/RIGHT/etc.) on multi-selection. - append_menu_item_precise_seam_submenu(menu); - append_menu_item_change_filament(menu); + append_menu_item_precise_seam_submenu(menu); // inserts itself right after "Change Type" + append_menu_item_set_auto_drop(menu); + menu->AppendSeparator(); + + append_menu_item_per_object_process(menu); + menu->AppendSeparator(); + + // Reload from disk / Replace all with STL + append_menu_item_more(menu, true /*multi_selection*/, true /*disk_op*/, false /*export_op*/); } return menu; } @@ -2215,6 +2273,7 @@ wxMenu* MenuFactory::assemble_multi_selection_menu() append_menu_item_set_visible(menu); //append_menu_item_fix_through_cgal(menu); //append_menu_item_simplify(menu); + menu->AppendSeparator(); append_menu_item_delete(menu); menu->AppendSeparator(); append_menu_item_change_extruder(menu); @@ -2250,8 +2309,9 @@ wxMenu *MenuFactory::filament_action_menu(int active_filament_menu_id) { //BBS: add partplate related logic wxMenu* MenuFactory::plate_menu() { - append_menu_item_locked(&m_plate_menu); - append_menu_item_plate_name(&m_plate_menu); + append_menu_item_plate_name( &m_plate_menu, m_plate_mods_pos); + append_menu_item_locked( &m_plate_menu, m_plate_mods_pos + 1); + append_menu_item_plate_delete(&m_plate_menu, m_plate_mods_pos + 2); return &m_plate_menu; } @@ -2261,6 +2321,7 @@ wxMenu* MenuFactory::assemble_object_menu() // Set Visible append_menu_item_set_visible(menu); // Delete + menu->AppendSeparator(); append_menu_item_delete(menu); //// Object Repair //append_menu_item_fix_through_cgal(menu); @@ -2280,6 +2341,7 @@ wxMenu* MenuFactory::assemble_part_menu() wxMenu* menu = new MenuWithSeparators(); append_menu_item_set_visible(menu); + menu->AppendSeparator(); append_menu_item_delete(menu); //append_menu_item_simplify(menu); menu->AppendSeparator(); @@ -2447,7 +2509,7 @@ void MenuFactory::append_menu_item_per_object_process(wxMenu* menu) m_parent); } -void MenuFactory::append_menu_item_per_object_settings(wxMenu* menu) +void MenuFactory::append_menu_item_per_object_settings(wxMenu* menu, size_t pos) { const std::vector names = { _L("Edit in Parameter Table"), _L("Edit print parameters for a single object") }; // Delete old menu item @@ -2464,10 +2526,10 @@ void MenuFactory::append_menu_item_per_object_settings(wxMenu* menu) []() { Selection& selection = plater()->canvas3D()->get_selection(); return selection.is_single_full_object() || selection.is_single_full_instance() || selection.is_single_volume(); - }, m_parent); + }, m_parent, pos); } -void MenuFactory::append_menu_item_change_filament(wxMenu* menu) +void MenuFactory::append_menu_item_change_filament(wxMenu* menu, size_t pos) { const std::vector names = { _L("Change Filament"), _L("Set Filament for selected items") }; // Delete old menu item @@ -2548,7 +2610,10 @@ void MenuFactory::append_menu_item_change_filament(wxMenu* menu) [i](wxCommandEvent&) { obj_list()->set_extruder_for_selected_items(i); }, i == 0 ? wxNullBitmap : *icons[i - 1], menu, [is_active_extruder]() { return !is_active_extruder; }, m_parent); } - menu->Append(wxID_ANY, name, extruder_selection_menu, _L("Change Filament")); + if (pos == wxNOT_FOUND) + menu->Append(wxID_ANY, name, extruder_selection_menu); + else + menu->Insert(pos, wxID_ANY, name, extruder_selection_menu, _L("Change Filament")); } void MenuFactory::append_menu_item_set_printable(wxMenu* menu) @@ -2604,7 +2669,7 @@ void MenuFactory::append_menu_item_set_auto_drop(wxMenu* menu) menu_item_set_auto_drop->GetId()); } -void MenuFactory::append_menu_item_locked(wxMenu* menu) +void MenuFactory::append_menu_item_locked(wxMenu* menu, size_t pos) { const std::vector names = { _L("Unlock"), _L("Lock") }; // Delete old menu item @@ -2622,7 +2687,7 @@ void MenuFactory::append_menu_item_locked(wxMenu* menu) [plate](wxCommandEvent&) { bool lock = plate->is_locked(); plate->lock(!lock); - }, "", nullptr, []() { return true; }, m_parent); + }, "", nullptr, []() { return true; }, m_parent, pos); m_parent->Bind(wxEVT_UPDATE_UI, [](wxUpdateUIEvent& evt) { PartPlate* plate = plater()->get_partplate_list().get_selected_plate(); @@ -2633,7 +2698,7 @@ void MenuFactory::append_menu_item_locked(wxMenu* menu) }, item->GetId()); } -void MenuFactory::append_menu_item_plate_name(wxMenu *menu) +void MenuFactory::append_menu_item_plate_name(wxMenu *menu, size_t pos) { wxString name= _L("Edit Plate Name"); // Delete old menu item @@ -2657,7 +2722,7 @@ void MenuFactory::append_menu_item_plate_name(wxMenu *menu) } plater()->get_current_canvas3D()->post_event(SimpleEvent(EVT_GLCANVAS_PLATE_NAME_CHANGE)); }, - "", nullptr, []() { return true; }, m_parent); + "", nullptr, []() { return true; }, m_parent, pos); m_parent->Bind( wxEVT_UPDATE_UI, @@ -2669,6 +2734,32 @@ void MenuFactory::append_menu_item_plate_name(wxMenu *menu) item->GetId()); } +void MenuFactory::append_menu_item_plate_delete(wxMenu *menu, size_t pos) +{ + wxString name= _L("Delete Plate"); + // Delete old menu item and the separator placed right before it + const int item_id = menu->FindItem(name); + if (item_id != wxNOT_FOUND) { + const size_t item_pos = FindPositionById(menu, item_id); + if (item_pos != size_t(wxNOT_FOUND) && item_pos > 0 && menu->FindItemByPosition(item_pos - 1)->IsSeparator()) + menu->Destroy(menu->FindItemByPosition(item_pos - 1)); + menu->Destroy(item_id); + } + + menu->InsertSeparator(pos); + + PartPlate *plate = plater()->get_partplate_list().get_selected_plate(); + assert(plate); + + // delete current plate + auto item = append_menu_item(menu, wxID_ANY, name, _L("Remove the selected plate"), + [](wxCommandEvent&) { plater()->delete_plate(); }, "", nullptr, + []() { return plater()->can_delete_plate(); }, m_parent, pos + 1); + + // no extra wxEVT_UPDATE_UI handler here: a second handler on the same id runs before the one bound + // by append_menu_item() and, without evt.Skip(), swallows the enable/disable condition +} + void MenuFactory::update_object_menu() { append_menu_items_add_volume(&m_object_menu); diff --git a/src/slic3r/GUI/GUI_Factories.hpp b/src/slic3r/GUI/GUI_Factories.hpp index 65526c5c04..d2ab760205 100644 --- a/src/slic3r/GUI/GUI_Factories.hpp +++ b/src/slic3r/GUI/GUI_Factories.hpp @@ -109,14 +109,25 @@ private: wxWindow* m_parent {nullptr}; MenuWithSeparators m_object_menu; + wxMenu* m_object_transform_menu; + size_t m_object_geometry_pos; + int m_object_props_marker; MenuWithSeparators m_part_menu; + wxMenu* m_part_transform_menu; + int m_part_props_marker; + int m_part_project_marker; MenuWithSeparators m_text_part_menu; + int m_text_props_marker; + int m_text_project_marker; MenuWithSeparators m_svg_part_menu; + int m_svg_props_marker; + int m_svg_project_marker; MenuWithSeparators m_sla_object_menu; MenuWithSeparators m_default_menu; MenuWithSeparators m_instance_menu; //BBS: add part plate related logic MenuWithSeparators m_plate_menu; + size_t m_plate_mods_pos; MenuWithSeparators m_assemble_object_menu; MenuWithSeparators m_assemble_part_menu; @@ -128,11 +139,12 @@ private: std::array items_decrease; std::array items_set_number_of_copies; + size_t FindPositionById(wxMenu* menu, int id); + void create_default_menu(); void create_common_object_menu(wxMenu *menu); void create_object_menu(); void create_sla_object_menu(); - void create_part_menu(); void create_text_part_menu(); void create_svg_part_menu(); //BBS: add part plate related logic @@ -170,16 +182,14 @@ private: void append_menu_item_delete(wxMenu* menu); void append_menu_item_scale_selection_to_fit_print_volume(wxMenu* menu); void append_menu_items_convert_unit(wxMenu* menu); // Add "Conver/Revert..." menu items (from/to inches/meters) after "Reload From Disk" - void append_menu_items_flush_options(wxMenu* menu); + void append_menu_items_flush_options(wxMenu* menu, size_t pos = -1); void append_menu_item_merge_to_multipart_object(wxMenu *menu); void append_menu_item_merge_to_single_object(wxMenu* menu); - void append_menu_item_merge_parts_to_single_part(wxMenu *menu); - void append_menu_items_mirror(wxMenu *menu); void append_menu_item_align_distribute(wxMenu *menu); void append_menu_item_precise_seam_submenu(wxMenu* menu); - void append_menu_item_invalidate_cut_info(wxMenu *menu); - void append_menu_item_edit_text(wxMenu *menu); - void append_menu_item_edit_svg(wxMenu *menu); + void append_menu_item_invalidate_cut_info(wxMenu *menu, size_t pos = -1); + void append_menu_item_edit_text(wxMenu *menu, size_t pos = -1); + void append_menu_item_edit_svg(wxMenu *menu, size_t pos = -1); void append_menu_items_instance_manipulation(wxMenu *menu); //void update_menu_items_instance_manipulation(MenuType type); @@ -190,13 +200,17 @@ private: void append_menu_item_center(wxMenu* menu); void append_menu_item_drop(wxMenu* menu); void append_menu_item_per_object_process(wxMenu* menu); - void append_menu_item_per_object_settings(wxMenu* menu); - void append_menu_item_change_filament(wxMenu* menu); + void append_menu_item_per_object_settings(wxMenu* menu, size_t pos = -1); + void append_menu_item_change_filament(wxMenu* menu, size_t pos = -1); void append_menu_item_set_printable(wxMenu* menu); void append_menu_item_set_auto_drop(wxMenu* menu); - void append_menu_item_locked(wxMenu* menu); + void append_menu_item_locked(wxMenu* menu, size_t pos = -1); void append_menu_item_fill_bed(wxMenu *menu); - void append_menu_item_plate_name(wxMenu *menu); + void append_menu_item_plate_name(wxMenu *menu, size_t pos = -1); + void append_menu_item_plate_delete(wxMenu *menu, size_t pos = -1); + wxMenu* append_menu_item_transform(wxMenu* menu, bool multi_selection, bool show_mirror, bool is_scalable); + wxMenu* append_menu_item_modify( wxMenu* menu, bool multi_selection, bool splittable, bool is_mesh, bool mesh_boolean); + wxMenu* append_menu_item_more( wxMenu* menu, bool multi_selection, bool disk_op, bool export_op); }; }} diff --git a/src/slic3r/GUI/Gizmos/GLGizmoEmboss.cpp b/src/slic3r/GUI/Gizmos/GLGizmoEmboss.cpp index ae39eade25..a3f680da59 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoEmboss.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoEmboss.cpp @@ -517,6 +517,46 @@ bool check(ModelVolumeType volume_type) { volume_type == ModelVolumeType::NEGATIVE_VOLUME || volume_type == ModelVolumeType::PARAMETER_MODIFIER; } + +// Text of a new text volume +const char *const default_text = L("Embossed text"); + +// Whether the loaded font of the style manager has a glyph for every character of the text +bool can_write(StyleManager &style_manager, const std::string &text) +{ + bool exist_unknown = false; + create_range_text(text, *style_manager.get_font_file_with_cache().font_file, + style_manager.get_font_prop().collection_number.value_or(0), &exist_unknown); + return !exist_unknown; +} + +bool can_write(const EmbossStyle &style, const std::string &text) +{ + StyleManager style_manager(nullptr, {}); + return style_manager.load_style(StyleManager::Style{style}) && can_write(style_manager, text); +} + +// The default styles use system fonts, which can lack the script of the translated default text, e.g. with +// a Chinese UI on an English system. Then put first a style with a bundled font that can write it. Only +// registered faces are used: a text volume can be edited again only when its font is found by face name. +void add_style_for_default_text(EmbossStyles &styles) +{ + const std::string text = _u8L(default_text); + // the untranslated text is Latin, which the system fonts have + if (text == default_text || can_write(styles.front(), text)) + return; + + for (const char *face_name : {"HarmonyOS Sans SC", "NanumGothic", "Sarabun"}) { + wxFont wx_font = *wxNORMAL_FONT; + if (!wx_font.SetFaceName(face_name)) + continue; + EmbossStyle style = WxFontUtils::create_emboss_style(wx_font, _u8L("Default font")); + if (can_write(style, text)) { + styles.insert(styles.begin(), std::move(style)); + return; + } + } +} } bool GLGizmoEmboss::init_create(ModelVolumeType volume_type) @@ -541,8 +581,10 @@ bool GLGizmoEmboss::init_create(ModelVolumeType volume_type) m_style_manager.discard_style_changes(); - // set default text - m_text = _u8L("Embossed text"); + // set default text, in English when the active font cannot write its translation + m_text = _u8L(default_text); + if (m_style_manager.is_active_font() && !can_write(m_style_manager, m_text)) + m_text = default_text; return true; } @@ -1070,29 +1112,28 @@ EmbossStyles GLGizmoEmboss::create_default_styles() }),styles.end() ); - // exist some valid style? - if (!styles.empty()) - return styles; - // No valid style in defult list // at least one style must contain loadable font - wxFont wx_font; - for (const wxString &face : facenames) { - wx_font = wxFont(face); - if (WxFontUtils::create_font_file(wx_font) != nullptr) - break; - wx_font = wxFont(); // NotOk - } + if (styles.empty()) { + wxFont wx_font; + for (const wxString &face : facenames) { + wx_font = wxFont(face); + if (WxFontUtils::create_font_file(wx_font) != nullptr) + break; + wx_font = wxFont(); // NotOk + } - if (wx_font.IsOk()) { - // use first alphabetic sorted installed font - styles.push_back(WxFontUtils::create_emboss_style(wx_font, _u8L("First font"))); - } else { - // On current OS is not installed any correct TTF font - // use font packed with OrcaSlicer - std::string font_path = Slic3r::resources_dir() + "/fonts/HarmonyOS_Sans_SC_Regular.ttf"; - styles.push_back(EmbossStyle{_u8L("Default font"), font_path, EmbossStyle::Type::file_path}); + if (wx_font.IsOk()) { + // use first alphabetic sorted installed font + styles.push_back(WxFontUtils::create_emboss_style(wx_font, _u8L("First font"))); + } else { + // On current OS is not installed any correct TTF font + // use font packed with OrcaSlicer + std::string font_path = Slic3r::resources_dir() + "/fonts/HarmonyOS_Sans_SC_Regular.ttf"; + styles.push_back(EmbossStyle{_u8L("Default font"), font_path, EmbossStyle::Type::file_path}); + } } + add_style_for_default_text(styles); return styles; } diff --git a/src/slic3r/GUI/ImGuiWrapper.cpp b/src/slic3r/GUI/ImGuiWrapper.cpp index b37b99f783..432bd80cae 100644 --- a/src/slic3r/GUI/ImGuiWrapper.cpp +++ b/src/slic3r/GUI/ImGuiWrapper.cpp @@ -49,6 +49,10 @@ #endif #include +#ifdef __APPLE__ +#include "MacIME.hpp" +#endif + #include "libslic3r/libslic3r.h" #include #include "libslic3r/Utils.hpp" @@ -612,6 +616,11 @@ void ImGuiWrapper::new_frame() ImDrawData* ImGuiWrapper::end_frame() { +#ifdef __APPLE__ + // io.ImeWindowHandle is the focused canvas' view (GLCanvas3D::on_set_focus()). + if (void* view = ImGui::GetIO().ImeWindowHandle) + mac_ime_set_active(view, ImGui::GetIO().WantTextInput); +#endif ImGui::Render(); m_new_frame_open = false; return ImGui::GetDrawData(); @@ -3222,6 +3231,14 @@ void ImGuiWrapper::init_input() // Don't let imgui special-case Mac, wxWidgets already do that io.ConfigMacOSXBehaviors = false; +#ifdef __APPLE__ + // Places the input method's candidate window at the text cursor. + io.ImeSetInputScreenPosFn = [](int x, int y) { + if (void* view = ImGui::GetIO().ImeWindowHandle) + mac_ime_set_caret(view, x, y, int(ImGui::GetFontSize())); + }; +#endif + // Setup clipboard interaction callbacks io.SetClipboardTextFn = clipboard_set; io.GetClipboardTextFn = clipboard_get; diff --git a/src/slic3r/GUI/LibVGCode/LibVGCodeWrapper.cpp b/src/slic3r/GUI/LibVGCode/LibVGCodeWrapper.cpp index 8c6e475ad7..f91fc0ed23 100644 --- a/src/slic3r/GUI/LibVGCode/LibVGCodeWrapper.cpp +++ b/src/slic3r/GUI/LibVGCode/LibVGCodeWrapper.cpp @@ -17,6 +17,7 @@ #include "libslic3r/libslic3r.h" #include "LibVGCodeWrapper.hpp" +#include "slic3r/GUI/3DScene.hpp" #include #include "libslic3r/Print.hpp" @@ -73,10 +74,28 @@ Color convert(const Slic3r::ColorRGBA& c) return { safe_val(c.r()), safe_val(c.g()), safe_val(c.b()) }; } -Color convert(const std::string& color_str) +Slic3r::ColorRGBA convert(const ColorWithAlpha& c) { - Slic3r::ColorRGBA color_rgba; - return decode_color(color_str, color_rgba) ? convert(color_rgba) : DUMMY_COLOR; + static const float inv_255 = 1.0f / 255.0f; + return { c[0] * inv_255, c[1] * inv_255, c[2] * inv_255, c[3] * inv_255 }; +} + +PaletteWithAlpha convert_filament_colors(const std::vector& colors_str) +{ + PaletteWithAlpha ret; + ret.reserve(colors_str.size()); + for (const std::string& color_str : colors_str) { + Slic3r::ColorRGBA color_rgba; + if (!decode_color(color_str, color_rgba)) { + ret.push_back({ DUMMY_COLOR[0], DUMMY_COLOR[1], DUMMY_COLOR[2], 255 }); + continue; + } + // as the 3D view draws it: a clear color kept at the least opacity, black lifted + color_rgba = adjust_color_for_rendering(color_rgba); + const Color color = convert(color_rgba); + ret.push_back({ color[0], color[1], color[2], static_cast(std::lround(255.0f * color_rgba.a())) }); + } + return ret; } Slic3r::ExtrusionRole convert(EGCodeExtrusionRole role) @@ -233,18 +252,8 @@ GCodeInputData convert(const Slic3r::GCodeProcessorResult& result, const std::ve return convert(v); }; - // collect tool colors - ret.tools_colors.reserve(str_tool_colors.size()); - for (const std::string& color : str_tool_colors) { - ret.tools_colors.emplace_back(convert(color)); - } - - // collect color print colors - const std::vector& str_colors = str_color_print_colors.empty() ? str_tool_colors : str_color_print_colors; - ret.color_print_colors.reserve(str_colors.size()); - for (const std::string& color : str_colors) { - ret.color_print_colors.emplace_back(convert(color)); - } + ret.tools_colors = convert_filament_colors(str_tool_colors); + ret.color_print_colors = convert_filament_colors(str_color_print_colors.empty() ? str_tool_colors : str_color_print_colors); const std::vector& moves = result.moves; // One vertex per move after the first, plus a phantom in front of every path start. Reserving @@ -874,18 +883,8 @@ GCodeInputData convert(const Slic3r::Print& print, const std::vector& str_colors = str_color_print_colors.empty() ? str_tool_colors : str_color_print_colors; - ret.color_print_colors.reserve(str_colors.size()); - for (const std::string& color : str_colors) { - ret.color_print_colors.emplace_back(convert(color)); - } + ret.tools_colors = convert_filament_colors(str_tool_colors); + ret.color_print_colors = convert_filament_colors(str_color_print_colors.empty() ? str_tool_colors : str_color_print_colors); return ret; } diff --git a/src/slic3r/GUI/LibVGCode/LibVGCodeWrapper.hpp b/src/slic3r/GUI/LibVGCode/LibVGCodeWrapper.hpp index a780a5f033..b354abd81e 100644 --- a/src/slic3r/GUI/LibVGCode/LibVGCodeWrapper.hpp +++ b/src/slic3r/GUI/LibVGCode/LibVGCodeWrapper.hpp @@ -47,8 +47,11 @@ extern Slic3r::ColorRGBA convert(const Color& c); // mapping from Slic3r::ColorRGBA to libvgcode::Color extern Color convert(const Slic3r::ColorRGBA& c); -// mapping from encoded color to libvgcode::Color -extern Color convert(const std::string& color_str); +// ORCA: mapping from libvgcode::ColorWithAlpha to Slic3r::ColorRGBA +extern Slic3r::ColorRGBA convert(const ColorWithAlpha& c); + +// ORCA: mapping from encoded filament colors to libvgcode::PaletteWithAlpha, keeping their opacity +extern PaletteWithAlpha convert_filament_colors(const std::vector& colors_str); // mapping from libvgcode::EGCodeExtrusionRole to Slic3r::ExtrusionRole extern Slic3r::ExtrusionRole convert(EGCodeExtrusionRole role); diff --git a/src/slic3r/GUI/MacIME.hpp b/src/slic3r/GUI/MacIME.hpp new file mode 100644 index 0000000000..1b6f3fb9e6 --- /dev/null +++ b/src/slic3r/GUI/MacIME.hpp @@ -0,0 +1,26 @@ +#pragma once + +// Input methods (Chinese, Japanese, Korean) for ImGui text fields drawn on a GL canvas on macOS. +// +// wxWidgets gives a wxGLCanvas a view that is no NSTextInputClient, so the view has no input context: +// keys skip the input method and a CJK input source types plain letters. These functions turn the +// canvas view into a text input client while an ImGui text field wants text input. Committed text still +// arrives as wxEVT_CHAR. + +namespace Slic3r::GUI { + +// Call every frame with io.WantTextInput. While active, the view's input context stays the current one, +// which also lets the input source's own language toggle (Caps Lock, 中/英) reach the field. Deactivating +// drops an unfinished composition. +void mac_ime_set_active(void* ns_view, bool active); + +// Anchors the candidate window at the text cursor. x, y (top of the cursor line) and height are canvas +// backing pixels, the coordinates ImGui works in. +void mac_ime_set_caret(void* ns_view, int x, int y, int height); + +// True when the key-down being dispatched belongs to the input method: it changed or ended a composition, +// or arrived while one was open. wxWidgets still sends a key-down for such a key, which must not also +// edit the text field. +bool mac_ime_owns_key(void* ns_view); + +} // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/MacIME.mm b/src/slic3r/GUI/MacIME.mm new file mode 100644 index 0000000000..5e9afdc489 --- /dev/null +++ b/src/slic3r/GUI/MacIME.mm @@ -0,0 +1,194 @@ +#import "MacIME.hpp" + +#import +#import + +// The canvas view's class (wxNSCustomOpenGLView) gets the NSTextInputClient methods added at runtime. +// Declaring the protocol at runtime does not give a view an input context, so the view also overrides +// -inputContext and owns its NSTextInputContext. The client models only the composition: it never sees +// the field's text, so the composition is the whole document as far as the input method is concerned. +// Per-view state lives in associated objects. Compiled without ARC. + +namespace { + +char key_installed; // on the class: methods added +char key_context; // NSTextInputContext* +char key_active; // NSNumber: an ImGui text field wants text input +char key_marked; // NSString*: the composition, nil when there is none +char key_selected; // NSValue (NSRange): the selection inside the composition +char key_caret; // NSValue (NSRect): the text cursor line in view coordinates +char key_ime_event; // NSEvent*: the last key-down that changed a composition + +id get(id object, const void* key) { return objc_getAssociatedObject(object, key); } + +void set(id object, const void* key, id value) { objc_setAssociatedObject(object, key, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } + +bool is_active(id view) { return [get(view, &key_active) boolValue]; } + +NSString* marked_text(id view) { return get(view, &key_marked); } + +void set_marked_text(id view, NSString* text, NSRange selected) +{ + const bool composing = text.length > 0; + set(view, &key_marked, composing ? text : nil); + set(view, &key_selected, composing ? [NSValue valueWithRange:selected] : nil); +} + +// The key-down being dispatched went to the input method. +void claim_current_key(id view) +{ + NSEvent* event = [NSApp currentEvent]; + if (event.type == NSEventTypeKeyDown) + set(view, &key_ime_event, event); +} + +NSString* plain_string(id text) { return [text isKindOfClass:[NSAttributedString class]] ? [text string] : text; } + +// wx's own insertText: sends the text as wxEVT_CHAR, preceded by a key-down when it is the character of +// the key being pressed. +void send_text(id view, NSString* text) +{ + if (text.length > 0) + [view performSelector:@selector(insertText:) withObject:text]; +} + +NSTextInputContext* ime_input_context(id self, SEL) { return is_active(self) ? get(self, &key_context) : nil; } + +void ime_insert_text(id self, SEL, id text, NSRange) +{ + if (marked_text(self) != nil) { + claim_current_key(self); + set_marked_text(self, nil, {}); + } + send_text(self, plain_string(text)); +} + +void ime_set_marked_text(id self, SEL, id text, NSRange selected, NSRange) +{ + claim_current_key(self); + set_marked_text(self, plain_string(text), selected); +} + +// Accepts the composition as typed. +void ime_unmark_text(id self, SEL) +{ + NSString* text = [[marked_text(self) retain] autorelease]; + if (text == nil) + return; + claim_current_key(self); + set_marked_text(self, nil, {}); + send_text(self, text); +} + +BOOL ime_has_marked_text(id self, SEL) { return marked_text(self) != nil; } + +NSRange ime_marked_range(id self, SEL) +{ + NSString* text = marked_text(self); + return text != nil ? NSMakeRange(0, text.length) : NSMakeRange(NSNotFound, 0); +} + +NSRange ime_selected_range(id self, SEL) +{ + NSValue* selected = get(self, &key_selected); + return selected != nil ? selected.rangeValue : NSMakeRange(NSNotFound, 0); +} + +NSRect ime_first_rect(id self, SEL, NSRange range, NSRangePointer actual_range) +{ + if (actual_range != nullptr) + *actual_range = range; + NSView* view = self; + NSValue* caret = get(self, &key_caret); + // Without a reported cursor, the top-left corner of the canvas. + const NSRect rect = caret != nil ? caret.rectValue : NSMakeRect(0, 0, 1, 16); + return view.window != nil ? [view.window convertRectToScreen:[view convertRect:rect toView:nil]] : NSZeroRect; +} + +NSAttributedString* ime_attributed_substring(id self, SEL, NSRange range, NSRangePointer actual_range) +{ + NSString* text = marked_text(self); + const NSRange clamped = text != nil ? NSIntersectionRange(range, NSMakeRange(0, text.length)) : NSMakeRange(0, 0); + if (clamped.length == 0) + return nil; + if (actual_range != nullptr) + *actual_range = clamped; + return [[[NSAttributedString alloc] initWithString:[text substringWithRange:clamped]] autorelease]; +} + +NSArray* ime_valid_attributes(id, SEL) { return @[]; } + +NSUInteger ime_character_index(id, SEL, NSPoint) { return NSNotFound; } + +void install(Class cls) +{ + if (get(cls, &key_installed) != nil) + return; + set(cls, &key_installed, @YES); + + Protocol* protocol = @protocol(NSTextInputClient); + class_addProtocol(cls, protocol); + const struct { SEL sel; IMP imp; } methods[] = { + { @selector(insertText:replacementRange:), (IMP) ime_insert_text }, + { @selector(setMarkedText:selectedRange:replacementRange:), (IMP) ime_set_marked_text }, + { @selector(unmarkText), (IMP) ime_unmark_text }, + { @selector(hasMarkedText), (IMP) ime_has_marked_text }, + { @selector(markedRange), (IMP) ime_marked_range }, + { @selector(selectedRange), (IMP) ime_selected_range }, + { @selector(firstRectForCharacterRange:actualRange:), (IMP) ime_first_rect }, + { @selector(attributedSubstringForProposedRange:actualRange:), (IMP) ime_attributed_substring }, + { @selector(validAttributesForMarkedText), (IMP) ime_valid_attributes }, + { @selector(characterIndexForPoint:), (IMP) ime_character_index }, + }; + for (const auto& method : methods) + class_addMethod(cls, method.sel, method.imp, protocol_getMethodDescription(protocol, method.sel, YES, YES).types); + // The view's own doCommandBySelector: (from wx) stays: keys the input method passes on reach wx unchanged. + class_addMethod(cls, @selector(inputContext), (IMP) ime_input_context, + method_getTypeEncoding(class_getInstanceMethod([NSView class], @selector(inputContext)))); +} + +} // namespace + +namespace Slic3r::GUI { + +void mac_ime_set_active(void* ns_view, bool active) +{ + NSView* view = (NSView*) ns_view; + if (view == nil || active == is_active(view)) + return; + NSTextInputContext* context = get(view, &key_context); + if (context == nil) { + install([view class]); + context = [[[NSTextInputContext alloc] initWithClient:(id) view] autorelease]; + set(view, &key_context, context); + } + // An open composition belongs to the field that lost input or to an earlier session; dropping it + // first keeps the input method's callbacks from committing it. + set_marked_text(view, nil, {}); + set(view, &key_active, @(active)); + if (active) + [context activate]; + else { + [context discardMarkedText]; + [context deactivate]; + } +} + +void mac_ime_set_caret(void* ns_view, int x, int y, int height) +{ + NSView* view = (NSView*) ns_view; + if (view == nil) + return; + const CGFloat scale = view.window != nil ? view.window.backingScaleFactor : 1.0; + set(view, &key_caret, [NSValue valueWithRect:NSMakeRect(x / scale, y / scale, 1.0, height / scale)]); +} + +bool mac_ime_owns_key(void* ns_view) +{ + NSView* view = (NSView*) ns_view; + NSEvent* event = [NSApp currentEvent]; + return view != nil && is_active(view) && event.type == NSEventTypeKeyDown && + (marked_text(view) != nil || get(view, &key_ime_event) == event); +} + +} // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/Mouse3DController.cpp b/src/slic3r/GUI/Mouse3DController.cpp index b517e36841..3e1943ecb3 100644 --- a/src/slic3r/GUI/Mouse3DController.cpp +++ b/src/slic3r/GUI/Mouse3DController.cpp @@ -21,6 +21,9 @@ #include #include #include +#ifdef _WIN32 +#include +#endif #include #include #include @@ -164,122 +167,96 @@ static std::string format_device_string(int vid, int pid) return ret; } +namespace { +// One HID top-level collection: what both device lists below report. +struct HidCollection +{ + unsigned short vendor_id{ 0 }; + unsigned short product_id{ 0 }; + unsigned short usage_page{ 0 }; + unsigned short usage{ 0 }; +}; +} // namespace + +// Windows keeps the ids and usage of every HID collection for Raw Input, so nothing is opened. +// hid_enumerate() opens and queries every HID device instead (~200 ms on a typical PC). +static bool list_hid_collections_raw_input(std::vector& out) +{ + std::vector devices; + bool listed = false; + for (int attempt = 0; attempt < 3 && ! listed; ++attempt) { + UINT count = 0; + if (::GetRawInputDeviceList(nullptr, &count, sizeof(RAWINPUTDEVICELIST)) != 0) + return false; + devices.resize(count); + const UINT got = count == 0 ? 0 : ::GetRawInputDeviceList(devices.data(), &count, sizeof(RAWINPUTDEVICELIST)); + if (got != UINT(-1)) { + devices.resize(got); + listed = true; + } else if (::GetLastError() != ERROR_INSUFFICIENT_BUFFER) + return false; + // else a device was plugged in meanwhile, try again + } + if (! listed) + return false; + + for (const RAWINPUTDEVICELIST& device : devices) { + if (device.dwType != RIM_TYPEHID) + continue; + RID_DEVICE_INFO info{}; + info.cbSize = sizeof(info); + UINT size = sizeof(info); + if (::GetRawInputDeviceInfoW(device.hDevice, RIDI_DEVICEINFO, &info, &size) == UINT(-1)) + continue; + out.push_back({ static_cast(info.hid.dwVendorId), static_cast(info.hid.dwProductId), + info.hid.usUsagePage, info.hid.usUsage }); + } + return true; +} + static std::string detect_attached_device() { - std::string ret; - // Initialize the hidapi library - int res = hid_init(); - if (res != 0) - BOOST_LOG_TRIVIAL(error) << "Unable to initialize hidapi library"; - else if (wxGetApp().app_config->get("skip_3dmouse_detect") == "true") { - BOOST_LOG_TRIVIAL(info) << "do not detect 3d Mouse"; + std::vector collections; + if (! list_hid_collections_raw_input(collections)) { + // A device plugged in later still connects through device_attached(). + const DWORD error = ::GetLastError(); + BOOST_LOG_TRIVIAL(warning) << "Raw Input device list unavailable, error " << error; + return {}; + } + if (collections.empty()) { + BOOST_LOG_TRIVIAL(trace) << "detect_attached_device() - no HID device enumerated."; + return {}; } - else { - // Enumerates devices - hid_device_info* devices = hid_enumerate(0, 0); - if (devices == nullptr) - BOOST_LOG_TRIVIAL(trace) << "detect_attached_device() - no HID device enumerated."; - else { - // Searches for 1st connected 3Dconnexion device - struct DeviceData - { - unsigned short usage_page{ 0 }; - unsigned short usage{ 0 }; - DeviceData(unsigned short usage_page, unsigned short usage) - : usage_page(usage_page), usage(usage) - {} + // https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf + // Usage page 1 - Generic Desktop Controls + // Usage page 1, usage 8 - Multi-axis Controller + const auto has_valid_usage = [](const HidCollection& c) { return c.usage_page == 1 && c.usage == 8; }; - // https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf - // Usage page 1 - Generic Desktop Controls - // Usage page 1, usage 8 - Multi-axis Controller - bool has_valid_usage() const { return usage_page == 1 && usage == 8; } - }; + // When using 3Dconnexion universal receiver, multiple devices are detected sharing the same vendor_id and product_id. + // To choose from them the right one we use: usage_page == 1 and usage == 8 + // When only a single device is detected, as for wired connections, vendor_id and product_id are enough - // When using 3Dconnexion universal receiver, multiple devices are detected sharing the same vendor_id and product_id. - // To choose from them the right one we use: usage_page == 1 and usage == 8 - // When only a single device is detected, as for wired connections, vendor_id and product_id are enough + // First we collect all the 3Dconnexion devices from the enumerated list. + typedef std::pair DeviceIds; + std::map> detected_devices; + for (const HidCollection& c : collections) { + if (std::find(_3DCONNEXION_VENDORS.begin(), _3DCONNEXION_VENDORS.end(), c.vendor_id) == _3DCONNEXION_VENDORS.end() || + std::find(_3DCONNEXION_DEVICES.begin(), _3DCONNEXION_DEVICES.end(), c.product_id) == _3DCONNEXION_DEVICES.end()) + continue; + detected_devices[DeviceIds(c.vendor_id, c.product_id)].push_back(c); + } - // First we count all the valid devices from the enumerated list, - - hid_device_info* current = devices; - typedef std::pair DeviceIds; - typedef std::vector DeviceDataList; - typedef std::map DetectedDevices; - DetectedDevices detected_devices; - while (current != nullptr) { - unsigned short vendor_id = 0; - unsigned short product_id = 0; - - for (size_t i = 0; i < _3DCONNEXION_VENDORS.size(); ++i) { - if (_3DCONNEXION_VENDORS[i] == current->vendor_id) { - vendor_id = current->vendor_id; - break; - } - } - - if (vendor_id != 0) { - for (size_t i = 0; i < _3DCONNEXION_DEVICES.size(); ++i) { - if (_3DCONNEXION_DEVICES[i] == current->product_id) { - product_id = current->product_id; - DeviceIds detected_device(vendor_id, product_id); - DetectedDevices::iterator it = detected_devices.find(detected_device); - if (it == detected_devices.end()) - it = detected_devices.insert(DetectedDevices::value_type(detected_device, DeviceDataList())).first; - - it->second.emplace_back(current->usage_page, current->usage); - } - } - } - - current = current->next; - } - - // Free enumerated devices - hid_free_enumeration(devices); - - unsigned short vendor_id = 0; - unsigned short product_id = 0; - if (!detected_devices.empty()) { - // Then we'll decide the choosing logic to apply in dependence of the device count and operating system - for (const DetectedDevices::value_type& device : detected_devices) { - if (device.second.size() == 1) { - if (device.second.front().has_valid_usage()) { - vendor_id = device.first.first; - product_id = device.first.second; - break; - } - } - else { - bool found = false; - for (const DeviceData& data : device.second) { - if (data.has_valid_usage()) { - vendor_id = device.first.first; - product_id = device.first.second; - found = true; - break; - } - } - - if (found) - break; - } - } - } - - if (vendor_id != 0 && product_id != 0) { - ret = format_device_string(static_cast(vendor_id), static_cast(product_id)); - BOOST_LOG_TRIVIAL(trace) << "Detected device: " << std::hex << vendor_id << std::dec << "::" << std::hex << product_id << std::dec << " " << ret; - } - else - BOOST_LOG_TRIVIAL(trace) << "No 3DConnexion device detected"; + // Then we pick the first device with a multi-axis controller collection. + for (const auto& [ids, device_collections] : detected_devices) { + if (std::any_of(device_collections.begin(), device_collections.end(), has_valid_usage)) { + std::string ret = format_device_string(static_cast(ids.first), static_cast(ids.second)); + BOOST_LOG_TRIVIAL(trace) << "Detected device: " << std::hex << ids.first << std::dec << "::" << std::hex << ids.second << std::dec << " " << ret; + return ret; } - - // Finalize the hidapi library - hid_exit(); } - - return ret; + BOOST_LOG_TRIVIAL(trace) << "No 3DConnexion device detected"; + return {}; } // Called by Win32 HID enumeration callback. @@ -827,7 +804,10 @@ bool Mouse3DController::handle_input(const DataPacketAxis& packet) void Mouse3DController::init() { #ifdef _WIN32 - m_device_str = detect_attached_device(); + if (wxGetApp().app_config->get("skip_3dmouse_detect") == "true") + BOOST_LOG_TRIVIAL(info) << "do not detect 3d Mouse"; + else + m_device_str = detect_attached_device(); if (!m_device_str.empty()) { m_connected = true; if (auto it_params = m_params_by_device.find(m_device_str); it_params != m_params_by_device.end()) diff --git a/src/slic3r/GUI/Preferences.cpp b/src/slic3r/GUI/Preferences.cpp index dc726ca6f6..567a9c218f 100644 --- a/src/slic3r/GUI/Preferences.cpp +++ b/src/slic3r/GUI/Preferences.cpp @@ -1097,6 +1097,16 @@ wxBoxSizer *PreferencesDialog::create_item_checkbox(wxString title, wxString too home->SendCloudProvidersInfo(); } } + // ORCA: apply the filament translucency change immediately to the currently loaded preview + else if (param == "preview_translucent_filaments") { + if (Plater* plater = wxGetApp().plater()) { + if (GLCanvas3D* canvas = plater->get_preview_canvas3D()) { + canvas->get_gcode_viewer().set_translucent_filaments(app_config->get_bool(param)); + canvas->set_as_dirty(); + canvas->request_extra_frame(); + } + } + } // ORCA: apply the preview dimming change immediately to the currently loaded preview else if (param == "preview_dim_previous_layers") { if (m_dim_previous_layers_brightness_input) @@ -2016,6 +2026,14 @@ void PreferencesDialog::create_items() SETTING_OPENGL_REALISTIC_SHADOWS, ShadowsLabels, ShadowsValues); g_sizer->Add(item_realistic_shadows); + auto item_realistic_gloss = create_item_checkbox( + _L("Glossy toolpaths"), + _L("Highlights the toolpaths in Preview as glossy plastic in realistic view.\n" + "Off, a translucent filament is matte and an opaque one keeps the highlight of the plain view."), + SETTING_OPENGL_REALISTIC_GLOSS + ); + g_sizer->Add(item_realistic_gloss); + //// GRAPHICS > Anti-aliasing g_sizer->Add(create_item_title(_L("Anti-aliasing")), 1, wxEXPAND); @@ -2155,6 +2173,13 @@ void PreferencesDialog::create_items() ); g_sizer->Add(item_dim_previous_layers_brightness); + auto item_translucent_filaments = create_item_checkbox( + _L("Translucent filaments"), + _L("Draw the toolpaths of filaments whose color is partly transparent as see-through, as the 3D view draws their objects. Turn it off to draw every filament opaque."), + "preview_translucent_filaments" + ); + g_sizer->Add(item_translucent_filaments); + g_sizer->AddSpacer(FromDIP(10)); sizer_page->Add(g_sizer, 0, wxEXPAND); diff --git a/src/slic3r/GUI/PrinterWebView.cpp b/src/slic3r/GUI/PrinterWebView.cpp index c27ddc62d4..dd597ad38d 100644 --- a/src/slic3r/GUI/PrinterWebView.cpp +++ b/src/slic3r/GUI/PrinterWebView.cpp @@ -307,9 +307,10 @@ void PrinterWebView::SendAPIKey() // RemoveAllUserScripts causes WebView to forget about our script message handler, // so re-add it here. m_browser->RemoveScriptMessageHandler("wx"); - if (m_browser->AddScriptMessageHandler("wx")) - WebView::MarkScriptMessageHandlerAdded(m_browser); - else + // Mark before adding: on WKWebView the add yields in RunScript() after registering "wx", + // and CreateWebView()'s deferred add, if it runs in that yield, would register it again. + WebView::MarkScriptMessageHandlerAdded(m_browser); + if (!m_browser->AddScriptMessageHandler("wx")) wxLogError("Could not add script message handler"); #ifdef __linux__ @@ -356,7 +357,8 @@ void PrinterWebView::OnError(wxWebViewEvent &evt) void PrinterWebView::OnLoaded(wxWebViewEvent& evt) { - if (evt.GetURL().IsEmpty()) + // The web view's initial empty document (about:blank on WebKit) is not the requested page. + if (evt.GetURL().IsEmpty() || evt.GetURL() == "about:blank") return; //ORCA: url loaded successfully, safe to clear m_url_deferred.clear(); diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index a29db94827..50cdc5abf3 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -3131,6 +3131,7 @@ void TabPrint::build() optgroup->append_single_option_line("top_shell_layers", "strength_settings_top_bottom_shells#shell-layers"); optgroup->append_single_option_line("top_shell_thickness", "strength_settings_top_bottom_shells#shell-thickness"); + optgroup->append_single_option_line("top_color_penetration_layers", "strength_settings_top_bottom_shells#paint-penetration-layers"); optgroup->append_single_option_line("top_surface_density", "strength_settings_top_bottom_shells#surface-density"); optgroup->append_single_option_line("top_surface_pattern", "strength_settings_top_bottom_shells#surface-pattern"); optgroup->append_single_option_line("top_surface_fill_order", "strength_settings_top_bottom_shells#fill-order"); @@ -3140,6 +3141,7 @@ void TabPrint::build() optgroup->append_single_option_line("top_surface_expansion_direction", "strength_settings_top_bottom_shells#surface-expansion-direction"); optgroup->append_single_option_line("bottom_shell_layers", "strength_settings_top_bottom_shells#shell-layers"); optgroup->append_single_option_line("bottom_shell_thickness", "strength_settings_top_bottom_shells#shell-thickness"); + optgroup->append_single_option_line("bottom_color_penetration_layers", "strength_settings_top_bottom_shells#paint-penetration-layers"); optgroup->append_single_option_line("bottom_surface_density", "strength_settings_top_bottom_shells#surface-density"); optgroup->append_single_option_line("bottom_surface_pattern", "strength_settings_top_bottom_shells#surface-pattern"); optgroup->append_single_option_line("bottom_surface_fill_order", "strength_settings_top_bottom_shells#fill-order"); diff --git a/src/slic3r/GUI/Widgets/PopupWindow.cpp b/src/slic3r/GUI/Widgets/PopupWindow.cpp index 371ece392b..a8273b5ce6 100644 --- a/src/slic3r/GUI/Widgets/PopupWindow.cpp +++ b/src/slic3r/GUI/Widgets/PopupWindow.cpp @@ -2,6 +2,11 @@ #include #include +#ifdef __WXGTK__ +#include +#include "slic3r/GUI/LinuxDisplayBackend.hpp" +#endif + static wxWindow *GetTopParent(wxWindow *pWindow) { wxWindow *pWin = pWindow; @@ -85,10 +90,56 @@ void PopupWindow::OnMouseEvent2(wxMouseEvent &evt) #endif #ifdef __WXGTK__ +template static void for_each_tooltip_window(Fn fn) +{ + GList *toplevels = gtk_window_list_toplevels(); + for (GList *l = toplevels; l; l = l->next) + if (gtk_window_get_type_hint(GTK_WINDOW(l->data)) == GDK_WINDOW_TYPE_HINT_TOOLTIP) + fn(GTK_WINDOW(l->data)); + g_list_free(toplevels); +} + +bool PopupWindow::Show(bool show) +{ + // On Wayland a shown GTK tooltip is itself an xdg_popup, and GDK maps a new popup only as a child of + // the topmost one ("Tried to map a popup with a non-top most parent"). GTK hides the tooltip on a + // click or key press only after the widgets have handled it, so a popup opened from that click would + // never appear. GtkMenu hides the tooltip first for the same reason, through a private call; hiding the + // tooltip window is the public equivalent, and GtkTooltip then treats it as closed and shows it again + // on a later hover. + if (show && !IsShown() && Slic3r::GUI::is_running_on_wayland()) + for_each_tooltip_window([](GtkWindow *win) { gtk_widget_hide(GTK_WIDGET(win)); }); + return wxPopupTransientWindow::Show(show); +} + +// Whether a tooltip of a widget in this popup, or in a popup opened from it, is on screen. Such a tooltip is +// transient for the window of the popup holding the widget, and that popup is transient for the one it opened from. +static bool own_tooltip_mapped(GtkWindow *popup) +{ + bool mapped = false; + for_each_tooltip_window([popup, &mapped](GtkWindow *win) { + // The compositor can dismiss a tooltip without GTK hiding the widget, so ask GDK whether it is mapped. + GdkWindow *gdk_win = gtk_widget_get_window(GTK_WIDGET(win)); + if (!gdk_win || !gdk_window_is_visible(gdk_win)) + return; + for (GtkWindow *w = gtk_window_get_transient_for(win); w && !mapped; w = gtk_window_get_transient_for(w)) + mapped = w == popup; + }); + return mapped; +} + +// On Wayland, a GTK tooltip of a widget in a shown popup takes the keyboard focus from the toplevel, which then +// reports a deactivation while the user is still on the popup: GTK makes the tooltip transient for the popup's +// window, which holds the seat grab, so GDK maps the tooltip as an xdg_popup with a grab of its own, and the +// compositor gives the keyboard to the topmost grabbing popup. The toplevel is activated again when the tooltip +// hides, so that deactivation is ignored. wxGTK reports no second deactivation until the next activation, so if +// the app loses the focus while such a tooltip holds it (another app's window taking the focus, a gesture), the +// popup stays open until the user returns. X11 tooltips never take the focus. void PopupWindow::topWindowActiavate(wxActivateEvent &event) { event.Skip(); - if (!event.GetActive() && IsShown() && ShouldDismissOnTopWindowDeactivate()) + if (!event.GetActive() && IsShown() && ShouldDismissOnTopWindowDeactivate() && + !(Slic3r::GUI::is_running_on_wayland() && own_tooltip_mapped(GTK_WINDOW(m_widget)))) DismissAndNotify(); } #endif diff --git a/src/slic3r/GUI/Widgets/PopupWindow.hpp b/src/slic3r/GUI/Widgets/PopupWindow.hpp index 45afea8213..a95a04e214 100644 --- a/src/slic3r/GUI/Widgets/PopupWindow.hpp +++ b/src/slic3r/GUI/Widgets/PopupWindow.hpp @@ -14,6 +14,9 @@ public: PopupWindow(wxWindow *parent, int style = wxBORDER_NONE) { Create(parent, style); } bool Create(wxWindow *parent, int flags = wxBORDER_NONE); +#ifdef __WXGTK__ + bool Show(bool show = true) override; +#endif #ifdef __WXMSW__ void BindUnfocusEvent(); #endif diff --git a/src/slic3r/Utils/FontConfigHelp.cpp b/src/slic3r/Utils/FontConfigHelp.cpp index 81f7d9784c..8e21051a28 100644 --- a/src/slic3r/Utils/FontConfigHelp.cpp +++ b/src/slic3r/Utils/FontConfigHelp.cpp @@ -11,6 +11,9 @@ #include #include +#include +#include +#include #include "libslic3r/Utils.hpp" @@ -22,11 +25,26 @@ static std::optional finalize_guard; // cache for Loading of the default configuration file and building information about the available fonts. static FcConfig *fc = nullptr; +// The bundled fonts can be registered only in wx's own font configuration (Label::initSysFont), +// so add them here too, to find the files of the faces wx offers. They are added file by file: +// adding the directory writes a font cache for its path, which in an AppImage differs on every start. +static FcConfig *load_font_config() +{ + FcConfig *config = FcInitLoadConfigAndFonts(); + if (config == nullptr) + return nullptr; + boost::system::error_code ec; + for (const auto &entry : boost::filesystem::directory_iterator(Slic3r::resources_dir() + "/fonts", ec)) + if (entry.path().extension() == ".ttf") + FcConfigAppFontAddFile(config, (const FcChar8 *) entry.path().string().c_str()); + return config; +} + std::string Slic3r::GUI::get_font_path(const wxFont &font, bool reload_fonts) { if (!finalize_guard.has_value()) { FcInit(); - fc = FcInitLoadConfigAndFonts(); + fc = load_font_config(); finalize_guard.emplace([]() { // Some internal problem of Font config or other library use FC too(like wxWidget) // fccache.c:795: FcCacheFini: Assertion `fcCacheChains[i] == NULL' failed. @@ -35,7 +53,7 @@ std::string Slic3r::GUI::get_font_path(const wxFont &font, bool reload_fonts) }); } else if (reload_fonts) { FcConfigDestroy(fc); - fc = FcInitLoadConfigAndFonts(); + fc = load_font_config(); } if (fc == nullptr) return ""; @@ -103,10 +121,10 @@ std::string Slic3r::GUI::get_font_path(const wxFont &font, bool reload_fonts) FcPatternAddInteger(matchPattern, FC_WEIGHT, weight); FcPatternAddInteger(matchPattern, FC_WIDTH, width); - FcConfigSubstitute(NULL, matchPattern, FcMatchPattern); + FcConfigSubstitute(fc, matchPattern, FcMatchPattern); FcDefaultSubstitute(matchPattern); - FcPattern *resultPattern = FcFontMatch(NULL, matchPattern, &res); + FcPattern *resultPattern = FcFontMatch(fc, matchPattern, &res); if (resultPattern == nullptr) return ""; ScopeGuard sg_rp([resultPattern]() { FcPatternDestroy(resultPattern); }); diff --git a/src/slic3r/plugin/PluginAuditManager.cpp b/src/slic3r/plugin/PluginAuditManager.cpp index 404191e8a9..2ebe34199f 100644 --- a/src/slic3r/plugin/PluginAuditManager.cpp +++ b/src/slic3r/plugin/PluginAuditManager.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -385,6 +386,33 @@ boost::filesystem::path canonical_for_comparison(const boost::filesystem::path& return canon; } +// True when the final component of `path` is a symlink whose target does not exist. +// +// weakly_canonical() leaves such a link in its lexical tail: it stats the prefix and stops at the +// first non-existing component, and exists() follows the link and reports false for a dangling +// one. A target such as /link would therefore compare as if it lived inside the tree even +// though a write through it lands at the link's target, which the grant does not describe. +// +// A link whose target exists is not dangling: symlink_status() reports the link itself (it does +// not follow it) while exists() follows it and succeeds. The canonical form of such a candidate is +// already resolved to the target, so this check does not fire for it. An intermediate dangling +// component is not reported here and needs no special case: the open cannot follow it either, so +// nothing is created. +bool ends_in_dangling_symlink(const boost::filesystem::path& path) +{ + namespace fs = boost::filesystem; + + boost::system::error_code ec; + const fs::file_status status = fs::symlink_status(path, ec); + // symlink_status does not follow the link, so a missing target still reports symlink; a path + // that does not exist at all reports an error instead. + if (ec || !fs::is_symlink(status)) + return false; + + // exists() follows the link: false means the target is missing. + return !fs::exists(path, ec); +} + bool same_path_component(const boost::filesystem::path& lhs, const boost::filesystem::path& rhs) { #ifdef _WIN32 @@ -434,8 +462,17 @@ bool suffix_inside_root(const boost::filesystem::path& canonical_candidate, bool is_inside_allowed_root(const boost::filesystem::path& candidate, const boost::filesystem::path& allowed_root) { + const boost::filesystem::path canonical_candidate = canonical_for_comparison(candidate); + + // Fail closed on a dangling final symlink instead of comparing the path it is spelled as: the + // grant describes the link, not the destination a write through it would create. The test is + // applied to the canonical form, which leaves a dangling link unresolved as its final + // component, so a trailing separator does not hide it either. + if (ends_in_dangling_symlink(canonical_candidate)) + return false; + boost::filesystem::path suffix; - return suffix_inside_root(canonical_for_comparison(candidate), canonical_for_comparison(allowed_root), suffix); + return suffix_inside_root(canonical_candidate, canonical_for_comparison(allowed_root), suffix); } // --------------------------------------------------------------------------- @@ -1085,9 +1122,99 @@ std::string event_grant_key(AuditEventCategory category, const std::string& even return std::string(category_name(category)) + ":" + event_name; } -bool has_permission(const std::vector& granted, const std::string& target) +// The directory named by a directory-tree grant, i.e. "/*". "*" is the only wildcard, and +// only as the grant's final path component; any other "*" is an ordinary character, so a grant +// can never widen into a pattern the plugin did not spell out. Returns false for a grant that is +// not a tree grant. +bool tree_grant_root(const std::string& grant, boost::filesystem::path& root) { - return std::find(granted.begin(), granted.end(), target) != granted.end(); + if (grant.size() < 2 || grant.back() != '*' || grant.find('*') != grant.size() - 1) + return false; + + const boost::filesystem::path path(grant); + if (path.filename() != "*") + return false; + + const boost::filesystem::path parent = path.parent_path(); + if (parent.empty()) + return false; + + // Never resolve ".." here: a grant shown to the user as "/a/../*" must not silently become + // the root or another ancestor. Without a wildcard the string still matches verbatim. + for (const boost::filesystem::path& component : parent) { + if (component == "..") + return false; + } + + // Rebuild from the components so "." and duplicate separators do not affect the canonical + // comparison below. + boost::filesystem::path normalized; + for (const boost::filesystem::path& component : parent.lexically_normal()) { + if (!component.empty()) + normalized /= component; + } + root = std::move(normalized); + return !root.empty(); +} + +// The grant to display and store for a permission request: a recognized tree grant is resolved +// against the working directory when the request is made, so a relative "/*" names the +// directory it actually covers. Grants that are already absolute, exact (non-tree) grants, and +// the non-filesystem buckets are returned unchanged: they are matched verbatim, and re-rendering +// them would change the string the user approved. +std::string absolute_tree_grant(const std::string& grant) +{ + boost::filesystem::path root; + if (!tree_grant_root(grant, root) || root.is_absolute()) + return grant; + + boost::system::error_code ec; + const boost::filesystem::path absolute_root = boost::filesystem::absolute(root, ec); + if (ec || !absolute_root.is_absolute()) + return grant; + + return (absolute_root.lexically_normal() / "*").string(); +} + +// True when a filesystem grant covers a target: the exact string, or -- for a tree grant -- the +// granted folder itself and every path beneath it, at any depth. Components are compared one by +// one, so "/root/*" covers "/root/a/b" but not "/root-other/file". +// +// A tree grant and its target are both canonicalized before the comparison, so a symlink inside +// the granted folder cannot launder access to a path outside it, and a grant rooted at a symlink +// applies to the symlink's target. weakly_canonical keeps a write target whose tail does not +// exist yet matchable: it canonicalizes the existing prefix and appends the rest lexically. A +// dangling final symlink is not covered at all: containment fails closed, because a write through +// it would land at its target rather than at the granted path. +bool fs_grant_covers(const std::string& grant, const std::string& target) +{ + if (grant == target) + return true; + if (target.empty()) + return false; + + boost::filesystem::path root; + if (!tree_grant_root(grant, root)) + return false; + + return is_inside_allowed_root(boost::filesystem::path(target), root); +} + +// True when `granted` already covers `target`. Only the filesystem buckets accept a tree grant: +// an event grant ("FsRead:open") and the non-filesystem buckets (URLs, socket addresses, +// commands) are matched verbatim, as before. +bool has_permission(AuditEventCategory category, bool by_event, const std::vector& granted, + const std::string& target) +{ + const bool fs_bucket = + !by_event && (category == AuditEventCategory::FsRead || category == AuditEventCategory::FsReadWrite); + for (const auto& grant : granted) { + if (grant == target) + return true; + if (fs_bucket && fs_grant_covers(grant, target)) + return true; + } + return false; } // A declared or previously approved network grant may live in either network list: an HTTP grant @@ -1122,6 +1249,8 @@ void seed_install_metadata(const PluginDescriptor& descriptor, PluginInstallStat bool persist_permission(const std::string& plugin_key, PluginInstallState& state, + AuditEventCategory category, + bool by_event, std::vector& permission_list, const std::string& target) { @@ -1131,7 +1260,7 @@ bool persist_permission(const std::string& plugin_key, seed_install_metadata(descriptor, state); - if (!has_permission(permission_list, target)) + if (!has_permission(category, by_event, permission_list, target)) permission_list.push_back(target); return write_install_state(boost::filesystem::path(descriptor.plugin_root), state); } @@ -1242,10 +1371,11 @@ void persist_grant(const std::string& plugin_key, AuditEventCategory category, b return; for (const auto& key : keys) - persist_permission(plugin_key, state, *permission_list, key); + persist_permission(plugin_key, state, category, by_event, *permission_list, key); } static PluginAuditManager::PermissionPrompt s_permission_prompt_for_testing; +static PluginAuditManager::PermissionMessagePrompt s_permission_message_prompt_for_testing; static const char* audit_category_name(AuditEventCategory category) { @@ -1333,7 +1463,7 @@ int decide_audited_event(PluginAuditManager& mgr, is_network_category(category) && (by_event ? has_any_network_permission(state.permissions) : has_network_permission(state.permissions, key)); - if (!(permission_list && has_permission(*permission_list, key)) && !granted_network) + if (!(permission_list && has_permission(category, by_event, *permission_list, key)) && !granted_network) unresolved.push_back(key); } if (unresolved.empty()) @@ -1350,7 +1480,7 @@ int decide_audited_event(PluginAuditManager& mgr, if (permission_list) for (const auto& key : unresolved) - persist_permission(plugin_key, state, *permission_list, key); + persist_permission(plugin_key, state, category, by_event, *permission_list, key); return 0; } @@ -1438,15 +1568,25 @@ bool PluginAuditManager::request_permissions(const std::string& plugin_key, cons const auto collect_missing = [&missing_buckets, &state](AuditEventCategory category, const std::vector& requested_targets, const std::vector& granted_targets) { + // Only the filesystem buckets accept a tree grant; the others match verbatim. + const bool tree_grant_bucket = + category == AuditEventCategory::FsRead || category == AuditEventCategory::FsReadWrite; MissingBucket bucket{category, {}}; - for (const std::string& target : requested_targets) { - if (target.empty()) + for (const std::string& requested_target : requested_targets) { + if (requested_target.empty()) continue; - + // A relative wildcard names a directory relative to the working directory the request + // is made in, while the audit hook reports absolute targets. Resolve it once, here, so + // the prompt shows and the sidecar stores the scope the grant actually covers. + const std::string target = tree_grant_bucket + ? PluginAuditDetail::absolute_tree_grant(requested_target) + : requested_target; + // A saved wildcard already covers a more specific request. Deduplicate inside the + // request verbatim only: two requested entries may cover different sets. const bool already_granted = is_network_category(category) ? PluginAuditDetail::has_network_permission(state.permissions, target) - : std::find(granted_targets.begin(), granted_targets.end(), target) != granted_targets.end(); + : PluginAuditDetail::has_permission(category, /*by_event=*/false, granted_targets, target); if (!already_granted && std::find(bucket.targets.begin(), bucket.targets.end(), target) == bucket.targets.end()) bucket.targets.push_back(target); @@ -1465,9 +1605,6 @@ bool PluginAuditManager::request_permissions(const std::string& plugin_key, cons if (missing_buckets.empty()) return true; - if (wxTheApp == nullptr || GUI::wxGetApp().is_closing()) - return false; - const auto build_message = [](const std::string& plugin_name, const std::vector& buckets) { wxString message; for (const MissingBucket& bucket : buckets) { @@ -1484,7 +1621,13 @@ bool PluginAuditManager::request_permissions(const std::string& plugin_key, cons }; bool granted = false; - if (wxIsMainThread()) { + if (PluginAuditDetail::s_permission_message_prompt_for_testing) { + // Tests run without a wxApp to host the dialog: hand the seam the message it would show. + granted = PluginAuditDetail::s_permission_message_prompt_for_testing( + build_message(descriptor.name, missing_buckets).utf8_string()); + } else if (wxTheApp == nullptr || GUI::wxGetApp().is_closing()) { + return false; + } else if (wxIsMainThread()) { granted = PluginAuditDetail::prompt_for_permission_message(build_message(descriptor.name, missing_buckets)); } else { auto result = std::make_shared>(); @@ -1612,6 +1755,11 @@ void PluginAuditManager::set_permission_prompt_for_testing(PermissionPrompt prom PluginAuditDetail::s_permission_prompt_for_testing = std::move(prompt); } +void PluginAuditManager::set_permission_message_prompt_for_testing(PermissionMessagePrompt prompt) +{ + PluginAuditDetail::s_permission_message_prompt_for_testing = std::move(prompt); +} + int PluginAuditManager::audit_hook(const char* event, PyObject* args, void* user_data) { auto* mgr = static_cast(user_data); diff --git a/src/slic3r/plugin/PluginAuditManager.hpp b/src/slic3r/plugin/PluginAuditManager.hpp index cc87189b45..b85a528840 100644 --- a/src/slic3r/plugin/PluginAuditManager.hpp +++ b/src/slic3r/plugin/PluginAuditManager.hpp @@ -54,7 +54,9 @@ enum class AuditEventCategory { }; // Returns true if candidate resolves to a path inside allowed_root. -// Uses weakly_canonical and component-wise comparison to reject traversal attacks. +// Uses weakly_canonical and component-wise comparison to reject traversal attacks. A candidate +// whose final component is a dangling symlink is never inside: containment fails closed rather +// than authorizing the destination a write through it would create. bool is_inside_allowed_root(const boost::filesystem::path& candidate, const boost::filesystem::path& allowed_root); @@ -145,6 +147,23 @@ public: // Targets already persisted for the plugin are not shown or asked for again. Returns true // only when every missing target was granted and persisted; denial aborts the plugin load // without adding a permission. + // + // A filesystem target may name a directory tree: a trailing "/*" (e.g. "/path/to/folder/*") + // grants the folder itself and every path beneath it, at any depth. "*" is the only wildcard + // and is only recognized as the final path component; elsewhere it is an ordinary character. + // The wildcard applies to fs_read and fs_readwrite only, never to event grants or the other + // buckets, and a read grant still never authorizes a write (or the reverse). Denied paths + // stay denied regardless of a covering wildcard. + // + // A relative tree grant is resolved against the working directory when the request is made: + // the prompt shows, and the sidecar stores, the absolute scope it covers. Exact grants and + // the non-filesystem buckets are stored and compared verbatim. + // + // Tree grants are matched on canonical paths: a symlink below the granted folder does not + // extend the grant outside it, and a grant whose root is a symlink applies to its target. A + // target whose final component is a dangling symlink is never covered, since a write through + // it would create the link's target rather than the path the grant describes. Exact + // (non-tree) grants keep their verbatim string comparison. bool request_permissions(const std::string& plugin_key, const PluginPermissions& requested); // Ask the user to grant network access to the given http(s) URLs. Each URL is reduced to its @@ -198,6 +217,12 @@ public: using PermissionPrompt = std::function& targets)>; static void set_permission_prompt_for_testing(PermissionPrompt prompt); + // Answers the combined permission-request prompt in place of the dialog, receiving the message + // it would show. Tests run without a wxApp, so this seam also stands in for the app check. + // Production never sets it. + using PermissionMessagePrompt = std::function; + static void set_permission_message_prompt_for_testing(PermissionMessagePrompt prompt); + bool verbose_events = true; private: diff --git a/src/slic3r/plugin/PluginFsUtils.hpp b/src/slic3r/plugin/PluginFsUtils.hpp index 64c57f9867..302519a3e4 100644 --- a/src/slic3r/plugin/PluginFsUtils.hpp +++ b/src/slic3r/plugin/PluginFsUtils.hpp @@ -98,13 +98,17 @@ inline nlohmann::json py_to_json(const pybind11::handle& o, int depth = 0) struct PluginPermissions { + // Filesystem targets. A target ending in "/*" (e.g. "/path/to/folder/*") grants the folder + // and its whole subtree, at any depth; "*" is the only wildcard and only as the final path + // component. Reads and writes stay separate buckets: a wildcard in one never grants the other. std::vector fs_read; std::vector fs_readwrite; std::vector network_http; std::vector network_socket; std::vector process; std::vector threading; - // Grants for audit events that expose no target, keyed ":" (e.g. "Socket:socket.__new__"). + // Grants for audit events that expose no target, keyed ":" (e.g. + // "Socket:socket.__new__"). Matched verbatim; the filesystem wildcard does not apply. std::vector events; }; diff --git a/src/slic3r/plugin/PythonPluginBridge.cpp b/src/slic3r/plugin/PythonPluginBridge.cpp index 379ffd8741..7e203f2b61 100644 --- a/src/slic3r/plugin/PythonPluginBridge.cpp +++ b/src/slic3r/plugin/PythonPluginBridge.cpp @@ -635,6 +635,15 @@ report: filesystem paths for fs_read and fs_readwrite, URLs for network_http, so for network_socket, and commands for process. threading=True requests permission to start threads. Targets already granted to the plugin are not asked for again. +A filesystem target may end in "/*" to grant a whole directory tree, for example +"/path/to/folder/*". That covers the folder itself and every path beneath it, at any depth. +"*" is the only wildcard and is recognized only as the final path component; a "*" anywhere +else in a target is an ordinary character. Wildcards apply to fs_read and fs_readwrite only, +and a grant in one of those buckets never authorizes the other direction. Tree grants are +matched on canonical paths, so a symlink below the granted folder does not extend the grant +outside it. Paths the host denies by name or keyword stay denied even when a wildcard covers +them. + `network` also lists http(s) URLs, but each is reduced to its scheme and host, so one grant covers every path, query and port on that host and also authorizes raw socket events for it. The host presents one request to the user after register_capabilities() returns and before any capability diff --git a/tests/cli/test_cli_project_missing_keys.sh b/tests/cli/test_cli_project_missing_keys.sh index f20a2eb822..00df605cfc 100644 --- a/tests/cli/test_cli_project_missing_keys.sh +++ b/tests/cli/test_cli_project_missing_keys.sh @@ -8,6 +8,9 @@ # key, one process key and two filament keys (one per filament, one per extruder variant) are changed # without being listed, one process key and the first filament's density are changed and listed, and it # is sliced again: as is, with --uptodate, and with --load-filaments replacing only the second filament. +# Without any entry in different_settings_to_system the project does not say which values it changed: +# a plain run then keeps every stored value and takes only the removed keys, three filament keys among +# them, from the system presets, while --uptodate still refreshes the unlisted ones. # # usage: test_cli_project_missing_keys.sh set -u @@ -71,11 +74,12 @@ with zipfile.ZipFile(src) as zin, zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED config[key] = str(int(float(config[key])) + 1) for key in ("filament_cost", "filament_max_volumetric_speed"): expected[key] = config[key] - config[key] = [str(float(v) + 1) for v in config[key]] + # Written as the slicer writes them, so the value a project keeps reads back the same. + config[key] = ["%g" % (float(v) + 1) for v in config[key]] expected["wall_loops"] = str(int(config["wall_loops"]) + 1) config["wall_loops"] = expected["wall_loops"] expected["filament_density"] = [str(float(config["filament_density"][0]) + 1)] + config["filament_density"][1:] - config["filament_density"] = [expected["filament_density"][0]] + [str(float(v) + 1) for v in config["filament_density"][1:]] + config["filament_density"] = [expected["filament_density"][0]] + ["%g" % (float(v) + 1) for v in config["filament_density"][1:]] # One entry for the process, one per filament, one for the printer. different = config["different_settings_to_system"] different[0] = ";".join([k for k in different[0].split(";") if k] + ["wall_loops"]) @@ -86,8 +90,9 @@ with open(dst + ".expected.json", "w") as f: json.dump(expected, f) EOF +# check [expected.json] check() { - if ! "$PY" - "$WORK/$1/out.3mf" "$WORK/old.3mf.expected.json" "$1" <<'EOF' + if ! "$PY" - "$WORK/$1/out.3mf" "${2:-$WORK/old.3mf.expected.json}" "$1" <<'EOF' import json, sys, zipfile with zipfile.ZipFile(sys.argv[1]) as z: @@ -112,4 +117,46 @@ check uptodate # The replaced second filament takes the system values the refresh would have given it. slice partial "$WORK/old.3mf" --load-filaments ";$PROFILES/filament/Bambu PLA Basic @BBL P1S 0.4 nozzle.json" check partial + +# The same project with no list and with an empty entry for every preset, and without two per-variant +# filament keys and one filament_dev key. A plain run keeps the stored values; --uptodate refreshes them +# all, and the listed keys have no system value to expect. +"$PY" - "$WORK/old.3mf" "$WORK/old.3mf.expected.json" "$WORK" <<'EOF' || exit $? +import json, sys, zipfile + +src, expected_path, work = sys.argv[1:] +with open(expected_path) as f: + expected = json.load(f) +# Read every entry first: writestr() updates the ZipInfo it is given, so zin could not read it again. +with zipfile.ZipFile(src) as zin: + items = [(item, zin.read(item.filename)) for item in zin.infolist()] +config = json.loads(next(data for item, data in items if item.filename == "Metadata/project_settings.config")) +stored = {key: config.get(key, want) for key, want in expected.items()} +refreshed = {key: want for key, want in expected.items() if key not in ("wall_loops", "filament_density")} +# The removed filament keys, with their option defaults from PrintConfig.cpp. +for key, default in (("nozzle_temperature", "200"), ("filament_flow_ratio", "1"), ("filament_dev_ams_drying_time", "0")): + if default in config[key]: + print("SKIP: %s is %s in the system preset, the option default, so the test cannot tell them apart" % (key, default)) + sys.exit(77) + stored[key] = refreshed[key] = config.pop(key) +for name, different in (("unlisted", None), ("empty_list", [""] * len(config["different_settings_to_system"]))): + if different is None: + config.pop("different_settings_to_system") + else: + config["different_settings_to_system"] = different + with zipfile.ZipFile("%s/%s.3mf" % (work, name), "w", zipfile.ZIP_DEFLATED) as zout: + for item, data in items: + if item.filename == "Metadata/project_settings.config": + data = json.dumps(config, indent=4) + zout.writestr(item, data) +for name, values in (("stored", stored), ("refreshed", refreshed)): + with open("%s/%s.expected.json" % (work, name), "w") as f: + json.dump(values, f) +EOF +slice unlisted "$WORK/unlisted.3mf" +check unlisted "$WORK/stored.expected.json" +slice empty_list "$WORK/empty_list.3mf" +check empty_list "$WORK/stored.expected.json" +slice unlisted_uptodate "$WORK/unlisted.3mf" --uptodate +check unlisted_uptodate "$WORK/refreshed.expected.json" echo "PASS" diff --git a/tests/data/seam_contour_benchy_split.txt b/tests/data/seam_contour_benchy_split.txt new file mode 100644 index 0000000000..9e030f2d75 --- /dev/null +++ b/tests/data/seam_contour_benchy_split.txt @@ -0,0 +1,582 @@ +1 +0 0.41999998688697815 0.4 287 +11.697874069213867 -8.5420131683349609 +11.807644844055176 -8.5151939392089844 +11.885490417480469 -8.4626426696777344 +11.955679893493652 -8.3574113845825195 +11.976012229919434 -8.2445869445800781 +11.975451469421387 -6.5400009155273438 +12.276429176330566 -6.5400009155273438 +12.276576995849609 -5.215482234954834 +10.389512062072754 -5.215482234954834 +10.388867378234863 -6.8882331848144531 +-6.7026500701904297 -5.9390401840209961 +-6.7026500701904297 5.9390377998352051 +-6.502957820892334 5.9501276016235352 +-6.3032655715942383 5.9612178802490234 +-6.1035733222961426 5.9723076820373535 +-5.9038810729980469 5.9833979606628418 +-5.7041888236999512 5.9944877624511719 +-5.5044965744018555 6.0055780410766602 +-5.3048038482666016 6.0166678428649902 +-5.1051115989685059 6.0277581214904785 +-4.9054193496704102 6.0388479232788086 +-4.7057271003723145 6.0499382019042969 +-4.5060348510742188 6.061028003692627 +-4.3063421249389648 6.0721182823181152 +-4.1066498756408691 6.0832080841064453 +-3.9069576263427734 6.0942983627319336 +-3.7072653770446777 6.1053881645202637 +-3.5075728893280029 6.116478443145752 +-3.3078806400299072 6.127568244934082 +-3.1081883907318115 6.1386585235595703 +-2.9084959030151367 6.1497483253479004 +-2.7088038921356201 6.1608386039733887 +-2.5091118812561035 6.1719284057617188 +-2.3094196319580078 6.183018684387207 +-2.1097273826599121 6.1941084861755371 +-1.9100356101989746 6.2051987648010254 +-1.7103433609008789 6.2162885665893555 +-1.5106511116027832 6.2273788452148438 +-1.3109593391418457 6.2384686470031738 +-1.11126708984375 6.2495589256286621 +-0.9115748405456543 6.2606487274169922 +-0.7118830680847168 6.2717390060424805 +-0.51219081878662109 6.2828288078308105 +-0.31249856948852539 6.2939190864562988 +-0.11280679702758789 6.3050088882446289 +0.086885452270507812 6.3160991668701172 +0.28657770156860352 6.3271889686584473 +0.48626947402954102 6.3382787704467773 +0.68596172332763672 6.3493690490722656 +0.88565397262573242 6.3604588508605957 +1.0853457450866699 6.371549129486084 +1.2850379943847656 6.3826389312744141 +1.4847307205200195 6.3937292098999023 +1.684422492980957 6.4048190116882324 +1.8841152191162109 6.4159092903137207 +2.0838069915771484 6.4269990921020508 +2.2834987640380859 6.4380893707275391 +2.4831914901733398 6.4491791725158691 +2.6828832626342773 6.4602694511413574 +2.8825750350952148 6.4713592529296875 +3.0822677612304688 6.4824495315551758 +3.2819595336914062 6.4935393333435059 +3.4816513061523438 6.5046296119689941 +3.6813440322875977 6.5157194137573242 +3.8810358047485352 6.5268096923828125 +4.0807275772094727 6.5378994941711426 +4.2804203033447266 6.5489892959594727 +4.4801120758056641 6.5600795745849609 +4.6798038482666016 6.571169376373291 +4.8794965744018555 6.5822596549987793 +5.079188346862793 6.5933494567871094 +5.2788801193237305 6.6044397354125977 +5.4785728454589844 6.6155295372009277 +5.6782646179199219 6.626619815826416 +5.8779563903808594 6.6377096176147461 +6.0776491165161133 6.6487998962402344 +6.2773408889770508 6.6598896980285645 +6.4770326614379883 6.6709799766540527 +6.6767253875732422 6.6820697784423828 +6.8764171600341797 6.6931600570678711 +7.0761089324951172 6.7042498588562012 +7.2758016586303711 6.7153401374816895 +7.4754934310913086 6.7264299392700195 +7.6751852035522461 6.7375202178955078 +7.8748779296875 6.7486100196838379 +8.0745697021484375 6.759699821472168 +8.274261474609375 6.7707901000976562 +8.4739542007446289 6.7818799018859863 +8.6736459732055664 6.7929701805114746 +8.8733377456665039 6.8040599822998047 +9.0730304718017578 6.815150260925293 +9.2727222442626953 6.826240062713623 +9.4724140167236328 6.8373303413391113 +9.6721076965332031 6.8484201431274414 +9.8718013763427734 6.8595104217529297 +10.071493148803711 6.870600700378418 +10.271186828613281 6.881690502166748 +10.388867378234863 6.8882260322570801 +10.389512062072754 5.2154779434204102 +12.276576995849609 5.2154779434204102 +12.276429176330566 6.5400009155273438 +11.975607872009277 6.5400009155273438 +11.974886894226074 8.2683258056640625 +11.942225456237793 8.3868656158447266 +11.873661994934082 8.4729747772216797 +11.778239250183105 8.5271291732788086 +11.658943176269531 8.542170524597168 +-8.0029592514038086 7.4495530128479004 +-8.1317710876464844 7.413823127746582 +-8.2030715942382812 7.3597521781921387 +-8.2685146331787109 7.249596118927002 +-8.283625602722168 7.1527981758117676 +-8.283625602722168 6.9527983665466309 +-8.283625602722168 6.7527980804443359 +-8.283625602722168 6.5527982711791992 +-8.283625602722168 6.3527979850769043 +-8.283625602722168 6.1527981758117676 +-8.283625602722168 5.9527978897094727 +-8.283625602722168 5.7527980804443359 +-8.283625602722168 5.5527982711791992 +-8.283625602722168 5.3527979850769043 +-8.283625602722168 5.1527976989746094 +-8.283625602722168 4.9527978897094727 +-8.283625602722168 4.7527980804443359 +-8.283625602722168 4.552797794342041 +-8.283625602722168 4.3527975082397461 +-8.283625602722168 4.1527976989746094 +-8.283625602722168 3.9527976512908936 +-8.283625602722168 3.7527976036071777 +-8.283625602722168 3.5527975559234619 +-8.283625602722168 3.3527975082397461 +-8.283625602722168 3.1527976989746094 +-8.283625602722168 2.9527978897094727 +-8.283625602722168 2.7527980804443359 +-8.283625602722168 2.5527982711791992 +-8.283625602722168 2.3527984619140625 +-8.283625602722168 2.1527986526489258 +-8.283625602722168 1.9527988433837891 +-8.283625602722168 1.7527990341186523 +-8.283625602722168 1.5527992248535156 +-8.283625602722168 1.3527994155883789 +-8.283625602722168 1.1527996063232422 +-8.283625602722168 0.95279979705810547 +-8.283625602722168 0.75279998779296875 +-8.283625602722168 0.55280017852783203 +-8.283625602722168 0.35280036926269531 +-8.283625602722168 0.15280055999755859 +-8.283625602722168 -0.047199249267578125 +-8.283625602722168 -0.24719905853271484 +-8.283625602722168 -0.44719886779785156 +-8.283625602722168 -0.64719867706298828 +-8.283625602722168 -0.847198486328125 +-8.283625602722168 -1.0471987724304199 +-8.283625602722168 -1.2471985816955566 +-8.283625602722168 -1.4471983909606934 +-8.283625602722168 -1.6471982002258301 +-8.283625602722168 -1.8471980094909668 +-8.283625602722168 -2.0471978187561035 +-8.283625602722168 -2.2471976280212402 +-8.283625602722168 -2.447197437286377 +-8.283625602722168 -2.6471972465515137 +-8.283625602722168 -2.8471970558166504 +-8.283625602722168 -3.0471968650817871 +-8.283625602722168 -3.2471966743469238 +-8.283625602722168 -3.4471964836120605 +-8.283625602722168 -3.6471962928771973 +-8.283625602722168 -3.847196102142334 +-8.283625602722168 -4.0471959114074707 +-8.283625602722168 -4.2471957206726074 +-8.283625602722168 -4.4471955299377441 +-8.283625602722168 -4.6471953392028809 +-8.283625602722168 -4.8471951484680176 +-8.283625602722168 -5.0471949577331543 +-8.283625602722168 -5.247194766998291 +-8.283625602722168 -5.4471945762634277 +-8.283625602722168 -5.6471943855285645 +-8.283625602722168 -5.8471941947937012 +-8.283625602722168 -6.0471940040588379 +-8.283625602722168 -6.2471938133239746 +-8.283625602722168 -6.4471936225891113 +-8.283625602722168 -6.647193431854248 +-8.283625602722168 -6.8471932411193848 +-8.283625602722168 -7.0471930503845215 +-8.283625602722168 -7.1494722366333008 +-8.2683954238891602 -7.2499008178710938 +-8.2184553146362305 -7.3418078422546387 +-8.0947837829589844 -7.430692195892334 +-8.0006170272827148 -7.4496769905090332 +-7.8009238243103027 -7.4607505798339844 +-7.6012306213378906 -7.4718241691589355 +-7.4015374183654785 -7.4828977584838867 +-7.2018442153930664 -7.4939713478088379 +-7.0021510124206543 -7.5050449371337891 +-6.8024578094482422 -7.516118049621582 +-6.6027646064758301 -7.5271916389465332 +-6.403071403503418 -7.5382652282714844 +-6.2033777236938477 -7.5493388175964355 +-6.0036849975585938 -7.5604124069213867 +-5.8039913177490234 -7.5714859962463379 +-5.6042985916137695 -7.5825595855712891 +-5.4046049118041992 -7.5936331748962402 +-5.2049117088317871 -7.6047067642211914 +-5.005218505859375 -7.6157803535461426 +-4.8055253028869629 -7.6268539428710938 +-4.6058320999145508 -7.6379270553588867 +-4.4061384201049805 -7.6490006446838379 +-4.2064456939697266 -7.6600742340087891 +-4.0067524909973145 -7.6711478233337402 +-3.8070592880249023 -7.6822214126586914 +-3.6073665618896484 -7.6932950019836426 +-3.4076733589172363 -7.7043685913085938 +-3.2079806327819824 -7.7154421806335449 +-3.0082874298095703 -7.7265157699584961 +-2.8085942268371582 -7.7375888824462891 +-2.6089015007019043 -7.7486624717712402 +-2.4092082977294922 -7.7597360610961914 +-2.2095155715942383 -7.7708096504211426 +-2.0098223686218262 -7.7818832397460938 +-1.8101291656494141 -7.7929568290710449 +-1.6104364395141602 -7.8040304183959961 +-1.410743236541748 -7.8151040077209473 +-1.2110505104064941 -7.8261775970458984 +-1.011357307434082 -7.8372507095336914 +-0.81166410446166992 -7.8483242988586426 +-0.61197137832641602 -7.8593978881835938 +-0.41227817535400391 -7.8704714775085449 +-0.21258544921875 -7.8815450668334961 +-0.012892246246337891 -7.8926186561584473 +0.18680095672607422 -7.9036922454833984 +0.38649463653564453 -7.9147658348083496 +0.58618736267089844 -7.9258394241333008 +0.78588008880615234 -7.9369125366210938 +0.98557376861572266 -7.9479861259460449 +1.1852664947509766 -7.9590597152709961 +1.3849592208862305 -7.9701333045959473 +1.5846519470214844 -7.9812068939208984 +1.7843456268310547 -7.9922804832458496 +1.9840383529663086 -8.0033540725708008 +2.1837310791015625 -8.0144271850585938 +2.3834247589111328 -8.0255012512207031 +2.5831174850463867 -8.0365743637084961 +2.7828102111816406 -8.0476484298706055 +2.9825038909912109 -8.0587215423583984 +3.1821966171264648 -8.0697956085205078 +3.3818893432617188 -8.0808687210083008 +3.5815820693969727 -8.0919418334960938 +3.781275749206543 -8.1030158996582031 +3.9809684753417969 -8.1140890121459961 +4.1806612014770508 -8.1251630783081055 +4.3803548812866211 -8.1362361907958984 +4.580047607421875 -8.1473102569580078 +4.7797403335571289 -8.1583833694458008 +4.9794340133666992 -8.1694564819335938 +5.1791267395019531 -8.1805305480957031 +5.378819465637207 -8.1916036605834961 +5.5785121917724609 -8.2026777267456055 +5.7782058715820312 -8.2137508392333984 +5.9778985977172852 -8.2248249053955078 +6.1775913238525391 -8.2358980178833008 +6.3772850036621094 -8.2469720840454102 +6.5769777297973633 -8.2580451965332031 +6.7766704559326172 -8.2691192626953125 +6.9763641357421875 -8.2801923751831055 +7.1760568618774414 -8.2912654876708984 +7.3757495880126953 -8.3023395538330078 +7.5754423141479492 -8.3134126663208008 +7.7751359939575195 -8.3244867324829102 +7.9748287200927734 -8.3355598449707031 +8.1745214462280273 -8.3466339111328125 +8.3742151260375977 -8.3577070236206055 +8.573908805847168 -8.3687810897827148 +8.7736043930053711 -8.3798542022705078 +8.9732980728149414 -8.3909282684326172 +9.1729917526245117 -8.4020013809204102 +9.372685432434082 -8.4130754470825195 +9.5723791122436523 -8.4241485595703125 +9.7720727920532227 -8.4352226257324219 +9.9717683792114258 -8.4462957382202148 +10.171462059020996 -8.4573688507080078 +10.371155738830566 -8.4684429168701172 +10.570849418640137 -8.4795169830322266 +10.770543098449707 -8.4905900955200195 +10.970236778259277 -8.5016632080078125 +11.169930458068848 -8.5127372741699219 +11.369626045227051 -8.5238113403320312 +11.569319725036621 -8.5348844528198242 +11.697874069213867 -8.5420131683349609 +2 +1 0.41999998688697815 0.4 93 +10.401542663574219 -4.8054819107055664 +10.401542663574219 4.8054780960083008 +10.401542663574219 4.8054780960083008 +10.401542663574219 6.8931269645690918 +-6.7068581581115723 5.9429759979248047 +-6.7068581581115723 -5.9429788589477539 +-6.5071659088134766 -5.9540691375732422 +-6.3074736595153809 -5.9651594161987305 +-6.1077814102172852 -5.9762496948242188 +-5.9080891609191895 -5.987339973449707 +-5.7083969116210938 -5.9984302520751953 +-5.5087041854858398 -6.0095205307006836 +-5.3090119361877441 -6.0206108093261719 +-5.1093196868896484 -6.0317010879516602 +-4.9096274375915527 -6.0427913665771484 +-4.709935188293457 -6.0538816452026367 +-4.5102424621582031 -6.064971923828125 +-4.3105506896972656 -6.0760622024536133 +-4.1108579635620117 -6.0871524810791016 +-3.911165714263916 -6.0982427597045898 +-3.7114734649658203 -6.1093330383300781 +-3.5117809772491455 -6.1204233169555664 +-3.3120887279510498 -6.1315135955810547 +-3.1123964786529541 -6.142603874206543 +-2.9127039909362793 -6.1536941528320312 +-2.7130119800567627 -6.1647844314575195 +-2.5133199691772461 -6.1758747100830078 +-2.3136277198791504 -6.1869649887084961 +-2.1139354705810547 -6.1980552673339844 +-1.9142436981201172 -6.2091455459594727 +-1.7145514488220215 -6.2202358245849609 +-1.5148591995239258 -6.2313261032104492 +-1.3151674270629883 -6.2424163818359375 +-1.1154751777648926 -6.2535066604614258 +-0.91578292846679688 -6.2645969390869141 +-0.71609115600585938 -6.2756872177124023 +-0.51639890670776367 -6.2867774963378906 +-0.31670665740966797 -6.2978677749633789 +-0.11701488494873047 -6.3089580535888672 +0.082677364349365234 -6.3200483322143555 +0.28236961364746094 -6.3311386108398438 +0.48206138610839844 -6.342228889465332 +0.68175363540649414 -6.3533191680908203 +0.88144588470458984 -6.3644094467163086 +1.0811376571655273 -6.3754997253417969 +1.280829906463623 -6.3865900039672852 +1.480522632598877 -6.3976802825927734 +1.6802144050598145 -6.4087705612182617 +1.8799071311950684 -6.41986083984375 +2.0795989036560059 -6.4309511184692383 +2.2792906761169434 -6.4420413970947266 +2.4789834022521973 -6.4531316757202148 +2.6786751747131348 -6.4642219543457031 +2.8783669471740723 -6.4753122329711914 +3.0780596733093262 -6.4864025115966797 +3.2777514457702637 -6.497492790222168 +3.4774432182312012 -6.5085830688476562 +3.6771359443664551 -6.5196733474731445 +3.8768277168273926 -6.5307636260986328 +4.0765194892883301 -6.5418539047241211 +4.276212215423584 -6.5529441833496094 +4.4759039878845215 -6.5640344619750977 +4.675595760345459 -6.5751247406005859 +4.8752884864807129 -6.5862150192260742 +5.0749802589416504 -6.5973052978515625 +5.2746720314025879 -6.6083955764770508 +5.4743647575378418 -6.6194858551025391 +5.6740565299987793 -6.6305761337280273 +5.8737483024597168 -6.6416664123535156 +6.0734410285949707 -6.6527566909790039 +6.2731328010559082 -6.6638469696044922 +6.4728245735168457 -6.6749372482299805 +6.6725172996520996 -6.6860275268554688 +6.8722090721130371 -6.697117805480957 +7.0719008445739746 -6.7082080841064453 +7.2715935707092285 -6.7192983627319336 +7.471285343170166 -6.7303886413574219 +7.6709771156311035 -6.7414789199829102 +7.8706698417663574 -6.7525691986083984 +8.0703620910644531 -6.7636594772338867 +8.2700538635253906 -6.774749755859375 +8.4697456359863281 -6.7858400344848633 +8.6694374084472656 -6.7969303131103516 +8.8691291809082031 -6.8080205917358398 +9.0688228607177734 -6.8191108703613281 +9.2685146331787109 -6.8302011489868164 +9.4682064056396484 -6.8412914276123047 +9.6679000854492188 -6.852381706237793 +9.8675937652587891 -6.8634719848632812 +10.067285537719727 -6.8745622634887695 +10.266979217529297 -6.8856525421142578 +10.401542663574219 -6.8931260108947754 +10.401542663574219 -4.8054819107055664 +0 0.41999998688697815 0.4 197 +12.289004325866699 4.8054780960083008 +12.289004325866699 6.5400009155273438 +11.988205909729004 6.5400009155273438 +11.987482070922852 8.2732219696044922 +11.954745292663574 8.3918991088867188 +11.886277198791504 8.4778499603271484 +11.790833473205566 8.5320243835449219 +11.671573638916016 8.5470714569091797 +-8.0071420669555664 7.4535188674926758 +-8.1360998153686523 7.4177150726318359 +-8.2072591781616211 7.3637189865112305 +-8.2727594375610352 7.253410816192627 +-8.2878179550170898 7.1567649841308594 +-8.2878179550170898 6.9567651748657227 +-8.2878179550170898 6.7567648887634277 +-8.2878179550170898 6.556765079498291 +-8.2878179550170898 6.3567647933959961 +-8.2878179550170898 6.1567649841308594 +-8.2878179550170898 5.9567651748657227 +-8.2878179550170898 5.7567648887634277 +-8.2878179550170898 5.5567646026611328 +-8.2878179550170898 5.3567647933959961 +-8.2878179550170898 5.1567649841308594 +-8.2878179550170898 4.9567646980285645 +-8.2878179550170898 4.7567644119262695 +-8.2878179550170898 4.5567646026611328 +-8.2878179550170898 4.3567647933959961 +-8.2878179550170898 4.1567645072937012 +-8.2878179550170898 3.9567644596099854 +-8.2878179550170898 3.7567644119262695 +-8.2878179550170898 3.5567643642425537 +-8.2878179550170898 3.3567643165588379 +-8.2878179550170898 3.1567645072937012 +-8.2878179550170898 2.9567646980285645 +-8.2878179550170898 2.7567648887634277 +-8.2878179550170898 2.556765079498291 +-8.2878179550170898 2.3567652702331543 +-8.2878179550170898 2.1567654609680176 +-8.2878179550170898 1.9567656517028809 +-8.2878179550170898 1.7567658424377441 +-8.2878179550170898 1.5567660331726074 +-8.2878179550170898 1.3567662239074707 +-8.2878179550170898 1.156766414642334 +-8.2878179550170898 0.95676660537719727 +-8.2878179550170898 0.75676679611206055 +-8.2878179550170898 0.55676698684692383 +-8.2878179550170898 0.35676717758178711 +-8.2878179550170898 0.15676736831665039 +-8.2878179550170898 -0.043232440948486328 +-8.2878179550170898 -0.24323225021362305 +-8.2878179550170898 -0.44323205947875977 +-8.2878179550170898 -0.64323186874389648 +-8.2878179550170898 -0.8432316780090332 +-8.2878179550170898 -1.0432319641113281 +-8.2878179550170898 -1.2432317733764648 +-8.2878179550170898 -1.4432315826416016 +-8.2878179550170898 -1.6432313919067383 +-8.2878179550170898 -1.843231201171875 +-8.2878179550170898 -2.0432310104370117 +-8.2878179550170898 -2.2432308197021484 +-8.2878179550170898 -2.4432306289672852 +-8.2878179550170898 -2.6432304382324219 +-8.2878179550170898 -2.8432302474975586 +-8.2878179550170898 -3.0432300567626953 +-8.2878179550170898 -3.243229866027832 +-8.2878179550170898 -3.4432296752929688 +-8.2878179550170898 -3.6432294845581055 +-8.2878179550170898 -3.8432292938232422 +-8.2878179550170898 -4.0432291030883789 +-8.2878179550170898 -4.2432289123535156 +-8.2878179550170898 -4.4432287216186523 +-8.2878179550170898 -4.6432285308837891 +-8.2878179550170898 -4.8432283401489258 +-8.2878179550170898 -5.0432281494140625 +-8.2878179550170898 -5.2432279586791992 +-8.2878179550170898 -5.4432277679443359 +-8.2878179550170898 -5.6432275772094727 +-8.2878179550170898 -5.8432273864746094 +-8.2878179550170898 -6.0432271957397461 +-8.2878179550170898 -6.2432270050048828 +-8.2878179550170898 -6.4432268142700195 +-8.2878179550170898 -6.6432266235351562 +-8.2878179550170898 -6.843226432800293 +-8.2878179550170898 -7.0432262420654297 +-8.2878179550170898 -7.1534209251403809 +-8.2725563049316406 -7.2539710998535156 +-8.2225713729858398 -7.3458738327026367 +-8.0987958908081055 -7.4347281455993652 +-8.0047931671142578 -7.4536409378051758 +-7.8051013946533203 -7.4647378921508789 +-7.6054096221923828 -7.4758353233337402 +-7.4057173728942871 -7.4869322776794434 +-7.2060256004333496 -7.4980297088623047 +-7.0063338279724121 -7.5091266632080078 +-6.8066415786743164 -7.5202240943908691 +-6.6069498062133789 -7.5313210487365723 +-6.4072580337524414 -7.5424180030822754 +-6.2075657844543457 -7.5535154342651367 +-6.0078740119934082 -7.5646123886108398 +-5.8081817626953125 -7.5757098197937012 +-5.608489990234375 -7.5868067741394043 +-5.4087982177734375 -7.5979042053222656 +-5.2091064453125 -7.6090011596679688 +-5.0094146728515625 -7.6200981140136719 +-4.8097224235534668 -7.6311955451965332 +-4.6100301742553711 -7.6422924995422363 +-4.4103384017944336 -7.6533899307250977 +-4.2106466293334961 -7.6644868850708008 +-4.0109548568725586 -7.6755843162536621 +-3.8112630844116211 -7.6866812705993652 +-3.6115713119506836 -7.6977782249450684 +-3.4118795394897461 -7.7088756561279297 +-3.2121882438659668 -7.7199726104736328 +-3.0124964714050293 -7.7310695648193359 +-2.8128046989440918 -7.7421669960021973 +-2.6131129264831543 -7.7532639503479004 +-2.4134211540222168 -7.7643613815307617 +-2.2137293815612793 -7.7754583358764648 +-2.0140376091003418 -7.7865557670593262 +-1.8143463134765625 -7.7976527214050293 +-1.614654541015625 -7.8087496757507324 +-1.4149627685546875 -7.8198471069335938 +-1.21527099609375 -7.8309440612792969 +-1.0155792236328125 -7.8420414924621582 +-0.815887451171875 -7.8531384468078613 +-0.6161961555480957 -7.8642354011535645 +-0.4165043830871582 -7.8753328323364258 +-0.2168126106262207 -7.8864297866821289 +-0.017120838165283203 -7.8975272178649902 +0.1825714111328125 -7.9086241722106934 +0.38226318359375 -7.9197211265563965 +0.5819549560546875 -7.9308185577392578 +0.781646728515625 -7.9419155120849609 +0.9813385009765625 -7.9530129432678223 +1.1810302734375 -7.9641098976135254 +1.3807210922241211 -7.9752068519592285 +1.5804128646850586 -7.9863042831420898 +1.7801046371459961 -7.997401237487793 +1.9797964096069336 -8.0084981918334961 +2.1794881820678711 -8.0195960998535156 +2.3791799545288086 -8.0306930541992188 +2.5788717269897461 -8.0417900085449219 +2.7785634994506836 -8.052886962890625 +2.9782552719116211 -8.0639839172363281 +3.1779470443725586 -8.0750808715820312 +3.3776388168334961 -8.0861787796020508 +3.5773305892944336 -8.0972757339477539 +3.7770223617553711 -8.108372688293457 +3.9767141342163086 -8.1194696426391602 +4.1764049530029297 -8.1305675506591797 +4.3760967254638672 -8.1416645050048828 +4.5757884979248047 -8.1527614593505859 +4.7754802703857422 -8.1638584136962891 +4.9751720428466797 -8.1749553680419922 +5.1748638153076172 -8.1860523223876953 +5.3745555877685547 -8.1971502304077148 +5.5742473602294922 -8.208247184753418 +5.7739391326904297 -8.2193441390991211 +5.9736309051513672 -8.2304410934448242 +6.1733226776123047 -8.2415390014648438 +6.3730144500732422 -8.2526359558105469 +6.5727062225341797 -8.26373291015625 +6.7723970413208008 -8.2748298645019531 +6.9720888137817383 -8.2859268188476562 +7.1717805862426758 -8.2970237731933594 +7.3714723587036133 -8.3081216812133789 +7.5711641311645508 -8.319218635559082 +7.7708559036254883 -8.3303155899047852 +7.9705476760864258 -8.3414125442504883 +8.1702384948730469 -8.3525104522705078 +8.3699321746826172 -8.3636074066162109 +8.5696239471435547 -8.3747043609619141 +8.769317626953125 -8.3858013153076172 +8.9690093994140625 -8.3968992233276367 +9.1687030792236328 -8.4079961776733398 +9.3683948516845703 -8.419093132019043 +9.5680885314941406 -8.4301900863647461 +9.7677803039550781 -8.4412879943847656 +9.9674739837646484 -8.4523849487304688 +10.167165756225586 -8.4634819030761719 +10.366859436035156 -8.474578857421875 +10.566551208496094 -8.4856767654418945 +10.766242980957031 -8.4967737197875977 +10.965936660766602 -8.5078706741333008 +11.165628433227539 -8.5189676284790039 +11.365322113037109 -8.5300655364990234 +11.565013885498047 -8.5411624908447266 +11.610186576843262 -8.5436725616455078 +11.75560188293457 -8.541447639465332 +11.872749328613281 -8.4889593124389648 +11.953274726867676 -8.3947839736938477 +11.988609313964844 -8.2494831085205078 +11.98805046081543 -6.5400009155273438 +12.289004325866699 -6.5400009155273438 +12.289004325866699 -4.8054819107055664 +12.289004325866699 -4.8054819107055664 +12.289004325866699 4.8054780960083008 diff --git a/tests/fff_print/CMakeLists.txt b/tests/fff_print/CMakeLists.txt index 4cf0826a2c..8c0281efb7 100644 --- a/tests/fff_print/CMakeLists.txt +++ b/tests/fff_print/CMakeLists.txt @@ -19,6 +19,7 @@ add_executable(${_TEST_NAME}_tests test_imex_slice_offset.cpp test_model.cpp test_multifilament.cpp + test_multimaterial_segmentation.cpp test_perimeters.cpp # Seam geometry and pipeline regressions share the existing Print fixtures. test_precise_seam.cpp diff --git a/tests/fff_print/test_multifilament.cpp b/tests/fff_print/test_multifilament.cpp index 1a5b9630c9..6557f64b2e 100644 --- a/tests/fff_print/test_multifilament.cpp +++ b/tests/fff_print/test_multifilament.cpp @@ -315,6 +315,152 @@ TEST_CASE("Per-object wall filament override is honored", "[MultiFilament]") CHECK(tools_for_role(gcode, "infill") == std::set{ 0 }); // infill not overridden: stays on F1 } +// 0-based tool indices extruding under the ";TYPE:" marker of `feature`. +static std::set tools_for_feature(const std::string& gcode, std::string_view feature) +{ + std::set tools; + int current_tool = 0; + bool in_feature = false; + GCodeReader reader; + reader.parse_buffer(gcode, [&](GCodeReader& self, const GCodeReader::GCodeLine& line) { + const std::string cmd(line.cmd()); + if (cmd.size() >= 2 && cmd[0] == 'T' && std::isdigit((unsigned char)cmd[1])) + current_tool = std::stoi(cmd.substr(1)); + else if (cmd.empty() && line.comment().substr(0, 5) == "TYPE:") + in_feature = line.comment().substr(5) == feature; + // Toolchange purges extrude in place under the previous feature's marker. + else if (in_feature && line.extruding(self) && line.dist_XY(self) > 0) + tools.insert(current_tool); + }); + return tools; +} + +// A 20x20mm slab on a 4x4mm pillar: on the slab's first layer both walls are overhangs from end to end, so +// only their wall index tells the inner wall from the outer one. +TEST_CASE("Overhanging inner walls print with the inner wall filament", "[MultiFilament]") +{ + const char *wall_generator = GENERATE("classic", "arachne"); + CAPTURE(wall_generator); + + TriangleMesh mesh = make_cube(4., 4., 5.); + mesh.translate(8.f, 8.f, 0.f); + TriangleMesh slab = make_cube(20., 20., 2.); + slab.translate(0.f, 0.f, 5.f); + mesh.merge(slab); + + const std::string gcode = slice({ mesh }, + multifilament_config(2, { + { "wall_generator", wall_generator }, + { "wall_loops", 2 }, + { "outer_wall_filament_id", 1 }, + { "inner_wall_filament_id", 2 }, + { "sparse_infill_filament_id", 1 }, + { "internal_solid_filament_id", 1 }, + { "top_surface_filament_id", 1 }, + { "bottom_surface_filament_id", 1 }, + { "detect_overhang_wall", true }, + { "extra_perimeters_on_overhangs", false }, + { "enable_support", false }, + { "skirt_loops", 0 }, + { "brim_type", "no_brim" }, + })); + CHECK(tools_for_feature(gcode, "Outer wall") == std::set{ 0 }); + CHECK(tools_for_feature(gcode, "Inner wall") == std::set{ 1 }); + CHECK(tools_for_feature(gcode, "Overhang wall") == std::set{ 0, 1 }); +} + +// Tool changes on a layer after which that tool extrudes nothing before the next tool or layer change. +static int idle_tool_changes(const std::string& gcode) +{ + int idle = 0; + bool in_layers = false, changed = false, extruded = false; + GCodeReader reader; + reader.parse_buffer(gcode, [&](GCodeReader& self, const GCodeReader::GCodeLine& line) { + const std::string cmd(line.cmd()); + const bool tool_change = cmd.size() >= 2 && cmd[0] == 'T' && std::isdigit((unsigned char)cmd[1]); + if (tool_change || line.comment() == "LAYER_CHANGE") { + if (changed && !extruded) + ++idle; + in_layers |= !tool_change; + changed = tool_change && in_layers; + extruded = false; + } else if (line.extruding(self) && line.dist_XY(self) > 0) + extruded = true; + }); + return idle + (changed && !extruded ? 1 : 0); +} + +// The fill of a top or bottom surface carries the gap fill around it, which must not move the surface to the +// internal solid filament, nor leave the surface's own filament scheduled with nothing to print. The round top and +// bottom of a cylinder leave gaps along their edge. +TEST_CASE("Top and bottom surfaces with gap fill print with their filaments", "[MultiFilament]") +{ + const std::string gcode = slice({ make_cylinder(10., 10.) }, + multifilament_config(4, { + { "wall_generator", "arachne" }, + { "gap_fill_target", "topbottom" }, + { "outer_wall_filament_id", 1 }, + { "inner_wall_filament_id", 1 }, + { "sparse_infill_filament_id", 1 }, + { "internal_solid_filament_id", 2 }, + { "top_surface_filament_id", 3 }, + { "bottom_surface_filament_id", 4 }, + { "skirt_loops", 0 }, + { "brim_type", "no_brim" }, + })); + REQUIRE_FALSE(tools_for_feature(gcode, "Gap infill").empty()); + CHECK(tools_for_feature(gcode, "Top surface") == std::set{ 2 }); + CHECK(tools_for_feature(gcode, "Bottom surface") == std::set{ 3 }); + CHECK(idle_tool_changes(gcode) == 0); +} + +// A 1.9mm plate leaves no room for sparse infill between its classic walls, only gap fill, which prints with the walls. +TEST_CASE("Gap fill between walls does not schedule the sparse infill filament", "[MultiFilament]") +{ + const std::string gcode = slice({ make_cube(20., 1.9, 5.) }, + multifilament_config(2, { + { "wall_generator", "classic" }, + { "wall_loops", 2 }, + { "outer_wall_filament_id", 1 }, + { "inner_wall_filament_id", 1 }, + { "sparse_infill_filament_id", 2 }, + { "internal_solid_filament_id", 1 }, + { "top_surface_filament_id", 1 }, + { "bottom_surface_filament_id", 1 }, + { "skirt_loops", 0 }, + { "brim_type", "no_brim" }, + })); + REQUIRE(tools_for_feature(gcode, "Gap infill") == std::set{ 0 }); + CHECK(tools_for_feature(gcode, "Sparse infill").empty()); + CHECK(idle_tool_changes(gcode) == 0); +} + +// A 20x20x2mm base carrying a 0.5mm fin: the fin's layers fit a single wall, so they must not switch to the inner +// wall filament the base uses. +TEST_CASE("A layer without inner walls does not switch to the inner wall filament", "[MultiFilament]") +{ + TriangleMesh mesh = make_cube(20., 20., 2.); + TriangleMesh fin = make_cube(20., 0.5, 5.); + fin.translate(0.f, 9.75f, 2.f); + mesh.merge(fin); + + const std::string gcode = slice({ mesh }, + multifilament_config(2, { + { "wall_generator", "arachne" }, + { "wall_loops", 2 }, + { "outer_wall_filament_id", 1 }, + { "inner_wall_filament_id", 2 }, + { "sparse_infill_filament_id", 1 }, + { "internal_solid_filament_id", 1 }, + { "top_surface_filament_id", 1 }, + { "bottom_surface_filament_id", 1 }, + { "skirt_loops", 0 }, + { "brim_type", "no_brim" }, + })); + CHECK(tools_for_feature(gcode, "Inner wall") == std::set{ 1 }); + CHECK(idle_tool_changes(gcode) == 0); +} + // 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 diff --git a/tests/fff_print/test_multimaterial_segmentation.cpp b/tests/fff_print/test_multimaterial_segmentation.cpp new file mode 100644 index 0000000000..2636d4c44b --- /dev/null +++ b/tests/fff_print/test_multimaterial_segmentation.cpp @@ -0,0 +1,90 @@ +#include +#include +#include + +#include +#include +#include + +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/Layer.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/Print.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libslic3r/TriangleSelector.hpp" +#include "libslic3r/libslic3r.h" + +#include "test_helpers.hpp" + +using namespace Slic3r; + +namespace { + +// Paints the top face of `volume` with filament 2 and its bottom face with filament 3. +void paint_top_and_bottom(ModelVolume &volume) +{ + const TriangleMesh &mesh = volume.mesh(); + const BoundingBoxf3 bbox = mesh.bounding_box(); + TriangleSelector selector(mesh); + for (int i = 0; i < int(mesh.its.indices.size()); ++i) { + bool top = true, bottom = true; + for (int j = 0; j < 3; ++j) { + const double z = mesh.its.vertices[mesh.its.indices[i][j]].z(); + top = top && std::abs(z - bbox.max.z()) < EPSILON; + bottom = bottom && std::abs(z - bbox.min.z()) < EPSILON; + } + if (top) + selector.set_facet(i, EnforcerBlockerType::Extruder2); + else if (bottom) + selector.set_facet(i, EnforcerBlockerType::Extruder3); + } + REQUIRE(volume.mmu_segmentation_facets.set(selector)); +} + +size_t layers_with_filament(const PrintObject &object, int filament_id) +{ + size_t count = 0; + for (const Layer *layer : object.layers()) + for (const LayerRegion *region : layer->regions()) + if (region->region().config().outer_wall_filament_id.value == filament_id && !region->slices.empty()) { + ++count; + break; + } + return count; +} + +} // namespace + +TEST_CASE("Painted top and bottom surfaces color their paint penetration layers", "[MultiMaterialSegmentation]") +{ + // 0 follows the shell layers; other values apply as set, below or above the shell. + const auto [top_penetration, bottom_penetration, expected_top, expected_bottom] = + GENERATE(table({{0, 0, 5, 4}, {2, 3, 2, 3}, {7, 6, 7, 6}})); + CAPTURE(top_penetration, bottom_penetration); + + // A 4 mm cube at 0.2 mm layers has 20 layers, enough to keep the top and bottom bands apart. + DynamicPrintConfig config = Test::multifilament_config(3, { + {"layer_height", "0.2"}, + {"initial_layer_print_height", "0.2"}, + {"top_shell_layers", "5"}, + {"bottom_shell_layers", "4"}, + {"top_color_penetration_layers", std::to_string(top_penetration)}, + {"bottom_color_penetration_layers", std::to_string(bottom_penetration)}, + {"gcode_comments", "1"}, // Match init_print so the second apply changes only the model. + }); + + Print print; + Model model; + Test::init_print({TriangleMesh(its_make_cube(20, 20, 4))}, print, model, config); + paint_top_and_bottom(*model.objects.front()->volumes.front()); + print.apply(model, config); + + REQUIRE(print.objects().size() == 1); + PrintObject &object = *print.get_object(0); + object.slice(); + REQUIRE(object.layers().size() == 20); + + CHECK(layers_with_filament(object, 2) == expected_top); + CHECK(layers_with_filament(object, 3) == expected_bottom); +} diff --git a/tests/fff_print/test_seam_placer.cpp b/tests/fff_print/test_seam_placer.cpp index 3aea296fc7..594b461a25 100644 --- a/tests/fff_print/test_seam_placer.cpp +++ b/tests/fff_print/test_seam_placer.cpp @@ -7,11 +7,14 @@ #include #include "test_helpers.hpp" #include "libslic3r/GCode/SeamPlacer.hpp" +#include "libslic3r/GCode/SeamContour.hpp" #include "libslic3r/Layer.hpp" #include "libslic3r/TriangleSelector.hpp" #include #include +#include +#include #include "libslic3r/Model.hpp" #include "libslic3r/PrintConfig.hpp" #include "libslic3r/TriangleMesh.hpp" @@ -35,9 +38,9 @@ struct PipelineFixture { Print print; DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); - explicit PipelineFixture(bool trapezoid = false) + explicit PipelineFixture(bool trapezoid = false, float height = 0.4f) { - auto mesh = its_make_cube(20, 20, 0.4); + auto mesh = its_make_cube(20, 20, height); if (trapezoid) { // Opposite painted sides have deliberately different lengths: 20 mm and 6 mm. for (auto &vertex : mesh.vertices) @@ -105,24 +108,32 @@ struct PipelineFixture { } }; -void append_loop(LayerRegion ®ion, Points points, bool separate_paths = false) +// Wall loop of the given role, as one path or one path per edge; inset_idx is set the way the perimeter generators do. +ExtrusionLoop make_loop(Points points, ExtrusionRole role, int inset_idx, bool separate_paths = false) { - // Inject deterministic external loops while keeping the real layer, region and paint-query machinery. REQUIRE(points.size() >= 3); points.push_back(points.front()); ExtrusionPaths paths; if (separate_paths) { for (size_t i = 1; i < points.size(); ++i) { - ExtrusionPath path(erExternalPerimeter, 0.08, 0.4f, 0.2f); + ExtrusionPath path(role, 0.08, 0.4f, 0.2f); path.polyline = Polyline3(Polyline(Points{points[i - 1], points[i]})); paths.push_back(std::move(path)); } } else { - ExtrusionPath path(erExternalPerimeter, 0.08, 0.4f, 0.2f); + ExtrusionPath path(role, 0.08, 0.4f, 0.2f); path.polyline = Polyline3(Polyline(std::move(points))); paths.push_back(std::move(path)); } - region.perimeters.append(ExtrusionLoop(std::move(paths))); + ExtrusionLoop loop(std::move(paths)); + loop.inset_idx = inset_idx; + return loop; +} + +void append_loop(LayerRegion ®ion, Points points, bool separate_paths = false) +{ + // Inject deterministic external loops while keeping the real layer, region and paint-query machinery. + region.perimeters.append(make_loop(std::move(points), erExternalPerimeter, -1, separate_paths)); } LayerRegion &clear_first_layer(PrintObject &object) @@ -131,8 +142,91 @@ LayerRegion &clear_first_layer(PrintObject &object) for (LayerRegion *region : layer.regions()) region->perimeters.clear(); return *layer.get_region(0); } + +// Replaces the perimeters of every layer with one external loop through outline(layer index). +template void set_loop_on_every_layer(PrintObject &object, Outline &&outline) +{ + for (size_t i = 0; i < object.layers().size(); ++i) { + Layer &layer = *object.layers()[i]; + for (LayerRegion *region : layer.regions()) region->perimeters.clear(); + append_loop(*layer.get_region(0), outline(i)); + } +} + +// Start of each layer's loop after the seam is placed, in unscaled XY. +std::vector placed_seams(const SeamPlacer &placer, const PrintObject &object) +{ + std::vector starts; + for (const Layer *layer : object.layers()) { + const auto *loop = dynamic_cast(layer->get_region(0)->perimeters.entities.front()); + REQUIRE(loop != nullptr); + ExtrusionLoop copy = *loop; + float overhang = 0.0f; + placer.place_seam(layer, copy, Point(0, 0), overhang); + starts.push_back(unscale(copy.first_point())); + } + return starts; +} + +using SeamType = SeamPlacerImpl::EnforcedBlockedSeamPoint; + +// Seam candidates of one loop through xy at z = 0; Neutral with angle 0 unless given. The loop starts at +// `offset`, after candidates of another loop. +std::vector loop_candidates(SeamPlacerImpl::Perimeter &perimeter, const std::vector &xy, + const std::vector &types = {}, + const std::vector &angles = {}, size_t offset = 0) +{ + static SeamPlacerImpl::Perimeter other; + perimeter.start_index = offset; + perimeter.end_index = offset + xy.size(); + std::vector points; + points.reserve(offset + xy.size()); + for (size_t i = 0; i < offset; ++i) + points.emplace_back(Vec3f(100.0f + float(i), 100.0f, 0.0f), other, 0.0f, SeamType::Enforced); + for (size_t i = 0; i < xy.size(); ++i) + points.emplace_back(Vec3f(float(xy[i].x()), float(xy[i].y()), 0.0f), perimeter, angles.empty() ? 0.0f : angles[i], + types.empty() ? SeamType::Neutral : types[i]); + return points; +} + +Vec2d placed_xy(const std::vector &points, size_t index, const Vec2d &target) +{ + return SeamPlacerImpl::place_on_loop(points, index, Vec3f(float(target.x()), float(target.y()), 0.0f)) + .head<2>() + .cast(); +} } // namespace +TEST_CASE("Paint proximity beyond painted facet heights remains a soft seam preference", "[SeamPlacer][Regression]") +{ + PipelineFixture fixture; + auto &volume = *fixture.model.objects.front()->volumes.front(); + const auto &mesh = volume.mesh(); + const double bottom = mesh.bounding_box().min.z(); + TriangleSelector selector(mesh); + // Only paint below the slicing plane: intersecting side paint exercises the separate exact-range tests. + for (size_t i = 0; i < mesh.its.indices.size(); ++i) { + const auto &face = mesh.its.indices[i]; + bool on_bottom = true; + for (int j = 0; j < 3; ++j) + on_bottom = on_bottom && std::abs(mesh.its.vertices[face[j]].z() - bottom) < 1e-6; + if (on_bottom) selector.set_facet(int(i), EnforcerBlockerType::ENFORCER); + } + volume.seam_facets.set(selector); + fixture.print.apply(fixture.model, fixture.config); + PrintObject &object = fixture.prepare(); + auto ®ion = clear_first_layer(object); + append_loop(region, fixture.points_in_layer(object, {{0, 0}, {20, 0}, {20, 20}, {0, 20}})); + SeamPlacer placer; + placer.init(fixture.print, [] {}); + const auto &data = placer.m_seam_per_object.at(&object).layers.front(); + REQUIRE(data.perimeters.size() == 1); + // The horizontal painted face is below the slice, but the old paint-radius test still marks candidates. + CHECK(std::count_if(data.points.begin(), data.points.end(), [](const auto &point) { + return point.type == SeamPlacerImpl::EnforcedBlockedSeamPoint::Enforced; + }) > 0); +} + TEST_CASE("Painted seams prefer the longer candidate patch regardless of contour origin", "[SeamPlacer][Regression]") { const bool clockwise = GENERATE(false, true); @@ -193,24 +287,785 @@ TEST_CASE("Painted seams prefer the longer candidate patch regardless of contour CHECK(centers == 1); // The old wrapped-length formula instead selected the short top patch. } -TEST_CASE("Entirely painted contours keep valid enforced seam candidates", "[SeamPlacer]") +TEST_CASE("Full surface paint preserves unpainted candidates and placed seams", "[SeamPlacer][Regression]") { - PipelineFixture fixture; - fixture.paint(true); + const std::string mode = GENERATE("back", "aligned", "random"); + const bool bevel = GENERATE(false, true); + CAPTURE(mode, bevel); + std::vector> expected_candidates; + std::vector expected_seams; + for (const bool painted : {false, true}) { + PipelineFixture fixture(false, 2.0f); + fixture.config.set_deserialize_strict("seam_position", mode); + if (painted) fixture.paint(true); + fixture.print.apply(fixture.model, fixture.config); // Apply the requested seam mode in both comparisons. + PrintObject &object = fixture.prepare(); + const std::vector outline = bevel ? + std::vector{{0, 1}, {1, 0}, {19, 0}, {20, 1}, {20, 19}, {19, 20}, {1, 20}, {0, 19}} : + std::vector{{0, 0}, {20, 0}, {20, 20}, {0, 20}}; + set_loop_on_every_layer(object, [&](size_t) { return fixture.points_in_layer(object, outline); }); + SeamPlacer placer; + placer.init(fixture.print, [] {}); + const auto &layers = placer.m_seam_per_object.at(&object).layers; + if (!painted) { + for (const auto &layer : layers) { + std::vector positions; + for (const auto &candidate : layer.points) positions.push_back(candidate.position); + expected_candidates.push_back(std::move(positions)); + } + expected_seams = placed_seams(placer, object); + } else { + REQUIRE(layers.size() == expected_candidates.size()); + for (size_t i = 0; i < layers.size(); ++i) { + // Equality of candidates catches paint oversampling even when a sharp seam happens to match. + REQUIRE(layers[i].points.size() == expected_candidates[i].size()); + for (size_t j = 0; j < layers[i].points.size(); ++j) { + const auto &candidate = layers[i].points[j]; + CHECK(candidate.type == SeamType::Neutral); + CHECK_FALSE(candidate.central_enforcer); + CHECK_THAT(double((candidate.position - expected_candidates[i][j]).norm()), + Catch::Matchers::WithinAbs(0.0, 1e-6)); + } + } + const auto actual = placed_seams(placer, object); + REQUIRE(actual.size() == expected_seams.size()); + for (size_t i = 0; i < actual.size(); ++i) + CHECK_THAT((actual[i] - expected_seams[i]).norm(), Catch::Matchers::WithinAbs(0.0, 1e-6)); + } + } +} + +TEST_CASE("Full surface paint preserves strong Precise Seam positions", "[SeamPlacer][PreciseSeam][Regression]") +{ + std::vector expected; + for (const bool painted : {false, true}) { + PipelineFixture fixture(false, 2.0f); + fixture.config.set_deserialize_strict("seam_position", "aligned"); + if (painted) fixture.paint(true); + auto *part = fixture.model.objects.front()->volumes.front(); + const Vec3d center = part->get_matrix() * (part->mesh().bounding_box().min + Vec3d(10, 0, 1)); + auto *helper = fixture.model.objects.front()->add_volume(make_cube(4, 4, 4)); + helper->set_type(ModelVolumeType::PRECISE_SEAM_CENTER); + helper->set_offset(center); // Cross the front side without adding another printing surface. + fixture.print.apply(fixture.model, fixture.config); + PrintObject &object = fixture.prepare(); + set_loop_on_every_layer(object, [&](size_t) { + return fixture.points_in_layer(object, {{0, 0}, {20, 0}, {20, 20}, {0, 20}}); + }); + SeamPlacer placer; + placer.init(fixture.print, [] {}); + for (const auto &layer : placer.m_seam_per_object.at(&object).layers) { + REQUIRE(layer.perimeters.size() == 1); + const auto &perimeter = layer.perimeters.front(); + REQUIRE(perimeter.precise_seam_point.has_value()); + // Strong placement stays exact. + CHECK_THAT(double((perimeter.final_seam_position - *perimeter.precise_seam_point).norm()), + Catch::Matchers::WithinAbs(0.0, 1e-6)); + } + const auto actual = placed_seams(placer, object); + if (!painted) expected = actual; + else { + REQUIRE(actual.size() == expected.size()); + for (size_t i = 0; i < actual.size(); ++i) + CHECK_THAT((actual[i] - expected[i]).norm(), Catch::Matchers::WithinAbs(0.0, 1e-6)); + } + } +} + +TEST_CASE("Complete side-wall paint is neutral away from unpainted caps", "[SeamPlacer][Regression]") +{ + PipelineFixture fixture(false, 2.0f); + auto &volume = *fixture.model.objects.front()->volumes.front(); + const auto &mesh = volume.mesh(); + TriangleSelector selector(mesh); + for (size_t i = 0; i < mesh.its.indices.size(); ++i) { + const auto &face = mesh.its.indices[i]; + const auto &a = mesh.its.vertices[face[0]], &b = mesh.its.vertices[face[1]], &c = mesh.its.vertices[face[2]]; + if (std::abs((b - a).cross(c - a).z()) < 1e-6) + selector.set_facet(int(i), EnforcerBlockerType::ENFORCER); // Keep the top and bottom gray. + } + volume.seam_facets.set(selector); + fixture.print.apply(fixture.model, fixture.config); + PrintObject &object = fixture.prepare(); + set_loop_on_every_layer(object, [&](size_t) { + return fixture.points_in_layer(object, {{0, 0}, {20, 0}, {20, 20}, {0, 20}}); + }); + SeamPlacer placer; + placer.init(fixture.print, [] {}); + const auto &layers = placer.m_seam_per_object.at(&object).layers; + REQUIRE(layers.size() == 10); + for (const auto &candidate : layers[4].points) CHECK(candidate.type == SeamType::Neutral); + // Near a gray cap the proof is intentionally conservative and retains the old paint semantics. + CHECK(std::any_of(layers.front().points.begin(), layers.front().points.end(), [](const auto &candidate) { + return candidate.type == SeamType::Enforced; + })); +} + +TEST_CASE("A nearby gray or blocked facet prevents full-green normalization", "[SeamPlacer][Regression]") +{ + const auto other = GENERATE(EnforcerBlockerType::NONE, EnforcerBlockerType::BLOCKER); + PipelineFixture fixture(false, 2.0f); + auto &volume = *fixture.model.objects.front()->volumes.front(); + const auto &mesh = volume.mesh(); + const float front = mesh.bounding_box().min.y(); + TriangleSelector selector(mesh); + bool changed = false; + for (size_t i = 0; i < mesh.its.indices.size(); ++i) { + selector.set_facet(int(i), EnforcerBlockerType::ENFORCER); + const auto &face = mesh.its.indices[i]; + if (!changed && std::abs(mesh.its.vertices[face[0]].y() - front) < 1e-6 && + std::abs(mesh.its.vertices[face[1]].y() - front) < 1e-6 && + std::abs(mesh.its.vertices[face[2]].y() - front) < 1e-6) { + selector.set_facet(int(i), other); // Vertices may still see neighboring green facets within line width. + changed = true; + } + } + REQUIRE(changed); + volume.seam_facets.set(selector); + fixture.print.apply(fixture.model, fixture.config); PrintObject &object = fixture.prepare(); auto ®ion = clear_first_layer(object); append_loop(region, fixture.points_in_layer(object, {{0, 0}, {20, 0}, {20, 20}, {0, 20}})); SeamPlacer placer; placer.init(fixture.print, [] {}); + const auto &points = placer.m_seam_per_object.at(&object).layers.front().points; + CHECK(std::any_of(points.begin(), points.end(), [](const auto &candidate) { return candidate.type == SeamType::Enforced; })); + if (other == EnforcerBlockerType::BLOCKER) + CHECK(std::any_of(points.begin(), points.end(), [](const auto &candidate) { return candidate.type == SeamType::Blocked; })); +} + +TEST_CASE("Painted seams run smoothly along a smooth contour", "[SeamPlacer][Regression]") +{ + // 10 layers of 0.2 mm: enough for the seams to be aligned as one string. + PipelineFixture fixture(false, 2.0f); + fixture.paint(false); + PrintObject &object = fixture.prepare(); + REQUIRE(object.layers().size() == 10); + // A circle of radius 6 mm touching the painted front face only near its lowest point. Its vertices + // rotate by an irregular fraction of a vertex step on every layer, so the candidates differ between layers. + const Vec2d center(10.0, 6.2); + const double radius = 6.0; + const size_t vertex_count = 120; + const double vertex_step = 2.0 * PI / double(vertex_count); + const double phases[] = {0.0, 0.62, 0.21, 0.87, 0.40, 0.05, 0.73, 0.31, 0.94, 0.18}; + set_loop_on_every_layer(object, [&](size_t layer) { + std::vector xy; + const double phase = phases[layer] * vertex_step; + for (size_t i = 0; i < vertex_count; ++i) { + const double angle = phase + vertex_step * double(i); + xy.emplace_back(center + radius * Vec2d(std::cos(angle), std::sin(angle))); + } + return fixture.points_in_layer(object, xy); + }); + SeamPlacer placer; + placer.init(fixture.print, [] {}); + + const Vec2d placed_center = unscale(fixture.points_in_layer(object, {center}).front()); + const std::vector seams = placed_seams(placer, object); + std::vector along; // Seam position along the loop, mm. + for (size_t i = 0; i < seams.size(); ++i) { + const Vec2d offset = seams[i] - placed_center; + const double angle = std::atan2(offset.y(), offset.x()); + CAPTURE(i, seams[i].x(), seams[i].y()); + // The seam stays near the lowest point, where the circle meets the painted face (+-0.3 rad). + CHECK_THAT(angle, Catch::Matchers::WithinAbs(-PI / 2.0, 0.3)); + along.push_back(radius * angle); + } + // The seam line may lean with the curve fitted to the candidates, but must neither step nor kink between + // layers. The scale is the candidate spacing near paint: a 0.4 pull toward the candidate passes at least + // 0.4 of it into the seam, while the step must stay below a quarter of it and its change below 0.15 of it. + const double spacing = SeamPlacer::enforcer_oversampling_distance; + for (size_t i = 1; i < along.size(); ++i) { + CAPTURE(i, along[i - 1], along[i]); + CHECK_THAT(along[i] - along[i - 1], Catch::Matchers::WithinAbs(0.0, 0.25 * spacing)); + } + for (size_t i = 1; i + 1 < along.size(); ++i) { + CAPTURE(i, along[i - 1], along[i], along[i + 1]); + CHECK_THAT(along[i + 1] - 2.0 * along[i] + along[i - 1], Catch::Matchers::WithinAbs(0.0, 0.15 * spacing)); + } +} + +TEST_CASE("Seam strings leave out no layer below their start", "[SeamPlacer][Regression]") +{ + // 41 layers of 0.2 mm with one square each. Painting the top face enforces the candidates of the top + // two layers only (paint radius 0.4 mm), so the aligned string starts at layer 39, the first of them. + // Layer 40 is a small square in the middle, out of reach of layer 39's seam, so the string cannot + // continue upward and turns down from layer 39. The string is long enough that alignment tries only + // some alternative starts, so a layer skipped when turning down stays out of it. + PipelineFixture fixture(false, 8.2f); + { + auto &volume = *fixture.model.objects.front()->volumes.front(); + const auto &mesh = volume.mesh(); + const double top = mesh.bounding_box().max.z(); + TriangleSelector selector(mesh); + for (size_t i = 0; i < mesh.its.indices.size(); ++i) { + bool on_top = true; + for (int j = 0; j < 3; ++j) + on_top = on_top && std::abs(double(mesh.its.vertices[mesh.its.indices[i][j]].z()) - top) < 1e-6; + if (on_top) + selector.set_facet(int(i), EnforcerBlockerType::ENFORCER); + } + volume.seam_facets.set(selector); + fixture.print.apply(fixture.model, fixture.config); + } + PrintObject &object = fixture.prepare(); + REQUIRE(object.layers().size() == 41); + set_loop_on_every_layer(object, [&](size_t layer) { + if (layer == 40) + return fixture.points_in_layer(object, {{9, 9}, {11, 9}, {11, 11}, {9, 11}}); + return fixture.points_in_layer(object, {{0, 0}, {20, 0}, {20, 20}, {0, 20}}); + }); + SeamPlacer placer; + placer.init(fixture.print, [] {}); + const auto &layers = placer.m_seam_per_object.at(&object).layers; + // Layer 0 is left out: with no layer below, its own seam differs and it does not join the string here. + for (size_t i = 1; i <= 39; ++i) { + CAPTURE(i); + REQUIRE(layers[i].perimeters.size() == 1); + CHECK(layers[i].perimeters.front().finalized); + } +} + +TEST_CASE("Painted seams stay at a corner of the painted side", "[SeamPlacer]") +{ + const std::string mode = GENERATE("back", "aligned"); + CAPTURE(mode); + PipelineFixture fixture(false, 2.0f); + fixture.config.set_deserialize_strict("seam_position", mode); + fixture.paint(false); + PrintObject &object = fixture.prepare(); + const std::vector square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}}; + set_loop_on_every_layer(object, [&](size_t) { return fixture.points_in_layer(object, square); }); + SeamPlacer placer; + placer.init(fixture.print, [] {}); + + const Points corners = fixture.points_in_layer(object, square); + for (const Vec2d &seam : placed_seams(placer, object)) { + double nearest = std::numeric_limits::max(); + for (const Point &corner : corners) + nearest = std::min(nearest, (unscale(corner) - seam).norm()); + CAPTURE(seam.x(), seam.y()); + // Painted sides are y = 0 and y = 20; candidates of the side walls are painted up to the 0.4 mm + // line width from them, so the seam lies on a painted corner or within that width of it. + CHECK(nearest <= 0.45); + } +} + +namespace { +// Paints the front face (lowest y) of the fixture's box only. +void paint_front_face(PipelineFixture &fixture, EnforcerBlockerType type = EnforcerBlockerType::ENFORCER) +{ + auto &volume = *fixture.model.objects.front()->volumes.front(); + const auto &mesh = volume.mesh(); + const double front = mesh.bounding_box().min.y(); + TriangleSelector selector(mesh); + for (size_t i = 0; i < mesh.its.indices.size(); ++i) { + bool on_front = true; + for (int j = 0; j < 3; ++j) + on_front = on_front && std::abs(double(mesh.its.vertices[mesh.its.indices[i][j]].y()) - front) < 1e-6; + if (on_front) + selector.set_facet(int(i), type); + } + volume.seam_facets.set(selector); + fixture.print.apply(fixture.model, fixture.config); +} +} // namespace + +TEST_CASE("Painted ranges end exactly where the paint contour crosses the layer", "[SeamPlacer][Regression]") +{ + // The front face spans x 0..20; the loop runs 0.2 mm in front of it from x = -5 to 25. Points within the + // 0.4 mm line width of the paint used to be Enforced up to about 0.35 mm past the face, and only from the + // vertex before the face, so the middle candidate was off the middle of the face. + PipelineFixture fixture; + paint_front_face(fixture); + PrintObject &object = fixture.prepare(); + auto ®ion = clear_first_layer(object); + append_loop(region, fixture.points_in_layer(object, {{-5, 0.2}, {-0.3, 0.2}, {25, 0.2}, {25, 10}, {-5, 10}})); + SeamPlacer placer; + placer.init(fixture.print, [] {}); + const auto &data = placer.m_seam_per_object.at(&object).layers.front(); + REQUIRE(data.perimeters.size() == 1); + CHECK(data.perimeters.front().exact_enforced_ends); + + const auto face = fixture.points_in_layer(object, {{0, 0.2}, {20, 0.2}, {10, 0.2}}); + double first = std::numeric_limits::max(), last = std::numeric_limits::lowest(); + size_t centers = 0; + for (const auto &candidate : data.points) { + if (candidate.type != SeamType::Enforced) + continue; + first = std::min(first, double(candidate.position.x())); + last = std::max(last, double(candidate.position.x())); + if (candidate.central_enforcer) { + ++centers; + CHECK((candidate.position.head<2>().cast() - unscale(face[2])).norm() < 1e-3); + } + } + CHECK_THAT(first, Catch::Matchers::WithinAbs(unscale(face[0].x()), 1e-3)); + CHECK_THAT(last, Catch::Matchers::WithinAbs(unscale(face[1].x()), 1e-3)); + CHECK(centers == 1); +} + +TEST_CASE("Exact paint ends do not depend on where the loop starts", "[SeamPlacer][Regression]") +{ + // The paint ends project onto the front corners of the loop. A loop repeats its first point, so at its + // first vertex the edge behind it has zero length; origin 0 puts the end with paint behind it there. + const int origin = GENERATE(0, 1, 2, 3); + CAPTURE(origin); + PipelineFixture fixture; + paint_front_face(fixture); + PrintObject &object = fixture.prepare(); + auto ®ion = clear_first_layer(object); + auto outline = fixture.points_in_layer(object, {{19.8, 0.2}, {19.8, 19.8}, {0.2, 19.8}, {0.2, 0.2}}); + std::rotate(outline.begin(), outline.begin() + origin, outline.end()); + append_loop(region, std::move(outline)); + SeamPlacer placer; + placer.init(fixture.print, [] {}); + const auto &data = placer.m_seam_per_object.at(&object).layers.front(); + REQUIRE(data.perimeters.size() == 1); + CHECK(data.perimeters.front().exact_enforced_ends); + + const auto corners = fixture.points_in_layer(object, {{0.2, 0.2}, {19.8, 0.2}}); + double first = std::numeric_limits::max(), last = std::numeric_limits::lowest(); + for (const auto &candidate : data.points) { + if (candidate.type != SeamType::Enforced) + continue; + CHECK_THAT(double(candidate.position.y()), Catch::Matchers::WithinAbs(unscale(corners[0].y()), 1e-3)); + first = std::min(first, double(candidate.position.x())); + last = std::max(last, double(candidate.position.x())); + } + CHECK_THAT(first, Catch::Matchers::WithinAbs(unscale(corners[0].x()), 1e-3)); + CHECK_THAT(last, Catch::Matchers::WithinAbs(unscale(corners[1].x()), 1e-3)); +} + +TEST_CASE("Random seams stay inside exact green ranges and keep varying", "[SeamPlacer][Regression]") +{ + const int origin = GENERATE(0, 1, 2); + const bool partial_blocker = GENERATE(false, true); + CAPTURE(origin, partial_blocker); + // One hundred layers exercise the outgoing edge of the last green sample at many random offsets. + PipelineFixture fixture(false, 20.0f); + fixture.config.set_deserialize_strict("seam_position", "random"); + paint_front_face(fixture); + if (partial_blocker) { + const auto *part = fixture.model.objects.front()->volumes.front(); + const Vec3d center = part->get_matrix() * (part->mesh().bounding_box().min + Vec3d(10, 0, 10)); + auto *modifier = fixture.model.objects.front()->add_volume(make_cube(4, 4, 22)); + modifier->set_type(ModelVolumeType::PRECISE_SEAM_BLOCKED); + modifier->set_offset(center); // Block x = 8..12 on the green face, throughout the object's height. + fixture.print.apply(fixture.model, fixture.config); + } + PrintObject &object = fixture.prepare(); + REQUIRE(object.layers().size() == 100); + set_loop_on_every_layer(object, [&](size_t) { + auto outline = fixture.points_in_layer(object, {{-5, 0.2}, {10, 0.2}, {25, 0.2}, {25, 10}, {-5, 10}}); + // Origin 1 wraps the green range; origin 2 tests its closing edge after modifier normalization. + std::rotate(outline.begin(), outline.begin() + origin, outline.end()); + return outline; + }); + SeamPlacer placer; + placer.init(fixture.print, [] {}); + for (const auto &layer : placer.m_seam_per_object.at(&object).layers) { + REQUIRE(layer.perimeters.size() == 1); + CHECK(layer.perimeters.front().exact_enforced_ends); + if (origin == 2 && partial_blocker) { + const auto &perimeter = layer.perimeters.front(); + // Modifiers remove the repeated loop endpoint, exposing the Enforced-to-Neutral closing edge. + CHECK(layer.points[perimeter.end_index - 1].type == SeamType::Enforced); + CHECK(layer.points[perimeter.start_index].type == SeamType::Neutral); + } + if (partial_blocker) + CHECK(std::any_of(layer.points.begin(), layer.points.end(), [](const auto &candidate) { + return candidate.type == SeamType::Blocked; + })); + } + const auto bounds = fixture.points_in_layer(object, {{0, 0.2}, {20, 0.2}, {8, 0.2}, {12, 0.2}}); + const Vec2d first = unscale(bounds[0]), last = unscale(bounds[1]); + const double blocked_begin = unscale(bounds[2].x()), blocked_end = unscale(bounds[3].x()); + double min_x = std::numeric_limits::max(), max_x = std::numeric_limits::lowest(); + // Check the actual split loop start: an Enforced candidate alone does not constrain Random's edge. + for (const Vec2d &seam : placed_seams(placer, object)) { + CAPTURE(seam.x(), seam.y()); + CHECK_THAT(seam.y(), Catch::Matchers::WithinAbs(first.y(), 1e-3)); + CHECK(seam.x() >= first.x() - 1e-3); + CHECK(seam.x() <= last.x() + 1e-3); + if (partial_blocker) { + const bool inside_blocker = seam.x() > blocked_begin + 1e-3 && seam.x() < blocked_end - 1e-3; + CHECK_FALSE(inside_blocker); + } + min_x = std::min(min_x, seam.x()); + max_x = std::max(max_x, seam.x()); + } + CHECK(max_x - min_x > 1.0); // Reject a false fix that pins every layer to one green endpoint. +} + +TEST_CASE("Projected paint boundaries do not color a distant contour detour", "[SeamPlacer][Regression]") +{ + const auto paint = GENERATE(EnforcerBlockerType::ENFORCER, EnforcerBlockerType::BLOCKER); + PipelineFixture fixture; + paint_front_face(fixture, paint); + PrintObject &object = fixture.prepare(); + auto ®ion = clear_first_layer(object); + // The projected ends span x=0..20, but the middle of this contour leaves the painted front face. + append_loop(region, fixture.points_in_layer(object, + {{-5, 0.2}, {5, 0.2}, {5, 10}, {15, 10}, {15, 0.2}, {25, 0.2}, {25, 15}, {-5, 15}})); + SeamPlacer placer; + placer.init(fixture.print, [] {}); const auto &data = placer.m_seam_per_object.at(&object).layers.front(); REQUIRE(data.perimeters.size() == 1); const auto &perimeter = data.perimeters.front(); - CHECK(perimeter.seam_index >= perimeter.start_index); - CHECK(perimeter.seam_index < perimeter.end_index); - for (const auto &candidate : data.points) { - CHECK(candidate.type == SeamPlacerImpl::EnforcedBlockedSeamPoint::Enforced); - CHECK_FALSE(candidate.central_enforcer); // There is no bounded patch to mark as central. + CHECK((paint == EnforcerBlockerType::ENFORCER ? perimeter.exact_enforced_ends : perimeter.exact_blocked_ends)); + const auto gray = fixture.points_in_layer(object, {{5, 10}, {15, 10}}); + for (const auto &point : gray) { + const auto position = unscale(point); + const auto candidate = std::find_if(data.points.begin(), data.points.end(), [&](const SeamPlacerImpl::SeamCandidate &p) { + return (p.position.head<2>().cast() - position).norm() < 1e-3; + }); + REQUIRE(candidate != data.points.end()); + CHECK(candidate->type == SeamType::Neutral); } + const auto expected = paint == EnforcerBlockerType::ENFORCER ? SeamType::Enforced : SeamType::Blocked; + CHECK(std::any_of(data.points.begin(), data.points.end(), [&](const auto &p) { return p.type == expected; })); +} + +TEST_CASE("Aligned painted seams follow the middle of the painted band", "[SeamPlacer][Regression]") +{ + // 10 layers with the loop of the previous test; the vertex before the face moves on every layer, which + // used to move the middle candidate and with it the seam. + PipelineFixture fixture(false, 2.0f); + fixture.config.set_deserialize_strict("seam_position", "aligned"); + paint_front_face(fixture); + PrintObject &object = fixture.prepare(); + REQUIRE(object.layers().size() == 10); + set_loop_on_every_layer(object, [&](size_t layer) { + const double before = -0.05 - 0.04 * double(layer); + return fixture.points_in_layer(object, {{-5, 0.2}, {before, 0.2}, {25, 0.2}, {25, 10}, {-5, 10}}); + }); + SeamPlacer placer; + placer.init(fixture.print, [] {}); + + const Vec2d middle = unscale(fixture.points_in_layer(object, {{10, 0.2}}).front()); + for (const Vec2d &seam : placed_seams(placer, object)) { + CAPTURE(seam.x(), seam.y()); + CHECK((seam - middle).norm() < 1e-3); + } +} + +TEST_CASE("Red paint blocks its exact range without blocking the nearby gray contour", "[SeamPlacer][Regression]") +{ + const bool reverse = GENERATE(false, true); + const bool wrap = GENERATE(false, true); + PipelineFixture fixture; + paint_front_face(fixture, EnforcerBlockerType::BLOCKER); + PrintObject &object = fixture.prepare(); + auto outline = fixture.points_in_layer(object, {{-5, 0.2}, {-0.1, 0.2}, {10, 0.2}, {20.1, 0.2}, + {25, 0.2}, {25, 10}, {-5, 10}}); + if (wrap) std::rotate(outline.begin(), outline.begin() + 2, outline.end()); // Red range crosses the loop origin. + if (reverse) std::reverse(outline.begin(), outline.end()); + append_loop(clear_first_layer(object), std::move(outline)); + SeamPlacer placer; + placer.init(fixture.print, [] {}); + const auto &data = placer.m_seam_per_object.at(&object).layers.front(); + REQUIRE(data.perimeters.size() == 1); + CHECK(data.perimeters.front().exact_blocked_ends); + const auto front = fixture.points_in_layer(object, {{0, 0.2}, {20, 0.2}, {-0.1, 0.2}, {20.1, 0.2}}); + const double lower = unscale(front[0].x()), upper = unscale(front[1].x()); + std::vector gray_near_edge(2, false); + double blocked_min = std::numeric_limits::max(), blocked_max = -blocked_min; + for (size_t i = 0; i < data.points.size(); ++i) { + const auto &candidate = data.points[i]; + const double x = candidate.position.x(); + if (candidate.type == SeamType::Blocked) { + blocked_min = std::min(blocked_min, x); + blocked_max = std::max(blocked_max, x); + CHECK(x >= lower - 1e-3); + CHECK(x <= upper + 1e-3); + } + for (const size_t index : {size_t(2), size_t(3)}) + if ((candidate.position.head<2>().cast() - unscale(front[index])).norm() < 1e-4) { + gray_near_edge[index - 2] = true; // A closed extrusion can repeat its start vertex. + CHECK(candidate.type == SeamType::Neutral); // Old radius test blocked both of these vertices. + const auto target = Vec3f(float(0.5 * (lower + upper)), candidate.position.y(), candidate.position.z()); + const auto projected = SeamPlacerImpl::place_on_loop(data.points, i, target); + // The normal projection may reach either end of the same permitted gray arc. + const double edge_distance = projected.x() < lower ? lower - projected.x() : projected.x() - upper; + CHECK(edge_distance > 0.0); + CHECK(edge_distance < 3e-3); // The stop follows the actual red edge, not the old gray vertex. + } + } + CHECK(gray_near_edge[0]); + CHECK(gray_near_edge[1]); + CHECK_THAT(blocked_min, Catch::Matchers::WithinAbs(lower, 1e-3)); + CHECK_THAT(blocked_max, Catch::Matchers::WithinAbs(upper, 1e-3)); +} + +TEST_CASE("Seams in every mode stay outside the exact red range", "[SeamPlacer][Regression]") +{ + const std::string mode = GENERATE(std::string("aligned"), std::string("aligned_back"), std::string("back"), + std::string("nearest"), std::string("random")); + PipelineFixture fixture(false, 2.0f); + fixture.config.set_deserialize_strict("seam_position", mode); + paint_front_face(fixture, EnforcerBlockerType::BLOCKER); + PrintObject &object = fixture.prepare(); + set_loop_on_every_layer(object, [&](size_t) { + return fixture.points_in_layer(object, {{-5, 0.2}, {-0.1, 0.2}, {10, 0.2}, {20.1, 0.2}, + {25, 0.2}, {25, 10}, {-5, 10}}); + }); + SeamPlacer placer; + placer.init(fixture.print, [] {}); + const auto front = fixture.points_in_layer(object, {{0, 0.2}, {20, 0.2}}); + const double lower = unscale(front[0].x()), upper = unscale(front[1].x()); + const double y = unscale(front[0].y()); + for (const auto &layer : placer.m_seam_per_object.at(&object).layers) { + const auto &perimeter = layer.perimeters.front(); + const size_t selected = perimeter.seam_index; + CHECK(layer.points[selected].type != SeamType::Blocked); + } + for (const Vec2d &seam : placed_seams(placer, object)) { + const bool inside_red = seam.x() >= lower && seam.x() <= upper && std::abs(seam.y() - y) < 1e-3; + CHECK_FALSE(inside_red); + } +} + +TEST_CASE("Entire red surface retains the existing all-blocked seam fallback", "[SeamPlacer][Regression]") +{ + PipelineFixture fixture; + auto &volume = *fixture.model.objects.front()->volumes.front(); + TriangleSelector selector(volume.mesh()); + for (size_t i = 0; i < volume.mesh().its.indices.size(); ++i) + selector.set_facet(int(i), EnforcerBlockerType::BLOCKER); // No legal gray arc exists. + volume.seam_facets.set(selector); + fixture.print.apply(fixture.model, fixture.config); + PrintObject &object = fixture.prepare(); + set_loop_on_every_layer(object, [&](size_t) { + return fixture.points_in_layer(object, {{0.2, 0.2}, {19.8, 0.2}, {19.8, 19.8}, {0.2, 19.8}}); + }); + SeamPlacer placer; + placer.init(fixture.print, [] {}); + const auto &data = placer.m_seam_per_object.at(&object).layers.front(); + CHECK_FALSE(data.perimeters.front().exact_blocked_ends); + for (const auto &candidate : data.points) CHECK(candidate.type == SeamType::Blocked); + CHECK(placed_seams(placer, object).front().allFinite()); +} + +TEST_CASE("Seams placed on a regular polygon with an even vertex count lie on the ray from its center", "[SeamPlacer]") +{ + const Vec2d center(3.0, -2.0); + const double radius = 5.0; + const size_t count = 24; + const double step = 2.0 * PI / double(count); + std::vector xy; + for (size_t i = 0; i < count; ++i) + xy.emplace_back(center + radius * Vec2d(std::cos((0.3 + double(i)) * step), std::sin((0.3 + double(i)) * step))); + SeamPlacerImpl::Perimeter perimeter; + const auto points = loop_candidates(perimeter, xy); + // Targets inside and outside the loop around vertex 5, placed from two neighboring candidates. + for (const double offset : {-0.1, -0.03, 0.0, 0.05, 0.12}) + for (const double distance : {3.5, 5.0, 6.5}) { + const double angle = (5.3 * step) + offset; + const Vec2d target = center + distance * Vec2d(std::cos(angle), std::sin(angle)); + const Vec2d from_5 = placed_xy(points, 5, target); + const Vec2d from_6 = placed_xy(points, 6, target); + CAPTURE(offset, distance, from_5.x(), from_5.y()); + CHECK_THAT(std::atan2(from_5.y() - center.y(), from_5.x() - center.x()), Catch::Matchers::WithinAbs(angle, 1e-5)); + CHECK((from_5 - center).norm() <= radius + 1e-5); + CHECK((from_5 - center).norm() >= radius * std::cos(step / 2.0) - 1e-5); + CHECK((from_6 - from_5).norm() < 1e-5); + } +} + +TEST_CASE("Seams placed on the loop do not depend on the chosen candidate", "[SeamPlacer]") +{ + // Inserted candidates at (0, 0) and (0.2, 0) on an asymmetric painted contour; a chord around the + // candidate would turn the target's offset across the bottom edge into a move along it. + SeamPlacerImpl::Perimeter perimeter; + const auto points = loop_candidates(perimeter, {{-1, 0}, {0, 0}, {0.2, 0}, {1, 0}, {1, 5}, {-6, 5}}, + std::vector(6, SeamType::Enforced)); + for (const Vec2d &target : {Vec2d(0, 3), Vec2d(0, 0.5), Vec2d(0.5, 1)}) { + const Vec2d from_1 = placed_xy(points, 1, target); + const Vec2d from_2 = placed_xy(points, 2, target); + CAPTURE(target.x(), target.y(), from_1.x(), from_1.y(), from_2.x(), from_2.y()); + CHECK((from_2 - from_1).norm() < 1e-5); + } + // Straight above the candidate the seam stays on the bottom edge. + CHECK((placed_xy(points, 2, {0, 0.5}) - Vec2d(0, 0)).norm() < 1e-5); +} + +TEST_CASE("Seams placed on a short loop follow a moving target continuously", "[SeamPlacer]") +{ + // A 2 x 2 mm painted square with a candidate inserted at (0, 0); the target goes up along the right + // side and beyond the loop, up to 5 mm from the candidate. + SeamPlacerImpl::Perimeter perimeter; + const auto points = loop_candidates(perimeter, {{-1, 0}, {0, 0}, {1, 0}, {1, 2}, {-1, 2}}, + std::vector(5, SeamType::Enforced)); + Vec2d previous = placed_xy(points, 1, {1, 0}); + for (int i = 1; i <= 500; ++i) { + const Vec2d target(1.0, 0.01 * i); + const Vec2d seam = placed_xy(points, 1, target); + CAPTURE(target.y(), seam.x(), seam.y()); + if (target.y() <= 2.0) + CHECK((seam - target).norm() < 1e-5); // A target on the loop is the seam. + CHECK((seam - previous).norm() <= 0.0101); + previous = seam; + } + // Above the loop the normals of the top side point to the square's center. + CHECK((previous - Vec2d(0.25, 2.0)).norm() < 1e-5); +} + +TEST_CASE("Seams placed on the loop stay in the allowed arc", "[SeamPlacer]") +{ + // A circle of 60 vertices; the target lies on vertex 16, beyond the arc allowed from candidate 12. + const size_t count = 60; + std::vector xy; + for (size_t i = 0; i < count; ++i) + xy.emplace_back(10.0 * Vec2d(std::cos(2.0 * PI * double(i) / count), std::sin(2.0 * PI * double(i) / count))); + const Vec2d target = xy[16]; + const Vec2d run_end = xy[13]; + const Vec2d past_end = run_end + 0.2 * (xy[14] - run_end).normalized(); + const auto placed = [&](const std::vector &types, bool exact_ends = false) { + SeamPlacerImpl::Perimeter perimeter; + perimeter.exact_enforced_ends = exact_ends; + const auto points = loop_candidates(perimeter, xy, types); + return placed_xy(points, 12, target); + }; + std::vector types(count, SeamType::Neutral); + // Enforced run 10..13: the seam may go 0.2 mm past its end, but not into a Blocked candidate. + std::fill(types.begin() + 10, types.begin() + 14, SeamType::Enforced); + CHECK((placed(types) - past_end).norm() < 1e-5); + // A run ending exactly at the paint is not extended. + CHECK((placed(types, true) - run_end).norm() < 1e-5); + types[14] = SeamType::Blocked; + CHECK((placed(types) - run_end).norm() < 1e-5); + // A candidate that is not Enforced stays between the Blocked candidates around it. + std::fill(types.begin() + 10, types.begin() + 14, SeamType::Neutral); + types[40] = SeamType::Blocked; + CHECK((placed(types) - run_end).norm() < 1e-5); + // With the target reachable around the loop, it is the seam. + types[40] = SeamType::Neutral; + CHECK((placed(types) - target).norm() < 1e-5); + types[14] = SeamType::Neutral; + CHECK((placed(types) - target).norm() < 1e-5); +} + +TEST_CASE("Seams placed on a short loop keep to the closest solution as the target moves", "[SeamPlacer][Regression]") +{ + // On a short painted square, the target moves upward left of the candidate: the solution on the left + // side stays the closest one, and must not be traded for the farther one on the right side. + SeamPlacerImpl::Perimeter perimeter; + const auto points = loop_candidates(perimeter, {{-1, 0}, {0, 0}, {1, 0}, {1, 2}, {-1, 2}}, + std::vector(5, SeamType::Enforced)); + Vec2d previous = placed_xy(points, 1, {-0.1, 1.0}); + for (int i = 1; i <= 1000; ++i) { + const Vec2d target(-0.1, 1.0 + 0.0001 * i); + const Vec2d seam = placed_xy(points, 1, target); + CAPTURE(target.y(), seam.x(), seam.y()); + CHECK(std::abs(seam.x() + 1.0) < 1e-5); + CHECK((seam - previous).norm() <= 0.0011); + previous = seam; + } +} + +TEST_CASE("Seams placed on the loop respect a painted run ending on the closing edge", "[SeamPlacer][Regression]") +{ + // The Enforced run goes around the loop from C and leaves 0.1 mm of its extension for the 10 mm closing + // edge back to C: the target on that edge lies outside the allowed arc. The loop is also placed after + // another loop and rotated, so that it does not start at index 0 and its run wraps around the array end. + const std::vector xy = {{0, 0}, {10, 0}, {10, 10}, {-10, 10}, {-10, 0.1}, {-10, 0}}; + std::vector types(6, SeamType::Enforced); + types[5] = SeamType::Neutral; + for (const size_t rotation : {size_t(0), size_t(3)}) { + std::vector rotated_xy = xy; + std::vector rotated_types = types; + std::rotate(rotated_xy.begin(), rotated_xy.begin() + rotation, rotated_xy.end()); + std::rotate(rotated_types.begin(), rotated_types.begin() + rotation, rotated_types.end()); + for (const size_t offset : {size_t(0), size_t(4)}) { + CAPTURE(rotation, offset); + SeamPlacerImpl::Perimeter perimeter; + const auto points = loop_candidates(perimeter, rotated_xy, rotated_types, {}, offset); + const size_t candidate = offset + (6 - rotation) % 6; + // The end of the allowed arc closer to the target: 0.2 mm from C toward the Neutral candidate. + CHECK((placed_xy(points, candidate, {-5, 0}) - Vec2d(-0.2, 0)).norm() < 1e-5); + } + } +} + +TEST_CASE("Seams held at the allowed arc keep their end across the arc midpoint", "[SeamPlacer][Regression]") +{ + // A single Enforced candidate; the target moves along the far side of the loop, past the point halfway + // around the loop from C. The end of the allowed arc closer to the target stays the same. + std::vector types(5, SeamType::Neutral); + types[0] = SeamType::Enforced; + SeamPlacerImpl::Perimeter perimeter; + const auto points = loop_candidates(perimeter, {{0, 0}, {10, 0}, {10, 1}, {-1, 1}, {-1, 0}}, types); + for (int i = 0; i <= 200; ++i) { + const Vec2d target(8.9 + 0.001 * i, 1.0); + CAPTURE(target.x()); + CHECK((placed_xy(points, 0, target) - Vec2d(0.2, 0)).norm() < 1e-5); + } +} + +TEST_CASE("Seams placed on the loop stay at the arc end their solution leaves through", "[SeamPlacer][Regression]") +{ + // The Enforced run of C = (4.2, 0) goes around the loop and ends 0.2 mm past (0, 0); the gap up to + // 0.2 mm before C is not allowed. The target follows the normal line through (x, 0) at a height of + // 2.15 mm, so that (x, 0) is its closest solution, while the target stays closer to the other arc end. + std::vector types(6, SeamType::Enforced); + types[1] = SeamType::Neutral; + SeamPlacerImpl::Perimeter perimeter; + const auto points = loop_candidates(perimeter, {{0, 0}, {3, 0}, {4.2, 0}, {100, 0}, {100, 100}, {0, 100}}, types); + const double a = 1.0 / std::sqrt(2.0); + for (int i = 0; i <= 200; ++i) { + // Normal at (x, 0), blended between (a, a) at (0, 0) and (0, 1) at (3, 0). + const double x = 0.1 + 0.001 * i; + const Vec2d normal(a * (1.0 - x / 3.0), a + (1.0 - a) * x / 3.0); + const Vec2d target(x + 2.15 * normal.x() / normal.y(), 2.15); + CAPTURE(x); + // The float target moves the solution by about 1e-5 mm here; the sweep step is 1e-3 mm. + CHECK((placed_xy(points, 2, target) - Vec2d(std::min(x, 0.2), 0)).norm() < 1e-4); + } +} + +TEST_CASE("Seams placed on the loop do not jump at duplicated points", "[SeamPlacer][Regression]") +{ + // Extrusion loops repeat the shared end points of their paths; both copies of the corner must get the + // same normal. + SeamPlacerImpl::Perimeter perimeter; + const auto points = loop_candidates(perimeter, {{0, 0}, {9, 0}, {10, 0}, {10, 0}, {10, 10}, {0, 10}}); + Vec2d previous = placed_xy(points, 1, {10.1, 0.0}); + for (int i = 1; i <= 200; ++i) { + const Vec2d target(10.1, -0.001 * i); + const Vec2d seam = placed_xy(points, 1, target); + CAPTURE(target.y(), seam.x(), seam.y()); + CHECK((seam - previous).norm() <= 0.0011); + CHECK((seam - Vec2d(10, 0)).norm() <= 0.11); + previous = seam; + } +} + +TEST_CASE("Corner influence is full near a corner and fades out along the loop", "[SeamPlacer]") +{ + // Candidates every 0.1 mm along the bottom of a 3 x 3 mm loop; angles are set directly. + std::vector xy; + for (int i = 0; i <= 30; ++i) + xy.emplace_back(0.1 * i, 0.0); + xy.emplace_back(3.0, 3.0); + xy.emplace_back(0.0, 3.0); + const auto influence = [&](float corner_angle, size_t index) { + std::vector angles(xy.size(), 0.0f); + angles[10] = corner_angle; + SeamPlacerImpl::Perimeter perimeter; + const auto points = loop_candidates(perimeter, xy, {}, angles); + return double(SeamPlacerImpl::enforced_corner_influence(points, index, 0.4f, 0.8f)); + }; + const float deg = float(PI) / 180.0f; + using Catch::Matchers::WithinAbs; + CHECK_THAT(influence(45.0f * deg, 10), WithinAbs(1.0, 1e-4)); + CHECK_THAT(influence(-45.0f * deg, 14), WithinAbs(1.0, 1e-4)); // Within R0 = 0.4 mm, either turn. + CHECK_THAT(influence(45.0f * deg, 6), WithinAbs(1.0, 1e-4)); + CHECK_THAT(influence(45.0f * deg, 16), WithinAbs(0.5, 1e-4)); // Halfway through the fade band. + CHECK_THAT(influence(45.0f * deg, 18), WithinAbs(0.0, 1e-4)); // R1 = 0.8 mm. + CHECK_THAT(influence(45.0f * deg, 25), WithinAbs(0.0, 1e-4)); + CHECK_THAT(influence(22.5f * deg, 10), WithinAbs(0.5, 1e-4)); // Halfway between 15 and 30 degrees. + CHECK_THAT(influence(10.0f * deg, 10), WithinAbs(0.0, 1e-4)); } TEST_CASE("Seam painting acts only from model parts and negative volumes", "[SeamPlacer]") @@ -405,3 +1260,281 @@ TEST_CASE("Precise Seam volume changes invalidate only G-code export", "[SeamPla CHECK(object->is_step_done(posSlice)); CHECK(object->is_step_done(posPerimeters)); } + +namespace { +// Axis-aligned rectangle given by two opposite corners in layer coordinates, as placed by the fixture. +BoundingBoxf layer_rectangle(const PipelineFixture &fixture, const PrintObject &object, const Vec2d &a, const Vec2d &b) +{ + std::vector corners; + for (const Point &corner : fixture.points_in_layer(object, {a, b})) + corners.push_back(unscale(corner)); + return BoundingBoxf(corners); +} + +// True if the point lies within `tolerance` mm of the boundary of the rectangle. +bool near_rectangle_boundary(const Vec3f &p, const BoundingBoxf &rect, double tolerance) +{ + const double dx = std::min(std::abs(p.x() - rect.min.x()), std::abs(p.x() - rect.max.x())); + const double dy = std::min(std::abs(p.y() - rect.min.y()), std::abs(p.y() - rect.max.y())); + const bool inside_x = p.x() > rect.min.x() - tolerance && p.x() < rect.max.x() + tolerance; + const bool inside_y = p.y() > rect.min.y() - tolerance && p.y() < rect.max.y() + tolerance; + return (dx < tolerance && inside_y) || (dy < tolerance && inside_x); +} + +// Checks that every seam candidate of the layer lies on the boundary of exactly one rectangle and that +// a perimeter never mixes candidates of two rectangles (a merged fallback polygon would). Rectangles +// must be at least 1 mm apart. Returns how many perimeters draw their candidates from each rectangle. +template +std::vector perimeters_per_rectangle(const LayerSeamsT &data, const std::vector &rects) +{ + std::vector result(rects.size(), 0); + for (const auto &perimeter : data.perimeters) { + std::vector hits(rects.size(), 0); + for (size_t i = perimeter.start_index; i < perimeter.end_index; ++i) { + const Vec3f &p = data.points[i].position; + size_t matched = 0; + for (size_t r = 0; r < rects.size(); ++r) + if (near_rectangle_boundary(p, rects[r], 0.5)) { + ++hits[r]; + ++matched; + } + CAPTURE(p.x(), p.y()); + CHECK(matched == 1); // A candidate off every outline comes from an inner loop. + } + size_t used = 0; + for (size_t r = 0; r < rects.size(); ++r) + if (hits[r] > 0) { + ++used; + ++result[r]; + } + CHECK(used <= 1); + } + return result; +} +} // namespace + +TEST_CASE("Fully overhanging outer loop is its own seam perimeter regardless of island order", "[SeamPlacer][Regression]") +{ + const bool overhang_first = GENERATE(false, true); + CAPTURE(overhang_first); + PipelineFixture fixture; + PrintObject &object = fixture.prepare(); + auto ®ion = clear_first_layer(object); + + // Island A: ordinary outer wall. Island B: the outer wall is entirely overhang but keeps inset_idx 0, + // followed by an inner wall that is overhang as well. + ExtrusionEntityCollection island_a, island_b; + island_a.append(make_loop(fixture.points_in_layer(object, {{2, 2}, {8, 2}, {8, 8}, {2, 8}}), erExternalPerimeter, 0)); + island_b.append(make_loop(fixture.points_in_layer(object, {{12, 2}, {18, 2}, {18, 8}, {12, 8}}), erOverhangPerimeter, 0)); + island_b.append(make_loop(fixture.points_in_layer(object, {{13.5, 3.5}, {16.5, 3.5}, {16.5, 6.5}, {13.5, 6.5}}), erOverhangPerimeter, 1)); + if (overhang_first) { + region.perimeters.append(std::move(island_b)); + region.perimeters.append(std::move(island_a)); + } else { + region.perimeters.append(std::move(island_a)); + region.perimeters.append(std::move(island_b)); + } + + SeamPlacer placer; + placer.init(fixture.print, [] {}); + const auto &data = placer.m_seam_per_object.at(&object).layers.front(); + // Exactly the two outer loops are registered; the inner loop is not merged into either of them. + REQUIRE(data.perimeters.size() == 2); + const auto counts = perimeters_per_rectangle(data, {layer_rectangle(fixture, object, {2, 2}, {8, 8}), + layer_rectangle(fixture, object, {12, 2}, {18, 8})}); + CHECK(counts == std::vector{1, 1}); +} + +TEST_CASE("External role selects the outer loop when inset_idx is unknown", "[SeamPlacer][Regression]") +{ + PipelineFixture fixture; + PrintObject &object = fixture.prepare(); + auto ®ion = clear_first_layer(object); + + // Thin-wall style loops carry the external role without a stored depth. + ExtrusionEntityCollection island; + island.append(make_loop(fixture.points_in_layer(object, {{2, 2}, {8, 2}, {8, 8}, {2, 8}}), erExternalPerimeter, -1)); + island.append(make_loop(fixture.points_in_layer(object, {{3.5, 3.5}, {6.5, 3.5}, {6.5, 6.5}, {3.5, 6.5}}), erPerimeter, -1)); + region.perimeters.append(std::move(island)); + + SeamPlacer placer; + placer.init(fixture.print, [] {}); + const auto &data = placer.m_seam_per_object.at(&object).layers.front(); + REQUIRE(data.perimeters.size() == 1); + const auto counts = perimeters_per_rectangle(data, {layer_rectangle(fixture, object, {2, 2}, {8, 8})}); + CHECK(counts == std::vector{1}); +} + +TEST_CASE("A collection without a recognizable outer loop gets its own fallback polygon", "[SeamPlacer][Regression]") +{ + PipelineFixture fixture; + PrintObject &object = fixture.prepare(); + auto ®ion = clear_first_layer(object); + + // The second collection has neither an external path nor a stored depth (for example, a loop loaded + // from the slicing cache). It must not be skipped just because an earlier collection added polygons. + ExtrusionEntityCollection island_a, island_b; + island_a.append(make_loop(fixture.points_in_layer(object, {{2, 2}, {8, 2}, {8, 8}, {2, 8}}), erExternalPerimeter, 0)); + island_b.append(make_loop(fixture.points_in_layer(object, {{12, 2}, {18, 2}, {18, 8}, {12, 8}}), erOverhangPerimeter, -1)); + region.perimeters.append(std::move(island_a)); + region.perimeters.append(std::move(island_b)); + + SeamPlacer placer; + placer.init(fixture.print, [] {}); + const auto &data = placer.m_seam_per_object.at(&object).layers.front(); + REQUIRE(data.perimeters.size() == 2); + const auto counts = perimeters_per_rectangle(data, {layer_rectangle(fixture, object, {2, 2}, {8, 8}), + layer_rectangle(fixture, object, {12, 2}, {18, 8})}); + CHECK(counts == std::vector{1, 1}); +} + +TEST_CASE("Mixed overhang and external outer loop is taken once", "[SeamPlacer][Regression]") +{ + // Whether or not the generator stored the depth, the external path alone identifies the loop. + const int outer_inset_idx = GENERATE(0, -1); + CAPTURE(outer_inset_idx); + PipelineFixture fixture; + PrintObject &object = fixture.prepare(); + auto ®ion = clear_first_layer(object); + + // The outer loop consists of one overhang path and external paths. + ExtrusionLoop mixed = make_loop(fixture.points_in_layer(object, {{2, 2}, {8, 2}, {8, 8}, {2, 8}}), erExternalPerimeter, + outer_inset_idx, true); + mixed.paths.front().set_extrusion_role(erOverhangPerimeter); + ExtrusionEntityCollection island; + island.append(std::move(mixed)); + island.append(make_loop(fixture.points_in_layer(object, {{3.5, 3.5}, {6.5, 3.5}, {6.5, 6.5}, {3.5, 6.5}}), erPerimeter, + outer_inset_idx == 0 ? 1 : -1)); + region.perimeters.append(std::move(island)); + + SeamPlacer placer; + placer.init(fixture.print, [] {}); + const auto &data = placer.m_seam_per_object.at(&object).layers.front(); + REQUIRE(data.perimeters.size() == 1); + const auto counts = perimeters_per_rectangle(data, {layer_rectangle(fixture, object, {2, 2}, {8, 8})}); + CHECK(counts == std::vector{1}); +} + +TEST_CASE("Contour boundary type is independent of extrusion direction", "[SeamPlacer]") +{ + const bool hole = GENERATE(false, true); + const bool clockwise = GENERATE(false, true); + PipelineFixture fixture; + PrintObject &object = fixture.prepare(); + auto ®ion = clear_first_layer(object); + append_loop(region, fixture.points_in_layer(object, {{2, 2}, {18, 2}, {18, 18}, {2, 18}}), false); + auto *loop = static_cast(region.perimeters.entities.front()); + loop->set_loop_role(hole ? elrHole : elrDefault); + if (clockwise) loop->make_clockwise(); else loop->make_counter_clockwise(); + // Geometric hole/outer identity must survive either choice of printing direction. + SeamPlacer placer; + placer.init(fixture.print, [] {}); + const auto &data = placer.m_seam_per_object.at(&object).layers.front(); + REQUIRE(data.perimeters.size() == 1); + CHECK(data.perimeters.front().is_hole == hole); +} + +TEST_CASE("Seam strings retain the legacy search when geometry finds no continuation", "[SeamPlacer][Regression]") +{ + PipelineFixture fixture(false, 2.0f); + PrintObject &object = fixture.prepare(); + REQUIRE(object.layers().size() == 10); + set_loop_on_every_layer(object, [&](size_t) { + return fixture.points_in_layer(object, {{2, 2}, {18, 2}, {18, 18}, {2, 18}}); + }); + for (size_t i = 0; i < object.layers().size(); ++i) { + auto *loop = static_cast(object.layers()[i]->get_region(0)->perimeters.entities.front()); + // Alternating roles deliberately fail geometric admissibility while preserving legacy candidates. + loop->set_loop_role(i % 2 == 0 ? elrDefault : elrHole); + } + SeamPlacer placer; + placer.init(fixture.print, [] {}); + const auto &layers = placer.m_seam_per_object.at(&object).layers; + for (size_t i = 1; i < layers.size(); ++i) { + CAPTURE(i); + REQUIRE(layers[i].perimeters.size() == 1); + CHECK(layers[i].perimeters.front().finalized); + } + SeamContour::Layers geometry(2); + for (size_t i = 0; i < 2; ++i) { + const auto &perimeter = layers[i].perimeters.front(); + SeamContour::Contour contour; + contour.hole = perimeter.is_hole; + contour.width = perimeter.flow_width; + for (size_t j = perimeter.start_index; j < perimeter.end_index; ++j) + contour.points.push_back(layers[i].points[j].position.head<2>().cast()); + geometry[i].push_back(std::move(contour)); + } + // Finalization alone could also pass through Unique; explicitly certify this fixture's empty result. + const auto &start = layers.front().perimeters.front(); + CHECK(SeamContour::Resolver(std::move(geometry)).resolve(0, 0, start.seam_index-start.start_index, 1).outcome + == SeamContour::Outcome::None); + +} + +TEST_CASE("Seam strings search all nondominated contour alternatives", "[SeamPlacer][Regression]") +{ + PipelineFixture fixture(false, 2.0f); + PrintObject &object = fixture.prepare(); + REQUIRE(object.layers().size() == 10); + for (size_t i = 0; i < object.layers().size(); ++i) { + Layer &layer = *object.layers()[i]; + for (LayerRegion *region : layer.regions()) region->perimeters.clear(); + auto ®ion = *layer.get_region(0); + if (i % 2 == 0) { + append_loop(region, fixture.points_in_layer(object, {{2, 2}, {18, 2}, {18, 18}, {2, 18}})); + } else { + // Both continuations share the rear edge, but their bounds defeat unique fast matching. + append_loop(region, fixture.points_in_layer(object, {{2, 2}, {20, 2}, {18, 18}, {2, 18}})); + append_loop(region, fixture.points_in_layer(object, {{2, 2}, {21, 2}, {18, 18}, {2, 18}})); + } + } + SeamPlacer placer; + placer.init(fixture.print, [] {}); + const auto &layers = placer.m_seam_per_object.at(&object).layers; + for (size_t i = 1; i < layers.size(); ++i) { + CAPTURE(i); + // Rejecting a nonunique geometric set would leave every short string unfinalized. + CHECK(std::any_of(layers[i].perimeters.begin(), layers[i].perimeters.end(), + [](const auto &perimeter) { return perimeter.finalized; })); + } +} + +TEST_CASE("Seam alignment remains cancellable after a string is finalized", "[SeamPlacer][Regression]") +{ + PipelineFixture fixture(false, 2.0f); + PrintObject &object = fixture.prepare(); + set_loop_on_every_layer(object, [&](size_t) { + return fixture.points_in_layer(object, {{2, 2}, {18, 2}, {18, 18}, {2, 18}}); + }); + SeamPlacer placer; + struct AlignmentCanceled {}; + CHECK_THROWS_AS(placer.init(fixture.print, [&] { + const auto found = placer.m_seam_per_object.find(&object); + if (found == placer.m_seam_per_object.end()) return; + // Cancel only after real alignment progress, rather than during earlier pipeline callbacks. + for (const auto &layer : found->second.layers) + if (std::any_of(layer.perimeters.begin(), layer.perimeters.end(), + [](const auto &perimeter) { return perimeter.finalized; })) + throw AlignmentCanceled{}; + }), AlignmentCanceled); +} + +TEST_CASE("Seam extraction preserves unknown boundary roles for open extrusion paths", "[SeamPlacer][Regression]") +{ + const bool open = GENERATE(false, true); + PipelineFixture fixture; + auto &object = fixture.prepare(); + auto ®ion = clear_first_layer(object); + const auto points = fixture.points_in_layer(object, {{2,2},{18,2},{18,18}}); + if (open) { + ExtrusionPath path(erExternalPerimeter, 0.08, 0.4f, 0.2f); + path.polyline = Polyline3(Polyline(points)); + region.perimeters.append(path); // A path has no closed-loop role even if its points look polygonal. + } else append_loop(region, points); + SeamPlacer placer; + placer.init(fixture.print, [] {}); + const auto &perimeters = placer.m_seam_per_object.at(&object).layers.front().perimeters; + REQUIRE(perimeters.size() == 1); + CHECK(perimeters.front().contour_reliable == !open); +} diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index 97fcf2804e..ef23b52203 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -12,6 +12,8 @@ add_executable(${_TEST_NAME}_tests test_precise_seam_3mf.cpp # Pure perimeter extraction is independent of Print/Layer fixtures. test_precise_seam.cpp + # Contour correspondence is pure geometry; Print integration stays in fff_print. + test_seam_contour.cpp test_aabbindirect.cpp test_appconfig.cpp test_arachne_walls.cpp diff --git a/tests/libslic3r/test_seam_contour.cpp b/tests/libslic3r/test_seam_contour.cpp new file mode 100644 index 0000000000..c019cd243f --- /dev/null +++ b/tests/libslic3r/test_seam_contour.cpp @@ -0,0 +1,400 @@ +#include +#include +#include "libslic3r/GCode/SeamContour.hpp" +#include "libslic3r/Point.hpp" +#include +#include +#include +#include +#include +#include +#include + +using namespace Slic3r; +using namespace Slic3r::SeamContour; +namespace { +Contour circle(double radius, double x, bool hole = false, size_t count = 64) { + Contour c; + c.hole = hole; + for (size_t i = 0; i < count; ++i) { + const double a = 2.0 * std::acos(-1.0) * double(i) / double(count); + c.points.emplace_back(x + radius * std::cos(a), radius * std::sin(a)); + } + return c; +} +Contour rectangle(double left, double right, double bottom, double top) { + Contour c; + c.points = {Vec2d(left, bottom), Vec2d(right, bottom), Vec2d(right, top), Vec2d(left, top)}; + return c; +} +} // namespace + +TEST_CASE("Indexed continuation preserves local holes among many distant contours", "[SeamContour][Regression]") { + const size_t side = GENERATE(1, 10, 40); + const double shrink = GENERATE(0.0, 0.1); + const bool reverse_order = GENERATE(false, true); + Layers layers(2); + for (size_t layer = 0; layer < 2; ++layer) { + layers[layer].push_back(rectangle(-2, 3*double(side), -2, 3*double(side))); + for (size_t y = 0; y < side; ++y) + for (size_t x = 0; x < side; ++x) { + Contour hole = circle(0.8 - layer*shrink, 3*double(x), true, 16); + for (auto &p : hole.points) p.y() += 3*double(y); + layers[layer].push_back(std::move(hole)); + } + if (reverse_order) std::reverse(layers[layer].begin(), layers[layer].end()); + } + Resolver resolver(std::move(layers)); + const size_t count = side*side; + for (size_t hole : {size_t(0), count/2, count-1}) { + const size_t index = reverse_order ? count-1-hole : hole+1; + const auto result = resolver.resolve(0, index, 0, 1); + REQUIRE(result.outcome == Outcome::Unique); + REQUIRE(result.contours.size() == 1); + CHECK(result.contours.front() == index); + } +} + +TEST_CASE("Unknown boundary geometry preserves unrestricted continuation near either layer", "[SeamContour][Regression]") { + const size_t unknown_layer = GENERATE(0, 1); + const bool nearby = GENERATE(false, true); + Layers layers{{rectangle(0, 10, 0, 10)}, {rectangle(0.2, 10.2, 0.2, 10.2)}}; + Contour unknown = nearby ? rectangle(-1, 11, -1, 11) : rectangle(100, 110, 100, 110); + unknown.reliable = false; // Its artificial closing edge cannot establish a material state. + layers[unknown_layer].push_back(std::move(unknown)); + Resolver resolver(std::move(layers)); + const auto result = resolver.resolve(0, 0, 0, 1); + if (nearby) { + CHECK(result.outcome == Outcome::None); + CHECK(result.contours.empty()); + } else { + REQUIRE(result.outcome == Outcome::Unique); + CHECK(result.contours.front() == 0); + } + CHECK(resolver.resolve(unknown_layer, 1, 0, unknown_layer == 0 ? 1 : -1).outcome == Outcome::None); +} + +TEST_CASE("Unknown reverse geometry preserves both split continuations for the legacy search", "[SeamContour][Regression]") { + const bool mirrored = GENERATE(false, true); + const bool descending = GENERATE(false, true); + const size_t unknown_layer = GENERATE(0, 1); + Contour source = rectangle(0, 10, 0, 10); + source.points.insert(source.points.begin() + 1, Vec2d(5, 0)); + Layers layers{{source}, {rectangle(0, mirrored ? 3.8 : 4.9, 0, 10), + rectangle(mirrored ? 5.1 : 6.2, 10, 0, 10)}}; + if (descending) std::reverse(layers.begin(), layers.end()); + const size_t source_layer = descending ? 1 : 0; + const int direction = descending ? -1 : 1; + // Both reliable walls remain eligible before the unknown path is introduced. + const auto baseline = Resolver(layers).resolve(source_layer, 0, 1, direction); + REQUIRE(baseline.outcome == Outcome::Multiple); + REQUIRE(baseline.contours == (std::vector{0, 1})); + Contour unknown; + const double x = mirrored ? 2.8 : 7.2; + unknown.points = {Vec2d(x, -0.2), Vec2d(x, 0.2)}; + unknown.reliable = false; + // Outside the direct query, this path is near only one candidate's reverse query. + layers[unknown_layer].push_back(std::move(unknown)); + const auto result = Resolver(std::move(layers)).resolve(source_layer, 0, 1, direction); + CHECK(result.outcome == Outcome::None); + CHECK(result.contours.empty()); +} + +TEST_CASE("Unknown reverse geometry invalidates a bounds certificate for the legacy search", "[SeamContour][Regression]") { + const bool descending = GENERATE(false, true); + const size_t unknown_layer = GENERATE(0, 1); + Layers layers{{rectangle(0, 10, 0, 10)}, + {rectangle(0.02, 10.02, 0.02, 10.02), rectangle(-10, -0.08, 0, 10)}}; + if (descending) std::reverse(layers.begin(), layers.end()); + const size_t source_layer = descending ? 1 : 0; + const int direction = descending ? -1 : 1; + // The near-coincident wall wins the reliable fast path, without a competing noise-band wall. + const auto baseline = Resolver(layers).resolve(source_layer, 0, 0, direction); + REQUIRE(baseline.outcome == Outcome::Unique); + REQUIRE(baseline.method == Method::Bounds); + REQUIRE(baseline.contours == (std::vector{0})); + Contour unknown; + unknown.points = {Vec2d(1.61, 0), Vec2d(1.61, 0.04)}; + unknown.reliable = false; + // The shifted foot sees this path; the direct query and the alternative foot do not. + layers[unknown_layer].push_back(std::move(unknown)); + const auto result = Resolver(std::move(layers)).resolve(source_layer, 0, 0, direction); + CHECK(result.outcome == Outcome::None); + CHECK(result.contours.empty()); +} + +TEST_CASE("Unknown geometry near a rejected tube wall preserves the reliable continuation", "[SeamContour][Regression]") { + const bool descending = GENERATE(false, true); + const size_t unknown_layer = GENERATE(0, 1); + const double width = 0.4, outer_radius = 4.0, inner_radius = 3.0, shift = 0.3; + Options options; + options.radius_width_factor = 4.0; + const double radius = width * options.radius_width_factor; + Layers layers{{circle(outer_radius, 0), circle(inner_radius, 0, true)}, + {circle(outer_radius, shift, false, 97), circle(inner_radius, shift, true, 93)}}; + for (auto &layer : layers) + for (auto &contour : layer) contour.width = contour.nozzle = width; + if (descending) std::reverse(layers.begin(), layers.end()); + const size_t source_layer = descending ? 1 : 0; + const int direction = descending ? -1 : 1; + // The shifted outer wall is a local match; the hole's opposing normal rejects it first. + const auto baseline = Resolver(layers, options).resolve(source_layer, 0, 0, direction, radius); + REQUIRE(baseline.outcome == Outcome::Unique); + REQUIRE(baseline.method == Method::Local); + REQUIRE(baseline.contours == (std::vector{0})); + Contour unknown; + const double x = inner_radius + shift - radius + 0.2; + // Only a premature reverse query from the rejected hole would encounter this path. + unknown.points = {Vec2d(x, -0.05), Vec2d(x, 0.05)}; + unknown.reliable = false; + layers[unknown_layer].push_back(std::move(unknown)); + const auto result = Resolver(std::move(layers), options).resolve(source_layer, 0, 0, direction, radius); + CHECK(result.outcome == Outcome::Unique); + CHECK(result.contours == (std::vector{0})); +} + +TEST_CASE("A split or merge keeps ambiguous continuations near the slit", "[SeamContour][Regression]") { + Resolver resolver({{rectangle(0, 10, 0, 10)}, + {rectangle(0, 4.8, 0, 10), rectangle(5.2, 10, 0, 10)}}); + REQUIRE(resolver.resolve(0, 0, 0, 1).outcome == Outcome::Unique); + CHECK(resolver.resolve(0, 0, 0, 1).contours.front() == 0); + const auto merged = resolver.resolve(1, 0, 0, -1); + REQUIRE(merged.outcome == Outcome::Unique); + CHECK(merged.contours.front() == 0); + // A vertex at the slit belongs to a separate source outline with the same bottom edge. + Contour source = rectangle(0, 10, 0, 10); + source.points.insert(source.points.begin()+1, Vec2d(5,0)); + Resolver at_slit({{source}, {rectangle(0,4.8,0,10), rectangle(5.2,10,0,10)}}); + const auto ambiguous = at_slit.resolve(0,0,1,1); + CHECK(ambiguous.outcome == Outcome::Multiple); + CHECK(ambiguous.contours == (std::vector{0,1})); +} + +TEST_CASE("Contour continuation preserves both tube walls despite candidate ordering", "[SeamContour]") { + const double thickness = GENERATE(0.8, 1.2, 2.0); + const double shift = GENERATE(0.0, 0.1, 0.4); + Resolver resolver({{circle(4, 0), circle(4-thickness, 0, true)}, + {circle(4-thickness, shift, true, 93), circle(4, shift, false, 97)}}); + for (size_t wall = 0; wall < 2; ++wall) + for (size_t vertex = 0; vertex < 64; ++vertex) { + const auto result = resolver.resolve(0, wall, vertex, 1); + REQUIRE(result.outcome == Outcome::Unique); + CHECK(result.contours.front() == 1-wall); + } +} + +TEST_CASE("Contour continuation follows an open wall after it becomes a hole", "[SeamContour][Regression]") { + const bool reverse_order = GENERATE(false, true); + Contour open = rectangle(0, 10, 0, 10); + // Closing the right-hand slit changes boundary type without changing its local material side. + open.points = {Vec2d(0, 0), Vec2d(10, 0), Vec2d(10, 1.2), Vec2d(6, 1.2), + Vec2d(6, 2.4), Vec2d(10, 2.4), Vec2d(10, 10), Vec2d(0, 10)}; + Contour hole = rectangle(6.004, 9.8, 1.204, 2.396); + hole.hole = true; + std::vector closed{rectangle(0, 10, 0, 10), hole}; + if (reverse_order) std::reverse(closed.begin(), closed.end()); + const size_t hole_index = reverse_order ? 0 : 1; + Resolver resolver({{open}, closed}); + const auto forward = resolver.resolve(0, 0, 3, 1); + REQUIRE(forward.outcome == Outcome::Unique); + REQUIRE(forward.contours.size() == 1); + CHECK(forward.contours.front() == hole_index); + CHECK(forward.method == Method::Local); + const auto backward = resolver.resolve(1, hole_index, 0, -1); + REQUIRE(backward.outcome == Outcome::Unique); + REQUIRE(backward.contours.size() == 1); + CHECK(backward.contours.front() == 0); +} + +TEST_CASE("Matching contour bounds cannot certify a transverse wall across material", "[SeamContour][Regression]") { + Contour open = rectangle(0, 10, 0, 10); + open.points = {Vec2d(0, 0), Vec2d(10, 0), Vec2d(10, 1.2), Vec2d(6, 1.2), + Vec2d(6, 2.4), Vec2d(10, 2.4), Vec2d(10, 10), Vec2d(0, 10)}; + // The box is identical and the wrong outer wall is inside the legacy search radius. + Resolver resolver({{open}, {rectangle(0, 10, 0, 10)}}); + const auto result = resolver.resolve(0, 0, 3, 1); + CHECK(result.outcome == Outcome::None); + CHECK(result.contours.empty()); +} + +TEST_CASE("A bounds match cannot hide another near-coincident local continuation", "[SeamContour][Regression]") { + Contour source = rectangle(0, 10, 0, 10); + source.points.insert(source.points.begin()+1, Vec2d(5, 0)); + // Only one box matches, but both local bottom edges are equally plausible. + Resolver resolver({{source}, {rectangle(0, 10, 0, 10), rectangle(0, 13, 0, 10)}}); + const auto result = resolver.resolve(0, 0, 1, 1); + CHECK(result.outcome == Outcome::Multiple); + CHECK(result.contours.size() == 2); +} + +TEST_CASE("A printed Benchy edge continues into the new hole after the opening closes", "[SeamContour][Regression]") { + std::ifstream input(std::string(TEST_DATA_DIR) + "/seam_contour_benchy_split.txt"); + REQUIRE(bool(input)); + Layers layers(2); + // Immutable printed contours from adjacent layers reproduce the real failure independently of chain weights. + for (auto &layer : layers) { + size_t count = 0; + input >> count; + layer.resize(count); + for (Contour &c : layer) { + size_t points = 0; + input >> c.hole >> c.width >> c.nozzle >> points; + for (size_t i = 0; i < points; ++i) { + double x = 0., y = 0.; + input >> x >> y; + c.points.emplace_back(x, y); + } + } + } + REQUIRE(bool(input)); + Resolver resolver(std::move(layers)); + const auto forward = resolver.resolve(0, 0, 9, 1); + REQUIRE(forward.outcome == Outcome::Unique); + REQUIRE(forward.contours.size() == 1); + CHECK(forward.contours.front() == 0); + CHECK(forward.method == Method::Local); + const auto backward = resolver.resolve(1, 0, 91, -1); + REQUIRE(backward.outcome == Outcome::Unique); + REQUIRE(backward.contours.size() == 1); + CHECK(backward.contours.front() == 0); +} + +TEST_CASE("Contour fallback rejects the translated-annulus false positive", "[SeamContour]") { + // The true outer wall is outside the radius; the closer hole must never replace it. + Resolver resolver({{circle(2, 0), circle(1, 0, true)}, {circle(2, 1.8), circle(1, 1.8, true)}}); + CHECK(resolver.resolve(0, 0, 0, 1).outcome != Outcome::Unique); +} + +TEST_CASE("Contour fallback follows a local wall despite changed global bounds", "[SeamContour]") { + Resolver resolver({{rectangle(0, 10, 0, 10)}, {rectangle(0, 13, 0, 10)}}); + const auto result = resolver.resolve(0, 0, 0, 1); + REQUIRE(result.outcome == Outcome::Unique); + CHECK(result.method == Method::Local); + CHECK(result.contours.front() == 0); +} + +TEST_CASE("Contour fallback handles an inclined wall without raster overlap", "[SeamContour]") { + Resolver resolver({{rectangle(0, 10, 0, 10)}, {rectangle(-0.7, 13, -0.7, 10)}}); + const auto result = resolver.resolve(0, 0, 0, 1); + CHECK(result.outcome == Outcome::Unique); + CHECK(result.method == Method::Local); +} + +TEST_CASE("Contour fallback does not resolve coincident competing surfaces by index", "[SeamContour]") { + Resolver resolver({{rectangle(0, 10, 0, 10)}, + {rectangle(0, 13, 0, 10), rectangle(0, 14, 0, 10)}}); + const auto result = resolver.resolve(0, 0, 0, 1); + CHECK(result.outcome == Outcome::Multiple); + CHECK(result.contours.size() == 2); +} + +TEST_CASE("Contour proximity includes a long edge with distant endpoints", "[SeamContour]") { + Contour current = rectangle(0, 10, 0, 10); + current.points.insert(current.points.begin()+1, Vec2d(5, 0)); + Resolver resolver({{current}, {rectangle(0, 10, 0, 10)}}); + CHECK(resolver.resolve(0, 0, 1, 1).outcome == Outcome::Unique); +} + +TEST_CASE("Contour dominance needs an advantage in distance and normal agreement", "[SeamContour]") { + const bool reverse = GENERATE(false, true); + Contour source = rectangle(-5, 5, 0, 10); + source.points.insert(source.points.begin()+1, Vec2d(0, 0)); + Contour tilted = rectangle(0.3, 5, 0, 13); + tilted.points[1].y() = 4.7 * std::tan(10.0 * std::acos(-1.0) / 180.0); + // Both branches are admissible, but the left one wins by both configured margins. + std::vector target{rectangle(-5, -0.02, 0, 13), tilted}; + if (reverse) std::reverse(target.begin(), target.end()); + const auto result = Resolver({{source}, target}).resolve(0, 0, 1, 1); + REQUIRE(result.outcome == Outcome::Unique); + REQUIRE(result.contours.size() == 1); + CHECK(result.contours.front() == (reverse ? 1 : 0)); +} + +TEST_CASE("Contour dominance keeps alternatives without enough distance advantage", "[SeamContour]") { + Contour source = rectangle(-5, 5, 0, 10); + source.points.insert(source.points.begin()+1, Vec2d(0, 0)); + Contour tilted = rectangle(0.08, 5, 0, 13); + tilted.points[1].y() = 4.92 * std::tan(10.0 * std::acos(-1.0) / 180.0); + const Layers layers{{source}, {rectangle(-5, -0.02, 0, 13), tilted}}; + const auto tied = Resolver(layers).resolve(0, 0, 1, 1); + CHECK(tied.outcome == Outcome::Multiple); + CHECK(tied.contours.size() == 2); + Options options; + options.dominance_width_factor = 0.1; // A smaller distance margin permits elimination. + const auto result = Resolver(layers, options).resolve(0, 0, 1, 1); + REQUIRE(result.outcome == Outcome::Unique); + CHECK(result.contours.front() == 0); +} + +TEST_CASE("Contour dominance keeps alternatives without enough angular advantage", "[SeamContour]") { + Contour source = rectangle(-5, 5, 0, 10); + source.points.insert(source.points.begin()+1, Vec2d(0, 0)); + Contour tilted = rectangle(0.3, 5, 0, 13); + tilted.points[1].y() = 4.7 * std::tan(3.0 * std::acos(-1.0) / 180.0); + const Layers layers{{source}, {rectangle(-5, -0.02, 0, 13), tilted}}; + CHECK(Resolver(layers).resolve(0, 0, 1, 1).contours.size() == 2); + Options options; + options.dominance_angle_degrees = 1.0; // Distance alone is insufficient with the default angular margin. + CHECK(Resolver(layers, options).resolve(0, 0, 1, 1).contours.size() == 1); +} + +TEST_CASE("Contour dominance keeps a farther branch with better normal agreement", "[SeamContour]") { + Contour source = rectangle(-5, 5, 0, 10); + source.points.insert(source.points.begin()+1, Vec2d(0, 0)); + Contour tilted = rectangle(-5, -0.02, 0, 13); + tilted.points[0].y() = -4.98 * std::tan(10.0 * std::acos(-1.0) / 180.0); + // The nearer branch is worse in orientation, so neither may discard the other. + const auto result = Resolver({{source}, {tilted, rectangle(0.3, 5, 0, 13)}}).resolve(0, 0, 1, 1); + CHECK(result.outcome == Outcome::Multiple); + CHECK(result.contours.size() == 2); +} + +TEST_CASE("Contour fallback accepts a source included in several reverse continuations", "[SeamContour]") { + // A merge can legitimately map back to both lower contours. + Resolver resolver({{rectangle(-5, -0.02, 0, 10), rectangle(0.02, 5, 0, 10)}, + {rectangle(-5, 5, 0, 13)}}); + const auto result = resolver.resolve(0, 0, 1, 1); + CHECK(result.outcome == Outcome::Unique); + CHECK(result.contours.size() == 1); +} + +TEST_CASE("Contour continuation refuses a disappeared wall and handles layer ends", "[SeamContour]") { + Resolver resolver({{circle(2, 0)}, {circle(2, 20)}}); + CHECK(resolver.resolve(0, 0, 0, 1).outcome == Outcome::None); + CHECK(resolver.resolve(0, 0, 0, -1).outcome == Outcome::None); +} + +TEST_CASE("Contour continuation is independent of loop start and duplicates", "[SeamContour]") { + Contour next = circle(2, 0.1); + std::rotate(next.points.begin(), next.points.begin()+17, next.points.end()); + next.points.push_back(next.points.front()); + Resolver resolver({{circle(2, 0)}, {next}}); + const auto first = resolver.resolve(0, 0, 0, 1); + const auto cached = resolver.resolve(0, 0, 0, 1); + REQUIRE(first.outcome == Outcome::Unique); + CHECK(cached.outcome == first.outcome); + CHECK(cached.contours == first.contours); +} + +TEST_CASE("Contour continuation finds the facing side of a shifted thin contour", "[SeamContour][Regression]") { + Contour source = rectangle(0.2, 0.7, 0, 10); + source.points.insert(source.points.begin()+2, Vec2d(0.7, 5)); + // The nearer left edge opposes the source normal; the right edge is its valid continuation. + Resolver resolver({{source}, {rectangle(0.5, 1.0, 0, 10)}}); + const auto result = resolver.resolve(0, 0, 2, 1); + REQUIRE(result.outcome == Outcome::Unique); + CHECK(result.contours.front() == 0); + CHECK(result.method == Method::Local); +} + +TEST_CASE("Contour continuation respects the caller radius across cached queries", "[SeamContour][Regression]") { + Contour source = rectangle(0, 10, 0, 10); + source.width = 0.1; + source.points.insert(source.points.begin()+2, Vec2d(10, 5)); + Resolver resolver({{source}, {rectangle(2, 12, 0, 10)}}); + // A wider seed permits this wall; the current layer's narrow width must not silently replace it. + CHECK(resolver.resolve(0, 0, 2, 1, 2.4).outcome == Outcome::Unique); + CHECK(resolver.resolve(0, 0, 2, 1, 0.4).outcome == Outcome::None); + CHECK(resolver.resolve(0, 0, 2, 1).outcome == Outcome::None); + CHECK(resolver.resolve(0, 0, 2, 1, 2.4).outcome == Outcome::Unique); +} diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index f1cd69b601..a53f161797 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -12,6 +12,7 @@ add_executable(${_TEST_NAME}_tests test_filament_bitmap_utils.cpp test_colour_picker_field.cpp test_filament_color_picker.cpp + test_gcode_preview_colors.cpp test_device_progress.cpp test_device_manager_integration.cpp test_web_media_controller.cpp diff --git a/tests/slic3rutils/test_gcode_preview_colors.cpp b/tests/slic3rutils/test_gcode_preview_colors.cpp new file mode 100644 index 0000000000..cc8d618ac4 --- /dev/null +++ b/tests/slic3rutils/test_gcode_preview_colors.cpp @@ -0,0 +1,78 @@ +// convert_filament_colors lives in libslic3r_gui; this is the only suite that links it. +#ifdef WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #ifndef NOMINMAX + #define NOMINMAX + #endif + #include +#endif + +#include +#include +#include + +#include +#include + +#include "libslic3r/Color.hpp" +#include "libvgcode/include/Types.hpp" +#include "slic3r/GUI/3DScene.hpp" +#include "slic3r/GUI/LibVGCode/LibVGCodeWrapper.hpp" + +using Catch::Matchers::WithinAbs; + +TEST_CASE("Filament colors keep their opacity for the G-code preview", "[GCodePreviewColors]") +{ + const libvgcode::PaletteWithAlpha palette = libvgcode::convert_filament_colors({ "#3366CC", "#3366CC80", "not a color" }); + REQUIRE(palette.size() == 3); + + CHECK(palette[0][3] == 255); + CHECK(palette[1][3] == 0x80); + for (size_t i = 0; i < 3; ++i) + CHECK(palette[1][i] == palette[0][i]); + + const libvgcode::ColorWithAlpha dummy{ libvgcode::DUMMY_COLOR[0], libvgcode::DUMMY_COLOR[1], libvgcode::DUMMY_COLOR[2], 255 }; + CHECK(palette[2] == dummy); +} + +TEST_CASE("An almost clear filament keeps its color at the least opacity", "[GCodePreviewColors]") +{ + Slic3r::ColorRGBA clear; + REQUIRE(Slic3r::decode_color("#3366CC10", clear)); + REQUIRE(clear.a() < FullyTransparentMaterialThreshold); + const Slic3r::ColorRGBA drawn = adjust_color_for_rendering(clear); + CHECK(drawn.r() == clear.r()); + CHECK(drawn.g() == clear.g()); + CHECK(drawn.b() == clear.b()); + CHECK(drawn.a() == FullyTransparentMaterialThreshold); + + const libvgcode::PaletteWithAlpha palette = libvgcode::convert_filament_colors({ "#3366CC10" }); + REQUIRE(palette.size() == 1); + for (int i = 0; i < 3; ++i) + CHECK(palette[0][i] == std::lround(255.0f * drawn[i])); + CHECK(palette[0][3] == std::lround(255.0f * drawn.a())); +} + +TEST_CASE("A translucent black filament is lifted to a grey that rises with its transparency", "[GCodePreviewColors]") +{ + const libvgcode::PaletteWithAlpha palette = libvgcode::convert_filament_colors({ "#000000", "#00000080", "#00000020" }); + REQUIRE(palette.size() == 3); + for (const libvgcode::ColorWithAlpha& color : palette) { + CHECK(color[1] == color[0]); + CHECK(color[2] == color[0]); + } + CHECK(palette[0][3] == 255); + CHECK(palette[1][3] == 0x80); + CHECK(palette[0][0] < palette[1][0]); + CHECK(palette[1][0] < palette[2][0]); + CHECK(palette[2][0] < 160); +} + +TEST_CASE("Preview filament colors convert back with their opacity", "[GCodePreviewColors]") +{ + const Slic3r::ColorRGBA color = libvgcode::convert(libvgcode::ColorWithAlpha{ 51, 102, 204, 128 }); + CHECK_THAT(color.r(), WithinAbs(51.0 / 255.0, 1e-6)); + CHECK_THAT(color.a(), WithinAbs(128.0 / 255.0, 1e-6)); +} diff --git a/tests/slic3rutils/test_plugin_audit.cpp b/tests/slic3rutils/test_plugin_audit.cpp index 7f7d9f6ea2..a257e304ea 100644 --- a/tests/slic3rutils/test_plugin_audit.cpp +++ b/tests/slic3rutils/test_plugin_audit.cpp @@ -1389,3 +1389,274 @@ site_packages_outcome = attempt(lambda: open(SITE_PACKAGE_FILE).close()) const std::string site_packages_prompt = "open: " + python.str("SITE_PACKAGE_FILE") + "\n"; CHECK(describe(harness.prompts) == write_prompt + site_packages_prompt); } + +TEST_CASE("A filesystem wildcard grant covers the folder and its descendants at any depth", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +DEEP_FILE = os.path.join(TREE, "one", "deep", "deeper", "f.txt") +os.makedirs(os.path.dirname(DEEP_FILE)) +with open(DEEP_FILE, "w") as f: + f.write("x") +NESTED_FILE = os.path.join(TREE, "one", "f.txt") +SIBLING = TREE + "-sibling" +SIBLING_FILE = os.path.join(SIBLING, "f.txt") +os.makedirs(SIBLING) +with open(SIBLING_FILE, "w") as f: + f.write("x") +# Lexically under TREE, but ".." resolves outside the granted folder. +ESCAPE_FILE = os.path.join(TREE, "..", "private.txt") +)PY"); + + const std::string tree = python.str("TREE"); + PluginPermissions permissions; + permissions.fs_read = {tree + "/*"}; + harness.save_permissions(PLUGIN, permissions); + + python.run_as(PLUGIN, R"PY( +deep_outcome = attempt(lambda: open(DEEP_FILE).read()) +root_outcome = attempt(lambda: os.listdir(TREE)) +sibling_outcome = attempt(lambda: open(SIBLING_FILE).read()) +escape_outcome = attempt(lambda: open(ESCAPE_FILE).read()) +)PY"); + + // The tree grant covers the folder itself (listing it) and a file two directories below it. + CHECK(python.str("deep_outcome") == "ok"); + CHECK(python.str("root_outcome") == "ok"); + // A path sharing the folder's prefix is not a descendant, and ".." is resolved before the + // comparison, so neither escapes the grant; both are asked about. + CHECK(python.str("sibling_outcome") == "denied"); + CHECK(python.str("escape_outcome") == "denied"); + const std::string sibling_prompt = "open: " + python.str("SIBLING_FILE") + "\n"; + const std::string escape_prompt = "open: " + python.str("ESCAPE_FILE") + "\n"; + CHECK(describe(harness.prompts) == sibling_prompt + escape_prompt); + + // Only the final component may be a wildcard: a "*" inside it is an ordinary character. + permissions.fs_read = {tree + "/*.txt"}; + harness.save_permissions(PLUGIN, permissions); + harness.prompts.clear(); + python.run_as(PLUGIN, "literal_outcome = attempt(lambda: open(NESTED_FILE).read())"); + CHECK(python.str("literal_outcome") == "denied"); + const std::string literal_prompt = "open: " + python.str("NESTED_FILE") + "\n"; + CHECK(describe(harness.prompts) == literal_prompt); +} + +TEST_CASE("A tree grant compares canonical paths on both sides", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + // A folder outside TREE, reached through a symlink planted inside it. + const fs::path tree = python.str("TREE"); + const fs::path outside_dir = harness.outside.path() / "symlink-target"; + const fs::path link = tree / "escape"; + fs::create_directories(outside_dir); + std::ofstream((outside_dir / "outside.txt").string(), std::ios::binary) << "x"; + + boost::system::error_code ec; + fs::create_directory_symlink(outside_dir, link, ec); + if (ec) + SKIP("Cannot create a directory symlink here: " + ec.message()); + + PluginPermissions permissions; + permissions.fs_read = {tree.string() + "/*"}; + harness.save_permissions(PLUGIN, permissions); + + const std::string escaped_file = (link / "outside.txt").string(); + python.globals["ESCAPED_FILE"] = escaped_file; + python.run_as(PLUGIN, "escaped_outcome = attempt(lambda: open(ESCAPED_FILE).read())"); + + // The target canonicalizes outside the canonical grant root, so the link does not inherit + // the tree grant. The read/write wildcard test covers a non-existing write tail. + CHECK(python.str("escaped_outcome") == "denied"); + CHECK(describe(harness.prompts) == "open: " + escaped_file + "\n"); + + // A grant rooted at the link applies to what the link points at, not just to its path. + permissions.fs_read = {link.string() + "/*"}; + harness.save_permissions(PLUGIN, permissions); + harness.prompts.clear(); + python.globals["TARGET_FILE"] = (outside_dir / "outside.txt").string(); + python.run_as(PLUGIN, "via_target_outcome = attempt(lambda: open(TARGET_FILE).read())"); + + CHECK(python.str("via_target_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); +} + +TEST_CASE("A write through a dangling symlink inside a granted tree is denied", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + // Two links inside TREE whose targets do not exist yet, so both dangle: + // - "dangling" points outside the tree, the reported escape; + // - "dangling-inside" points at a not-yet-created file that would be inside the tree, to pin + // the fail-closed choice: a dangling link is rejected whatever its target. + const fs::path tree = python.str("TREE"); + const fs::path outside_file = harness.outside.path() / "written-through-link.txt"; + const fs::path link = tree / "dangling"; + const fs::path inside_target = tree / "not-created.txt"; + const fs::path inside_link = tree / "dangling-inside"; + boost::system::error_code ec; + fs::create_symlink(outside_file, link, ec); + if (ec) + SKIP("Cannot create a file symlink here: " + ec.message()); + fs::create_symlink(inside_target, inside_link, ec); + if (ec) + SKIP("Cannot create a file symlink here: " + ec.message()); + + PluginPermissions permissions; + permissions.fs_readwrite = {tree.string() + "/*"}; + harness.save_permissions(PLUGIN, permissions); + + python.globals["DANGLING_LINK"] = link.string(); + python.globals["DANGLING_INSIDE_LINK"] = inside_link.string(); + python.run_as(PLUGIN, R"PY( +inside_outcome = attempt(lambda: open(os.path.join(TREE, "inside.txt"), "w").close()) +outcome = attempt(lambda: open(DANGLING_LINK, "w").close()) +inside_link_outcome = attempt(lambda: open(DANGLING_INSIDE_LINK, "w").close()) +)PY"); + + // The wildcard still covers an ordinary new file in the tree. A dangling final symlink is not + // covered: the grant describes the path the plugin spelled, while a write through the link + // would land at its target, so the prompt is refused and neither destination is created. + CHECK(python.str("inside_outcome") == "ok"); + CHECK(python.str("outcome") == "denied"); + CHECK(python.str("inside_link_outcome") == "denied"); + CHECK(describe(harness.prompts) == "open: " + link.string() + "\nopen: " + inside_link.string() + "\n"); + CHECK_FALSE(fs::exists(outside_file)); + CHECK_FALSE(fs::exists(inside_target)); +} + +TEST_CASE("A relative wildcard permission request is shown and stored as an absolute grant", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + PluginAuditManager& mgr = PluginAuditManager::instance(); + + // The plugin declares the grant relative to the working directory of the request, while the + // audit hook reports absolute targets. Resolve against the directory the request is made in. + const std::string relative_grant = "tree/*"; + PluginPermissions requested; + requested.fs_readwrite = {relative_grant}; + + const fs::path original_cwd = fs::current_path(); + boost::system::error_code ec; + fs::current_path(harness.outside.path(), ec); + REQUIRE_FALSE(ec); + const fs::path request_dir = fs::current_path(); + + std::string shown; + PluginAuditManager::set_permission_message_prompt_for_testing( + [&shown](const std::string& message) { shown = message; return true; }); + const bool granted = mgr.request_permissions(PLUGIN, requested); + PluginAuditManager::set_permission_message_prompt_for_testing(nullptr); + fs::current_path(original_cwd, ec); + + const std::string absolute_grant = (request_dir / "tree" / "*").string(); + + REQUIRE(granted); + // The prompt names the resolved scope, not the relative declaration. + CHECK(shown.find(absolute_grant) != std::string::npos); + CHECK(shown.find("\n" + relative_grant + "\n") == std::string::npos); + CHECK(harness.saved_permissions(PLUGIN).fs_readwrite == std::vector{absolute_grant}); + + // The saved absolute grant is the effective one: an absolute target below the resolved + // directory is covered, so the write is not asked about again. + python.globals["RESOLVED_FILE"] = (harness.outside.path() / "tree" / "written.txt").string(); + python.run_as(PLUGIN, "outcome = attempt(lambda: open(RESOLVED_FILE, 'w').close())"); + CHECK(python.str("outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); +} + +TEST_CASE("A filesystem wildcard keeps read and write grants separate", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +NESTED_FILE = os.path.join(TREE, "one", "f.txt") +NEW_FILE = os.path.join(TREE, "one", "new.txt") +)PY"); + const std::string tree = python.str("TREE"); + PluginPermissions permissions; + permissions.fs_read = {tree + "/*"}; + harness.save_permissions(PLUGIN, permissions); + + python.run_as(PLUGIN, R"PY( +read_outcome = attempt(lambda: open(NESTED_FILE).read()) +write_outcome = attempt(lambda: open(NEW_FILE, "w").close()) +)PY"); + CHECK(python.str("read_outcome") == "ok"); + CHECK(python.str("write_outcome") == "denied"); + // A read grant does not cover the write-shaped open, so that one is asked about. + const std::string write_prompt = "open: " + python.str("NEW_FILE") + "\n"; + CHECK(describe(harness.prompts) == write_prompt); + + // The reverse direction is separate too: a read/write wildcard leaves plain reads in the + // read bucket, which is now empty. + permissions.fs_read.clear(); + permissions.fs_readwrite = {tree + "/*"}; + harness.save_permissions(PLUGIN, permissions); + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +write_outcome = attempt(lambda: open(NEW_FILE, "w").close()) +reread_outcome = attempt(lambda: open(NESTED_FILE).read()) +)PY"); + CHECK(python.str("write_outcome") == "ok"); + CHECK(python.str("reread_outcome") == "denied"); + const std::string reread_prompt = "open: " + python.str("NESTED_FILE") + "\n"; + CHECK(describe(harness.prompts) == reread_prompt); +} + +TEST_CASE("A filesystem wildcard does not override a denied path", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + PluginAuditManager& mgr = PluginAuditManager::instance(); + + python.exec(R"PY( +DENIED_DIR = os.path.join(OUTSIDE, "secrets") +os.makedirs(DENIED_DIR) +with open(os.path.join(DENIED_DIR, "token.txt"), "w") as f: + f.write("x") +)PY"); + + // A grant wide enough to cover the deny registry's target still loses to the deny. + PluginPermissions permissions; + permissions.fs_read = {python.str("OUTSIDE") + "/*"}; + harness.save_permissions(PLUGIN, permissions); + + python.run_as(PLUGIN, "denied_outcome = attempt(lambda: open(os.path.join(DENIED_DIR, 'token.txt')).read())"); + + CHECK(python.str("denied_outcome") == "denied"); + CHECK(describe(harness.prompts).empty()); + AuditViolation violation; + REQUIRE(mgr.last_violation(violation)); + CHECK(violation.reason == "denied path"); +}