diff --git a/.github/workflows/publish_release.yml b/.github/workflows/publish_release.yml index eafe131f47..9cca6a8216 100644 --- a/.github/workflows/publish_release.yml +++ b/.github/workflows/publish_release.yml @@ -3,6 +3,7 @@ name: Publish to draft release # Manually pulls the platform binaries produced by a "Build all" run and uploads # them to an existing DRAFT release. Decoupled from the build so you can test a # build first, then publish exactly that run's artifacts once you're happy. +# It also writes an ordered download table into the draft's release notes. # # Trigger: Actions tab -> "Publish to draft release" -> Run workflow. # Locked to a single person: the first step aborts unless the actor matches the @@ -129,3 +130,68 @@ jobs: gh release upload "$TAG" upload/* --repo "$GITHUB_REPOSITORY" --clobber echo "Uploaded to draft release: $TAG" gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json assets --jq '.assets[].name' + + # GitHub lists release assets alphabetically by filename whatever order they + # are uploaded in, so the platform order users see comes from this table in + # the release notes. The table sits between the two markers: a rerun + # replaces it in place, and notes without markers get it appended. Text + # outside the markers is kept. Links use the tag's download URL, which only + # resolves once the draft is published. + - name: Write download table into release notes + run: | + set -euo pipefail + start='' + end='' + + # Sort key and label of an asset, in the order the table lists them. + describe() { + case "$1" in + *Windows_Installer_*_x64.exe) echo "01|Windows installer (x64)" ;; + *Windows_Installer_*_arm64.exe) echo "02|Windows installer (ARM64)" ;; + *_x64_portable.zip) echo "03|Windows portable (x64)" ;; + *_arm64_portable.zip) echo "04|Windows portable (ARM64)" ;; + *.dmg) echo "05|macOS (Apple Silicon and Intel)" ;; + *_aarch64_*.AppImage) echo "07|Linux AppImage (aarch64)" ;; + *.AppImage) echo "06|Linux AppImage (x86_64)" ;; + *_x86_64.flatpak) echo "08|Linux Flatpak (x86_64)" ;; + *_aarch64.flatpak) echo "09|Linux Flatpak (aarch64)" ;; + Debug_PDB_*) echo "10|Windows debug symbols (for developers)" ;; + *) echo "99|$1" ;; + esac + } + + { + echo "$start" + echo + echo "## Downloads" + echo + echo "| Platform | File |" + echo "| --- | --- |" + gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json assets --jq '.assets[].name' | while read -r name; do + echo "$(describe "$name")|$name" + done | sort | while IFS='|' read -r _ label name; do + echo "| $label | [$name](https://github.com/$GITHUB_REPOSITORY/releases/download/$TAG/$name) |" + done + echo + echo "$end" + } > table.md + + gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json body --jq '.body' > notes.md + starts=$(grep -cF "$start" notes.md || true) + ends=$(grep -cF "$end" notes.md || true) + if [ "$starts" -ne "$ends" ] || [ "$starts" -gt 1 ]; then + echo "::error::The release notes must contain each download-table marker exactly once, or neither. Fix them by hand and rerun." + exit 1 + fi + if [ "$starts" -eq 1 ]; then + awk -v start="$start" -v end="$end" ' + index($0, start) { while ((getline line < "table.md") > 0) print line; skip = 1; next } + index($0, end) { skip = 0; next } + !skip + END { exit skip } + ' notes.md > notes.new || { echo "::error::The download-table end marker must be on its own line, after the start marker."; exit 1; } + else + { cat notes.md; echo; cat table.md; } > notes.new + fi + gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --notes-file notes.new + cat table.md diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index b89694fbe5..4e0ed5ae87 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -910,8 +910,8 @@ which close the endpoint the call came through). Writing the key would skip all The dialog's controls are named after their AppConfig keys, so `ui_snapshot` shows the key and `ui_input {"target": {"name": "export_statistics", "within": "Preferences"}, "value": true}` changes one -through its own handler. The Speed Dial's `open_preferences` takes `[:]` (`general`, `control`, -`graphics`, `online` or `developer`) and opens the dialog there through `GUI_App::open_preferences()`, +through its own handler. The Speed Dial's `open_preferences` takes `[:]` (`general`, `files`, +`behaviour`, `control`, `graphics`, `online` or `developer`) and opens the dialog there through `GUI_App::open_preferences()`, scrolled to the key's control and focused; a key on another tab is shown on its own tab. Checkboxes, number and text fields and the language combobox change this way. The other comboboxes (those of `create_item_combobox()`, the log level, the login region and the network plug-in version) save from a diff --git a/docs/HLSD/preset-cache.md b/docs/HLSD/preset-cache.md index ed7403f5ef..41a52bd633 100644 --- a/docs/HLSD/preset-cache.md +++ b/docs/HLSD/preset-cache.md @@ -95,9 +95,16 @@ declaration order at static init — cannot: inserting one option into the middl *succeeds on the wrong option*, silently, wherever the two share a type. Because a name-keyed payload instead drops the individual options this build cannot place, the file as a whole stays readable, and there is no schema fingerprint — no checksum over -the option schema that would reject every cache on every release. An option this build -no longer defines, or now defines with a different type, gets exactly what it gets from -a JSON profile: read, dropped, and the rest of the preset loads. +the option schema that would reject every cache on every release. An option this build no +longer defines gets exactly what it gets from a JSON profile: read, dropped, and the rest +of the preset loads. An option this build now defines with a different type is read by the +type the writer recorded and handed to `set_deserialize` as its text, again as a JSON +profile's value would be: `handle_legacy` maps an old spelling (a bool's `1` onto an +enum's `enabled`) and an enum name a bool cannot parse is substituted. Only a text this +build cannot parse into the new type is dropped, that option alone. Dropping a retyped +option outright would leave the key at the collection default in every preset that sets +it, which is not what the JSON says, and an installed cache outlives the app upgrade that +retyped the key. The ordinal-keyed cereal hooks in `PrintConfig.hpp` are untouched — they are also the undo/redo wire format, where the process cannot change underneath them. The cache has @@ -365,8 +372,11 @@ The system is designed so that no cache problem is fatal: - **Corrupt, truncated or foreign file** — rejected at the header, vendor parsed. A cache is written to a temp file beside its target and moved into place, so a write that dies partway leaves the previous cache intact rather than a truncated one. -- **An option this build no longer has, or now types differently** — that option alone - is dropped, exactly as a JSON profile's would be. The preset and the file load. +- **An option this build no longer has** — that option alone is dropped, exactly as a + JSON profile's would be. The preset and the file load. +- **An option this build now types differently** — its value is read as the writer + typed it and parsed from its text as a JSON profile's would be, legacy conversions + included; only a text this build cannot parse into the new type is dropped. - **Cache from a build with a different cache layout** — rejected on `CACHE_VERSION`. A vendor with JSONs beside it is parsed and re-cached; a cache-only vendor reads as not installed and the updater reinstalls it. @@ -393,7 +403,10 @@ enumerates only `*.json` will find no vendors at all in a packaged build. - **Adding, removing, retyping or reordering a config option** needs nothing. The payload names its keys and its enum values, so an option a cache carries and this build does not is dropped; one this build has and the cache does not is simply - absent, as it would be from a JSON that predates it. + absent, as it would be from a JSON that predates it. A retyped option is read + through `handle_legacy`, so give it the same conversion a JSON profile needs and the + cache follows; an installed cache survives the upgrade that retyped the key, so that + conversion is what every user who upgrades reads. - **Changing a hand-written `serialize()`** — `VendorProfile` or its nested types — or the `CachedPreset` field list — written and read by `visit_entry` in `PresetCacheFormat.cpp`, one list for the save, the load and the name peek alike — or diff --git a/docs/HLSD/printer-agent.md b/docs/HLSD/printer-agent.md index 81947f1735..7062fab966 100644 --- a/docs/HLSD/printer-agent.md +++ b/docs/HLSD/printer-agent.md @@ -100,14 +100,8 @@ the active printer agent because a normal LAN agent represents one physical prin ## Agent registration and selection `NetworkAgentFactory` maintains the printer-agent registry. Each registry entry contains an agent ID, -a display name, a factory function, and whether the native Device and Calibration tabs apply to the -agent's printers. Built-in agents register during application initialization. Python printer-agent -capabilities register dynamically and contribute an agent ID and factory entry. - -The tab flag is read from the registry rather than the live agent because the main window lays out its -tabs before the newly selected preset's agent is installed. It defaults to true. An agent that clears -it is one whose printers have their own web interface and nothing the Bambu-shaped Device and -Calibration tabs can show; for those printers the web Device page takes the Device tab's place. +a display name, and a factory function. Built-in agents register during application initialization. +Python printer-agent capabilities register dynamically and contribute an agent ID and factory entry. The selected printer preset contains the printer-agent choice. If no explicit choice is stored, the application preserves the existing default behavior: Bambu presets select the Bambu agent and other diff --git a/localization/i18n/OrcaSlicer.pot b/localization/i18n/OrcaSlicer.pot index 8c4ffa92e2..a9e1a583f8 100644 --- a/localization/i18n/OrcaSlicer.pot +++ b/localization/i18n/OrcaSlicer.pot @@ -8967,7 +8967,7 @@ msgstr "" msgid "Some filament slots were changed:" msgstr "" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "" msgid "Because of unsupported text encoding, garbage characters may appear!" @@ -20655,7 +20655,7 @@ msgstr "" msgid "Expecting a regular expression." msgstr "" -msgid "Invalid utf8 sequence" +msgid "Invalid UTF-8 sequence" msgstr "" msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -23153,7 +23153,7 @@ msgstr "" msgid "Volumetric speed" msgstr "" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -31913,14 +31913,14 @@ msgid "Suspiciously low number of configuration values extracted from %1%: %2%" msgstr "" msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "" -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "" msgid "Custom G-code reports negative z_retracted." diff --git a/localization/i18n/ca/OrcaSlicer_ca.po b/localization/i18n/ca/OrcaSlicer_ca.po index a598931de4..7d54824430 100644 --- a/localization/i18n/ca/OrcaSlicer_ca.po +++ b/localization/i18n/ca/OrcaSlicer_ca.po @@ -10022,7 +10022,7 @@ msgid "Some filament slots were changed:" msgstr "S'han canviat algunes ranures de filament:" # AI Translated -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "Els noms dels components dins del fitxer STEP no tenen format UTF-8!" # AI Translated @@ -23917,8 +23917,8 @@ msgid "Expecting a regular expression." msgstr "S'esperava una expressió regular." # AI Translated -msgid "Invalid utf8 sequence" -msgstr "Seqüència utf8 no vàlida" +msgid "Invalid UTF-8 sequence" +msgstr "Seqüència UTF-8 no vàlida" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -26791,7 +26791,7 @@ msgstr "s" msgid "Volumetric speed" msgstr "Velocitat volumètrica" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "Paràmetres d'importació de fitxers STEP" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -38265,18 +38265,18 @@ msgstr "S'ha extret un nombre sospitosament baix de valors de configuració de % # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "Ha fallat la càrrega del fitxer STEP.\n" "No es pot obrir el fitxer per llegir-lo.\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "ha fallat la importació de l'SVG: no s'ha pogut obrir l'SVG." # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "ha fallat la importació de l'SVG: no s'han pogut analitzar les dades SVG importades." # AI Translated diff --git a/localization/i18n/cs/OrcaSlicer_cs.po b/localization/i18n/cs/OrcaSlicer_cs.po index ebcc86a97f..97980ea903 100644 --- a/localization/i18n/cs/OrcaSlicer_cs.po +++ b/localization/i18n/cs/OrcaSlicer_cs.po @@ -10032,7 +10032,7 @@ msgstr "Některá publikovaná nastavení nebylo možné použít:" msgid "Some filament slots were changed:" msgstr "Některé sloty filamentu byly změněny:" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "Názvy komponent v souboru STEP nejsou ve formátu UTF-8!" # AI Translated @@ -23923,8 +23923,8 @@ msgid "Expecting a regular expression." msgstr "Očekává se regulární výraz." # AI Translated -msgid "Invalid utf8 sequence" -msgstr "Neplatná sekvence utf8" +msgid "Invalid UTF-8 sequence" +msgstr "Neplatná sekvence UTF-8" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -26836,7 +26836,7 @@ msgid "Volumetric speed" msgstr "Objemová rychlost" # AI Translated -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "Parametry importu souboru STEP" # AI Translated @@ -38392,18 +38392,18 @@ msgstr "Podezřele nízký počet konfiguračních hodnot získaných z %1%: %2% # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "Načtení souboru STEP se nezdařilo.\n" "Soubor nelze otevřít pro čtení.\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "import SVG selhal: soubor SVG nelze otevřít." # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "import SVG selhal: importovaná data SVG nelze zpracovat." # AI Translated diff --git a/localization/i18n/de/OrcaSlicer_de.po b/localization/i18n/de/OrcaSlicer_de.po index 1155df8aec..a67ae3610d 100644 --- a/localization/i18n/de/OrcaSlicer_de.po +++ b/localization/i18n/de/OrcaSlicer_de.po @@ -9869,7 +9869,7 @@ msgstr "Einige veröffentlichte Einstellungen konnten nicht angewendet werden:" msgid "Some filament slots were changed:" msgstr "Einige Filament-Steckplätze wurden geändert:" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "Der Name der Komponenten in der Step-Datei ist nicht im UTF-8-Format!" msgid "Because of unsupported text encoding, garbage characters may appear!" @@ -23537,7 +23537,7 @@ msgid "Expecting a regular expression." msgstr "Erwartet wird ein regulärer Ausdruck." # AI Translated -msgid "Invalid utf8 sequence" +msgid "Invalid UTF-8 sequence" msgstr "Ungültige UTF-8-Sequenz" # AI Translated @@ -26274,7 +26274,7 @@ msgstr "s" msgid "Volumetric speed" msgstr "Volumetrische Geschwindigkeit" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "STEP-Datei-Importparameter" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -37719,18 +37719,18 @@ msgstr "Verdächtig geringe Anzahl an Konfigurationswerten aus %1% extrahiert: % # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "Laden der STEP-Datei fehlgeschlagen.\n" "Die Datei kann nicht zum Lesen geöffnet werden.\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "SVG-Import fehlgeschlagen: SVG konnte nicht geöffnet werden." # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "SVG-Import fehlgeschlagen: Die importierten SVG-Daten konnten nicht analysiert werden." # AI Translated diff --git a/localization/i18n/en/OrcaSlicer_en.po b/localization/i18n/en/OrcaSlicer_en.po index cc66aa760c..c4c7ecfe12 100644 --- a/localization/i18n/en/OrcaSlicer_en.po +++ b/localization/i18n/en/OrcaSlicer_en.po @@ -8963,7 +8963,7 @@ msgstr "" msgid "Some filament slots were changed:" msgstr "" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "" msgid "Because of unsupported text encoding, garbage characters may appear!" @@ -20651,7 +20651,7 @@ msgstr "" msgid "Expecting a regular expression." msgstr "" -msgid "Invalid utf8 sequence" +msgid "Invalid UTF-8 sequence" msgstr "" msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -23149,7 +23149,7 @@ msgstr "" msgid "Volumetric speed" msgstr "" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -31909,14 +31909,14 @@ msgid "Suspiciously low number of configuration values extracted from %1%: %2%" msgstr "" msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "" -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "" msgid "Custom G-code reports negative z_retracted." diff --git a/localization/i18n/es/OrcaSlicer_es.po b/localization/i18n/es/OrcaSlicer_es.po index daf669e42b..73218cc50e 100644 --- a/localization/i18n/es/OrcaSlicer_es.po +++ b/localization/i18n/es/OrcaSlicer_es.po @@ -9654,7 +9654,7 @@ msgstr "Algunos ajustes publicados no se han podido aplicar:" msgid "Some filament slots were changed:" msgstr "Se han cambiado algunas ranuras de filamento:" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "¡El nombre de los componentes dentro del archivo de pasos no tiene formato UTF-8!" msgid "Because of unsupported text encoding, garbage characters may appear!" @@ -23101,8 +23101,8 @@ msgid "Expecting a regular expression." msgstr "Se esperaba una expresión regular." # AI Translated -msgid "Invalid utf8 sequence" -msgstr "Secuencia utf8 no válida" +msgid "Invalid UTF-8 sequence" +msgstr "Secuencia UTF-8 no válida" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -25824,7 +25824,7 @@ msgstr "s" msgid "Volumetric speed" msgstr "Velocidad volumétrica" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "Parámetros de importación de archivos Step" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -37218,18 +37218,18 @@ msgstr "Número sospechosamente bajo de valores de configuración extraídos de # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "Error al cargar el archivo STEP.\n" "No se puede abrir el archivo para lectura.\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "error al importar SVG: no se pudo abrir el SVG." # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "error al importar SVG: no se pudieron analizar los datos SVG importados." # AI Translated diff --git a/localization/i18n/eu/OrcaSlicer_eu.po b/localization/i18n/eu/OrcaSlicer_eu.po index b2c3928abc..76abdac722 100644 --- a/localization/i18n/eu/OrcaSlicer_eu.po +++ b/localization/i18n/eu/OrcaSlicer_eu.po @@ -9752,7 +9752,7 @@ msgstr "Argitaratutako ezarpen batzuk ezin izan dira aplikatu:" msgid "Some filament slots were changed:" msgstr "Filamentu-erreten batzuk aldatu dira:" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "STEP fitxategiko osagai-izena(k) ez dago/daude UTF-8 formatuan!" msgid "Because of unsupported text encoding, garbage characters may appear!" @@ -23318,8 +23318,8 @@ msgid "Expecting a regular expression." msgstr "Adierazpen erregular bat espero zen." # AI Translated -msgid "Invalid utf8 sequence" -msgstr "utf8 sekuentzia baliogabea" +msgid "Invalid UTF-8 sequence" +msgstr "UTF-8 sekuentzia baliogabea" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -26049,7 +26049,7 @@ msgstr "s" msgid "Volumetric speed" msgstr "Abiadura bolumetrikoa" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "STEP fitxategia inportatzeko parametroak" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -37474,18 +37474,18 @@ msgstr "%1% fitxategitik atera den konfigurazio-balio kopurua susmagarriki txiki # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "STEP fitxategia kargatzeak huts egin du.\n" "Ezin da fitxategia ireki irakurtzeko.\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "SVG inportatzeak huts egin du: ezin izan da SVGa ireki." # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "SVG inportatzeak huts egin du: ezin izan dira inportatutako SVG datuak analizatu." # AI Translated diff --git a/localization/i18n/fr/OrcaSlicer_fr.po b/localization/i18n/fr/OrcaSlicer_fr.po index ea1f05319d..3b5f3cb53e 100644 --- a/localization/i18n/fr/OrcaSlicer_fr.po +++ b/localization/i18n/fr/OrcaSlicer_fr.po @@ -9752,7 +9752,7 @@ msgstr "Certains réglages publiés n'ont pas pu être appliqués :" msgid "Some filament slots were changed:" msgstr "Certains emplacements de filament ont été modifiés :" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "Le nom des composants dans le fichier STEP n'est pas au format UTF-8 !" msgid "Because of unsupported text encoding, garbage characters may appear!" @@ -23311,8 +23311,8 @@ msgid "Expecting a regular expression." msgstr "Expression régulière attendue." # AI Translated -msgid "Invalid utf8 sequence" -msgstr "Séquence utf8 non valide" +msgid "Invalid UTF-8 sequence" +msgstr "Séquence UTF-8 non valide" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -26037,7 +26037,7 @@ msgstr "s" msgid "Volumetric speed" msgstr "Vitesse volumétrique" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "Paramètres d'importation de fichier STEP" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -37153,18 +37153,18 @@ msgstr "Nombre anormalement faible de valeurs de configuration extraites de %1% # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "Échec du chargement du fichier STEP.\n" "Impossible d’ouvrir le fichier en lecture.\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "échec de l’import SVG : impossible d’ouvrir le SVG." # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "échec de l’import SVG : impossible d’analyser les données SVG importées." # AI Translated diff --git a/localization/i18n/hu/OrcaSlicer_hu.po b/localization/i18n/hu/OrcaSlicer_hu.po index 556061bab9..71bd4e658c 100644 --- a/localization/i18n/hu/OrcaSlicer_hu.po +++ b/localization/i18n/hu/OrcaSlicer_hu.po @@ -9947,7 +9947,7 @@ msgstr "Néhány közzétett beállítást nem sikerült alkalmazni:" msgid "Some filament slots were changed:" msgstr "Néhány filamenthely megváltozott:" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "A STEP fájlon belüli komponens neve nem UTF-8 formátumban van!" # AI Translated @@ -23784,8 +23784,8 @@ msgid "Expecting a regular expression." msgstr "Reguláris kifejezés várt." # AI Translated -msgid "Invalid utf8 sequence" -msgstr "Érvénytelen utf8 sorozat" +msgid "Invalid UTF-8 sequence" +msgstr "Érvénytelen UTF-8 sorozat" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -26635,7 +26635,7 @@ msgstr "mp" msgid "Volumetric speed" msgstr "Volumetrikus sebesség" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "STEP fájl importálási paraméterei" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -38131,18 +38131,18 @@ msgstr "Gyanúsan kevés konfigurációs értéket sikerült kinyerni a(z) %1% f # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "A STEP fájl betöltése sikertelen.\n" "A fájl nem nyitható meg olvasásra.\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "Az svg importálása sikertelen: az svg nem nyitható meg." # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "Az svg importálása sikertelen: az importált svg-adatok nem dolgozhatók fel." # AI Translated diff --git a/localization/i18n/it/OrcaSlicer_it.po b/localization/i18n/it/OrcaSlicer_it.po index 6c5e5af48d..f623ed0de7 100644 --- a/localization/i18n/it/OrcaSlicer_it.po +++ b/localization/i18n/it/OrcaSlicer_it.po @@ -9916,7 +9916,7 @@ msgstr "Alcune impostazioni pubblicate non sono state applicate:" msgid "Some filament slots were changed:" msgstr "Alcuni slot filamento sono stati modificati:" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "Il nome dei componenti all'interno del file STEP non è in formato UTF-8!" msgid "Because of unsupported text encoding, garbage characters may appear!" @@ -23651,8 +23651,8 @@ msgid "Expecting a regular expression." msgstr "Attesa un'espressione regolare." # AI Translated -msgid "Invalid utf8 sequence" -msgstr "Sequenza utf8 non valida" +msgid "Invalid UTF-8 sequence" +msgstr "Sequenza UTF-8 non valida" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -26498,7 +26498,7 @@ msgstr "s" msgid "Volumetric speed" msgstr "Velocità volumetrica" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "Parametri importazione file STEP" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -37967,18 +37967,18 @@ msgstr "Numero sospettosamente basso di valori di configurazione estratti da %1% # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "Caricamento del file STEP non riuscito.\n" "Impossibile aprire il file in lettura.\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "importazione SVG non riuscita: impossibile aprire l'SVG." # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "importazione SVG non riuscita: impossibile analizzare i dati SVG importati." # AI Translated diff --git a/localization/i18n/ja/OrcaSlicer_ja.po b/localization/i18n/ja/OrcaSlicer_ja.po index 220edb9f1b..12ee4cfb61 100644 --- a/localization/i18n/ja/OrcaSlicer_ja.po +++ b/localization/i18n/ja/OrcaSlicer_ja.po @@ -10238,7 +10238,7 @@ msgstr "一部のフィラメントスロットが変更されました:" # AI Translated # Needs human review: Rewrote a person's translation: Lost 'component names inside the STEP file' -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "STEPファイル内のコンポーネント名がUTF-8形式ではありません!" # AI Translated @@ -24962,8 +24962,8 @@ msgid "Expecting a regular expression." msgstr "正規表現が必要です。" # AI Translated -msgid "Invalid utf8 sequence" -msgstr "無効なutf8シーケンス" +msgid "Invalid UTF-8 sequence" +msgstr "無効なUTF-8シーケンス" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -27906,7 +27906,7 @@ msgstr "s" msgid "Volumetric speed" msgstr "体積速度" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "STEPファイルインポートパラメータ" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -39344,18 +39344,18 @@ msgstr "%1%から抽出された設定値の数が異常に少ないです: %2%" # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "STEPファイルの読み込みに失敗しました。\n" "ファイルを読み取り用に開けません。\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "SVGのインポートに失敗しました: SVGを開けませんでした。" # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "SVGのインポートに失敗しました: インポートしたSVGデータを解析できませんでした。" # AI Translated diff --git a/localization/i18n/ko/OrcaSlicer_ko.po b/localization/i18n/ko/OrcaSlicer_ko.po index be5c762040..e352c926ce 100644 --- a/localization/i18n/ko/OrcaSlicer_ko.po +++ b/localization/i18n/ko/OrcaSlicer_ko.po @@ -9978,7 +9978,7 @@ msgid "Some filament slots were changed:" msgstr "일부 필라멘트 슬롯이 변경되었습니다:" # AI Translated -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "STEP 파일 내부의 구성 요소 이름이 UTF-8 형식이 아닙니다!" # AI Translated @@ -24132,8 +24132,8 @@ msgid "Expecting a regular expression." msgstr "정규식이 필요합니다." # AI Translated -msgid "Invalid utf8 sequence" -msgstr "잘못된 utf8 시퀀스" +msgid "Invalid UTF-8 sequence" +msgstr "잘못된 UTF-8 시퀀스" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -27043,7 +27043,7 @@ msgstr "s" msgid "Volumetric speed" msgstr "압출 속도" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "스텝 파일 가져오기 매개변수" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -38470,18 +38470,18 @@ msgstr "%1%에서 추출된 구성 값의 수가 비정상적으로 적습니다 # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "STEP 파일 로드에 실패했습니다.\n" "읽기 위해 파일을 열 수 없습니다.\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "SVG 가져오기 실패: SVG를 열 수 없습니다." # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "SVG 가져오기 실패: 가져온 SVG 데이터를 구문 분석할 수 없습니다." # AI Translated diff --git a/localization/i18n/list.txt b/localization/i18n/list.txt index 32a03e0918..beee206475 100644 --- a/localization/i18n/list.txt +++ b/localization/i18n/list.txt @@ -312,6 +312,7 @@ src/slic3r/GUI/FilamentPickerDialog.cpp src/slic3r/GUI/NetworkPluginDialog.cpp src/slic3r/GUI/RammingChart.cpp src/slic3r/GUI/StepMeshDialog.cpp +src/slic3r/GUI/GeometryImportDialog.cpp src/slic3r/GUI/FilamentPickerDialog.hpp src/slic3r/GUI/PresetBundleDialog.cpp src/slic3r/GUI/ExportPresetBundleDialog.cpp diff --git a/localization/i18n/lt/OrcaSlicer_lt.po b/localization/i18n/lt/OrcaSlicer_lt.po index 72fe77a35c..c8ff4b577f 100644 --- a/localization/i18n/lt/OrcaSlicer_lt.po +++ b/localization/i18n/lt/OrcaSlicer_lt.po @@ -9966,7 +9966,7 @@ msgstr "Kai kurių patalpintų parametrų pritaikyti nepavyko:" msgid "Some filament slots were changed:" msgstr "Kai kurie gijų lizdai buvo pakeisti:" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "Komponentų pavadinimai STEP faile nėra UTF-8 formato!" msgid "Because of unsupported text encoding, garbage characters may appear!" @@ -23698,8 +23698,8 @@ msgid "Expecting a regular expression." msgstr "Tikimasi reguliariosios išraiškos." # AI Translated -msgid "Invalid utf8 sequence" -msgstr "Netinkama utf8 seka" +msgid "Invalid UTF-8 sequence" +msgstr "Netinkama UTF-8 seka" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -26435,7 +26435,7 @@ msgstr "s" msgid "Volumetric speed" msgstr "Tūrinis greitis" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "STEP failų importavimo parametrai" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -37954,18 +37954,18 @@ msgstr "Įtartinai mažai konfigūracijos verčių išgauta iš %1%: %2%" # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "STEP failo įkėlimas nepavyko.\n" "Nepavyksta atidaryti failo skaitymui.\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "SVG importas nepavyko: nepavyko atidaryti SVG." # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "SVG importas nepavyko: nepavyko išanalizuoti importuotų SVG duomenų." # AI Translated diff --git a/localization/i18n/nl/OrcaSlicer_nl.po b/localization/i18n/nl/OrcaSlicer_nl.po index f8d8a2e9eb..21c0b9b543 100644 --- a/localization/i18n/nl/OrcaSlicer_nl.po +++ b/localization/i18n/nl/OrcaSlicer_nl.po @@ -10633,7 +10633,7 @@ msgstr "Sommige gepubliceerde instellingen konden niet worden toegepast:" msgid "Some filament slots were changed:" msgstr "Sommige filamentsleuven zijn gewijzigd:" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "Naam van componenten in step-bestand is niet UTF-8-formaat!" msgid "Because of unsupported text encoding, garbage characters may appear!" @@ -25576,8 +25576,8 @@ msgid "Expecting a regular expression." msgstr "Regex verwacht." # AI Translated -msgid "Invalid utf8 sequence" -msgstr "Ongeldige utf8-reeks" +msgid "Invalid UTF-8 sequence" +msgstr "Ongeldige UTF-8-reeks" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -28634,7 +28634,7 @@ msgid "Volumetric speed" msgstr "Volumetrische snelheid" # AI Translated -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "Importparameters voor STEP-bestanden" # AI Translated @@ -40153,18 +40153,18 @@ msgstr "Verdacht laag aantal configuratiewaarden uit %1% gehaald: %2%" # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "Laden van STEP-bestand mislukt.\n" "Kan het bestand niet openen om te lezen.\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "svg importeren mislukt: svg kon niet worden geopend." # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "svg importeren mislukt: de geïmporteerde svg-gegevens konden niet worden geparseerd." # AI Translated diff --git a/localization/i18n/pl/OrcaSlicer_pl.po b/localization/i18n/pl/OrcaSlicer_pl.po index 75ff3e9cd0..415b937287 100644 --- a/localization/i18n/pl/OrcaSlicer_pl.po +++ b/localization/i18n/pl/OrcaSlicer_pl.po @@ -10100,7 +10100,7 @@ msgstr "Niektórych opublikowanych ustawień nie udało się zastosować:" msgid "Some filament slots were changed:" msgstr "Niektóre gniazda filamentu zostały zmienione:" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "Nazwa komponentów w pliku step nie jest w formacie UTF-8!" msgid "Because of unsupported text encoding, garbage characters may appear!" @@ -24173,7 +24173,7 @@ msgid "Expecting a regular expression." msgstr "Oczekiwano wyrażenia regularnego." # AI Translated -msgid "Invalid utf8 sequence" +msgid "Invalid UTF-8 sequence" msgstr "Nieprawidłowa sekwencja UTF-8" # AI Translated @@ -27103,7 +27103,7 @@ msgstr "s" msgid "Volumetric speed" msgstr "Prędkość przepływu" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "Parametry importu pliku Step" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -38553,18 +38553,18 @@ msgstr "Podejrzanie mała liczba wartości konfiguracji wyodrębnionych z %1%: % # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "Nie udało się wczytać pliku STEP.\n" "Nie można otworzyć pliku do odczytu.\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "import SVG nie powiódł się: nie można otworzyć pliku SVG." # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "import SVG nie powiódł się: nie udało się przeanalizować zaimportowanych danych SVG." # AI Translated diff --git a/localization/i18n/pt_BR/OrcaSlicer_pt_BR.po b/localization/i18n/pt_BR/OrcaSlicer_pt_BR.po index 326ba9715f..52de79396c 100644 --- a/localization/i18n/pt_BR/OrcaSlicer_pt_BR.po +++ b/localization/i18n/pt_BR/OrcaSlicer_pt_BR.po @@ -9348,7 +9348,7 @@ msgstr "Algumas configurações publicadas não puderam ser aplicadas:" msgid "Some filament slots were changed:" msgstr "Alguns espaços de filamento foram alterados:" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "Os nomes dos componentes dentro do arquivo STEP não estão no formato UTF-8!" msgid "Because of unsupported text encoding, garbage characters may appear!" @@ -22471,9 +22471,8 @@ msgstr "Esperava-se um nome de variável." msgid "Expecting a regular expression." msgstr "Esperava-se uma expressão regular." -# AI Translated -msgid "Invalid utf8 sequence" -msgstr "Sequência utf8 inválida" +msgid "Invalid UTF-8 sequence" +msgstr "Sequência UTF-8 inválida" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -25161,7 +25160,7 @@ msgstr "s" msgid "Volumetric speed" msgstr "Velocidade volumétrica" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "Parâmetros de importação de arquivo STEP" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -36032,16 +36031,16 @@ 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%" msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "Falha ao carregar o arquivo STEP.\n" "Não foi possível abrir o arquivo para leitura.\n" -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "falha ao importar o SVG: não foi possível abrir o SVG." -msgid "import svg failed: could not parse imported svg data." +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." msgid "Custom G-code reports negative z_retracted." diff --git a/localization/i18n/ru/OrcaSlicer_ru.po b/localization/i18n/ru/OrcaSlicer_ru.po index f54bb5f9cb..f765c38c85 100644 --- a/localization/i18n/ru/OrcaSlicer_ru.po +++ b/localization/i18n/ru/OrcaSlicer_ru.po @@ -9662,7 +9662,7 @@ msgstr "Некоторые опубликованные настройки не msgid "Some filament slots were changed:" msgstr "Некоторые слоты материалов были изменены:" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "Имена компонентов внутри файла STEP не в формате UTF-8." msgid "Because of unsupported text encoding, garbage characters may appear!" @@ -23366,8 +23366,8 @@ msgid "Expecting a regular expression." msgstr "Ожидается регулярное выражение." # AI Translated -msgid "Invalid utf8 sequence" -msgstr "Недопустимая последовательность utf8" +msgid "Invalid UTF-8 sequence" +msgstr "Недопустимая последовательность UTF-8" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -26126,7 +26126,7 @@ msgstr "с" msgid "Volumetric speed" msgstr "Объёмный расход" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "Параметры импорта STEP" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -37593,18 +37593,18 @@ msgstr "Подозрительно мало значений конфигура # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "Не удалось загрузить файл STEP.\n" "Невозможно открыть файл для чтения.\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "ошибка импорта SVG: не удалось открыть SVG." # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "ошибка импорта SVG: не удалось разобрать импортированные данные SVG." # AI Translated diff --git a/localization/i18n/sv/OrcaSlicer_sv.po b/localization/i18n/sv/OrcaSlicer_sv.po index 7b628bd410..e6b1d655d4 100644 --- a/localization/i18n/sv/OrcaSlicer_sv.po +++ b/localization/i18n/sv/OrcaSlicer_sv.po @@ -10729,7 +10729,7 @@ msgstr "Vissa publicerade inställningar kunde inte tillämpas:" msgid "Some filament slots were changed:" msgstr "Vissa filamentplatser har ändrats:" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "Komponent namnet i STEP filen är inte UTF-8 format!" msgid "Because of unsupported text encoding, garbage characters may appear!" @@ -25754,8 +25754,8 @@ msgid "Expecting a regular expression." msgstr "Förväntade ett reguljärt uttryck." # AI Translated -msgid "Invalid utf8 sequence" -msgstr "Ogiltig utf8-sekvens" +msgid "Invalid UTF-8 sequence" +msgstr "Ogiltig UTF-8-sekvens" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -28846,7 +28846,7 @@ msgid "Volumetric speed" msgstr "Volymetrisk hastighet" # AI Translated -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "Importparametrar för STEP-fil" # AI Translated @@ -40356,18 +40356,18 @@ msgstr "Misstänkt få konfigurationsvärden extraherades från %1%: %2%" # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "Det gick inte att läsa in step-filen.\n" "Filen kan inte öppnas för läsning.\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "import av svg misslyckades: kunde inte öppna svg." # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "import av svg misslyckades: kunde inte tolka den importerade svg-datan." # AI Translated diff --git a/localization/i18n/th/OrcaSlicer_th.po b/localization/i18n/th/OrcaSlicer_th.po index 8a281514e3..757f1b0059 100644 --- a/localization/i18n/th/OrcaSlicer_th.po +++ b/localization/i18n/th/OrcaSlicer_th.po @@ -9887,7 +9887,7 @@ msgstr "การตั้งค่าที่เผยแพร่บางส msgid "Some filament slots were changed:" msgstr "ช่องเส้นพลาสติกบางช่องมีการเปลี่ยนแปลง:" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "ชื่อของส่วนประกอบภายในไฟล์ STEP ไม่ใช่รูปแบบ UTF-8!" msgid "Because of unsupported text encoding, garbage characters may appear!" @@ -23774,8 +23774,8 @@ msgid "Expecting a regular expression." msgstr "คาดหวัง regex" # AI Translated -msgid "Invalid utf8 sequence" -msgstr "ลำดับ utf8 ไม่ถูกต้อง" +msgid "Invalid UTF-8 sequence" +msgstr "ลำดับ UTF-8 ไม่ถูกต้อง" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -26546,7 +26546,7 @@ msgstr "วินาที" msgid "Volumetric speed" msgstr "ความเร็วปริมาตร" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "พารามิเตอร์การนำเข้าไฟล์ขั้นตอน" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -37944,18 +37944,18 @@ msgstr "จำนวนค่าการกำหนดค่าที่ดึ # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "โหลดไฟล์ STEP ล้มเหลว\n" "ไม่สามารถเปิดไฟล์เพื่ออ่านได้\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "นำเข้า SVG ล้มเหลว: ไม่สามารถเปิด SVG ได้" # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "นำเข้า SVG ล้มเหลว: ไม่สามารถแยกวิเคราะห์ข้อมูล SVG ที่นำเข้าได้" # AI Translated diff --git a/localization/i18n/tr/OrcaSlicer_tr.po b/localization/i18n/tr/OrcaSlicer_tr.po index b6a017d73f..d2fe9fe953 100644 --- a/localization/i18n/tr/OrcaSlicer_tr.po +++ b/localization/i18n/tr/OrcaSlicer_tr.po @@ -9821,7 +9821,7 @@ msgstr "Bazı yayınlanan ayarlar uygulanamadı:" msgid "Some filament slots were changed:" msgstr "Bazı filament yuvaları değiştirildi:" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "Step dosyasındaki bileşenlerin adı UTF-8 formatında değil!" # AI Translated @@ -23680,8 +23680,8 @@ msgid "Expecting a regular expression." msgstr "Bir düzenli ifade bekleniyordu." # AI Translated -msgid "Invalid utf8 sequence" -msgstr "Geçersiz utf8 dizisi" +msgid "Invalid UTF-8 sequence" +msgstr "Geçersiz UTF-8 dizisi" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -26539,7 +26539,7 @@ msgstr "s" msgid "Volumetric speed" msgstr "Hacimsel hız" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "Adım dosyası içe aktarma parametreleri" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -38029,18 +38029,18 @@ msgstr "%1% dosyasından çıkarılan yapılandırma değerlerinin sayısı şü # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "STEP dosyası yüklenemedi.\n" "Dosya okuma için açılamıyor.\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "SVG içe aktarma başarısız oldu: SVG açılamadı." # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "SVG içe aktarma başarısız oldu: içe aktarılan SVG verileri ayrıştırılamadı." # AI Translated diff --git a/localization/i18n/uk/OrcaSlicer_uk.po b/localization/i18n/uk/OrcaSlicer_uk.po index 1cc9a2e70a..cf586fa1c6 100644 --- a/localization/i18n/uk/OrcaSlicer_uk.po +++ b/localization/i18n/uk/OrcaSlicer_uk.po @@ -10014,7 +10014,7 @@ msgid "Some filament slots were changed:" msgstr "Деякі слоти філаменту було змінено:" # AI Translated -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "Назви компонентів усередині файлу STEP не у форматі UTF-8!" msgid "Because of unsupported text encoding, garbage characters may appear!" @@ -24175,8 +24175,8 @@ msgid "Expecting a regular expression." msgstr "Очікується регулярний вираз." # AI Translated -msgid "Invalid utf8 sequence" -msgstr "Недійсна послідовність utf8" +msgid "Invalid UTF-8 sequence" +msgstr "Недійсна послідовність UTF-8" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -26986,7 +26986,7 @@ msgstr "c" msgid "Volumetric speed" msgstr "Обʼємна швидкість" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "Параметри імпорту STEP-файлу" # AI Translated @@ -38592,18 +38592,18 @@ msgstr "Підозріло мала кількість значень конфі # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "Не вдалося завантажити файл step.\n" "Не вдається відкрити файл для читання.\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "помилка імпорту svg: не вдалося відкрити svg." # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "помилка імпорту svg: не вдалося розібрати імпортовані дані svg." # AI Translated diff --git a/localization/i18n/vi/OrcaSlicer_vi.po b/localization/i18n/vi/OrcaSlicer_vi.po index 050ec9f618..d217422b80 100644 --- a/localization/i18n/vi/OrcaSlicer_vi.po +++ b/localization/i18n/vi/OrcaSlicer_vi.po @@ -10347,7 +10347,7 @@ msgstr "Không thể áp dụng một số cài đặt đã xuất bản:" msgid "Some filament slots were changed:" msgstr "Một số khe filament đã bị thay đổi:" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "Tên của các thành phần bên trong file STEP không phải định dạng UTF-8!" # AI Translated @@ -24534,8 +24534,8 @@ msgid "Expecting a regular expression." msgstr "Cần một biểu thức chính quy." # AI Translated -msgid "Invalid utf8 sequence" -msgstr "Chuỗi utf8 không hợp lệ" +msgid "Invalid UTF-8 sequence" +msgstr "Chuỗi UTF-8 không hợp lệ" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -27482,7 +27482,7 @@ msgid "Volumetric speed" msgstr "Tốc độ thể tích" # AI Translated -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "Tham số nhập file STEP" # AI Translated @@ -38917,18 +38917,18 @@ msgstr "Số lượng giá trị cấu hình trích xuất từ %1% thấp một # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "Tải file step thất bại.\n" "Không thể mở file để đọc.\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "nhập svg thất bại: không thể mở svg." # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "nhập svg thất bại: không thể phân tích dữ liệu svg đã nhập." # AI Translated diff --git a/localization/i18n/zh_CN/OrcaSlicer_zh_CN.po b/localization/i18n/zh_CN/OrcaSlicer_zh_CN.po index 4235f7559e..b106470fe2 100644 --- a/localization/i18n/zh_CN/OrcaSlicer_zh_CN.po +++ b/localization/i18n/zh_CN/OrcaSlicer_zh_CN.po @@ -10114,7 +10114,7 @@ msgstr "部分已发布的设置无法应用:" msgid "Some filament slots were changed:" msgstr "部分耗材丝槽位已更改:" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "STEP 文件中的部件名称不是 UTF-8 格式!" # AI Translated @@ -24432,8 +24432,8 @@ msgid "Expecting a regular expression." msgstr "应为正则表达式。" # AI Translated -msgid "Invalid utf8 sequence" -msgstr "无效的 utf8 序列" +msgid "Invalid UTF-8 sequence" +msgstr "无效的 UTF-8 序列" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -27366,7 +27366,7 @@ msgstr "s" msgid "Volumetric speed" msgstr "体积流量" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "STEP 文件导入参数" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -38779,18 +38779,18 @@ msgstr "从 %1% 提取的配置值数量异常偏少:%2%" # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "加载 STEP 文件失败。\n" "无法以读取方式打开文件。\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "导入 SVG 失败:无法打开 SVG。" # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "导入 SVG 失败:无法解析导入的 SVG 数据。" # AI Translated diff --git a/localization/i18n/zh_TW/OrcaSlicer_zh_TW.po b/localization/i18n/zh_TW/OrcaSlicer_zh_TW.po index 350ba90af5..30aae50434 100644 --- a/localization/i18n/zh_TW/OrcaSlicer_zh_TW.po +++ b/localization/i18n/zh_TW/OrcaSlicer_zh_TW.po @@ -10342,7 +10342,7 @@ msgstr "部分已發布的設定無法套用:" msgid "Some filament slots were changed:" msgstr "部分線材槽位已變更:" -msgid "Component name(s) inside step file not in UTF-8 format!" +msgid "Component name(s) inside STEP file not in UTF-8 format!" msgstr "STEP 檔案內部元件的名稱不是 UTF-8 格式!" # AI Translated @@ -24936,8 +24936,8 @@ msgid "Expecting a regular expression." msgstr "預期為正規表示式。" # AI Translated -msgid "Invalid utf8 sequence" -msgstr "無效的 utf8 序列" +msgid "Invalid UTF-8 sequence" +msgstr "無效的 UTF-8 序列" # AI Translated msgid "Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks." @@ -27905,7 +27905,7 @@ msgstr "秒" msgid "Volumetric speed" msgstr "體積流量" -msgid "Step file import parameters" +msgid "STEP file import parameters" msgstr "STEP 檔案匯入參數" msgid "Smaller linear and angular deflections result in higher-quality transformations but increase the processing time." @@ -39337,18 +39337,18 @@ msgstr "從 %1% 擷取到的設定值數量異常偏少:%2%" # AI Translated msgid "" -"Load step file failed.\n" +"Load STEP file failed.\n" "Cannot open file for reading.\n" msgstr "" "載入 STEP 檔案失敗。\n" "無法開啟檔案進行讀取。\n" # AI Translated -msgid "import svg failed: could not open svg." +msgid "import SVG failed: could not open svg." msgstr "匯入 SVG 失敗:無法開啟 SVG。" # AI Translated -msgid "import svg failed: could not parse imported svg data." +msgid "import SVG failed: could not parse imported svg data." msgstr "匯入 SVG 失敗:無法解析匯入的 SVG 資料。" # AI Translated diff --git a/src/libslic3r/AppConfig.cpp b/src/libslic3r/AppConfig.cpp index 5614385e05..e4b577e633 100644 --- a/src/libslic3r/AppConfig.cpp +++ b/src/libslic3r/AppConfig.cpp @@ -18,6 +18,7 @@ #include "nlohmann/json.hpp" #include +#include #include #include #include @@ -703,8 +704,29 @@ void AppConfig::set_defaults() set("angle_deflection", "0.5"); } if (get("is_split_compound").empty()) { - set_bool("is_split_compound", false); + // Splitting keeps the bodies of a multi-body part, and with them their original names. + set_bool("is_split_compound", true); } + // Geometry-import choices are editor preferences, never project print settings. + for (const std::string format : {"step", "amf", "3mf"}) { + const std::string prefix = "import_names_" + format + "_"; + if (get(prefix + "keep").empty()) + set_bool(prefix + "keep", true); + if (get(prefix + "sort").empty()) + set_bool(prefix + "sort", false); + if (format != "3mf" && get(prefix + "assembly").empty()) + set_bool(prefix + "assembly", true); + if (format == "amf" && get(prefix + "separate").empty()) + set_bool(prefix + "separate", true); + if (format != "step" && get(prefix + "show_dialog").empty()) + set_bool(prefix + "show_dialog", true); + } + if (get("import_names_cleanup_show_dialog").empty()) + set_bool("import_names_cleanup_show_dialog", true); + if (get("import_names_cleanup_remove").empty()) + set_bool("import_names_cleanup_remove", false); + if (get("import_names_cleanup_replacement").empty()) + set("import_names_cleanup_replacement", "_"); if (get("enable_primitive_size_dialog").empty()) { set_bool("enable_primitive_size_dialog", true); } diff --git a/src/libslic3r/BeltBrim.cpp b/src/libslic3r/BeltBrim.cpp index d51f1248de..c60a03ed21 100644 --- a/src/libslic3r/BeltBrim.cpp +++ b/src/libslic3r/BeltBrim.cpp @@ -7,6 +7,8 @@ #include "Polygon.hpp" #include "Print.hpp" #include "ShortestPath.hpp" +#include "Surface.hpp" +#include "SurfaceCollection.hpp" #include "Support/BeltFloorContext.hpp" #include "BoundingBox.hpp" #include "ExPolygon.hpp" @@ -257,9 +259,12 @@ struct BeltBrimContext }; // Emit the cross-belt brim lines that belong to the band [print_z - height, print_z]. +// wall_inset is how far the centreline of the outer wall of the band's object layer lies +// inside where the layer's slice met the belt, mm. static void belt_brim_band_paths(const BeltBrimContext &bc, coordf_t print_z, coordf_t height, + double wall_inset, const Polygons &obstacles, ExtrusionEntityCollection &out, ExPolygons &areas_out) @@ -272,10 +277,15 @@ static void belt_brim_band_paths(const BeltBrimContext &bc, // How wide this band is measured ON the belt, versus one nominal bead. const double band_in_plane = (u_hi - u_lo) * bc.frame.u_stretch(); - // Fraction of the layer height at which a line sits above the belt. Toward the - // downhill edge, so the sheet is reasonably thick while the nozzle stays clear of - // the belt itself. - static constexpr double BAND_CLEARANCE_FRACTION = 0.75; + // Nozzle-to-belt clearance of the object's own outer wall where it rests on the belt. + // The layer is sliced half a layer below print_z, so the slice meets the belt there, and + // the wall's centreline is inset from that edge, where the belt lies lower by the inset + // times the shear. No brim line sits closer to the belt than this, so brim and object + // are laid at the same height and one calibration of the belt height (endstop, extruder + // offset) serves both. A contour compensation that pushes the wall down to the belt + // cannot be matched: the brim keeps a tenth of a layer, so its lines still have a + // cross-section. + const double wall_clearance = std::max(0.5 * height + wall_inset * std::abs(bc.frame.shear), 0.1 * height); std::vector us; double uniform_clearance = 0.; // 0 => derive per line from its own position @@ -285,19 +295,20 @@ static void belt_brim_band_paths(const BeltBrimContext &bc, // wider. Two lattice lines in such a band would land almost on top of each other. if (band_in_plane <= 1.5 * bc.in_plane_pitch + EPSILON) { // Steep belt, which is the normal case: the band is narrower than one bead, so - // exactly one line fits. Place it at a FIXED fraction of the band rather than - // on a nominal-spacing lattice. On a lattice each line lands at an arbitrary - // point in its band, the clearance sweeps [0, height] from band to band, and the - // bead width therefore varies by 2x - visible as ragged, uneven brim lines. - // Anchoring to the band makes the clearance identical everywhere, so every bead - // is the same width. + // exactly one line fits. Place it at the outer wall's clearance rather than on + // a nominal-spacing lattice. On a lattice each line lands at an arbitrary point + // in its band, the clearance sweeps [0, height] from band to band, and the bead + // width therefore varies by 2x - visible as ragged, uneven brim lines. A fixed + // clearance is identical everywhere, so every bead is the same width. It can + // exceed the layer height, which only moves every band's line downhill by the + // same distance. // // The spacing is then whatever the bands give (height / sin(tilt) on the belt) // rather than the nominal bead spacing, so the flow below is matched to THAT // pitch. Matched flow at the real pitch is what keeps the sheet uniform and // gap-free; using nominal flow at band spacing would over-feed it. - us.push_back(scale_(bc.ctx.cutoff_u(print_z - BAND_CLEARANCE_FRACTION * height))); - uniform_clearance = BAND_CLEARANCE_FRACTION * height; + us.push_back(scale_(bc.ctx.cutoff_u(print_z - wall_clearance))); + uniform_clearance = wall_clearance; line_pitch = band_in_plane; } else { // Shallow belt: the band is wider than a bead, so it takes several lines and they @@ -324,18 +335,17 @@ static void belt_brim_band_paths(const BeltBrimContext &bc, // // A lattice line can fall where the belt is only a hair below the band's print_z. // The bead there would be laid scraping the belt while its flow is sized for a - // taller cell, so it is moved uphill to the same fraction of the band the - // single-line case uses. (The clearance is along slice Z; the real gap under the - // nozzle is clearance x cos(tilt), 0.53 h at 45 degrees for the 0.75 fraction.) + // taller cell, so it is moved to the outer wall's clearance, where the single-line + // case puts every line. (The clearance is along slice Z; the real gap under the + // nozzle is clearance x cos(tilt).) double clearance = uniform_clearance; if (clearance <= 0.) { const Point probe = bc.frame.from_axis == 0 ? Point(u, 0) : Point(0, u); - clearance = print_z - bc.ctx.floor_print_z(probe); - if (clearance < BAND_CLEARANCE_FRACTION * height) { - clearance = BAND_CLEARANCE_FRACTION * height; + clearance = std::min(print_z - bc.ctx.floor_print_z(probe), height); + if (clearance < wall_clearance) { + clearance = wall_clearance; u = scale_(bc.ctx.cutoff_u(print_z - clearance)); } - clearance = std::min(clearance, height); } // A line moved uphill can land on, or almost on, its neighbour; two beads closer // than half a pitch would be laid into the same cell. @@ -357,10 +367,12 @@ static void belt_brim_band_paths(const BeltBrimContext &bc, if (pieces.empty()) continue; - // with_cross_section, not with_height: it reaches the prescribed volume while - // KEEPING the extrusion spacing, so the bead is sized to fill exactly one - // pitch x clearance cell of the sheet. - const Flow f = bc.brim_flow.with_cross_section(float(line_pitch * clearance)); + // A bead as tall as the clearance and line_pitch apart from the next fills exactly + // one pitch x clearance cell of the sheet, at any clearance. (with_cross_section() + // makes a round bead of a quarter of the area asked for when the cell is small.) + const float height_f = float(clearance); + const Flow f(Flow::rounded_rectangle_extrusion_width_from_spacing(float(line_pitch), height_f), height_f, + bc.brim_flow.nozzle_diameter()); // Footprint of these beads, for the first-layer convex hull and bbox. for (const Polygon &p : offset(pieces, 0.5f * float(f.scaled_width()))) @@ -445,6 +457,9 @@ void make_belt_brim(PrintObject &object) ExPolygons footprint_acc; // The first layer that touches the belt: where the leading-edge brim is cut. const Layer *first_contact = nullptr; + // Per layer, the width of the outer wall resting on the belt, the narrowest where several + // regions do, as it sits lowest; 0 where the layer does not rest on the belt. + std::vector contact_wall_width(nlayers, 0.); for (size_t i = 0; i < nlayers; ++ i) { const Layer &layer = *object.layers()[i]; if (layer.lslices.empty()) @@ -466,6 +481,11 @@ void make_belt_brim(PrintObject &object) if (first_contact == nullptr) first_contact = &layer; expolygons_append(footprint_acc, std::move(contact)); + for (const LayerRegion *layerm : layer.regions()) + if (! layerm->slices.empty() && ! intersection(to_polygons(layerm->slices.surfaces), Polygons{ band }).empty()) { + const double w = layerm->flow(frExternalPerimeter).width(); + contact_wall_width[i] = contact_wall_width[i] > 0. ? std::min(contact_wall_width[i], w) : w; + } } const ExPolygons footprint = union_ex(footprint_acc); if (footprint.empty()) @@ -519,17 +539,37 @@ void make_belt_brim(PrintObject &object) : (low_side ? fbb.min.y() : fbb.max.y()); } + // How far each layer's outer wall, which the layer's brim band is levelled with, lies + // inside where the layer's slice met the belt: half its width, less the XY contour + // compensation that grew the slice toward the belt (none where slicing skips it, see + // PrintObject::slice_volumes()). The first layer's walls take initial_layer_line_width. + // A layer that does not rest on the belt takes the wall of the last one before it that + // does, and the layers ahead of the part the first one's. + const double contour_compensation = print.config().filament_diameter.size() > 1 && object.is_mm_painted() ? + 0. : object.config().xy_contour_compensation.value; + std::vector wall_insets(nlayers); + { + const auto first_wall = std::find_if(contact_wall_width.begin(), contact_wall_width.end(), [](double w) { return w > 0.; }); + double width = first_wall != contact_wall_width.end() ? *first_wall : 0.; + for (size_t i = 0; i < nlayers; ++ i) { + if (contact_wall_width[i] > 0.) + width = contact_wall_width[i]; + wall_insets[i] = 0.5 * width - contour_compensation; + } + } + // 4. Bands coincident with an object layer. std::vector by_layer(nlayers); std::vector areas_by_layer(nlayers); for (size_t i = 0; i < nlayers; ++ i) { const Layer &layer = *object.layers()[i]; const Polygons obstacles = belt_brim_obstacles(print, object, bc.region_bbox, layer.print_z, 0.5 * layer.height); - belt_brim_band_paths(bc, layer.print_z, layer.height, obstacles, by_layer[i], areas_by_layer[i]); + belt_brim_band_paths(bc, layer.print_z, layer.height, wall_insets[i], obstacles, by_layer[i], areas_by_layer[i]); } // 5. Apron prologue: the part of the region downhill of the object's first - // layer, which has no object layer to ride on. + // layer, which has no object layer to ride on. It continues the first layer's + // band, so it takes that layer's height, and the first contact's wall. std::vector prologue; { const Layer &first = *object.layers().front(); @@ -548,7 +588,7 @@ void make_belt_brim(PrintObject &object) BeltBrimBand band; band.print_z = z; band.height = h; - belt_brim_band_paths(bc, z, h, obstacles, band.fills, band.areas); + belt_brim_band_paths(bc, z, h, wall_insets.front(), obstacles, band.fills, band.areas); if (! band.fills.empty()) prologue.emplace_back(std::move(band)); } diff --git a/src/libslic3r/CMakeLists.txt b/src/libslic3r/CMakeLists.txt index 034f8b577a..116a154319 100644 --- a/src/libslic3r/CMakeLists.txt +++ b/src/libslic3r/CMakeLists.txt @@ -217,6 +217,8 @@ set(lisbslic3r_sources Format/3mf.hpp Format/AMF.cpp Format/AMF.hpp + Format/ImportNames.cpp + Format/ImportNames.hpp Format/AssembleList.cpp Format/AssembleList.hpp Format/DRC.cpp diff --git a/src/libslic3r/ExtrusionEntity.cpp b/src/libslic3r/ExtrusionEntity.cpp index 2e024c9b8a..cf45eac073 100644 --- a/src/libslic3r/ExtrusionEntity.cpp +++ b/src/libslic3r/ExtrusionEntity.cpp @@ -441,6 +441,9 @@ bool ExtrusionLoop::is_smooth(double angle_threshold, double min_arm_length) con // scarf extrudes through both ends, and the planner nearly halts on a block that short. Drop the // vertex next to the seam point instead, so the loop still starts and ends at the seam. A trimmed // path loses its arc fitting; its geometry is unchanged, it just prints as line segments. +// An eighth of a common line width: the path moves by less than that where a vertex is dropped. +const double seam_path_tolerance = scale_(0.05); + static void trim_seam_ends(ExtrusionPaths &paths, double tolerance) { const auto shorter = [tolerance](const Point3 &a, const Point3 &b) { return (b - a).cast().norm() < tolerance; }; @@ -480,10 +483,13 @@ static void trim_seam_ends(ExtrusionPaths &paths, double tolerance) } } -// Split `polyline` where the scarf ramp ends. When the split would leave a remainder shorter -// than half a slope step before the next vertex, the ramp is extended to that vertex instead: -// a stub that short makes the motion planner slow down at the end of the ramp. Planners treat -// moves of a millimetre and more as ordinary, so the ramp never grows by more than that. +// Split `polyline` where the scarf ramp ends. A remainder shorter than half a slope step before +// the next vertex would be a flat stub that makes the motion planner slow down at the end of the +// ramp. Where that vertex lies within `seam_path_tolerance` of the straight line from the exact +// ramp end to the vertex after it, the flat path skips it: the ramp keeps its exact length, so it +// ends at the same place on every layer however the loop's vertices fall there. At a corner, or +// when the vertex ends the path, the ramp is extended to the vertex instead. Planners treat moves +// of a millimetre and more as ordinary, so the ramp never grows by more than that. static void split_at_slope_end(const Polyline3 &polyline, double length, double slope_max_segment_length, Polyline3 &slope, Polyline3 &flat) { const double snap_distance = std::min(0.5 * slope_max_segment_length, scale_(1.)); @@ -493,6 +499,21 @@ static void split_at_slope_end(const Polyline3 &polyline, double length, double const double end_length = acc_length + line.length(); if (end_length >= length) { if (end_length - length < snap_distance) { + const size_t after = line_idx + 2; + if (length >= SCALED_EPSILON && after < polyline.size()) { + // Distance of the skipped vertex from the chord, in 3D so that a Z contour is kept too. + const Vec3d a = lerp(line.a, line.b, (length - acc_length) / line.length()).cast(); + const Vec3d b = polyline.points[after].cast(); + const Vec3d p = line.b.cast(); + const double t = (b - a).squaredNorm() > 0. ? std::clamp((p - a).dot(b - a) / (b - a).squaredNorm(), 0., 1.) : 0.; + if ((p - a - t * (b - a)).norm() <= seam_path_tolerance) { + Polyline3 rest; + polyline.split_at_length(length, &slope, &rest); + polyline.split_at_index(after, &rest, &flat); + flat.append_before(slope.last_point()); + return; + } + } polyline.split_at_index(line_idx + 1, &slope, &flat); return; } @@ -512,8 +533,7 @@ ExtrusionLoopSloped::ExtrusionLoopSloped(ExtrusionPaths& original_paths, ExtrusionLoopRole role) : ExtrusionLoop(role) { - // An eighth of a common line width: the path moves by less than that at the seam. - trim_seam_ends(original_paths, scale_(0.05)); + trim_seam_ends(original_paths, seam_path_tolerance); // The caller measured the loop before the trim; a scarf that covers the whole loop must still end at 1. double trimmed_length = 0.; for (const ExtrusionPath &path : original_paths) diff --git a/src/libslic3r/Format/AMF.cpp b/src/libslic3r/Format/AMF.cpp index 42583419b4..08495f2359 100644 --- a/src/libslic3r/Format/AMF.cpp +++ b/src/libslic3r/Format/AMF.cpp @@ -2,11 +2,13 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include @@ -20,6 +22,7 @@ #include "libslic3r/TriangleMesh.hpp" #include "AMF.hpp" +#include "ProjectStrategy.hpp" #include #include @@ -67,11 +70,15 @@ namespace Slic3r struct AMFParserContext { - AMFParserContext(XML_Parser parser, DynamicPrintConfig* config, ConfigSubstitutionContext* config_substitutions, Model* model) : + AMFParserContext(XML_Parser parser, DynamicPrintConfig* config, ConfigSubstitutionContext* config_substitutions, Model* model, LoadStrategy options, + const char* source_path) : m_parser(parser), m_model(*model), m_config(config), - m_config_substitutions(config_substitutions) + m_config_substitutions(config_substitutions), + m_assemble_parts((options & LoadStrategy::AssembleParts) && !(options & LoadStrategy::LoadConfig)), + m_keep_original_names(options & LoadStrategy::KeepOriginalNames), + m_fallback_name(boost::filesystem::path(source_path).filename().string()) { m_path.reserve(12); } @@ -96,7 +103,8 @@ struct AMFParserContext void startElement(const char *name, const char **atts); void endElement(const char *name); - void endDocument(); + bool endDocument(); + bool assemble_constellations(); void characters(const XML_Char *s, int len); static void XMLCALL startElement(void *userData, const char *name, const char **atts) @@ -246,6 +254,10 @@ struct AMFParserContext ModelObject *m_object { nullptr }; // Map from obect name to object idx & instances. std::map m_object_instances_map; + // Preserve XML membership and occurrence order only for explicit assembly import. + std::vector>> m_constellations; + // XML ids of m_constellations, so a group can be referenced from another group. + std::vector m_constellation_ids; // Vertices parsed for the current m_object. std::vector m_object_vertices; // Current volume allocated for an amf/object/mesh/volume subtree. @@ -266,6 +278,9 @@ struct AMFParserContext ConfigSubstitutionContext *m_config_substitutions { nullptr }; //BBS: add units logic bool m_use_inches { false }; + bool m_assemble_parts { false }; + bool m_keep_original_names { false }; + std::string m_fallback_name; private: AMFParserContext& operator=(AMFParserContext&); @@ -306,6 +321,11 @@ void AMFParserContext::startElement(const char *name, const char **atts) node_type_new = NODE_TYPE_OBJECT; } } else if (strcmp(name, "constellation") == 0) { + if (m_assemble_parts) { + m_constellations.emplace_back(); + const char *constellation_id = get_attribute(atts, "id"); + m_constellation_ids.emplace_back(constellation_id == nullptr ? "" : constellation_id); + } node_type_new = NODE_TYPE_CONSTELLATION; }/*else if (strcmp(name, "custom_gcodes_per_height") == 0) { node_type_new = NODE_TYPE_CUSTOM_GCODE; @@ -333,8 +353,14 @@ void AMFParserContext::startElement(const char *name, const char **atts) if (object_id == nullptr) this->stop(); else { - m_object_instances_map[object_id].instances.push_back(AMFParserContext::Instance()); - m_instance = &m_object_instances_map[object_id].instances.back(); + if (m_assemble_parts) { + auto &occurrences = m_constellations.back(); + occurrences.emplace_back(object_id, Instance()); + m_instance = &occurrences.back().second; + } else { + m_object_instances_map[object_id].instances.push_back(Instance()); + m_instance = &m_object_instances_map[object_id].instances.back(); + } node_type_new = NODE_TYPE_INSTANCE; } } @@ -858,8 +884,178 @@ void AMFParserContext::endElement(const char * /* name */) m_path.pop_back(); } -void AMFParserContext::endDocument() +bool AMFParserContext::assemble_constellations() { + auto object_index = [this](const std::string &target) { + auto definition = m_object_instances_map.find(target); + return definition == m_object_instances_map.end() ? -1 : definition->second.idx; + }; + // Malformed ids are skipped as Orca always did: an objectid names an object first, then the first group with that id. + std::map constellation_index; + for (size_t index = 0; index < m_constellation_ids.size(); ++index) { + const std::string &id = m_constellation_ids[index]; + if (id.empty()) + continue; + if (object_index(id) >= 0) + BOOST_LOG_TRIVIAL(warning) << "AMF constellation id " << id << " equals an object id; references resolve to the object"; + else if (!constellation_index.emplace(id, index).second) + BOOST_LOG_TRIVIAL(error) << "Duplicate AMF constellation id " << id << "; only the first group can be referenced"; + } + auto group_index = [&constellation_index](const std::string &target) { + auto group = constellation_index.find(target); + return group == constellation_index.end() ? -1 : int(group->second); + }; + + // A group referenced from another group is flattened into it and is not an assembly of its own. + std::set nested; + for (const auto &constellation : m_constellations) + for (const auto &occurrence : constellation) { + if (object_index(occurrence.first) >= 0) + continue; + if (const int group = group_index(occurrence.first); group >= 0) + nested.insert(size_t(group)); + else + BOOST_LOG_TRIVIAL(error) << "Undefined object " << occurrence.first << " referenced in constellation"; + } + + auto instance_matrix = [](const Instance &source) { + Geometry::Transformation transformation; + transformation.set_offset(Vec3d(source.deltax_set ? source.deltax : 0., source.deltay_set ? source.deltay : 0., + source.deltaz_set ? source.deltaz : 0.)); + transformation.set_rotation(Vec3d(source.rx_set ? source.rx : 0., source.ry_set ? source.ry : 0., + source.rz_set ? source.rz : 0.)); + transformation.set_scaling_factor(Vec3d(source.scalex_set ? source.scalex : 1., source.scaley_set ? source.scaley : 1., + source.scalez_set ? source.scalez : 1.)); + transformation.set_mirror(Vec3d(source.mirrorx_set ? source.mirrorx : 1., source.mirrory_set ? source.mirrory : 1., + source.mirrorz_set ? source.mirrorz : 1.)); + return transformation.get_matrix(); + }; + // Nesting and expansion limits keep a small malformed file from exhausting the stack or the time. + constexpr size_t max_depth = 256; + constexpr size_t max_expanded = 100000; + // One depth-first pass rejects cycles, so the expansion below always terminates. + std::vector state(m_constellations.size(), 0); // 0 new, 1 on the current path, 2 done + std::function acyclic = [&](size_t group, size_t depth) { + if (depth > max_depth) + return false; + state[group] = 1; + for (const auto &occurrence : m_constellations[group]) { + const int child = object_index(occurrence.first) >= 0 ? -1 : group_index(occurrence.first); + if (child < 0) + continue; + if (state[child] == 1 || (state[child] == 0 && !acyclic(size_t(child), depth + 1))) + return false; + } + state[group] = 2; + return true; + }; + for (size_t group = 0; group < m_constellations.size(); ++group) + if (state[group] == 0 && !acyclic(group, 0)) { + BOOST_LOG_TRIVIAL(error) << "Cyclic or too deeply nested AMF constellation references"; + return false; + } + + struct Placement + { + int index; + Transform3d matrix; + bool printable; + // Some occurrence on the path sets a transform; the legacy loader creates instances only then. + bool placed; + }; + // Every expanded occurrence counts, so groups that reach no body cannot multiply the work unnoticed. + size_t expanded = 0; + // Nested placements multiply down to the object definitions of the top-level group. + // The cycle check skips groups it already visited, so the expansion bounds its own depth too. + std::function &)> flatten = + [&](size_t group, const Transform3d &parent, bool parent_printable, bool parent_placed, size_t depth, + std::vector &out) { + if (depth > max_depth) + return false; + for (const auto &occurrence : m_constellations[group]) { + if (++expanded > max_expanded) + return false; + const Transform3d matrix = parent * instance_matrix(occurrence.second); + const bool printable = parent_printable && occurrence.second.printable; + const bool placed = parent_placed || occurrence.second.anything_set(); + if (const int index = object_index(occurrence.first); index >= 0) + out.push_back({index, matrix, printable, placed}); + else if (const int group = group_index(occurrence.first); + group >= 0 && !flatten(size_t(group), matrix, printable, placed, depth + 1, out)) + return false; + } + return true; + }; + + std::set referenced; + std::vector> groups; + for (size_t group = 0; group < m_constellations.size(); ++group) { + if (nested.count(group) != 0) + continue; + std::vector placements; + if (!flatten(group, Transform3d::Identity(), true, false, 0, placements)) { + BOOST_LOG_TRIVIAL(error) << "Too many AMF constellation placements"; + return false; + } + for (const Placement &placement : placements) + referenced.insert(placement.index); + groups.emplace_back(std::move(placements)); + } + + Model prepared; + int assemblies = 0; + for (const std::vector &placements : groups) { + if (placements.empty()) + continue; + Model group; + const bool printable = placements.front().printable; + bool mixed_printable = false; + bool placed = false; + for (const Placement &placement : placements) { + ModelObject *object = group.add_object(*m_model.objects[placement.index]); + // Match the GUI's filename fallback before merging discards the source objects. + if (object->name.empty()) + object->name = m_fallback_name; + for (ModelVolume* volume : object->volumes) + if (volume->name.empty()) + volume->name = object->name; + object->clear_instances(); + ModelInstance *instance = object->add_instance(); + // An identity occurrence is still an explicit instance, including its printability. + instance->set_transformation(Geometry::Transformation(placement.matrix)); + instance->printable = placement.printable; + mixed_printable = mixed_printable || placement.printable != printable; + placed = placed || placement.placed; + } + if (!mixed_printable && group.objects.size() > 1) { + group.convert_multipart_object(0, m_keep_original_names); + // An assembly is named after its file like other single-file imports; later groups get a suffix. + ++assemblies; + group.objects.front()->name = m_fallback_name + (assemblies > 1 ? "_" + std::to_string(assemblies) : std::string()); + group.objects.front()->add_instance()->printable = printable; + } + // Without any placement in the file the GUI centres the object on the bed, as for legacy AMF objects. + // An excluded group keeps its identity instance: dropping it would make the part printable. + if (!placed && printable && group.objects.size() == 1) + group.objects.front()->clear_instances(); + // Mixed printability cannot be expressed by one instance; preserve separate occurrences. + for (const ModelObject *object : group.objects) + prepared.add_object(*object); + } + // Unreferenced definitions remain independent, in their original XML order. + for (size_t index = 0; index < m_model.objects.size(); ++index) + if (referenced.count(static_cast(index)) == 0) + prepared.add_object(*m_model.objects[index]); + m_model.clear_objects(); + for (const ModelObject *object : prepared.objects) + m_model.add_object(*object); + return true; +} + +bool AMFParserContext::endDocument() +{ + if (m_assemble_parts) + return assemble_constellations(); for (const auto &object : m_object_instances_map) { if (object.second.idx == -1) { BOOST_LOG_TRIVIAL(error) << "Undefined object " << object.first.c_str() << " referenced in constellation"; @@ -888,11 +1084,12 @@ void AMFParserContext::endDocument() } } } + return true; } // Load an AMF file into a provided model. //BBS: add inches check logic -bool load_amf_file(const char *path, DynamicPrintConfig *config, ConfigSubstitutionContext *config_substitutions, Model *model, bool *use_inches) +bool load_amf_file(const char *path, DynamicPrintConfig *config, ConfigSubstitutionContext *config_substitutions, Model *model, bool *use_inches, LoadStrategy options) { if ((path == nullptr) || (model == nullptr)) return false; @@ -909,7 +1106,7 @@ bool load_amf_file(const char *path, DynamicPrintConfig *config, ConfigSubstitut return false; } - AMFParserContext ctx(parser, config, config_substitutions, model); + AMFParserContext ctx(parser, config, config_substitutions, model, options, path); XML_SetUserData(parser, (void*)&ctx); XML_SetElementHandler(parser, AMFParserContext::startElement, AMFParserContext::endElement); XML_SetCharacterDataHandler(parser, AMFParserContext::characters); @@ -937,7 +1134,7 @@ bool load_amf_file(const char *path, DynamicPrintConfig *config, ConfigSubstitut ::fclose(pFile); if (result) - ctx.endDocument(); + result = ctx.endDocument(); if (use_inches) { *use_inches = ctx.m_use_inches; } @@ -955,7 +1152,7 @@ bool load_amf_file(const char *path, DynamicPrintConfig *config, ConfigSubstitut } //BBS: add inches logic -bool extract_model_from_archive(mz_zip_archive& archive, const mz_zip_archive_file_stat& stat, DynamicPrintConfig* config, ConfigSubstitutionContext* config_substitutions, Model* model, bool* use_inches) +bool extract_model_from_archive(mz_zip_archive& archive, const mz_zip_archive_file_stat& stat, DynamicPrintConfig* config, ConfigSubstitutionContext* config_substitutions, Model* model, bool* use_inches, LoadStrategy options, const char* source_path) { if (stat.m_uncomp_size == 0) { @@ -971,7 +1168,7 @@ bool extract_model_from_archive(mz_zip_archive& archive, const mz_zip_archive_fi return false; } - AMFParserContext ctx(parser, config, config_substitutions, model); + AMFParserContext ctx(parser, config, config_substitutions, model, options, source_path); XML_SetUserData(parser, (void*)&ctx); XML_SetElementHandler(parser, AMFParserContext::startElement, AMFParserContext::endElement); XML_SetCharacterDataHandler(parser, AMFParserContext::characters); @@ -1017,7 +1214,8 @@ bool extract_model_from_archive(mz_zip_archive& archive, const mz_zip_archive_fi return false; } - ctx.endDocument(); + if (!ctx.endDocument()) + return false; if (use_inches) { *use_inches = ctx.m_use_inches; } @@ -1033,7 +1231,7 @@ bool extract_model_from_archive(mz_zip_archive& archive, const mz_zip_archive_fi } // Load an AMF archive into a provided model. -bool load_amf_archive(const char* path, DynamicPrintConfig* config, ConfigSubstitutionContext* config_substitutions, Model* model, bool* use_inches) +bool load_amf_archive(const char* path, DynamicPrintConfig* config, ConfigSubstitutionContext* config_substitutions, Model* model, bool* use_inches, LoadStrategy options) { if ((path == nullptr) || (model == nullptr)) return false; @@ -1059,7 +1257,7 @@ bool load_amf_archive(const char* path, DynamicPrintConfig* config, ConfigSubsti { try { - if (!extract_model_from_archive(archive, stat, config, config_substitutions, model, use_inches)) + if (!extract_model_from_archive(archive, stat, config, config_substitutions, model, use_inches, options, path)) { close_zip_reader(&archive); BOOST_LOG_TRIVIAL(error) << "Archive does not contain a valid model"; @@ -1102,7 +1300,7 @@ bool load_amf_archive(const char* path, DynamicPrintConfig* config, ConfigSubsti // Load an AMF file into a provided model. // If config is not a null pointer, updates it if the amf file/archive contains config data //BBS: refine the amf logic -bool load_amf(const char *path, DynamicPrintConfig *config, ConfigSubstitutionContext *config_substitutions, Model *model, bool* use_inches) +bool load_amf(const char *path, DynamicPrintConfig *config, ConfigSubstitutionContext *config_substitutions, Model *model, bool* use_inches, LoadStrategy options) { CNumericLocalesSetter locales_setter; // use "C" locales and point as a decimal separator @@ -1116,7 +1314,8 @@ bool load_amf(const char *path, DynamicPrintConfig *config, ConfigSubstitutionCo file.read(zip_mask.data(), 2); file.close(); - return (zip_mask == "PK") ? load_amf_archive(path, config, config_substitutions, model, use_inches) : load_amf_file(path, config, config_substitutions, model, use_inches); + return (zip_mask == "PK") ? load_amf_archive(path, config, config_substitutions, model, use_inches, options) : + load_amf_file(path, config, config_substitutions, model, use_inches, options); } else return false; diff --git a/src/libslic3r/Format/AMF.hpp b/src/libslic3r/Format/AMF.hpp index 335d47d6fb..1133660c7b 100644 --- a/src/libslic3r/Format/AMF.hpp +++ b/src/libslic3r/Format/AMF.hpp @@ -1,6 +1,8 @@ #ifndef slic3r_Format_AMF_hpp_ #define slic3r_Format_AMF_hpp_ +#include "ProjectStrategy.hpp" + namespace Slic3r { class Model; @@ -8,7 +10,8 @@ class DynamicPrintConfig; struct ConfigSubstitutionContext; // Load the content of an amf file into the given model and configuration. -extern bool load_amf(const char* path, DynamicPrintConfig* config, ConfigSubstitutionContext* config_substitutions, Model* model, bool* use_inches); +extern bool load_amf(const char* path, DynamicPrintConfig* config, ConfigSubstitutionContext* config_substitutions, Model* model, bool* use_inches, + LoadStrategy options = LoadStrategy::Default); //BBS: remove amf export // Save the given model and the config data into an amf file. diff --git a/src/libslic3r/Format/ImportNames.cpp b/src/libslic3r/Format/ImportNames.cpp new file mode 100644 index 0000000000..7c95ecd403 --- /dev/null +++ b/src/libslic3r/Format/ImportNames.cpp @@ -0,0 +1,115 @@ +#include "ImportNames.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { +namespace { + +std::u32string decode_name(const std::string& name) +{ + try { + return boost::locale::conv::utf_to_utf(name, boost::locale::conv::stop); + } catch (const boost::locale::conv::conversion_error&) { + throw std::invalid_argument("An imported name contains invalid UTF-8."); + } +} + +bool unsupported_character(char32_t c) +{ + // XML permits tab/newline/CR, but excludes other C0 controls and noncharacters FFFE/FFFF. + const bool valid_xml = c == 9 || c == 10 || c == 13 || + (c >= 0x20 && c <= 0xd7ff) || + (c >= 0xe000 && c <= 0xfffd) || + (c >= 0x10000 && c <= 0x10ffff); + constexpr std::u32string_view forbidden = U"<>:/\\|?*\""; + return !valid_xml || forbidden.find(c) != std::u32string_view::npos; +} + +std::string replace_characters(const std::string& name, const std::string& replacement) +{ + std::u32string output; + const std::u32string substitute = decode_name(replacement); + for (char32_t c : decode_name(name)) { + if (unsupported_character(c)) + output += substitute; + else + output += c; + } + return boost::locale::conv::utf_to_utf(output); +} + +} // namespace + +bool has_unsupported_name_characters(const std::string& name) +{ + for (char32_t c : decode_name(name)) + if (unsupported_character(c)) + return true; + return false; +} + +bool valid_import_name_replacement(const std::string& replacement) +{ + if (replacement.empty()) + return false; + try { + return !has_unsupported_name_characters(replacement); + } catch (const std::invalid_argument&) { + return false; + } +} + +std::vector sanitize_import_names(const std::vector& names, + const std::string& replacement, + const std::string& fallback) +{ + if (!replacement.empty() && !valid_import_name_replacement(replacement)) + throw std::invalid_argument("The name replacement contains unsupported characters."); + + // Reserve all existing valid names before processing, including those appearing later. + std::set reserved; + for (const auto& name : names) + if (!has_unsupported_name_characters(name)) + reserved.insert(name); + + std::string safe_fallback = replace_characters(fallback, replacement); + if (safe_fallback.empty()) + safe_fallback = "Part"; + + std::map cleaned; + std::vector result; + result.reserve(names.size()); + for (const auto& name : names) { + if (!has_unsupported_name_characters(name)) { + result.push_back(name); + continue; + } + // Equal original names stay equal even when both require the same cleaning. + const auto previous = cleaned.find(name); + if (previous != cleaned.end()) { + result.push_back(previous->second); + continue; + } + std::string base = replace_characters(name, replacement); + if (base.empty()) + base = safe_fallback; + std::string candidate = base; + for (size_t suffix = 2; reserved.count(candidate) != 0; ++suffix) + candidate = base + " (" + std::to_string(suffix) + ")"; + reserved.insert(candidate); + cleaned.emplace(name, candidate); + result.push_back(candidate); + } + return result; +} + +} // namespace Slic3r diff --git a/src/libslic3r/Format/ImportNames.hpp b/src/libslic3r/Format/ImportNames.hpp new file mode 100644 index 0000000000..dc6ba84e34 --- /dev/null +++ b/src/libslic3r/Format/ImportNames.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include +#include + +namespace Slic3r { + +// Names follow Orca's rename restrictions as well as XML 1.0 and UTF-8 requirements. +bool has_unsupported_name_characters(const std::string& name); +bool valid_import_name_replacement(const std::string& replacement); + +// Empty replacement means removal; only collisions introduced by cleaning receive suffixes. +std::vector sanitize_import_names(const std::vector& names, + const std::string& replacement, + const std::string& fallback = "Part"); + +} // namespace Slic3r diff --git a/src/libslic3r/Format/ProjectStrategy.hpp b/src/libslic3r/Format/ProjectStrategy.hpp index a274dd52b9..7ff3d8a23c 100644 --- a/src/libslic3r/Format/ProjectStrategy.hpp +++ b/src/libslic3r/Format/ProjectStrategy.hpp @@ -18,6 +18,9 @@ enum class LoadStrategy LoadAuxiliary = 16, Silence = 32, ImperialUnits = 64, + // Geometry-import policies are opt-in; opening existing projects retains its defaults. + KeepOriginalNames = 128, + AssembleParts = 256, Restore = 0x10000 | LoadModel | LoadConfig | LoadAuxiliary | Silence, }; diff --git a/src/libslic3r/Format/STEP.cpp b/src/libslic3r/Format/STEP.cpp index 3e59ef52a7..b26b6a7259 100644 --- a/src/libslic3r/Format/STEP.cpp +++ b/src/libslic3r/Format/STEP.cpp @@ -14,7 +14,10 @@ #include #include #include +#include #include +#include +#include #include #include #include @@ -48,6 +51,7 @@ #include "XCAFDoc_ShapeTool.hxx" #include "XCAFApp_Application.hxx" #include "NCollection_Sequence.hxx" +#include #include "TDF_Label.hxx" #include "TopoDS_Solid.hxx" #include "TopoDS_Compound.hxx" @@ -59,6 +63,16 @@ #include "BRep_Tool.hxx" #include "BRepTools.hxx" #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include namespace fs = boost::filesystem; @@ -69,7 +83,7 @@ bool StepPreProcessor::preprocess(const char* path, std::string &output_path) { boost::nowide::ifstream infile(path); if (!infile.good()) { - throw Slic3r::RuntimeError(_u8L("Load step file failed.\nCannot open file for reading.\n")); + throw Slic3r::RuntimeError(_u8L("Load STEP file failed.\nCannot open file for reading.\n")); return false; } @@ -117,7 +131,7 @@ bool StepPreProcessor::isUtf8File(const char* path) { boost::nowide::ifstream infile(path); if (!infile.good()) { - throw Slic3r::RuntimeError(_u8L("Load step file failed.\nCannot open file for reading.\n")); + throw Slic3r::RuntimeError(_u8L("Load STEP file failed.\nCannot open file for reading.\n")); return false; } @@ -201,13 +215,41 @@ int StepPreProcessor::preNum(const unsigned char byte) { return num; } +using StepBodyNames = NCollection_DataMap; + +// Resolve the original topology before BRepBuilderAPI_Transform copies its TShape. +static void add_named_solid(std::vector& namedSolids, const TopoDS_Shape& mesh_shape, const TopoDS_Shape& source, + const StepBodyNames* body_names, const std::string& fallback) +{ + if (body_names != nullptr && body_names->IsBound(source)) + namedSolids.emplace_back(mesh_shape, body_names->Find(source), true); + else + namedSolids.emplace_back(mesh_shape, fallback); +} + +// The single body of a compound, or a null shape when Split compound would produce several parts. +static TopoDS_Shape single_body(const TopoDS_Shape& compound) +{ + TopoDS_Shape body; + int bodies = 0; + TopExp_Explorer explorer; + for (explorer.Init(compound, TopAbs_SOLID); explorer.More(); explorer.Next(), ++bodies) + body = explorer.Current(); + for (explorer.Init(compound, TopAbs_SHELL, TopAbs_SOLID); explorer.More(); explorer.Next(), ++bodies) + body = explorer.Current(); + explorer.Init(compound, TopAbs_FACE, TopAbs_SHELL); + // Loose faces form one more part, so the compound is then not a single body. + return bodies == 1 && !explorer.More() ? body : TopoDS_Shape(); +} + static void getNamedSolids(const TopLoc_Location& location, const std::string& prefix, unsigned int& id, const Handle(XCAFDoc_ShapeTool) shapeTool, const TDF_Label label, std::vector& namedSolids, - bool isSplitCompound = false) { + bool isSplitCompound = false, + const StepBodyNames* body_names = nullptr) { TDF_Label referredLabel{label}; if (shapeTool->IsReference(label)) shapeTool->GetReferredShape(label, referredLabel); @@ -226,7 +268,7 @@ static void getNamedSolids(const TopLoc_Location& location, NCollection_Sequence components; if (shapeTool->GetComponents(referredLabel, components)) { for (int compIndex = 1; compIndex <= components.Length(); ++compIndex) { - getNamedSolids(localLocation, fullName, id, shapeTool, components.Value(compIndex), namedSolids, isSplitCompound); + getNamedSolids(localLocation, fullName, id, shapeTool, components.Value(compIndex), namedSolids, isSplitCompound, body_names); } } else { TopoDS_Shape shape; @@ -239,23 +281,30 @@ static void getNamedSolids(const TopLoc_Location& location, case TopAbs_COMPOUND: case TopAbs_COMPSOLID: if (!isSplitCompound) { - namedSolids.emplace_back(transform.Shape(), fullName); + // One body keeps its label without splitting; the mesh is the unchanged compound. + const TopoDS_Shape body = single_body(shape); + if (body.IsNull()) + namedSolids.emplace_back(transform.Shape(), fullName); + else + add_named_solid(namedSolids, transform.Shape(), body, body_names, fullName); } else { - for (explorer.Init(transform.Shape(), TopAbs_SOLID); explorer.More(); explorer.Next()) { + for (explorer.Init(shape, TopAbs_SOLID); explorer.More(); explorer.Next()) { i++; const TopoDS_Shape& currentShape = explorer.Current(); - namedSolids.emplace_back(TopoDS::Solid(currentShape), fullName + "-SOLID-" + std::to_string(i)); + add_named_solid(namedSolids, transform.ModifiedShape(currentShape), currentShape, body_names, + fullName + "-SOLID-" + std::to_string(i)); } // Surface models have no solids: each shell outside a solid is a part, and loose faces stay together. i = 0; - for (explorer.Init(transform.Shape(), TopAbs_SHELL, TopAbs_SOLID); explorer.More(); explorer.Next()) - namedSolids.emplace_back(explorer.Current(), fullName + "-SHELL-" + std::to_string(++i)); + for (explorer.Init(shape, TopAbs_SHELL, TopAbs_SOLID); explorer.More(); explorer.Next()) + add_named_solid(namedSolids, transform.ModifiedShape(explorer.Current()), explorer.Current(), body_names, + fullName + "-SHELL-" + std::to_string(++i)); TopoDS_Compound loose_faces; TopoDS_Builder builder; builder.MakeCompound(loose_faces); bool has_loose_faces = false; - for (explorer.Init(transform.Shape(), TopAbs_FACE, TopAbs_SHELL); explorer.More(); explorer.Next()) { - builder.Add(loose_faces, explorer.Current()); + for (explorer.Init(shape, TopAbs_FACE, TopAbs_SHELL); explorer.More(); explorer.Next()) { + builder.Add(loose_faces, transform.ModifiedShape(explorer.Current())); has_loose_faces = true; } if (has_loose_faces) @@ -263,10 +312,10 @@ static void getNamedSolids(const TopLoc_Location& location, } break; case TopAbs_SOLID: - namedSolids.emplace_back(TopoDS::Solid(transform.Shape()), fullName); + add_named_solid(namedSolids, TopoDS::Solid(transform.Shape()), shape, body_names, fullName); break; case TopAbs_SHELL: - namedSolids.emplace_back(TopoDS::Shell(transform.Shape()), fullName); + add_named_solid(namedSolids, TopoDS::Shell(transform.Shape()), shape, body_names, fullName); break; default: break; @@ -486,8 +535,9 @@ void Step::update_process(int load_stage, int current, int total, bool& cancel) } } -Step::Step_Status Step::load() +Step::Step_Status Step::load(bool collect_original_names) { + m_body_names.Clear(); if (!StepPreProcessor::isUtf8File(m_path.c_str()) && m_utf8Fn) { m_utf8Fn(false); return Step_Status::LOAD_ERROR; @@ -512,6 +562,27 @@ Step::Step_Status Step::load() } if (cb_cancel) return; progress = 6; + if (collect_original_names) { + // The transfer process records which BREP produced each shape, independently of traversal order. + const auto step_model = reader.Reader().StepModel(); + const auto transfer = reader.Reader().WS()->TransferReader()->TransientProcess(); + for (int entity_index = 1; entity_index <= step_model->NbEntities(); ++entity_index) { + const auto entity = step_model->Value(entity_index); + if (!entity->IsKind(STANDARD_TYPE(StepShape_ManifoldSolidBrep)) && + !entity->IsKind(STANDARD_TYPE(StepShape_ConnectedFaceSet)) && + !entity->IsKind(STANDARD_TYPE(StepShape_ShellBasedSurfaceModel))) + continue; + const auto item = Handle(StepRepr_RepresentationItem)::DownCast(entity); + if (item.IsNull() || item->Name().IsNull() || item->Name()->IsEmpty()) + continue; + const std::string body_name = item->Name()->ToCString(); + if (!StepPreProcessor::isUtf8(body_name)) + continue; + const TopoDS_Shape original_shape = TransferBRep::ShapeResult(transfer, entity); + if (!original_shape.IsNull() && !m_body_names.IsBound(original_shape)) + m_body_names.Bind(original_shape, body_name); + } + } m_shape_tool = XCAFDoc_DocumentTool::ShapeTool(m_doc->Main()); NCollection_Sequence topLevelShapes; m_shape_tool->GetFreeShapes(topLevelShapes); @@ -521,6 +592,11 @@ Step::Step_Status Step::load() if (cb_cancel) return; getNamedSolids(TopLoc_Location{}, "", id, m_shape_tool, topLevelShapes.Value(iLabel), m_name_solids); } + // Without Split compound these leaves stay whole; a multi-body one would lose its body names. + m_multi_body_compound = std::any_of(m_name_solids.begin(), m_name_solids.end(), [](const NamedSolid& leaf) { + const TopAbs_ShapeEnum type = leaf.solid.ShapeType(); + return (type == TopAbs_COMPOUND || type == TopAbs_COMPSOLID) && single_body(leaf.solid).IsNull(); + }); progress = 10; load_result = true; task_result = true; @@ -557,7 +633,8 @@ Step::Step_Status Step::mesh(Model* model, bool& is_cancel, bool isSplitCompound, double linear_deflection/*=0.003*/, - double angle_deflection/*= 0.5*/) + double angle_deflection/*= 0.5*/, + bool keep_original_names/*= false*/) { bool task_result = false; @@ -582,8 +659,12 @@ Step::Step_Status Step::mesh(Model* model, if (cb_cancel) { return; } - getNamedSolids(TopLoc_Location{}, "", id, m_shape_tool, topLevelShapes.Value(iLabel), namedSolids, isSplitCompound); + getNamedSolids(TopLoc_Location{}, "", id, m_shape_tool, topLevelShapes.Value(iLabel), namedSolids, + isSplitCompound, keep_original_names ? &m_body_names : nullptr); } + // A single part is not listed under its object, so the object shows the body label instead. + if (namedSolids.size() == 1 && namedSolids.front().original_name) + new_object->name = namedSolids.front().name; std::vector stl; stl.resize(namedSolids.size()); diff --git a/src/libslic3r/Format/STEP.hpp b/src/libslic3r/Format/STEP.hpp index 5d18f9e88f..422c0ea0cb 100644 --- a/src/libslic3r/Format/STEP.hpp +++ b/src/libslic3r/Format/STEP.hpp @@ -5,6 +5,9 @@ #include "XCAFDoc_ShapeTool.hxx" #include #include +#include +#include +#include #include #include #include @@ -37,10 +40,13 @@ typedef std::function StepIsUtf8Fn; struct NamedSolid { NamedSolid(const TopoDS_Shape& s, - const std::string& n) : solid{ s }, name{ n } { + const std::string& n, + bool original = false) : solid{ s }, name{ n }, original_name{ original } { } const TopoDS_Shape solid; const std::string name; + // The name is the CAD body label rather than a generated or product name. + const bool original_name; int tri_face_cout = 0; }; @@ -106,7 +112,14 @@ public: Step(boost::filesystem::path path, ImportStepProgressFn stepFn = nullptr, StepIsUtf8Fn isUtf8Fn = nullptr); Step(std::string path, ImportStepProgressFn stepFn = nullptr, StepIsUtf8Fn isUtf8Fn = nullptr); ~Step(); - Step_Status load(); + Step_Status load(bool collect_original_names = false); + // The import dialog may change this preference after the CAD document is read. + void set_keep_original_names(bool keep) { m_keep_original_names = keep; } + bool keep_original_names() const { return m_keep_original_names; } + // Valid after load(true): the file stores body labels that Keep original names can apply. + bool has_original_names() const { return !m_body_names.IsEmpty(); } + // Valid after load(): some compound holds several bodies, so their names need Split compound. + bool has_multi_body_compound() const { return m_multi_body_compound; } unsigned int get_triangle_num(double linear_deflection, double angle_deflection); unsigned int get_triangle_num_tbb(double linear_deflection, double angle_deflection); void clean_mesh_data(); @@ -114,7 +127,8 @@ public: bool& is_cancel, bool isSplitCompound, double linear_deflection = 0.003, - double angle_deflection = 0.5); + double angle_deflection = 0.5, + bool keep_original_names = false); std::atomic m_stop_mesh{false}; void update_process(int load_stage, int current, int total, bool& cancel); @@ -126,6 +140,10 @@ private: Handle(TDocStd_Document) m_doc; Handle(XCAFDoc_ShapeTool) m_shape_tool; std::vector m_name_solids; + // Keys retain the exact transferred topology and location, before copied transforms. + NCollection_DataMap m_body_names; + bool m_keep_original_names = false; + bool m_multi_body_compound = false; }; }; // namespace Slic3r diff --git a/src/libslic3r/Format/bbs_3mf.cpp b/src/libslic3r/Format/bbs_3mf.cpp index d00349fb66..4d07e2606e 100644 --- a/src/libslic3r/Format/bbs_3mf.cpp +++ b/src/libslic3r/Format/bbs_3mf.cpp @@ -351,6 +351,7 @@ static constexpr const char* TRANSFORM_ATTR = "transform"; static constexpr const char* OFFSET_ATTR = "offset"; static constexpr const char* PRINTABLE_ATTR = "printable"; static constexpr const char* AUTO_DROP_ATTR = "auto_drop"; +static constexpr const char* IMPORTED_PARTS_HIDDEN_KEY = "orca:imported_parts_hidden"; static constexpr const char* INSTANCESCOUNT_ATTR = "instances_count"; static constexpr const char* CUSTOM_SUPPORTS_ATTR = "paint_supports"; static constexpr const char* CUSTOM_FUZZY_SKIN_ATTR = "paint_fuzzy_skin"; @@ -1167,6 +1168,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) bool m_load_model = false; bool m_load_aux = false; bool m_load_config = false; + bool m_keep_original_names = false; // backup & restore bool m_load_restore = false; std::string m_backup_path; @@ -1492,6 +1494,8 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) m_load_aux = strategy & LoadStrategy::LoadAuxiliary; m_load_restore = strategy & LoadStrategy::Restore; m_load_config = strategy & LoadStrategy::LoadConfig; + // Project part metadata remains authoritative; the opt-in only fills missing CAD labels. + m_keep_original_names = (strategy & LoadStrategy::KeepOriginalNames) && !m_load_config; m_model = &model; m_unit_factor = 1.0f; m_curr_object = nullptr; @@ -2259,6 +2263,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) ObjectMetadata::VolumeMetadataList volumes; ObjectMetadata::VolumeMetadataList* volumes_ptr = nullptr; + bool imported_parts_hidden = false; // 2.4.x stored auto_drop on build items, shared by all instances of an object; any "off" wins const bool legacy_auto_drop = !m_items_auto_drop_off.count(object.first.second); @@ -2273,6 +2278,9 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) for (const Metadata& metadata : obj_metadata->second.metadata) { if (metadata.key == "name") model_object->name = metadata.value; + // This is model presentation state, never a print configuration option. + else if (metadata.key == IMPORTED_PARTS_HIDDEN_KEY) + imported_parts_hidden = metadata.value == "1"; //BBS: add module name else if (metadata.key == "module") model_object->module_name = metadata.value; @@ -2316,6 +2324,8 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) if (!_generate_volumes_new(*model_object, object_id_list, *volumes_ptr, config_substitutions)) return false; + // add_volume reveals edited objects, so restore persisted presentation after creation. + model_object->imported_parts_hidden = imported_parts_hidden; // Apply cut information for object if any was loaded // m_cut_object_ids are indexed by a 1 based model object index. @@ -5476,6 +5486,8 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) } // this may happen for 3mf saved by 3rd part softwares + if (volume->name.empty() && m_keep_original_names) + volume->name = sub_object->name; if (volume->name.empty()) { volume->name = object.name; if (renamed_volumes_count > 0) @@ -8321,6 +8333,9 @@ bool _BBS_3MF_Exporter::_add_model_config_file_to_archive(mz_zip_archive& archiv stream << " <" << METADATA_TAG << " " << KEY_ATTR << "=\"module\" " << VALUE_ATTR << "=\"" << xml_escape(obj->module_name) << "\"/>\n"; // stores object's config data + if (obj->imported_parts_hidden) + stream << " <" << METADATA_TAG << " " << KEY_ATTR << "=\"" << IMPORTED_PARTS_HIDDEN_KEY + << "\" " << VALUE_ATTR << "=\"1\"/>\n"; for (const std::string& key : obj->config.keys()) { stream << " <" << METADATA_TAG << " " << KEY_ATTR << "=\"" << key << "\" " << VALUE_ATTR << "=\"" << obj->config.opt_serialize(key) << "\"/>\n"; } diff --git a/src/libslic3r/Format/svg.cpp b/src/libslic3r/Format/svg.cpp index 6b67f766cf..093fe1cc66 100644 --- a/src/libslic3r/Format/svg.cpp +++ b/src/libslic3r/Format/svg.cpp @@ -144,11 +144,11 @@ bool get_svg_profile(const char *path, std::vector &element_infos, NSVGimage *svg_data = nullptr; svg_data = nsvgParseFromFile(path, "mm", 96.0f); if (svg_data == nullptr) { - message = _u8L("import svg failed: could not open svg."); + message = _u8L("import SVG failed: could not open SVG."); return false; } if (svg_data->shapes == nullptr) { - message = _u8L("import svg failed: could not parse imported svg data."); + message = _u8L("import SVG failed: could not parse imported SVG data."); return false; } diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index 4312271a03..d876c93dc1 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -3489,9 +3489,13 @@ void GCode::_do_export(Print& print, GCodeOutputStream &file, ThumbnailsGenerato // Undo what point_to_gcode() added (m_origin, minus the extruder offset) and // what the writer then took off (its XY offset, the plate origin). const Vec2d plate_offset = m_writer.get_xy_offset().cast(); + // Judged like the path the travel leads to (see belt_path_height()). + if (m_belt_travel_target != nullptr && m_belt_travel_target->role() == erBrim) + return true; return this->on_first_layer(Vec3d(point_logical.x() - (m_origin.x() - plate_offset.x()) + extruder_offset.x(), point_logical.y() - (m_origin.y() - plate_offset.y()) + extruder_offset.y(), - point_logical.z())); + point_logical.z()), + m_belt_travel_target != nullptr ? m_belt_travel_target->width : 0.); }); } @@ -9229,6 +9233,89 @@ static bool overhang_fan_active(float overlap, int overhang_fan_threshold, Extru } std::string GCode::_extrude(const ExtrusionPath &path, const std::string &path_description, double speed) +{ + std::vector> uncut_line_lengths; + const ExtrusionPaths pieces = this->belt_cut_at_band_edges(path, uncut_line_lengths); + if (pieces.size() < 2) + return this->_extrude_piece(path, path_description, speed); + std::string gcode; + for (size_t i = 0; i < pieces.size(); ++ i) { + m_belt_uncut_line_lengths = &uncut_line_lengths[i]; + gcode += this->_extrude_piece(pieces[i], path_description, speed); + } + m_belt_uncut_line_lengths = nullptr; + return gcode; +} + +// Belt printers: whether a path is on the first layer, and its step of the slow_down_layers +// ramp, set its speed, flow and acceleration as a whole. A wall loop runs from the belt up +// the part, so a path is cut where it crosses the edge of the first-layer band above the belt +// or of a band of the ramp, and each piece is judged on its own. Otherwise the loop would +// take the settings of wherever its seam is all the way round. Returns no pieces when the +// path stays in one band, and else, for each piece, the length of the uncut line each of its +// lines comes from, so that small-area flow compensation sees the line as it was. +ExtrusionPaths GCode::belt_cut_at_band_edges(const ExtrusionPath &path, std::vector> &uncut_line_lengths) const +{ + ExtrusionPaths pieces; + // A sloped seam carries its slope along it, and a contoured path scales each line's + // extrusion by the Z offset at the line's end, which a cut would move; both are judged + // whole. + if (! m_config.belt_printer.value || path.z_contoured || dynamic_cast(&path) != nullptr) + return pieces; + // Band 0 is the first layer as on_first_layer() has it, band k > 0 the heights the ramp + // gives step k (effective_layer_index_for_point()), the last one everything above it. + const double first = m_config.initial_layer_print_height.value; + const double band = this->first_layer_band_mm(); + const int last = std::max(1, m_config.slow_down_layers.value); + auto band_of = [this, first, last](double h) { + return h <= first + EPSILON ? 0 : std::clamp(this->belt_band_index(h), 1, last); + }; + auto band_top = [first, band](int k) { return k == 0 ? first : (k + 1) * band; }; + const Points3 &points = path.polyline.points; + double h_prev; + if (points.size() < 2 || ! this->belt_path_height(path, points.front(), h_prev)) + return pieces; + int band_prev = band_of(h_prev); + Points3 current{ points.front() }; + std::vector current_lengths; + auto extend = [¤t, ¤t_lengths](const Point3 &p, double uncut_length) { + if (p != current.back()) { + current.push_back(p); + current_lengths.push_back(uncut_length); + } + }; + for (size_t i = 1; i < points.size(); ++ i) { + double h; + this->belt_path_height(path, points[i], h); + const int band_i = band_of(h); + const double length = unscale((points[i] - points[i - 1]).cast().norm()); + // Cut at each edge the segment crosses. The belt is a plane, so the height is + // linear along the segment. + for (int k = band_prev; k != band_i; k += band_i > band_prev ? 1 : -1) { + const double edge = band_top(band_i > band_prev ? k : k - 1); + const double t = std::clamp((edge - h_prev) / (h - h_prev), 0., 1.); + const Vec3d cut = points[i - 1].cast() + t * (points[i] - points[i - 1]).cast(); + const Point3 cut_point(cut.x(), cut.y(), cut.z()); + extend(cut_point, length); + if (current.size() > 1) { + pieces.emplace_back(Polyline3(current), path); + uncut_line_lengths.emplace_back(std::move(current_lengths)); + } + current = { cut_point }; + current_lengths.clear(); + } + extend(points[i], length); + h_prev = h; + band_prev = band_i; + } + if (! pieces.empty() && current.size() > 1) { + pieces.emplace_back(Polyline3(current), path); + uncut_line_lengths.emplace_back(std::move(current_lengths)); + } + return pieces; +} + +std::string GCode::_extrude_piece(const ExtrusionPath &path, const std::string &path_description, double speed) { std::string gcode; @@ -9240,15 +9327,29 @@ std::string GCode::_extrude(const ExtrusionPath &path, const std::string &path_d // evaluator is inactive (non-belt printers, or belt printers without // a Z-axis shear) `path_on_first_layer` falls back to the legacy // layer-id check, so behavior is bit-identical to the pre-feature path. - // A belt brim apron band has no Layer of its own, so it publishes its Z - // through m_belt_brim_z instead; without that the plane would be probed at - // Z=0 and the apron mis-classified for fan and speed. const Vec3d path_point_mm{ unscale(path.first_point().x()), unscale(path.first_point().y()), m_layer ? m_layer->print_z : (m_belt_brim_z ? *m_belt_brim_z : 0.0) }; - const bool path_on_first_layer = this->on_first_layer(path_point_mm); + bool path_on_first_layer = this->on_first_layer(path_point_mm); + // On a belt a path is judged by how high above the belt all of it is: it is on the first + // layer when all of it is, and takes the slow_down_layers step of its middle. A piece cut + // at the edge of a band (see belt_cut_at_band_edges()) starts or ends on the edge, so + // neither of its ends would do. + int belt_layer = -1; + if (m_config.belt_printer.value) { + double lo = std::numeric_limits::max(), hi = std::numeric_limits::lowest(), h; + for (const Point3 &p : path.polyline.points) + if (this->belt_path_height(path, p, h)) { + lo = std::min(lo, h); + hi = std::max(hi, h); + } + if (lo <= hi) { + path_on_first_layer = hi <= m_config.initial_layer_print_height.value + EPSILON; + belt_layer = path_on_first_layer ? 0 : std::max(1, this->belt_band_index(0.5 * (lo + hi))); + } + } const ExtrusionPathSloped* sloped = dynamic_cast(&path); @@ -9277,7 +9378,10 @@ std::string GCode::_extrude(const ExtrusionPath &path, const std::string &path_d z = unscale_(path.polyline.lines().begin()->a.z()) + m_nominal_z; } + // The writer's first-layer test judges the travel like the path it leads to. + m_belt_travel_target = &path; gcode += this->travel_to(first_point, path.role(), "move to first " + description + " point", z); + m_belt_travel_target = nullptr; // Orca: ensure Z matches planned layer height if (!slope_need_z_travel && (_last_pos_undefined || m_need_change_layer_lift_z)) { @@ -9483,16 +9587,18 @@ std::string GCode::_extrude(const ExtrusionPath &path, const std::string &path_d // Use the belt-aware effective layer index when on a belt printer so // the speed fade tracks perpendicular distance from the plane on // belt printers; otherwise this falls back to the slicing layer id. - const int _layer = this->effective_layer_index_for_point(path_point_mm); + const int _layer = belt_layer >= 0 ? belt_layer : this->effective_layer_index_for_point(path_point_mm); // Belt printers: a tilted layer runs from the belt to the top of the part, so the // "first layers" the fan stays off for are a band along the belt. Mark where the // extrusion enters and leaves it, per segment, for the cooling buffer. const bool belt_band_tags = m_enable_cooling_markers && m_config.belt_printer.value; const int belt_band_layers = belt_band_tags ? m_config.close_fan_the_first_x_layers.get_at(m_writer.filament()->id()) : 0; - auto tag_belt_band = [this, &gcode, belt_band_tags, belt_band_layers, z = path_point_mm.z()](coord_t x, coord_t y) { + auto tag_belt_band = [this, &gcode, &path, &path_point_mm, belt_band_tags, belt_band_layers](const Point3 &p) { if (! belt_band_tags) return; - const bool in_band = this->effective_layer_index_for_point(Vec3d(unscale(x), unscale(y), z)) < belt_band_layers; + double h; + const int layer = this->belt_path_height(path, p, h) ? this->belt_band_index(h) : this->effective_layer_index_for_point(path_point_mm); + const bool in_band = layer < belt_band_layers; if (in_band != m_belt_in_band) { gcode += in_band ? ";_BELT_BAND_START\n" : ";_BELT_BAND_END\n"; m_belt_in_band = in_band; @@ -9620,6 +9726,11 @@ std::string GCode::_extrude(const ExtrusionPath &path, const std::string &path_d fan_overlap_threshold = overhang_fan_overlap_threshold(FILAMENT_CONFIG(overhang_fan_threshold)); if (NOZZLE_CONFIG(slowdown_for_curled_perimeters)){ + const FloatOrPercent fully_unsupported_speed = path.role() == erBridgeInfill ? + FloatOrPercent{NOZZLE_CONFIG(bridge_speed) * 100 / ref_speed, true} : + (NOZZLE_CONFIG(overhang_4_4_speed).get_abs_value(ref_speed) < 0.5 ? + FloatOrPercent{100, true} : + FloatOrPercent{NOZZLE_CONFIG(overhang_4_4_speed).get_abs_value(ref_speed) * 100 / ref_speed, true}); ConfigOptionFloatsOrPercents dynamic_overhang_speeds( {FloatOrPercent{100, true}, (NOZZLE_CONFIG(overhang_1_4_speed).get_abs_value(ref_speed) < 0.5) ? @@ -9634,9 +9745,7 @@ std::string GCode::_extrude(const ExtrusionPath &path, const std::string &path_d (NOZZLE_CONFIG(overhang_4_4_speed).get_abs_value(ref_speed) < 0.5) ? FloatOrPercent{100, true} : FloatOrPercent{NOZZLE_CONFIG(overhang_4_4_speed).get_abs_value(ref_speed) * 100 / ref_speed, true}, - (NOZZLE_CONFIG(overhang_4_4_speed).get_abs_value(ref_speed) < 0.5) ? - FloatOrPercent{100, true} : - FloatOrPercent{NOZZLE_CONFIG(overhang_4_4_speed).get_abs_value(ref_speed) * 100 / ref_speed, true}}); + fully_unsupported_speed}); new_points = m_extrusion_quality_estimator.estimate_extrusion_quality(path, overhang_overlap_levels, dynamic_overhang_speeds, ref_speed, speed, NOZZLE_CONFIG(slowdown_for_curled_perimeters), @@ -9960,7 +10069,11 @@ std::string GCode::_extrude(const ExtrusionPath &path, const std::string &path_d double total_length = sloped == nullptr ? 0. : path.polyline.length() * SCALING_FACTOR; double saved_z = m_writer.get_position().z(); + size_t line_idx = 0; for (const Line3& line : path.polyline.lines()) { + // A line cut at a band edge above a belt is compensated as the line it was. + const double uncut_length = m_belt_uncut_line_lengths != nullptr ? (*m_belt_uncut_line_lengths)[line_idx] : 0.; + ++ line_idx; std::string flow_description; const double line_length = line.length() * SCALING_FACTOR; if (line_length < EPSILON) @@ -9969,13 +10082,13 @@ std::string GCode::_extrude(const ExtrusionPath &path, const std::string &path_d auto dE = e_per_mm * line_length; if (_needSAFC(path)) { auto oldE = dE; - dE = m_small_area_infill_flow_compensator->modify_flow(line_length, dE, path.role()); + dE = m_small_area_infill_flow_compensator->modify_flow(m_belt_uncut_line_lengths != nullptr ? uncut_length : line_length, dE, path.role()); if (m_config.gcode_comments && oldE > 0 && oldE != dE) { flow_description = description + Slic3r::format(" | Old Flow Value: %0.5f Length: %0.5f",oldE, line_length); } } - tag_belt_band((line.a.x() + line.b.x()) / 2, (line.a.y() + line.b.y()) / 2); + tag_belt_band(line.midpoint()); if (path.z_contoured) { // ZAA: Z anti-aliased extrusion with variable Z per point Vec2d dest2d = this->point_to_gcode(line.b.to_point()); @@ -10106,7 +10219,7 @@ std::string GCode::_extrude(const ExtrusionPath &path, const std::string &path_d const ProcessedPoint &processed_point = new_points[i]; const ProcessedPoint &pre_processed_point = new_points[i-1]; Vec3d p = this->point_to_gcode_quantized(processed_point.p); - tag_belt_band((pre_processed_point.p.x() + processed_point.p.x()) / 2, (pre_processed_point.p.y() + processed_point.p.y()) / 2); + tag_belt_band(Point3((pre_processed_point.p + processed_point.p) / 2)); if (m_enable_cooling_markers) { if (enable_overhang_bridge_fan) { cur_fan_enabled = overhang_fan_active(processed_point.overlap, overhang_fan_threshold, path.role()); @@ -11493,7 +11606,22 @@ int GCode::belt_layer_past_first_layer_band(const Layer *object_layer) const return min_height >= this->first_layer_band_mm() - EPSILON ? 1 : 0; } -bool GCode::belt_height_above_floor(const Vec3d &point_slicing_mm, double &height_mm) const +bool GCode::belt_path_height(const ExtrusionPath &path, const Point3 &p, double &height_mm) const +{ + // A belt brim apron band has no Layer of its own, so it publishes its Z through + // m_belt_brim_z; without that the belt would be probed at Z=0 and the apron + // misjudged for fan and speed. + const double z = m_layer ? m_layer->print_z : (m_belt_brim_z ? *m_belt_brim_z : 0.0); + const Vec3d point(unscale(p.x()), unscale(p.y()), path.z_contoured ? z + unscale(p.z()) : z); + if (! this->belt_height_above_floor(point, height_mm, path.width)) + return false; + // The brim's lines are as wide as the bands are far apart, not as the bead they lay. + if (path.role() == erBrim) + height_mm = 0.; + return true; +} + +bool GCode::belt_height_above_floor(const Vec3d &point_slicing_mm, double &height_mm, double width) const { // The owning object, which is what carries the belt description. During // object-brim and coincident-apron emission m_layer still points at whichever @@ -11517,7 +11645,7 @@ bool GCode::belt_height_above_floor(const Vec3d &point_slicing_mm, double &heigh // horizontal slabs in the sliced frame, so the slab holding the material that // rests on the belt at this point is the one within one layer height of it. // A perpendicular measure would shrink the band by 1/cos(tilt). - height_mm = point_slicing_mm.z() - floor_z; + height_mm = point_slicing_mm.z() - floor_z - 0.5 * width * std::abs(sp.belt_floor_shear_factor); return true; } diff --git a/src/libslic3r/GCode.hpp b/src/libslic3r/GCode.hpp index e5fb414cd3..03c5325953 100644 --- a/src/libslic3r/GCode.hpp +++ b/src/libslic3r/GCode.hpp @@ -962,6 +962,12 @@ protected: // The last extrusion segment was inside the belt's first-layer fan band (see _extrude()). bool m_belt_in_band{false}; + // The path that the travel being emitted leads to, for the writer's first-layer test on a + // belt; null for any other travel. + const ExtrusionPath *m_belt_travel_target{nullptr}; + // For a path cut at the edges of the bands above a belt (see _extrude()), the length, mm, + // of the uncut line each of its lines comes from; null for any other path. + const std::vector *m_belt_uncut_line_lengths{nullptr}; std::set m_initial_layer_extruders; std::vector> m_sorted_layer_filaments; @@ -973,6 +979,9 @@ protected: double calc_max_volumetric_speed(const double layer_height, const double line_width, const std::string co_str); std::string _extrude(const ExtrusionPath &path, const std::string &path_description = "", double speed = -1); + ExtrusionPaths belt_cut_at_band_edges(const ExtrusionPath &path, std::vector> &uncut_line_lengths) const; + // _extrude() of a path that stays in one band above the belt (see belt_cut_at_band_edges()). + std::string _extrude_piece(const ExtrusionPath &path, const std::string &path_description, double speed); bool _needSAFC(const ExtrusionPath &path); void print_machine_envelope(GCodeOutputStream& file, Print& print); void _print_first_layer_bed_temperature(GCodeOutputStream &file, Print &print, const std::string &gcode, unsigned int first_printing_extruder_id, bool wait); @@ -983,10 +992,12 @@ protected: // Per-point first-layer test. On a belt printer the result depends on the // supplied slicing-frame point (its height above the belt); otherwise we // delegate to the legacy per-layer test. This is the entry point used by - // per-path call sites in _extrude. - bool on_first_layer(const Vec3d &point_slicing_mm) const { + // per-path call sites in _extrude and by travels, which pass the width of the + // extrusion they lead to (see belt_height_above_floor()). _extrude_piece() + // judges a belt path by all of its points (see belt_path_height()). + bool on_first_layer(const Vec3d &point_slicing_mm, double width = 0.) const { double h; - if (this->belt_height_above_floor(point_slicing_mm, h)) + if (this->belt_height_above_floor(point_slicing_mm, h, width)) return h <= m_config.initial_layer_print_height.value + EPSILON; return on_first_layer(); } @@ -995,12 +1006,14 @@ protected: // first_layer_band_mm() units; otherwise it is the legacy slicing layer index. int effective_layer_index_for_point(const Vec3d &point_slicing_mm) const { double h; - if (this->belt_height_above_floor(point_slicing_mm, h)) { - const double lh = this->first_layer_band_mm(); - return h <= 0. ? 0 : int(std::floor(h / lh)); - } + if (this->belt_height_above_floor(point_slicing_mm, h)) + return this->belt_band_index(h); return on_first_layer() ? 0 : layer_id(); } + // The effective layer index of a height above the belt. + int belt_band_index(double height_mm) const { + return height_mm <= 0. ? 0 : int(std::floor(height_mm / this->first_layer_band_mm())); + } // Band thickness for the *effective layer index*: one first layer height, so // "the first N layers" means the same height above the belt as on a flat bed. @@ -1016,7 +1029,17 @@ protected: // parameters (belt_floor_shear_factor / _from_axis / _z_shift) -- the same // description the support generator uses, independent of every remap and // back-transform. - bool belt_height_above_floor(const Vec3d &point_slicing_mm, double &height_mm) const; + // + // With `width`, the point is the nozzle over an extrusion that wide, and the height + // is taken above the highest belt under the bead: the belt rises across it, so the + // wall of a tilted layer that rests on the belt has its nozzle half a layer plus + // half its width x tan(tilt) up, more than one first layer at 45 degrees. + bool belt_height_above_floor(const Vec3d &point_slicing_mm, double &height_mm, double width = 0.) const; + // Height above the belt of a point of `path` on the layer being emitted, with the nozzle + // over the path's bead and the Z offset of a contoured path; false when this is not a belt + // print. A brim line rests on the belt by construction, however narrow the spacing of the + // bands makes its bead, so it is at 0. + bool belt_path_height(const ExtrusionPath &path, const Point3 &p, double &height_mm) const; // 1 / 0 / -1: the object layer is entirely past the first-layer band above the // belt / reaches into it / the belt surface is not known for it. int belt_layer_past_first_layer_band(const Layer *object_layer) const; diff --git a/src/libslic3r/MeshBoolean.cpp b/src/libslic3r/MeshBoolean.cpp index 074eff3121..0752d65e95 100644 --- a/src/libslic3r/MeshBoolean.cpp +++ b/src/libslic3r/MeshBoolean.cpp @@ -271,6 +271,10 @@ triangle_mesh_to_cgal(const std::vector &V, { std::unique_ptr out(new CGALMesh{}); triangle_mesh_to_cgal(V, F, out->m); + // CGAL's volume predicate dereferences an incident halfedge for every vertex. + // Remove isolated vertices and compact their indices for conversion back to an ITS. + if (CGALProc::remove_isolated_vertices(out->m) != 0) + out->m.collect_garbage(); return out; } diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index c4cff42a64..6074107d76 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -251,7 +251,9 @@ Model Model::read_from_step(const std::string& bool is_cb_cancel = false; Step::Step_Status status; Step step_file(input_file, stepFn); - status = step_file.load(); + step_file.set_keep_original_names(options & LoadStrategy::KeepOriginalNames); + // A geometry-import dialog can enable names after load, so collect them for that path too. + status = step_file.load(step_file.keep_original_names() || (options & LoadStrategy::AssembleParts)); if(status != Step::Step_Status::LOAD_SUCCESS) { goto _finished; } @@ -262,7 +264,9 @@ Model Model::read_from_step(const std::string& } } - status = step_file.mesh(&model, is_cb_cancel, is_split_compound, linear_deflection, angle_deflection); + // The callback may have changed the name preference after inspecting the CAD document. + status = step_file.mesh(&model, is_cb_cancel, is_split_compound, linear_deflection, angle_deflection, + step_file.keep_original_names()); _finished: @@ -463,7 +467,7 @@ Model Model::read_from_file(const std::string& result = load_drc(input_file.c_str(), &model); else if (boost::algorithm::iends_with(input_file, ".amf")) //BBS: is_xxx is used for is_inches when load amf - result = load_amf(input_file.c_str(), config, config_substitutions, &model, is_xxx); + result = load_amf(input_file.c_str(), config, config_substitutions, &model, is_xxx, options); else if (boost::algorithm::iends_with(input_file, ".3mf")) //BBS: add part plate related logic // BBS: backup & restore @@ -543,7 +547,7 @@ Model Model::read_from_archive(const std::string& input_file, DynamicPrintConfig } } else if (boost::algorithm::iends_with(input_file, ".zip.amf")) - result = load_amf(input_file.c_str(), config, config_substitutions, &model, &is_bbl_3mf); + result = load_amf(input_file.c_str(), config, config_substitutions, &model, &is_bbl_3mf, options); else throw Slic3r::RuntimeError(_L("Unknown file format: input file must have .3mf or .zip.amf extension.")); @@ -904,7 +908,8 @@ bool Model::looks_like_multipart_object() const if (obj->volumes.size() > 1 || obj->config.keys().size() > 1) return false; - double zmin_this = obj->min_z(); + // Objects the file does not place have no instance yet; they read zero, as min_z() did in Release builds. + double zmin_this = obj->instances.empty() ? 0. : obj->min_z(); if (zmin == std::numeric_limits::max()) zmin = zmin_this; else if (std::abs(zmin - zmin_this) > EPSILON) @@ -923,7 +928,7 @@ static inline int auto_extruder_id(unsigned int max_extruders, unsigned int &cnt return out; } -void Model::convert_multipart_object(unsigned int max_extruders) +void Model::convert_multipart_object(unsigned int max_extruders, bool preserve_volume_names) { assert(this->objects.size() >= 2); if (this->objects.size() < 2) @@ -945,9 +950,13 @@ void Model::convert_multipart_object(unsigned int max_extruders) // Revert the centering operation. trafo_volume.set_offset(trafo_volume.get_offset() - o->origin_translation); int counter = 1; - auto copy_volume = [o, v, &counter](ModelVolume *new_v) { + auto copy_volume = [o, v, &counter, preserve_volume_names](ModelVolume *new_v) { assert(new_v != nullptr); - new_v->name = (counter > 1) ? o->name + "_" + std::to_string(counter++) : o->name; + // Existing callers keep their naming; CAD import retains a concrete part name. + if (preserve_volume_names) + new_v->name = v->name.empty() ? o->name : v->name; + else + new_v->name = (counter > 1) ? o->name + "_" + std::to_string(counter++) : o->name; //BBS: Use extruder priority: volumn > object > default if (v->config.option("extruder")) new_v->config.set("extruder", v->config.extruder()); @@ -1285,6 +1294,7 @@ ModelObject& ModelObject::assign_copy(const ModelObject &rhs) this->layer_height_profile = rhs.layer_height_profile; this->printable = rhs.printable; this->auto_drop = rhs.auto_drop; + this->imported_parts_hidden = rhs.imported_parts_hidden; this->origin_translation = rhs.origin_translation; this->cut_id.copy(rhs.cut_id); this->copy_transformation_caches(rhs); @@ -1326,6 +1336,7 @@ ModelObject& ModelObject::assign_copy(ModelObject &&rhs) this->layer_height_profile = std::move(rhs.layer_height_profile); this->printable = std::move(rhs.printable); this->auto_drop = rhs.auto_drop; + this->imported_parts_hidden = rhs.imported_parts_hidden; this->origin_translation = std::move(rhs.origin_translation); this->copy_transformation_caches(rhs); @@ -1388,6 +1399,8 @@ bool ModelObject::make_boolean(ModelObject *cut_object, const std::string &boole ModelVolume *ModelObject::add_volume(const TriangleMesh &mesh, bool modify_to_center_geometry) { + // Newly added parts must remain visible even on a single-object import. + imported_parts_hidden = false; ModelVolume* v = new ModelVolume(this, mesh); this->volumes.push_back(v); if (modify_to_center_geometry) { @@ -1401,6 +1414,7 @@ ModelVolume *ModelObject::add_volume(const TriangleMesh &mesh, bool modify_to_ce ModelVolume *ModelObject::add_volume(TriangleMesh &&mesh, ModelVolumeType type /*= ModelVolumeType::MODEL_PART*/, bool modify_to_center_geometry) { + imported_parts_hidden = false; ModelVolume* v = new ModelVolume(this, std::move(mesh), type); this->volumes.push_back(v); if (modify_to_center_geometry) { @@ -1414,6 +1428,7 @@ ModelVolume *ModelObject::add_volume(TriangleMesh &&mesh, ModelVolumeType type / ModelVolume* ModelObject::add_volume(const ModelVolume &other, ModelVolumeType type /*= ModelVolumeType::INVALID*/) { + imported_parts_hidden = false; ModelVolume* v = new ModelVolume(this, other); if (type != ModelVolumeType::INVALID && v->type() != type) v->set_type(type); @@ -1431,6 +1446,7 @@ ModelVolume* ModelObject::add_volume(const ModelVolume &other, ModelVolumeType t ModelVolume* ModelObject::add_volume(const ModelVolume &other, TriangleMesh &&mesh) { + imported_parts_hidden = false; ModelVolume* v = new ModelVolume(this, other, std::move(mesh)); this->volumes.push_back(v); v->center_geometry_after_creation(); @@ -1442,6 +1458,7 @@ ModelVolume* ModelObject::add_volume(const ModelVolume &other, TriangleMesh &&me ModelVolume* ModelObject::add_volume_with_shared_mesh(const ModelVolume &other, ModelVolumeType type /*= ModelVolumeType::INVALID*/) { + imported_parts_hidden = false; ModelVolume* v = new ModelVolume(this, other.m_mesh); if (type != ModelVolumeType::INVALID && v->type() != type) v->set_type(type); @@ -1511,6 +1528,27 @@ bool ModelObject::is_fuzzy_skin_painted() const return std::any_of(this->volumes.cbegin(), this->volumes.cend(), [](const ModelVolume *mv) { return mv->is_fuzzy_skin_painted(); }); } +bool ModelObject::has_individual_part_settings() const +{ + // Copying objects gives them filament 1, and merging copies it to their parts. + const int object_extruder = this->config.has("extruder") && this->config.extruder() > 0 ? this->config.extruder() : 1; + const bool part_settings = std::any_of(this->volumes.cbegin(), this->volumes.cend(), [object_extruder](const ModelVolume *mv) { + if (!mv->is_model_part() || !mv->texture_displacement_layers.empty()) + return true; + const size_t keys = mv->config.size(); + const bool same_filament = keys == 1 && mv->config.has("extruder") && + (mv->config.extruder() == 0 || mv->config.extruder() == object_extruder); + return keys > 0 && !same_filament; + }); + return part_settings || this->is_fdm_support_painted() || this->is_seam_painted() || this->is_mm_painted() || + this->is_fuzzy_skin_painted(); +} + +bool ModelObject::hides_imported_parts() const +{ + return this->imported_parts_hidden && this->volumes.size() > 1 && !this->has_individual_part_settings(); +} + void ModelObject::sort_volumes(bool full_sort) { // sort volumes inside the object to order "Model Part, Negative Volume, Modifier, Support Blocker and Support Enforcer. " diff --git a/src/libslic3r/Model.hpp b/src/libslic3r/Model.hpp index 6d9797ff67..5f56f981a9 100644 --- a/src/libslic3r/Model.hpp +++ b/src/libslic3r/Model.hpp @@ -403,6 +403,9 @@ public: // Whether this object is snapped to the build plate after transformations. // Instance Z offsets are shared by all instances of an object. bool auto_drop { true }; + // Single-object import keeps named bodies internally until the user reveals its parts. + // A stored choice: part settings or painting still show the parts, see hides_imported_parts(). + bool imported_parts_hidden { false }; // This vector holds position of selected support points for SLA. The data are // saved in mesh coordinates to allow using them for several instances. @@ -458,6 +461,11 @@ public: bool is_mm_painted() const; // Checks if any of object volume is painted using the fuzzy skin painting gizmo. bool is_fuzzy_skin_painted() const; + // Whether a part has settings or painting of its own; a part that only repeats the object's filament has none. + bool has_individual_part_settings() const; + // Whether the object list shows a single-object import without its parts. Never true while + // a part has its own settings or painting, so effective per-part controls stay visible. + bool hides_imported_parts() const; // This object may have a varying layer height by painting or by a table. // Even if true is returned, the layer height profile may be "flat" with no difference to default layering. bool has_custom_layering() const @@ -709,7 +717,7 @@ private: Internal::StaticSerializationWrapper config_wrapper(config); Internal::StaticSerializationWrapper layer_heigth_profile_wrapper(layer_height_profile); ar(name, module_name, input_file, instances, volumes, config_wrapper, layer_config_ranges, layer_heigth_profile_wrapper, - sla_support_points, sla_points_status, sla_drain_holes, printable, auto_drop, origin_translation, brim_points, + sla_support_points, sla_points_status, sla_drain_holes, printable, auto_drop, imported_parts_hidden, origin_translation, brim_points, m_bounding_box_approx, m_bounding_box_approx_valid, m_bounding_box_exact, m_bounding_box_exact_valid, m_min_max_z_valid, m_raw_bounding_box, m_raw_bounding_box_valid, m_raw_mesh_bounding_box, m_raw_mesh_bounding_box_valid, @@ -722,7 +730,7 @@ private: // BBS: add backup, check modify SaveObjectGaurd gaurd(*this); ar(name, module_name, input_file, instances, volumes, config_wrapper, layer_config_ranges, layer_heigth_profile_wrapper, - sla_support_points, sla_points_status, sla_drain_holes, printable, auto_drop, origin_translation, brim_points, + sla_support_points, sla_points_status, sla_drain_holes, printable, auto_drop, imported_parts_hidden, origin_translation, brim_points, m_bounding_box_approx, m_bounding_box_approx_valid, m_bounding_box_exact, m_bounding_box_exact_valid, m_min_max_z_valid, m_raw_bounding_box, m_raw_bounding_box_valid, m_raw_mesh_bounding_box, m_raw_mesh_bounding_box_valid, @@ -832,6 +840,8 @@ class ModelVolume final : public ObjectBase { public: std::string name; + // Session-only tree position; snapshots preserve it without changing project file order. + int import_display_order { -1 }; // struct used by reload from disk command to recover data from disk struct Source { @@ -1253,7 +1263,7 @@ private: // Copying an existing volume, therefore this volume will get a copy of the ID assigned. ModelVolume(ModelObject *object, const ModelVolume &other) : ObjectBase(other), - name(other.name), source(other.source), m_mesh(other.m_mesh), m_convex_hull(other.m_convex_hull), + name(other.name), import_display_order(other.import_display_order), source(other.source), m_mesh(other.m_mesh), m_convex_hull(other.m_convex_hull), config(other.config), m_type(other.m_type), object(object), m_transformation(other.m_transformation), supported_facets(other.supported_facets), seam_facets(other.seam_facets), mmu_segmentation_facets(other.mmu_segmentation_facets), fuzzy_skin_facets(other.fuzzy_skin_facets), @@ -1286,7 +1296,7 @@ private: } // Providing a new mesh, therefore this volume will get a new unique ID assigned. ModelVolume(ModelObject *object, const ModelVolume &other, TriangleMesh &&mesh) : - name(other.name), source(other.source), config(other.config), object(object), m_mesh(new TriangleMesh(std::move(mesh))), m_type(other.m_type), m_transformation(other.m_transformation), + name(other.name), import_display_order(other.import_display_order), source(other.source), config(other.config), object(object), m_mesh(new TriangleMesh(std::move(mesh))), m_type(other.m_type), m_transformation(other.m_transformation), cut_info(other.cut_info), text_configuration(other.text_configuration), emboss_shape(other.emboss_shape) { assert(this->id().valid()); @@ -1343,7 +1353,7 @@ private: // BBS: add backup, check modify bool mesh_changed = false; auto tr = m_transformation; - ar(name, source, m_mesh, m_type, m_material_id, m_transformation, m_is_splittable, has_convex_hull, cut_info); + ar(name, import_display_order, source, m_mesh, m_type, m_material_id, m_transformation, m_is_splittable, has_convex_hull, cut_info); mesh_changed |= !(tr == m_transformation); auto t = supported_facets.timestamp(); cereal::load_by_value(ar, supported_facets); @@ -1379,7 +1389,7 @@ private: } template void save(Archive &ar) const { bool has_convex_hull = m_convex_hull.get() != nullptr; - ar(name, source, m_mesh, m_type, m_material_id, m_transformation, m_is_splittable, has_convex_hull, cut_info); + ar(name, import_display_order, source, m_mesh, m_type, m_material_id, m_transformation, m_is_splittable, has_convex_hull, cut_info); cereal::save_by_value(ar, supported_facets); cereal::save_by_value(ar, seam_facets); cereal::save_by_value(ar, mmu_segmentation_facets); @@ -1845,7 +1855,7 @@ public: void duplicate_objects_grid(size_t x, size_t y, coordf_t dist); bool looks_like_multipart_object() const; - void convert_multipart_object(unsigned int max_extruders); + void convert_multipart_object(unsigned int max_extruders, bool preserve_volume_names = false); bool looks_like_imperial_units() const; void convert_from_imperial_units(bool only_small_volumes); bool looks_like_saved_in_meters() const; diff --git a/src/libslic3r/PlaceholderParser.cpp b/src/libslic3r/PlaceholderParser.cpp index 2b08538fea..a0478799f1 100644 --- a/src/libslic3r/PlaceholderParser.cpp +++ b/src/libslic3r/PlaceholderParser.cpp @@ -2110,7 +2110,7 @@ namespace client first = it; return true; err: - MyContext::throw_exception(L("Invalid utf8 sequence"), IteratorRange(first, last)); + MyContext::throw_exception(L("Invalid UTF-8 sequence"), IteratorRange(first, last)); return false; } diff --git a/src/libslic3r/PresetCacheFormat.cpp b/src/libslic3r/PresetCacheFormat.cpp index 0a2d82cca7..26c8240c4f 100644 --- a/src/libslic3r/PresetCacheFormat.cpp +++ b/src/libslic3r/PresetCacheFormat.cpp @@ -117,10 +117,9 @@ void CacheDictionary::load(cereal::BinaryInputArchive& ar) throw std::runtime_error("preset cache: dictionary is missing its unnamed-enum slot"); // Resolved once per file: every option read after this is a vector index. m_defs.resize(m_keys.size()); - for (size_t i = 0; i < m_keys.size(); ++ i) { - const ConfigOptionDef* def = print_config_def.get(m_keys[i]); - m_defs[i] = (def != nullptr && uint16_t(def->type) == m_types[i]) ? def : nullptr; - } + m_reported.assign(m_keys.size(), char(0)); + for (size_t i = 0; i < m_keys.size(); ++ i) + m_defs[i] = print_config_def.get(m_keys[i]); } // ---- one config ----------------------------------------------------------- @@ -138,10 +137,14 @@ static void save_enum_option(cereal::BinaryOutputArchive& ar, const ConfigOption } } -// `config` may be null, in which case the option is read and dropped. +// `config` may be null, in which case the option is read and dropped. With +// `text` given, the value is also returned as the text a JSON profile would +// carry — the names, comma-separated for a vector, with an int the writer +// could not name as a number or "nil" — for read_config to place a key this +// build types differently through handle_legacy. static void load_enum_option(cereal::BinaryInputArchive& ar, ConfigOptionType type, const ConfigOptionDef* def, DynamicPrintConfig* config, - const CacheDictionary& dict) + const CacheDictionary& dict, std::string* text = nullptr) { uint32_t cnt = 0; ar(cnt); @@ -151,32 +154,38 @@ static void load_enum_option(cereal::BinaryInputArchive& ar, ConfigOptionType ty // whatever follows this option still loads. bool usable = def != nullptr && config != nullptr; std::vector values; - values.reserve(cnt); + if (usable) + values.reserve(cnt); for (uint32_t i = 0; i < cnt; ++ i) { uint16_t idx = 0; ar(idx); if (! dict.valid_enum_index(idx)) throw std::runtime_error("preset cache: enum value index past the end of the dictionary"); - if (idx == CacheDictionary::ENUM_UNNAMED) { - // An int the writer could not name — a nil, or an option whose - // definition carried no enum_keys_map. It travels verbatim. - int32_t raw = 0; + // An int the writer could not name — a nil, or an option whose + // definition carried no enum_keys_map — follows its index verbatim. + int32_t raw = 0; + if (idx == CacheDictionary::ENUM_UNNAMED) ar(raw); - values.push_back(int(raw)); - continue; - } - if (! usable) - continue; // the index above was this element's whole payload - if (def->enum_keys_map == nullptr) { - usable = false; // this build no longer maps this option's names - continue; - } - const auto it = def->enum_keys_map->find(dict.enum_name_at(idx)); - if (it == def->enum_keys_map->end()) { + if (usable) { + if (idx == CacheDictionary::ENUM_UNNAMED) { + values.push_back(int(raw)); + continue; + } + const auto it = def->enum_keys_map == nullptr ? def->enum_keys_map->end() : def->enum_keys_map->find(dict.enum_name_at(idx)); + if (def->enum_keys_map != nullptr && it != def->enum_keys_map->end()) { + values.push_back(it->second); + continue; + } usable = false; // a value this build dropped: the option goes with it - continue; } - values.push_back(it->second); + if (text != nullptr) { + if (! text->empty()) + *text += ','; + if (idx != CacheDictionary::ENUM_UNNAMED) + *text += dict.enum_name_at(idx); + else + *text += raw == ConfigOptionIntsNullable::nil_value() ? std::string("nil") : std::to_string(raw); + } } if (! usable) return; @@ -209,6 +218,41 @@ void save_config(cereal::BinaryOutputArchive& ar, const DynamicPrintConfig& conf } } +// The nullable form of a vector type reads the same bytes as the plain form +// and serializes a nil entry as "nil", which a nullable option parses back. +static bool has_nullable_form(ConfigOptionType type) +{ + return type == coFloats || type == coInts || type == coPercents || type == coBools || type == coFloatsOrPercents; +} + +// Place the value of a key this build types differently from the writer, the +// way a JSON profile's text is placed: handle_legacy maps the old spelling (a +// bool's 1 onto an enum's enabled) and a bool or enum that still does not +// parse is substituted, silently as for a system preset. The parse goes +// through a scratch config: set_deserialize_raw creates an option before +// parsing into it, so a failed parse must leave nothing behind, and the +// placing of one key must not take the whole cache down. +static void set_from_text(DynamicPrintConfig& config, const CacheDictionary& dict, uint16_t idx, + const std::string& text, ConfigSubstitutionContext& substitutions) +{ + const std::string& key = dict.key_at(idx); + DynamicPrintConfig parsed; + bool placed = false; + try { + placed = parsed.set_deserialize_nothrow(key, text, substitutions); + } catch (const std::exception&) { + placed = false; + } + if (placed) { + config.apply(parsed); + return; + } + if (dict.first_report(idx)) + // The key and the types only: the value may be a G-code template. + BOOST_LOG_TRIVIAL(warning) << "preset cache: dropped " << key << ", written as type " << int(dict.type_at(idx)) + << ", which this build cannot read as type " << int(dict.def_at(idx)->type); +} + // `config` null means: read everything, keep nothing. static void read_config(cereal::BinaryInputArchive& ar, DynamicPrintConfig* config, const CacheDictionary& dict) { @@ -216,26 +260,42 @@ static void read_config(cereal::BinaryInputArchive& ar, DynamicPrintConfig* conf ar(cnt); if (config != nullptr) config->clear(); - // Reused across the loop: constructing a ConfigOptionDef per dropped option - // would allocate its strings and vectors for nothing. + // Reused across the loop: constructing a ConfigOptionDef per option read by + // the writer's type would allocate its strings and vectors for nothing. ConfigOptionDef scratch; + ConfigSubstitutionContext substitutions(ForwardCompatibilitySubstitutionRule::EnableSilent); for (uint32_t i = 0; i < cnt; ++ i) { uint16_t idx = 0; ar(idx); if (! dict.valid_key_index(idx)) throw std::runtime_error("preset cache: option index past the end of the dictionary"); - const ConfigOptionType type = dict.type_at(idx); - const ConfigOptionDef* def = dict.def_at(idx); + const ConfigOptionType type = dict.type_at(idx); + const ConfigOptionDef* def = dict.def_at(idx); + const bool as_written = def != nullptr && def->type == type; + // Built from the bytes where this build defines the key as written. + // Otherwise read by the type the writer recorded: dropped where this + // build has no such key, the same outcome a JSON profile gets, and + // placed from its text, as a JSON profile's value is, where it has the + // key under another type. + const bool retyped = def != nullptr && ! as_written && config != nullptr; + std::string text; + std::string* text_out = retyped ? &text : nullptr; if (type == coEnum || type == coEnums) { - load_enum_option(ar, type, def, config, dict); - } else if (def != nullptr && config != nullptr) { + load_enum_option(ar, type, as_written ? def : nullptr, config, dict, text_out); + if (! retyped) + continue; + } else if (as_written && config != nullptr) { config->set_key_value(def->opt_key, def->load_option_from_archive(ar)); + continue; } else { - // Read by the type the writer recorded, then drop: the same outcome - // a JSON profile gets for an option this build no longer has. - scratch.type = type; - std::unique_ptr discard(scratch.load_option_from_archive(ar)); + scratch.type = type; + scratch.nullable = has_nullable_form(type); + std::unique_ptr value(scratch.load_option_from_archive(ar)); + if (! retyped) + continue; + text = value->serialize(); } + set_from_text(*config, dict, idx, text, substitutions); } } diff --git a/src/libslic3r/PresetCacheFormat.hpp b/src/libslic3r/PresetCacheFormat.hpp index c6e5fcb65a..ee7b22fe3e 100644 --- a/src/libslic3r/PresetCacheFormat.hpp +++ b/src/libslic3r/PresetCacheFormat.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -61,17 +62,22 @@ public: // ---- reading ---- - // The definition an index resolves to in THIS build, or nullptr where the - // key is unknown here or is now defined with a different type. A nullptr - // entry's value is still read — using type_at(idx), the type the writer - // recorded — and then dropped, which is what a JSON profile gets for an - // option this build no longer has. + // The definition THIS build has for an index's key, or nullptr where the key + // is unknown here. type_at(idx) is the type the writer recorded; the value + // is read by that type whatever this build's is. With no definition it is + // then dropped, which is what a JSON profile gets for an option this build + // no longer has; with a definition of another type it is placed as a JSON + // profile's text would be (see read_config), so the key is never left at + // the collection default while a JSON profile would have mapped it. const ConfigOptionDef* def_at(uint16_t idx) const { return m_defs[idx]; } + const std::string& key_at(uint16_t idx) const { return m_keys[idx]; } ConfigOptionType type_at(uint16_t idx) const { return ConfigOptionType(m_types[idx]); } const std::string& enum_name_at(uint16_t idx) const { return m_enum_values[idx]; } // m_defs, not m_keys: only load() sizes it, so this is false for every index // on a dictionary that was collected rather than read. bool valid_key_index(uint16_t idx) const { return size_t(idx) < m_defs.size(); } + // True the first time it is asked for an index, false after. + bool first_report(uint16_t idx) const { return ! std::exchange(m_reported[idx], char(1)); } bool valid_enum_index(uint16_t idx) const { return size_t(idx) < m_enum_values.size(); } // The layout these two agree on is covered by CACHE_VERSION (PresetCacheFormat.cpp); @@ -99,6 +105,10 @@ private: std::unordered_map m_enum_index; // Reading, resolved once by load(). std::vector m_defs; + // Keys whose value read_config already reported dropping from this file, + // so a key set by every preset is logged once, not once per preset. The + // entries of one file are read in sequence, never concurrently. + mutable std::vector m_reported; }; // One config, keyed through `dict`. Options print_config_def does not know are diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index 953cb5f8f5..4852aa51ba 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -2362,19 +2362,13 @@ StringObjectException Print::validate(std::vector *warnin // A mixed (virtual) filament always resolves to multiple physical components, which // spiral vase cannot print. const auto &is_mixed = m_config.filament_is_mixed.values; - for (const PrintObject *object : m_objects) - for (unsigned int ext : object->object_extruders()) - if (ext < is_mixed.size() && is_mixed[ext]) - return {L("Spiral (vase) mode does not work when an object contains more than one material."), nullptr, "spiral_mode"}; - assert(m_objects.size() == 1); - const auto all_regions = m_objects.front()->all_regions(); - if (all_regions.size() > 1) { - // Orca: make sure regions are not compatible - if (std::any_of(all_regions.begin() + 1, all_regions.end(), [this, ra = all_regions.front()](const auto rb) { - return !Layer::is_perimeter_compatible(*this, ra, rb); - })) { + for (const PrintObject *object : m_objects) { + const auto used_filament_ids = object->object_extruders(); + if (used_filament_ids.size() > 1 || + std::any_of(used_filament_ids.begin(), used_filament_ids.end(), [&is_mixed](unsigned int filament_id) { + return filament_id < is_mixed.size() && is_mixed[filament_id]; + })) return {L("Spiral (vase) mode does not work when an object contains more than one material."), nullptr, "spiral_mode"}; - } } } @@ -2440,7 +2434,7 @@ StringObjectException Print::validate(std::vector *warnin print_object.model_object(), "" }; - } else if (effective_max_z > this->config().printable_height + EPSILON) { + } else if (compensated_max_z > this->config().printable_height + EPSILON) { return StringObjectException{ last_layer_below_max ? Slic3r::format(_u8L("While the object %1% itself fits the build volume, its last layer exceeds the maximum build volume height."), print_object.model_object()->name) + diff --git a/src/libslic3r/PrintApply.cpp b/src/libslic3r/PrintApply.cpp index 389db20896..0160cf75b8 100644 --- a/src/libslic3r/PrintApply.cpp +++ b/src/libslic3r/PrintApply.cpp @@ -427,10 +427,12 @@ public: }; LayerRanges() = default; - LayerRanges(const t_layer_config_ranges &in) { this->assign(in); } + LayerRanges(const t_layer_config_ranges &in, double shrinkage_compensation_z) { this->assign(in, shrinkage_compensation_z); } // Convert input config ranges into continuous non-overlapping sorted vector of intervals and their configs. - void assign(const t_layer_config_ranges &in) { + // The input ranges are uncompensated print heights, the intervals are scaled by the Z shrinkage compensation + // like the PrintObject trafo the regions are generated in. + void assign(const t_layer_config_ranges &in, double shrinkage_compensation_z) { m_ranges.clear(); m_ranges.reserve(in.size()); // Input ranges are sorted lexicographically. First range trims the other ranges. @@ -454,6 +456,11 @@ public: m_ranges.back().layer_height_range.second = DBL_MAX; else m_ranges.push_back({ t_layer_height_range(m_ranges.back().layer_height_range.second, DBL_MAX) }); + for (LayerRange &range : m_ranges) { + range.layer_height_range.first *= shrinkage_compensation_z; + if (range.layer_height_range.second != DBL_MAX) + range.layer_height_range.second *= shrinkage_compensation_z; + } } const DynamicPrintConfig* config(const t_layer_height_range &range) const { @@ -1063,6 +1070,12 @@ static PrintObjectRegions* generate_print_object_regions( all_regions.clear(); bool reuse_old = print_object_regions_old && !print_object_regions_old->layer_ranges.empty(); + if (reuse_old && ! std::equal(model_layer_ranges.begin(), model_layer_ranges.end(), layer_ranges_regions.begin(), layer_ranges_regions.end(), + [](const LayerRanges::LayerRange &range, const PrintObjectRegions::LayerRangeRegions &r) { return range.layer_height_range == r.layer_height_range; })) { + // The ranges carry the Z shrinkage compensation, which may have changed together with the volumes. + out->clear(); + reuse_old = false; + } if (reuse_old) { // Reuse old bounding boxes of some ModelVolumes and their ranges. @@ -2162,10 +2175,12 @@ Print::ApplyStatus Print::apply(const Model &model, DynamicPrintConfig new_full_ if (print_object_regions == nullptr || model_object_status.print_object_regions_status != ModelObjectStatus::PrintObjectRegionsStatus::Valid) { // Layer ranges with their associated configurations. Remove overlaps between the ranges // and create the regions from scratch. + // A belt printer slices in the rotated frame, which the ranges do not follow (see slices_to_regions()), + // so they stay as they are there. print_object_regions = generate_print_object_regions( print_object_regions, print_object.model_object()->volumes, - LayerRanges(print_object.model_object()->layer_config_ranges), + LayerRanges(print_object.model_object()->layer_config_ranges, m_config.belt_printer.value ? 1. : this->shrinkage_compensation().z()), m_default_region_config, model_object_status.print_instances.front().trafo, num_extruders , diff --git a/src/libslic3r/PrintObject.cpp b/src/libslic3r/PrintObject.cpp index 634d2ed291..2d6d200ef1 100644 --- a/src/libslic3r/PrintObject.cpp +++ b/src/libslic3r/PrintObject.cpp @@ -4467,6 +4467,7 @@ void PrintObject::update_slicing_parameters() coordf_t object_height = this->model_object()->max_z(); BeltTransformPipeline::BeltFloorParams belt_floor; const auto &pcfg = this->print()->config(); + const Vec3d shrinkage_compensation = this->print()->shrinkage_compensation(); if (pcfg.belt_printer.value) { // The box of the mesh in the frame it is sliced in: XY centred and Z as // placed on the bed (trafo_centered()). raw_bounding_box() has the @@ -4479,12 +4480,14 @@ void PrintObject::update_slicing_parameters() for (const ModelVolume *v : this->model_object()->volumes) if (v->is_model_part()) bb.merge(v->mesh().transformed_bounding_box(trafo * v->get_matrix())); - auto hr = BeltTransformPipeline::compute_belt_height_and_floor(pcfg, bb, object_height); - object_height = hr.object_height; + // trafo() already carries the shrinkage compensation, so the belt height is + // compensated, while create_from_config() expects object_height without it. + auto hr = BeltTransformPipeline::compute_belt_height_and_floor(pcfg, bb, object_height * shrinkage_compensation.z()); + object_height = hr.object_height / shrinkage_compensation.z(); belt_floor = hr.floor_params; } m_slicing_params = SlicingParameters::create_from_config(pcfg, m_config, object_height, - this->object_extruders(), this->print()->shrinkage_compensation()); + this->object_extruders(), shrinkage_compensation); // Populate belt floor parameters into slicing params for support clipping. m_slicing_params.belt_floor_shear_factor = belt_floor.shear_factor; m_slicing_params.belt_floor_from_axis = belt_floor.from_axis; diff --git a/src/libslic3r/PrintObjectSlice.cpp b/src/libslic3r/PrintObjectSlice.cpp index d52184ee8c..701231a7e0 100644 --- a/src/libslic3r/PrintObjectSlice.cpp +++ b/src/libslic3r/PrintObjectSlice.cpp @@ -228,26 +228,31 @@ static std::vector slice_volumes_inner( MeshSlicingParamsEx params { params_base }; if (! model_volume->is_negative_volume()) params.extra_offset = extra_offset; - if (layer_ranges.size() == 1) { - if (const PrintObjectRegions::LayerRangeRegions &layer_range = layer_ranges.front(); layer_range.has_volume(model_volume->id())) { - if (model_volume->is_model_part() && print_config.spiral_mode) { - auto it = std::find_if(layer_range.volume_regions.begin(), layer_range.volume_regions.end(), - [model_volume](const auto &slice){ return model_volume == slice.model_volume; }); + if (model_volume->is_model_part() && print_config.spiral_mode) { + if (const auto layer_range_it = std::find_if(layer_ranges.begin(), layer_ranges.end(), + [model_volume](const auto &layer_range) { return layer_range.has_volume(model_volume->id()); }); + layer_range_it != layer_ranges.end()) { + if (const auto volume_region_it = std::find_if(layer_range_it->volume_regions.begin(), layer_range_it->volume_regions.end(), + [model_volume](const auto &slice) { return model_volume == slice.model_volume; }); + volume_region_it != layer_range_it->volume_regions.end()) { params.mode = MeshSlicingParams::SlicingMode::PositiveLargestContour; // Slice the bottom layers with SlicingMode::Regular. // This needs to be in sync with LayerRegion::make_perimeters() spiral_mode! - const PrintRegionConfig ®ion_config = it->region->config(); + const PrintRegionConfig ®ion_config = volume_region_it->region->config(); params.slicing_mode_normal_below_layer = size_t(region_config.bottom_shell_layers.value); for (; params.slicing_mode_normal_below_layer < zs.size() && zs[params.slicing_mode_normal_below_layer] < region_config.bottom_shell_thickness - EPSILON; ++ params.slicing_mode_normal_below_layer); } + } + } + if (layer_ranges.size() == 1) { + if (const PrintObjectRegions::LayerRangeRegions &layer_range = layer_ranges.front(); layer_range.has_volume(model_volume->id())) { out.push_back({ model_volume->id(), slice_volume(*model_volume, zs, params, throw_on_cancel_callback) }); } } else { - assert(! print_config.spiral_mode); slicing_ranges.clear(); for (const PrintObjectRegions::LayerRangeRegions &layer_range : layer_ranges) if (layer_range.has_volume(model_volume->id())) diff --git a/src/libslic3r/Slicing.cpp b/src/libslic3r/Slicing.cpp index 5fbc7238ac..209050e4ed 100644 --- a/src/libslic3r/Slicing.cpp +++ b/src/libslic3r/Slicing.cpp @@ -255,7 +255,7 @@ std::vector layer_height_profile_from_ranges( // The height ranges are sorted lexicographically by low / high layer boundaries. for (t_layer_config_ranges::const_iterator it_range = layer_config_ranges.begin(); it_range != layer_config_ranges.end(); ++ it_range) { coordf_t lo = it_range->first.first; - coordf_t hi = std::min(it_range->first.second, slicing_params.object_print_z_height()); + coordf_t hi = std::min(it_range->first.second, slicing_params.object_print_z_uncompensated_height()); coordf_t height = it_range->second.option("layer_height")->getFloat(); if (! ranges_non_overlapping.empty()) // Trim current low with the last high. diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 2d16a24a92..272fa8072d 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -629,6 +629,8 @@ set(SLIC3R_GUI_SOURCES GUI/StatusPanel.hpp GUI/StepMeshDialog.cpp GUI/StepMeshDialog.hpp + GUI/GeometryImportDialog.cpp + GUI/GeometryImportDialog.hpp GUI/SurfaceDrag.cpp GUI/SurfaceDrag.hpp GUI/Tabbook.cpp diff --git a/src/slic3r/GUI/AMSSetting.hpp b/src/slic3r/GUI/AMSSetting.hpp index 1d6b559981..84b8bc855e 100644 --- a/src/slic3r/GUI/AMSSetting.hpp +++ b/src/slic3r/GUI/AMSSetting.hpp @@ -21,7 +21,7 @@ #include #include #include -#include +#include #define AMS_SETTING_DEF_COLOUR wxColour(255, 255, 255) #define AMS_SETTING_GREY800 wxColour(50, 58, 61) @@ -130,7 +130,7 @@ private: std::weak_ptr m_ams_firmware_switch; int m_ams_firmware_current_idx{ -1 }; - std::unordered_map m_ams_firmwares; + std::map m_ams_firmwares; // widgets AMSSetting* m_setting_dlg; diff --git a/src/slic3r/GUI/CloneDialog.cpp b/src/slic3r/GUI/CloneDialog.cpp index a34dbfa4a4..a00a1ea416 100644 --- a/src/slic3r/GUI/CloneDialog.cpp +++ b/src/slic3r/GUI/CloneDialog.cpp @@ -76,7 +76,7 @@ CloneDialog::CloneDialog(wxWindow *parent) // Keep pointer to OK button so we can trigger it manually on Enter. Button *ok_btn = dlg_btns->GetOK(); - dlg_btns->GetFIRST()->SetToolTip(_L("Fill bed with copies")); + dlg_btns->GetFIRST()->SetToolTip(_L("Fill bed with instances")); dlg_btns->GetFIRST()->Bind(wxEVT_BUTTON, [this](wxCommandEvent &e) { m_plater->fill_bed_with_instances(); EndModal(wxID_OK); diff --git a/src/slic3r/GUI/DeviceCore/DevFilaAmsSetting.h b/src/slic3r/GUI/DeviceCore/DevFilaAmsSetting.h index f8d194c999..f806f4c062 100644 --- a/src/slic3r/GUI/DeviceCore/DevFilaAmsSetting.h +++ b/src/slic3r/GUI/DeviceCore/DevFilaAmsSetting.h @@ -2,7 +2,7 @@ #include #include #include -#include // Orca: for m_firmwares / GetSuppotedFirmwares() — the unordered_map AMSSetting.cpp mirrors and iterates +#include #include #include "DevCtrl.h" @@ -78,7 +78,8 @@ public: DevAmsSystemIdx GetCurrentFirmwareIdxSel() const { return m_current_firmware_sel.m_firmare_idx; }; DevAmsSystemIdx GetCurrentFirmwareIdxRun() const { return m_current_firmware_run.m_firmare_idx; }; - std::unordered_map GetSuppotedFirmwares() const { return m_firmwares;}; // Orca: unordered (mirrored by AMSSetting.cpp) + // Ordered by firmware id: the AMS type combo lists these in order and uses the id as its row index. + std::map GetSuppotedFirmwares() const { return m_firmwares;}; bool IsSwitching() const { return m_status == "SWITCHING";}; bool IsIdle() const { return m_status == "IDLE";}; @@ -97,7 +98,7 @@ private: DevAmsSystemFirmware m_current_firmware_run; DevAmsSystemFirmware m_current_firmware_sel; - std::unordered_map m_firmwares; // Orca: unordered (mirrored by AMSSetting.cpp) + std::map m_firmwares; DevCtrlInfo m_ctrl_switching; }; diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index 6674737bfd..2bd15f18e4 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -4365,7 +4365,9 @@ void GUI_App::set_live_printer_agent(std::shared_ptr agent) } m_agent->set_printer_agent(agent); - sidebar().update_all_preset_comboboxes(); + // Before mainframe is shown this runs from load_current_presets(), right after + // printer refilled the filament combos; no printer is connected yet, so they would not change + sidebar().update_all_preset_comboboxes(mainframe == nullptr || mainframe->IsShown()); } std::string GUI_App::resolve_printer_agent_id(const std::string& stored_id) const diff --git a/src/slic3r/GUI/GUI_Factories.cpp b/src/slic3r/GUI/GUI_Factories.cpp index a6be6fd61e..2bfbf1333b 100644 --- a/src/slic3r/GUI/GUI_Factories.cpp +++ b/src/slic3r/GUI/GUI_Factories.cpp @@ -1190,7 +1190,8 @@ void MenuFactory::append_menu_item_change_extruder(wxMenu* menu) void MenuFactory::append_menu_item_scale_selection_to_fit_print_volume(wxMenu* menu) { append_menu_item(menu, wxID_ANY, _L("Scale to build volume"), _L("Scale an object to fit the build volume"), - [](wxCommandEvent&) { plater()->scale_selection_to_fit_print_volume(); }, "", menu); + [](wxCommandEvent&) { plater()->scale_selection_to_fit_print_volume(); }, "", menu, + []() { return plater()->can_scale_to_print_volume(); }, m_parent); } void MenuFactory::append_menu_items_flush_options(wxMenu* menu, size_t pos) diff --git a/src/slic3r/GUI/GUI_ObjectList.cpp b/src/slic3r/GUI/GUI_ObjectList.cpp index 5e7d7ae24d..12cabf375e 100644 --- a/src/slic3r/GUI/GUI_ObjectList.cpp +++ b/src/slic3r/GUI/GUI_ObjectList.cpp @@ -348,11 +348,13 @@ ObjectList::ObjectList(wxWindow* parent) : //Bind(wxCUSTOMEVT_LAST_VOLUME_IS_DELETED, [this](wxCommandEvent& e) { last_volume_is_deleted(e.GetInt()); }); Bind(wxEVT_SIZE, ([this](wxSizeEvent &e) { - if (m_last_size == this->GetSize()) { + // ORCA: compare client size instead window size + // Name column stays wide that shows horizontal scrollbar when vertical scrollbar (dis)appears + if (m_last_size == this->GetClientSize()) { e.Skip(); return; } else { - m_last_size = this->GetSize(); + m_last_size = this->GetClientSize(); } update_name_column_width(); @@ -362,7 +364,7 @@ ObjectList::ObjectList(wxWindow* parent) : e.Skip(); })); - m_last_size = this->GetSize(); + m_last_size = this->GetClientSize(); } ObjectList::~ObjectList() @@ -698,12 +700,14 @@ void ObjectList::set_tooltip_for_item(const wxPoint& pt) tooltip = _(L("Click the icon to reset all settings of the object")); #endif //__WXMSW__ } - else if (col->GetModelColumn() == (unsigned int)colPrint) + else if (col->GetModelColumn() == (unsigned int)colPrint) { + if (node->IsPrintable() != piUndef) #ifdef __WXOSX__ - tooltip = _(L("Right click the icon to drop the object printable property")); + tooltip = _(L("Right click the icon to drop the object printable property")); #else - tooltip = _(L("Click the icon to toggle printable properties of the object")); + tooltip = _(L("Click the icon to toggle printable properties of the object")); #endif //__WXMSW__ + } // BBS else if (col->GetModelColumn() == (unsigned int)colSupportPaint) { if (node->HasSupportPainting()) @@ -2117,6 +2121,34 @@ void ObjectList::OnDrop(wxDataViewEvent &event) return; } + // Move in the displayed order too, keeping presentation independent of slicing precedence. + const bool imported_order = std::any_of(volumes.begin(), volumes.end(), [](const ModelVolume* volume) { + return volume->import_display_order >= 0; + }); + ModelVolume* dragged_volume = volumes[visible_volume_indices[size_t(from_volume_id)]]; + if (imported_order) { + // The rebuild below deletes the rows, so a name editor still open on one of them must not write back. + if (wxDataViewRenderer* renderer = GetColumn(colName)->GetRenderer(); renderer->GetEditorCtrl()) + renderer->CancelEditing(); + wxDataViewItemArray children; + m_objects_model->GetChildren(m_objects_model->GetParent(item), children); + std::vector displayed; + for (const auto& child : children) { + const int index = m_objects_model->GetVolumeIdByItem(child); + if (index >= 0 && size_t(index) < visible_volume_indices.size()) + displayed.push_back(volumes[visible_volume_indices[size_t(index)]]); + } + ModelVolume* target_volume = volumes[visible_volume_indices[size_t(to_volume_id)]]; + const auto from = std::find(displayed.begin(), displayed.end(), dragged_volume); + const auto to = std::find(displayed.begin(), displayed.end(), target_volume); + if (from != displayed.end() && to != displayed.end()) { + const auto target_position = to - displayed.begin(); + displayed.erase(from); + displayed.insert(displayed.begin() + target_position, dragged_volume); + for (size_t i = 0; i < displayed.size(); ++i) + displayed[i]->import_display_order = static_cast(i); + } + } // Move through visible slots only, keeping hidden cut connectors at their original indices. // The local mapping stays valid because no hidden volume changes slots during the move. for (int id = from_volume_id; id != to_volume_id; id += delta) { @@ -2131,7 +2163,15 @@ void ObjectList::OnDrop(wxDataViewEvent &event) for (size_t idx = 0; idx < visible_volume_indices.size(); ++idx) ui_to_model[int(idx)] = int(visible_volume_indices[idx]); - select_item(m_objects_model->ReorganizeChildren(from_volume_id, to_volume_id, m_objects_model->GetParent(item))); + if (imported_order) { + // Rebuild re-reads presentation ranks; native ReorganizeChildren assumes model order. + const auto selected = add_volumes_to_object_in_list(size_t(obj_idx), [dragged_volume](const ModelVolume* volume) { + return volume == dragged_volume; + }); + if (!selected.empty()) + select_item(selected.front()); + } else + select_item(m_objects_model->ReorganizeChildren(from_volume_id, to_volume_id, m_objects_model->GetParent(item))); changed_object(m_dragged_data.obj_idx()); } @@ -3106,6 +3146,16 @@ void ObjectList::split() if (!item || obj_idx < 0) return; + ModelObject* imported = (*m_objects)[obj_idx]; + if (imported->hides_imported_parts()) { + // Reveal the original CAD bodies, including their names and exact transforms. + take_snapshot(_u8L("Split to parts")); + imported->imported_parts_hidden = false; + add_volumes_to_object_in_list(size_t(obj_idx)); + changed_object(obj_idx); + return; + } + ModelVolume* volume; if (!get_volume_by_item(item, volume)) return; DynamicPrintConfig& config = printer_config(); @@ -3647,6 +3697,13 @@ bool ObjectList::is_splittable(bool to_objects) const wxDataViewItem item = GetSelection(); if (!item) return false; + const int selected_object = get_selected_obj_idx(); + if (!to_objects && selected_object >= 0) { + const ModelObject* object = (*m_objects)[size_t(selected_object)]; + if (object->hides_imported_parts()) + return true; + } + if (to_objects) { ItemType type = m_objects_model->GetItemType(item); @@ -4151,6 +4208,8 @@ void ObjectList::update_variable_layer_obj_num(ObjectDataViewModelNode* obj_node } } +static bool can_add_volumes_to_object(const ModelObject *object); + void ObjectList::update_info_items(size_t obj_idx, wxDataViewItemArray *selections /* = nullptr*/, bool added_object /* = false*/, bool color_mode_changed /* = false*/) { // BBS @@ -4161,6 +4220,35 @@ void ObjectList::update_info_items(size_t obj_idx, wxDataViewItemArray *selectio wxDataViewItem item_obj = m_objects_model->GetItemById(obj_idx); assert(item_obj.IsOk()); + // Painting decides whether a single-object import shows its parts; the painting gizmos call this after each change. + if (model_object->imported_parts_hidden) { + wxDataViewItemArray children; + m_objects_model->GetChildren(item_obj, children); + bool shows_parts = false; + for (const wxDataViewItem& child : children) + shows_parts = shows_parts || m_objects_model->GetItemType(child) == itVolume; + if (shows_parts != can_add_volumes_to_object(model_object)) { + // A tracked selection must not keep rows of the parts that are about to go. + if (selections != nullptr && shows_parts) { + auto in_removed_parts = [this, &item_obj](const wxDataViewItem& item) { + const wxDataViewItem parent = m_objects_model->GetParent(item); + if (m_objects_model->GetItemType(item) == itVolume) + return parent == item_obj; + return parent.IsOk() && m_objects_model->GetItemType(parent) == itVolume && m_objects_model->GetParent(parent) == item_obj; + }; + bool removed = false; + for (int index = int(selections->GetCount()) - 1; index >= 0; --index) + if (in_removed_parts((*selections)[index])) { + selections->RemoveAt(index); + removed = true; + } + if (removed && selections->Index(item_obj) == wxNOT_FOUND) + selections->Add(item_obj); + } + add_volumes_to_object_in_list(obj_idx); + } + } + // Cut connectors { wxDataViewItem item = m_objects_model->GetInfoItemByType(item_obj, InfoItemType::CutConnectors); @@ -4393,6 +4481,9 @@ void ObjectList::add_object_to_list(size_t obj_idx, bool call_selection_changed, static bool can_add_volumes_to_object(const ModelObject *object) { + // Single-object imports retain their bodies internally until the user chooses Split to parts. + if (object->hides_imported_parts()) + return false; bool can = object->volumes.size() > 1; if (can && object->is_cut()) { @@ -4419,7 +4510,7 @@ wxDataViewItemArray ObjectList::add_volumes_to_object_in_list(size_t obj_idx, st wxDataViewItemArray items; - const ModelObject *object = (*m_objects)[obj_idx]; + ModelObject *object = (*m_objects)[obj_idx]; // add volumes to the object if (can_add_volumes_to_object(object)) { if (object->volumes.size() > 1) { @@ -7126,6 +7217,19 @@ void sort_objects(std::vector& objects, ObjectOrder order, bool de objects[i] = entries[i].object; } +void set_import_volume_order(ModelObject& object, bool sort_names) +{ + // Capture after the final clone and before the model's required type grouping. + auto parts = object.volumes; + if (sort_names) + std::stable_sort(parts.begin(), parts.end(), [](const ModelVolume* a, const ModelVolume* b) { + return wxCmpNatural(from_u8(a->name).Lower(), from_u8(b->name).Lower()) < 0; + }); + // The rank travels with the volume through cloning and Undo/Redo, without changing slicing order. + for (size_t i = 0; i < parts.size(); ++i) + parts[i]->import_display_order = static_cast(i); +} + void ObjectList::order_objects(ObjectOrder order, bool all_plates) { Plater* plater = wxGetApp().plater(); diff --git a/src/slic3r/GUI/GUI_ObjectList.hpp b/src/slic3r/GUI/GUI_ObjectList.hpp index c886962ad7..f32701c52d 100644 --- a/src/slic3r/GUI/GUI_ObjectList.hpp +++ b/src/slic3r/GUI/GUI_ObjectList.hpp @@ -64,6 +64,9 @@ enum class ObjectOrder { Name, Filament, Height, Size }; // Stable sort by natural name order, filament, top Z, or bounding box volume of the first instance. void sort_objects(std::vector& objects, ObjectOrder order, bool descending = false); +// Set import-only presentation ranks without changing part order used by slicing. +void set_import_volume_order(ModelObject& object, bool sort_names); + // The dimensions the Primitive size dialog asks for a shape ("Cube", "Cylinder", "Sphere", "Cone", "Disc", "Torus"), in its // order, as untranslated labels; none for another name. std::vector primitive_size_names(const std::string& type_name); diff --git a/src/slic3r/GUI/GeometryImportDialog.cpp b/src/slic3r/GUI/GeometryImportDialog.cpp new file mode 100644 index 0000000000..0f276e7028 --- /dev/null +++ b/src/slic3r/GUI/GeometryImportDialog.cpp @@ -0,0 +1,461 @@ +#include "GeometryImportDialog.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "GUI.hpp" +#include "GUI_App.hpp" +#include "GUI_Utils.hpp" +#include "I18N.hpp" +#include "MsgDialog.hpp" +#include "slic3r/GUI/format.hpp" +#include "Widgets/Button.hpp" +#include "Widgets/CheckBox.hpp" +#include "Widgets/DialogButtons.hpp" +#include "Widgets/Label.hpp" +#include "Widgets/RadioGroup.hpp" +#include "Widgets/RoundedRectangle.hpp" +#include "Widgets/StateColor.hpp" +#include "Widgets/TextInput.hpp" +#include "libslic3r/AppConfig.hpp" +#include "libslic3r/Format/ImportNames.hpp" +#include "libslic3r/LocalesUtils.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/miniz_extension.hpp" +#include "libslic3r/Utils.hpp" + +namespace Slic3r::GUI { +namespace { + +class ImportDialog final : public DPIDialog { +public: + using DPIDialog::DPIDialog; + +protected: + void on_dpi_changed(const wxRect&) override { + // Respect the controls' new minimum size when moved between DPI settings. + if (GetSizer() != nullptr) + GetSizer()->SetSizeHints(this); + Layout(); + } +}; + +std::string option_key(const std::string& format, const char* suffix) +{ + return "import_names_" + format + "_" + suffix; +} + +bool config_bool(const AppConfig& config, const std::string& key, bool fallback) +{ + // Existing user configurations predate these keys. + return config.has(key) ? config.get_bool(key) : fallback; +} + +// Same font and label color as the check boxes of the STEP import dialog. +void apply_label_style(wxWindow* control) +{ + control->SetFont(::Label::Body_14); + control->SetForegroundColour(StateColor::darkModeColorFor(wxColour("#363636"))); +} + +// White dialog with the explanation in a grey rounded box, as in the STEP import dialog. +void add_tip(DPIDialog& dialog, wxBoxSizer& sizer, const wxString& text, int wrap_width) +{ + dialog.SetBackgroundColour(*wxWHITE); + const wxColour tip_colour = StateColor::darkModeColorFor(wxColour("#F1F1F1")); + auto* frame = new RoundedRectangle(&dialog, tip_colour, wxDefaultPosition, wxSize(-1, -1), 6, 0); + auto* tip_sizer = new wxBoxSizer(wxHORIZONTAL); + auto* info = new wxStaticText(frame, wxID_ANY, text); + apply_label_style(info); + info->SetBackgroundColour(tip_colour); + info->Wrap(dialog.FromDIP(wrap_width)); + tip_sizer->Add(info, 0, wxEXPAND | wxALL, dialog.FromDIP(10)); + frame->SetSizer(tip_sizer); + frame->Layout(); + sizer.Add(frame, 0, wxEXPAND | wxLEFT | wxRIGHT | wxTOP, dialog.FromDIP(12)); +} + +ImportCheckBox add_checkbox(DPIDialog& dialog, wxBoxSizer& sizer, const wxString& label, bool value) +{ + return add_import_checkbox(&dialog, sizer, label, value, wxLEFT | wxRIGHT | wxTOP, dialog.FromDIP(12)); +} + +// The radio group takes the dialog background at creation, so add it after add_tip. +RadioGroup* add_radio_group(DPIDialog& dialog, const std::vector& labels, int selection, long direction) +{ + auto* group = new RadioGroup(&dialog, labels, direction); + group->SetSelection(selection); + return group; +} + +using NameGroup = std::vector; + +// Each group has its own collision scope: object siblings or parts of one object. +std::vector name_groups(const std::vector& models) +{ + std::vector groups; + for (Model* model : models) { + NameGroup objects; + for (ModelObject* object : model->objects) { + objects.push_back(&object->name); + NameGroup parts; + for (ModelVolume* volume : object->volumes) + parts.push_back(&volume->name); + groups.push_back(std::move(parts)); + } + groups.push_back(std::move(objects)); + } + return groups; +} + +std::vector> cleaned_groups(const std::vector& groups, const std::string& replacement) +{ + std::vector> results; + results.reserve(groups.size()); + for (const NameGroup& group : groups) { + std::vector names; + names.reserve(group.size()); + for (const std::string* name : group) + names.push_back(*name); + results.push_back(sanitize_import_names(names, replacement)); + } + return results; +} + +} // namespace + +std::string geometry_import_format(const std::string& path) +{ + if (boost::algorithm::iends_with(path, ".step") || boost::algorithm::iends_with(path, ".stp")) + return "step"; + if (boost::algorithm::iends_with(path, ".amf")) + return "amf"; + if (boost::algorithm::iends_with(path, ".3mf")) + return "3mf"; + return {}; +} + +GeometryImportOptions geometry_import_options(const AppConfig& config, const std::string& format) +{ + GeometryImportOptions options; + options.keep_names = config_bool(config, option_key(format, "keep"), true); + options.sort_names = config_bool(config, option_key(format, "sort"), false); + // A 3MF keeps the structure written in it, so it has no presentation choice. + options.load_as_assembly = format == "3mf" || config_bool(config, option_key(format, "assembly"), true); + // Files from other slicers keep a whole plate in one AMF group, so assembling it is opt-in. + options.separate_objects = format == "amf" && config_bool(config, option_key(format, "separate"), true); + // The same key drives Preferences, Replace and Reload, so all STEP paths split alike. + options.split_compound = format == "step" && config_bool(config, "is_split_compound", true); + options.show_dialog = config_bool(config, format == "step" ? "enable_step_mesh_setting" : option_key(format, "show_dialog"), true); + // Read the same quality defaults as the existing STEP import dialog. + options.linear_deflection = string_to_double_decimal_point(config.get("linear_deflection")); + options.angle_deflection = string_to_double_decimal_point(config.get("angle_deflection")); + if (!std::isfinite(options.linear_deflection) || options.linear_deflection < 0.001 || options.linear_deflection > 0.1) + options.linear_deflection = 0.003; + if (!std::isfinite(options.angle_deflection) || options.angle_deflection < 0.01 || options.angle_deflection > 1.0) + options.angle_deflection = 0.5; + return options; +} + +bool is_geometry_only_3mf(const std::string& path) +{ + if (!boost::algorithm::iends_with(path, ".3mf")) + return false; + mz_zip_archive archive; + mz_zip_zero_struct(&archive); + if (!open_zip_reader(&archive, path)) + return false; // Let the normal reader report unreadable or malformed archives. + ScopeGuard close_archive([&archive]() { close_zip_reader(&archive); }); + + // Minimal published Orca projects also retain model_settings.config. + const char* project_markers[] = { + "Metadata/model_settings.config", "Metadata/project_settings.config", "Metadata/print_profile.config", + "Metadata/slice_info.config", "Metadata/Slic3r_PE.config", "Metadata/Slic3r_PE_model.config", + "Metadata/Prusa_Slicer_layer_config_ranges.xml", "Metadata/Slic3r_PE_layer_heights_profile.txt", + "Metadata/Slic3r_PE_sla_support_points.txt", "Metadata/Slic3r_PE_sla_drain_holes.txt" + }; + bool has_model = false; + for (mz_uint index = 0; index < mz_zip_reader_get_num_files(&archive); ++index) { + mz_zip_archive_file_stat stat; + if (!mz_zip_reader_file_stat(&archive, index, &stat)) + return false; + std::string name = stat.m_filename; + std::replace(name.begin(), name.end(), '\\', '/'); + while (boost::algorithm::starts_with(name, "./")) + name.erase(0, 2); + for (const char* marker : project_markers) + if (boost::algorithm::iequals(name, marker)) + return false; + has_model = has_model || (boost::algorithm::istarts_with(name, "3D/") && boost::algorithm::iends_with(name, ".model")); + } + return has_model; +} + +GeometryImportNamePolicy geometry_import_name_policy(const AppConfig& config) +{ + GeometryImportNamePolicy policy; + policy.show_dialog = config_bool(config, "import_names_cleanup_show_dialog", true); + policy.remove = config_bool(config, "import_names_cleanup_remove", false); + if (config.has("import_names_cleanup_replacement")) + policy.replacement = config.get("import_names_cleanup_replacement"); + return policy; +} + +bool ImportCheckBox::GetValue() const { return box->GetValue(); } + +void ImportCheckBox::SetValue(bool value) const { box->SetValue(value); } + +void ImportCheckBox::Enable(bool enable) const +{ + box->Enable(enable); + label->Enable(enable); + // Same disabled text color as RadioGroup. + label->SetForegroundColour(enable ? StateColor::darkModeColorFor(wxColour("#363636")) : wxColour("#6B6A6A")); + label->Refresh(); +} + +void ImportCheckBox::SetToolTip(const wxString& tip) const +{ + box->SetToolTip(tip); + label->SetToolTip(tip); +} + +ImportCheckBox add_import_checkbox(wxWindow* parent, wxSizer& sizer, const wxString& text, bool value, int flags, int border) +{ + ImportCheckBox checkbox{new ::CheckBox(parent), new wxStaticText(parent, wxID_ANY, text)}; + apply_label_style(checkbox.label); + checkbox.box->SetValue(value); + ::CheckBox* box = checkbox.box; + auto toggle = [box]() { + if (!box->IsEnabled()) + return; + box->SetValue(!box->GetValue()); + wxCommandEvent event(wxEVT_TOGGLEBUTTON, box->GetId()); + event.SetEventObject(box); + box->GetEventHandler()->ProcessEvent(event); + }; + // A double click arrives as one down and one double-click event, so each toggles once. + checkbox.label->Bind(wxEVT_LEFT_DOWN, [toggle](wxMouseEvent&) { toggle(); }); + checkbox.label->Bind(wxEVT_LEFT_DCLICK, [toggle](wxMouseEvent&) { toggle(); }); + auto* row = new wxBoxSizer(wxHORIZONTAL); + row->Add(checkbox.box, 0, wxALIGN_CENTER_VERTICAL); + row->Add(checkbox.label, 0, wxALIGN_CENTER_VERTICAL | wxLEFT, parent->FromDIP(5)); + sizer.Add(row, 0, flags, border); + return checkbox; +} + +// Sorting only makes sense for original names; while Keep is off it is disabled but keeps its remembered value. +void link_sort_to_keep(const ImportCheckBox& keep, const ImportCheckBox& sort) +{ + sort.Enable(keep.GetValue()); + keep.box->Bind(wxEVT_TOGGLEBUTTON, [keep, sort](wxCommandEvent& event) { + sort.Enable(keep.GetValue()); + event.Skip(); + }); +} + +bool show_geometry_import_options(wxWindow* parent, const std::string& format, GeometryImportOptions& options) +{ + if (options.chosen) + return true; + options.chosen = true; + if (!options.show_dialog) + return true; + + // One choice per format applies to all of its files in this import operation. + ImportDialog dialog(parent, wxID_ANY, format == "3mf" ? _L("3MF geometry import options") : _L("AMF geometry import options"), wxDefaultPosition, wxDefaultSize, + wxDEFAULT_DIALOG_STYLE); + auto* sizer = new wxBoxSizer(wxVERTICAL); + // A 3MF keeps its own structure, so only the naming choices remain for it. + add_tip(dialog, *sizer, format == "3mf" ? _L("Choose how to name and order the parts of this file.") : + _L("Choose how to load the bodies in this file."), 430); + + // Item 0 loads separate objects, item 1 an assembly, item 2 a single object. + RadioGroup* load_mode = nullptr; + if (format != "3mf") { + load_mode = add_radio_group(dialog, {_L("Load as separate objects"), _L("Load as an assembly"), _L("Load as a single object (can be split later)")}, + options.separate_objects ? 0 : options.load_as_assembly ? 1 : 2, wxVERTICAL); + load_mode->SetRadioTooltip(0, _L("Each object in the file is loaded on its own, as OrcaSlicer always loaded AMF files.")); + load_mode->SetRadioTooltip(1, _L("The bodies of each group in the file become parts of one object, in their relative positions.")); + load_mode->SetRadioTooltip(2, _L("The original bodies and names are kept inside the object. Use Split to parts to show them as separate parts.")); + sizer->Add(load_mode, 0, wxLEFT | wxRIGHT | wxTOP, dialog.FromDIP(12)); + } + const auto keep = add_checkbox(dialog, *sizer, _L("Keep original names"), options.keep_names); + keep.SetToolTip(_L("Use the body names stored in the file, when there are any. When disabled, the usual OrcaSlicer names are used; existing project names are kept.")); + const auto sort = add_checkbox(dialog, *sizer, _L("Sort parts by name"), options.sort_names); + sort.SetToolTip(_L("Sort the parts inside each imported assembly in the object list. This does not change the order used for slicing. Available when Keep original names is on.")); + link_sort_to_keep(keep, sort); + const auto remember = add_checkbox(dialog, *sizer, _L("Remember my choice"), false); + remember.SetToolTip(_L("Use these choices as defaults next time. The dialog still opens.")); + const auto dont_ask = add_checkbox(dialog, *sizer, _L("Don't ask again"), false); + dont_ask.SetToolTip(_L("Save these choices and apply them without asking next time. You can show this dialog again in Preferences.")); + + auto* buttons = new DialogButtons(&dialog, {"OK", "Cancel"}); + buttons->GetOK()->Bind(wxEVT_BUTTON, [&](wxCommandEvent&) { dialog.EndModal(wxID_OK); }); + buttons->GetCANCEL()->Bind(wxEVT_BUTTON, [&](wxCommandEvent&) { dialog.EndModal(wxID_CANCEL); }); + sizer->Add(buttons, 0, wxEXPAND | wxALL, dialog.FromDIP(12)); + dialog.SetSizerAndFit(sizer); + // DPIDialog centres itself before the sizer sets the final size. + dialog.CenterOnParent(); + wxGetApp().UpdateDlgDarkUI(&dialog); + if (dialog.ShowModal() != wxID_OK) + return false; + + options.keep_names = keep.GetValue(); + options.sort_names = sort.GetValue(); + if (load_mode != nullptr) { + options.separate_objects = load_mode->GetSelection() == 0; + // Separate objects leave the remembered assembly choice as it was. + if (!options.separate_objects) + options.load_as_assembly = load_mode->GetSelection() == 1; + } + options.remember = remember.GetValue(); + options.dont_ask = dont_ask.GetValue(); + return true; +} + +bool prepare_geometry_import_names(wxWindow* parent, const std::vector& models, GeometryImportNamePolicy& policy) +{ + const std::vector groups = name_groups(models); + bool needs_cleanup = false; + try { + for (const NameGroup& group : groups) + for (const std::string* name : group) + needs_cleanup = has_unsupported_name_characters(*name) || needs_cleanup; + } catch (const std::invalid_argument&) { + MessageDialog(parent, _L("A name in the file is not valid Unicode. The geometry was not imported."), + _L("Invalid name"), wxOK | wxICON_ERROR).ShowModal(); + return false; + } + if (!needs_cleanup) + return true; + policy.used = true; + + // A damaged saved replacement must not silently create more invalid names. + if (!policy.remove && !valid_import_name_replacement(policy.replacement)) { + policy.replacement = "_"; + policy.show_dialog = true; + } + + if (policy.show_dialog) { + ImportDialog dialog(parent, wxID_ANY, _L("Unsupported characters in names"), wxDefaultPosition, wxDefaultSize, + wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER); + auto* sizer = new wxBoxSizer(wxVERTICAL); + add_tip(dialog, *sizer, _L("Some original names contain characters that OrcaSlicer cannot use. Choose how to change them before importing."), 520); + // Item 0 removes the characters, item 1 replaces them with the text right after it. + auto* rule = add_radio_group(dialog, {_L("Remove unsupported characters"), _L("Replace with:")}, policy.remove ? 0 : 1, wxHORIZONTAL); + rule->SetRadioTooltip(1, _L("Each unsupported character is replaced with this text. It may be longer than one character.")); + auto* replacement_row = new wxBoxSizer(wxHORIZONTAL); + replacement_row->Add(rule, 0, wxALIGN_CENTER_VERTICAL); + auto* replacement = new ::TextInput(&dialog, from_u8(policy.replacement)); + replacement->GetTextCtrl()->SetFont(::Label::Body_14); + replacement_row->Add(replacement, 1, wxALIGN_CENTER_VERTICAL); + sizer->Add(replacement_row, 0, wxEXPAND | wxLEFT | wxRIGHT | wxTOP, dialog.FromDIP(12)); + auto* preview = new wxTextCtrl(&dialog, wxID_ANY, wxEmptyString, wxDefaultPosition, dialog.FromDIP(wxSize(540, 180)), + wxTE_MULTILINE | wxTE_READONLY | wxTE_DONTWRAP); + apply_label_style(preview); + sizer->Add(preview, 1, wxEXPAND | wxALL, dialog.FromDIP(12)); + const auto remember = add_checkbox(dialog, *sizer, _L("Remember my choice"), false); + remember.SetToolTip(_L("Use this rule as the default next time. The dialog still opens.")); + const auto dont_ask = add_checkbox(dialog, *sizer, _L("Don't ask again"), false); + dont_ask.SetToolTip(_L("Save this rule and apply it without asking next time. You can show this dialog again in Preferences.")); + auto* buttons = new DialogButtons(&dialog, {"OK", "Cancel"}); + + auto update_preview = [&]() { + const bool remove = rule->GetSelection() == 0; + replacement->Enable(!remove); + const std::string text = into_u8(replacement->GetTextCtrl()->GetValue()); + const bool valid = remove || valid_import_name_replacement(text); + buttons->GetOK()->Enable(valid); + if (!valid) { + preview->ChangeValue(_L("Enter a non-empty replacement containing only supported characters, or choose removal.")); + return; + } + const auto results = cleaned_groups(groups, remove ? std::string() : text); + wxString lines; + for (size_t group = 0; group < groups.size(); ++group) + for (size_t index = 0; index < groups[group].size(); ++index) + if (*groups[group][index] != results[group][index]) { + // TRN The placeholders are the original name and its imported replacement. + lines += format_wxstr(_L("%1% → %2%"), from_u8(*groups[group][index]), from_u8(results[group][index])) + "\n"; + } + preview->ChangeValue(lines); + }; + rule->Bind(wxEVT_COMMAND_RADIOBOX_SELECTED, [&](wxCommandEvent&) { update_preview(); }); + replacement->Bind(wxEVT_TEXT, [&](wxCommandEvent&) { update_preview(); }); + buttons->GetOK()->Bind(wxEVT_BUTTON, [&](wxCommandEvent&) { dialog.EndModal(wxID_OK); }); + buttons->GetCANCEL()->Bind(wxEVT_BUTTON, [&](wxCommandEvent&) { dialog.EndModal(wxID_CANCEL); }); + sizer->Add(buttons, 0, wxEXPAND | wxALL, dialog.FromDIP(12)); + dialog.SetSizerAndFit(sizer); + // DPIDialog centres itself before the sizer sets the final size. + dialog.CenterOnParent(); + wxGetApp().UpdateDlgDarkUI(&dialog); + update_preview(); + if (dialog.ShowModal() != wxID_OK) + return false; + policy.remove = rule->GetSelection() == 0; + policy.replacement = into_u8(replacement->GetTextCtrl()->GetValue()); + policy.remember = remember.GetValue(); + policy.dont_ask = dont_ask.GetValue(); + } + + const auto results = cleaned_groups(groups, policy.remove ? std::string() : policy.replacement); + for (size_t group = 0; group < groups.size(); ++group) + for (size_t index = 0; index < groups[group].size(); ++index) + *groups[group][index] = results[group][index]; + return true; +} + +void save_geometry_import_options(AppConfig& config, const std::string& format, const GeometryImportOptions& options) +{ + if (!options.chosen || (!options.remember && !options.dont_ask)) + return; + config.set_bool(option_key(format, "keep"), options.keep_names); + // A disabled sorting choice (Keep off) leaves the remembered one untouched. + if (options.keep_names) + config.set_bool(option_key(format, "sort"), options.sort_names); + if (format != "3mf") + config.set_bool(option_key(format, "assembly"), options.load_as_assembly); + if (format == "amf") + config.set_bool(option_key(format, "separate"), options.separate_objects); + if (format == "step") + config.set_bool("is_split_compound", options.split_compound); + if (options.dont_ask) + config.set_bool(format == "step" ? "enable_step_mesh_setting" : option_key(format, "show_dialog"), false); + if (format == "step") { + config.set("linear_deflection", float_to_string_decimal_point(options.linear_deflection, 3)); + config.set("angle_deflection", float_to_string_decimal_point(options.angle_deflection, 2)); + } +} + +void save_geometry_import_name_policy(AppConfig& config, const GeometryImportNamePolicy& policy) +{ + if (!policy.used || (!policy.remember && !policy.dont_ask)) + return; + config.set_bool("import_names_cleanup_remove", policy.remove); + config.set("import_names_cleanup_replacement", policy.replacement); + if (policy.dont_ask) + config.set_bool("import_names_cleanup_show_dialog", false); +} + +} // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/GeometryImportDialog.hpp b/src/slic3r/GUI/GeometryImportDialog.hpp new file mode 100644 index 0000000000..7623e7e981 --- /dev/null +++ b/src/slic3r/GUI/GeometryImportDialog.hpp @@ -0,0 +1,71 @@ +#pragma once + +#include +#include + +class CheckBox; +class wxSizer; +class wxStaticText; +class wxString; +class wxWindow; + +namespace Slic3r { +class AppConfig; +class Model; + +namespace GUI { + +// Values remain local to an import until all of its new dialogs have succeeded. +struct GeometryImportOptions { + bool keep_names = true; + bool sort_names = false; + bool load_as_assembly = true; + // AMF only: load the objects as separate objects, as OrcaSlicer did before; the assembly choice is then unused. + bool separate_objects = false; + // STEP only: Orca's Split compound choice; without it a multi-body compound loses its body names. + bool split_compound = true; + bool show_dialog = true; + bool remember = false; + bool dont_ask = false; + bool chosen = false; + double linear_deflection = 0.003; + double angle_deflection = 0.5; + bool single_object() const { return !separate_objects && !load_as_assembly; } +}; + +struct GeometryImportNamePolicy { + bool show_dialog = true; + bool remove = false; + bool remember = false; + bool dont_ask = false; + bool used = false; + std::string replacement = "_"; +}; + +// STEP and STP share one preference set; an empty result means an unrelated format. +std::string geometry_import_format(const std::string& path); +// Inspect the ZIP directory only, so CAD files do not enter the project-opening path. +bool is_geometry_only_3mf(const std::string& path); +GeometryImportOptions geometry_import_options(const AppConfig& config, const std::string& format); +GeometryImportNamePolicy geometry_import_name_policy(const AppConfig& config); +bool show_geometry_import_options(wxWindow* parent, const std::string& format, GeometryImportOptions& options); +// App-styled check box with its label, shared by the import dialogs. +struct ImportCheckBox { + ::CheckBox* box = nullptr; + wxStaticText* label = nullptr; + bool GetValue() const; + void SetValue(bool value) const; + // Greys the label too and stops it toggling the box. + void Enable(bool enable) const; + void SetToolTip(const wxString& tip) const; +}; +// A click on the label toggles the box and sends its wxEVT_TOGGLEBUTTON, as a click on the box does. +ImportCheckBox add_import_checkbox(wxWindow* parent, wxSizer& sizer, const wxString& text, bool value, int flags, int border); +// Sorting is offered only together with Keep original names; shared by the STEP dialog. +void link_sort_to_keep(const ImportCheckBox& keep, const ImportCheckBox& sort); +bool prepare_geometry_import_names(wxWindow* parent, const std::vector& models, GeometryImportNamePolicy& policy); +void save_geometry_import_options(AppConfig& config, const std::string& format, const GeometryImportOptions& options); +void save_geometry_import_name_policy(AppConfig& config, const GeometryImportNamePolicy& policy); + +} // namespace GUI +} // namespace Slic3r diff --git a/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.cpp b/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.cpp index c67de1d320..c54bc239a5 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.cpp @@ -2582,10 +2582,6 @@ void GLGizmoTextureDisplacement::update_uv_editor() { Plater *plater = wxGetApp().plater(); UVEditorCanvas *uv_canvas = plater->get_uv_editor_canvas(); - if (uv_canvas == nullptr) - return; - // Wired on every call rather than with the first unwrap: Unwrap itself is one of the pane's commands. - uv_canvas->set_command_callback([this](UVEditorCanvas::Command cmd, float value) { on_uv_command(int(cmd), value); }); const ModelVolume *mv = texture_volume(); TextureDisplacementLayer *layer = active_layer(); @@ -2600,6 +2596,15 @@ void GLGizmoTextureDisplacement::update_uv_editor() plater->show_uv_editor(false); return; } + if (uv_canvas == nullptr) { + // The pane does not exist yet: show_uv_editor() builds it after this frame. Run again right + // after that - both are queued on the plater, so they run in this order. + plater->show_uv_editor(true); + plater->CallAfter([this]() { update_uv_editor(); }); + return; + } + // Wired on every call rather than with the first unwrap: Unwrap itself is one of the pane's commands. + uv_canvas->set_command_callback([this](UVEditorCanvas::Command cmd, float value) { on_uv_command(int(cmd), value); }); // A vertex/edge edit committing (or an undo reverting one) changes the per-vertex UV overrides // without going through the Unwrap button. Detect that and force a re-solve, so the pane's geometry diff --git a/src/slic3r/GUI/MainFrame.cpp b/src/slic3r/GUI/MainFrame.cpp index 22e52d3b20..cce5dc796f 100644 --- a/src/slic3r/GUI/MainFrame.cpp +++ b/src/slic3r/GUI/MainFrame.cpp @@ -163,6 +163,7 @@ #include #include #include +#include using json = nlohmann::json; @@ -1218,7 +1219,11 @@ void MainFrame::update_layout() wxBusyCursor busy; - Freeze(); + // While the main frame is being created nothing is on screen, and a freeze would only walk + // every child window to block redraws that cannot happen. + wxWindowUpdateLocker no_updates; + if (IsShownOnScreen()) + no_updates.Lock(this); // Remove old settings if (m_layout != ESettingsLayout::Unknown) @@ -1310,7 +1315,6 @@ void MainFrame::update_layout() #endif Layout(); - Thaw(); } #ifdef __WXGTK__ @@ -1680,14 +1684,6 @@ void MainFrame::show_device(bool should_use_native) { // get it — otherwise a Bambu user sees two Device tabs, one of them permanently empty. const bool want_web_device_tab = use_printer_agents && wxGetApp().preset_bundle != nullptr && !wxGetApp().preset_bundle->use_bbl_device_tab(); - // An agent whose printers have nothing for the native Device and Calibration tabs leaves the web page as the only Device tab - bool want_native_device_tabs = true; - if (want_web_device_tab) { - const std::string agent_id = wxGetApp().resolve_printer_agent_id( - wxGetApp().preset_bundle->printers.get_edited_preset().config.opt_string("printer_agent")); - const PrinterAgentInfo* agent_info = NetworkAgentFactory::get_printer_agent_info(agent_id); - want_native_device_tabs = agent_info == nullptr || agent_info->native_device_tab; - } // Remove the extra page before switching to any layout that shouldn't have it. if (!want_web_device_tab) { @@ -1698,16 +1694,7 @@ void MainFrame::show_device(bool should_use_native) { } if (use_printer_agents) { - if (!want_native_device_tabs) { - if ((idx = m_tabpanel->FindPage(m_monitor_page)) != wxNOT_FOUND) { - m_monitor_page->Show(false); - m_tabpanel->RemovePage(idx); - } - if ((idx = m_tabpanel->FindPage(m_calibration_page)) != wxNOT_FOUND) { - m_calibration_page->Show(false); - m_tabpanel->RemovePage(idx); - } - } else if (!m_monitor_page->in_book()) { + if (!m_monitor_page->in_book()) { if ((idx = m_tabpanel->FindPage(m_printer_view_page)) != wxNOT_FOUND) { m_printer_view_page->Show(false); m_tabpanel->RemovePage(idx); @@ -1727,29 +1714,20 @@ void MainFrame::show_device(bool should_use_native) { TAB_ID_MULTI_DEVICE, m_multi_machine_page, _L("Multi-device"), "tab_multi_active"); } } - if (want_native_device_tabs && !m_calibration_page->in_book()) { + if (!m_calibration_page->in_book()) { m_calibration_page->Show(false); m_tabpanel->InsertPage(m_tabpanel->PositionAfter({TAB_ID_PROJECT}), TAB_ID_CALIBRATION, m_calibration_page, _L("Calibration"), "tab_calibration_active"); } if (want_web_device_tab) { - // Without the native Device tab the web page takes its id, so every way to the Device tab leads here - const char* id = want_native_device_tabs ? TAB_ID_MONITOR_WEB : TAB_ID_MONITOR; - const wxString label = want_native_device_tabs ? _L("Device (Web)") : _L("Device"); - idx = m_tabpanel->FindPage(m_printer_view_page); - if (idx != wxNOT_FOUND && m_tabpanel->FindPageByName(id) != idx) { + if ((idx = m_tabpanel->FindPage(m_printer_view_page)) == wxNOT_FOUND) { m_printer_view_page->Show(false); - m_tabpanel->RemovePage(idx); - idx = wxNOT_FOUND; - } - if (idx == wxNOT_FOUND) { - m_printer_view_page->Show(false); - // Immediately right of the native Device tab, or of Preview without it, not at the end of the tab bar. - m_tabpanel->InsertPage(m_tabpanel->PositionAfter({TAB_ID_MONITOR, TAB_ID_PREVIEW}), id, m_printer_view_page, label, - "tab_monitor_active"); + // Immediately right of the native Device tab, not at the end of the tab bar. + m_tabpanel->InsertPage(m_tabpanel->PositionAfter({TAB_ID_MONITOR}), TAB_ID_MONITOR_WEB, + m_printer_view_page, _L("Device (Web)"), "tab_monitor_active"); } else { - m_tabpanel->SetPageText(idx, label); + m_tabpanel->SetPageText(idx, _L("Device (Web)")); } } diff --git a/src/slic3r/GUI/NativeCommands.cpp b/src/slic3r/GUI/NativeCommands.cpp index b51fbd03aa..b379ec9e8d 100644 --- a/src/slic3r/GUI/NativeCommands.cpp +++ b/src/slic3r/GUI/NativeCommands.cpp @@ -524,7 +524,7 @@ void describe_commands(std::vector& commands) {"open_preferences", "Open the Preferences dialog on a tab, scrolled to one preference when given (shown on its own tab). Its " "controls are named after their preference keys: ui_input {\"target\": {\"name\": key, \"within\": " "\"Preferences\"}} changes one through the dialog; get_settings scope preferences reads them.", - CommandParamType::Text, "general, control, graphics, online or developer, optionally :, e.g. control:auto_arrange"}, + CommandParamType::Text, "general, files, behaviour, control, graphics, online or developer, optionally :, e.g. behaviour:auto_arrange"}, {"mode_simple", "Switch the settings view to Simple mode."}, {"mode_advanced", "Switch the settings view to Advanced mode."}, {"mode_expert", "Switch the settings view to Expert mode."}, @@ -770,6 +770,8 @@ std::vector build_command_catalog() } // "tab[:key]": the tab to show, and the preference whose control is scrolled into view and focused. static const std::pair tabs[] = {{"general", PreferencesTab::General}, + {"files", PreferencesTab::Files}, + {"behaviour", PreferencesTab::Behaviour}, {"control", PreferencesTab::Control}, {"graphics", PreferencesTab::Graphics}, {"online", PreferencesTab::Online}, @@ -779,7 +781,7 @@ std::vector build_command_catalog() const auto it = std::find_if(std::begin(tabs), std::end(tabs), [&](const auto& t) { return tab == t.first; }); if (it == std::end(tabs)) return AppActionRunResult{AppActionRunResult::Level::Error, - from_u8("Unknown tab \"" + tab + "\": general, control, graphics, online or developer")}; + from_u8("Unknown tab \"" + tab + "\": general, files, behaviour, control, graphics, online or developer")}; wxGetApp().open_preferences(it->second, colon == std::string::npos ? std::string() : param.substr(colon + 1)); return AppActionRunResult{AppActionRunResult::Level::Success}; }); diff --git a/src/slic3r/GUI/ObjectDataViewModel.cpp b/src/slic3r/GUI/ObjectDataViewModel.cpp index 6694c27448..7eaa8ee6bb 100644 --- a/src/slic3r/GUI/ObjectDataViewModel.cpp +++ b/src/slic3r/GUI/ObjectDataViewModel.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include "slic3r/GUI/GUI_ObjectSettings.hpp" #include #include @@ -1298,7 +1299,9 @@ void ObjectDataViewModel::DeleteVolumeChildren(wxDataViewItem& parent) // set m_containet to FALSE if parent has no child #ifndef __WXGTK__ - root->m_container = false; + // Instances, settings and other rows may remain after the volumes are gone. + if (root->GetChildCount() == 0) + root->m_container = false; #endif //__WXGTK__ } @@ -2105,12 +2108,44 @@ unsigned int ObjectDataViewModel::GetChildren(const wxDataViewItem &parent, wxDa return 0; } - unsigned int count = node->GetChildren().GetCount(); - for (unsigned int pos = 0; pos < count; pos++) - { - ObjectDataViewModelNode* child = node->GetChildren().Item(pos); - array.Add(wxDataViewItem((void*)child)); + std::vector children; + for (auto* child : node->GetChildren()) + children.push_back(child); + if (node->m_type == itObject && node->m_model_object != nullptr) { + const ModelObject& object = *node->m_model_object; + if (std::any_of(object.volumes.begin(), object.volumes.end(), [](const ModelVolume* volume) { + return volume->import_display_order >= 0; + })) { + // Node indices count visible volumes; cut connectors do not create tree nodes. + std::vector visible_parts; + for (const ModelVolume* part : object.volumes) + if (!(object.is_cut() && part->is_cut_connector())) + visible_parts.push_back(part); + std::vector slots; + std::vector parts; + for (size_t i = 0; i < children.size(); ++i) + if (children[i]->GetType() == itVolume) { + slots.push_back(i); + parts.push_back(children[i]); + } + auto rank = [&](const ObjectDataViewModelNode* part) { + const int index = part->GetIdx(); + if (index >= 0 && size_t(index) < visible_parts.size() && + visible_parts[size_t(index)]->import_display_order >= 0) + return size_t(visible_parts[size_t(index)]->import_display_order); + return std::numeric_limits::max(); + }; + std::stable_sort(parts.begin(), parts.end(), [&](const auto* a, const auto* b) { + return rank(a) < rank(b); + }); + // Keep settings/layers/instances in their existing slots and never alter m_idx. + for (size_t i = 0; i < slots.size(); ++i) + children[slots[i]] = parts[i]; + } } + const auto count = static_cast(children.size()); + for (auto* child : children) + array.Add(wxDataViewItem((void*)child)); return count; } diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index d145c3ba29..52fa105039 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -193,6 +193,8 @@ #include "GUI.hpp" #include "GUI_App.hpp" +#include "I18N.hpp" +#include "Lazy.hpp" #include "Shortcuts.hpp" #include "GUI_ObjectList.hpp" #ifdef __WXGTK__ @@ -301,6 +303,10 @@ #include "../Utils/Http.hpp" #include "../Utils/OrcaCloudServiceAgent.hpp" #include "StepMeshDialog.hpp" +#include "GeometryImportDialog.hpp" +#include "libslic3r/Format/ImportNames.hpp" +#include "libslic3r/Utils.hpp" +#include #include "FilamentMapDialog.hpp" #include "CloneDialog.hpp" #include "PurgeModeDialog.hpp" @@ -430,12 +436,12 @@ bool Plater::has_illegal_filename_characters(const wxString& wxs_name) bool Plater::has_illegal_filename_characters(const std::string& name) { - const char* illegal_characters = "<>:/\\|?*\""; - for (size_t i = 0; i < std::strlen(illegal_characters); i++) - if (name.find_first_of(illegal_characters[i]) != std::string::npos) - return true; - - return false; + try { + return has_unsupported_name_characters(name); + } catch (const std::invalid_argument&) { + // Invalid Unicode is not a valid editable project name either. + return true; + } } void Plater::show_illegal_characters_warning(wxWindow* parent) @@ -3789,7 +3795,7 @@ void Sidebar::remove_unused_filament_combos(const size_t current_extruder_count) } } -void Sidebar::update_all_preset_comboboxes() +void Sidebar::update_all_preset_comboboxes(bool update_filament_combos) { PresetBundle &preset_bundle = *wxGetApp().preset_bundle; const auto print_tech = preset_bundle.printers.get_edited_preset().printer_technology(); @@ -3902,7 +3908,7 @@ void Sidebar::update_all_preset_comboboxes() //p->combo_printer->update(); // Update the filament choosers to only contain the compatible presets, update the color preview, // update the dirty flags. - if (print_tech == ptFFF) { + if (print_tech == ptFFF && update_filament_combos) { for (PlaterPresetComboBox* cb : p->combos_filament) cb->update(); } @@ -3945,8 +3951,11 @@ void Sidebar::update_presets(Preset::Type preset_type) } - for (size_t i = 0; i < filament_cnt; i++) - p->combos_filament[i]->update(); + // Preset change must still refill the combos. Refill not needed before the mainframe shown. + // load_current_presets() loads the printer tab right after this and refills them anyway + if (wxGetApp().mainframe == nullptr || wxGetApp().mainframe->IsShown()) + for (size_t i = 0; i < filament_cnt; i++) + p->combos_filament[i]->update(); update_dynamic_filament_list(); break; @@ -4325,7 +4334,10 @@ void Sidebar::update_mixed_filament_list() auto* plater = dynamic_cast(GetParent()); if (!plater) return; - wxWindowUpdateLocker noUpdates(this); + // Freezing walks every child of the sidebar, a few ms each time; a hidden sidebar has nothing to repaint. + wxWindowUpdateLocker noUpdates; + if (IsShownOnScreen()) + noUpdates.Lock(this); const wxColour mc_bg = StateColor::darkModeColorFor(*wxWHITE); const wxColour mc_border = StateColor::darkModeColorFor(wxColour("#DBDBDB")); // same color with filament combo box border @@ -5726,7 +5738,9 @@ void Sidebar::on_filament_count_change(size_t num_filaments) if (choices.size() == 1 || num_physical == 1) choices[0]->GetDropDown().Invalidate(); - wxWindowUpdateLocker noUpdates_scrolled_panel(this); + wxWindowUpdateLocker noUpdates_scrolled_panel; + if (IsShownOnScreen()) + noUpdates_scrolled_panel.Lock(this); size_t i = choices.size(); while (i < num_physical) @@ -5737,8 +5751,12 @@ void Sidebar::on_filament_count_change(size_t num_filaments) choices.push_back(choice); // initialize selection - choice->update(); - choice->SetSelection(last_selection); + // While the main frame is still being created the list is left empty: + // load_current_presets() fills every filament combo once the window is built. + if (wxGetApp().mainframe != nullptr) { + choice->update(); + choice->SetSelection(last_selection); + } ++i; } @@ -7294,11 +7312,12 @@ struct Plater::priv AssembleView* assemble_view { nullptr }; // Docked/resizable 2D pane showing GLGizmoTextureDisplacement's LSCM unwrap of a painted // patch; a sibling AUI pane alongside "sidebar"/"main", not part of the view3D/preview/ - // assemble_view sizer - see its registration below and Plater::get_uv_editor_canvas(). The - // pane hosts the panel (toolbar + canvas + status line); uv_editor_canvas is its inner canvas, - // cached so the gizmo can reach it directly. - UVEditorPanel* uv_editor_panel { nullptr }; - UVEditorCanvas* uv_editor_canvas { nullptr }; + // assemble_view sizer - see make_uv_editor() and Plater::get_uv_editor_canvas(). The + // pane hosts the panel (toolbar + canvas + status line). Built by the first + // show_uv_editor(true), never prebuilt. + Lazy uv_editor{ "uv_editor", -1, [this] { return make_uv_editor(); } }; + // Builds the pane hidden and adds it to m_aui_mgr at its saved place. + UVEditorPanel* make_uv_editor(); bool first_enter_assemble{ true }; std::unique_ptr notification_manager; @@ -7315,7 +7334,8 @@ struct Plater::priv // UIThreadWorker can be used as a replacement for BoostThreadWorker if // no additional worker threads are desired (useful for debugging or profiling) PlaterWorker m_worker; - SLAImportDialog * m_sla_import_dlg; + // Built on the first import, never prebuilt. + Lazy m_sla_import_dlg{ "sla_import_dialog", -1, [this] { return new SLAImportDialog{ q }; } }; int m_job_prepare_state; @@ -7478,8 +7498,11 @@ struct Plater::priv LoadStrategy strategy, bool ask_multi = false, bool* published_out = nullptr, - bool* config_loaded_out = nullptr); - std::vector load_model_objects(const ModelObjectPtrs& model_objects, bool allow_negative_z = false, bool split_object = false, bool auto_drop = true); + bool* config_loaded_out = nullptr, + // Runs once the import dialogs were answered and the files read, before the model changes. + const std::function& before_publish = nullptr); + std::vector load_model_objects(const ModelObjectPtrs& model_objects, bool allow_negative_z = false, bool split_object = false, + bool auto_drop = true, const std::map* import_display_options = nullptr); // Texture-to-color import: a mesh loaded with UVs + a texture map gets its faces clustered // into printable colours, which are then matched against (or added to) the filament list. @@ -7900,7 +7923,6 @@ Plater::priv::priv(Plater *q, MainFrame *main_frame) , sidebar(new Sidebar(q)) , notification_manager(std::make_unique(q)) , m_worker{q, std::make_unique(notification_manager.get()), "ui_worker"} - , m_sla_import_dlg{new SLAImportDialog{q}} , m_job_prepare_state(Job::JobPrepareState::PREPARE_STATE_DEFAULT) , delayed_scene_refresh(false) , collapse_toolbar(GLToolbar::Normal, "Collapse") @@ -7993,24 +8015,13 @@ Plater::priv::priv(Plater *q, MainFrame *main_frame) // Orca: Make sidebar dockable m_aui_mgr.AddPane(sidebar, AuiMgr::sidebar_pane_info()); - // UV editor pane for GLGizmoTextureDisplacement's LSCM unwrap preview - a resizable/dockable - // sibling of "sidebar"/"main" like everything else registered on this same AUI manager, not a - // change to the view3D/preview/assemble_view sizer above. Hidden by default: only relevant - // while that gizmo is active with a layer using the "Unwrap (LSCM)" projection method (see - // Plater::show_uv_editor()), so it stays out of the way of everyone else's window layout. - uv_editor_panel = new UVEditorPanel(q); - uv_editor_canvas = uv_editor_panel->canvas(); - m_aui_mgr.AddPane(uv_editor_panel, wxAuiPaneInfo() - .Name("uv_editor") - .Caption(_L("UV Editor")) - .Right() - .Hide() - .BestSize(wxSize(40 * wxGetApp().em_unit(), 40 * wxGetApp().em_unit()))); + // The UV editor pane is added by make_uv_editor(). // Closing the pane with its own X has to reach the gizmo, or its next update would simply show the pane again. q->Bind(wxEVT_AUI_PANE_CLOSE, [this](wxAuiManagerEvent &evt) { evt.Skip(); - if (evt.GetPane() != nullptr && evt.GetPane()->window == uv_editor_panel && uv_editor_canvas != nullptr) - uv_editor_canvas->run_command(UVEditorCanvas::Command::PaneClosed); + UVEditorPanel* panel = uv_editor.get(); + if (panel != nullptr && evt.GetPane() != nullptr && evt.GetPane()->window == panel) + panel->canvas()->run_command(UVEditorCanvas::Command::PaneClosed); }); auto* panel_sizer = new wxBoxSizer(wxHORIZONTAL); @@ -8045,7 +8056,8 @@ Plater::priv::priv(Plater *q, MainFrame *main_frame) #ifdef __WXGTK__ layout = sanitize_window_layout_for_wayland(layout, &removed_floating_state); #endif - + // Panes that don't exist yet (uv_editor, dock panes) are skipped here; + // make_uv_editor() and add_dock_pane() read their entries from the saved layout when they are built. if (!m_aui_mgr.LoadPerspective(layout, false)) { BOOST_LOG_TRIVIAL(warning) << "Failed to restore saved window layout"; m_aui_mgr.LoadPerspective(m_default_window_layout, false); @@ -8053,13 +8065,6 @@ Plater::priv::priv(Plater *q, MainFrame *main_frame) BOOST_LOG_TRIVIAL(info) << "Removed floating AUI state from saved window layout for Wayland"; } - // The UV editor is a transient, gizmo-driven pane (see show_uv_editor()); a saved layout - // from a session that happened to close with it open would otherwise restore it visible on - // startup, with nothing painted in it. Force it hidden here so it only ever appears when the - // texture-displacement gizmo asks for it. - if (wxAuiPaneInfo &uv_pane = m_aui_mgr.GetPane("uv_editor"); uv_pane.IsOk()) - uv_pane.Hide(); - sidebar_layout.is_collapsed = !sidebar.IsShown(); } @@ -8989,7 +8994,8 @@ std::vector Plater::priv::load_files(const std::vector& input_ LoadStrategy strategy, bool ask_multi, bool* published_out, - bool* config_loaded_out) + bool* config_loaded_out, + const std::function& before_publish) { if (config_loaded_out != nullptr) *config_loaded_out = false; @@ -9004,11 +9010,30 @@ std::vector Plater::priv::load_files(const std::vector& input_ if (input_files.empty()) return std::vector(); - if (!input_files.empty()) - q->m_3mf_path = input_files[0].string(); - - // SoftFever: ugly fix so we can exist pa calib mode - background_process.fff_print()->calib_mode() = CalibMode::Calib_None; + const bool previous_thumbnail_state = q->skip_thumbnail_invalid; + ScopeGuard restore_thumbnail_state([this, previous_thumbnail_state]() { + // In particular, parser errors and cancelled preparation must restore this flag. + q->skip_thumbnail_invalid = previous_thumbnail_state; + }); + + if ((strategy & LoadStrategy::LoadModel) && (strategy & LoadStrategy::LoadConfig) && !(strategy & LoadStrategy::Restore)) { + const bool has_3mf = std::any_of(input_files.begin(), input_files.end(), [](const fs::path& file) { + return boost::algorithm::iends_with(file.string(), ".3mf"); + }); + const bool geometry_only = has_3mf && std::all_of(input_files.begin(), input_files.end(), [](const fs::path& file) { + return !boost::algorithm::iends_with(file.string(), ".3mf") || is_geometry_only_3mf(file.string()); + }); + if (geometry_only) { + // A plain CAD 3MF has no project to restore, even if its caller used default load flags. + const int project_flags = static_cast(LoadStrategy::LoadConfig) | static_cast(LoadStrategy::LoadAuxiliary); + strategy = static_cast(static_cast(strategy) & ~project_flags); + } + } + // New import dialogs run before any project path, calibration or material changes. + const bool stage_geometry = (strategy & LoadStrategy::LoadModel) && !(strategy & LoadStrategy::LoadConfig) && + std::any_of(input_files.begin(), input_files.end(), [](const fs::path& file) { + return !geometry_import_format(file.string()).empty(); + }); // BBS @@ -9034,7 +9059,9 @@ std::vector Plater::priv::load_files(const std::vector& input_ ProgressDialog dlg(loading, "", 100, find_toplevel_parent(q), wxPD_AUTO_HIDE | wxPD_CAN_ABORT | wxPD_APP_MODAL); wxBusyCursor busy; - auto *new_model = (!load_model || one_by_one) ? nullptr : new Slic3r::Model(); + // Owned here so that early returns of the import preparation do not leak it. + std::unique_ptr new_model_owner((!load_model || one_by_one) ? nullptr : new Slic3r::Model()); + auto *new_model = new_model_owner.get(); std::vector obj_idxs; std::string designer_model_id; @@ -9078,6 +9105,189 @@ std::vector Plater::priv::load_files(const std::vector& input_ const float LOAD_MODEL_RATIO = 0.9; + struct StagedGeometryFile { + // Reader outputs have one owner even when parsing throws or the user cancels. + Model model; + DynamicPrintConfig config; + ConfigSubstitutionContext substitutions{ForwardCompatibilitySubstitutionRule::Enable}; + PlateDataPtrs plates; + std::vector presets; + Semver version; + En3mfType file_type = En3mfType::From_BBS; + bool is_inches = false; + std::string format; + // Keep original names actually applied to this file, not only the remembered preference. + bool names_kept = false; + // A 3MF without project data; only its CAD part labels are offered as original names. + bool cad_3mf = false; + std::string designer_id; + std::string country_code; + ~StagedGeometryFile() { + release_PlateData_list(plates); + for (Preset* preset : presets) + delete preset; + } + }; + std::vector> staged_files; + std::map import_options; + GeometryImportNamePolicy name_policy = geometry_import_name_policy(*wxGetApp().app_config); + std::map import_display_options; + // Applies the presentation choices; returns true when part settings keep a single object shown as an assembly. + auto apply_import_presentation = [&import_display_options](ModelObject& object, bool single_object, bool sort) { + const bool has_part_settings = object.has_individual_part_settings(); + // Never hide effective part-specific print controls in the single-object mode. + object.imported_parts_hidden = single_object && object.volumes.size() > 1 && !has_part_settings; + import_display_options[object.id()] = sort; + return single_object && object.volumes.size() > 1 && has_part_settings; + }; + // Staged files are read before the load loop: the reading takes this share of the bar and the loop the rest. + const int staged_read_share = stage_geometry ? static_cast(INPUT_FILES_RATIO * 100) : 0; + auto loop_progress = [staged_read_share](int percent) { return staged_read_share + percent * (100 - staged_read_share) / 100; }; + if (stage_geometry) { + staged_files.reserve(input_files.size()); + bool visible_part_settings = false; + try { + auto file_options = [&](const StagedGeometryFile& file) -> GeometryImportOptions* { + return file.format.empty() ? nullptr : &import_options.at(file.format); + }; + // Keep original names is applied by the readers, so every choice is made before a file is read. + auto read_staged = [&](size_t index, StagedGeometryFile& target) { + const fs::path& file_path = input_files[index]; + // Readers restart their count at each stage, so the bar keeps the furthest point of this file. + int file_percent = 0; + auto progress = [&](int percent) { + file_percent = std::max(file_percent, std::clamp(percent, 0, 100)); + const int overall = static_cast(staged_read_share * (static_cast(index) + file_percent / 100.0) / input_files.size()); + return dlg.Update(overall, format_wxstr(_L("Loading file: %s"), from_path(file_path.filename()))); + }; + if (!progress(0)) + return false; + GeometryImportOptions* options = file_options(target); + LoadStrategy read_strategy = strategy; + if (options != nullptr) { + // Assembly modes keep each group's bodies together as one object; the presentation is chosen separately. + if (!options->separate_objects) + read_strategy = read_strategy | LoadStrategy::AssembleParts; + // Project part names already win in a 3MF project, so only a CAD 3MF takes its labels. + if (options->keep_names && (target.format != "3mf" || target.cad_3mf)) + read_strategy = read_strategy | LoadStrategy::KeepOriginalNames; + } + if (target.format == "step") { + target.model = Model::read_from_step(file_path.string(), read_strategy, + [&](int, int current, int total, bool& cancel) { + cancel = !progress(total > 0 ? current * 100 / total : 0); + is_user_cancel = is_user_cancel || cancel; + }, nullptr, + [&](Step& file, double& linear, double& angle, bool& split) { + if (!options->chosen) { + if (options->show_dialog) { + StepMeshDialog mesh_dialog(q, file, options->linear_deflection, options->angle_deflection, options); + if (mesh_dialog.ShowModal() != wxID_OK) { + is_user_cancel = true; + return -1; + } + } + options->chosen = true; + } + linear = options->linear_deflection; + angle = options->angle_deflection; + split = options->split_compound; + // Names of bodies merged by an unsplit compound cannot be kept, so that file gets Orca's names. + file.set_keep_original_names(options->keep_names && file.has_original_names() && + (split || !file.has_multi_body_compound())); + target.names_kept = file.keep_original_names(); + return 1; + }, options->linear_deflection, options->angle_deflection, options->split_compound); + } else if (target.format == "3mf") { + target.model = Model::read_from_archive(file_path.string(), &target.config, &target.substitutions, + target.file_type, read_strategy, &target.plates, &target.presets, &target.version, + [&](int, int current, int total, bool& cancel) { + cancel = !progress(total > 0 ? current * 100 / total : 0); + is_user_cancel = is_user_cancel || cancel; + }); + } else { + target.model = Model::read_from_file(file_path.string(), nullptr, nullptr, read_strategy, + &target.plates, &target.presets, &target.is_inches, &target.version, nullptr, + [&](int current, int total, bool& cancel, std::string& designer, std::string& country) { + target.designer_id = designer; + target.country_code = country; + cancel = !progress(total > 0 ? current * 100 / total : 0); + is_user_cancel = is_user_cancel || cancel; + }); + } + return !is_user_cancel && !dlg.WasCancelled(); + }; + + for (size_t index = 0; index < input_files.size(); ++index) { + auto staged = std::make_unique(); + staged->format = geometry_import_format(input_files[index].string()); + if (!staged->format.empty()) { + auto inserted = import_options.emplace(staged->format, geometry_import_options(*wxGetApp().app_config, staged->format)); + if (silence) + inserted.first->second.show_dialog = false; + } + staged->cad_3mf = staged->format == "3mf" && is_geometry_only_3mf(input_files[index].string()); + // One AMF/3MF dialog per format, at its first file; a 3MF project has nothing to choose. + // The STEP dialog runs inside the reader, which needs the document for its triangle count. + if ((staged->format == "amf" || staged->cad_3mf) && + !show_geometry_import_options(q, staged->format, import_options.at(staged->format))) + return empty_result; + if (!read_staged(index, *staged)) + return empty_result; + staged_files.push_back(std::move(staged)); + } + + for (const auto& staged : staged_files) { + const GeometryImportOptions* options = file_options(*staged); + if (options == nullptr) + continue; + if (staged->format != "step") + // A 3MF project keeps its own part names; only a CAD 3MF takes the labels from the file. + staged->names_kept = options->keep_names && (staged->format != "3mf" || staged->cad_3mf); + // Orca's own names carry no order worth sorting by. + for (ModelObject* object : staged->model.objects) + visible_part_settings = apply_import_presentation(*object, options->single_object(), + options->keep_names && options->sort_names) || visible_part_settings; + } + std::vector named_models; + for (const auto& staged : staged_files) + if (staged->names_kept) + named_models.push_back(&staged->model); + if (silence) + name_policy.show_dialog = false; + if (!prepare_geometry_import_names(q, named_models, name_policy)) + return empty_result; + if (visible_part_settings && !silence) + MessageDialog(q, _L("Some imported objects contain modifiers or parts with individual settings. They are shown as assemblies so that these settings remain visible."), + _L("Geometry import"), wxOK | wxICON_INFORMATION).ShowModal(); + } catch (const std::exception& error) { + if (!is_user_cancel && !dlg.WasCancelled()) + GUI::show_error(q, error.what()); + return empty_result; + } + } + + // The new import dialogs and the staged reading are done: a deferred project replacement starts here. + if (before_publish) { + // Only a CAD 3MF defers the replacement, and it always takes the staged path. + assert(stage_geometry); + // Replacing the project needs something to load; objects below this volume are dropped while loading, + // as in Model::removed_objects_with_zero_volume(). + const bool has_geometry = std::any_of(staged_files.begin(), staged_files.end(), [](const auto& staged) { + return std::any_of(staged->model.objects.begin(), staged->model.objects.end(), [](const ModelObject* object) { + return object->get_object_stl_stats().volume >= 0.0000000001; + }); + }); + if (!has_geometry) { + GUI::show_error(q, _L("The file does not contain any geometry data.")); + return empty_result; + } + before_publish(); + } + q->m_3mf_path = input_files.front().string(); + // Leave the previous calibration mode intact when preparation was cancelled. + background_process.fff_print()->calib_mode() = CalibMode::Calib_None; + for (size_t i = 0; i < input_files.size(); ++i) { int project_filament_count = 1; @@ -9094,7 +9304,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ const auto real_filename = (strategy & LoadStrategy::Restore) ? input_files[++i].filename() : filename; const auto dlg_info = _L("Loading file") + ": " + from_path(real_filename); BOOST_LOG_TRIVIAL(trace) << __FUNCTION__ << boost::format(": load file %1%") % filename; - dlg_cont = dlg.Update(progress_percent, dlg_info); + dlg_cont = dlg.Update(loop_progress(progress_percent), dlg_info); if (!dlg_cont) return empty_result; const bool type_3mf = std::regex_match(path.string(), pattern_3mf); @@ -9103,6 +9313,8 @@ std::vector Plater::priv::load_files(const std::vector& input_ // const bool type_prusa = std::regex_match(path.string(), pattern_prusa); Slic3r::Model model; + StagedGeometryFile legacy_read; + StagedGeometryFile& parsed_file = stage_geometry ? *staged_files[i] : legacy_read; // BBS: add auxiliary files related logic bool load_aux = strategy & LoadStrategy::LoadAuxiliary, load_old_project = false; if (load_model && load_config && type_3mf) { @@ -9115,23 +9327,26 @@ std::vector Plater::priv::load_files(const std::vector& input_ try { if (type_3mf) { DynamicPrintConfig config; - Semver file_version; - En3mfType en_3mf_file_type = En3mfType::From_BBS; + Semver& file_version = parsed_file.version; + En3mfType& en_3mf_file_type = parsed_file.file_type; // BBS: a "published" 3MF carries a flag plus the author-selected setting keys; // on load keep the user's current presets and overlay only those keys. Declared // here (outside the config block below) so it stays alive for the embedded-preset // gate, the metadata strip and the preset overlay after the block closes. PublishedConfig published_config; { - DynamicPrintConfig config_loaded; + DynamicPrintConfig& config_loaded = parsed_file.config; - // BBS: add part plate related logic - PlateDataPtrs plate_data; - ConfigSubstitutionContext config_substitutions{ForwardCompatibilitySubstitutionRule::Enable}; - std::vector project_presets; + // Reader outputs remain owned through every downstream early return. + PlateDataPtrs& plate_data = parsed_file.plates; + ConfigSubstitutionContext& config_substitutions = parsed_file.substitutions; + std::vector& project_presets = parsed_file.presets; // BBS: backup & restore q->skip_thumbnail_invalid = true; - model = Slic3r::Model::read_from_archive(path.string(), &config_loaded, &config_substitutions, en_3mf_file_type, strategy, &plate_data, &project_presets, + if (stage_geometry) { + model = std::move(parsed_file.model); + } else { + model = Slic3r::Model::read_from_archive(path.string(), &config_loaded, &config_substitutions, en_3mf_file_type, strategy, &plate_data, &project_presets, &file_version, [&dlg, real_filename, &progress_percent, stage_percent, INPUT_FILES_RATIO, total_files, i, &is_user_cancel](int import_stage, int current, int total, bool &cancel) { @@ -9145,6 +9360,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ if (cancel) is_user_cancel = cancel; }); + } BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ":" << __LINE__ << boost::format(", plate_data.size %1%, project_preset.size %2%, is_bbs_or_orca_3mf %3%, file_version %4% \n") % plate_data.size() % project_presets.size() % (en_3mf_file_type == En3mfType::From_BBS || en_3mf_file_type == En3mfType::From_Orca) % file_version.to_string(); @@ -9424,7 +9640,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ if (plate_data.size() > 0) { BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ":" << __LINE__ << boost::format(", import 3mf UPDATE_GCODE_RESULT \n"); wxString msg = wxString::Format(_L("Loading file: %s"), from_path(real_filename)); - dlg_cont = dlg.Update(progress_percent, msg); + dlg_cont = dlg.Update(loop_progress(progress_percent), msg); if (!dlg_cont) { q->skip_thumbnail_invalid = false; return empty_result; @@ -9477,7 +9693,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ if (load_config && !config_loaded.empty()) { BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ":" << __LINE__ << boost::format(", import 3mf IMPORT_LOAD_CONFIG \n"); wxString msg = wxString::Format(_L("Loading file: %s"), from_path(real_filename)); - dlg_cont = dlg.Update(progress_percent, msg); + dlg_cont = dlg.Update(loop_progress(progress_percent), msg); if (!dlg_cont) { q->skip_thumbnail_invalid = false; return empty_result; @@ -9801,13 +10017,17 @@ std::vector Plater::priv::load_files(const std::vector& input_ } } else { // BBS: add plate data related logic - PlateDataPtrs plate_data; - // BBS: project embedded settings - std::vector project_presets; - bool is_xxx; - Semver file_version; + PlateDataPtrs& plate_data = parsed_file.plates; + // Reader outputs stay alive through the existing import branches. + std::vector& project_presets = parsed_file.presets; + bool& is_xxx = parsed_file.is_inches; + Semver& file_version = parsed_file.version; - if (boost::iends_with(path.string(), ".stp") || + if (stage_geometry) { + model = std::move(parsed_file.model); + designer_model_id = parsed_file.designer_id; + designer_country_code = parsed_file.country_code; + } else if (boost::iends_with(path.string(), ".stp") || boost::iends_with(path.string(), ".step")) { double linear = string_to_double_decimal_point(wxGetApp().app_config->get("linear_deflection")); if (linear <= 0) linear = 0.003; @@ -9829,7 +10049,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ if (!isUtf8StepFile) { const auto no_warn = wxGetApp().app_config->get_bool("step_not_utf8_no_warn"); if (!no_warn) { - MessageDialog dlg(nullptr, _L("Component name(s) inside step file not in UTF-8 format!") + "\n\n" + _L("Because of unsupported text encoding, garbage characters may appear!"), + MessageDialog dlg(nullptr, _L("Component name(s) inside STEP file not in UTF-8 format!") + "\n\n" + _L("Because of unsupported text encoding, garbage characters may appear!"), wxString(SLIC3R_APP_FULL_NAME " - ") + _L("Attention!"), wxOK | wxICON_INFORMATION); dlg.show_dsa_button(_L("Remember my choice.")); dlg.ShowModal(); @@ -9920,7 +10140,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ } progress_percent = 100.0f * (float)i / (float)total_files + INIT_MODEL_RATIO * 100.0f / (float)total_files; - dlg_cont = dlg.Update(progress_percent); + dlg_cont = dlg.Update(loop_progress(progress_percent)); if (!dlg_cont) { q->skip_thumbnail_invalid = false; return empty_result; @@ -9980,11 +10200,25 @@ std::vector Plater::priv::load_files(const std::vector& input_ // convert_model_if(model, answer_convert_from_imperial_units == wxID_YES); } - if (!is_project_file && model.looks_like_multipart_object()) { + // An AMF group with non-printable bodies was kept apart on purpose; merging it would make them printable. + // Only the assembly modes keep such groups apart; Separate objects asks as before. + const auto amf_options = import_options.find("amf"); + const bool amf_assembly = stage_geometry && parsed_file.format == "amf" && amf_options != import_options.end() && + !amf_options->second.separate_objects; + const bool has_excluded_bodies = amf_assembly && std::any_of(model.objects.begin(), model.objects.end(), [](const ModelObject* object) { + return std::any_of(object->instances.begin(), object->instances.end(), [](const ModelInstance* instance) { return !instance->printable; }); + }); + if (!is_project_file && !has_excluded_bodies && model.looks_like_multipart_object()) { MessageDialog msg_dlg(q, _L("This file contains several objects positioned at multiple heights.\nInstead of considering them as multiple objects, should the file be loaded as a single object with multiple parts\?") + "\n", _L("Multi-part object detected"), wxICON_WARNING | wxYES | wxNO); if (msg_dlg.ShowModal() == wxID_YES) { - model.convert_multipart_object(filaments_cnt); + // Kept original part names survive Orca's own merge; other files keep its naming. + model.convert_multipart_object(filaments_cnt, parsed_file.names_kept); + // The merged object is new, so the choices of this file's import dialog apply to it again. + if (auto options = import_options.find(parsed_file.format); stage_geometry && options != import_options.end()) + for (ModelObject* object : model.objects) + apply_import_presentation(*object, options->second.single_object(), + options->second.keep_names && options->second.sort_names); } } } @@ -10000,7 +10234,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ //} progress_percent = 100.0f * (float)i / (float)total_files + CENTER_AROUND_ORIGIN_RATIO * 100.0f / (float)total_files; - dlg_cont = dlg.Update(progress_percent); + dlg_cont = dlg.Update(loop_progress(progress_percent)); if (!dlg_cont) { q->skip_thumbnail_invalid = false; return empty_result; @@ -10015,7 +10249,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ":" << __LINE__ << " " << boost::format("import 3mf IMPORT_LOAD_MODEL_OBJECTS \n"); wxString msg = wxString::Format(_L("Loading file: %s"), from_path(real_filename)); model_idx++; - dlg_cont = dlg.Update(progress_percent, msg); + dlg_cont = dlg.Update(loop_progress(progress_percent), msg); if (!dlg_cont) { q->skip_thumbnail_invalid = false; return empty_result; @@ -10028,7 +10262,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ tolal_model_count += model_idx; progress_percent = 100.0f * (float)i / (float)total_files + LOAD_MODEL_RATIO * 100.0f / (float)total_files; - dlg_cont = dlg.Update(progress_percent); + dlg_cont = dlg.Update(loop_progress(progress_percent)); if (!dlg_cont) { q->skip_thumbnail_invalid = false; return empty_result; @@ -10051,9 +10285,9 @@ std::vector Plater::priv::load_files(const std::vector& input_ if (model.texture_mesh && has_importable_texture(*model.texture_mesh)) { TextureImportResult texture_import_result; auto cancel_cb = [&dlg, &dlg_cont]() { return !dlg_cont || dlg.WasCancelled(); }; - auto progress_cb = [&dlg, &dlg_cont, &progress_percent](int percent) { + auto progress_cb = [&dlg, &dlg_cont, &progress_percent, &loop_progress](int percent) { progress_percent = std::clamp(percent, 0, 100); - dlg_cont = dlg.Update(progress_percent, _L("Matching textures to filaments")); + dlg_cont = dlg.Update(loop_progress(progress_percent), _L("Matching textures to filaments")); return dlg_cont; }; if (!run_textured_mesh_import_dialog(model, texture_import_result, cancel_cb, progress_cb)) { @@ -10068,8 +10302,8 @@ std::vector Plater::priv::load_files(const std::vector& input_ if (!texture_import_result.painted.face_colors.empty()) { std::vector texture_object_idxs(model.objects.size()); std::iota(texture_object_idxs.begin(), texture_object_idxs.end(), 0); - auto apply_progress_cb = [&dlg](int percent, const wxString& msg) { - dlg.Update(std::clamp(percent, 0, 100), msg); + auto apply_progress_cb = [&dlg, &loop_progress](int percent, const wxString& msg) { + dlg.Update(loop_progress(std::clamp(percent, 0, 100)), msg); return true; }; apply_textured_mesh_import_result(model, texture_object_idxs, texture_import_result, @@ -10078,7 +10312,8 @@ std::vector Plater::priv::load_files(const std::vector& input_ } BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ":" << __LINE__ << boost::format(", before load_model_objects, count %1%")%model.objects.size(); - auto loaded_idxs = load_model_objects(model.objects, is_project_file); + auto loaded_idxs = load_model_objects(model.objects, is_project_file, false, true, + stage_geometry ? &import_display_options : nullptr); obj_idxs.insert(obj_idxs.end(), loaded_idxs.begin(), loaded_idxs.end()); // load_model_objects only transfers ModelObjects; carry the Model-level CAD recipe @@ -10093,7 +10328,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ":" << __LINE__ << boost::format(", finished load_model_objects"); wxString msg = wxString::Format(_L("Loading file: %s"), from_path(real_filename)); - dlg_cont = dlg.Update(progress_percent, msg); + dlg_cont = dlg.Update(loop_progress(progress_percent), msg); if (!dlg_cont) { q->skip_thumbnail_invalid = false; return empty_result; @@ -10101,11 +10336,14 @@ std::vector Plater::priv::load_files(const std::vector& input_ } else { // This must be an .stl or .obj file, which may contain a maximum of one volume. for (const ModelObject *model_object : model.objects) { - new_model->add_object(*model_object); + ModelObject* copied_object = new_model->add_object(*model_object); + const auto display = import_display_options.find(model_object->id()); + if (display != import_display_options.end()) + import_display_options.emplace(copied_object->id(), display->second); BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ":" << __LINE__ << boost::format(", added object %1%")%model_object->name; wxString msg = wxString::Format(_L("Loading file: %s"), from_path(real_filename)); - dlg_cont = dlg.Update(progress_percent, msg); + dlg_cont = dlg.Update(loop_progress(progress_percent), msg); if (!dlg_cont) { q->skip_thumbnail_invalid = false; return empty_result; @@ -10131,8 +10369,24 @@ std::vector Plater::priv::load_files(const std::vector& input_ // convert to multipart and split after load_model_objects // to keep relative positioning if auto_drop == false - if (single_object_answer == wxID_YES || new_model_auto_drop == false) - new_model->convert_multipart_object(filaments_cnt); + if (single_object_answer == wxID_YES || new_model_auto_drop == false) { + // Parts keep their imported names when any geometry import asked to keep them. + new_model->convert_multipart_object(filaments_cnt, std::any_of(staged_files.begin(), staged_files.end(), + [](const auto& staged) { return staged->names_kept; })); + // Files of several kinds share the merged object; it takes a choice only when every file made it. + const bool all_staged = stage_geometry && std::all_of(staged_files.begin(), staged_files.end(), + [](const auto& staged) { return !staged->format.empty(); }); + bool single_object = all_staged; + bool sort = all_staged; + for (const auto& staged : staged_files) + if (const auto options = import_options.find(staged->format); options != import_options.end()) { + single_object = single_object && options->second.single_object(); + sort = sort && options->second.keep_names && options->second.sort_names; + } + if (stage_geometry) + for (ModelObject* object : new_model->objects) + apply_import_presentation(*object, single_object, sort); + } } // TODO @@ -10142,7 +10396,8 @@ std::vector Plater::priv::load_files(const std::vector& input_ // DONE when manually split to object ask users if looks_like_multipart and none have auto_drob disabled if they want to disable auto_drop for all resulting objects. // - add icon in object list, similar to fuzzy painting, etc. - auto loaded_idxs = load_model_objects(new_model->objects, false, false, new_model_auto_drop); + auto loaded_idxs = load_model_objects(new_model->objects, false, false, new_model_auto_drop, + stage_geometry ? &import_display_options : nullptr); obj_idxs.insert(obj_idxs.end(), loaded_idxs.begin(), loaded_idxs.end()); if (single_object_answer == wxID_NO && new_model_auto_drop == false) { @@ -10194,7 +10449,6 @@ std::vector Plater::priv::load_files(const std::vector& input_ } } - if (new_model) delete new_model; //BBS: translate old 3mf to correct positions if (translate_old) { @@ -10332,6 +10586,12 @@ std::vector Plater::priv::load_files(const std::vector& input_ msg.ShowModal(); } } + if (stage_geometry && !obj_idxs.empty()) { + // Save only after all new questions succeeded and the prepared models were published. + for (const auto& entry : import_options) + save_geometry_import_options(*wxGetApp().app_config, entry.first, entry.second); + save_geometry_import_name_policy(*wxGetApp().app_config, name_policy); + } q->schedule_background_process(true); q->mark_plate_toolbar_image_dirty(); return obj_idxs; @@ -10339,7 +10599,8 @@ std::vector Plater::priv::load_files(const std::vector& input_ #define AUTOPLACEMENT_ON_LOAD -std::vector Plater::priv::load_model_objects(const ModelObjectPtrs& model_objects, bool allow_negative_z, bool split_object, bool auto_drop) +std::vector Plater::priv::load_model_objects(const ModelObjectPtrs& model_objects, bool allow_negative_z, bool split_object, + bool auto_drop, const std::map* import_display_options) { const Vec3d bed_size = Slic3r::to_3d(this->bed.build_volume().bounding_volume2d().size(), 1.0) - 2.0 * Vec3d::Ones(); @@ -10355,6 +10616,12 @@ std::vector Plater::priv::load_model_objects(const ModelObjectPtrs& mode #endif /* AUTOPLACEMENT_ON_LOAD */ for (ModelObject *model_object : model_objects) { auto *object = model.add_object(*model_object); + if (import_display_options != nullptr) { + const auto display = import_display_options->find(model_object->id()); + if (display != import_display_options->end()) + // The final clone has fresh IDs but still has the source volume order here. + set_import_volume_order(*object, display->second); + } object->sort_volumes(true); std::string object_name = object->name.empty() ? fs::path(object->input_file).filename().string() : object->name; obj_idxs.push_back(obj_count++); @@ -10951,6 +11218,12 @@ void Plater::priv::reset(bool apply_presets_change, bool reload_presets) sidebar.Show(); } auto layout = m_aui_mgr.SavePerspective(); + // The UV editor pane is only built when first used; keep its saved place from an earlier session. + if (!uv_editor.built()) { + const std::string kept = aui_pane_layout_entry(wxGetApp().app_config->get("window_layout"), "uv_editor"); + if (!kept.empty()) + layout += wxString::FromUTF8(kept) + "|"; + } wxGetApp().app_config->set("window_layout", layout.utf8_string()); } } @@ -13943,6 +14216,34 @@ void Plater::priv::on_action_print_plate_from_sdcard(SimpleEvent&) open_machine_select_dialog(0, PrintFromType::FROM_SDCARD_VIEW); } +UVEditorPanel* Plater::priv::make_uv_editor() +{ + auto* panel = new UVEditorPanel(q); + // AddPane() leaves the window's visibility alone; the next m_aui_mgr.Update() shows it with the pane. + panel->Hide(); +#ifdef _MSW_DARK_MODE + // Built after MainFrame gave the window its dark colours, so it needs its own. + wxGetApp().UpdateDarkUIWin(panel); +#endif + wxAuiPaneInfo pane = wxAuiPaneInfo() + .Name("uv_editor") + .Right() + .BestSize(wxSize(40 * wxGetApp().em_unit(), 40 * wxGetApp().em_unit())); + // The window layout was restored before this pane existed, so take its saved place from there. + if (const std::string saved = aui_pane_layout_entry(wxGetApp().app_config->get("window_layout"), "uv_editor"); !saved.empty()) { + wxString entry = wxString::FromUTF8(saved); +#ifdef __WXGTK__ + entry = sanitize_window_layout_for_wayland(entry); +#endif + m_aui_mgr.LoadPaneInfo(entry, pane); + } + // After LoadPaneInfo(), which also restores the caption saved in another UI language, and + // hidden even if the layout was saved with it open: only the gizmo shows it. + pane.Caption(_L("UV Editor")).Hide(); + m_aui_mgr.AddPane(panel, pane); + return panel; +} + void Plater::priv::on_tab_selection_changing(wxBookCtrlEvent& e) { // Ignore event raised by child controls @@ -13964,12 +14265,7 @@ void Plater::priv::on_tab_selection_changing(wxBookCtrlEvent& e) const bool use_printer_agents = wxGetApp().app_config->get_bool("use_printer_agents"); const bool use_native_device_tab = wxGetApp().preset_bundle && (wxGetApp().preset_bundle->use_bbl_device_tab() || use_printer_agents); - // Pointer test, not a name lookup: in printer-agents mode this page is TAB_ID_MONITOR_WEB - // while the native Device tab holds TAB_ID_MONITOR, and in legacy-web mode, or for an agent - // without the native tab, it holds TAB_ID_MONITOR itself. - const bool selecting_web_device_tab = main_frame->m_printer_view_page && - main_frame->m_tabpanel->GetPage(new_sel) == main_frame->m_printer_view_page; - if (use_native_device_tab && new_name == TAB_ID_MONITOR && !selecting_web_device_tab) { + if (use_native_device_tab && new_name == TAB_ID_MONITOR) { // BBL network module is only required for BBL-vendor printers. // Non-BBL Python plugins (e.g. moonraker) drive the Device tab without it. if (!use_printer_agents && wxGetApp().preset_bundle->is_bbl_vendor() && !Slic3r::NetworkAgent::is_network_module_loaded()) { @@ -13981,6 +14277,11 @@ void Plater::priv::on_tab_selection_changing(wxBookCtrlEvent& e) } } } else { + // Pointer test, not a name lookup: in printer-agents mode this page is TAB_ID_MONITOR_WEB + // while the native Device tab holds TAB_ID_MONITOR, and in legacy-web mode it holds + // TAB_ID_MONITOR itself. + const bool selecting_web_device_tab = main_frame->m_printer_view_page && + main_frame->m_tabpanel->GetPage(new_sel) == main_frame->m_printer_view_page; if (selecting_web_device_tab) { // Use the selected discovered machine when the preset has no host. main_frame->load_printer_url(); @@ -14957,8 +15258,11 @@ bool Plater::priv::has_assemble_view() const bool Plater::priv::can_scale_to_print_volume() const { const BuildVolume_Type type = this->bed.build_volume().type(); + const Selection& selection = get_selection(); + // Selection::scale_to_fit_print_volume() does nothing for a selection of parts, so don't offer it return !sidebar->obj_list()->has_selected_cut_object() - && !view3D->get_canvas3d()->get_selection().is_empty() + && !selection.is_empty() + && selection.get_mode() != Selection::Volume && (type == BuildVolume_Type::Rectangle || type == BuildVolume_Type::Circle); } #endif // ENABLE_ENHANCED_PRINT_VOLUME_FIT @@ -16222,9 +16526,6 @@ LoadType determine_load_type(std::string filename, std::string override_setting void Plater::load_project(wxString const& filename2, wxString const& originfile) { - model().calib_pa_pattern.reset(nullptr); - model().plates_custom_gcodes.clear(); - BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "filename is: " << filename2 << "and originfile is: " << originfile; BOOST_LOG_TRIVIAL(info) << __FUNCTION__; auto filename = filename2; @@ -16241,7 +16542,9 @@ void Plater::load_project(wxString const& filename2, // BSS: save project, force close int result; - if ((result = close_with_confirm(check)) == wxID_CANCEL) { + // Run by replace_project(), so a load that stops before it leaves the current project unchanged. + std::function close_project; + if ((result = close_with_confirm(check, &close_project)) == wxID_CANCEL) { return; } @@ -16256,17 +16559,6 @@ void Plater::load_project(wxString const& filename2, m_loading_project = true; ScopeGuard loading_project_sc([this]() { m_loading_project = false; }); // Make sure state restored on any early return - m_only_gcode = false; - m_exported_file = false; - get_notification_manager()->bbl_close_plateinfo_notification(); - get_notification_manager()->bbl_close_preview_only_notification(); - get_notification_manager()->bbl_close_3mf_warn_notification(); - get_notification_manager()->close_notification_of_type(NotificationType::PlaterError); - get_notification_manager()->close_notification_of_type(NotificationType::PlaterWarning); - get_notification_manager()->close_notification_of_type(NotificationType::SlicingError); - get_notification_manager()->close_notification_of_type(NotificationType::SlicingSeriousWarning); - get_notification_manager()->close_notification_of_type(NotificationType::SlicingWarning); - auto path = into_path(filename); auto strategy = LoadStrategy::LoadModel | LoadStrategy::LoadConfig; @@ -16285,10 +16577,32 @@ void Plater::load_project(wxString const& filename2, } bool load_restore = strategy & LoadStrategy::Restore; - // Take the Undo / Redo snapshot. - reset(); - - Plater::TakeSnapshot snapshot(this, "Load Project", UndoRedo::SnapshotType::ProjectSeparator); + std::optional snapshot; + auto replace_project = [&]() { + // close_with_confirm() sets it on every path that does not cancel. + assert(close_project); + close_project(); + get_notification_manager()->bbl_close_plateinfo_notification(); + get_notification_manager()->bbl_close_preview_only_notification(); + get_notification_manager()->bbl_close_3mf_warn_notification(); + get_notification_manager()->close_notification_of_type(NotificationType::PlaterError); + get_notification_manager()->close_notification_of_type(NotificationType::PlaterWarning); + get_notification_manager()->close_notification_of_type(NotificationType::SlicingError); + get_notification_manager()->close_notification_of_type(NotificationType::SlicingSeriousWarning); + get_notification_manager()->close_notification_of_type(NotificationType::SlicingWarning); + model().calib_pa_pattern.reset(nullptr); + model().plates_custom_gcodes.clear(); + m_only_gcode = false; + m_exported_file = false; + reset(); + // Take the Undo / Redo snapshot. + snapshot.emplace(this, "Load Project", UndoRedo::SnapshotType::ProjectSeparator); + }; + // A CAD 3MF passes its import dialogs first: the project is replaced only once the file is ready, + // so a Cancel there keeps the current project. + const bool replace_when_ready = !load_restore && is_geometry_only_3mf(path.string()); + if (!replace_when_ready) + replace_project(); std::vector input_paths; input_paths.push_back(path); @@ -16296,7 +16610,11 @@ void Plater::load_project(wxString const& filename2, input_paths.push_back(into_u8(originfile)); bool loaded_published = false; - std::vector res = load_files(input_paths, strategy, false, &loaded_published); + std::vector res = load_files(input_paths, strategy, false, &loaded_published, + replace_when_ready ? replace_project : std::function()); + // The import was cancelled or failed before the project was replaced. + if (!snapshot) + return; reset_project_dirty_initial_presets(); update_project_dirty_from_presets(); @@ -18202,9 +18520,12 @@ void Plater::import_zip_archive() void Plater::import_sl1_archive() { auto &w = get_ui_job_worker(); - if (w.is_idle() && p->m_sla_import_dlg->ShowModal() == wxID_OK) { + if (!w.is_idle()) + return; + SLAImportDialog* dlg = p->m_sla_import_dlg.ensure(); + if (dlg->ShowModal() == wxID_OK) { p->take_snapshot(_u8L("Import SLA archive")); - replace_job(w, std::make_unique(p->m_sla_import_dlg)); + replace_job(w, std::make_unique(dlg)); } } @@ -18482,13 +18803,25 @@ void Plater::force_update_all_plate_thumbnails() } // BBS: backup -std::vector Plater::load_files(const std::vector& input_files, LoadStrategy strategy, bool ask_multi, bool* published_out) { - //BBS: wish to reset state when load a new file - p->m_slice_all_only_has_gcode = false; - //BBS: wish to reset all plates stats item selected state when load a new file - p->preview->get_canvas3d()->reset_select_plate_toolbar_selection(); +std::vector Plater::load_files(const std::vector& input_files, LoadStrategy strategy, bool ask_multi, bool* published_out, + const std::function& before_publish) { + auto reset_load_state = [this]() { + //BBS: wish to reset state when load a new file + p->m_slice_all_only_has_gcode = false; + //BBS: wish to reset all plates stats item selected state when load a new file + p->preview->get_canvas3d()->reset_select_plate_toolbar_selection(); + }; + // A deferred project replacement also defers this reset, so a cancelled import keeps the preview state. + std::function publish; + if (before_publish) + publish = [&]() { + reset_load_state(); + before_publish(); + }; + else + reset_load_state(); bool config_loaded = false; - std::vector result = p->load_files(input_files, strategy, ask_multi, published_out, &config_loaded); + std::vector result = p->load_files(input_files, strategy, ask_multi, published_out, &config_loaded, publish); if (config_loaded && !is_loading_project()) normalize_bed_types(false); return result; @@ -18826,6 +19159,17 @@ void ProjectDropDialog::on_dpi_changed(const wxRect& suggested_rect) Refresh(); } +LoadType determine_load_type(std::string filename, std::string override_setting); + +static LoadType choose_3mf_load_type(Plater& plater, const fs::path& file) +{ + if (is_geometry_only_3mf(file.string())) + return LoadType::LoadGeometry; + const std::string filename = encode_path(file.filename().string().c_str()); + const bool ask_when_relevant = wxGetApp().app_config->get(SETTING_PROJECT_LOAD_BEHAVIOUR) == OPTION_PROJECT_LOAD_BEHAVIOUR_ASK_WHEN_RELEVANT; + return determine_load_type(filename, !plater.model().objects.empty() && ask_when_relevant ? OPTION_PROJECT_LOAD_BEHAVIOUR_ALWAYS_ASK : ""); +} + //BBS: remove GCodeViewer as seperate APP logic bool Plater::load_files(const wxArrayString& filenames) { @@ -18934,9 +19278,27 @@ bool Plater::load_files(const wxArrayString& filenames) return res; }; + const auto first_3mf = std::find_if(normal_paths.begin(), normal_paths.end(), [](const fs::path& path) { + return boost::algorithm::iends_with(path.string(), ".3mf"); + }); + LoadType first_3mf_action = LoadType::Unknown; + if (first_3mf != normal_paths.end()) { + first_3mf_action = choose_3mf_load_type(*this, *first_3mf); + if (first_3mf_action == LoadType::Unknown) + return false; + const bool contains_zip = std::any_of(normal_paths.begin(), normal_paths.end(), [](const fs::path& path) { + return boost::algorithm::iends_with(path.string(), ".zip"); + }); + if (first_3mf_action == LoadType::LoadGeometry && !contains_zip) { + // Do not split a geometry operation into several imports: Cancel applies to the entire set. + Plater::TakeSnapshot snapshot(this, snapshot_label); + return !load_files(normal_paths, LoadStrategy::LoadModel, false).empty(); + } + } + switch (loadfiles_type) { case LoadFilesType::Single3MF: - open_3mf_file(normal_paths[0]); + res = open_3mf_file(normal_paths[0], first_3mf_action); break; case LoadFilesType::SingleOther: { @@ -18951,7 +19313,7 @@ bool Plater::load_files(const wxArrayString& filenames) if (i > 0) { other_file.push_back(normal_paths[i]); } }; - open_3mf_file(first_file[0]); + if (!open_3mf_file(first_file[0], first_3mf_action)) return false; if (load_files(other_file, LoadStrategy::LoadModel).empty()) { res = false; } break; @@ -18976,7 +19338,7 @@ bool Plater::load_files(const wxArrayString& filenames) } } - open_3mf_file(first_file[0]); + if (!open_3mf_file(first_file[0], first_3mf_action)) return false; if (load_files(tmf_file, LoadStrategy::LoadModel).empty()) { res = false; } if (res && handle_zips(other_file)) { if (normal_paths.empty()) return true; @@ -19021,39 +19383,30 @@ LoadType determine_load_type(std::string filename, std::string override_setting) bool Plater::open_3mf_file(const fs::path &file_path) { - std::string filename = encode_path(file_path.filename().string().c_str()); - if (!boost::algorithm::iends_with(filename, ".3mf")) { + if (!boost::algorithm::iends_with(file_path.string(), ".3mf")) return false; - } - - bool not_empty_plate = !model().objects.empty(); - bool load_setting_ask_when_relevant = wxGetApp().app_config->get(SETTING_PROJECT_LOAD_BEHAVIOUR) == OPTION_PROJECT_LOAD_BEHAVIOUR_ASK_WHEN_RELEVANT; - LoadType load_type = determine_load_type(filename, (not_empty_plate && load_setting_ask_when_relevant) ? OPTION_PROJECT_LOAD_BEHAVIOUR_ALWAYS_ASK : ""); - - if (load_type == LoadType::Unknown) return false; + return open_3mf_file(file_path, choose_3mf_load_type(*this, file_path)); +} +bool Plater::open_3mf_file(const fs::path &file_path, LoadType load_type) +{ switch (load_type) { - case LoadType::OpenProject: { - if (wxGetApp().can_load_project()) - load_project(from_path(file_path), ""); - break; - } + case LoadType::OpenProject: + if (!wxGetApp().can_load_project()) + return false; + load_project(from_path(file_path), ""); + return true; case LoadType::LoadGeometry: { Plater::TakeSnapshot snapshot(this, "Import Object"); - load_files({file_path}, LoadStrategy::LoadModel); - break; + return !load_files({file_path}, LoadStrategy::LoadModel).empty(); } - case LoadType::LoadConfig: { + case LoadType::LoadConfig: load_files({file_path}, LoadStrategy::LoadConfig); - break; - } - case LoadType::Unknown: { - assert(false); - break; - } + return true; + case LoadType::Unknown: + return false; } - - return true; + return false; } int Plater::get_3mf_file_count(std::vector paths) @@ -19088,6 +19441,28 @@ void Plater::add_file() snapshot_label += encode_path(paths[i].filename().string().c_str()); } + const auto first_3mf = std::find_if(paths.begin(), paths.end(), [](const fs::path& path) { + return boost::algorithm::iends_with(path.string(), ".3mf"); + }); + LoadType first_3mf_action = LoadType::Unknown; + if (first_3mf != paths.end()) { + first_3mf_action = choose_3mf_load_type(*this, *first_3mf); + if (first_3mf_action == LoadType::Unknown) + return; + if (first_3mf_action == LoadType::LoadGeometry) { + Plater::TakeSnapshot snapshot(this, snapshot_label); + if (!load_files(paths, LoadStrategy::LoadModel, false).empty()) { + if (get_project_name() == _L("Untitled")) + p->set_project_name(from_u8(paths.front().stem().string())); + wxGetApp().mainframe->update_title(); + if (wxGetApp().app_config->get("recent_models") == "true") + for (const fs::path& file : paths) + wxGetApp().mainframe->add_to_recent_projects(file.wstring()); + } + return; + } + } + // BBS: check file types auto loadfiles_type = LoadFilesType::NoFile; auto amf_files_count = get_3mf_file_count(paths); @@ -19105,7 +19480,7 @@ void Plater::add_file() switch (loadfiles_type) { case LoadFilesType::Single3MF: - open_3mf_file(paths[0]); + open_3mf_file(paths[0], first_3mf_action); break; case LoadFilesType::SingleOther: { @@ -19127,7 +19502,7 @@ void Plater::add_file() if (i > 0) { other_file.push_back(paths[i]); } }; - open_3mf_file(first_file[0]); + if (!open_3mf_file(first_file[0], first_3mf_action)) return; if (!load_files(other_file, LoadStrategy::LoadModel).empty()) { wxGetApp().mainframe->update_title(); } break; @@ -19157,7 +19532,7 @@ void Plater::add_file() } } - open_3mf_file(first_file[0]); + if (!open_3mf_file(first_file[0], first_3mf_action)) return; load_files(tmf_file, LoadStrategy::LoadModel); if (!load_files(other_file, LoadStrategy::LoadModel, false).empty()) { wxGetApp().mainframe->update_title(); @@ -19277,11 +19652,18 @@ void Plater::reset_with_confirm() } // BBS: save logic -int GUI::Plater::close_with_confirm(std::function second_check) +int GUI::Plater::close_with_confirm(std::function second_check, std::function* deferred_close) { + // A caller that may still keep the current project runs these steps itself once it is replaced. + auto close = [deferred_close](std::function steps) { + if (deferred_close != nullptr) + *deferred_close = std::move(steps); + else + steps(); + }; if (up_to_date(false, false)) { if (second_check && !second_check(false)) return wxID_CANCEL; - model().set_backup_path(""); + close([this]() { model().set_backup_path(""); }); return wxID_NO; } @@ -19306,9 +19688,11 @@ int GUI::Plater::close_with_confirm(std::function second_check) if (second_check && !second_check(result == wxID_YES)) return wxID_CANCEL; - model().set_backup_path(""); - up_to_date(true, false); - up_to_date(true, true); + close([this]() { + model().set_backup_path(""); + up_to_date(true, false); + up_to_date(true, true); + }); return result; } @@ -21672,6 +22056,8 @@ void Plater::on_config_change(const DynamicPrintConfig &config) bool bed_shape_changed = false; bool exclusion_preview_changed = false; bool imex_changed = false; + bool filament_colour_changed = false; + bool filament_list_changed = false; //bool print_sequence_changed = false; t_config_option_keys diff_keys = p->config->diff(config); @@ -21684,20 +22070,15 @@ void Plater::on_config_change(const DynamicPrintConfig &config) } for (auto opt_key : diff_keys) { + // The filament lists are refreshed once after the loop, as these keys usually change together. if (opt_key == "filament_colour") { update_scheduled = true; // update should be scheduled (for update 3DScene) #2738 - - if (update_filament_colors_in_full_config()) { - p->sidebar->update_mixed_filament_list(); - p->partplate_list.invalidate_exclusion_volume_previews(); - p->sidebar->obj_list()->update_filament_colors(); - p->sidebar->update_dynamic_filament_list(); - continue; - } + filament_colour_changed = true; + exclusion_preview_changed = true; + continue; } if (opt_key == "filament_type") { - update_filament_colors_in_full_config(); - p->sidebar->update_mixed_filament_list(); + filament_list_changed = true; continue; } // The mixed-filament type check folds filament_is_support into the component type @@ -21705,7 +22086,7 @@ void Plater::on_config_change(const DynamicPrintConfig &config) // refresh the list even though filament_type itself did not change. if (opt_key == "filament_is_support") { p->config->set_key_value(opt_key, config.option(opt_key)->clone()); - p->sidebar->update_mixed_filament_list(); + filament_list_changed = true; continue; } if (opt_key == "material_colour") { @@ -21797,6 +22178,15 @@ void Plater::on_config_change(const DynamicPrintConfig &config) p->view3D->get_canvas3d()->set_as_dirty(); } + if (filament_colour_changed || filament_list_changed) { + update_filament_colors_in_full_config(); + p->sidebar->update_mixed_filament_list(); + if (filament_colour_changed) { + p->sidebar->obj_list()->update_filament_colors(); + p->sidebar->update_dynamic_filament_list(); + } + } + if (bed_shape_changed) { set_bed_shape(); get_current_canvas3D()->requires_check_outside_state(); @@ -22264,24 +22654,30 @@ GLCanvas3D* Plater::get_assmeble_canvas3D() UVEditorCanvas* Plater::get_uv_editor_canvas() { - return p->uv_editor_canvas; + UVEditorPanel* panel = p->uv_editor.get(); + return panel != nullptr ? panel->canvas() : nullptr; } void Plater::show_uv_editor(bool show) { - if (p->uv_editor_panel == nullptr) - return; - const wxAuiPaneInfo &pane = p->m_aui_mgr.GetPane(p->uv_editor_panel); - if (!pane.IsOk() || pane.IsShown() == show) - return; + if (!p->uv_editor.built()) { + // Built below on the first show; nothing to hide before that. + if (!show) + return; + } else { + const wxAuiPaneInfo &pane = p->m_aui_mgr.GetPane(p->uv_editor.get()); + if (!pane.IsOk() || pane.IsShown() == show) + return; + } // Deferred, because GLGizmoTextureDisplacement calls this from its ImGui panel - that is, from // the middle of the 3D canvas's GL frame. Showing an AUI pane re-lays out the window and // delivers the resulting size/paint events synchronously, and the UV canvas painting itself // makes its own surface current in the app's *shared* GL context, which mid-frame is the one // the 3D canvas is drawing into. Doing the layout once the frame is over avoids that entirely. + // Building the pane creates a wxGLCanvas, so it waits here too. CallAfter([this, show]() { - wxAuiPaneInfo &deferred_pane = p->m_aui_mgr.GetPane(p->uv_editor_panel); + wxAuiPaneInfo &deferred_pane = p->m_aui_mgr.GetPane(p->uv_editor.ensure()); if (!deferred_pane.IsOk() || deferred_pane.IsShown() == show) return; deferred_pane.Show(show); diff --git a/src/slic3r/GUI/Plater.hpp b/src/slic3r/GUI/Plater.hpp index 7f2ecc5205..e230d948bc 100644 --- a/src/slic3r/GUI/Plater.hpp +++ b/src/slic3r/GUI/Plater.hpp @@ -98,6 +98,7 @@ namespace UndoRedo { } namespace GUI { +enum class LoadType : unsigned char; class SyncAmsInfoDialog; class MainFrame; class ConfigOptionsGroup; @@ -196,7 +197,7 @@ public: void create_printer_preset(); void init_filament_combo(PlaterPresetComboBox **combo, const int filament_idx); void remove_unused_filament_combos(const size_t current_extruder_count); - void update_all_preset_comboboxes(); + void update_all_preset_comboboxes(bool update_filament_combos = true); //void update_partplate(PartPlateList& list); void update_presets(Slic3r::Preset::Type preset_type); //BBS @@ -393,6 +394,8 @@ public: bool up_to_date(bool saved, bool backup); bool open_3mf_file(const boost::filesystem::path &file_path); + // Batch import resolves the project/geometry question once before staging the whole set. + bool open_3mf_file(const boost::filesystem::path &file_path, LoadType resolved_type); int get_3mf_file_count(std::vector paths); void add_file(); // Returns false when no object was added (e.g. the user cancelled the load dialog). @@ -460,7 +463,8 @@ public: bool preview_zip_archive(const boost::filesystem::path& archive_path); // BBS: restore - std::vector load_files(const std::vector& input_files, LoadStrategy strategy = LoadStrategy::LoadModel | LoadStrategy::LoadConfig, bool ask_multi = false, bool* published_out = nullptr); + std::vector load_files(const std::vector& input_files, LoadStrategy strategy = LoadStrategy::LoadModel | LoadStrategy::LoadConfig, bool ask_multi = false, bool* published_out = nullptr, + const std::function& before_publish = nullptr); // to be called on drag and drop bool load_files(const wxArrayString& filenames); @@ -556,7 +560,8 @@ public: void reset(bool apply_presets_change = false, bool reload_presets = true); void reset_with_confirm(); //BBS: return int for various result - int close_with_confirm(std::function second_check = nullptr); // BBS close project + // With deferred_close, the steps that mark the current project closed are returned instead of run. + int close_with_confirm(std::function second_check = nullptr, std::function* deferred_close = nullptr); // BBS close project //BBS: trigger a restore project event void trigger_restore_project(int skip_confirm = 0); bool delete_object_from_model(size_t obj_idx, bool refresh_immediately = true); // BBS support refresh immediately diff --git a/src/slic3r/GUI/Preferences.cpp b/src/slic3r/GUI/Preferences.cpp index d9bbac1bff..dcdbcf7ef1 100644 --- a/src/slic3r/GUI/Preferences.cpp +++ b/src/slic3r/GUI/Preferences.cpp @@ -2086,108 +2086,12 @@ void PreferencesDialog::create_items() //auto item_hints = create_item_checkbox(_L("Show \"Daily Tips\" after start"), page, _L("If enabled, useful hints are displayed at startup."), "show_daily_tips"); //g_sizer->Add(item_hints); - auto item_downloads = create_item_downloads(_L("Downloads folder"), _L("Target folder for downloaded items")); - g_sizer->Add(item_downloads); - - //// GENERAL > Project - g_sizer->Add(create_item_title(_L("Project")), 1, wxEXPAND); - - std::vector projectLoadSettingsBehaviourOptions = {_L("Load All"), _L("Ask When Relevant"), _L("Always Ask"), _L("Load Geometry Only")}; - std::vector projectLoadSettingsConfigOptions = { OPTION_PROJECT_LOAD_BEHAVIOUR_LOAD_ALL, OPTION_PROJECT_LOAD_BEHAVIOUR_ASK_WHEN_RELEVANT, OPTION_PROJECT_LOAD_BEHAVIOUR_ALWAYS_ASK, OPTION_PROJECT_LOAD_BEHAVIOUR_LOAD_GEOMETRY }; - auto item_project_load = create_item_combobox(_L("Load behavior"), _L("Should printer/filament/process settings be loaded when opening a 3MF file?"), SETTING_PROJECT_LOAD_BEHAVIOUR, projectLoadSettingsBehaviourOptions, projectLoadSettingsConfigOptions); - g_sizer->Add(item_project_load); - - auto item_backup = create_item_backup(_L("Auto backup"), _L("Backup your project periodically to help with restoring from an occasional crash.")); - g_sizer->Add(item_backup); - - auto item_max_recent_count = create_item_input(_L("Maximum recent files"), "", _L("Maximum count of recent files"), "max_recent_count", [](wxString value) { - long max = 0; - if (value.ToLong(&max)) - wxGetApp().mainframe->set_max_recent_count(max); - }); - g_sizer->Add(item_max_recent_count); - - auto item_recent_models = create_item_checkbox(_L("Add STL/STEP files to recent files list"), "", "recent_models"); - g_sizer->Add(item_recent_models); - - auto item_gcodes_warning = create_item_checkbox(_L("Don't warn when loading 3MF with modified G-code"), "", "no_warn_when_modified_gcodes"); - g_sizer->Add(item_gcodes_warning); - - auto item_step_dialog = create_item_checkbox( - _L("Show options when importing STEP file"), _L("If enabled, a parameter settings dialog will appear during STEP file import."), - "enable_step_mesh_setting", wxEmptyString, "import_export#dont-show-again" - ); - g_sizer->Add(item_step_dialog); - - auto item_step_linear = create_item_decimal_input(_L("STEP importing: linear deflection"), "mm", _L("Linear deflection used when meshing imported STEP files.\nSmaller values produce higher-quality meshes but increase processing time.\nUsed as the default in the import dialog, or directly when the import dialog is disabled.\nDefault: 0.003 mm."), "linear_deflection", 0.001, 0.1, 3); - g_sizer->Add(item_step_linear); - - auto item_step_angle = create_item_decimal_input(_L("STEP importing: angle deflection"), "", _L("Angle deflection used when meshing imported STEP files.\nSmaller values produce higher-quality meshes but increase processing time.\nUsed as the default in the import dialog, or directly when the import dialog is disabled.\nDefault: 0.5."), "angle_deflection", 0.01, 1.0, 2); - g_sizer->Add(item_step_angle); - - auto item_step_split = create_item_checkbox(_L("STEP importing: Split into multiple objects"), _L("If enabled, compound and compsolid shapes in imported STEP files are split into multiple objects.\nUsed as the default in the import dialog, or directly when the import dialog is disabled.\nDefault: disabled."), "is_split_compound"); - g_sizer->Add(item_step_split); - - auto item_draco_bits = create_item_spinctrl(_L("Quality level for Draco export"), "", - _L("bits"), - _L("Controls the quantization bit depth used when compressing the mesh to Draco format.\n" - "0 = lossless compression (geometry is preserved at full precision). Valid lossy values range from 8 to 30.\n" - "Lower values produce smaller files but lose more geometric detail; higher values preserve more detail at the cost of larger files."), - "drc_bits", DRC_BITS_MIN, DRC_BITS_MAX, nullptr, "import_export#drc" - ); - g_sizer->Add(item_draco_bits); - - auto item_full_source_paths = create_item_checkbox(_L("Store full source file paths in projects"), - _L("If enabled, saved projects store the absolute path to imported source files (STEP/STL/...), so " - "\"Reload from disk\" still works when the source file is kept in a different folder than the project. " - "If disabled, only the filename is stored, which keeps projects portable and avoids embedding absolute paths."), - "export_sources_full_pathnames"); - g_sizer->Add(item_full_source_paths); - - //// GENERAL > Preset - g_sizer->Add(create_item_title(_L("Preset")), 1, wxEXPAND); - - auto item_remember_printer = create_item_checkbox(_L("Remember printer configuration"), _L("If enabled, Orca will remember and switch filament/process configuration for each printer automatically."), "remember_printer_config"); - g_sizer->Add(item_remember_printer); - - auto item_filament_preset_grouping = create_item_combobox(_L("Group user filament presets"), _L("Group user filament presets based on selection"), - "group_filament_presets", {_L("All"), _L("None"), _L("By type"), _L("By vendor")}, [](wxString value) {wxGetApp().plater()->sidebar().update_presets(Preset::TYPE_FILAMENT);}); - g_sizer->Add(item_filament_preset_grouping); - - // prevent burst calling on keyboard / spin events - m_filament_height_timer.Bind(wxEVT_TIMER, [this](wxTimerEvent&) { - wxGetApp().plater()->sidebar().update_filaments_area_height(); - UpdateSidebarLayout(); - }); - auto item_filament_area_height = create_item_spinctrl(_L("Optimize filaments area height for..."), "", _L("filaments"), _L("Optimizes filament area maximum height by chosen filament count."), - "filaments_area_preferred_count", 8, 99, [this](int value) {m_filament_height_timer.StartOnce(500);}); - g_sizer->Add(item_filament_area_height); - - auto item_shared_profiles = create_item_checkbox(_L("Show shared profiles notification"), _L("Show a notification with a link to browse shared profiles when the selected printer is changed."), "show_shared_profiles_notification"); - g_sizer->Add(item_shared_profiles); - //// GENERAL > Features g_sizer->Add(create_item_title(_L("Features")), 1, wxEXPAND); auto item_multi_machine = create_item_checkbox(_L("Multi device management"), _L("With this option enabled, you can send a task to multiple devices at the same time and manage multiple devices."), "enable_multi_machine", _L("(Requires restart)")); g_sizer->Add(item_multi_machine); - auto item_speed_dial = create_item_checkbox(_L("Open the Speed Dial from the keyboard"), - _L("When enabled, the Speed Dial keyboard shortcut (Space by default) opens the action search from any page."), - "enable_speed_dial"); - g_sizer->Add(item_speed_dial); - - auto item_speed_dial_recents = create_item_spinctrl( - _L("Recent actions"), - "", - // TRN Unit shown after the number of recent actions, as in "5 actions". - _L("actions"), - _L("How many recently launched actions to show at the top of the Speed Dial. Set to 0 to hide recent actions."), - SETTING_SPEED_DIAL_RECENT_COUNT, - SPEED_DIAL_RECENT_COUNT_MIN, - SPEED_DIAL_RECENT_COUNT_MAX); - g_sizer->Add(item_speed_dial_recents); - #ifdef SLIC3R_CAD auto item_cad_feature = create_item_checkbox(_L("CAD feature (experimental)"), _L("With this option enabled, the Design tab is shown, where models can be built and edited " @@ -2256,7 +2160,277 @@ void PreferencesDialog::create_items() g_sizer->Add(item_pop_up_filament_map_dialog); #endif - //// GENERAL > Plugins + + //// GENERAL > Clear my choice on ... + g_sizer->Add(create_item_title(_L("Clear my choice on...")), 1, wxEXPAND); + + auto item_save_choise = create_item_button(_L("Unsaved projects"), _L("Clear"), "", _L("Clear my choice on the unsaved projects."), []() { + wxGetApp().app_config->set("save_project_choise", ""); + }); + g_sizer->Add(item_save_choise); + + auto item_save_presets = create_item_button(_L("Unsaved presets"), _L("Clear"), "", _L("Clear my choice on the unsaved presets."), []() { + wxGetApp().app_config->set("save_preset_choise", ""); + }); + g_sizer->Add(item_save_presets); + + auto item_restore_hide_pop_ups = create_item_button(_L("Synchronizing printer preset"), _L("Clear"), L"", _L("Clear my choice for synchronizing printer preset after loading the file."), []() { + wxGetApp().app_config->erase("app", "sync_after_load_file_show_flag"); + }); + g_sizer->Add(item_restore_hide_pop_ups); + + g_sizer->AddSpacer(FromDIP(10)); + sizer_page->Add(g_sizer, 0, wxEXPAND); + + ////////////////////////// + //// FILES TAB + ///////////////////////////////////// + m_tab_index[PreferencesTab::Files] = m_pref_tabs->AppendItem(_L("Files")); + f_sizers.push_back(new wxFlexGridSizer(1, 1, v_gap, 0)); + g_sizer = f_sizers.back(); + g_sizer->AddGrowableCol(0, 1); + + //// FILES > Project + g_sizer->Add(create_item_title(_L("Project")), 1, wxEXPAND); + std::vector projectLoadSettingsBehaviourOptions = {_L("Load All"), _L("Ask When Relevant"), _L("Always Ask"), _L("Load Geometry Only")}; + std::vector projectLoadSettingsConfigOptions = { OPTION_PROJECT_LOAD_BEHAVIOUR_LOAD_ALL, OPTION_PROJECT_LOAD_BEHAVIOUR_ASK_WHEN_RELEVANT, OPTION_PROJECT_LOAD_BEHAVIOUR_ALWAYS_ASK, OPTION_PROJECT_LOAD_BEHAVIOUR_LOAD_GEOMETRY }; + auto item_project_load = create_item_combobox(_L("Load behavior"), _L("Should printer/filament/process settings be loaded when opening a 3MF file?"), SETTING_PROJECT_LOAD_BEHAVIOUR, projectLoadSettingsBehaviourOptions, projectLoadSettingsConfigOptions); + g_sizer->Add(item_project_load); + + auto item_backup = create_item_backup(_L("Auto backup"), _L("Backup your project periodically to help with restoring from an occasional crash.")); + g_sizer->Add(item_backup); + + auto item_full_source_paths = create_item_checkbox(_L("Store full source file paths in projects"), + _L("If enabled, saved projects store the absolute path to imported source files (STEP/STL/...), so " + "\"Reload from disk\" still works when the source file is kept in a different folder than the project. " + "If disabled, only the filename is stored, which keeps projects portable and avoids embedding absolute paths."), + "export_sources_full_pathnames"); + g_sizer->Add(item_full_source_paths); + + //// FILES > Recent files + g_sizer->Add(create_item_title(_L("Recent files")), 1, wxEXPAND); + auto item_max_recent_count = create_item_input(_L("Maximum recent files"), "", _L("Maximum count of recent files"), "max_recent_count", [](wxString value) { + long max = 0; + if (value.ToLong(&max)) + wxGetApp().mainframe->set_max_recent_count(max); + }); + g_sizer->Add(item_max_recent_count); + + auto item_recent_models = create_item_checkbox(_L("Add STL/STEP files to recent files list"), "", "recent_models"); + g_sizer->Add(item_recent_models); + + //// FILES > Folder paths + g_sizer->Add(create_item_title(_L("Folder paths")), 1, wxEXPAND); + auto item_downloads = create_item_downloads(_L("Downloads folder"), _L("Target folder for downloaded items")); + g_sizer->Add(item_downloads); + + //// FILES > File import + g_sizer->Add(create_item_title(_L("File import")), 1, wxEXPAND); + g_sizer->Add(create_item_checkbox(_L("Ask how to handle unsupported characters in imported names"), + _L("Show the removal or replacement choices when original names contain unsupported characters."), + "import_names_cleanup_show_dialog")); + + //// FILES > 3MF import + g_sizer->Add(create_item_title(_L("3MF import")), 1, wxEXPAND); + g_sizer->Add(create_item_checkbox(_L("Show options when importing"), + _L("Show original-name and sorting options when importing a 3MF without project settings into the current project."), + "import_names_3mf_show_dialog")); + g_sizer->Add(create_item_checkbox(_L("Keep original names"), + _L("Use the body names stored in the imported file when it contains them."), "import_names_3mf_keep")); + auto item_gcodes_warning = create_item_checkbox(_L("Don't warn when loading 3MF with modified G-code"), "", "no_warn_when_modified_gcodes"); + g_sizer->Add(item_gcodes_warning); + + //// FILES > STEP import + g_sizer->Add(create_item_title(_L("STEP import")), 1, wxEXPAND); + auto item_step_dialog = create_item_checkbox( + _L("Show options when importing"), _L("If enabled, a parameter settings dialog will appear during STEP file import."), + "enable_step_mesh_setting", wxEmptyString, "import_export#dont-show-again" + ); + g_sizer->Add(item_step_dialog); + + auto item_step_linear = create_item_decimal_input(_L("Linear deflection"), "mm", _L("Linear deflection used when meshing imported STEP files.\nSmaller values produce higher-quality meshes but increase processing time.\nUsed as the default in the import dialog, or directly when the import dialog is disabled.\nDefault: 0.003 mm."), "linear_deflection", 0.001, 0.1, 3); + g_sizer->Add(item_step_linear); + + auto item_step_angle = create_item_decimal_input(_L("Angle deflection"), "", _L("Angle deflection used when meshing imported STEP files.\nSmaller values produce higher-quality meshes but increase processing time.\nUsed as the default in the import dialog, or directly when the import dialog is disabled.\nDefault: 0.5."), "angle_deflection", 0.01, 1.0, 2); + g_sizer->Add(item_step_angle); + + auto item_step_split = create_item_checkbox(_L("Split into multiple objects"), _L("If enabled, compound and compsolid shapes in imported STEP files are split into multiple objects.\nUsed as the default in the import dialog, or directly when the import dialog is disabled.\nDefault: enabled."), "is_split_compound"); + g_sizer->Add(item_step_split); + + g_sizer->Add(create_item_checkbox(_L("Keep original names"), + _L("Use the body names stored in the imported file when it contains them."), "import_names_step_keep")); + + //// FILES > AMF import + g_sizer->Add(create_item_title(_L("AMF import")), 1, wxEXPAND); + g_sizer->Add(create_item_checkbox(_L("Show options when importing"), + _L("Show body grouping, original-name and sorting options when importing geometry into the current project."), + "import_names_amf_show_dialog")); + g_sizer->Add(create_item_checkbox(_L("Keep original names"), + _L("Use the body names stored in the imported file when it contains them."), "import_names_amf_keep")); + + //// FILES > DRC export + g_sizer->Add(create_item_title(_L("DRC export")), 1, wxEXPAND); + auto item_draco_bits = create_item_spinctrl(_L("Quality level for Draco export"), "", + _L("bits"), + _L("Controls the quantization bit depth used when compressing the mesh to Draco format.\n" + "0 = lossless compression (geometry is preserved at full precision). Valid lossy values range from 8 to 30.\n" + "Lower values produce smaller files but lose more geometric detail; higher values preserve more detail at the cost of larger files."), + "drc_bits", DRC_BITS_MIN, DRC_BITS_MAX, nullptr, "import_export#drc" + ); + g_sizer->Add(item_draco_bits); + +#ifdef _WIN32 + // MSIX: associations are declared in the package manifest and defaults are + // managed by Windows Settings; the runtime registry toggles below cannot work. + // Show a minimal page that sends the user to Windows' Default Apps settings instead. + if (is_running_in_msix()) { + g_sizer->Add(create_item_title(_L("Associate files to OrcaSlicer")), 1, wxEXPAND); + + auto item_open_default_apps = create_item_button( + _L("File associations for the Microsoft Store version are managed by Windows Settings."), + _L("Open Windows Default Apps Settings"), "", "", + []() { wxLaunchDefaultBrowser("ms-settings:defaultapps"); }); + g_sizer->Add(item_open_default_apps); + } else { + //// FILES > Extensions + g_sizer->Add(create_item_title(_L("Associate files to OrcaSlicer")), 1, wxEXPAND); + + auto item_associate_3mf = create_item_checkbox(_L("Associate 3MF files to OrcaSlicer"), _L("If enabled, this sets OrcaSlicer as the default application to open 3MF files.") , "associate_3mf"); + g_sizer->Add(item_associate_3mf); + + auto item_associate_drc = create_item_checkbox(_L("Associate DRC files to OrcaSlicer"), _L("If enabled, sets OrcaSlicer as default application to open DRC files."), "associate_drc"); + g_sizer->Add(item_associate_drc); + + auto item_associate_stl = create_item_checkbox(_L("Associate STL files to OrcaSlicer"), _L("If enabled, this sets OrcaSlicer as the default application to open STL files.") , "associate_stl"); + g_sizer->Add(item_associate_stl); + + auto item_associate_step = create_item_checkbox(_L("Associate STEP files to OrcaSlicer"), _L("If enabled, this sets OrcaSlicer as the default application to open STEP files."), "associate_step"); + g_sizer->Add(item_associate_step); + + //// FILES > WebLinks + g_sizer->Add(create_item_title(_L("Associate web links to OrcaSlicer")), 1, wxEXPAND); + + auto associate_url_prusa = create_item_link_association(L"prusaslicer", "Printables.com"); + g_sizer->Add(associate_url_prusa); + + auto associate_url_bambu = create_item_link_association(L"bambustudio", "Makerworld.com"); + g_sizer->Add(associate_url_bambu); + + auto associate_url_cura = create_item_link_association(L"cura", "Thingiverse.com"); + g_sizer->Add(associate_url_cura); + } +#endif // _WIN32 + + g_sizer->AddSpacer(FromDIP(10)); + sizer_page->Add(g_sizer, 0, wxEXPAND); + + ////////////////////////// + //// BEHAVIOUR TAB + ///////////////////////////////////// + m_tab_index[PreferencesTab::Behaviour] = m_pref_tabs->AppendItem(_L("Behaviour")); + f_sizers.push_back(new wxFlexGridSizer(1, 1, v_gap, 0)); + g_sizer = f_sizers.back(); + g_sizer->AddGrowableCol(0, 1); + + //// BEHAVIOUR > Prepare + g_sizer->Add(create_item_title(_L("Prepare")), 1, wxEXPAND); + + std::vector FlushOptionLabels = {_L("All"),_L("Color"),_L("None")}; + std::vector FlushOptionValues = { "all","color change","disabled" }; + auto item_auto_flush = create_item_combobox(_L("Auto flush after changing..."), _L("Auto calculate flushing volumes when selected values changed"), "auto_calculate_flush", FlushOptionLabels, FlushOptionValues); + g_sizer->Add(item_auto_flush); + + auto item_auto_arrange = create_item_checkbox(_L("Auto arrange plate after cloning"), "", "auto_arrange"); + g_sizer->Add(item_auto_arrange); + + auto item_auto_reslice = create_item_auto_reslice( + _L("Auto slice after changes"), + _L("If enabled, OrcaSlicer will re-slice automatically whenever slicing-related settings change."), + _L("Delay in seconds before auto slicing starts, allowing multiple edits to be grouped. Use 0 to slice immediately.")); + g_sizer->Add(item_auto_reslice); + + auto item_primitive_dialog = create_item_checkbox(_L("Show options when adding a primitive"), + _L("If enabled, a dialog asks for the dimensions of a primitive shape before it is added."), "enable_primitive_size_dialog"); + g_sizer->Add(item_primitive_dialog); + + auto item_mix_print_high_low_temperature = create_item_checkbox(_L("Remove mixed temperature restriction"), _L("With this option enabled, you can print materials with a large temperature difference together."), "enable_high_low_temp_mixed_printing"); + g_sizer->Add(item_mix_print_high_low_temperature); + + auto item_remember_print_action = create_item_checkbox(_L("Remember last print action"), _L("If enabled, OrcaSlicer will remember the last selected option in the print button's dropdown (e.g. Print, Export plate sliced file, Export G-code file) and use it as the default on next startup."), "remember_print_action"); + g_sizer->Add(item_remember_print_action); + + //// BEHAVIOUR > Preview + g_sizer->Add(create_item_title(_L("Preview")), 1, wxEXPAND); + + // ORCA: view type the preview opens with + std::vector PreviewViewTypeLabels; + std::vector PreviewViewTypeValues; + for (const auto& [value, label] : GCodeViewer::default_view_type_choices()) { + PreviewViewTypeValues.push_back(value); + PreviewViewTypeLabels.push_back(from_u8(label)); + } + auto item_preview_view_type = create_item_combobox( + _L("Default view type"), + _L("The color scheme the sliced preview opens with.\n" + "Automatic: Filament for multi material prints, Line Type for single material ones.\n" + "Last used: the view type you selected last.\n" + "Any other value always opens that view type.\n" + "You can still switch the view type in the preview afterwards."), + "preview_default_view_type", PreviewViewTypeLabels, PreviewViewTypeValues); + g_sizer->Add(item_preview_view_type); + + auto item_dim_previous_layers = create_item_checkbox( + _L("Dim lower layers"), + _L("When scrubbing the layer slider in the sliced preview, render the layers below the current one darkened so that only the layer being viewed is shown at full brightness."), + "preview_dim_previous_layers" + ); + g_sizer->Add(item_dim_previous_layers); + + auto item_dim_previous_layers_brightness = create_item_spinctrl( + _L("Dimmed layer brightness"), + "", + _L("%"), + _L("How brightly the dimmed layers are rendered when \"Dim lower layers\" is enabled.\n" + "99% is barely darkened, 0% renders them black. Capped at 99% because 100% would be the same as disabling the option."), + "preview_dim_previous_layers_brightness", + 0, + 99, + // ORCA: apply the new brightness immediately to the currently loaded preview + [](int value) { + if (Plater* plater = wxGetApp().plater()) { + if (GLCanvas3D* canvas = plater->get_preview_canvas3D()) { + canvas->get_gcode_viewer().set_dim_previous_layers_brightness(0.01f * value); + canvas->set_as_dirty(); + canvas->request_extra_frame(); + } + } + } + ); + g_sizer->Add(item_dim_previous_layers_brightness); + + //// BEHAVIOUR > Preset + g_sizer->Add(create_item_title(_L("Preset")), 1, wxEXPAND); + + auto item_remember_printer = create_item_checkbox(_L("Remember printer configuration"), _L("If enabled, Orca will remember and switch filament/process configuration for each printer automatically."), "remember_printer_config"); + g_sizer->Add(item_remember_printer); + + auto item_filament_preset_grouping = create_item_combobox(_L("Group user filament presets"), _L("Group user filament presets based on selection"), + "group_filament_presets", {_L("All"), _L("None"), _L("By type"), _L("By vendor")}, [](wxString value) {wxGetApp().plater()->sidebar().update_presets(Preset::TYPE_FILAMENT);}); + g_sizer->Add(item_filament_preset_grouping); + + // prevent burst calling on keyboard / spin events + m_filament_height_timer.Bind(wxEVT_TIMER, [this](wxTimerEvent&) { + wxGetApp().plater()->sidebar().update_filaments_area_height(); + UpdateSidebarLayout(); + }); + auto item_filament_area_height = create_item_spinctrl(_L("Optimize filaments area height for..."), "", _L("filaments"), _L("Optimizes filament area maximum height by chosen filament count."), + "filaments_area_preferred_count", 8, 99, [this](int value) {m_filament_height_timer.StartOnce(500);}); + g_sizer->Add(item_filament_area_height); + + auto item_shared_profiles = create_item_checkbox(_L("Show shared profiles notification"), _L("Show a notification with a link to browse shared profiles when the selected printer is changed."), "show_shared_profiles_notification"); + g_sizer->Add(item_shared_profiles); + + //// BEHAVIOUR > Plugins g_sizer->Add(create_item_title(_L("Plugins")), 1, wxEXPAND); auto item_plugin_pages_visible_count = create_item_spinctrl( @@ -2271,6 +2445,49 @@ void PreferencesDialog::create_items() ); g_sizer->Add(item_plugin_pages_visible_count); + //// BEHAVIOUR > Design +#ifdef SLIC3R_CAD + // Design-tab only, so it stays out of the way while the CAD feature is switched off. + if (wxGetApp().is_enable_cad_feature()) { + g_sizer->Add(create_item_title(_L("Design")), 1, wxEXPAND); + auto item_connector_face_glyph = create_item_checkbox(_L("Draw mate connectors as a face"), + _L("In the Design tab, draw a mate connector as a small face instead of the conventional " + "disc with a roll quadrant. A face shows its orientation at a glance, without learning the disc convention. " + "Turn this off for the conventional CAD representation."), "design_connector_face_glyph"); + g_sizer->Add(item_connector_face_glyph); + + // Saved WITH each design (it decides which loops are closed, i.e. what solid a project + // rebuilds into), so it applies to designs started from now on; an open design keeps + // the rule it was made with. + auto item_auto_close_sketch_loops = create_item_checkbox(_L("Auto-close sketch loops"), + _L("Treat sketch endpoints within 0.001 mm as one joint and weld the loop shut. " + "Off: only exactly coincident endpoints join, so a loop with a tiny gap is " + "shown as open instead of being closed for you. Saved with each design; " + "applies to designs started after the change."), + "auto_close_sketch_loops"); + g_sizer->Add(item_auto_close_sketch_loops); + } +#endif + + //// BEHAVIOUR > Speed dial + g_sizer->Add(create_item_title(_L("Speed dial")), 1, wxEXPAND); + + auto item_speed_dial = create_item_checkbox(_L("Open the Speed Dial from the keyboard"), + _L("When enabled, the Speed Dial keyboard shortcut (Space by default) opens the action search from any page."), + "enable_speed_dial"); + g_sizer->Add(item_speed_dial); + + auto item_speed_dial_recents = create_item_spinctrl( + _L("Recent actions"), + "", + // TRN Unit shown after the number of recent actions, as in "5 actions". + _L("actions"), + _L("How many recently launched actions to show at the top of the Speed Dial. Set to 0 to hide recent actions."), + SETTING_SPEED_DIAL_RECENT_COUNT, + SPEED_DIAL_RECENT_COUNT_MIN, + SPEED_DIAL_RECENT_COUNT_MAX); + g_sizer->Add(item_speed_dial_recents); + g_sizer->AddSpacer(FromDIP(10)); sizer_page->Add(g_sizer, 0, wxEXPAND); @@ -2282,36 +2499,6 @@ void PreferencesDialog::create_items() g_sizer = f_sizers.back(); g_sizer->AddGrowableCol(0, 1); - //// CONTROL > Behaviour - g_sizer->Add(create_item_title(_L("Behavior")), 1, wxEXPAND); - - std::vector FlushOptionLabels = {_L("All"),_L("Color"),_L("None")}; - std::vector FlushOptionValues = { "all","color change","disabled" }; - auto item_auto_flush = create_item_combobox(_L("Auto flush after changing..."), _L("Auto calculate flushing volumes when selected values changed"), "auto_calculate_flush", FlushOptionLabels, FlushOptionValues); - g_sizer->Add(item_auto_flush); - - auto item_auto_arrange = create_item_checkbox(_L("Auto arrange plate after cloning"), "", "auto_arrange"); - g_sizer->Add(item_auto_arrange); - - auto item_primitive_dialog = create_item_checkbox(_L("Show options when adding a primitive"), - _L("If enabled, a dialog asks for the dimensions of a primitive shape before it is added."), "enable_primitive_size_dialog"); - g_sizer->Add(item_primitive_dialog); - - //// CONTROL > Slicing - g_sizer->Add(create_item_title(_L("Slicing")), 1, wxEXPAND); - - auto item_auto_reslice = create_item_auto_reslice( - _L("Auto slice after changes"), - _L("If enabled, OrcaSlicer will re-slice automatically whenever slicing-related settings change."), - _L("Delay in seconds before auto slicing starts, allowing multiple edits to be grouped. Use 0 to slice immediately.")); - g_sizer->Add(item_auto_reslice); - - auto item_mix_print_high_low_temperature = create_item_checkbox(_L("Remove mixed temperature restriction"), _L("With this option enabled, you can print materials with a large temperature difference together."), "enable_high_low_temp_mixed_printing"); - g_sizer->Add(item_mix_print_high_low_temperature); - - auto item_remember_print_action = create_item_checkbox(_L("Remember last print action"), _L("If enabled, OrcaSlicer will remember the last selected option in the print button's dropdown (e.g. Print, Export plate sliced file, Export G-code file) and use it as the default on next startup."), "remember_print_action"); - g_sizer->Add(item_remember_print_action); - //// CONTROL > Camera g_sizer->Add(create_item_title(_L("Camera")), 1, wxEXPAND); @@ -2331,28 +2518,6 @@ void PreferencesDialog::create_items() auto reverse_mouse_zoom = create_item_checkbox(_L("Reverse mouse zoom"), _L("If enabled, reverses the direction of zoom with mouse wheel."), "reverse_mouse_wheel_zoom"); g_sizer->Add(reverse_mouse_zoom); -#ifdef SLIC3R_CAD - // Design-tab only, so it stays out of the way while the CAD feature is switched off. - if (wxGetApp().is_enable_cad_feature()) { - auto item_connector_face_glyph = create_item_checkbox(_L("Draw mate connectors as a face"), - _L("In the Design tab, draw a mate connector as a small face instead of the conventional " - "disc with a roll quadrant. A face shows its orientation at a glance, without learning the disc convention. " - "Turn this off for the conventional CAD representation."), "design_connector_face_glyph"); - g_sizer->Add(item_connector_face_glyph); - - // Saved WITH each design (it decides which loops are closed, i.e. what solid a project - // rebuilds into), so it applies to designs started from now on; an open design keeps - // the rule it was made with. - auto item_auto_close_sketch_loops = create_item_checkbox(_L("Auto-close sketch loops"), - _L("Treat sketch endpoints within 0.001 mm as one joint and weld the loop shut. " - "Off: only exactly coincident endpoints join, so a loop with a tiny gap is " - "shown as open instead of being closed for you. Saved with each design; " - "applies to designs started after the change."), - "auto_close_sketch_loops"); - g_sizer->Add(item_auto_close_sketch_loops); - } -#endif - std::vector ButtonDragActions = {_L("None"), _L("Pan"), _L("Rotate")}; auto item_left_mouse_drag = create_item_combobox(_L("Left Mouse Drag"), _L("Set the action that dragging the left mouse button should perform."), "left_mouse_drag_action", ButtonDragActions); g_sizer->Add(item_left_mouse_drag); @@ -2369,24 +2534,6 @@ void PreferencesDialog::create_items() }); g_sizer->Add(item_shortcuts); - //// CONTROL > Clear my choice on ... - g_sizer->Add(create_item_title(_L("Clear my choice on...")), 1, wxEXPAND); - - auto item_save_choise = create_item_button(_L("Unsaved projects"), _L("Clear"), "", _L("Clear my choice on the unsaved projects."), []() { - wxGetApp().app_config->set("save_project_choise", ""); - }); - g_sizer->Add(item_save_choise); - - auto item_save_presets = create_item_button(_L("Unsaved presets"), _L("Clear"), "", _L("Clear my choice on the unsaved presets."), []() { - wxGetApp().app_config->set("save_preset_choise", ""); - }); - g_sizer->Add(item_save_presets); - - auto item_restore_hide_pop_ups = create_item_button(_L("Synchronizing printer preset"), _L("Clear"), L"", _L("Clear my choice for synchronizing printer preset after loading the file."), []() { - wxGetApp().app_config->erase("app", "sync_after_load_file_show_flag"); - }); - g_sizer->Add(item_restore_hide_pop_ups); - g_sizer->AddSpacer(FromDIP(10)); sizer_page->Add(g_sizer, 0, wxEXPAND); @@ -2409,6 +2556,13 @@ void PreferencesDialog::create_items() ); g_sizer->Add(smooth_normals); + 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); + //// GRAPHICS > Realistic view g_sizer->Add(create_item_title(_L("Realistic View")), 1, wxEXPAND); @@ -2547,62 +2701,6 @@ void PreferencesDialog::create_items() g_sizer->Add(item_benchmark); } - //// GRAPHICS > G-code Preview - g_sizer->Add(create_item_title(_L("G-code Preview")), 1, wxEXPAND); - - // ORCA: view type the preview opens with - std::vector PreviewViewTypeLabels; - std::vector PreviewViewTypeValues; - for (const auto& [value, label] : GCodeViewer::default_view_type_choices()) { - PreviewViewTypeValues.push_back(value); - PreviewViewTypeLabels.push_back(from_u8(label)); - } - auto item_preview_view_type = create_item_combobox( - _L("Default view type"), - _L("The color scheme the sliced preview opens with.\n" - "Automatic: Filament for multi material prints, Line Type for single material ones.\n" - "Last used: the view type you selected last.\n" - "Any other value always opens that view type.\n" - "You can still switch the view type in the preview afterwards."), - "preview_default_view_type", PreviewViewTypeLabels, PreviewViewTypeValues); - g_sizer->Add(item_preview_view_type); - - auto item_dim_previous_layers = create_item_checkbox( - _L("Dim lower layers"), - _L("When scrubbing the layer slider in the sliced preview, render the layers below the current one darkened so that only the layer being viewed is shown at full brightness."), - "preview_dim_previous_layers" - ); - g_sizer->Add(item_dim_previous_layers); - - auto item_dim_previous_layers_brightness = create_item_spinctrl( - _L("Dimmed layer brightness"), - "", - _L("%"), - _L("How brightly the dimmed layers are rendered when \"Dim lower layers\" is enabled.\n" - "99% is barely darkened, 0% renders them black. Capped at 99% because 100% would be the same as disabling the option."), - "preview_dim_previous_layers_brightness", - 0, - 99, - // ORCA: apply the new brightness immediately to the currently loaded preview - [](int value) { - if (Plater* plater = wxGetApp().plater()) { - if (GLCanvas3D* canvas = plater->get_preview_canvas3D()) { - canvas->get_gcode_viewer().set_dim_previous_layers_brightness(0.01f * value); - canvas->set_as_dirty(); - canvas->request_extra_frame(); - } - } - } - ); - 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); @@ -2679,67 +2777,6 @@ void PreferencesDialog::create_items() g_sizer->AddSpacer(FromDIP(10)); sizer_page->Add(g_sizer, 0, wxEXPAND); - ////////////////////////// - //// ASSOCIATE TAB - ///////////////////////////////////// -#ifdef _WIN32 - // MSIX: associations are declared in the package manifest and defaults are - // managed by Windows Settings; the runtime registry toggles below cannot work. - // Show a minimal page that sends the user to Windows' Default Apps settings instead. - if (is_running_in_msix()) { - m_pref_tabs->AppendItem(_L("Associate")); - f_sizers.push_back(new wxFlexGridSizer(1, 1, v_gap, 0)); - g_sizer = f_sizers.back(); - g_sizer->AddGrowableCol(0, 1); - - g_sizer->Add(create_item_title(_L("Associate files to OrcaSlicer")), 1, wxEXPAND); - - auto item_open_default_apps = create_item_button( - _L("File associations for the Microsoft Store version are managed by Windows Settings."), - _L("Open Windows Default Apps Settings"), "", "", - []() { wxLaunchDefaultBrowser("ms-settings:defaultapps"); }); - g_sizer->Add(item_open_default_apps); - - g_sizer->AddSpacer(FromDIP(10)); - sizer_page->Add(g_sizer, 0, wxEXPAND); - } else { - m_pref_tabs->AppendItem(_L("Associate")); - f_sizers.push_back(new wxFlexGridSizer(1, 1, v_gap, 0)); - g_sizer = f_sizers.back(); - g_sizer->AddGrowableCol(0, 1); - - //// ASSOCIATE > Extensions - g_sizer->Add(create_item_title(_L("Associate files to OrcaSlicer")), 1, wxEXPAND); - - auto item_associate_3mf = create_item_checkbox(_L("Associate 3MF files to OrcaSlicer"), _L("If enabled, this sets OrcaSlicer as the default application to open 3MF files.") , "associate_3mf"); - g_sizer->Add(item_associate_3mf); - - auto item_associate_drc = create_item_checkbox(_L("Associate DRC files to OrcaSlicer"), _L("If enabled, sets OrcaSlicer as default application to open DRC files."), "associate_drc"); - g_sizer->Add(item_associate_drc); - - auto item_associate_stl = create_item_checkbox(_L("Associate STL files to OrcaSlicer"), _L("If enabled, this sets OrcaSlicer as the default application to open STL files.") , "associate_stl"); - g_sizer->Add(item_associate_stl); - - auto item_associate_step = create_item_checkbox(_L("Associate STEP files to OrcaSlicer"), _L("If enabled, this sets OrcaSlicer as the default application to open STEP files."), "associate_step"); - g_sizer->Add(item_associate_step); - - //// ASSOCIATE > WebLinks - g_sizer->Add(create_item_title(_L("Associate web links to OrcaSlicer")), 1, wxEXPAND); - - auto associate_url_prusa = create_item_link_association(L"prusaslicer", "Printables.com"); - g_sizer->Add(associate_url_prusa); - - auto associate_url_bambu = create_item_link_association(L"bambustudio", "Makerworld.com"); - g_sizer->Add(associate_url_bambu); - - auto associate_url_cura = create_item_link_association(L"cura", "Thingiverse.com"); - g_sizer->Add(associate_url_cura); - - g_sizer->AddSpacer(FromDIP(10)); - sizer_page->Add(g_sizer, 0, wxEXPAND); - } -#endif // _WIN32 - ////////////////////////// //// DEVELOPER TAB ///////////////////////////////////// diff --git a/src/slic3r/GUI/Preferences.hpp b/src/slic3r/GUI/Preferences.hpp index 042488dbf7..9485fa4ecd 100644 --- a/src/slic3r/GUI/Preferences.hpp +++ b/src/slic3r/GUI/Preferences.hpp @@ -40,7 +40,7 @@ namespace Slic3r { namespace GUI { #define DESIGN_LEFT_MARGIN 25 // The tabs other dialogs and the Speed Dial's open_preferences open Preferences on. -enum class PreferencesTab { General, Control, Graphics, Online, Developer }; +enum class PreferencesTab { General, Files, Behaviour, Control, Graphics, Online, Developer }; class PreferencesDialog : public DPIDialog { diff --git a/src/slic3r/GUI/Search.cpp b/src/slic3r/GUI/Search.cpp index 20870b26b4..6687b036ca 100644 --- a/src/slic3r/GUI/Search.cpp +++ b/src/slic3r/GUI/Search.cpp @@ -38,6 +38,7 @@ #include #include #include +#include #include "wx/dataview.h" #include "wx/numformatter.h" @@ -76,6 +77,19 @@ bool focus_left_popup(wxWindow* popup, wxWindow* focus_window, wxWindow* related focus_window != related_window_2 && focus_window != related_window_3; } +// Close a search popup on Esc and stop the key there. Without this, Esc reaches the window holding the search, +// and a settings dialog closes while the popup keeps the input grab. Only GTK puts the search field inside the +// popup, so only there does the key pass through it; elsewhere the field stays outside and this never runs. +template void close_on_escape(wxWindow* popup, Close close) +{ + popup->Bind(wxEVT_CHAR_HOOK, [close](wxKeyEvent& e) { + if (e.GetKeyCode() == WXK_ESCAPE) + close(); + else + e.Skip(); + }); +} + } // namespace namespace Search { @@ -515,6 +529,13 @@ SearchDialog::SearchDialog(OptionsSearcher *searcher, Preset::Type type, wxWindo search_line->Bind(wxEVT_LEFT_UP, &SearchDialog::OnLeftUpInTextCtrl, this); search_line2 = search_line->GetTextCtrl(); + close_on_escape(this, [this] { + Die(); + // The focused field hides with the popup. Give the focus back to the search button once the exit event + // has shown it again, so a second Esc reaches the dialog. + CallAfter([this] { m_search_item_tag->SetFocus(); }); + }); + // scroll window m_scrolledWindow = new ScrolledWindow(m_client_panel, wxID_ANY, wxDefaultPosition, wxSize(POPUP_WIDTH * em - (em + em /2), POPUP_HEIGHT * em), wxVSCROLL, 6, 6); m_scrolledWindow->SetMarginColor(m_bg_colour); @@ -768,6 +789,7 @@ SearchObjectDialog::SearchObjectDialog(GUI::ObjectList* object_list, wxWindow* p search_line->Bind(wxEVT_TEXT, &SearchObjectDialog::OnInputText, this); search_line->Bind(wxEVT_LEFT_UP, &SearchObjectDialog::OnLeftUpInTextCtrl, this); search_line2 = search_line->GetTextCtrl(); + close_on_escape(this, [this] { Die(); }); // scroll window diff --git a/src/slic3r/GUI/StepMeshDialog.cpp b/src/slic3r/GUI/StepMeshDialog.cpp index 379c354e72..0841777a43 100644 --- a/src/slic3r/GUI/StepMeshDialog.cpp +++ b/src/slic3r/GUI/StepMeshDialog.cpp @@ -1,6 +1,7 @@ #include "StepMeshDialog.hpp" #include "libslic3r/Format/STEP.hpp" +#include "slic3r/GUI/GeometryImportDialog.hpp" #include "slic3r/GUI/GUI_Utils.hpp" #include "slic3r/GUI/Widgets/StateColor.hpp" #include "slic3r/GUI/Widgets/Label.hpp" @@ -14,6 +15,7 @@ #include #include #include +#include #include #include "GUI_App.hpp" #include "I18N.hpp" @@ -21,6 +23,7 @@ #include "Widgets/Button.hpp" #include "Widgets/TextInput.hpp" #include "Widgets/DialogButtons.hpp" +#include "Widgets/RadioGroup.hpp" #include "Widgets/RoundedRectangle.hpp" #include #include @@ -84,13 +87,14 @@ bool StepMeshDialog:: validate_number_range(const wxString& value, double min, d return (num >= min && num <= max); } -StepMeshDialog::StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double linear_init, double angle_init) +StepMeshDialog::StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double linear_init, double angle_init, + Slic3r::GUI::GeometryImportOptions* import_options) : DPIDialog(parent ? parent : static_cast(wxGetApp().mainframe), wxID_ANY, - _(L("Step file import parameters")), + _(L("STEP file import parameters")), wxDefaultPosition, wxDefaultSize, - wxDEFAULT_DIALOG_STYLE /* | wxRESIZE_BORDER*/), m_file(file) + wxDEFAULT_DIALOG_STYLE /* | wxRESIZE_BORDER*/), m_import_options(import_options), m_file(file) { m_linear_last = wxString::Format("%.3f", linear_init); m_angle_last = wxString::Format("%.2f", angle_init); @@ -255,13 +259,38 @@ StepMeshDialog::StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double line bSizer->Add(angle_sizer, 0, wxEXPAND | wxLEFT | wxRIGHT, LEFT_RIGHT_PADING); - wxBoxSizer* check_sizer = new wxBoxSizer(wxHORIZONTAL); - m_split_compound_checkbox = new wxCheckBox(this, wxID_ANY, _L("Split compound and compsolid into multiple objects"), wxDefaultPosition, wxDefaultSize, 0); - m_split_compound_checkbox->SetFont(::Label::Body_14); - m_split_compound_checkbox->SetForegroundColour(StateColor::darkModeColorFor(FONT_COLOR)); - m_split_compound_checkbox->SetValue(wxGetApp().app_config->get_bool("is_split_compound")); - check_sizer->Add(m_split_compound_checkbox, 0, wxALIGN_LEFT); - bSizer->Add(check_sizer, 0, wxEXPAND | wxLEFT | wxRIGHT | wxTOP, LEFT_RIGHT_PADING); + // App-styled check boxes, the same as in the AMF and 3MF import dialogs. + m_split_compound_checkbox = add_import_checkbox(this, *bSizer, _L("Split compound and compsolid into multiple objects"), + wxGetApp().app_config->get_bool("is_split_compound"), wxLEFT | wxRIGHT | wxTOP, LEFT_RIGHT_PADING); + if (m_import_options != nullptr) { + m_split_compound_checkbox.SetToolTip(_L("Loads each body of a multi-body part separately. Needed to keep the bodies' original names.")); + m_split_compound_checkbox.SetValue(m_import_options->split_compound); + m_load_mode = new RadioGroup(this, {_L("Load as an assembly"), _L("Load as a single object (can be split later)")}, wxVERTICAL); + m_load_mode->SetSelection(m_import_options->load_as_assembly ? 0 : 1); + m_load_mode->SetRadioTooltip(1, _L("The original bodies and names are kept inside the object. Use Split to parts to show them as separate parts.")); + bSizer->Add(m_load_mode, 0, wxLEFT | wxRIGHT | wxTOP, LEFT_RIGHT_PADING); + m_keep_names_checkbox = add_import_checkbox(this, *bSizer, _L("Keep original names"), m_import_options->keep_names, + wxLEFT | wxRIGHT | wxTOP, LEFT_RIGHT_PADING); + m_keep_names_checkbox.SetToolTip(_L("Use the body names stored in the file, when there are any. Needs Split compound for parts with several bodies.")); + m_sort_names_checkbox = add_import_checkbox(this, *bSizer, _L("Sort parts by name"), m_import_options->sort_names, + wxLEFT | wxRIGHT | wxTOP, LEFT_RIGHT_PADING); + m_sort_names_checkbox.SetToolTip(_L("Sort the parts inside each imported assembly in the object list. This does not change the order used for slicing. Available when Keep original names is on.")); + // The dialog opens with the remembered values; only the user's clicks move the linked option. + m_keep_names_checkbox.box->Bind(wxEVT_TOGGLEBUTTON, [this](wxCommandEvent& e) { + // Body names of a multi-body part exist only after splitting it. + if (m_keep_names_checkbox.GetValue()) + m_split_compound_checkbox.SetValue(true); + e.Skip(); + }); + m_split_compound_checkbox.box->Bind(wxEVT_TOGGLEBUTTON, [this](wxCommandEvent& e) { + if (!m_split_compound_checkbox.GetValue() && m_keep_names_checkbox.GetValue()) { + m_keep_names_checkbox.SetValue(false); + m_sort_names_checkbox.Enable(false); + } + e.Skip(); + }); + Slic3r::GUI::link_sort_to_keep(m_keep_names_checkbox, m_sort_names_checkbox); + } wxBoxSizer* mesh_face_number_sizer = new wxBoxSizer(wxHORIZONTAL); wxStaticText *mesh_face_number_title = new wxStaticText(this, wxID_ANY, _L("Number of triangular facets") + ": "); @@ -276,20 +305,16 @@ StepMeshDialog::StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double line bSizer->AddSpacer(FromDIP(10)); - wxBoxSizer* save_default_sizer = new wxBoxSizer(wxHORIZONTAL); - m_save_default_checkbox = new wxCheckBox(this, wxID_ANY, _L("Save these settings as default"), wxDefaultPosition, wxDefaultSize, 0); - m_save_default_checkbox->SetFont(::Label::Body_14); - m_save_default_checkbox->SetForegroundColour(StateColor::darkModeColorFor(FONT_COLOR)); - m_save_default_checkbox->SetToolTip(_L("If enabled, the values above are stored as the defaults used for future STEP imports (and shown in Preferences).")); - save_default_sizer->Add(m_save_default_checkbox, 0, wxALIGN_LEFT); - bSizer->Add(save_default_sizer, 0, wxEXPAND | wxLEFT | wxRIGHT, LEFT_RIGHT_PADING); + m_save_default_checkbox = add_import_checkbox(this, *bSizer, + m_import_options ? _L("Remember my choice") : _L("Save these settings as default"), false, wxLEFT | wxRIGHT, LEFT_RIGHT_PADING); + m_save_default_checkbox.SetToolTip(_L("If enabled, the values above are stored as the defaults used for future STEP imports (and shown in Preferences).")); bSizer->AddSpacer(FromDIP(10)); - m_checkbox = new wxCheckBox(this, wxID_ANY, _L("Don't show again"), wxDefaultPosition, wxDefaultSize, 0); - m_checkbox->SetFont(::Label::Body_14); - m_checkbox->SetForegroundColour(StateColor::darkModeColorFor(FONT_COLOR)); - bSizer->Add(m_checkbox, 0, wxLEFT, LEFT_RIGHT_PADING); + m_checkbox = add_import_checkbox(this, *bSizer, + m_import_options ? _L("Don't ask again") : _L("Don't show again"), false, wxLEFT, LEFT_RIGHT_PADING); + if (m_import_options != nullptr) + m_checkbox.SetToolTip(_L("Save these choices and apply them without asking next time. You can show this dialog again in Preferences.")); wxBoxSizer* bSizer_button = new wxBoxSizer(wxHORIZONTAL); @@ -312,13 +337,26 @@ StepMeshDialog::StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double line stop_task(); if (validate_number_range(angle_input->GetTextCtrl()->GetValue(), 0.01, 1) && validate_number_range(linear_input->GetTextCtrl()->GetValue(), 0.001, 0.1)) { - if (m_checkbox->IsChecked()) { - wxGetApp().app_config->set_bool("enable_step_mesh_setting", false); - } - if (m_save_default_checkbox->IsChecked()) { - wxGetApp().app_config->set_bool("is_split_compound", m_split_compound_checkbox->GetValue()); - wxGetApp().app_config->set("linear_deflection", float_to_string_decimal_point(get_linear_deflection(), 3)); - wxGetApp().app_config->set("angle_deflection", float_to_string_decimal_point(get_angle_deflection(), 2)); + if (m_import_options != nullptr) { + // The callback uses these values now; AppConfig is updated only after batch success. + m_import_options->keep_names = m_keep_names_checkbox.GetValue(); + m_import_options->split_compound = m_split_compound_checkbox.GetValue(); + m_import_options->sort_names = m_sort_names_checkbox.GetValue(); + m_import_options->load_as_assembly = m_load_mode->GetSelection() == 0; + m_import_options->remember = m_save_default_checkbox.GetValue(); + m_import_options->dont_ask = m_checkbox.GetValue(); + m_import_options->linear_deflection = get_linear_deflection(); + m_import_options->angle_deflection = get_angle_deflection(); + m_import_options->chosen = true; + } else { + if (m_checkbox.GetValue()) { + wxGetApp().app_config->set_bool("enable_step_mesh_setting", false); + } + if (m_save_default_checkbox.GetValue()) { + wxGetApp().app_config->set_bool("is_split_compound", m_split_compound_checkbox.GetValue()); + wxGetApp().app_config->set("linear_deflection", float_to_string_decimal_point(get_linear_deflection(), 3)); + wxGetApp().app_config->set("angle_deflection", float_to_string_decimal_point(get_angle_deflection(), 2)); + } } EndModal(wxID_OK); @@ -336,6 +374,8 @@ StepMeshDialog::StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double line this->SetSizerAndFit(bSizer); update_mesh_number_text(); this->Layout(); + // DPIDialog centres itself before the sizer sets the final size. + CenterOnParent(); this->Bind(wxEVT_LEFT_DOWN, [this](auto& e) { SetFocusIgnoringChildren(); @@ -404,4 +444,4 @@ void StepMeshDialog::update_mesh_number_text() } })); } -} \ No newline at end of file +} diff --git a/src/slic3r/GUI/StepMeshDialog.hpp b/src/slic3r/GUI/StepMeshDialog.hpp index 34673d1561..ce5b95f022 100644 --- a/src/slic3r/GUI/StepMeshDialog.hpp +++ b/src/slic3r/GUI/StepMeshDialog.hpp @@ -7,12 +7,15 @@ #include "GUI_Utils.hpp" #include "libslic3r/Format/STEP.hpp" #include "Widgets/Button.hpp" +#include "GeometryImportDialog.hpp" class Button; +class RadioGroup; class StepMeshDialog : public Slic3r::GUI::DPIDialog { public: - StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double linear_init, double angle_init); + StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double linear_init, double angle_init, + Slic3r::GUI::GeometryImportOptions* import_options = nullptr); ~StepMeshDialog() override; void on_dpi_changed(const wxRect& suggested_rect) override; inline double get_linear_deflection() { @@ -32,13 +35,19 @@ public: } } inline bool get_split_compound_value() { - return m_split_compound_checkbox->GetValue(); + return m_split_compound_checkbox.GetValue(); } private: + // A non-null context defers all preference writes until the whole import is ready. + Slic3r::GUI::GeometryImportOptions* m_import_options = nullptr; + Slic3r::GUI::ImportCheckBox m_keep_names_checkbox; + Slic3r::GUI::ImportCheckBox m_sort_names_checkbox; + // Item 0 loads as an assembly, item 1 as a single object. + RadioGroup* m_load_mode = nullptr; Slic3r::Step& m_file; - wxCheckBox* m_checkbox = nullptr; - wxCheckBox* m_split_compound_checkbox = nullptr; - wxCheckBox* m_save_default_checkbox = nullptr; + Slic3r::GUI::ImportCheckBox m_checkbox; + Slic3r::GUI::ImportCheckBox m_split_compound_checkbox; + Slic3r::GUI::ImportCheckBox m_save_default_checkbox; wxString m_linear_last; wxString m_angle_last; wxStaticText* mesh_face_number_text; @@ -52,4 +61,4 @@ private: void stop_task(); }; -#endif // _STEP_MESH_DIALOG_H_ \ No newline at end of file +#endif // _STEP_MESH_DIALOG_H_ diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index 9086ce9a48..d958dc6448 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -3699,7 +3699,8 @@ void TabPrint::update() toggle_options(); // update() could be called during undo/redo execution // Update of objectList can cause a crash in this case (because m_objects doesn't match ObjectList) - if (m_type != Preset::TYPE_MODEL && !wxGetApp().plater()->inside_snapshot_capture()) + // Before the main window is shown no object can be selected, and the refresh would only lay out the sidebar. + if (m_type != Preset::TYPE_MODEL && !wxGetApp().plater()->inside_snapshot_capture() && wxGetApp().mainframe->IsShown()) wxGetApp().obj_list()->update_and_show_object_settings_item(); wxGetApp().mainframe->on_config_changed(m_config); diff --git a/src/slic3r/Utils/IPrinterAgent.hpp b/src/slic3r/Utils/IPrinterAgent.hpp index 16d31092b9..293b0af2b8 100644 --- a/src/slic3r/Utils/IPrinterAgent.hpp +++ b/src/slic3r/Utils/IPrinterAgent.hpp @@ -32,7 +32,6 @@ struct AgentInfo { std::string name; ///< Human-readable agent name, e.g. "Orca", "Bambu Lab" std::string version; ///< Agent version string, e.g. "1.0.0" std::string description; ///< Brief description of the agent's capabilities, e.g. "Orca printer agent" - bool native_device_tab = true; ///< False when the native Device and Calibration tabs don't apply to the agent's printers }; struct PrinterConnectionParams diff --git a/src/slic3r/Utils/NetworkAgentFactory.cpp b/src/slic3r/Utils/NetworkAgentFactory.cpp index 09d01792e8..7f59dc7573 100644 --- a/src/slic3r/Utils/NetworkAgentFactory.cpp +++ b/src/slic3r/Utils/NetworkAgentFactory.cpp @@ -76,20 +76,16 @@ template void register_agent() if (cloud_agent) agent->set_cloud_agent(cloud_agent); return agent; - }, - info.native_device_tab); + }); } } // anonymous namespace -bool NetworkAgentFactory::register_printer_agent(const std::string& id, const std::string& display_name, PrinterAgentFactory factory, - bool native_device_tab) +bool NetworkAgentFactory::register_printer_agent(const std::string& id, const std::string& display_name, PrinterAgentFactory factory) { std::lock_guard lock(s_registry_mutex); auto& agents = get_printer_agents(); - PrinterAgentInfo info(id, display_name, std::move(factory)); - info.native_device_tab = native_device_tab; - return agents.emplace(id, std::move(info)).second; + return agents.emplace(id, PrinterAgentInfo(id, display_name, std::move(factory))).second; } bool NetworkAgentFactory::is_printer_agent_registered(const std::string& id) diff --git a/src/slic3r/Utils/NetworkAgentFactory.hpp b/src/slic3r/Utils/NetworkAgentFactory.hpp index cb8a82e81e..ea2758618a 100644 --- a/src/slic3r/Utils/NetworkAgentFactory.hpp +++ b/src/slic3r/Utils/NetworkAgentFactory.hpp @@ -31,7 +31,6 @@ struct PrinterAgentInfo std::string display_name; // e.g., "Orca Native", "Bambu Lab" std::string plugin_identifier; // Empty for built-ins, otherwise ;; PrinterAgentFactory factory; // Function to create the agent - bool native_device_tab = true; // See AgentInfo::native_device_tab bool is_plugin() const { return !plugin_identifier.empty(); } PrinterAgentInfo(const std::string& id_, const std::string& display_name_, PrinterAgentFactory factory_) @@ -85,11 +84,9 @@ public: * @param id Unique identifier for the agent (e.g., "orca", "bbl") * @param display_name Human-readable name for UI * @param factory Factory function to create the agent - * @param native_device_tab Whether the native Device and Calibration tabs apply to the agent's printers * @return true if registration succeeded, false if already registered */ - static bool register_printer_agent(const std::string& id, const std::string& display_name, PrinterAgentFactory factory, - bool native_device_tab = true); + static bool register_printer_agent(const std::string& id, const std::string& display_name, PrinterAgentFactory factory); /** * Check if an agent registry/config key is registered diff --git a/src/slic3r/Utils/QidiPrinterAgent.cpp b/src/slic3r/Utils/QidiPrinterAgent.cpp index 3cb7c3e682..528c11c161 100644 --- a/src/slic3r/Utils/QidiPrinterAgent.cpp +++ b/src/slic3r/Utils/QidiPrinterAgent.cpp @@ -46,8 +46,7 @@ QidiPrinterAgent::QidiPrinterAgent(std::string log_dir) : MoonrakerPrinterAgent( AgentInfo QidiPrinterAgent::get_agent_info_static() { - // The native Device and Calibration tabs have nothing to show for Qidi printers yet, so Fluidd's web Device tab is the only one - return AgentInfo{"qidi", "Qidi", QidiPrinterAgent_VERSION, "Qidi printer agent", false}; + return AgentInfo{"qidi", "Qidi", QidiPrinterAgent_VERSION, "Qidi printer agent"}; } bool QidiPrinterAgent::fetch_filament_info(std::string dev_id, FilamentSyncMode /*sync_mode*/) diff --git a/src/slic3r/plugin/PluginFsUtils.cpp b/src/slic3r/plugin/PluginFsUtils.cpp index c29aab38d6..5134ad56af 100644 --- a/src/slic3r/plugin/PluginFsUtils.cpp +++ b/src/slic3r/plugin/PluginFsUtils.cpp @@ -394,31 +394,41 @@ std::string unquote_toml_string(const std::string& val) return val; } -// Split a TOML inline array: ["a", "b"] → {"a", "b"}. -// Handles trailing commas and single-line format. -std::vector parse_toml_inline_array(const std::string& val) +// Append the string items of one line of a TOML array to `items`. A quoted item keeps its commas, +// as a version range ("numpy>=1.20,<2") needs; '#' starts a comment and ']' closes the array. +// Returns true when the array closes on this line. +bool read_toml_array_items(const std::string& line, std::vector& items) { - std::vector result; - std::string inner = val; - // Strip outer brackets. - if (!inner.empty() && inner.front() == '[') - inner.erase(0, 1); - if (!inner.empty() && inner.back() == ']') - inner.pop_back(); - - // Simple split by comma, strip quotes and whitespace. - std::istringstream ss(inner); - std::string item; - while (std::getline(ss, item, ',')) { - // Trim whitespace. - size_t s = 0, e = item.size(); - while (s < e && (item[s] == ' ' || item[s] == '\t')) ++s; - while (e > s && (item[e - 1] == ' ' || item[e - 1] == '\t')) --e; - item = item.substr(s, e - s); + size_t i = 0; + while (i < line.size()) { + const char c = line[i]; + if (c == ']') + return true; + if (c == '#') + return false; + if (c == ' ' || c == '\t' || c == ',') { + ++i; + continue; + } + std::string item; + if (c == '"' || c == '\'') { + // A basic string ("...") takes backslash escapes; a literal string ('...') takes none. + for (++i; i < line.size() && line[i] != c; ++i) { + if (c == '"' && line[i] == '\\' && i + 1 < line.size()) + ++i; + item += line[i]; + } + ++i; + } else { + // An unquoted item isn't TOML, but is kept as the requirement it names. + const size_t end = std::min(line.find_first_of(" \t,]#", i), line.size()); + item = line.substr(i, end - i); + i = end; + } if (!item.empty()) - result.push_back(unquote_toml_string(item)); + items.push_back(item); } - return result; + return false; } // Parse PEP 723 TOML subset for dependencies, requires-python, and @@ -485,16 +495,8 @@ bool parse_pep723_toml(const std::string& toml_content, } if (section == TomlSection::InDepsArray) { - if (trimmed == "]") { + if (read_toml_array_items(trimmed, out_deps)) section = TomlSection::Root; - continue; - } - std::string val = trimmed; - if (!val.empty() && val.back() == ',') - val.pop_back(); - val = unquote_toml_string(val); - if (!val.empty()) - out_deps.push_back(val); continue; } @@ -518,12 +520,11 @@ bool parse_pep723_toml(const std::string& toml_content, if (key == "requires-python") { out_requires_python = unquote_toml_string(val); } else if (key == "dependencies") { - if (val == "[") { + // The array may close on this line or run on over the following ones. + out_deps.clear(); + const bool array = !val.empty() && val.front() == '['; + if (!read_toml_array_items(array ? val.substr(1) : val, out_deps) && array) section = TomlSection::InDepsArray; - } else { - // Inline array: dependencies = ["a", "b"] - out_deps = parse_toml_inline_array(val); - } } } else if (section == TomlSection::OrcaPlugin) { if (key == "name") out_name = unquote_toml_string(val); diff --git a/tests/data/named_compound_bodies.step b/tests/data/named_compound_bodies.step new file mode 100644 index 0000000000..6a05345b33 --- /dev/null +++ b/tests/data/named_compound_bodies.step @@ -0,0 +1,124 @@ +ISO-10303-21; +HEADER; +FILE_DESCRIPTION(('Named tetrahedra for body identity regression'),'2;1'); +FILE_NAME('named_compound_bodies','2026-10-27T00:00:00',(''),(''),'','',''); +FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }')); +ENDSEC; +DATA; +#1=APPLICATION_CONTEXT('automotive design'); +#2=APPLICATION_PROTOCOL_DEFINITION('international standard','automotive_design',2000,#1); +#3=PRODUCT_CONTEXT('',#1,'mechanical'); +#4=PRODUCT('Body collection','Body collection','',(#3)); +#5=PRODUCT_DEFINITION_FORMATION('','',#4); +#6=PRODUCT_DEFINITION_CONTEXT('part definition',#1,'design'); +#7=PRODUCT_DEFINITION('design','',#5,#6); +#8=PRODUCT_DEFINITION_SHAPE('','',#7); +#9=SHAPE_DEFINITION_REPRESENTATION(#8,#20); +#13=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.)); +#14=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.)); +#15=(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT()); +#16=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(0.001),#13,'distance_accuracy_value',''); +#17=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#16))GLOBAL_UNIT_ASSIGNED_CONTEXT((#13,#14,#15))REPRESENTATION_CONTEXT('','')); +#21=AXIS2_PLACEMENT_3D('',#30,#40,#41); +#20=FACETED_BREP_SHAPE_REPRESENTATION('',(#21,#22,#1022,#2022),#17); +#22=FACETED_BREP('Part10',#23); +#23=CLOSED_SHELL('',(#50,#51,#52,#53)); +#30=CARTESIAN_POINT('',(0.0,0.,0.)); +#31=CARTESIAN_POINT('',(10.0,0.,0.)); +#32=CARTESIAN_POINT('',(0.0,10.,0.)); +#33=CARTESIAN_POINT('',(0.0,0.,10.)); +#40=DIRECTION('',(0.,0.,1.)); +#41=DIRECTION('',(1.,0.,0.)); +#42=DIRECTION('',(0.,0.,-1.)); +#43=DIRECTION('',(0.,-1.,0.)); +#44=DIRECTION('',(-1.,0.,0.)); +#45=DIRECTION('',(0.577350269189626,0.577350269189626,0.577350269189626)); +#46=DIRECTION('',(0.,0.,1.)); +#50=FACE_SURFACE('',(#60),#70,.T.); +#51=FACE_SURFACE('',(#61),#71,.T.); +#52=FACE_SURFACE('',(#62),#72,.T.); +#53=FACE_SURFACE('',(#63),#73,.T.); +#60=FACE_OUTER_BOUND('',#80,.T.); +#61=FACE_OUTER_BOUND('',#81,.T.); +#62=FACE_OUTER_BOUND('',#82,.T.); +#63=FACE_OUTER_BOUND('',#83,.T.); +#70=PLANE('',#90); +#71=PLANE('',#91); +#72=PLANE('',#92); +#73=PLANE('',#93); +#80=POLY_LOOP('',(#30,#32,#31)); +#81=POLY_LOOP('',(#30,#31,#33)); +#82=POLY_LOOP('',(#30,#33,#32)); +#83=POLY_LOOP('',(#31,#32,#33)); +#90=AXIS2_PLACEMENT_3D('',#30,#42,#41); +#91=AXIS2_PLACEMENT_3D('',#30,#43,#41); +#92=AXIS2_PLACEMENT_3D('',#30,#44,#46); +#93=AXIS2_PLACEMENT_3D('',#31,#45,$); +#1022=FACETED_BREP('Part2',#1023); +#1023=CLOSED_SHELL('',(#1050,#1051,#1052,#1053)); +#1030=CARTESIAN_POINT('',(25.0,0.,0.)); +#1031=CARTESIAN_POINT('',(35.0,0.,0.)); +#1032=CARTESIAN_POINT('',(25.0,10.,0.)); +#1033=CARTESIAN_POINT('',(25.0,0.,10.)); +#1040=DIRECTION('',(0.,0.,1.)); +#1041=DIRECTION('',(1.,0.,0.)); +#1042=DIRECTION('',(0.,0.,-1.)); +#1043=DIRECTION('',(0.,-1.,0.)); +#1044=DIRECTION('',(-1.,0.,0.)); +#1045=DIRECTION('',(0.577350269189626,0.577350269189626,0.577350269189626)); +#1046=DIRECTION('',(0.,0.,1.)); +#1050=FACE_SURFACE('',(#1060),#1070,.T.); +#1051=FACE_SURFACE('',(#1061),#1071,.T.); +#1052=FACE_SURFACE('',(#1062),#1072,.T.); +#1053=FACE_SURFACE('',(#1063),#1073,.T.); +#1060=FACE_OUTER_BOUND('',#1080,.T.); +#1061=FACE_OUTER_BOUND('',#1081,.T.); +#1062=FACE_OUTER_BOUND('',#1082,.T.); +#1063=FACE_OUTER_BOUND('',#1083,.T.); +#1070=PLANE('',#1090); +#1071=PLANE('',#1091); +#1072=PLANE('',#1092); +#1073=PLANE('',#1093); +#1080=POLY_LOOP('',(#1030,#1032,#1031)); +#1081=POLY_LOOP('',(#1030,#1031,#1033)); +#1082=POLY_LOOP('',(#1030,#1033,#1032)); +#1083=POLY_LOOP('',(#1031,#1032,#1033)); +#1090=AXIS2_PLACEMENT_3D('',#1030,#1042,#1041); +#1091=AXIS2_PLACEMENT_3D('',#1030,#1043,#1041); +#1092=AXIS2_PLACEMENT_3D('',#1030,#1044,#1046); +#1093=AXIS2_PLACEMENT_3D('',#1031,#1045,$); +#2022=FACETED_BREP('\X2\04220435043B043E\X0\ & shell',#2023); +#2023=CLOSED_SHELL('',(#2050,#2051,#2052,#2053)); +#2030=CARTESIAN_POINT('',(50.0,0.,0.)); +#2031=CARTESIAN_POINT('',(60.0,0.,0.)); +#2032=CARTESIAN_POINT('',(50.0,10.,0.)); +#2033=CARTESIAN_POINT('',(50.0,0.,10.)); +#2040=DIRECTION('',(0.,0.,1.)); +#2041=DIRECTION('',(1.,0.,0.)); +#2042=DIRECTION('',(0.,0.,-1.)); +#2043=DIRECTION('',(0.,-1.,0.)); +#2044=DIRECTION('',(-1.,0.,0.)); +#2045=DIRECTION('',(0.577350269189626,0.577350269189626,0.577350269189626)); +#2046=DIRECTION('',(0.,0.,1.)); +#2050=FACE_SURFACE('',(#2060),#2070,.T.); +#2051=FACE_SURFACE('',(#2061),#2071,.T.); +#2052=FACE_SURFACE('',(#2062),#2072,.T.); +#2053=FACE_SURFACE('',(#2063),#2073,.T.); +#2060=FACE_OUTER_BOUND('',#2080,.T.); +#2061=FACE_OUTER_BOUND('',#2081,.T.); +#2062=FACE_OUTER_BOUND('',#2082,.T.); +#2063=FACE_OUTER_BOUND('',#2083,.T.); +#2070=PLANE('',#2090); +#2071=PLANE('',#2091); +#2072=PLANE('',#2092); +#2073=PLANE('',#2093); +#2080=POLY_LOOP('',(#2030,#2032,#2031)); +#2081=POLY_LOOP('',(#2030,#2031,#2033)); +#2082=POLY_LOOP('',(#2030,#2033,#2032)); +#2083=POLY_LOOP('',(#2031,#2032,#2033)); +#2090=AXIS2_PLACEMENT_3D('',#2030,#2042,#2041); +#2091=AXIS2_PLACEMENT_3D('',#2030,#2043,#2041); +#2092=AXIS2_PLACEMENT_3D('',#2030,#2044,#2046); +#2093=AXIS2_PLACEMENT_3D('',#2031,#2045,$); +ENDSEC; +END-ISO-10303-21; diff --git a/tests/data/named_single_body.step b/tests/data/named_single_body.step new file mode 100644 index 0000000000..f1a0ff78bb --- /dev/null +++ b/tests/data/named_single_body.step @@ -0,0 +1,58 @@ +ISO-10303-21; +HEADER; +FILE_DESCRIPTION(('Named tetrahedra for body identity regression'),'2;1'); +FILE_NAME('named_single_body','2026-10-27T00:00:00',(''),(''),'','',''); +FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }')); +ENDSEC; +DATA; +#1=APPLICATION_CONTEXT('automotive design'); +#2=APPLICATION_PROTOCOL_DEFINITION('international standard','automotive_design',2000,#1); +#3=PRODUCT_CONTEXT('',#1,'mechanical'); +#4=PRODUCT('Body collection','Body collection','',(#3)); +#5=PRODUCT_DEFINITION_FORMATION('','',#4); +#6=PRODUCT_DEFINITION_CONTEXT('part definition',#1,'design'); +#7=PRODUCT_DEFINITION('design','',#5,#6); +#8=PRODUCT_DEFINITION_SHAPE('','',#7); +#9=SHAPE_DEFINITION_REPRESENTATION(#8,#20); +#13=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.)); +#14=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.)); +#15=(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT()); +#16=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(0.001),#13,'distance_accuracy_value',''); +#17=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#16))GLOBAL_UNIT_ASSIGNED_CONTEXT((#13,#14,#15))REPRESENTATION_CONTEXT('','')); +#21=AXIS2_PLACEMENT_3D('',#30,#40,#41); +#20=FACETED_BREP_SHAPE_REPRESENTATION('',(#21,#22),#17); +#22=FACETED_BREP('Body name',#23); +#23=CLOSED_SHELL('',(#50,#51,#52,#53)); +#30=CARTESIAN_POINT('',(0.0,0.,0.)); +#31=CARTESIAN_POINT('',(10.0,0.,0.)); +#32=CARTESIAN_POINT('',(0.0,10.,0.)); +#33=CARTESIAN_POINT('',(0.0,0.,10.)); +#40=DIRECTION('',(0.,0.,1.)); +#41=DIRECTION('',(1.,0.,0.)); +#42=DIRECTION('',(0.,0.,-1.)); +#43=DIRECTION('',(0.,-1.,0.)); +#44=DIRECTION('',(-1.,0.,0.)); +#45=DIRECTION('',(0.577350269189626,0.577350269189626,0.577350269189626)); +#46=DIRECTION('',(0.,0.,1.)); +#50=FACE_SURFACE('',(#60),#70,.T.); +#51=FACE_SURFACE('',(#61),#71,.T.); +#52=FACE_SURFACE('',(#62),#72,.T.); +#53=FACE_SURFACE('',(#63),#73,.T.); +#60=FACE_OUTER_BOUND('',#80,.T.); +#61=FACE_OUTER_BOUND('',#81,.T.); +#62=FACE_OUTER_BOUND('',#82,.T.); +#63=FACE_OUTER_BOUND('',#83,.T.); +#70=PLANE('',#90); +#71=PLANE('',#91); +#72=PLANE('',#92); +#73=PLANE('',#93); +#80=POLY_LOOP('',(#30,#32,#31)); +#81=POLY_LOOP('',(#30,#31,#33)); +#82=POLY_LOOP('',(#30,#33,#32)); +#83=POLY_LOOP('',(#31,#32,#33)); +#90=AXIS2_PLACEMENT_3D('',#30,#42,#41); +#91=AXIS2_PLACEMENT_3D('',#30,#43,#41); +#92=AXIS2_PLACEMENT_3D('',#30,#44,#46); +#93=AXIS2_PLACEMENT_3D('',#31,#45,$); +ENDSEC; +END-ISO-10303-21; diff --git a/tests/fff_print/test_extrusion_entity.cpp b/tests/fff_print/test_extrusion_entity.cpp index b3a071bdc4..af116ddf0a 100644 --- a/tests/fff_print/test_extrusion_entity.cpp +++ b/tests/fff_print/test_extrusion_entity.cpp @@ -91,31 +91,80 @@ SCENARIO("Polygon flattening", "[ExtrusionEntity]") { } } -static ExtrusionPaths straight_path(const std::vector &xs) +static ExtrusionPaths path_through(const std::vector &points) { ExtrusionPath path{erExternalPerimeter, 1.0, 0.45f, 0.2f}; - for (double x : xs) - path.polyline.append(Point3::new_scale(x, 0., 0.)); + for (const Vec2d &point : points) + path.polyline.append(Point3::new_scale(point.x(), point.y(), 0.)); return {path}; } -TEST_CASE("Scarf ramp ends on the next loop vertex instead of leaving a short stub", "[ExtrusionEntity]") +static ExtrusionPaths straight_path(const std::vector &xs) +{ + std::vector points; + for (double x : xs) + points.emplace_back(x, 0.); + return path_through(points); +} + +TEST_CASE("Scarf ramp leaves no short stub before the next loop vertex", "[ExtrusionEntity]") { using Catch::Matchers::WithinAbs; - // A 20 mm scarf in 10 steps: a remainder shorter than half a 2 mm step is snapped forward. + // A 20 mm scarf in 10 steps: a remainder shorter than half a 2 mm step is merged away. const double slope_length = 20.; const double max_segment = scale_(slope_length / 10); - SECTION("a 0.09 mm remainder extends the ramp to the vertex") { + SECTION("a 0.09 mm remainder before a vertex on the straight line skips that vertex") { ExtrusionPaths paths = straight_path({0., 5., 10., 15., 20.09, 25., 30.}); ExtrusionLoopSloped loop(paths, 0., slope_length, max_segment, 0.); REQUIRE(loop.starts.size() == 1); REQUIRE(loop.ends.size() == 1); REQUIRE(loop.paths.size() == 1); - CHECK_THAT(unscale_(loop.starts.front().polyline.last_point().x()), WithinAbs(20.09, 1e-3)); - CHECK_THAT(unscale_(loop.ends.front().polyline.last_point().x()), WithinAbs(20.09, 1e-3)); - CHECK_THAT(unscale_(loop.paths.front().polyline.first_point().x()), WithinAbs(20.09, 1e-3)); - CHECK_THAT(unscale_(loop.paths.front().polyline.lines().front().length()), WithinAbs(4.91, 1e-3)); + CHECK_THAT(unscale_(loop.starts.front().polyline.last_point().x()), WithinAbs(20., 1e-3)); + CHECK_THAT(unscale_(loop.ends.front().polyline.last_point().x()), WithinAbs(20., 1e-3)); + const Polyline3 &flat = loop.paths.front().polyline; + CHECK_THAT(unscale_(flat.first_point().x()), WithinAbs(20., 1e-3)); + CHECK_THAT(unscale_(flat.lines().front().length()), WithinAbs(5., 1e-3)); + CHECK_THAT(unscale_(flat.last_point().x()), WithinAbs(30., 1e-3)); + } + + SECTION("the ramp ends at the same place whichever vertex the loop has just past it") { + // One layer's wall has a vertex 0.1 mm past the scarf length, the next layer's 0.4 mm past it. + for (double vertex : {20.1, 20.4}) { + ExtrusionPaths paths = straight_path({0., 5., 10., 15., vertex, 25., 30.}); + ExtrusionLoopSloped loop(paths, 0., slope_length, max_segment, 0.); + REQUIRE(loop.paths.size() == 1); + CHECK_THAT(unscale_(loop.starts.front().polyline.last_point().x()), WithinAbs(20., 1e-3)); + CHECK_THAT(unscale_(loop.paths.front().polyline.lines().front().length()), WithinAbs(5., 1e-3)); + } + } + + SECTION("a slight bend within the window is skipped, a corner is not") { + // Skipping a vertex 0.3 mm past the ramp moves the path by 0.3 mm times the sine of its turn: + // 0.026 mm at 5 degrees, 0.15 mm at 30 degrees, against a tolerance of 0.05 mm. + ExtrusionPaths bend = path_through({{0., 0.}, {5., 0.}, {10., 0.}, {15., 0.}, {20.3, 0.}, {25.28, 0.436}, {30.26, 0.872}}); + ExtrusionLoopSloped bend_loop(bend, 0., slope_length, max_segment, 0.); + REQUIRE(bend_loop.paths.size() == 1); + CHECK_THAT(unscale_(bend_loop.starts.front().polyline.last_point().x()), WithinAbs(20., 1e-3)); + CHECK(bend_loop.paths.front().polyline.size() == 3); + + ExtrusionPaths corner = path_through({{0., 0.}, {5., 0.}, {10., 0.}, {15., 0.}, {20.3, 0.}, {24.63, 2.5}, {28.96, 5.}}); + ExtrusionLoopSloped corner_loop(corner, 0., slope_length, max_segment, 0.); + REQUIRE(corner_loop.paths.size() == 1); + CHECK_THAT(unscale_(corner_loop.starts.front().polyline.last_point().x()), WithinAbs(20.3, 1e-3)); + CHECK(corner_loop.paths.front().polyline.size() == 3); + } + + SECTION("the ramp that ends in a loop's second path keeps its exact length too") { + ExtrusionPaths paths = straight_path({0., 5., 12.}); + ExtrusionPaths rest = straight_path({12., 15., 20.2, 25., 30.}); + paths.push_back(rest.front()); + ExtrusionLoopSloped loop(paths, 0., slope_length, max_segment, 0.); + REQUIRE(loop.starts.size() == 2); + REQUIRE(loop.paths.size() == 1); + CHECK_THAT(unscale_(loop.starts.back().polyline.last_point().x()), WithinAbs(20., 1e-3)); + CHECK_THAT(unscale_(loop.paths.front().polyline.first_point().x()), WithinAbs(20., 1e-3)); + CHECK_THAT(unscale_(loop.paths.front().polyline.lines().front().length()), WithinAbs(5., 1e-3)); } SECTION("a remainder longer than half a step keeps the exact scarf length") { diff --git a/tests/fff_print/test_extrusion_processor.cpp b/tests/fff_print/test_extrusion_processor.cpp index b1e192cde8..452f5fe430 100644 --- a/tests/fff_print/test_extrusion_processor.cpp +++ b/tests/fff_print/test_extrusion_processor.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include "libslic3r/Line.hpp" #include "libslic3r/Point.hpp" #include @@ -128,6 +129,44 @@ template std::vector outer_wall_feed_rates(const std: return feed_rates; } +std::vector bridge_center_feed_rates(const std::string& gcode) +{ + struct BridgeMove { double start_x, end_x, speed; }; + std::vector bridge_moves; + bool bridge = false; + GCodeReader parser; + parser.parse_buffer(gcode, [&bridge_moves, &bridge](GCodeReader& self, const GCodeReader::GCodeLine& line) { + const std::string_view comment = line.comment(); + if (comment.find("FEATURE:") != std::string_view::npos || comment.find("TYPE:") != std::string_view::npos) + bridge = comment.find("Bridge") != std::string_view::npos && comment.find("Internal Bridge") == std::string_view::npos; + + const double start_x = self.x(); + const double end_x = line.new_X(self); + if (bridge && line.extruding(self) && std::abs(line.new_Z(self) - 5.2) < 0.01 && + std::abs(end_x - start_x) > 1.0) + bridge_moves.push_back({start_x, end_x, line.new_F(self) / MM_PER_MIN}); + }); + + if (bridge_moves.empty()) + return {}; + + double min_x = std::numeric_limits::max(); + double max_x = std::numeric_limits::lowest(); + for (const BridgeMove& move : bridge_moves) { + min_x = std::min({min_x, move.start_x, move.end_x}); + max_x = std::max({max_x, move.start_x, move.end_x}); + } + + const double center_margin = 0.25 * (max_x - min_x); + std::vector feed_rates; + for (const BridgeMove& move : bridge_moves) { + const double mid_x = 0.5 * (move.start_x + move.end_x); + if (mid_x > min_x + center_margin && mid_x < max_x - center_margin) + feed_rates.push_back(move.speed); + } + return feed_rates; +} + // The caged 45 degree overhang: outer walls crossing the sloped face for most of its width, on the // layers where the face genuinely overhangs. // Both ends are tested against the slope plane rather than requiring a constant Y. Arachne's @@ -729,6 +768,31 @@ TEST_CASE("Curled walls are estimated only when overhang speed and the slowdown CHECK(has_curled_lines(*cage.object) == estimated); } +TEST_CASE("Bridge infill keeps bridge speed with curled perimeter slowdown", "[ExtrusionProcessor][Regression]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ + {"initial_layer_print_height", "0.2"}, + {"layer_height", "0.2"}, + {"enable_overhang_speed", "1"}, + {"slowdown_for_curled_perimeters", "1"}, + {"overhang_1_4_speed", "0"}, + {"overhang_2_4_speed", "50"}, + {"overhang_3_4_speed", "30"}, + {"overhang_4_4_speed", "10"}, + {"bridge_speed", "45"}, + {"filament_max_volumetric_speed", "1000"}, + {"slow_down_for_layer_cooling", "0"}, + {"slow_down_layers", "0"}, + }); + + const std::vector feed_rates = bridge_center_feed_rates(slice({TestMesh::bridge}, config)); + + REQUIRE_FALSE(feed_rates.empty()); + for (const double feed_rate : feed_rates) + CHECK_THAT(feed_rate, Catch::Matchers::WithinAbs(45.0, 0.5)); +} + TEST_CASE("Curled walls are estimated when overhang speed and the slowdown for curled perimeters are on in different objects", "[ExtrusionProcessor]") { const std::vector> overrides{ diff --git a/tests/fff_print/test_print.cpp b/tests/fff_print/test_print.cpp index e87a698720..249385741f 100644 --- a/tests/fff_print/test_print.cpp +++ b/tests/fff_print/test_print.cpp @@ -1372,9 +1372,14 @@ TEST_CASE("Belt printers refuse an object taller than the gantry clearance", "[P // On a belt every tilted layer starts on the belt, so "the first layers" the fan stays off // for are a band along the belt, not the first slicing layers. The generator marks where // each extrusion segment enters and leaves that band and the cooling buffer keeps the fan -// off inside it, on every layer. +// off inside it, on every layer. The lowest wall of each tilted layer rests on the belt with +// its nozzle half a layer plus half its width up (0.1 + 0.21 mm here), so a band of one +// first layer has to be judged from the bead, not the nozzle, to hold it. TEST_CASE("Belt printers keep the part fan off within the band above the belt", "[Print][belt][Cooling]") { + // Fan-off layers, and the gantry Y below which an extrusion is well inside that band. + const auto [fan_off_layers, band_y] = GENERATE(table({ { 1, 0.35 }, { 3, 0.45 } })); + CAPTURE(fan_off_layers); DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); config.set_deserialize_strict({ { "belt_printer", 1 }, @@ -1387,9 +1392,8 @@ TEST_CASE("Belt printers keep the part fan off within the band above the belt", { "initial_layer_print_height", 0.2 }, { "skirt_loops", 0 }, { "z_hop", 0 }, - // Three layers, 0.6 mm: the lowest wall of each tilted layer is centred about 0.3 mm - // above the belt (half a line width in from the contact edge). - { "close_fan_the_first_x_layers", 3 }, + { "outer_wall_line_width", 0.42 }, + { "close_fan_the_first_x_layers", fan_off_layers }, { "full_fan_speed_layer", 0 }, { "fan_min_speed", 100 }, { "fan_max_speed", 100 }, @@ -1406,9 +1410,9 @@ TEST_CASE("Belt printers keep the part fan off within the band above the belt", CHECK(gcode.find(";_BELT_BAND") == std::string::npos); // With this axis mapping machine Y is the height above the belt along the gantry. Walk - // the moves with the fan state: extrusions that stay within 0.45 mm of the belt are well - // inside the band and must print with the fan off; extrusions that stay 5 mm clear of it - // must print with it on. The first three slicing layers have the fan off altogether. + // the moves with the fan state: extrusions that stay below band_y are well inside the band + // and must print with the fan off; extrusions that stay 5 mm clear of it must print with + // it on. The first fan_off_layers slicing layers have the fan off altogether. size_t in_band = 0, in_band_fan_on = 0, clear = 0, clear_fan_off = 0; int layer = -1; bool fan_on = false; @@ -1430,8 +1434,8 @@ TEST_CASE("Belt printers keep the part fan off within the band above the belt", continue; const double y_new = std::atof(cmd.c_str() + ypos + 2); const bool extruding = epos != std::string::npos && std::atof(cmd.c_str() + epos + 2) > 0.; - if (extruding && layer >= 3) { - if (std::max(y, y_new) < 0.45) { + if (extruding && layer >= fan_off_layers) { + if (std::max(y, y_new) < band_y) { ++ in_band; in_band_fan_on += fan_on; } else if (std::min(y, y_new) > 5.) { @@ -1448,6 +1452,144 @@ TEST_CASE("Belt printers keep the part fan off within the band above the belt", CHECK(clear_fan_off == 0); } +// On a belt one wall loop runs from the belt up the part, and whether a path is on the first +// layer, and its step of the slow_down_layers ramp, set its speed, flow and acceleration as a +// whole. Each part of the loop must take the settings of its own height above the belt, +// wherever the seam starts the loop. +TEST_CASE("Belt printers use first-layer settings only where a wall rests on the belt", "[Print][belt][Regression]") +{ + const std::string seam = GENERATE("back", "random"); + const int slow_down_layers = GENERATE(0, 4); + CAPTURE(seam, slow_down_layers); + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ + { "belt_printer", 1 }, + { "belt_slice_rotation", "x" }, + { "belt_slice_rotation_angle", 45 }, + { "gcode_remap_x", "rev_x" }, + { "gcode_remap_y", "pos_z" }, + { "gcode_remap_z", "pos_y" }, + { "layer_height", 0.2 }, + { "initial_layer_print_height", 0.2 }, + { "skirt_loops", 0 }, + { "brim_type", "no_brim" }, + { "z_hop", 0 }, + { "wall_generator", "classic" }, + { "outer_wall_line_width", 0.42 }, + { "seam_position", seam }, + // One path per wall loop, so nothing but the edges of the bands cut it. + { "detect_overhang_wall", 0 }, + { "enable_overhang_speed", 0 }, + { "initial_layer_speed", 10 }, + { "outer_wall_speed", 40 }, + { "slow_down_layers", slow_down_layers }, + { "filament_max_volumetric_speed", 20 }, + { "slow_down_for_layer_cooling", 0 }, + { "set_other_flow_ratios", 1 }, + { "first_layer_flow_ratio", 0.8 }, + { "machine_start_gcode", "T[initial_tool]\n" }, + { "layer_change_gcode", "G92 E0\n" }, + }); + const std::string gcode = slice({ cube(20) }, config); + + // As above, machine Y is the height above the belt. The outer wall's nozzle is half its + // width, 0.21 mm, higher than the belt under its edge, so the first layer, up to 0.2 mm, + // ends at Y = 0.41 and step k of the ramp spans Y = 0.21 + [0.2 k, 0.2 (k + 1)). Its wall + // resting on the belt is at Y = 0.31. + const double ramp_step_2 = 10. + (40. - 10.) * 2. / 4.; + std::vector in_band_e, clear_e; // E per mm + size_t in_band = 0, in_band_fast = 0, step_2 = 0, step_2_off = 0, clear = 0, clear_slow = 0; + std::string type; + GCodeReader reader; + reader.parse_buffer(gcode, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) { + if (boost::starts_with(line.raw(), ";TYPE:")) { + type = line.raw().substr(6); + return; + } + if (type != "Outer wall" || ! line.extruding(self) || line.dist_XY(self) <= EPSILON) + return; + const double y_lo = std::min(self.y(), line.new_Y(self)); + const double y_hi = std::max(self.y(), line.new_Y(self)); + const double f = line.new_F(self); + // Long moves only for the flow, so that the rounding of E does not blur it. + const bool long_move = line.dist_XY(self) >= 0.5; + if (y_hi < 0.35) { + ++ in_band; + in_band_fast += std::abs(f - 10. * 60.) > 1.; + if (long_move) + in_band_e.push_back(line.dist_E(self) / line.dist_XY(self)); + } else if (slow_down_layers == 4 && y_lo > 0.61 - 1e-3 && y_hi < 0.81 + 1e-3) { + ++ step_2; + step_2_off += std::abs(f - ramp_step_2 * 60.) > 1.; + } else if (y_lo > 1.5) { + ++ clear; + clear_slow += std::abs(f - 40. * 60.) > 1.; + if (long_move) + clear_e.push_back(line.dist_E(self) / line.dist_XY(self)); + } + }); + REQUIRE(in_band > 20); + REQUIRE(clear > 20); + CHECK(in_band_fast == 0); + CHECK(clear_slow == 0); + if (slow_down_layers == 4) { + REQUIRE(step_2 > 10); + CHECK(step_2_off == 0); + } + // first_layer_flow_ratio on the belt and nowhere else. + auto median = [](std::vector v) { + std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end()); + return v[v.size() / 2]; + }; + CHECK_THAT(median(in_band_e) / median(clear_e), Catch::Matchers::WithinRel(0.8, 0.02)); +} + +// Small-area flow compensation scales a line's flow by the line's length. The cuts a belt path +// gets at the edges of the bands above the belt must not make it see the pieces as short lines. +TEST_CASE("Belt band cuts leave small-area flow compensation unchanged", "[Print][belt][Regression]") +{ + // Plastic per role. The slow_down_layers ramp adds band edges every 0.2 mm above the belt, + // here up to well past the top of the part, and with them cuts through the solid infill + // under its top face, but changes nothing else about how much plastic is laid. + auto plastic = [](int slow_down_layers) { + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ + { "belt_printer", 1 }, + { "belt_slice_rotation", "x" }, + { "belt_slice_rotation_angle", 45 }, + { "gcode_remap_x", "rev_x" }, + { "gcode_remap_y", "pos_z" }, + { "gcode_remap_z", "pos_y" }, + { "layer_height", 0.2 }, + { "initial_layer_print_height", 0.2 }, + { "skirt_loops", 0 }, + { "brim_type", "no_brim" }, + { "z_hop", 0 }, + { "bottom_shell_layers", 4 }, + { "internal_solid_infill_pattern", "monotonic" }, + { "small_area_infill_flow_compensation", 1 }, + { "slow_down_layers", slow_down_layers }, + { "machine_start_gcode", "T[initial_tool]\n" }, + { "layer_change_gcode", "G92 E0\n" }, + }); + std::map e; + std::string type; + GCodeReader reader; + reader.parse_buffer(slice({ cube(20) }, config), [&](GCodeReader &self, const GCodeReader::GCodeLine &line) { + if (boost::starts_with(line.raw(), ";TYPE:")) + type = line.raw().substr(6); + else if (line.extruding(self) && line.dist_XY(self) > EPSILON) + e[type] += line.dist_E(self); + }); + return e; + }; + const std::map uncut = plastic(0); + const std::map cut = plastic(200); + REQUIRE(uncut.count("Internal solid infill") == 1); + REQUIRE(cut.count("Internal solid infill") == 1); + CHECK_THAT(cut.at("Internal solid infill"), Catch::Matchers::WithinRel(uncut.at("Internal solid infill"), 1e-4)); +} + // Organic supports under an overhang on a belt printer reach below the object's first layer, // where the virtual belt raft layers sit at negative Z. The lowest of them used to get a // negative height and abort slicing with a negative flow error. @@ -2312,3 +2454,154 @@ TEST_CASE("Objects on extruders with different layer height limits can share a p INFO(error.string); CHECK(error.string.empty()); } + +TEST_CASE("Belt printers apply the Z shrinkage compensation to the slicing height once", "[Print][belt][Regression]") +{ + // A 20 mm cube printed with a filament that shrinks to xy % / z % is sliced like an uncompensated box + // 20 * 100 / xy wide and 20 * 100 / z tall. The span of the layers is compared, as the belt Z offset + // depends on where the object is centred. + const auto [xy, z, angle] = GENERATE(table({ { 100., 95., 45. }, { 100., 105., 45. }, { 90., 95., 45. }, { 100., 105., 0. } })); + const auto sliced_height = [](const TriangleMesh &mesh, double xy, double z, double angle) { + DynamicPrintConfig config = belt_test_config(); + config.set_deserialize_strict({ { "filament_shrink", xy }, { "filament_shrinkage_compensation_z", z }, { "belt_slice_rotation_angle", angle } }); + Print print; + init_and_process_print({ mesh }, print, config); + const PrintObject &object = *print.objects().front(); + return std::make_pair(object.slicing_parameters().object_print_z_max, + object.layers().back()->print_z - object.layers().front()->print_z); + }; + + const auto [compensated_max_z, compensated_span] = sliced_height(cube(20.), xy, z, angle); + const auto [expected_max_z, expected_span] = sliced_height(make_cube(20. * 100. / xy, 20. * 100. / xy, 20. * 100. / z), 100., 100., angle); + CHECK_THAT(compensated_max_z, Catch::Matchers::WithinAbs(expected_max_z, EPSILON)); + CHECK_THAT(compensated_span, Catch::Matchers::WithinAbs(expected_span, 0.2 * 100. / z)); +} + +TEST_CASE("The belt build height check uses the compensated height", "[Print][belt][validate][Regression]") +{ + // printable_height is 100 mm. Z shrinkage 105 % prints 101 mm at about 96.2 mm, which fits, and 106 mm at + // about 101 mm, which does not; with 95 % a 97 mm object only becomes too tall through the compensation. + const auto [z, height, expected] = GENERATE(table({ + { 105., 101., "" }, + { 105., 106., "exceeds the maximum build volume height." }, + { 95., 92., "" }, + { 95., 97., "because of material shrinkage compensation" }, + })); + DynamicPrintConfig config = belt_test_config(); + config.set_deserialize_strict({ { "printable_height", 100. }, { "filament_shrinkage_compensation_z", z } }); + + Print print; + Model model; + init_print({ make_cube(20., 20., height) }, print, model, config); + const std::string error = print.validate().string; + INFO(error); + if (expected.empty()) + CHECK(error.empty()); + else + CHECK(error.find(expected) != std::string::npos); +} + +// A 20 mm cube on the bed with a height range override. +static ModelObject* cube_with_height_range(Model &model, const t_layer_height_range &range, DynamicPrintConfig &&range_config) +{ + ModelObject *object = model.add_object(); + object->add_volume(cube(20.)); + // Every layer range must carry a layer_height (see layer_height_profile_from_ranges). + object->layer_config_ranges[range].assign_config(std::move(range_config)); + object->add_instance()->set_offset(Vec3d(90., 90., 0.)); + object->ensure_on_bed(); + return object; +} + +static DynamicPrintConfig height_range_test_config(double shrinkage_z) +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ + { "filament_shrinkage_compensation_z", shrinkage_z }, + { "layer_height", 0.2 }, + { "initial_layer_print_height", 0.2 }, + { "precise_z_height", false }, + { "sparse_infill_density", "15%" }, + }); + return config; +} + +// The 0.1 mm / 50 % height range [10, 15] has to print both its layer height and its infill from 10 * 100 / z +// up to 15 * 100 / z of the object. +static void check_thin_dense_height_range(const PrintObject &print_object, double shrinkage_z) +{ + size_t mismatched = 0; + double first_dense_z = -1.; + for (const Layer *layer : print_object.layers()) { + const bool thin = layer->height < 0.15; + const bool dense = std::any_of(layer->regions().begin(), layer->regions().end(), [](const LayerRegion *region) { + return ! region->slices.empty() && region->region().config().sparse_infill_density.value > 40.; + }); + if (thin != dense) + ++ mismatched; + if (dense && first_dense_z < 0.) + first_dense_z = layer->slice_z; + } + CHECK(mismatched == 0); + CHECK_THAT(first_dense_z, Catch::Matchers::WithinAbs(10. * 100. / shrinkage_z, 0.2)); +} + +static DynamicPrintConfig thin_dense_height_range() +{ + DynamicPrintConfig range; + range.set_key_value("layer_height", new ConfigOptionFloat(0.1)); + range.set_key_value("sparse_infill_density", new ConfigOptionPercent(50)); + return range; +} + +TEST_CASE("A height range above the object keeps its layer height up to the compensated top", "[Print][Regression]") +{ + // The range [10, 100] covers the top of the 20 mm cube, which the Z shrinkage compensation moves to 20 * 100 / z. + const double z = GENERATE(95., 105.); + DynamicPrintConfig range; + range.set_key_value("layer_height", new ConfigOptionFloat(0.1)); + Model model; + cube_with_height_range(model, { 10., 100. }, std::move(range)); + Print print; + print.apply(model, height_range_test_config(z)); + print.process(); + + const PrintObject &print_object = *print.objects().front(); + CHECK_THAT(print_object.layers().back()->print_z, Catch::Matchers::WithinAbs(20. * 100. / z, 0.1)); + const size_t thick_layers_in_range = std::count_if(print_object.layers().begin(), print_object.layers().end(), + [z](const Layer *layer) { return layer->slice_z > 11. * 100. / z && layer->height > 0.15; }); + CHECK(thick_layers_in_range == 0); +} + +TEST_CASE("Height range settings apply where the height range prints", "[Print][Regression]") +{ + // The range [10, 15] prints with 0.1 mm layers and 50 % infill. The Z shrinkage compensation moves both + // to 10 * 100 / z ... 15 * 100 / z. + const double z = GENERATE(100., 95., 105.); + Model model; + cube_with_height_range(model, { 10., 15. }, thin_dense_height_range()); + Print print; + print.apply(model, height_range_test_config(z)); + print.process(); + + check_thin_dense_height_range(*print.objects().front(), z); +} + +TEST_CASE("Height range settings follow a Z shrinkage change that comes with a modifier change", "[Print][Regression]") +{ + // Adding a modifier lets Print::apply() reuse the cached regions; the cached height ranges were + // compensated for the old Z shrinkage. + Model model; + ModelObject *object = cube_with_height_range(model, { 10., 15. }, thin_dense_height_range()); + Print print; + print.apply(model, height_range_test_config(100.)); + print.process(); + + DynamicPrintConfig modifier_config; + modifier_config.set_key_value("wall_loops", new ConfigOptionInt(3)); + object->add_volume(cube(5.), ModelVolumeType::PARAMETER_MODIFIER, false)->config.apply(modifier_config); + print.apply(model, height_range_test_config(95.)); + print.process(); + + check_thin_dense_height_range(*print.objects().front(), 95.); +} diff --git a/tests/fff_print/test_skirt_brim.cpp b/tests/fff_print/test_skirt_brim.cpp index c732c54793..29326e9a49 100644 --- a/tests/fff_print/test_skirt_brim.cpp +++ b/tests/fff_print/test_skirt_brim.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include "libslic3r/Polygon.hpp" #include "libslic3r/Point.hpp" #include "libslic3r/Polyline.hpp" @@ -1409,22 +1410,30 @@ TEST_CASE("Belt brim coexists with support material", "[SkirtBrim][belt]") CHECK(role_passes(gc, "brim") > 0); } -// With a 0.3 mm first layer at 45 degrees the brim band on the belt is wider than one bead, -// so its lines go on the nominal lattice instead of at a fixed fraction of the band. A -// lattice line can then land where the belt is almost at the band's print_z; it must be -// moved uphill to the same 0.75 fraction the single-line case uses, not laid scraping the -// belt with its flow clamped to half a layer. +// On a shallow belt (25 degrees, 0.3 mm layers) the brim band on the belt is wider than one +// bead, so its lines go on the nominal lattice instead of at one fixed clearance. A lattice +// line can then land where the belt is almost at the band's print_z; it must be moved to the +// clearance of the object's outer wall, where every line of a steep belt sits, not laid +// scraping the belt with its flow clamped to half a layer. TEST_CASE("Belt brim lattice lines keep their clearance above the belt", "[SkirtBrim][belt]") { + const double layer_height = 0.3; + const double wall_width = 0.42; + const double tilt_deg = 25.; DynamicPrintConfig config = belt_brim_config(); config.set_deserialize_strict({ - { "layer_height", 0.3 }, - { "initial_layer_print_height", 0.3 }, + { "belt_slice_rotation_angle", tilt_deg }, + { "layer_height", layer_height }, + { "initial_layer_print_height", layer_height }, + { "outer_wall_line_width", wall_width }, { "brim_type", "outer_only" }, { "brim_width", 4 }, { "brim_object_gap", 0 }, }); const std::string gcode = slice({ cube(20) }, config); + // Along slice Z: half a layer down to where the slice meets the belt, then half a wall + // width inwards, where the belt lies lower by that times tan(tilt). + const double wall_clearance = 0.5 * layer_height + 0.5 * wall_width * std::tan(Geometry::deg2rad(tilt_deg)); // Heights of the brim extrusions, from the ;HEIGHT: tags inside ;TYPE:Brim sections. std::vector brim_heights; @@ -1437,12 +1446,246 @@ TEST_CASE("Belt brim lattice lines keep their clearance above the belt", "[Skirt brim_heights.push_back(std::stod(line.substr(8))); } REQUIRE(! brim_heights.empty()); + // Lattice lines have clearances of their own; a single clearance would mean the band + // took the steep-belt branch and the lattice went untested. + std::set distinct_heights; + for (const double h : brim_heights) + distinct_heights.insert(std::lround(h * 1000.)); + REQUIRE(distinct_heights.size() > 1); for (const double h : brim_heights) { - CHECK(h >= 0.75 * 0.3 - 1e-3); - CHECK(h <= 0.3 + 1e-3); + CHECK(h >= wall_clearance - 1e-3); + CHECK(h <= layer_height + 1e-3); } } +// Lowest gantry Y of the `type` extrusions on each layer, keyed by machine Z, which is the +// belt position and therefore one value per tilted layer. Under the belt remap the gantry is +// the height above the belt, so for a role resting on the belt this is its nozzle clearance. +static std::map belt_layer_lowest_y(const std::string &gcode, const std::string &type) +{ + std::map lowest; + bool in_type = false; + GCodeReader reader; + reader.parse_buffer(gcode, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) { + if (boost::starts_with(line.raw(), ";TYPE:")) { + in_type = line.raw().substr(6) == type; + return; + } + if (! in_type || ! line.extruding(self) || line.dist_XY(self) <= EPSILON) + return; + const double y = std::min(self.y(), line.new_Y(self)); + auto [it, inserted] = lowest.emplace(std::lround(line.new_Z(self) * 1000.), y); + if (! inserted) + it->second = std::min(it->second, y); + }); + return lowest; +} + +// The brim is the first thing laid on the belt, so it is what a user levels the belt height +// against (endstop, extruder offset). Its lines must then sit exactly as high above the belt +// as the object's outer wall does where it rests on the belt, or a belt levelled for the brim +// lays the part too high to stick. +TEST_CASE("Belt brim sits as high above the belt as the object's outer wall", "[SkirtBrim][belt][Regression]") +{ + const double layer_height = GENERATE(0.2, 0.32); + // A wider first-layer line widens only the walls of object layer 0, so it must not lift + // the brim off the walls of the layers that rest on the belt. 0 keeps the outer wall's. + const double first_width = GENERATE(0., 0.6); + // XY contour compensation moves the slice's edge, and with it the wall, toward or away + // from the belt, also by more than half the wall's width. Shrinking it by half a layer or + // more lifts it off the belt's contact band, and the object gets no brim. + const double compensation = GENERATE(0., 0.05, -0.05, 0.25); + DYNAMIC_SECTION("layer_height=" << layer_height << " initial_layer_line_width=" << first_width + << " xy_contour_compensation=" << compensation) { + const double wall_width = 0.4; + DynamicPrintConfig config = belt_brim_config(); + config.set_deserialize_strict({ + { "layer_height", layer_height }, + { "initial_layer_print_height", layer_height }, + { "outer_wall_line_width", wall_width }, + { "initial_layer_line_width", first_width }, + { "xy_contour_compensation", compensation }, + { "print_flow_ratio", 1 }, + { "brim_flow_ratio", 1 }, + { "filament_diameter", "1.75" }, + { "brim_type", "outer_only" }, + { "brim_width", 4 }, + { "brim_object_gap", 0 }, + }); + const std::string gcode = slice({ cube(20) }, config); + const std::map brim = belt_layer_lowest_y(gcode, "Brim"); + const std::map wall = belt_layer_lowest_y(gcode, "Outer wall"); + REQUIRE(! brim.empty()); + REQUIRE(! wall.empty()); + + // The wall's clearance on the layers it rests on the belt, i.e. the most common lowest + // Y. Not the lowest one: the sliver at the first contact can carry a narrower wall, + // which sits lower; and layers past the part's bottom face do not reach the belt. + std::map votes; + for (const auto &[z, y] : wall) + ++ votes[std::lround(y * 1000.)]; + const auto typical = std::max_element(votes.begin(), votes.end(), + [](const auto &a, const auto &b) { return a.second < b.second; }); + const double wall_y = 0.001 * typical->first; + for (const auto &[z, y] : brim) + CHECK_THAT(y, Catch::Matchers::WithinAbs(wall_y, 0.005)); + + // Each brim line fills the cell between it and the next, one band apart on the belt + // (the layer height / sin(45 deg)) and as tall as its clearance (its ;HEIGHT:), also + // where the clearance is small. + const double filament_area = 0.25 * PI * 1.75 * 1.75; + const double pitch = layer_height * std::sqrt(2.); + size_t long_moves = 0; + double clearance = 0.; + bool in_brim = false; + GCodeReader reader; + reader.parse_buffer(gcode, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) { + if (boost::starts_with(line.raw(), ";TYPE:")) + in_brim = line.raw().substr(6) == "Brim"; + else if (boost::starts_with(line.raw(), ";HEIGHT:")) + clearance = std::stod(line.raw().substr(8)); + else if (in_brim && line.extruding(self) && line.dist_XY(self) >= 1.) { + ++ long_moves; + CHECK_THAT(line.dist_E(self) / line.dist_XY(self) * filament_area, + Catch::Matchers::WithinRel(pitch * clearance, 0.01)); + } + }); + CHECK(long_moves > 20); + } +} + +// A modifier that gives the part a narrower outer wall away from the belt shares the tilted +// layers with the wall that rests on the belt. The brim must be levelled with the wall that +// rests on the belt, not with the narrowest wall in the layer. +TEST_CASE("Belt brim follows the wall that rests on the belt rather than a modifier's", "[SkirtBrim][belt][Regression]") +{ + DynamicPrintConfig config = belt_brim_config(); + config.set_deserialize_strict({ + { "gcode_comments", 1 }, + { "outer_wall_line_width", 0.6 }, + { "brim_type", "outer_only" }, + { "brim_width", 4 }, + { "brim_object_gap", 0 }, + }); + // The top half of the cube, 10 mm and more above the belt, gets a 0.4 mm outer wall. + DynamicPrintConfig modifier_config; + modifier_config.set_deserialize_strict({ { "outer_wall_line_width", 0.4 } }); + TriangleMesh modifier = make_cube(22., 22., 11.); + modifier.translate(-1.f, -1.f, 10.f); + Print print; + Model model; + init_print({ cube(20) }, print, model, config, nullptr, false); + model.objects.front()->add_volume(std::move(modifier), ModelVolumeType::PARAMETER_MODIFIER, false)->config.apply(modifier_config); + print.apply(model, config); + const std::string out = gcode(print); + + // Both walls print. + std::set wall_widths; + bool in_wall = false; + std::istringstream lines(out); + for (std::string line; std::getline(lines, line); ) { + if (boost::starts_with(line, ";TYPE:")) + in_wall = line.substr(6) == "Outer wall"; + else if (in_wall && boost::starts_with(line, ";WIDTH:")) + wall_widths.insert(std::lround(std::stod(line.substr(7)) * 100.)); + } + REQUIRE(wall_widths.count(40) == 1); + REQUIRE(wall_widths.count(60) == 1); + + const std::map brim = belt_layer_lowest_y(out, "Brim"); + const std::map wall = belt_layer_lowest_y(out, "Outer wall"); + REQUIRE(! brim.empty()); + std::map votes; + for (const auto &[z, y] : wall) + ++ votes[std::lround(y * 1000.)]; + const auto typical = std::max_element(votes.begin(), votes.end(), + [](const auto &a, const auto &b) { return a.second < b.second; }); + const double wall_y = 0.001 * typical->first; + // Half a 0.2 mm layer plus half the 0.6 mm wall, x tan(45 deg). + CHECK_THAT(wall_y, Catch::Matchers::WithinAbs(0.1 + 0.3, 0.005)); + for (const auto &[z, y] : brim) + CHECK_THAT(y, Catch::Matchers::WithinAbs(wall_y, 0.005)); +} + +// The brim rests on the belt, so it prints, and is reached, with first-layer settings, even +// though raising it to the outer wall's clearance puts the nozzle further above the belt than +// one first layer. With thin layers its lines are also far narrower than a bead, as narrow as +// the bands are far apart, so their width must not decide it either. +TEST_CASE("Belt brim lines print with first-layer settings", "[SkirtBrim][belt][Regression]") +{ + const double layer_height = GENERATE(0.2, 0.08); + CAPTURE(layer_height); + DynamicPrintConfig config = belt_brim_config(); + config.set_deserialize_strict({ + { "layer_height", layer_height }, + { "initial_layer_print_height", 0.2 }, + { "outer_wall_line_width", 0.45 }, + { "brim_type", "outer_only" }, + { "brim_width", 4 }, + { "brim_object_gap", 0 }, + { "z_hop", 0 }, + { "travel_speed", 200 }, + { "initial_layer_travel_speed", 50 }, + { "initial_layer_speed", 15 }, + { "filament_max_volumetric_speed", 20 }, + { "slow_down_for_layer_cooling", 0 }, + // The fan is on everywhere but in the band above the belt. + { "close_fan_the_first_x_layers", 1 }, + { "full_fan_speed_layer", 0 }, + { "fan_min_speed", 100 }, + { "fan_max_speed", 100 }, + { "fan_cooling_layer_time", 1000 }, + { "reduce_fan_stop_start_freq", 0 }, + }); + const std::string gcode = slice({ cube(20) }, config); + + // The feedrate of the last travel before each brim line, and the feedrate and fan of + // each of its moves. + size_t brim_lines = 0, fast_travels = 0, brim_moves = 0, brim_fast = 0, brim_fan_on = 0, fan_on_moves = 0; + std::string type; + double travel_f = 0.; + bool travelled = false, fan_on = false; + GCodeReader reader; + reader.parse_buffer(gcode, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) { + if (boost::starts_with(line.raw(), ";TYPE:")) { + type = line.raw().substr(6); + return; + } + if (line.cmd_is("M107")) { + fan_on = false; + return; + } + if (line.cmd_is("M106")) { + const size_t s = line.raw().find('S'); + fan_on = s != std::string::npos && std::atof(line.raw().c_str() + s + 1) > 0.; + return; + } + if (! line.cmd_is("G1") || line.dist_XY(self) <= EPSILON) + return; + if (! line.extruding(self)) { + travel_f = line.new_F(self); + travelled = true; + return; + } + fan_on_moves += fan_on; + if (type == "Brim") { + if (travelled) { + ++ brim_lines; + fast_travels += std::abs(travel_f - 50. * 60.) > 1.; + } + ++ brim_moves; + brim_fast += std::abs(line.new_F(self) - 15. * 60.) > 1.; + brim_fan_on += fan_on; + } + travelled = false; + }); + REQUIRE(brim_lines > 20); + REQUIRE(fan_on_moves > 0); + CHECK(fast_travels == 0); + CHECK(brim_fast == 0); + CHECK(brim_fan_on == 0); +} + // The brim prints in the object's outer wall filament even when every extrusion of the object // is offered to purging (flush_into_objects): the tool ordering registers the brim filament // itself, so the writer always knows it. diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index 2925c0dbef..a95b476341 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -8,6 +8,8 @@ add_executable(${_TEST_NAME}_tests ${_TEST_NAME}_tests.cpp test_3mf.cpp test_amf.cpp + # Import naming policy is independent of the GUI and slicing pipeline. + test_import_names.cpp # Round-trip seam metadata and active/dormant volume settings in both formats. test_precise_seam_3mf.cpp # Pure perimeter extraction is independent of Print/Layer fixtures. diff --git a/tests/libslic3r/test_3mf.cpp b/tests/libslic3r/test_3mf.cpp index c37e5e1d36..fedda45f64 100644 --- a/tests/libslic3r/test_3mf.cpp +++ b/tests/libslic3r/test_3mf.cpp @@ -9,6 +9,7 @@ #include "libslic3r/Model.hpp" #include "libslic3r/Format/3mf.hpp" #include "libslic3r/Format/bbs_3mf.hpp" +#include "libslic3r/Format/ProjectStrategy.hpp" #include "libslic3r/GCode/ThumbnailData.hpp" #include "libslic3r/Format/STL.hpp" #include "libslic3r/Utils.hpp" @@ -111,6 +112,128 @@ namespace Catch { using namespace Slic3r; +namespace { + +// A plain CAD archive exercises core object names without exporter-generated part metadata. +void write_named_cad_3mf(const std::string &path, bool project_part_names, bool leaf_names = true) +{ + std::string model = R"xml( + + + + + + + + + + + + + + + +)xml"; + if (!leaf_names) + for (const std::string label : {" name=\"Leaf2\"", " name=\"Leaf10\""}) + model.erase(model.find(label), label.size()); + Zipper archive(path); + archive.add_entry("[Content_Types].xml"); + archive << R"xml()xml"; + archive.add_entry("_rels/.rels"); + archive << R"xml()xml"; + archive.add_entry("3D/3dmodel.model", model.data(), model.size()); + if (project_part_names) { + // Conflicting names prove that project metadata takes priority over core mesh labels. + archive.add_entry("Metadata/model_settings.config"); + archive << R"xml( + + + +)xml"; + } + archive.finalize(); +} + +bool load_named_cad_3mf(const std::string &path, Model &model, LoadStrategy options) +{ + DynamicPrintConfig config; + ConfigSubstitutionContext substitutions(ForwardCompatibilitySubstitutionRule::Enable); + PlateDataPtrs plates; + std::vector presets; + bool is_bambu = false; + bool is_orca = false; + Semver version; + const bool loaded = load_bbs_3mf(path.c_str(), &config, &substitutions, &model, &plates, + &presets, &is_bambu, &is_orca, &version, nullptr, options); + release_PlateData_list(plates); + for (Preset *preset : presets) + delete preset; + return loaded; +} + +} // namespace + +TEST_CASE("CAD 3MF imports leaf names only when original names are enabled", "[3mf][OriginalNames]") +{ + const bool keep_names = GENERATE(false, true); + ScopedSlic3rTemporaryDir temporary_dir("orca_cad_names"); + ScopedTemporaryFile file(".3mf"); + write_named_cad_3mf(file.string(), false); + LoadStrategy options = LoadStrategy::LoadModel | LoadStrategy::AssembleParts; + if (keep_names) + options = options | LoadStrategy::KeepOriginalNames; + Model model; + REQUIRE(load_named_cad_3mf(file.string(), model, options)); + REQUIRE(model.objects.size() == 1); + CHECK(model.objects.front()->name == "Assembly"); + const auto &parts = model.objects.front()->volumes; + REQUIRE(parts.size() == 2); + CHECK(parts[0]->name == (keep_names ? "Leaf2" : "Assembly")); + CHECK(parts[1]->name == (keep_names ? "Leaf10" : "Assembly_2")); + // Different shapes and offsets prove name-to-geometry correspondence, not just a name set. + TriangleMesh first(parts[0]->mesh()); + TriangleMesh second(parts[1]->mesh()); + first.transform(parts[0]->get_matrix()); + second.transform(parts[1]->get_matrix()); + CHECK_THAT(first.bounding_box().size().x(), Catch::Matchers::WithinAbs(1.0, 1e-6)); + CHECK_THAT(second.bounding_box().size().x(), Catch::Matchers::WithinAbs(2.0, 1e-6)); + CHECK_THAT(second.bounding_box().min.x() - first.bounding_box().min.x(), Catch::Matchers::WithinAbs(10.0, 1e-6)); + CHECK_THAT(second.bounding_box().min.z() - first.bounding_box().min.z(), Catch::Matchers::WithinAbs(5.0, 1e-6)); +} + +TEST_CASE("A CAD 3MF without part labels keeps Orca's part names", "[3mf][OriginalNames]") +{ + ScopedSlic3rTemporaryDir temporary_dir("orca_cad_unnamed"); + ScopedTemporaryFile file(".3mf"); + write_named_cad_3mf(file.string(), false, false); + Model model; + REQUIRE(load_named_cad_3mf(file.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 2); + CHECK(model.objects.front()->volumes[0]->name == "Assembly"); + CHECK(model.objects.front()->volumes[1]->name == "Assembly_2"); +} + +TEST_CASE("3MF project part names take priority over CAD mesh names", "[3mf][OriginalNames]") +{ + const bool keep_names = GENERATE(false, true); + ScopedSlic3rTemporaryDir temporary_dir("orca_project_names"); + ScopedTemporaryFile file(".3mf"); + write_named_cad_3mf(file.string(), true); + LoadStrategy options = LoadStrategy::LoadModel; + if (keep_names) + options = options | LoadStrategy::KeepOriginalNames; + Model model; + REQUIRE(load_named_cad_3mf(file.string(), model, options)); + REQUIRE(model.objects.size() == 1); + CHECK(model.objects.front()->name == "ProjectAssembly"); + REQUIRE(model.objects.front()->volumes.size() == 2); + CHECK(model.objects.front()->volumes[0]->name == "UserPartA"); + CHECK(model.objects.front()->volumes[1]->name == "UserPartB"); +} + SCENARIO("Reading 3mf file", "[3mf]") { GIVEN("umlauts in the path of the file") { @@ -485,6 +608,46 @@ static bool load_project(const std::string& path, Model& model, const ScopedTemp return loaded; } +TEST_CASE("A single imported object retains hidden named bodies through cloning and project reload", "[3mf][OriginalNames]") +{ + const bool hidden = GENERATE(false, true); + ScopedSlic3rTemporaryDir temporary_dir("orca_hidden_parts"); + ScopedTemporaryDir backup_dir("orca_hidden_parts_reload"); + ScopedTemporaryFile file(".3mf"); + Model source; + ModelObject *object = source.add_object(); + object->name = "Assembly"; + object->add_volume(make_cube(1., 1., 1.))->name = "FirstBody"; + object->add_volume(make_cube(2., 2., 2.))->name = "SecondBody"; + object->add_instance(); + object->imported_parts_hidden = hidden; + + // Cloning must preserve the wrapper without collapsing its underlying independent bodies. + Model cloned(source); + REQUIRE(cloned.objects.size() == 1); + CHECK(cloned.objects.front()->imported_parts_hidden == hidden); + REQUIRE(cloned.objects.front()->volumes.size() == 2); + CHECK(cloned.objects.front()->volumes[0]->name == "FirstBody"); + CHECK(cloned.objects.front()->volumes[1]->name == "SecondBody"); + store_project(cloned, file.string(), SaveStrategy::Zip64 | SaveStrategy::Silence); + bool metadata_present = false; + rewrite_3mf_entries(file.string(), [&](std::string &name, std::string &data) { + if (boost::algorithm::ends_with(name, "model_settings.config")) + metadata_present = data.find("orca:imported_parts_hidden") != std::string::npos; + return false; + }); + CHECK(metadata_present == hidden); + + Model restored; + REQUIRE(load_project(file.string(), restored, backup_dir)); + REQUIRE(restored.objects.size() == 1); + CHECK(restored.objects.front()->imported_parts_hidden == hidden); + CHECK_FALSE(restored.objects.front()->config.has("orca:imported_parts_hidden")); + REQUIRE(restored.objects.front()->volumes.size() == 2); + CHECK(restored.objects.front()->volumes[0]->name == "FirstBody"); + CHECK(restored.objects.front()->volumes[1]->name == "SecondBody"); +} + TEST_CASE("A plate's G-code statistics are stored next to its G-code", "[3mf]") { const bool with_statistics = GENERATE(false, true); diff --git a/tests/libslic3r/test_amf.cpp b/tests/libslic3r/test_amf.cpp index eea678fc4a..f8b416894f 100644 --- a/tests/libslic3r/test_amf.cpp +++ b/tests/libslic3r/test_amf.cpp @@ -1,16 +1,28 @@ #include +#include +#include +#include +#include #include "libslic3r/Config.hpp" +#include "libslic3r/BoundingBox.hpp" #include "libslic3r/Format/AMF.hpp" +#include "libslic3r/Format/ProjectStrategy.hpp" #include "libslic3r/Model.hpp" #include "libslic3r/PrintConfig.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libslic3r/libslic3r.h" #include "test_utils.hpp" #include +#include +#include +#include #include #include +#include using namespace Slic3r; @@ -78,3 +90,554 @@ TEST_CASE("An AMF object metadata element with no type attribute is rejected", " CHECK_FALSE(load(tmp.string(), model)); } } + +namespace { + +// Reuse the tetrahedron fixture, giving object and volume deliberately different names. +std::string named_amf_object(int id, const std::string &object_name, const std::string &volume_name) +{ + std::string xml = amf_with_object_metadata("" + object_name + ""); + const size_t begin = xml.find(" ", begin) + std::string(" ").size() - begin); + const std::string id_attribute = "id=\"0\""; + xml.replace(xml.find(id_attribute), id_attribute.size(), "id=\"" + std::to_string(id) + "\""); + xml.insert(xml.find("") + std::string("").size(), + "" + volume_name + ""); + return xml; +} + +bool load_amf_with_options(const std::string &path, Model &model, LoadStrategy options) +{ + DynamicPrintConfig config; + ConfigSubstitutionContext substitutions(ForwardCompatibilitySubstitutionRule::Disable); + return load_amf(path.c_str(), &config, &substitutions, &model, nullptr, options); +} + +// Read the part's actual geometry in assembly coordinates, including importer centering. +BoundingBoxf3 amf_part_bounds(const ModelVolume &volume) +{ + TriangleMesh mesh(volume.mesh()); + mesh.transform(volume.get_matrix()); + return mesh.bounding_box(); +} + +} // namespace + +TEST_CASE("AMF assembly parts retain their volume names and instance transforms", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + "" + "" + "1052" + ""); + + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + const auto &parts = model.objects.front()->volumes; + REQUIRE(parts.size() == 2); + CHECK(parts[0]->name == "LeafA"); + CHECK(parts[1]->name == "LeafB"); + const BoundingBoxf3 first = amf_part_bounds(*parts[0]); + const BoundingBoxf3 second = amf_part_bounds(*parts[1]); + CHECK_THAT(first.min.x(), Catch::Matchers::WithinAbs(0.0, 1e-6)); + CHECK_THAT(first.min.z(), Catch::Matchers::WithinAbs(0.0, 1e-6)); + CHECK_THAT(second.min.x(), Catch::Matchers::WithinAbs(10.0, 1e-6)); + CHECK_THAT(second.min.z(), Catch::Matchers::WithinAbs(5.0, 1e-6)); + CHECK_THAT(second.size().x(), Catch::Matchers::WithinAbs(2.0, 1e-6)); + CHECK_THAT(second.size().z(), Catch::Matchers::WithinAbs(2.0, 1e-6)); +} + +TEST_CASE("AMF constellations preserve separate groups and repeated object occurrences", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + // The same definition is referenced twice in one group and again in another. + write_file(tmp.string(), "" + + named_amf_object(1, "SharedParent", "SharedLeaf") + named_amf_object(2, "Standalone", "Alone") + + "" + "10" + "30" + ""); + + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 3); + size_t repeated_groups = 0; + size_t distant_groups = 0; + size_t standalone_objects = 0; + for (const ModelObject *object : model.objects) { + if (object->name == "Standalone") { + ++standalone_objects; + REQUIRE(object->volumes.size() == 1); + CHECK(object->volumes.front()->name == "Alone"); + } else if (object->volumes.size() == 2) { + ++repeated_groups; + CHECK(object->volumes[0]->name == "SharedLeaf"); + CHECK(object->volumes[1]->name == "SharedLeaf"); + CHECK_THAT(amf_part_bounds(*object->volumes[1]).min.x() - + amf_part_bounds(*object->volumes[0]).min.x(), Catch::Matchers::WithinAbs(10.0, 1e-6)); + } else { + ++distant_groups; + REQUIRE(object->volumes.size() == 1); + CHECK(object->volumes.front()->name == "SharedLeaf"); + REQUIRE(object->instances.size() == 1); + CHECK_THAT(object->instance_bounding_box(0).min.x(), Catch::Matchers::WithinAbs(30.0, 1e-6)); + } + } + CHECK(repeated_groups == 1); + CHECK(distant_groups == 1); + CHECK(standalone_objects == 1); +} + +TEST_CASE("AMF assembly structure is independent of original name selection", "[AMF][OriginalNames]") +{ + const bool keep_names = GENERATE(false, true); + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + ""); + LoadStrategy options = LoadStrategy::LoadModel | LoadStrategy::AssembleParts; + if (keep_names) + options = options | LoadStrategy::KeepOriginalNames; + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, options)); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 2); + CHECK(model.objects.front()->volumes[0]->name == (keep_names ? "LeafA" : "ParentA")); + CHECK(model.objects.front()->volumes[1]->name == (keep_names ? "LeafB" : "ParentB")); +} + +TEST_CASE("AMF assemblies without placements are left for the GUI to centre on the bed", "[AMF][OriginalNames]") +{ + // CAD exporters list occurrences without deltas; the legacy loader then creates no instance either. + const bool merged = GENERATE(false, true); + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + "" + + std::string(merged ? "" : "") + ""); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + // Unreferenced object 2 of the single-occurrence case stays a separate object, as before. + REQUIRE(model.objects.size() == (merged ? 1 : 2)); + CHECK(model.objects.front()->volumes.size() == (merged ? 2 : 1)); + CHECK(model.objects.front()->instances.empty()); +} + +TEST_CASE("Unplaced excluded AMF assemblies keep their excluded instance", "[AMF][OriginalNames]") +{ + // Without an instance the GUI would add a printable one and print the excluded part. + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + "0" + "0"); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->instances.size() == 1); + CHECK_FALSE(model.objects.front()->instances.front()->printable); +} + +TEST_CASE("Multi-part detection compares unplaced AMF groups at zero height", "[AMF][OriginalNames]") +{ + // The GUI checks before it adds instances to unplaced objects, so they have no height on the bed yet; + // as before, they compare at zero and their mesh heights are ignored. + const bool placed = GENERATE(false, true); + const bool raised = GENERATE(false, true); + const std::string placement = placed ? "10" : ""; + // A placed object is raised by its placement; the GUI's centering moves the volumes, not the instance, so the rise stays. + const std::string raised_placement = placement + (placed && raised ? "10" : ""); + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + "" + placement + "" + "" + raised_placement + ""); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 2); + // An unplaced object can only be raised in its mesh. + if (raised && !placed) { + model.objects[1]->volumes.front()->translate(Vec3d(0., 0., 10.)); + model.objects[1]->invalidate_bounding_box(); + } + CHECK(model.looks_like_multipart_object() == (placed && raised)); + // The check must not place the objects; the GUI still centers unplaced ones later. + CHECK(model.objects[0]->instances.empty() == !placed); + CHECK(model.objects[1]->instances.empty() == !placed); +} + +TEST_CASE("Multi-part detection of mixed and centered unplaced AMF objects", "[AMF][OriginalNames]") +{ + // Either object comes first, so the result does not depend on which one sets the reference height. + const bool swapped = GENERATE(false, true); + const size_t first = swapped ? 1 : 0; + const size_t second = swapped ? 0 : 1; + // A placed object stands at its placement, and an unplaced one compares at zero, so they differ. + SECTION("mixed placement asks") { + const std::string unplaced = ""; + const std::string placed = "1010"; + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + "" + (swapped ? placed : unplaced) + "" + "" + (swapped ? unplaced : placed) + ""); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 2); + CHECK(model.looks_like_multipart_object()); + // The unplaced object comes from the first group unless swapped. + CHECK(model.objects[first]->instances.empty()); + CHECK(model.objects[second]->instances.size() == 1); + } + // The reviewer's case: unplaced objects of different heights after the GUI's rotation, which centers them. + SECTION("unplaced objects of different heights do not ask") { + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + ""); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, LoadStrategy::LoadModel | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 2); + model.objects[first]->volumes.front()->scale(Vec3d(1., 1., 4.)); + for (ModelObject *object : model.objects) { + object->invalidate_bounding_box(); + object->rotate(0., Axis::Z); + } + CHECK_FALSE(model.looks_like_multipart_object()); + CHECK(model.objects[0]->instances.empty()); + CHECK(model.objects[1]->instances.empty()); + } +} + +TEST_CASE("AMF assemblies with any placement keep their position from the file", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + "" + "10"); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->instances.size() == 1); + CHECK_THAT(model.objects.front()->instance_bounding_box(0).min.x(), Catch::Matchers::WithinAbs(0.0, 1e-6)); +} + +TEST_CASE("Legacy AMF loading keeps independent object definitions", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + ""); + Model model; + REQUIRE(load(tmp.string(), model)); + REQUIRE(model.objects.size() == 2); + CHECK(model.objects[0]->name == "ParentA"); + CHECK(model.objects[0]->volumes.front()->name == "LeafA"); + CHECK(model.objects[1]->name == "ParentB"); + CHECK(model.objects[1]->volumes.front()->name == "LeafB"); +} + +TEST_CASE("AMF mixed printable occurrences retain their individual printability", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + // Combining these occurrences into one printable instance would print an excluded part. + write_file(tmp.string(), "" + named_amf_object(1, "Parent", "Leaf") + + "" + "1" + "100" + ""); + + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 2); + size_t printable = 0; + size_t excluded = 0; + for (const ModelObject *object : model.objects) { + REQUIRE(object->volumes.size() == 1); + REQUIRE(object->instances.size() == 1); + CHECK(object->volumes.front()->name == "Leaf"); + const BoundingBoxf3 bounds = object->instance_bounding_box(0); + if (object->instances.front()->printable) { + ++printable; + CHECK_THAT(bounds.min.x(), Catch::Matchers::WithinAbs(0.0, 1e-6)); + } else { + ++excluded; + CHECK_THAT(bounds.min.x(), Catch::Matchers::WithinAbs(10.0, 1e-6)); + } + } + CHECK(printable == 1); + CHECK(excluded == 1); +} + +TEST_CASE("AMF constellations containing only excluded occurrences stay excluded", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "LeafA") + named_amf_object(2, "ParentB", "LeafB") + + "" + "0" + "100" + ""); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 2); + REQUIRE(model.objects.front()->instances.size() == 1); + CHECK_FALSE(model.objects.front()->instances.front()->printable); +} + +TEST_CASE("AMF assembly import skips unresolved constellation references like the legacy loader", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + named_amf_object(1, "Parent", "Leaf") + + named_amf_object(2, "Other", "OtherLeaf") + + "" + "10"); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + CHECK(model.objects.front()->volumes.size() == 2); +} + +TEST_CASE("AMF assembly import rejects cyclic constellation references", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + named_amf_object(1, "Parent", "Leaf") + + "" + ""); + Model model; + CHECK_FALSE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); +} + +TEST_CASE("AMF nested constellations flatten into one assembly with composed placements", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + // Group 20 is placed twice inside group 10; its own occurrence offset adds to each placement. + write_file(tmp.string(), "" + + named_amf_object(1, "Base", "BaseBody") + named_amf_object(2, "Pin", "PinBody") + + "" + "10" + "20" + "5"); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + // The nested group is not an assembly of its own. + REQUIRE(model.objects.size() == 1); + const auto &parts = model.objects.front()->volumes; + REQUIRE(parts.size() == 3); + CHECK(parts[0]->name == "BaseBody"); + CHECK(parts[1]->name == "PinBody"); + CHECK(parts[2]->name == "PinBody"); + CHECK_THAT(amf_part_bounds(*parts[1]).min.x() - amf_part_bounds(*parts[0]).min.x(), Catch::Matchers::WithinAbs(10.0, 1e-6)); + CHECK_THAT(amf_part_bounds(*parts[2]).min.x() - amf_part_bounds(*parts[0]).min.x(), Catch::Matchers::WithinAbs(20.0, 1e-6)); + CHECK_THAT(amf_part_bounds(*parts[1]).min.z() - amf_part_bounds(*parts[0]).min.z(), Catch::Matchers::WithinAbs(5.0, 1e-6)); +} + +TEST_CASE("AMF nested placements apply the parent transform to the child placement", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + // The nested group is mirrored in X; the child's own +5 shift must be mirrored with it. + write_file(tmp.string(), "" + + named_amf_object(1, "Base", "BaseBody") + named_amf_object(2, "Pin", "PinBody") + + "" + "-1" + "5"); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 2); + // parent * child puts the pin at x in [-6, -5]; child * parent would give [4, 5]. + CHECK_THAT(amf_part_bounds(*model.objects.front()->volumes[1]).max.x() - + amf_part_bounds(*model.objects.front()->volumes[0]).min.x(), Catch::Matchers::WithinAbs(-5.0, 1e-6)); +} + +TEST_CASE("AMF nested printability multiplies into the top-level group", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "Base", "BaseBody") + named_amf_object(2, "Pin", "PinBody") + + "" + "0" + ""); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + // A non-printable nested occurrence makes the group mixed, so its bodies stay separate objects. + REQUIRE(model.objects.size() == 2); + CHECK(model.objects[0]->instances.front()->printable); + CHECK_FALSE(model.objects[1]->instances.front()->printable); +} + +TEST_CASE("AMF assembly import loads files with duplicate or object-like constellation ids", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + // Group 1 shares its id with object 1, and two groups share id 10: references still resolve to the object. + write_file(tmp.string(), "" + named_amf_object(1, "Parent", "Leaf") + + "" + "10" + "20"); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + // Each single-occurrence group stays one object with its own placement. + CHECK(model.objects.size() == 3); +} + +TEST_CASE("AMF nesting that only multiplies work or depth is rejected", "[AMF][OriginalNames]") +{ + const bool deep = GENERATE(false, true); + // The order of declaration must not let a deep chain slip past the cycle check. + const bool leaf_first = GENERATE(false, true); + CAPTURE(deep, leaf_first); + ScopedTemporaryFile tmp(".amf"); + // Doubling chain: every group references the next twice and the last one reaches no body. + // Deep chain: one reference per level, deeper than any real assembly. + const int levels = deep ? 400 : 30; + std::vector chain; + for (int level = 0; level < levels; ++level) { + const std::string next = level + 1 < levels ? std::to_string(1000 + level + 1) : std::string("999"); + chain.push_back("" + + (deep ? std::string() : "") + ""); + } + if (leaf_first) + std::reverse(chain.begin(), chain.end()); + std::string groups; + for (const std::string &group : chain) + groups += group; + write_file(tmp.string(), "" + named_amf_object(1, "Parent", "Leaf") + groups + ""); + Model model; + CHECK_FALSE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); +} + +TEST_CASE("AMF assemblies are named after the file, with suffixes for later groups", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "First", "FirstBody") + named_amf_object(2, "Second", "SecondBody") + + "10" + "10" + ""); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 2); + const std::string file_name = boost::filesystem::path(tmp.string()).filename().string(); + CHECK(model.objects[0]->name == file_name); + CHECK(model.objects[1]->name == file_name + "_2"); + // The first body name is a part name, never the assembly name. + CHECK(model.objects[0]->volumes.front()->name == "FirstBody"); +} + +TEST_CASE("AMF preserves equal valid names belonging to different bodies", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(1, "ParentA", "Same") + named_amf_object(2, "ParentB", "Same") + + "" + "7"); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 2); + CHECK(model.objects.front()->volumes[0]->name == "Same"); + CHECK(model.objects.front()->volumes[1]->name == "Same"); + CHECK_THAT(amf_part_bounds(*model.objects.front()->volumes[1]).min.z() - + amf_part_bounds(*model.objects.front()->volumes[0]).min.z(), Catch::Matchers::WithinAbs(7.0, 1e-6)); +} + +TEST_CASE("AMF standalone multipart objects keep their volume metadata and definition order", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + std::string multipart = named_amf_object(9, "FirstDefinition", "FirstPart"); + const size_t volume_begin = multipart.find(""); + std::string second_volume = multipart.substr(volume_begin, + multipart.find("", volume_begin) + std::string("").size() - volume_begin); + second_volume.replace(second_volume.find("FirstPart"), std::string("FirstPart").size(), "SecondPart"); + multipart.insert(multipart.find(""), second_volume); + // Numeric IDs deliberately disagree with file order; neither object belongs to a constellation. + write_file(tmp.string(), "" + multipart + + named_amf_object(1, "SecondDefinition", "LastPart") + ""); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 2); + CHECK(model.objects[0]->name == "FirstDefinition"); + REQUIRE(model.objects[0]->volumes.size() == 2); + CHECK(model.objects[0]->volumes[0]->name == "FirstPart"); + CHECK(model.objects[0]->volumes[1]->name == "SecondPart"); + CHECK(model.objects[1]->name == "SecondDefinition"); + REQUIRE(model.objects[1]->volumes.size() == 1); + CHECK(model.objects[1]->volumes.front()->name == "LastPart"); +} + +TEST_CASE("Unnamed AMF assembly parts use the existing filename fallback", "[AMF][OriginalNames]") +{ + const bool keep_names = GENERATE(false, true); + ScopedTemporaryFile tmp(".amf"); + std::string objects = named_amf_object(1, "", "") + named_amf_object(2, "", ""); + const std::string empty_metadata = ""; + // No name metadata at either level: this matches the user's unmodified CAD AMF export. + for (size_t pos = objects.find(empty_metadata); pos != std::string::npos; pos = objects.find(empty_metadata)) + objects.erase(pos, empty_metadata.size()); + write_file(tmp.string(), "" + objects + + "" + "10"); + LoadStrategy options = LoadStrategy::LoadModel | LoadStrategy::AssembleParts; + if (keep_names) + options = options | LoadStrategy::KeepOriginalNames; + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, options)); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 2); + const std::string fallback = boost::filesystem::path(tmp.string()).filename().string(); + CHECK(model.objects.front()->name == fallback); + CHECK(model.objects.front()->volumes[0]->name == fallback); + CHECK(model.objects.front()->volumes[1]->name == fallback); + // Later splitting existing bodies into objects must retain these same ordinary names. + ModelObjectPtrs separated; + model.objects.front()->split(&separated, false); + REQUIRE(separated.size() == 2); + CHECK(separated[0]->name == fallback); + CHECK(separated[1]->name == fallback); +} + +TEST_CASE("AMF assemblies have no part settings of their own", "[AMF][OriginalNames]") +{ + ScopedTemporaryFile tmp(".amf"); + write_file(tmp.string(), "" + + named_amf_object(0, "ParentA", "LeafA") + named_amf_object(1, "ParentB", "LeafB") + + "10" + "20"); + Model model; + REQUIRE(load_amf_with_options(tmp.string(), model, + LoadStrategy::LoadModel | LoadStrategy::AssembleParts | LoadStrategy::KeepOriginalNames)); + REQUIRE(model.objects.size() == 1); + ModelObject& object = *model.objects.front(); + REQUIRE(object.volumes.size() == 3); + // Merging copies the object's filament to every part; repeating it is not a setting of the part. + CHECK_FALSE(object.has_individual_part_settings()); + object.imported_parts_hidden = true; + CHECK(object.hides_imported_parts()); + + object.volumes[1]->config.set("extruder", 2); + CHECK(object.has_individual_part_settings()); + CHECK_FALSE(object.hides_imported_parts()); +} diff --git a/tests/libslic3r/test_import_names.cpp b/tests/libslic3r/test_import_names.cpp new file mode 100644 index 0000000000..fb8eb2ee84 --- /dev/null +++ b/tests/libslic3r/test_import_names.cpp @@ -0,0 +1,63 @@ +#include + +#include "libslic3r/Format/ImportNames.hpp" + +#include +#include +#include + +using namespace Slic3r; + +TEST_CASE("Imported names preserve Unicode and XML escaping characters", "[ImportNames]") +{ + // Ampersands need XML escaping at serialization, not destructive renaming. + const std::vector names{u8"Шов & тело", u8"部品2", "Same", "Same", ""}; + CHECK(sanitize_import_names(names, "_") == names); + for (const auto& name : names) + CHECK_FALSE(has_unsupported_name_characters(name)); +} + +TEST_CASE("Each unsupported character accepts a complete replacement string", "[ImportNames]") +{ + // Multi-character replacement applies to each character, including adjacent ones. + CHECK(sanitize_import_names({"Part/A:B"}, "_slash_") == + std::vector{"Part_slash_A_slash_B"}); + CHECK(sanitize_import_names({"A//B"}, "xyz") == std::vector{"AxyzxyzB"}); + CHECK(sanitize_import_names({"A<>:/\\|?*\"B"}, "") == std::vector{"AB"}); +} + +TEST_CASE("Cleaning names resolves only newly introduced sibling collisions", "[ImportNames]") +{ + // Existing duplicates remain equal; a cleaned name cannot take an existing valid name. + const auto names = sanitize_import_names({"A/B", "AB", "AB", "A:B", "A/B", "AB (2)"}, ""); + REQUIRE(names.size() == 6); + CHECK(names[0] == "AB (3)"); + CHECK(names[1] == "AB"); + CHECK(names[2] == "AB"); + CHECK(names[3] == "AB (4)"); + CHECK(names[4] == names[0]); + CHECK(names[5] == "AB (2)"); +} + +TEST_CASE("Names emptied by cleaning receive a usable fallback", "[ImportNames]") +{ + // An unnamed input stays under the importer's existing fallback policy. + CHECK(sanitize_import_names({"///", "Part", ""}, "") == + std::vector{"Part (2)", "Part", ""}); + CHECK(sanitize_import_names({"///"}, "", "Assembly/part") == + std::vector{"Assemblypart"}); +} + +TEST_CASE("Name validation rejects unsupported replacement and malformed Unicode", "[ImportNames]") +{ + CHECK(valid_import_name_replacement("_slash_")); + CHECK(valid_import_name_replacement(u8"替换")); + CHECK_FALSE(valid_import_name_replacement("")); + CHECK_FALSE(valid_import_name_replacement("x/y")); + CHECK_FALSE(valid_import_name_replacement(std::string("x\x01", 2))); + CHECK_THROWS_AS(sanitize_import_names({"A/B"}, "/"), std::invalid_argument); + CHECK_THROWS_AS(sanitize_import_names({std::string("\xc3\x28", 2)}, "_"), std::invalid_argument); + CHECK(has_unsupported_name_characters(std::string("x\x01", 2))); + CHECK(has_unsupported_name_characters(u8"x\ufffe")); + CHECK_FALSE(has_unsupported_name_characters("\t\n\r")); +} diff --git a/tests/libslic3r/test_meshboolean.cpp b/tests/libslic3r/test_meshboolean.cpp index fc04ba27fc..ed5f938c7c 100644 --- a/tests/libslic3r/test_meshboolean.cpp +++ b/tests/libslic3r/test_meshboolean.cpp @@ -5,6 +5,8 @@ #include #include #include +#include +#include #include using namespace Slic3r; @@ -27,6 +29,41 @@ TEST_CASE("CGAL and TriangleMesh conversions", "[MeshBoolean]") { REQUIRE(! MeshBoolean::cgal::does_self_intersect(M)); } +TEST_CASE("CGAL volume checks ignore unreferenced vertices", "[MeshBoolean][Regression]") { + indexed_triangle_set mesh = its_make_cube(10., 10., 10.); + // Leave isolated vertices before, between, and after the vertices used by faces. + mesh.vertices.insert(mesh.vertices.begin(), Vec3f(-1.f, -1.f, -1.f)); + mesh.vertices.insert(mesh.vertices.begin() + 4, Vec3f(5.f, 5.f, 5.f)); + mesh.vertices.emplace_back(20.f, 20.f, 20.f); + for (Vec3i32 &face : mesh.indices) + for (int i = 0; i < 3; ++i) + face[i] += face[i] >= 3 ? 2 : 1; + + auto cgal_mesh = MeshBoolean::cgal::triangle_mesh_to_cgal(mesh); + REQUIRE(cgal_mesh); + REQUIRE(MeshBoolean::cgal::does_bound_a_volume(*cgal_mesh)); + REQUIRE_FALSE(MeshBoolean::cgal::does_self_intersect(*cgal_mesh)); + + TriangleMesh result = MeshBoolean::cgal::cgal_to_triangle_mesh(*cgal_mesh); + REQUIRE(result.its.indices.size() == mesh.indices.size()); + for (const Vec3i32 &face : result.its.indices) + for (int i = 0; i < 3; ++i) { + REQUIRE(face[i] >= 0); + REQUIRE(static_cast(face[i]) < result.its.vertices.size()); + } + REQUIRE_THAT(result.volume(), Catch::Matchers::WithinRel(1000., 1e-6)); +} + +TEST_CASE("CGAL volume checks reject open meshes with unreferenced vertices", "[MeshBoolean][Regression]") { + indexed_triangle_set mesh = its_make_cube(10., 10., 10.); + mesh.indices.pop_back(); + mesh.vertices.emplace_back(20.f, 20.f, 20.f); + + auto cgal_mesh = MeshBoolean::cgal::triangle_mesh_to_cgal(mesh); + REQUIRE(cgal_mesh); + REQUIRE_FALSE(MeshBoolean::cgal::does_bound_a_volume(*cgal_mesh)); +} + TEST_CASE("mcut difference handles source splits between cuts", "[MeshBoolean]") { TriangleMesh body = make_cube(30., 10., 10.); diff --git a/tests/libslic3r/test_step.cpp b/tests/libslic3r/test_step.cpp index ff8ce1dcba..45714e8cd5 100644 --- a/tests/libslic3r/test_step.cpp +++ b/tests/libslic3r/test_step.cpp @@ -3,12 +3,42 @@ #include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include +#include +#include +#include "libslic3r/BoundingBox.hpp" #include "libslic3r/Model.hpp" #include "libslic3r/Format/STEP.hpp" +#include "libslic3r/Format/ProjectStrategy.hpp" #include "libslic3r/TriangleMesh.hpp" #include "test_utils.hpp" @@ -112,6 +142,243 @@ TEST_CASE("A surface model imports whether or not compounds are split", "[Step]" CHECK(model.objects.front()->volumes.front()->mesh().facets_count() > 0); } +// Three tetrahedra share one product, while each BREP carries its own independent name. +TEST_CASE("Original STEP body names stay attached to their own compound geometry", "[Step][OriginalNames]") +{ + const bool keep_names = GENERATE(false, true); + const std::string path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR "named_compound_bodies.step"; + LoadStrategy strategy = LoadStrategy::LoadModel | LoadStrategy::AddDefaultInstances; + if (keep_names) + strategy = strategy | LoadStrategy::KeepOriginalNames; + + Model model = Model::read_from_step(path, strategy, nullptr, nullptr, nullptr, 0.003, 0.5, true); + REQUIRE(model.objects.size() == 1); + const ModelObject *object = model.objects.front(); + REQUIRE(object->volumes.size() == 3); + REQUIRE(object->instances.size() == 1); + + const std::array names = {"Part10", "Part2", "\xD0\xA2\xD0\xB5\xD0\xBB\xD0\xBE & shell"}; + for (size_t i = 0; i < names.size(); ++i) { + CAPTURE(i, keep_names); + const ModelVolume *volume = object->volumes[i]; + CHECK(volume->name == (keep_names ? names[i] : "Body collection-SOLID-" + std::to_string(i + 1))); + const BoundingBoxf3 bounds = volume->mesh().transformed_bounding_box(volume->get_matrix()); + // Distinct X positions verify identity, rather than only comparing the list of names. + CHECK_THAT(bounds.min.x(), Catch::Matchers::WithinAbs(25.0 * i, 1e-5)); + CHECK_THAT(bounds.max.x(), Catch::Matchers::WithinAbs(25.0 * i + 10.0, 1e-5)); + CHECK_THAT(bounds.size().y(), Catch::Matchers::WithinAbs(10.0, 1e-5)); + CHECK_THAT(bounds.size().z(), Catch::Matchers::WithinAbs(10.0, 1e-5)); + CHECK(volume->mesh().facets_count() == 4); + } +} + +TEST_CASE("A STEP body name takes precedence over its enclosing product name only when requested", "[Step][OriginalNames]") +{ + const bool keep_names = GENERATE(false, true); + const bool split = GENERATE(false, true); + CAPTURE(keep_names, split); + LoadStrategy strategy = LoadStrategy::LoadModel; + if (keep_names) + strategy = strategy | LoadStrategy::KeepOriginalNames; + + const std::string path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR "named_single_body.step"; + Model model = Model::read_from_step(path, strategy, nullptr, nullptr, nullptr, 0.003, 0.5, split); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 1); + CHECK(model.objects.front()->volumes.front()->name == (keep_names ? "Body name" : "Body collection")); + CHECK(model.objects.front()->volumes.front()->mesh().facets_count() == 4); + // A single part is not listed, so the object carries the body name; otherwise the file name stays. + CHECK(model.objects.front()->name == (keep_names ? std::string("Body name") : std::string("named_single_body.step"))); +} + +TEST_CASE("The STEP import dialog can change original names after loading the CAD document", "[Step][OriginalNames]") +{ + const bool initial_keep = GENERATE(false, true); + LoadStrategy strategy = LoadStrategy::LoadModel | LoadStrategy::AssembleParts; + if (initial_keep) + strategy = strategy | LoadStrategy::KeepOriginalNames; + const std::string path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR "named_single_body.step"; + auto callback = [initial_keep](Step& step, double&, double&, bool&) { + CHECK(step.keep_original_names() == initial_keep); + step.set_keep_original_names(!initial_keep); + return 1; + }; + Model model = Model::read_from_step(path, strategy, nullptr, nullptr, callback, 0.003, 0.5, true); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 1); + CHECK(model.objects.front()->volumes.front()->name == (initial_keep ? "Body collection" : "Body name")); +} + +TEST_CASE("STEP geometry import honours Split compound like the legacy import", "[Step][OriginalNames]") +{ + const bool split = GENERATE(false, true); + CAPTURE(split); + const std::string path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR "named_compound_bodies.step"; + Model model = Model::read_from_step(path, LoadStrategy::LoadModel | LoadStrategy::AssembleParts, + nullptr, nullptr, nullptr, 0.003, 0.5, split); + REQUIRE(model.objects.size() == 1); + if (split) { + REQUIRE(model.objects.front()->volumes.size() == 3); + CHECK(model.objects.front()->volumes[0]->name == "Body collection-SOLID-1"); + CHECK(model.objects.front()->volumes[1]->name == "Body collection-SOLID-2"); + } else { + // An unsplit compound stays one part, as before this feature. + REQUIRE(model.objects.front()->volumes.size() == 1); + CHECK(model.objects.front()->volumes.front()->name == "Body collection"); + } +} + +TEST_CASE("One body beside helper geometry keeps its name without Split compound", "[Step][OriginalNames]") +{ + const std::string source_path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR "named_single_body.step"; + boost::nowide::ifstream input(source_path, std::ios::binary); + REQUIRE(input.good()); + std::string data{std::istreambuf_iterator(input), std::istreambuf_iterator()}; + // A curve set next to the body makes OCCT return a compound that holds a single solid. + const std::string representation = "#20=FACETED_BREP_SHAPE_REPRESENTATION('',(#21,#22),#17);"; + const size_t representation_pos = data.find(representation); + REQUIRE(representation_pos != std::string::npos); + data.replace(representation_pos, representation.size(), + "#20=SHAPE_REPRESENTATION('',(#21,#22,#24),#17);\n#24=GEOMETRIC_CURVE_SET('',(#25));\n#25=POLYLINE('',(#30,#31));"); + ScopedTemporaryFile file(".step"); + { + boost::nowide::ofstream output(file.string(), std::ios::binary); + REQUIRE(output.good()); + output << data; + } + // Prove the fixture reaches the compound branch rather than the plain solid one. + STEPControl_Reader reader; + REQUIRE(reader.ReadFile(file.string().c_str()) == IFSelect_RetDone); + REQUIRE(reader.TransferRoots() > 0); + REQUIRE(reader.OneShape().ShapeType() == TopAbs_COMPOUND); + + Step step(file.string()); + REQUIRE(step.load(true) == Step::Step_Status::LOAD_SUCCESS); + CHECK_FALSE(step.has_multi_body_compound()); + + Model model = Model::read_from_step(file.string(), LoadStrategy::LoadModel | LoadStrategy::KeepOriginalNames, + nullptr, nullptr, nullptr, 0.003, 0.5, false); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 1); + CHECK(model.objects.front()->volumes.front()->name == "Body name"); + CHECK(model.objects.front()->name == "Body name"); + CHECK(model.objects.front()->volumes.front()->mesh().facets_count() == 4); +} + +TEST_CASE("A loaded STEP document reports its body labels and multi-body compounds", "[Step][OriginalNames]") +{ + const bool compound = GENERATE(false, true); + CAPTURE(compound); + const std::string path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR + + (compound ? "named_compound_bodies.step" : "named_single_body.step"); + Step step(path); + REQUIRE(step.load(true) == Step::Step_Status::LOAD_SUCCESS); + CHECK(step.has_original_names()); + // Only a compound of several bodies needs Split compound for its names. + CHECK(step.has_multi_body_compound() == compound); +} + +TEST_CASE("Empty STEP body names retain the product fallback and raw Unicode names survive", "[Step][OriginalNames]") +{ + const std::string body_name = GENERATE(std::string(), std::string("\xD0\xA2\xD0\xB5\xD0\xBB\xD0\xBE")); + const std::string source_path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR "named_single_body.step"; + boost::nowide::ifstream input(source_path, std::ios::binary); + REQUIRE(input.good()); + std::string data{std::istreambuf_iterator(input), std::istreambuf_iterator()}; + const size_t name_pos = data.find("'Body name'"); + REQUIRE(name_pos != std::string::npos); + // Change only the body metadata; the product label and geometry remain independent controls. + data.replace(name_pos, std::string("'Body name'").size(), "'" + body_name + "'"); + ScopedTemporaryFile file(".STEP"); + { + boost::nowide::ofstream output(file.string(), std::ios::binary); + REQUIRE(output.good()); + output << data; + } + Model model = Model::read_from_step(file.string(), LoadStrategy::LoadModel | LoadStrategy::KeepOriginalNames, + nullptr, nullptr, nullptr, 0.003, 0.5, true); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 1); + CHECK(model.objects.front()->volumes.front()->name == (body_name.empty() ? "Body collection" : body_name)); +} + +TEST_CASE("Equal STEP body names remain equal without losing their individual geometry", "[Step][OriginalNames]") +{ + const std::string source_path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR "named_compound_bodies.step"; + boost::nowide::ifstream input(source_path, std::ios::binary); + REQUIRE(input.good()); + std::string data{std::istreambuf_iterator(input), std::istreambuf_iterator()}; + const size_t name_pos = data.find("'Part2'"); + REQUIRE(name_pos != std::string::npos); + // Duplicate only the label, so matching by name would assign the wrong geometry to a sibling. + data.replace(name_pos, std::string("'Part2'").size(), "'Part10'"); + ScopedTemporaryFile file(".stp"); + { + boost::nowide::ofstream output(file.string(), std::ios::binary); + REQUIRE(output.good()); + output << data; + } + Model model = Model::read_from_step(file.string(), LoadStrategy::LoadModel | LoadStrategy::KeepOriginalNames, + nullptr, nullptr, nullptr, 0.003, 0.5, true); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 3); + for (size_t i = 0; i < 2; ++i) { + const ModelVolume *volume = model.objects.front()->volumes[i]; + CHECK(volume->name == "Part10"); + CHECK_THAT(volume->mesh().transformed_bounding_box(volume->get_matrix()).min.x(), + Catch::Matchers::WithinAbs(25.0 * i, 1e-5)); + } +} + +TEST_CASE("Repeated STEP assembly prototypes keep each instance placement", "[Step][OriginalNames]") +{ + ScopedTemporaryFile file(".step"); + Handle(TDocStd_Document) document; + const auto application = XCAFApp_Application::GetApplication(); + application->NewDocument(TCollection_ExtendedString("BinXCAF"), document); + const auto shape_tool = XCAFDoc_DocumentTool::ShapeTool(document->Main()); + const TDF_Label prototype = shape_tool->AddShape(BRepPrimAPI_MakeBox(10.0, 20.0, 30.0).Shape(), false); + TDataStd_Name::Set(prototype, "Repeated prototype"); + + TopoDS_Compound compound; + BRep_Builder builder; + builder.MakeCompound(compound); + const TDF_Label assembly = shape_tool->AddShape(compound, true); + TDataStd_Name::Set(assembly, "Assembly"); + gp_Trsf first_location; + first_location.SetTranslation(gp_Vec(25.0, 0.0, 5.0)); + shape_tool->AddComponent(assembly, prototype, TopLoc_Location(first_location)); + gp_Trsf second_location; + second_location.SetRotation(gp_Ax1(gp_Pnt(0.0, 0.0, 0.0), gp_Dir(0.0, 0.0, 1.0)), 0.5 * std::acos(-1.0)); + second_location.SetTranslationPart(gp_Vec(100.0, 40.0, 0.0)); + shape_tool->AddComponent(assembly, prototype, TopLoc_Location(second_location)); + shape_tool->UpdateAssemblies(); + + STEPCAFControl_Writer writer; + REQUIRE(writer.Transfer(document)); + REQUIRE(writer.Write(file.string().c_str()) == IFSelect_RetDone); + application->Close(document); + + Model model = Model::read_from_step(file.string(), LoadStrategy::LoadModel | LoadStrategy::KeepOriginalNames, + nullptr, nullptr, nullptr, 0.003, 0.5, true); + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 2); + // Both volumes use the shared prototype name; their independent transforms must not be merged. + for (const ModelVolume *volume : model.objects.front()->volumes) + CHECK(volume->name == "Repeated prototype"); + const auto first = model.objects.front()->volumes[0]; + const auto second = model.objects.front()->volumes[1]; + const auto first_bounds = first->mesh().transformed_bounding_box(first->get_matrix()); + const auto second_bounds = second->mesh().transformed_bounding_box(second->get_matrix()); + CHECK_THAT(first_bounds.min.x(), Catch::Matchers::WithinAbs(25.0, 1e-5)); + CHECK_THAT(first_bounds.min.z(), Catch::Matchers::WithinAbs(5.0, 1e-5)); + CHECK_THAT(first_bounds.size().x(), Catch::Matchers::WithinAbs(10.0, 1e-5)); + CHECK_THAT(second_bounds.min.x(), Catch::Matchers::WithinAbs(80.0, 1e-5)); + CHECK_THAT(second_bounds.min.y(), Catch::Matchers::WithinAbs(40.0, 1e-5)); + CHECK_THAT(second_bounds.size().x(), Catch::Matchers::WithinAbs(20.0, 1e-5)); + CHECK_THAT(second_bounds.size().y(), Catch::Matchers::WithinAbs(10.0, 1e-5)); +} + TEST_CASE("isUtf8 recognises two, three and four byte sequences", "[Step]") { CHECK(StepPreProcessor::isUtf8("\xC3\xA9")); // U+00E9 diff --git a/tests/libslic3r/test_timeutils.cpp b/tests/libslic3r/test_timeutils.cpp index 9550740fa8..26f682596b 100644 --- a/tests/libslic3r/test_timeutils.cpp +++ b/tests/libslic3r/test_timeutils.cpp @@ -11,8 +11,11 @@ static void test_time_fmt(Slic3r::Utils::TimeFormat fmt) { using namespace Slic3r::Utils; - time_t t = get_current_time_utc(); - + // A fixed mid-year time (2019-07-10 08:50:00 UTC) rather than the current one: local + // time text can't tell apart the hour that repeats when daylight saving ends, so the + // local round trip would fail during that hour. + time_t t = 1562748600; + std::string tstr = time2str(t, TimeZone::local, fmt); time_t parsedtime = str2time(tstr, TimeZone::local, fmt); REQUIRE(t == parsedtime); diff --git a/tests/libslic3r/test_vendor_cache.cpp b/tests/libslic3r/test_vendor_cache.cpp index b78ce77e1f..ee590f823f 100644 --- a/tests/libslic3r/test_vendor_cache.cpp +++ b/tests/libslic3r/test_vendor_cache.cpp @@ -15,6 +15,7 @@ #include #include "libslic3r/Semver.hpp" #include "libslic3r/Config.hpp" +#include "libslic3r/PrintConfig.hpp" #include #include #include @@ -36,7 +37,6 @@ #include "libslic3r/PresetBundle.hpp" #include "libslic3r/PresetCacheFormat.hpp" #include "libslic3r/Preset.hpp" -#include "libslic3r/PrintConfig.hpp" #include "libslic3r/Utils.hpp" using namespace Slic3r; @@ -1958,35 +1958,151 @@ TEST_CASE("an option the build no longer knows is dropped, and the rest still lo CHECK(out.opt_string("printer_model") == "Test Model"); } -TEST_CASE("an option whose type changed is dropped, and the rest still load", "[VendorCache]") +namespace { + +// A payload from a build whose dictionary this build did not produce: only +// such a dictionary can type a key differently from print_config_def. `write` +// emits the option values in the order of `keys`. +DynamicPrintConfig load_foreign_payload(const std::vector& keys, const std::vector& types, + const std::vector& enum_names, + const std::function& write) { - // A payload from a build where layer_height was a coString. This one has it - // as a coFloat, so nothing can be done with the value - but the dictionary - // says how it was written, so its bytes are still consumed and printer_model - // behind it still lands. Hand-written rather than round-tripped: only a - // dictionary this build did not produce can disagree with it. std::ostringstream os(std::ios::binary); { cereal::BinaryOutputArchive ar(os); - const std::vector keys { "layer_height", "printer_model" }; - const std::vector types { uint16_t(coString), uint16_t(coString) }; - const std::vector enums { std::string() }; // the ENUM_UNNAMED slot + std::vector enums { std::string() }; // the ENUM_UNNAMED slot + enums.insert(enums.end(), enum_names.begin(), enum_names.end()); ar(keys, types, enums); - ar(uint32_t(2)); - ar(uint16_t(0)); ar(ConfigOptionString("0.28")); - ar(uint16_t(1)); ar(ConfigOptionString("Test Model")); + ar(uint32_t(keys.size())); + write(ar); } - std::istringstream is(os.str(), std::ios::binary); cereal::BinaryInputArchive ar(is); CacheDictionary rdict; rdict.load(ar); DynamicPrintConfig out; REQUIRE_NOTHROW(load_config(ar, out, rdict)); - CHECK(out.option("layer_height") == nullptr); + return out; +} + +} // namespace + +TEST_CASE("an option whose type changed is read as a JSON profile's text, and the rest still load", "[VendorCache]") +{ + // A payload from a build where layer_height was a coString. This one has it + // as a coFloat, so the value goes in as the text "0.28" would from a JSON + // profile, and printer_model behind it still lands. + REQUIRE(print_config_def.get("layer_height")->type == coFloat); + const DynamicPrintConfig out = load_foreign_payload( + { "layer_height", "printer_model" }, { uint16_t(coString), uint16_t(coString) }, {}, + [](cereal::BinaryOutputArchive& ar) { + ar(uint16_t(0)); ar(ConfigOptionString("0.28")); + ar(uint16_t(1)); ar(ConfigOptionString("Test Model")); + }); + REQUIRE(out.option("layer_height") != nullptr); + CHECK_THAT(out.opt_float("layer_height"), Catch::Matchers::WithinAbs(0.28, 1e-9)); CHECK(out.opt_string("printer_model") == "Test Model"); } +TEST_CASE("a bool an older build cached is read by the enum that replaced it", "[VendorCache]") +{ + // enable_arc_fitting was a coBool until it became an enum. A cache written + // before that carries true/false; this build maps them through handle_legacy + // to enabled/disabled, as it does for a JSON profile, instead of dropping the + // key and leaving the preset at the collection default. + REQUIRE(print_config_def.get("enable_arc_fitting")->type == coEnum); + const DynamicPrintConfig out = load_foreign_payload( + { "enable_arc_fitting", "printer_model" }, { uint16_t(coBool), uint16_t(coString) }, {}, + [](cereal::BinaryOutputArchive& ar) { + ar(uint16_t(0)); ar(ConfigOptionBool(true)); + ar(uint16_t(1)); ar(ConfigOptionString("Test Model")); + }); + REQUIRE(out.option("enable_arc_fitting") != nullptr); + CHECK(out.option("enable_arc_fitting")->serialize() == "enabled"); + CHECK(out.opt_string("printer_model") == "Test Model"); +} + +TEST_CASE("an enum a newer build cached is read by the bool this build still has", "[VendorCache]") +{ + // The other direction: a cache from a build that turned a bool into an enum, + // read by a build where the key is still a bool. The enum travels by name, + // and the name is substituted the way a JSON profile's would be. + REQUIRE(print_config_def.get("reduce_crossing_wall")->type == coBool); + const DynamicPrintConfig out = load_foreign_payload( + { "reduce_crossing_wall", "printer_model" }, { uint16_t(coEnum), uint16_t(coString) }, { "enabled" }, + [](cereal::BinaryOutputArchive& ar) { + ar(uint16_t(0)); ar(uint32_t(1)); ar(uint16_t(1)); // one value, enum name index 1 = "enabled" + ar(uint16_t(1)); ar(ConfigOptionString("Test Model")); + }); + REQUIRE(out.option("reduce_crossing_wall") != nullptr); + CHECK(out.opt_bool("reduce_crossing_wall") == true); + CHECK(out.opt_string("printer_model") == "Test Model"); +} + +TEST_CASE("a retyped value this build cannot parse is dropped, and the rest still load", "[VendorCache]") +{ + // A string that is no number for a key this build types as a float: nothing + // to substitute it with, so the key alone is dropped, as from a JSON profile. + REQUIRE(print_config_def.get("layer_height")->type == coFloat); + const DynamicPrintConfig out = load_foreign_payload( + { "layer_height", "printer_model" }, { uint16_t(coString), uint16_t(coString) }, {}, + [](cereal::BinaryOutputArchive& ar) { + ar(uint16_t(0)); ar(ConfigOptionString("thick")); + ar(uint16_t(1)); ar(ConfigOptionString("Test Model")); + }); + CHECK(out.option("layer_height") == nullptr); + CHECK(out.keys() == t_config_option_keys{ "printer_model" }); +} + +TEST_CASE("a nullable vector cached under another type keeps its nil entries", "[VendorCache]") +{ + // default_acceleration is a nullable coFloats. Written as coInts by a build + // that typed it so, its nil entry must come back as nil, not as the int the + // sentinel happens to be. + const ConfigOptionDef* def = print_config_def.get("default_acceleration"); + REQUIRE(def->type == coFloats); + REQUIRE(def->nullable); + const DynamicPrintConfig out = load_foreign_payload( + { "default_acceleration", "printer_model" }, { uint16_t(coInts), uint16_t(coString) }, {}, + [](cereal::BinaryOutputArchive& ar) { + ar(uint16_t(0)); ar(ConfigOptionInts({ ConfigOptionIntsNullable::nil_value(), 5000 })); + ar(uint16_t(1)); ar(ConfigOptionString("Test Model")); + }); + const auto* accel = out.option("default_acceleration"); + REQUIRE(accel != nullptr); + REQUIRE(accel->values.size() == 2); + CHECK(accel->is_nil(0)); + CHECK_THAT(accel->values[1], Catch::Matchers::WithinAbs(5000., 1e-9)); + CHECK(out.opt_string("printer_model") == "Test Model"); +} + +TEST_CASE("skip_config consumes a config with options this build cannot place", "[VendorCache]") +{ + // The entries a name peek reads past may be ones this build would replay + // from text; skipping must still consume exactly their bytes. + std::ostringstream os(std::ios::binary); + { + cereal::BinaryOutputArchive ar(os); + const std::vector keys { "enable_arc_fitting", "sparse_infill_pattern", "no_such_option" }; + const std::vector types { uint16_t(coBool), uint16_t(coEnum), uint16_t(coString) }; + const std::vector enums { std::string(), "zig-zag" }; + ar(keys, types, enums); + ar(uint32_t(3)); + ar(uint16_t(0)); ar(ConfigOptionBool(true)); + ar(uint16_t(1)); ar(uint32_t(1)); ar(uint16_t(1)); + ar(uint16_t(2)); ar(ConfigOptionString("x")); + ar(std::string("sentinel")); + } + std::istringstream is(os.str(), std::ios::binary); + cereal::BinaryInputArchive ar(is); + CacheDictionary rdict; + rdict.load(ar); + skip_config(ar, rdict); + std::string sentinel; + ar(sentinel); + CHECK(sentinel == "sentinel"); +} + TEST_CASE("skip_config consumes a config without building one", "[VendorCache]") { DynamicPrintConfig in; diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index acdde05586..2d3040b406 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -75,6 +75,7 @@ add_executable(${_TEST_NAME}_tests test_user_manager.cpp test_sequential_clearance.cpp test_object_list.cpp + test_geometry_import.cpp ../fff_print/test_helpers.cpp ) diff --git a/tests/slic3rutils/test_geometry_import.cpp b/tests/slic3rutils/test_geometry_import.cpp new file mode 100644 index 0000000000..70c32f1bae --- /dev/null +++ b/tests/slic3rutils/test_geometry_import.cpp @@ -0,0 +1,141 @@ +#include +#include +#include + +#include "slic3r/GUI/GeometryImportDialog.hpp" +#include "libslic3r/AppConfig.hpp" +#include "libslic3r/Zipper.hpp" +#include "test_utils.hpp" + +#include + +using namespace Slic3r; +using namespace Slic3r::GUI; + +TEST_CASE("CAD 3MF routing recognizes project markers without reading geometry", "[GeometryImport]") +{ + const std::string marker = GENERATE(std::string(), std::string("Metadata/model_settings.config"), + std::string("Metadata/project_settings.config"), std::string("Metadata/Slic3r_PE.config"), + std::string("Metadata/Slic3r_PE_model.config")); + CAPTURE(marker); + ScopedTemporaryFile file(".3mf"); + Zipper archive(file.string()); + // Directory-only classification must not triangulate or parse this placeholder mesh. + archive.add_entry("3D/3dmodel.model"); + archive << ""; + if (!marker.empty()) { + archive.add_entry(marker); + archive << "{}"; + } + archive.finalize(); + CHECK(is_geometry_only_3mf(file.string()) == marker.empty()); +} + +TEST_CASE("Geometry import choices distinguish remembering from suppressing questions", "[GeometryImport]") +{ + const std::string format = GENERATE(std::string("step"), std::string("amf"), std::string("3mf")); + const bool remember = GENERATE(false, true); + const bool dont_ask = GENERATE(false, true); + CAPTURE(format, remember, dont_ask); + AppConfig config; + const std::string prefix = "import_names_" + format + "_"; + const std::string show = format == "step" ? "enable_step_mesh_setting" : prefix + "show_dialog"; + config.set_bool(prefix + "keep", false); + config.set_bool(prefix + "sort", false); + config.set_bool(prefix + "assembly", false); + config.set_bool("is_split_compound", false); + config.set_bool(show, true); + GeometryImportOptions options; + options.keep_names = true; + options.sort_names = true; + options.load_as_assembly = true; + options.split_compound = true; + options.chosen = true; + options.remember = remember; + options.dont_ask = dont_ask; + save_geometry_import_options(config, format, options); + // Suppression must persist the action even with Remember my choice unchecked. + const bool persisted = remember || dont_ask; + CHECK(config.get_bool(prefix + "keep") == persisted); + CHECK(config.get_bool(prefix + "sort") == persisted); + // A 3MF keeps its own structure, so it has no presentation choice to remember. + CHECK(config.get_bool(prefix + "assembly") == (persisted && format != "3mf")); + // Reading side: a 3MF keeps the structure written in it whatever the stored key says. + CHECK(geometry_import_options(config, format).load_as_assembly == (format == "3mf" || persisted)); + CHECK(config.get_bool("is_split_compound") == (persisted && format == "step")); + CHECK(config.get_bool(show) == !dont_ask); +} + +TEST_CASE("Sorting disabled by Keep original names keeps its remembered value", "[GeometryImport]") +{ + const std::string format = GENERATE(std::string("step"), std::string("amf"), std::string("3mf")); + CAPTURE(format); + AppConfig config; + const std::string prefix = "import_names_" + format + "_"; + config.set_bool(prefix + "sort", true); + GeometryImportOptions options; + options.keep_names = false; + options.sort_names = false; + options.chosen = true; + options.remember = true; + save_geometry_import_options(config, format, options); + CHECK_FALSE(config.get_bool(prefix + "keep")); + CHECK(config.get_bool(prefix + "sort")); +} + +TEST_CASE("Name cleanup remembers the complete replacement string", "[GeometryImport]") +{ + const bool remember = GENERATE(false, true); + const bool dont_ask = GENERATE(false, true); + AppConfig config; + config.set("import_names_cleanup_replacement", "_"); + config.set_bool("import_names_cleanup_remove", true); + config.set_bool("import_names_cleanup_show_dialog", true); + GeometryImportNamePolicy policy; + policy.used = true; + policy.remove = false; + policy.replacement = "_slash_"; + policy.remember = remember; + policy.dont_ask = dont_ask; + save_geometry_import_name_policy(config, policy); + const bool persisted = remember || dont_ask; + CHECK(config.get("import_names_cleanup_replacement") == (persisted ? "_slash_" : "_")); + CHECK(config.get_bool("import_names_cleanup_remove") == !persisted); + CHECK(config.get_bool("import_names_cleanup_show_dialog") == !dont_ask); +} + +TEST_CASE("Geometry import treats STEP and STP extensions as the same format", "[GeometryImport]") +{ + CHECK(geometry_import_format("model.STEP") == "step"); + CHECK(geometry_import_format("model.sTp") == "step"); + CHECK(geometry_import_format("model.AMF") == "amf"); + CHECK(geometry_import_format("model.3MF") == "3mf"); + CHECK(geometry_import_format("model.stl").empty()); +} + +TEST_CASE("AMF loads separate objects unless an assembly mode was chosen", "[GeometryImport]") +{ + AppConfig config; + // Files from other slicers hold a whole plate in one group, so the default keeps them apart. + CHECK(geometry_import_options(config, "amf").separate_objects); + CHECK_FALSE(geometry_import_options(config, "amf").single_object()); + CHECK_FALSE(geometry_import_options(config, "step").separate_objects); + CHECK_FALSE(geometry_import_options(config, "3mf").separate_objects); + + const bool separate = GENERATE(false, true); + const bool assembly = GENERATE(false, true); + CAPTURE(separate, assembly); + config.set_bool("import_names_amf_assembly", !assembly); + GeometryImportOptions options; + options.separate_objects = separate; + options.load_as_assembly = assembly; + options.chosen = true; + options.remember = true; + save_geometry_import_options(config, "amf", options); + const GeometryImportOptions restored = geometry_import_options(config, "amf"); + CHECK(restored.separate_objects == separate); + CHECK(restored.load_as_assembly == assembly); + CHECK(restored.single_object() == (!separate && !assembly)); + // The STEP dialog has no separate mode and keeps its own key. + CHECK_FALSE(config.has("import_names_step_separate")); +} diff --git a/tests/slic3rutils/test_object_list.cpp b/tests/slic3rutils/test_object_list.cpp index 0552d0eabb..16e41cfabe 100644 --- a/tests/slic3rutils/test_object_list.cpp +++ b/tests/slic3rutils/test_object_list.cpp @@ -1,12 +1,16 @@ #include +#include +#include #include "slic3r/GUI/GUI_ObjectList.hpp" #include #include #include +#include #include +#include #include using namespace Slic3r; @@ -88,3 +92,110 @@ TEST_CASE("Objects sort by bounding box volume", "[ObjectList]") CHECK(sorted_names(model, ObjectOrder::Size) == std::vector{"cube", "tall", "flat"}); } + +TEST_CASE("Imported part names sort only their presentation and survive cloning", "[ObjectList][OriginalNames]") +{ + Model model; + ModelObject* object = model.add_object(); + // Include a modifier to ensure display sorting never changes its slicing precedence. + auto* ten = object->add_volume(make_cube(10., 10., 10.)); + ten->name = "Part10"; + auto* two = object->add_volume(make_cube(2., 2., 2.)); + two->name = "part2"; + auto* duplicate = object->add_volume(make_cube(3., 3., 3.)); + duplicate->name = "part2"; + duplicate->set_type(ModelVolumeType::PARAMETER_MODIFIER); + const auto slicing_order = object->volumes; + set_import_volume_order(*object, true); + CHECK(object->volumes == slicing_order); + CHECK(two->import_display_order < duplicate->import_display_order); + CHECK(duplicate->import_display_order < ten->import_display_order); + + Model clone; + const ModelObject* copied = clone.add_object(*object); + REQUIRE(copied->volumes.size() == object->volumes.size()); + for (size_t i = 0; i < copied->volumes.size(); ++i) { + CHECK(copied->volumes[i]->id() != object->volumes[i]->id()); + CHECK(copied->volumes[i]->import_display_order == object->volumes[i]->import_display_order); + } +} + +TEST_CASE("Unsorted imports preserve source presentation through type grouping", "[ObjectList][OriginalNames]") +{ + Model model; + ModelObject* object = model.add_object(); + auto* modifier = object->add_volume(make_cube(2., 2., 2.)); + modifier->name = "Z modifier"; + modifier->set_type(ModelVolumeType::PARAMETER_MODIFIER); + auto* part = object->add_volume(make_cube(10., 10., 10.)); + part->name = "A part"; + set_import_volume_order(*object, false); + object->sort_volumes(true); + CHECK(object->volumes.front() == part); + CHECK(modifier->import_display_order < part->import_display_order); +} + +TEST_CASE("Adding a part or modifier reveals a single-object import", "[ObjectList][OriginalNames]") +{ + const auto type = GENERATE(ModelVolumeType::MODEL_PART, ModelVolumeType::PARAMETER_MODIFIER); + Model model; + ModelObject* object = model.add_object(); + object->add_volume(make_cube(10., 10., 10.)); + object->add_volume(make_cube(2., 2., 2.)); + object->imported_parts_hidden = true; + // An editing operation must not leave the newly added, effective geometry invisible. + object->add_volume(make_cube(3., 3., 3.), type); + CHECK_FALSE(object->imported_parts_hidden); + REQUIRE(object->volumes.size() == 3); + CHECK(object->volumes.back()->type() == type); +} + +TEST_CASE("Part settings show a single-object import without changing it", "[ObjectList][OriginalNames]") +{ + Model model; + ModelObject* object = model.add_object(); + object->add_volume(make_cube(10., 10., 10.)); + ModelVolume* body = object->add_volume(make_cube(2., 2., 2.)); + object->imported_parts_hidden = true; + REQUIRE(object->hides_imported_parts()); + + // The check only reads the object: the stored choice survives while part settings show the parts. + body->config.set("wall_loops", 3); + CHECK_FALSE(object->hides_imported_parts()); + CHECK(object->imported_parts_hidden); + CHECK(body->config.has("wall_loops")); + + body->config.erase("wall_loops"); + CHECK(object->hides_imported_parts()); + + TriangleSelector selector(body->mesh()); + selector.set_facet(0, EnforcerBlockerType::ENFORCER); + REQUIRE(body->seam_facets.set(selector)); + CHECK_FALSE(object->hides_imported_parts()); + CHECK(object->imported_parts_hidden); + + body->seam_facets.reset(); + CHECK(object->hides_imported_parts()); +} + +TEST_CASE("A part that repeats the object's filament has no settings of its own", "[ObjectList][OriginalNames]") +{ + struct Case { int object_filament; int part_filament; bool extra_setting; bool individual; }; + // object_filament 0 means no object filament, which prints with filament 1. + const Case c = GENERATE(Case{0, 1, false, false}, Case{2, 2, false, false}, Case{2, 0, false, false}, + Case{2, 1, false, true}, Case{0, 2, false, true}, Case{2, 2, true, true}); + CAPTURE(c.object_filament, c.part_filament, c.extra_setting); + Model model; + ModelObject* object = model.add_object(); + object->config.erase("extruder"); + if (c.object_filament > 0) + object->config.set("extruder", c.object_filament); + object->add_volume(make_cube(10., 10., 10.)); + ModelVolume* body = object->add_volume(make_cube(2., 2., 2.)); + body->config.set("extruder", c.part_filament); + if (c.extra_setting) + body->config.set("wall_loops", 3); + object->imported_parts_hidden = true; + CHECK(object->has_individual_part_settings() == c.individual); + CHECK(object->hides_imported_parts() == !c.individual); +} diff --git a/tests/slic3rutils/test_plugin_install.cpp b/tests/slic3rutils/test_plugin_install.cpp index ac7f826ed8..122b0e1281 100644 --- a/tests/slic3rutils/test_plugin_install.cpp +++ b/tests/slic3rutils/test_plugin_install.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include "catch2/catch_message.hpp" @@ -19,6 +20,7 @@ #include #include +#include #include @@ -107,6 +109,30 @@ TEST_CASE("install_plugin accepts a side-loaded .py with complete PEP 723 metada CHECK(error.empty()); } +TEST_CASE("a .py plugin's PEP 723 dependencies split only at the commas between items", "[PluginInstall][PluginFsUtils]") +{ + // Each layout holds the same two items; the first has a comma inside its quotes, as a version + // range does, and the comments hold commas too. + const std::string array = GENERATE(std::string("[\"numpy>=1.20,<2\", 'pillow']\n"), + std::string("[\n# \"numpy>=1.20,<2\",\n# \"pillow\",\n# ]\n"), + std::string("[\n# \"numpy>=1.20,<2\", \"pillow\",\n# ]\n"), + std::string("[\"numpy>=1.20,<2\",\n# \"pillow\",\n# ]\n"), + std::string("[ # runtime, pinned\n" + "# \"numpy>=1.20,<2\", # below 2, for now\n" + "# 'pillow']\n")); + ScopedTemporaryDir dir("pep723-deps"); + const fs::path py = write_py_file(dir.path(), "deps.py", + "# /// script\n# dependencies = " + array + + "#\n# [tool.orcaslicer.plugin]\n# name = \"Deps\"\n# ///\nprint('ok')\n"); + + PluginDescriptor descriptor; + std::string error; + REQUIRE(read_python_plugin_metadata(py, descriptor, error)); + INFO(array); + CHECK(descriptor.dependencies == std::vector{"numpy>=1.20,<2", "pillow"}); + CHECK(descriptor.name == "Deps"); +} + TEST_CASE("install-state sidecar is the source of truth for a cloud plugin's installed version", "[PluginInstall]") { ScopedDataDir data_dir_guard("installed-version"); diff --git a/tests/slic3rutils/test_printer_agent.cpp b/tests/slic3rutils/test_printer_agent.cpp index 62379de103..ac4140284c 100644 --- a/tests/slic3rutils/test_printer_agent.cpp +++ b/tests/slic3rutils/test_printer_agent.cpp @@ -57,23 +57,6 @@ TEST_CASE("unit: printer-agent registry register / lookup / duplicate-reject", " CHECK(count == 1); } -TEST_CASE("The registry records whether the native Device tab applies to an agent", "[registry][unit]") -{ - // why: ids unique to this case, as the registry is process-global - auto stub_factory = [](std::shared_ptr, const std::string&) - -> std::shared_ptr { return nullptr; }; - - REQUIRE(NetworkAgentFactory::register_printer_agent("orca-test::native-tab-default-2c91", "Default", stub_factory)); - REQUIRE(NetworkAgentFactory::register_printer_agent("orca-test::native-tab-off-2c91", "Web only", stub_factory, false)); - - const PrinterAgentInfo* with_tab = NetworkAgentFactory::get_printer_agent_info("orca-test::native-tab-default-2c91"); - const PrinterAgentInfo* web_only = NetworkAgentFactory::get_printer_agent_info("orca-test::native-tab-off-2c91"); - REQUIRE(with_tab != nullptr); - REQUIRE(web_only != nullptr); - CHECK(with_tab->native_device_tab); - CHECK_FALSE(web_only->native_device_tab); -} - // =========================================================================== // INTEGRATION - the orca.printer_agent Python binding surface. // Boots the embedded interpreter and asserts the C++ to Python contract that diff --git a/tools/mcp/README.md b/tools/mcp/README.md index e071fa2ad5..b5e5fe9abd 100644 --- a/tools/mcp/README.md +++ b/tools/mcp/README.md @@ -204,7 +204,7 @@ from, unsaved changes and a printer that is not selected. It exports a filament Preset Bundle dialog to its `out_dir` (`export_config` with a directory), imports the archive again with `import_configs` and a path (kept while the preset exists, imported once it is deleted) and imports `tests/fixtures/mcp_import_pla.json`. It changes a preference in the Preferences dialog -opened with `open_preferences` `control:auto_arrange`, by the control's name, and reads it back with +opened with `open_preferences` `behaviour:auto_arrange`, by the control's name, and reads it back with `get_settings {"scope": "preferences"}`. It starts from the harness's default printer with one filament slot in Simple mode, deleting slots and selecting the mode first, and reruns on the same datadir. diff --git a/tools/mcp/tests/presets.json b/tools/mcp/tests/presets.json index 4eb228db35..ba79fda9fe 100644 --- a/tools/mcp/tests/presets.json +++ b/tools/mcp/tests/presets.json @@ -328,7 +328,7 @@ {"tool": "set_settings", "args": {"scope": "preferences", "values": {"auto_arrange": false}}, "optional": true}, {"tool": "run_action", "args": {"id": "orca_command:open_preferences:orca", "param": "advanced"}, "optional": true}, {"tool": "get_state", "expect": {"/dialogs": {"empty": true}}}, - {"tool": "run_action", "args": {"id": "orca_command:open_preferences:orca", "param": "control:auto_arrange"}, "await": false, "save_as": "prefs"}, + {"tool": "run_action", "args": {"id": "orca_command:open_preferences:orca", "param": "behaviour:auto_arrange"}, "await": false, "save_as": "prefs"}, {"tool": "ui_input", "args": {"target": {"name": "auto_arrange", "within": "Preferences"}, "value": false}, "expect": {"/checked": {"eq": false}}}, {"tool": "dialog_respond", "args": {"dialog": {"title": "Preferences"}, "button": "close"}}, {"tool": "wait", "args": {"for": "job", "job": "${jobs.prefs}"}},