Merge upstream/main into dev/ams-custom-color-alpha-gradient

This commit is contained in:
Noisyfox committed 2026-10-26 15:18:06 +08:00
commit 0d7c956558
736 files changed
+80020 -117129

No files matched your search

+3 -1
View File
@@ -27,6 +27,7 @@ CheckOptions:
# are included through clipper2/clipper.h, or clipper2_z.hpp, which defines
# USINGZ first. minilzo's config
# headers are internal to minilzo.h.
# The boost/process headers are only included through Utils/BoostProcessCompat.hpp.
# FFmpeg's C headers are left alone because they are only included inside
# extern "C", which an inserted include would miss. OS-specific headers (GLib,
# GTK, D-Bus, POSIX, the Windows SDK) are only used inside platform #if blocks,
@@ -72,4 +73,5 @@ CheckOptions:
mcut[/\\]platform\.h;
boost[/\\]polygon[/\\].*;
clipper2[/\\]clipper\.(core|engine|offset|minkowski|rectclip|export|triangulation|version)\.h;
lzo(conf|defs)\.h
lzo(conf|defs)\.h;
boost[/\\]process[/\\].*
+88 -14
View File
@@ -1,6 +1,6 @@
---
name: orca-translations
description: Use when updating, filling, reviewing or fixing OrcaSlicer translations in localization/i18n — running scripts/run_gettext --full, translating empty or new msgids in the .po catalogs, AI translation passes and their "# AI Translated" / "# Needs human review" comments, plural forms, msgctxt homonyms, and keeping catalogs consistent with the localization glossary (OrcaSlicer_WIKI localization_glossary.tsv), including adding new glossary terms. Also use for msgfmt or run_gettext failures, placeholder or line-break mismatches, and reviewing a translation PR against the glossary.
description: Use when updating, filling, reviewing or fixing OrcaSlicer translations in localization/i18n — running scripts/run_gettext --full, translating empty or new msgids in the .po catalogs, reviewing and fixing a language's existing translations for wrong meanings, competing terms and unnatural wording, AI translation passes and their "# AI Translated" / "# Needs human review" comments, plural forms, msgctxt homonyms, and keeping catalogs consistent with the localization glossary (OrcaSlicer_WIKI developer_reference/glossary), including adding new glossary terms. Also use for msgfmt or run_gettext failures, placeholder or line-break mismatches, and reviewing a translation PR against the glossary.
---
# OrcaSlicer translations
@@ -9,7 +9,7 @@ The UI strings live in gettext catalogs: `localization/i18n/OrcaSlicer.pot` is t
`localization/i18n/<lang>/OrcaSlicer_<lang>.po` holds each language. The `en` catalog is empty on
purpose, so skip it. Recurring terms are fixed by the
[localization glossary](https://github.com/OrcaSlicer/OrcaSlicer_WIKI/blob/main/developer_reference/localization_glossary.md),
whose source is `developer_reference/localization_glossary.tsv` in the **OrcaSlicer_WIKI** repository.
whose source is the per-language files in `developer_reference/glossary/` (`terms.tsv`, `languages.txt` and one `<lang>.tsv`) in the **OrcaSlicer_WIKI** repository.
A translation pass therefore touches two repositories: the catalogs here, and the glossary there.
All catalog editing goes through [`scripts/po_tool.py`](scripts/po_tool.py) (standard library only).
@@ -51,9 +51,10 @@ scripts\run_gettext.bat --full # Windows (PowerShell: & .\scripts\run_
```
It must exit 0. New msgids arrive empty, and removed ones become obsolete `#~` entries. A msgid that
comes back gets its old translation revived from `#~`, which is one reason never to purge obsolete
entries. It also compiles the `.mo` files (gitignored). The bundled Windows gettext may re-wrap a long
`#:` reference line. That churn is harmless.
comes back gets its old translation revived from `#~`, and `pending` offers obsolete entries as similar
earlier translations, so they stay until the translations are done and are purged in step 5. It also
compiles the `.mo` files (gitignored). The bundled Windows gettext may re-wrap a long `#:` reference
line. That churn is harmless.
Then take stock: `python3 $T status`.
@@ -112,22 +113,35 @@ For each language:
- `note`: the developer's `TRN` comment.
- `flags`: `c-format` or `boost-format`.
- `description`: present when a sense has to be chosen.
- `refs`, `code` and `nearby`: where the source uses the string, the lines around that use (for
short strings and placeholder strings), and the translations of the short strings used next to
it, such as the label a tooltip describes or the other items of a menu. The catalogs carry no
source references, so this is the only place the context shows. Read it before writing; the
rules file's *Context* says what to take from it.
- `similar`: earlier translations of similar English. `"human": true` marks a person's work: when
the English barely changed, patch that translation instead of translating again (see the rules).
3. Read every apply message:
- **REJECTED:** a hard rule broke. Fix the translation and apply the corrected items again.
- **WARNING:** something worth a second look, such as a glossary rendering not found, ending
punctuation, or snake_case. A glossary warning on an inflected form you checked is fine.
punctuation, or snake_case. A glossary warning is fine on an inflected form you checked, and
on a word the string uses in another sense than the row's description (the printer's `Model:` is
not the glossary's 3D *Model*).
Otherwise correct the translation (`apply --overwrite` replaces your own entry), or add a
`review` reason.
`apply` adds `# AI Translated` to every entry it writes, and `# Needs human review: <reason>` where an
item has `review`. On an `--overwrite`, `"review": ""` removes an earlier note. Never add either to a translation a person wrote. `--human` is for applying their
text.
text, and for a fix that keeps their words; it also drops a stale AI mark. `apply` rejects text that
strays from a person's translation more than the English change explains, unless the item says why
with `"rewrite": "<reason>"`.
**The work is large:** every new string, times every language. When subagents are available, give each
one a language or a few. Each agent only touches its own catalogs, so they can run
in parallel. Settle step 3 first. Give each agent the language list, this skill's path, the rules file,
and these instructions:
- Fill every empty entry.
- Fill every empty entry, reading each one's `code` and `nearby` first.
- Patch a person's earlier translation (`"human": true` in `similar`) instead of translating again, and
keep their words when fixing their entries.
- Don't add glossary rows.
- Report what it could not translate, the review notes it added, and any term it thinks the glossary
still lacks.
@@ -140,6 +154,8 @@ Add the terms they report yourself, then have the affected languages revisit the
python3 $T check --lang <L> --warnings # every AI-translated entry, plus msgfmt --check-format
```
- **Remove the obsolete entries:** `python3 $T purge-obsolete` drops every `#~` entry, with its
comments, from every catalog (`--lang L` for a pass limited to some languages).
- **Run the full gettext again.** It must exit 0 and leave the catalogs as the pass left them.
- **Run `python generate_glossary.py --check` in the wiki clone.**
- **Errors on entries you didn't write predate the pass.** Report them rather than fixing them in the
@@ -153,10 +169,65 @@ Report:
- anything left empty, and why;
- the glossary rows added or filled.
The catalogs (and `OrcaSlicer.pot`) and the glossary (`localization_glossary.tsv` and `.md`) are
The catalogs (and `OrcaSlicer.pot`) and the glossary (`developer_reference/glossary/*.tsv` and `localization_glossary.md`) are
separate changes in separate repositories. The wiki change should land with, or before, the catalog
change. Commit or open PRs only when asked.
## Workflow: review and fix an existing catalog
When the user asks for more than a fill (review a language, fix its translations, a complete pass),
fill it first with the workflow above, then audit what the catalog already holds. The request is what
allows existing entries to change (rule 4). Work one language at a time, and stop to ask only about
established glossary terms (step 4); fix everything else directly.
1. **Save a copy of the catalog** in the scratch directory, to diff the audit against.
2. **Read the catalog area by area,** one pass each:
- the 3D view, navigation, camera and rendering;
- gizmos, CAD and mesh tools;
- printer hardware and the device tab;
- print-process settings and their tooltips;
- errors, warnings and dialogs.
The catalogs carry no `#:` references, so split them with `lookup --lang <L> . --file '<regex>'
--limit 0`, which keeps the entries used in matching source files (`Gizmos/`, `Device`,
`PrintConfig`), and add `--code` to see each use. Read every pair in an area: short labels in full,
with their code, and long tooltips at least for their terms. When subagents are available, give
each one an area, the rules file and the term decisions made so far, have it return findings rather
than edits, and merge them yourself.
3. **Look for:**
- **Competing renderings of one term.** For each recurring English term, list every rendering it
has (`lookup --lang <L> "<term>"`, then `lookup --msgstr` for each rendering found), and settle on
one per sense: the glossary's where it has a row, otherwise by the rules file's order of sources.
A recurring term the glossary lacks goes into it with `glossary-set`, as in step 3 of the fill.
- **Wrong meanings:** a word that means something else in context, the wrong sense of a homonym
(one `msgctxt` translated with another's word), a setting quoted differently from its own label.
A short msgid used in several places must fit every use `--code` lists; when no wording can,
report the missing `msgctxt`.
- **Sets that don't read as one:** the items of a menu, a choice or a toolbar in different
grammatical forms, or two items translated alike.
- **Broken entries:** a lost `\n`, text left over from another string, untranslated fragments,
a `msgstr` left identical to the English (a symbol, token or bare placeholder may be), typos.
`check --lang <L> --scope all --warnings` finds the mechanical ones.
- **Unnatural wording,** judged by the rules file's *Style*.
4. **Hold back changes to established glossary terms.** When the right fix changes a term the
glossary already fixes, leave those entries and the cell alone and keep a list. After the whole
audit, ask the user once: each term, the proposed rendering, why, and how many entries it touches,
with a recommendation. Apply the approved ones as in *Changing an established term*.
5. **Fix the rest** with `apply --overwrite`, from items `{"id": ..., "msgstr": ...}`.
- The patch rules for a person's translation still hold: change only what is wrong. When more than
a patch is needed, add `"rewrite": "<what was wrong>"`; it becomes the entry's review note.
- Entries you rewrite are marked `# AI Translated`; a patch that keeps a person's words goes in
with `--human`. Add `review` where unsure.
6. **Verify** as in step 5 of the fill workflow. Then compare every glossary cell for the language
with the final catalog (`check --scope all --warnings` reports renderings not found), and list the
disagreements left.
7. **Report:**
- the changes grouped by area, with representative before → after examples;
- the term decisions and the sources behind them;
- the review notes added;
- the source problems found;
- the glossary changes made, and the disagreements left.
## Rules
1. **Run the full gettext first.** Translate against the regenerated template, never a stale one.
@@ -166,12 +237,14 @@ change. Commit or open PRs only when asked.
3. **New recurring terms go into the glossary before the translations that use them.** Without a wiki
clone, stop and tell the user (step 3).
4. **Fill, don't rewrite.** A fill pass writes only empty and fuzzy entries.
- Existing translations, human or AI, change only on request (`--overwrite`).
- A glossary violation in a human translation is reported, not changed.
- Existing translations, human or AI, change only on request (`--overwrite`), as in the review
workflow.
- Outside that workflow, a glossary violation in a human translation is reported, not changed.
5. **Machine output is labelled.** Every AI translation gets `# AI Translated`; uncertain ones also get
`# Needs human review: <reason>`. Never use `fuzzy`.
6. **Never edit `msgid`, `msgctxt`, the header, or obsolete `#~` entries,** and never fix the English in
a translation. Report source problems (see the rules file).
a translation. Report source problems (see the rules file). Obsolete entries are only removed whole,
with `purge-obsolete` at the end of a pass.
7. **Write catalogs only through `po_tool.py` or gettext.** PO libraries such as polib reflow unrelated
entries, and hand edits skip the validation.
@@ -195,9 +268,10 @@ inherits the mistake, so fix both in the same change:
Review it for these:
- glossary compliance (`check --scope all --warnings` on the language, then read the hits);
- the sense of each changed short string where it is used (`lookup --code`);
- placeholders and line breaks (`check` errors);
- `# AI Translated` kept on text a person rewrote, or added to text a person wrote;
- purged obsolete entries;
- obsolete entries left in the catalogs, or removed other than by `purge-obsolete`;
- reflowed unrelated entries;
- plural forms short of `nplurals`.
@@ -210,7 +284,7 @@ with the translators, followed by the catalogs.
When this skill and the checkouts disagree, the checkouts win:
- `scripts/run_gettext.sh` / `.bat` for extraction and merging;
- `localization/i18n/list.txt` for the scanned sources;
- the wiki's `localization_guide.md` and `localization_glossary.md` / `.tsv` for the rules and terms;
- the wiki's `localization_guide.md` and `localization_glossary.md` and `glossary/*.tsv` for the rules and terms;
- `AGENTS.md` (Localization & translations) for the repository's conventions.
## Editing this skill
@@ -11,7 +11,8 @@ can detect; everything else is on the translator.
A rejected entry is not written. Fix it and apply again.
- **Placeholders stay exactly as written:** `%s`, `%d`, `%.1f`, `%1$d`, `%1%`, `%%`. Never `%1 %`, never
`%` for `%%`. Plain printf placeholders keep their order; only positional ones (`%1$s`, `%1%`) may move.
`%` for `%%`. Plain printf placeholders keep their order; only positional ones (`%1$s`, `%1%`) may move,
and one the msgid repeats may appear just once.
A broken placeholder crashes the app.
- **Line breaks:** the same number of `\n`, with the same leading and trailing ones. Don't add breaks to fit
text, least of all in parameter names.
@@ -26,6 +27,26 @@ A rejected entry is not written. Fix it and apply again.
ja/ko/zh/th/vi, 3 for ru/cs/pl/lt, 4 for uk). Each form is really inflected for its quantity. Repeating
one sentence is a bug in Slavic and Baltic languages, but correct in Turkish and Hungarian.
## A person's translation: patch it, don't rewrite it
A translator's wording is kept unless it is wrong. Machine output never replaces it wholesale.
- **A reworded string:** `pending` lists earlier translations of similar English under `similar`, and
marks a person's work with `"human": true`. When the English barely changed, start from that
translation and change only what the English change requires: a renamed term, an added clause, a
period. Keep the translator's wording, word order, terms and line structure. If they already wrote what
the new English says, the translation does not change at all.
- **A fix in a person's translation:** for a check error (a line break, a space, placeholder order, a
missing clause), change only what the error needs. Keep the rest of their words, even where they differ
from the glossary or from how you would phrase it. Report such glossary differences instead.
- **Rewrite only what is plainly wrong:** another string's text, a cut-off sentence, a mistranslation.
Say why with `"rewrite": "<what was wrong>"` in the item; the reason becomes the review note.
- `apply` enforces this. It rejects text that strays further from a person's translation than the
English change explains (below 85% alike for a fix, or clearly less alike than the English for a
reworded string), unless the item carries `rewrite`.
- Apply a fix that keeps the person's words with `--human`, so the entry stays theirs. Text you wrote
gets the default `# AI Translated`.
## Mechanical: not detectable, still required
- Edit only `msgstr`. Never change `msgid`, `msgctxt`, the header or another entry's text.
@@ -36,6 +57,49 @@ A rejected entry is not written. Fix it and apply again.
control.
- Don't use `fuzzy` for uncertainty. Fuzzy entries are hidden, and users then see English.
## Context: know what the string is before choosing its words
English reuses one word for different things, and a string seen alone often reads several ways. Settle
what each entry is before translating it. `pending` gives every entry the context the source holds:
`refs` (where it is used), `code` (the lines around the use, for short strings and placeholder
strings) and `nearby` (the translated short strings used next to it). `lookup --code` shows the same
for existing entries. The catalogs themselves carry no source references.
- **What kind of text it is,** from `code`: a button or menu item is a command, a field label or column
header names a value, a checkbox states something that is on or off, and a tooltip, status line,
error or dialog title each have their own register. Keep a label as short as a label.
- **What it belongs to.** A setting's strings sit together in `PrintConfig.cpp`: `this->add("<key>", …)`,
then `label`, `category`, `tooltip`, `sidetext`. The tooltip describes that option, and quotes the
label exactly as `nearby` shows it translated. The items of one menu, choice or toolbar
(`enum_labels`, `Append`, an array of names) are a set: give them one grammatical form, and words that
tell them apart.
- **`msgctxt` separates homonyms.** `Back` in *Camera View* is the rear view, and `Back` in
*Navigation* is the go-back button. Translate each context on its own.
- **Overloaded English: translate the meaning.**
- *Flow ratio* is a multiplier, *Flow Rate* is throughput, and *Flow Dynamics* is pressure
compensation. These are three different terms.
- *Extruder* can mean the toolhead, the feeder motor ("High extruder current on filament swap") or
the nozzle ("all extruders must have the same diameter").
- *Home* is the homing move ("Please home all axes"), the home page, or the Home key (*Keyboard
Shortcut*), which takes the name printed on that language's keyboards. *Fill* is infill, gap fill,
or the paint tools' bucket and smart fill. *Normal* is the ordinary kind ("Normal support",
"Normal printing") or the surface normal ("Normal X", "Smooth normals"). *Model* is the 3D model,
or the printer model in "Model:". *Process* is the process preset, or an operation under way ("the
slicing process").
- The glossary's rows record the senses that recur (`Plate` versus `Bed / Build plate`, `Feature
(print)` versus `Feature (Design)`); the code tells which one a string means.
- **Check the meaning in the code** when the English leaves it open: read the call site, and further
in the file when `code` is not enough.
- See what each placeholder is filled with. A fallback string substituted into a sentence must
fit the slot it fills.
- Settle the semantics the English blurs: a ratio or a difference, which way a rotation turns,
which control a hint names.
- **A msgid used in several places** (`left` is a view name and a hotend; `Sphere` is a primitive
and a paint brush) needs a wording that fits every use. When none can, report the missing
`msgctxt` as a source problem.
- **When the context still leaves two readings,** take the likelier one and add a review note naming
the other.
## Choosing the words
- **The glossary is binding.** Use the language's rendering for every glossary term the `pending`
@@ -52,24 +116,63 @@ A rejected entry is not written. Fix it and apply again.
glossary page's *Kept in English* table.
- **Language specifics** on the glossary page (`po_tool.py glossary --lang L` prints them) override
general habits for that language.
- **Consistency beyond the glossary:** before translating a label, or a tooltip that names a setting,
run `lookup` for the setting name. Quote the label's existing translation exactly, so the tooltip and
the field match. Reuse obsolete (`#~`) entries as a translation memory.
- **`msgctxt` separates homonyms.** `Back` in *Camera View* is the rear view, and `Back` in
*Navigation* is the go-back button. Translate each context on its own.
- **Overloaded English: translate the meaning.**
- *Flow ratio* is a multiplier, *Flow Rate* is throughput, and *Flow Dynamics* is pressure
compensation. These are three different terms.
- *Extruder* can mean the toolhead, the feeder motor ("High extruder current on filament swap") or
the nozzle ("all extruders must have the same diameter").
- When a short label is ambiguous, grep `src/` for the msgid to see the widget it labels.
- **The catalog's existing words come next.** A tooltip or message that names a setting, a button or a
menu item quotes that control's translation exactly, so the text matches what the user sees. `nearby`
shows the controls next to the string; `lookup` finds the rest. For a recurring term the glossary
lacks, `lookup` the English and `lookup --msgstr` the rendering you intend, and use the one the
catalog already settled on in that sense. Reuse obsolete (`#~`) entries as a translation memory.
- **No settled term: look outside the catalog, in this order.**
1. **Other slicers' shipped catalogs** for the same language:
[BambuStudio](https://github.com/bambulab/BambuStudio) `bbl/i18n/<lang>/BambuStudio_<lang>.po`
and [PrusaSlicer](https://github.com/prusa3d/PrusaSlicer)
`resources/localization/<lang>/PrusaSlicer_<lang>.po` (a local clone, if there is one). Orca
shares much of its UI with both, so their translators have often rendered the same string
already. Their choice is evidence, not a rule: the glossary and Orca's own catalog win.
2. **The 3D-printing community in that language:** manuals, wikis and forums of printer vendors
(Bambu Lab, Prusa, Creality, Snapmaker) and their users. Take the term printers actually use,
a loanword where they use the loanword.
3. **Neighbouring fields,** when printing has no term of its own: CAD (SolidWorks, Fusion,
Onshape, AutoCAD), CNC/CAM and machining, then engineering and mathematics. General UI
vocabulary (*Settings*, *Preferences*, *Undo*, *Browse*, *Quit*, *Copy*, *Paste*) follows the
operating systems' own translations, which users already know.
4. **English,** when nothing is established: brand names, acronyms, file formats, G-code tokens,
variables, and Orca-specific feature names with no equivalent.
Translate paired terms as a pair, so they read as the two sides of one choice (direct drive and
Bowden, inner and outer wall). Name the sources a term came from in the report.
- **Each field keeps its own vocabulary.** 3D-view and CAD strings follow CAD software and drafting
standards: the standard view names, *isometric*, *orbit*, *pan* and *zoom*, *cut plane* versus
*section plane*, the primitive names. The camera of the 3D view (the viewpoint) and the printer's
camera (the device) are different things and take different words wherever the language has two.
- **A regional variant is its own language.** Never derive one from the other character by character
or word by word: zh_TW and zh_CN differ in vocabulary, not only in script. Start from the
variant's own glossary column and catalog. A converter (OpenCC `s2twp` for zh_CN → zh_TW) gives a
draft at most; review every entry it produced.
- **Boilerplate stays uniform.** `Failed to connect to …`, `Are you sure you want to …?` and
`If expressed as a %, it will be computed over …` each get one template in the language, even where
the English varies.
## Style
- **Localize, don't translate word-for-word.** Know what the string controls before translating it.
- **Localize, don't translate word-for-word.** Translate what the string means where it appears (see
*Context*), not each English word.
- **Write native UI text.** The result should read as if the app had been written in that language.
- Restructure the sentence instead of following English word order.
- Break up long noun chains.
- Drop passive and filler constructions the language doesn't use in UI text.
- Don't calque English idioms or compounds where the language has its own expression.
- Don't carry English Title Case over: capitalize as the language does (sentence case in most,
German nouns as German writes them).
- Use the language's own punctuation. Don't carry English marks over, such as ` — ` or straight
quotes where the language has its own. ASCII quotes around a literal value the user types or
the app matches stay as written.
- **Follow the catalog's conventions,** which a new entry must match:
- formal or informal address;
- full-width or half-width punctuation;
- spacing between scripts (CJK next to Latin letters or digits);
- the separator sibling labels use before their value;
- the verb form of buttons and menu commands (infinitive, imperative or noun);
- the form of a confirmation question.
- **Simplify developer phrasing** when the meaning survives. *"This option determines whether
OrcaSlicer should apply the retract reduction on infill"* reads better as *"Disable retractions while
printing infill."* Introduce nuances in following sentences, not in one packed clause.
@@ -77,14 +180,17 @@ A rejected entry is not written. Fix it and apply again.
descriptions is for human translators, who can confirm the extra content.
- **Write for both audiences:** professionals and people with a printer at home. Keep the established
terminology, used as plainly as the string allows.
- **Read the batch back without the English** before applying it, as a user of the app would see it.
Rewrite whatever reads like a translation, is ambiguous on its own, or uses a word differently from
the strings around it.
## When to add a review note
Add `"review": "<what to check>"` to an item when the translation is probable but unconfirmed. It
becomes `# Needs human review: …`, and the entry still ships. Typical reasons:
- The English is ambiguous out of context: "Tile" as a verb or a noun.
- A short label's role only shows in the app.
- The English stays ambiguous even with its code: "Tile" as a verb or a noun.
- A short label's role shows only in the running app, not in its code.
- Two established terms compete, or the glossary cell is unsettled.
- The string's grammar depends on a value substituted at runtime: `%zu %s` counts with no plural entry.
@@ -96,6 +202,7 @@ right for the whole row."*
Report these; don't work around them in a catalog.
- **The English is wrong.** Never "fix" it in the translation only.
- **A hint names a control that doesn't exist,** or a user-visible literal isn't wrapped in `_L`.
- **One msgid needs two translations.** The source needs `_L_CONTEXT` / `_u8L_CONTEXT` (a code change).
- **A literal `%` in a string xgettext flagged `possible-c-format`** fails `msgfmt`. The fix is a
`// xgettext:no-c-format, no-boost-format` comment above the string in the source, not `%%` in the
@@ -5,11 +5,14 @@ Standard library only. Edits a catalog in place, rewriting just the entries it
changes in the layout `msgmerge --no-wrap` writes, so every other byte stays put.
status [--lang L ...] per-catalog counts
pending --lang L [--offset N --limit N] [--out FILE] [--no-include-fuzzy] (adds similar earlier translations)
pending --lang L [--offset N --limit N] [--out FILE] [--no-include-fuzzy] (adds similar earlier
translations, where the source uses each msgid, and the translated labels near it)
apply --lang L --input FILE [--overwrite] [--dry-run] adds "# AI Translated"
check [--lang L ...] [--scope ai|all] [--warnings]
lookup --lang L PATTERN [--msgstr] existing translations with ids, obsolete ones included
glossary --lang L [TERM] the language's glossary column and notes
lookup --lang L PATTERN [--msgstr] [--code] [--file RX] existing translations with ids, obsolete
ones included; --file keeps those used in matching source files
purge-obsolete [--lang L ...] drop the obsolete (#~) entries, every catalog by default
glossary --lang L [TERM] the language's glossary column and notes
candidates [--min-count N] [--limit N] recurring untranslated phrases not in the glossary
glossary-set --term T [--description D] --set L=VALUE ... [--replace]
@@ -23,18 +26,20 @@ import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
import unicodedata
import urllib.error
import urllib.request
from pathlib import Path
REPO = Path(__file__).resolve().parents[4]
I18N = REPO / "localization" / "i18n"
SKIP_LANGS = {"en"} # the English catalog is intentionally empty
GLOSSARY_TSV = Path("developer_reference") / "localization_glossary.tsv"
GLOSSARY_DIR = Path("developer_reference") / "glossary" # terms.tsv, languages.txt and one <lang>.tsv per language
GLOSSARY_MD = Path("developer_reference") / "localization_glossary.md"
MISSING = {"", "—"}
RAW_URL = "https://raw.githubusercontent.com/OrcaSlicer/OrcaSlicer_WIKI/main/"
@@ -73,7 +78,7 @@ class Entry:
self.lines = lines
self.first_line = first_line # 0-based index in the file
self.obsolete = all(l.startswith("#~") for l in lines if not l.startswith("#") or l.startswith("#~"))
self.tcomments, self.xcomments, self.flags = [], [], []
self.tcomments, self.xcomments, self.flags, self.refs = [], [], [], []
self.fields = {} # keyword -> [value, start, end)
self.order = []
current = None
@@ -90,6 +95,8 @@ class Entry:
self.xcomments.append(line[2:].strip())
elif line.startswith("#,"):
self.flags += [f.strip() for f in line[2:].split(",") if f.strip()]
elif line.startswith("#:"):
self.refs += [(f, int(n)) for f, n in re.findall(r"(\S+):(\d+)", line[2:])]
elif line == "#" or line.startswith("# "):
self.tcomments.append(line[2:])
continue
@@ -176,6 +183,11 @@ class Entry:
while pos < len(lines) and (lines[pos] == "#" or lines[pos].startswith("# ")):
pos += 1
add = []
if not ai: # a person's words: drop a stale AI mark
lines = [l for l in lines if l != "# " + AI_TAG]
pos = 0
while pos < len(lines) and (lines[pos] == "#" or lines[pos].startswith("# ")):
pos += 1
if review is not None: # "" clears an earlier note, a reason replaces it
lines = [l for l in lines if not l.startswith("# " + REVIEW_TAG)]
pos = 0
@@ -247,35 +259,116 @@ def all_langs():
return sorted(d.name for d in I18N.iterdir() if (d / f"OrcaSlicer_{d.name}.po").exists() and d.name not in SKIP_LANGS)
# ---------------------------------------------------------------------------
# Source locations
class Sources:
"""Where the source uses each msgid. The catalogs are extracted with --no-location, so this runs
xgettext again over localization/i18n/list.txt with the keywords scripts/run_gettext.sh passes."""
def __init__(self):
self.refs = {} # (msgctxt, msgid) -> [(file, line)]
self.keys = {} # file -> [(line, key)]
self._lines = {}
xgettext = shutil.which("xgettext") or next((str(t) for t in [REPO / "tools" / "xgettext.exe"] if t.exists()), None)
keywords = sorted(set(re.findall(r"--keyword=\S+", (REPO / "scripts" / "run_gettext.sh").read_text(encoding="utf-8"))))
if not xgettext or not keywords:
print("note: xgettext not found; entries carry no source context", file=sys.stderr)
return
listed = (REPO / "localization" / "i18n" / "list.txt").read_text(encoding="utf-8").splitlines()
files = [f.strip() for f in listed if f.strip() and not f.startswith("#") and (REPO / f.strip()).is_file()]
with tempfile.TemporaryDirectory() as d:
lst, pot = Path(d) / "list.txt", Path(d) / "located.pot"
lst.write_text("\n".join(files) + "\n", encoding="utf-8")
r = subprocess.run([xgettext, *keywords, "--from-code=UTF-8", "--boost", "--no-wrap", "-f", str(lst), "-o", str(pot)],
cwd=REPO, capture_output=True, text=True)
if r.returncode or not pot.exists():
print(f"note: xgettext failed; entries carry no source context\n{r.stderr.strip()}", file=sys.stderr)
return
for e in Catalog(pot).active():
self.refs[e.key()] = e.refs
for f, n in e.refs:
self.keys.setdefault(f, []).append((n, e.key()))
def lines(self, f):
if f not in self._lines:
self._lines[f] = (REPO / f).read_text(encoding="utf-8", errors="replace").splitlines()
return self._lines[f]
def spread(self, key, n):
"""Up to n uses, from as many different places as possible, so a msgid that a gizmo and a
menu share shows both."""
picked = []
for place in (lambda f: f.rsplit("/", 1)[0], lambda f: f):
for f, line in self.refs.get(key, []):
if len(picked) < n and place(f) not in {place(p) for p, _ in picked}:
picked.append((f, line))
return picked
def code(self, key, n=3):
"""The lines around a msgid's uses: the widget or option it belongs to, and what fills its
placeholders."""
out = []
for f, line in self.spread(key, n):
lines = self.lines(f)
end = line # through the end of the statement, where the placeholder arguments are
while end < min(len(lines), line + 8) and ";" not in lines[end - 1]:
end += 1
around = [l.strip()[:160] for l in lines[max(line - 3, 0):end] if l.strip()]
out.append({"at": f"{f}:{line}", "code": "\n".join(around)})
return out
def nearby(self, key, translated, span=6, limit=4):
"""Translated short msgids used within a few lines of this one: the label a tooltip describes,
the other items of a menu or a choice. Their wording is what this one must agree with."""
dist = {}
for f, line in self.refs.get(key, []):
for n, k in self.keys.get(f, []):
if k != key and k in translated and len(k[1]) <= 80 and abs(n - line) <= span:
dist[k] = min(dist.get(k, span), abs(n - line))
return [dict({"msgctxt": k[0]} if k[0] else {}, msgid=k[1], msgstr=translated[k])
for k in sorted(dist, key=dist.get)[:limit]]
# ---------------------------------------------------------------------------
# Glossary
def find_wiki(arg):
for cand in [arg, os.environ.get("ORCA_WIKI_DIR"), REPO.parent / "OrcaSlicer_WIKI", REPO.parent / "OrcaSlicer.wiki"]:
if cand and (Path(cand) / GLOSSARY_TSV).exists():
if cand and (Path(cand) / GLOSSARY_DIR / "terms.tsv").exists():
return Path(cand)
return None
def _download(rel):
cache = Path(tempfile.gettempdir()) / ("orca_glossary_" + rel.name)
def _download(rel, required=True):
cache = Path(tempfile.gettempdir()) / "orca_glossary" / rel
if not cache.exists() or time.time() - cache.stat().st_mtime > 3600:
with urllib.request.urlopen(RAW_URL + rel.as_posix(), timeout=30) as r:
cache.write_bytes(r.read())
try:
with urllib.request.urlopen(RAW_URL + rel.as_posix(), timeout=30) as r:
data = r.read()
except urllib.error.HTTPError:
if required:
raise
return None
cache.parent.mkdir(parents=True, exist_ok=True)
cache.write_bytes(data)
return cache
class Glossary:
def __init__(self, wiki_arg=None, quiet=False):
"""The glossary: rows of [English, Description, <one translation per language loaded>]."""
def __init__(self, wiki_arg=None, quiet=False, langs=None):
self.wiki = find_wiki(wiki_arg)
self.langs = langs # only these languages' files are read (and downloaded); None means all
if self.wiki:
self.tsv, self.md = self.wiki / GLOSSARY_TSV, self.wiki / GLOSSARY_MD
self.dir, self.md = self.wiki / GLOSSARY_DIR, self.wiki / GLOSSARY_MD
if not quiet:
self.report_clone_state()
else:
if not quiet:
print("note: no OrcaSlicer_WIKI clone found; using the published glossary read-only", file=sys.stderr)
self.tsv, self.md = _download(GLOSSARY_TSV), _download(GLOSSARY_MD)
self.dir, self.md = _download(GLOSSARY_DIR / "terms.tsv").parent, _download(GLOSSARY_MD)
self.load()
def report_clone_state(self):
@@ -290,11 +383,23 @@ class Glossary:
if behind and behind != "0":
print(f"note: the wiki clone is {behind} commits behind origin/main (as of its last fetch)", file=sys.stderr)
def _read(self, name, required=True):
path = self.dir / name if self.wiki else _download(GLOSSARY_DIR / name, required)
return path.read_text(encoding="utf-8-sig").splitlines() if path and path.exists() else None
def load(self):
rows = [l.split("\t") for l in self.tsv.read_text(encoding="utf-8-sig").splitlines() if l.strip()]
self.header = rows[0]
# "—" marks a language with no established rendering yet
self.rows = [[c if c.strip() not in MISSING else "" for c in r] + [""] * (len(rows[0]) - len(r)) for r in rows[1:]]
terms = [l.split(" ") for l in self._read("terms.tsv")[1:] if l.strip()]
langs = [l.strip() for l in self._read("languages.txt") if l.strip()]
langs = [l for l in langs if self.langs is None or l in self.langs]
self.header = ["English", "Description"] + langs
self.rows = [[r[0], r[1] if len(r) > 1 else ""] + [""] * len(langs) for r in terms]
index = {r[0]: r for r in self.rows}
for col, lang in enumerate(langs, start=2):
for line in (self._read(f"{lang}.tsv", required=False) or [])[1:]:
cells = line.split(" ")
# "—" marks a language with no established rendering yet
if len(cells) > 2 and cells[0] in index and cells[2].strip() not in MISSING:
index[cells[0]][col] = cells[2].strip()
self.matchers = []
for row in self.rows:
base = re.sub(r"\s*\([^)]*\)\s*$", "", row[0]).strip()
@@ -379,9 +484,9 @@ def validate(e, msgstrs, nplurals, glossary=None, lang=None):
b1, c1 = _placeholders(src, flags)
b2, c2 = _placeholders(s, flags)
positional = any("$" in p for p in c1)
c_bad = sorted(c1) != sorted(c2) if positional else c1 != c2
c_bad = set(c1) != set(c2) if positional else c1 != c2
bad = []
if sorted(b1) != sorted(b2):
if set(b1) != set(b2):
bad.append(f"boost placeholders {b1} -> {b2}")
if c_bad:
bad.append(f"printf placeholders {c1} -> {c2}" + ("" if positional else " (order must match)"))
@@ -481,24 +586,54 @@ def similar_entries(c, e, pool, cutoff=0.72):
sm = difflib.SequenceMatcher(autojunk=False)
sm.set_seq2(e.msgid)
best = []
for other, msgstr, obsolete in pool:
for other, msgstr, obsolete, human in pool:
sm.set_seq1(other)
if sm.real_quick_ratio() < cutoff or sm.quick_ratio() < cutoff:
continue
r = sm.ratio()
if r >= cutoff and other != e.msgid:
best.append((r, other, msgstr, obsolete))
best.append((r, other, msgstr, obsolete, human))
best.sort(key=lambda t: -t[0])
return [{"msgid": o, "msgstr": s, "obsolete": ob, "similarity": round(r, 2)} for r, o, s, ob in best[:2]]
return [dict({"msgid": o, "msgstr": s, "obsolete": ob, "similarity": round(r, 2)}, **({"human": True} if h else {}))
for r, o, s, ob, h in best[:2]]
def similar_pool(c):
return [(x.msgid, x.msgstrs()[0], x.obsolete, not x.ai) for x in c.entries
if not x.is_header and x.msgstrs() and x.msgstrs()[0] and not x.fuzzy and 8 < len(x.msgid) < 600]
def human_drift(e, strs, pool):
"""Why a translation strays from a person's text more than the English change explains, or None."""
import difflib
alike = lambda x, y: difflib.SequenceMatcher(None, x, y, autojunk=False).ratio()
new, old = "\n".join(strs), "\n".join(e.msgstrs())
if old.strip() and not e.ai:
r = alike(old, new)
if r < 0.85:
return (f"replaces a person's translation with text only {r:.0%} like it: keep their words and change "
f"only what the fix needs, or give \"rewrite\": \"<reason>\"")
return None
if old.strip() or len(e.msgid) <= 8:
return None
for s in similar_entries(None, e, pool, cutoff=0.85):
if s.get("human"):
r = alike(s["msgstr"], new)
if r < s["similarity"] - 0.1:
return (f"the English is {s['similarity']:.0%} like a string a person translated, but this translation is "
f"only {r:.0%} like theirs: patch their translation, or give \"rewrite\": \"<reason>\"")
break
return None
def cmd_pending(a):
c = Catalog(catalog_path(a.lang))
g = Glossary(a.wiki)
g = Glossary(a.wiki, langs=[a.lang])
todo = [e for e in c.active() if needs_translation(e, c.nplurals, a.include_fuzzy)]
batch = todo[a.offset:a.offset + a.limit] if a.limit else todo[a.offset:]
pool = [(x.msgid, x.msgstrs()[0], x.obsolete) for x in c.entries
if not x.is_header and x.msgstrs() and x.msgstrs()[0] and not x.fuzzy and 8 < len(x.msgid) < 600]
pool = similar_pool(c)
src = Sources()
translated = {e.key(): e.msgstrs()[0] for e in c.active() if e.msgstrs() and e.msgstrs()[0] and not e.fuzzy}
items = []
for e in batch:
item = {"id": e.id(), "msgctxt": e.msgctxt, "msgid": e.msgid}
@@ -516,6 +651,13 @@ def cmd_pending(a):
item["fuzzy"] = True
if e.msgstrs()[0]:
item["previous_translation"] = e.msgstrs()[0]
refs = src.refs.get(e.key(), [])
if refs:
item["refs"] = [f"{f}:{n}" for f, n in refs[:4]] + ([f"+{len(refs) - 4} more"] if len(refs) > 4 else [])
# Code only where it settles the meaning: short labels, and what fills the placeholders.
if len(e.msgid.split()) <= 8 or {"c-format", "boost-format"} & set(flags):
item["code"] = src.code(e.key()) or None
item["nearby"] = src.nearby(e.key(), translated) or None
if len(e.msgid) > 8:
sim = similar_entries(c, e, pool)
if sim:
@@ -533,11 +675,12 @@ def cmd_pending(a):
def cmd_apply(a):
c = Catalog(catalog_path(a.lang))
g = None if a.no_glossary else Glossary(a.wiki, quiet=True)
g = None if a.no_glossary else Glossary(a.wiki, quiet=True, langs=[a.lang])
data = json.loads(Path(a.input).read_text(encoding="utf-8"))
items = data["entries"] if isinstance(data, dict) else data
idx = c.index()
by_id = {c.entries[i].id(): i for i in idx.values()}
pool = similar_pool(c)
applied, skipped, rejected, warned = 0, 0, [], []
for it in items:
if "msgid" in it:
@@ -565,9 +708,16 @@ def cmd_apply(a):
if errors:
rejected.append((label, errors))
continue
drift = None if it.get("rewrite") else human_drift(e, strs, pool)
if drift:
rejected.append((label, [drift]))
continue
if warnings:
warned.append((label, warnings))
c.changes[i] = e.rewrite(strs, ai=not a.human, review=it.get("review"))
review = it.get("review")
if it.get("rewrite") and not review:
review = "Rewrote a person's translation: " + it["rewrite"]
c.changes[i] = e.rewrite(strs, ai=not a.human, review=review)
applied += 1
if not a.dry_run and c.changes:
c.save()
@@ -588,7 +738,7 @@ def find_msgfmt():
def cmd_check(a):
g = None if a.no_glossary else Glossary(a.wiki, quiet=True)
g = None if a.no_glossary else Glossary(a.wiki, quiet=True, langs=a.lang or None)
msgfmt = find_msgfmt()
status = 0
for lang in a.lang or all_langs():
@@ -613,7 +763,7 @@ def cmd_check(a):
if msgfmt:
fd, mo = tempfile.mkstemp(suffix=".mo") # Windows msgfmt cannot write to "nul"
os.close(fd)
r = subprocess.run([msgfmt, "--check-format", "-o", mo, str(c.path)], capture_output=True, text=True)
r = subprocess.run([msgfmt, "--check-format", "--check-header", "-o", mo, str(c.path)], capture_output=True, text=True)
os.unlink(mo)
if r.returncode:
print(f"{lang}: msgfmt --check-format failed\n{r.stderr.strip()}")
@@ -625,9 +775,29 @@ def cmd_check(a):
return status
def cmd_purge_obsolete(a):
"""Drop the obsolete (#~) entries, with their comments and the blank line before each."""
for lang in a.lang or sorted(set(all_langs()) | SKIP_LANGS):
c = Catalog(catalog_path(lang))
# a block of comments alone also parses as obsolete, so require a #~ line
gone = [e for e in c.entries if e.obsolete and any(l.startswith("#~") for l in e.lines)]
drop = set()
for e in gone:
start = e.first_line
while start > 0 and c.lines[start - 1].strip() == "":
start -= 1
drop.update(range(start, e.first_line + len(e.lines)))
if drop:
c.lines = [l for i, l in enumerate(c.lines) if i not in drop]
c.save()
print(f"{lang}: {len(gone)} obsolete entries removed")
def cmd_lookup(a):
c = Catalog(catalog_path(a.lang))
rx = re.compile(a.pattern, re.I)
src = Sources() if a.code or a.file else None
in_files = re.compile(a.file) if a.file else None
n = 0
for e in c.entries:
strs = [s for s in e.msgstrs() if s]
@@ -636,17 +806,25 @@ def cmd_lookup(a):
texts = strs if a.msgstr else [e.msgid, e.msgid_plural or ""]
if not any(rx.search(t) for t in texts):
continue
if in_files and (e.obsolete or not any(in_files.search(f) for f, _ in src.refs.get(e.key(), []))):
continue
mark = "obsolete " if e.obsolete else f"{e.id()} " + ("AI " if e.ai else "")
ctx = f"[{e.msgctxt}] " if e.msgctxt else ""
print(f"{mark}{ctx}{json.dumps(e.msgid, ensure_ascii=False)}\n -> {json.dumps(strs[0] if len(strs) == 1 else strs, ensure_ascii=False)}")
if a.code and not e.obsolete:
refs, uses = src.refs.get(e.key(), []), src.code(e.key())
if len(refs) > len(uses):
print(" used in " + " ".join(f"{f}:{l}" for f, l in refs))
for use in uses:
print(f" {use['at']}\n" + "\n".join(" | " + l for l in use["code"].splitlines()))
n += 1
if n >= a.limit:
if a.limit and n >= a.limit:
print("... (limit reached)")
break
def cmd_glossary(a):
g = Glossary(a.wiki)
g = Glossary(a.wiki, langs=[a.lang])
col = g.column(a.lang)
if col is None:
print(f"'{a.lang}' has no glossary column yet; add one with glossary-set --set {a.lang}=...")
@@ -733,6 +911,17 @@ def cmd_candidates(a):
print(f"{cnt:7} {langs:6} {text}{' [label]' if k in labels else ''} e.g. {ex[:70]}{'…' if len(ex) > 70 else ''}")
def _edit_tsv(path, edit):
"""Apply edit(lines) to a glossary TSV, keeping its BOM and line endings."""
data = path.read_bytes()
bom = data.startswith(b"\xef\xbb\xbf")
text = data.decode("utf-8-sig")
nl = "\r\n" if "\r\n" in text else "\n"
lines = text.splitlines()
edit(lines)
path.write_bytes((b"\xef\xbb\xbf" if bom else b"") + (nl.join(lines) + nl).encode("utf-8"))
def cmd_glossary_set(a):
wiki = find_wiki(a.wiki)
if not wiki:
@@ -741,8 +930,21 @@ def cmd_glossary_set(a):
f" {a.term}: " + ", ".join(a.set) + "\n"
"Clone https://github.com/OrcaSlicer/OrcaSlicer_WIKI next to this repository, or pass --wiki.", file=sys.stderr)
return 2
tsv = wiki / GLOSSARY_TSV
lock = tsv.with_suffix(".lock")
gdir = wiki / GLOSSARY_DIR
gen = wiki / "generate_glossary.py"
if not gen.exists():
sys.exit(f"{gen} not found")
run_gen = lambda *args: subprocess.run([sys.executable, str(gen), *args], cwd=wiki, capture_output=True, text=True)
langs = [l.strip() for l in (gdir / "languages.txt").read_text(encoding="utf-8-sig").splitlines() if l.strip()]
values = {}
for s in a.set:
lang, _, val = s.partition("=")
if lang not in langs:
sys.exit(f"no glossary language '{lang}' (add it to {GLOSSARY_DIR.as_posix()}/languages.txt)")
if "\t" in val or "\n" in val:
sys.exit("values cannot contain tabs or line breaks")
values[lang] = val.strip()
lock = gdir / ".lock"
for _ in range(100):
try:
fd = os.open(lock, os.O_CREAT | os.O_EXCL)
@@ -752,50 +954,51 @@ def cmd_glossary_set(a):
else:
sys.exit(f"could not lock {lock}; remove it if no other run is active")
try:
data = tsv.read_bytes()
bom = data.startswith(b"\xef\xbb\xbf")
text = data.decode("utf-8-sig")
nl = "\r\n" if "\r\n" in text else "\n"
lines = text.splitlines()
header = lines[0].split("\t")
values = {}
for s in a.set:
lang, _, val = s.partition("=")
if lang not in header:
sys.exit(f"no glossary column '{lang}'")
if "\t" in val or "\n" in val:
sys.exit("values cannot contain tabs or line breaks")
values[header.index(lang)] = val.strip()
row_i = next((i for i, l in enumerate(lines[1:], 1) if l.split("\t")[0] == a.term), None)
new = row_i is None
if new:
if not a.description:
sys.exit("a new term needs --description (one sentence saying what it is)")
row = [a.term, a.description] + [""] * (len(header) - 2)
lines.append("")
row_i = len(lines) - 1
else:
row = lines[row_i].split("\t")
row += [""] * (len(header) - len(row))
if a.description:
row[1] = a.description
conflicts = [f"{header[i]}: '{row[i]}' -> '{v}'" for i, v in values.items() if row[i].strip() not in MISSING and row[i] != v]
terms = (gdir / "terms.tsv").read_text(encoding="utf-8-sig").splitlines()
new = not any(l.split("\t")[0] == a.term for l in terms[1:])
if new and not a.description:
sys.exit("a new term needs --description (one sentence saying what it is)")
# an established translation is only replaced on request
conflicts = []
for lang, v in values.items():
for line in (gdir / f"{lang}.tsv").read_text(encoding="utf-8-sig").splitlines()[1:]:
cells = line.split("\t")
if cells[0] == a.term and len(cells) > 2 and cells[2].strip() not in MISSING and cells[2] != v:
conflicts.append(f"{lang}: '{cells[2]}' -> '{v}'")
if conflicts and not a.replace:
sys.exit("established translations differ (pass --replace, and update the catalogs to match):\n " + "\n ".join(conflicts))
for i, v in values.items():
row[i] = v
lines[row_i] = "\t".join(row)
tsv.write_bytes((b"\xef\xbb\xbf" if bom else b"") + (nl.join(lines) + nl).encode("utf-8"))
def edit_terms(lines):
for i, l in enumerate(lines):
if i and l.split("\t")[0] == a.term:
if a.description:
lines[i] = f"{a.term}\t{a.description}"
return
lines.append(f"{a.term}\t{a.description}")
if new or a.description:
_edit_tsv(gdir / "terms.tsv", edit_terms)
r = run_gen("--sync") # copies the term and description into every language file
if r.returncode:
sys.exit((r.stdout + r.stderr).strip())
def setter(lang, v):
def edit(lines):
for i, l in enumerate(lines):
cells = l.split("\t")
if i and cells[0] == a.term:
lines[i] = "\t".join(cells[:2] + [v])
return
sys.exit(f"{lang}.tsv has no row for '{a.term}'")
return edit
for lang, v in values.items():
_edit_tsv(gdir / f"{lang}.tsv", setter(lang, v))
finally:
os.close(fd)
os.unlink(lock)
print(f"glossary: {'added' if new else 'updated'} '{a.term}'")
gen = wiki / "generate_glossary.py"
if gen.exists():
r = subprocess.run([sys.executable, str(gen), "--update"], cwd=wiki, capture_output=True, text=True)
print((r.stdout + r.stderr).strip())
return r.returncode
return 0
r = run_gen("--update")
print((r.stdout + r.stderr).strip())
return r.returncode
def main():
@@ -833,11 +1036,17 @@ def main():
s.add_argument("--no-glossary", action="store_true")
s.set_defaults(func=cmd_check)
s = sub.add_parser("purge-obsolete")
s.add_argument("--lang", action="append", help="default: every catalog")
s.set_defaults(func=cmd_purge_obsolete)
s = sub.add_parser("lookup")
s.add_argument("--lang", required=True)
s.add_argument("pattern")
s.add_argument("--msgstr", action="store_true", help="search the translations instead of the English")
s.add_argument("--limit", type=int, default=40)
s.add_argument("--code", action="store_true", help="show where the source uses each hit")
s.add_argument("--file", help="only entries used in source files matching this regex (e.g. 'Gizmos/')")
s.add_argument("--limit", type=int, default=40, help="0 for no limit")
s.set_defaults(func=cmd_lookup)
s = sub.add_parser("glossary")
@@ -867,6 +867,8 @@ append_shortcut_item(export_menu, Shortcut::ExportSlicedFile, true, _L("Export p
itself; never keep a raw pointer (`interface/wx/tipwin.h:20-110`).
- `wxRichToolTip` is not a window: each `ShowFor()` creates a new one, and the native MSW version
only applies to text controls (`interface/wx/richtooltip.h:70-192`).
- On Wayland, a GTK tooltip of a widget inside a shown popup maps as a grabbing `xdg_popup` and takes the
keyboard focus from the toplevel, which reports a deactivation → `references/popups-menus.md` §9.
| Static [source] | MSW | GTK | macOS |
|---|---|---|---|
@@ -541,6 +541,14 @@ Pitfall:
`set_option_label` (rename a row at runtime, e.g. `brim_width` → "Brim ear radius").
`Tab::get_config_manipulation()` builds the callbacks (variant index → `+256`, see [Variants](#per-extruder-variant-options));
`Tab` also records each public toggle in its own `OptionStateRegistry` before looking up a field.
The optional reason is localized text; false stores or replaces it, true removes only that kind of
restriction. Keys are kept exactly as supplied, independently of the separate variant index. Direct
field toggles are not recorded. The registry's `description` composes the localized restriction
text; public toggles refresh the field tooltip, and `OG_CustomCtrl` reads the same registry for the
row label. The label is the portable hover target for a disabled field. Markdown tips prepend this
dynamic text to the loaded document and include it in their content-change check.
`TabX::toggle_options()` calls the `toggle_*` function and adds tab-local tweaks. They run on every page activation,
after every `update()`, and after a variant switch.
@@ -592,10 +600,21 @@ English and translated label/group/category, so search matches either. `UnsavedC
name settings from the same index and skip a changed key the index lacks; only the extruder-transfer view
(`UnsavedChangesDialog::update_tree(type, config, from, to)`) falls back to the def's label/category, then "Others".
`get_tab_for_option` resolves the model tab when it has the key, otherwise the global tab; search
availability descriptions and `Sidebar::jump_to_option` use that same owner. The settings search
shows recorded restrictions below the result title and in its tooltip without changing fuzzy name
matching. The Speed Dial retains recorded hidden settings and puts their explanations in the detail
strip. Restrictions absent from the registry keep their existing row filter.
`Sidebar::jump_to_option(key, type, category)` → (model tab if it has the key, else switch to global) →
`Tab::activate_option`, which selects the page by translated category, focuses the field and blinks it
`Tab::activate_option`, which selects the page by translated category, reruns `toggle_options()`,
then either shows the registry's hidden reason or focuses the field and blinks it
(`get_custom_ctrl_with_blinking_ptr`). `Tab::apply_searcher()` refreshes the index for one tab.
Pitfall: the registry is only as fresh as the last `toggle_options()` of the page owning the key, and
its keys carry no extruder index. A check made before navigating refuses settings that a printer edit
or another extruder has made visible; check after the page and extruder are selected and the rules rerun.
Pitfalls:
- **Rule:** Create tab groups with a non-empty English title; a key that should be findable must be on a tab.
**Why:** `append_options` skips entries with an empty group or category, so `page->new_optgroup("")` rows and
@@ -372,14 +372,17 @@ form a chain of parents. Window icons come from the `.desktop` file. The full li
`references/mouse-keyboard-focus.md`;
- GL blending must keep destination alpha at 1 (d8369e5f75);
- GL post-init must retry until the surface is committed (d2c24fdabb) →
`references/webview-gl-aui-media.md`.
`references/webview-gl-aui-media.md`;
- a shown GTK tooltip is the topmost `xdg_popup`, so it must be hidden before a popup maps
(`PopupWindow::Show`) → `references/popups-menus.md` §9.
### XWayland (GTK3 X11 backend inside a Wayland session)
Users opt in with `GDK_BACKEND=x11…`. GTK then talks X11, so `is_running_on_x11()` is true and Orca
uses GLX through `PreferGLX()`. `CLI::run` prepares this path before GTK starts (PRIME variables,
`XInitThreads()`, no WebKit compositing workaround; the source comment says multi-monitor handling
is compromised there) → [Runtime detection](#runtime-x11wayland-detection),
uses GLX through `PreferGLX()`. `CLI::run` prepares this path before GTK starts (`XInitThreads()`, no
WebKit compositing workaround; GPU choice is the `prefer_discrete_gpu` preference on either backend;
the source comment says multi-monitor handling is compromised there) →
[Runtime detection](#runtime-x11wayland-detection),
`references/webview-gl-aui-media.md` §WebKitGTK on Linux sessions. Intel's XWayland GL exposes a
smaller `GL_MAX_TEXTURE_SIZE`, so the ImGui font atlas is re-packed to fit (22e121f4e4) →
`references/webview-gl-aui-media.md`.
@@ -409,7 +412,8 @@ start there when looking for prior art. The sites below are exemplars, cited by
(`focus_left_popup(...)`) instead of hit-testing `wxGetMousePosition()`.
- `PopupWindow::Create`: on GTK it binds the top-level `wxEVT_ACTIVATE` to `topWindowActiavate` →
`DismissAndNotify()`, gated by the virtual `ShouldDismissOnTopWindowDeactivate()`, which `DropDown`
overrides for Wayland popup chains. On `__WXOSX__` with `wxPU_CONTAINS_CONTROLS`,
overrides for Wayland popup chains. `PopupWindow::Show` (GTK) hides visible GTK tooltips before mapping
on Wayland. On `__WXOSX__` with `wxPU_CONTAINS_CONTROLS`,
`PopupWindow::OnMouseEvent2` hit-tests children, re-dispatches mouse events and synthesises
enter/leave.
- `SidePopup::Popup` (`Widgets/SideMenuPopup.cpp`): on `__APPLE__` the menu is anchored flush against
@@ -569,12 +573,19 @@ on the **first** call. So:
#endif
```
**Before GTK starts**, only the environment exists. `CLI::run` (`src/OrcaSlicer.cpp`) branches on
`GDK_BACKEND` (an `x11` prefix means the X11 opt-in). On the default path it forces `GDK_BACKEND=x11`
when wx lacks EGL and `WAYLAND_DISPLAY` is set. It sets `WEBKIT_DISABLE_COMPOSITING_MODE=1`
(non-replacing) only when both `DISPLAY` and `WAYLAND_DISPLAY` are set, and calls `XInitThreads()`
**Before GTK starts**, only the environment exists. `CLI::run` (`src/OrcaSlicer.cpp`) sets the NVIDIA
DMABUF workaround and then branches on `GDK_BACKEND` (an `x11` prefix means the X11 opt-in). On both
paths, when `/proc/driver/nvidia/version` exists and the linked WebKitGTK honours the switch (>= 2.44,
`WebView::SupportsForceSharedMemory()`), it sets `WEBKIT_DMABUF_RENDERER_FORCE_SHM=1` and
`WEBKIT_FORCE_DMABUF_RENDERER=1` (non-replacing): the proprietary driver cannot back WebKit's hardware
DMABUF renderer. On a hypervisor guest (`/proc/cpuinfo` `hypervisor` flag) and WebKitGTK >= 2.44 it sets
`WEBKIT_DMABUF_RENDERER_FORCE_SHM=1` alone, since virtual GPUs cannot back the hardware path either. On the default path it forces `GDK_BACKEND=x11` when wx lacks EGL and `WAYLAND_DISPLAY`
is set, and sets `WEBKIT_DISABLE_COMPOSITING_MODE=1` (non-replacing) inside that branch when the linked
WebKitGTK is older than 2.42: a forced X11 backend in a Wayland session is the only default-path case
that runs through XWayland, which `DISPLAY` and `WAYLAND_DISPLAY` alone do not tell you (a native
Wayland app inherits both). It calls `XInitThreads()`
only when `DISPLAY` is set. With neither variable set, the GUI refuses to start ("Neither DISPLAY nor
WAYLAND_DISPLAY set"). The details and the WebKit rule (c12912e0df) are in
WAYLAND_DISPLAY set"). The details and the WebKit rules (c12912e0df) are in
`references/webview-gl-aui-media.md` §WebKitGTK on Linux sessions.
**wx's own detectors**, for reference:
@@ -626,7 +637,7 @@ headers. Rows marked [source] or "protocol" come from the implementation or from
| `wxBitmap(const wxCursor&)` | creates an invalid bitmap | `interface/wx/bitmap.h:393-395` | — |
| OpenGL | only EGL; `PreferGLX()` has no effect. Without EGL in the build, wxGTK's `wxGLCanvas` shows a fatal message and refuses to work [source: `src/gtk/glcanvas.cpp` `IsAvailable`]. The EGL surface is a subsurface over the canvas, ready only after map and a frame callback [source: `src/unix/glegl.cpp`] | `interface/wx/glcanvas.h:1094-1095` | `CLI::run` forces X11 when wx lacks EGL; overlays are drawn in GL/ImGui, never as wx children over the canvas → `references/webview-gl-aui-media.md` |
| AUI | the doc note "live resize is always used … for wxOSX and wxGTK3 when using Wayland" is obsolete: "As of wxWidgets 3.3.0 this function always returns false", and `wxAUI_MGR_LIVE_RESIZE` is in the default flags. Floating panes need global positions | `interface/wx/aui/framemanager.h:336-345` | `Plater::priv::priv` clears `wxAUI_MGR_ALLOW_FLOATING`; `sanitize_window_layout_for_wayland` strips floating state from the saved layout → `references/webview-gl-aui-media.md` §wxAuiManager |
| Popups | a GTK popup is an `xdg_popup` only for COMBO/DROPDOWN/POPUP_MENU hints, so wx creates popups with `GDK_WINDOW_TYPE_HINT_COMBO` [source]. A chained popup's parent must be the mapped popup, and mapping it with a grab deactivates the toplevel (Orca's comments in `DropDown::mouseMove`, `DropDown::ShouldDismissOnTopWindowDeactivate`) | `src/gtk/popupwin.cpp:110-114` | `DropDown` transient-for chain, `ShouldDismissOnTopWindowDeactivate` → `references/popups-menus.md` |
| Popups | a GTK popup is an `xdg_popup` only for COMBO/DROPDOWN/POPUP_MENU hints, so wx creates popups with `GDK_WINDOW_TYPE_HINT_COMBO` [source]. A chained popup's parent must be the mapped popup, and mapping it with a grab deactivates the toplevel (Orca's comments in `DropDown::mouseMove`, `DropDown::ShouldDismissOnTopWindowDeactivate`). A GTK tooltip of a widget in a shown popup maps as that popup's grabbing child and deactivates the toplevel the same way | `src/gtk/popupwin.cpp:110-114` | `DropDown` transient-for chain, `ShouldDismissOnTopWindowDeactivate`, the tooltip check in `PopupWindow::topWindowActiavate` → `references/popups-menus.md` |
| Fractional scale | arrives as an integer GDK scale | `docs/doxygen/overviews/high_dpi.md:348-351` | → `references/dpi-bitmaps-fonts.md` |
| Window decorations | some desktop environments draw a title bar on undecorated windows anyway | — | [Undecorated windows](#wayland-undecorated-top-level-windows-splash) |
| `wxWebViewChromium` | X11 only | `interface/wx/webview_chromium.h:133-146` | not built (`wxUSE_WEBVIEW_CHROMIUM` OFF) |
@@ -73,6 +73,14 @@ Contents: [Rules](#rules) · [1. Choosing the window kind](#1-choosing-the-windo
27. Build `MenuFactory` menus once. Pass `parent` to `append_menu_item` only for items that persist. (§16)
28. macOS: bind `wxID_EXIT` on `OSXGetAppleMenu()` to `Close()`, only insert into the Apple menu, and always
`Skip()` a frame's `wxEVT_ACTIVATE`. (§15)
29. On Wayland, a popup that can open while a GTK tooltip is shown hides every visible tooltip window before
it maps. `PopupWindow::Show` does it for every Orca popup; a popup outside `PopupWindow` opened from a
widget with a GTK tooltip must do it itself. Only a popup that cannot map while a GTK tooltip is visible,
such as one opened from the GL canvas (whose tooltips are ImGui), needs nothing. (§9)
30. On Wayland, a hook that dismisses a popup when its toplevel deactivates ignores the deactivation while a GTK
tooltip of a widget in that popup, or in a popup opened from it, is on screen: the tooltip has taken the
keyboard while the user is still on the popup. `PopupWindow::topWindowActiavate` does it for every Orca popup;
a popup outside `PopupWindow` with such a hook must do it itself. (§9)
## 1. Choosing the window kind
@@ -390,6 +398,10 @@ compensates for (§6).
on older GTK and GTK2. On hide: `gdk_seat_ungrab` + `gtk_grab_remove` (`popupcmn.cpp:335-403`).
`gdk_seat_ungrab` releases the *seat's* grab, whichever popup took it, so hiding a sub-popup also drops the
parent popup's pointer grab.
- The window is mapped before the grab is taken (`wxPopupWindow::Show` at `popupcmn.cpp:370`, the grab from
375). Under Wayland the popup itself therefore maps as an `xdg_popup` without an explicit grab, while GDK
records the grab seat on its window, and a popup mapped later as its transient child (a sub-dropdown, a GTK
tooltip of a widget inside it) inherits that seat and maps with `xdg_popup.grab` (§9).
- An outside press arrives at the grab widget. `gtk_popup_button_press` sends `wxEVT_KILL_FOCUS` to the popup
and **consumes the click** (`return TRUE`, `src/gtk/popupwin.cpp:28-58`). Presses older than the popup's
creation time are ignored (33-34).
@@ -439,6 +451,9 @@ class PopupWindow : public wxPopupTransientWindow {
public:
PopupWindow(wxWindow* parent, int style = wxBORDER_NONE);
bool Create(wxWindow* parent, int flags = wxBORDER_NONE);
#ifdef __WXGTK__
bool Show(bool show = true) override; // hides GTK tooltips first on Wayland (§9)
#endif
#ifdef __WXMSW__
void BindUnfocusEvent(); // opt-in
#endif
@@ -451,7 +466,7 @@ What it adds per platform:
| Port | Behaviour |
|---|---|
| GTK | `Create` binds `wxEVT_ACTIVATE` on `GetTopParent(parent)`. `topWindowActiavate` calls `event.Skip()`, then `DismissAndNotify()` if the toplevel deactivated, the popup is shown and `ShouldDismissOnTopWindowDeactivate()` returns true. This supplies the app/toplevel deactivation dismissal that stock wxGTK lacks. |
| GTK | `Create` binds `wxEVT_ACTIVATE` on `GetTopParent(parent)`. `topWindowActiavate` calls `event.Skip()`, then `DismissAndNotify()` if the toplevel deactivated, the popup is shown, `ShouldDismissOnTopWindowDeactivate()` returns true and, under Wayland, no GTK tooltip of the popup's own is on screen (§9). This supplies the app/toplevel deactivation dismissal that stock wxGTK lacks. Under Wayland, `Show(true)` on a hidden popup first hides every visible GTK tooltip window (§9). |
| MSW | Nothing automatic. `BindUnfocusEvent()` binds the toplevel's `wxEVT_ACTIVATE`/`wxEVT_ICONIZE`/`wxEVT_SHOW` to `Dismiss()` (no `OnDismiss`). It is for default-style popups: they are desktop children that Windows does not hide with the frame, and stock wx closes them on deactivation or minimizing only if a focus message reaches a wx window (§4, §5). `topWindowActivate` does **not** `Skip()`, so while the popup lives it swallows the frame's `wxEVT_ACTIVATE`, and with it `wxTopLevelWindowMSW::OnActivate`'s focus save and restore (`src/msw/toplevel.cpp:1326-1360`). |
| macOS | Only with `wxPU_CONTAINS_CONTROLS`: `OnMouseEvent2`, bound on the popup for `LEFT_DOWN/UP/DCLICK`, `MOTION` and `MOUSEWHEEL`, hit-tests the children (static `HitTest`) and re-dispatches the event to the deepest child under the cursor with `ProcessEventLocally`. On `MOTION` it synthesizes `ENTER`/`LEAVE` for the hovered target. This compensates for the capture rerouting in §5. |
@@ -721,6 +736,85 @@ fights the grab and focus model (§10). Two more [source] facts:
`DropDown::Popup`, applied when `!mainDropDown && m_widget`).
- **Rule:** Don't open a grabbing popup on hover on Linux if the opener must stay clickable.
Cite: `MainFrame` slice-button hover handlers (`#ifndef __linux__`).
- **Rule:** On Wayland, hide every visible GTK tooltip window right before mapping a popup that can open
while one is shown.
**Why:** A GTK3 tooltip is a `GTK_WINDOW_POPUP` with the `tooltip` type hint, placed with
`gdk_window_move_to_rect` (`gtktooltip.c:974-983`), so GDK Wayland maps it as an `xdg_popup` of the
hovered widget's toplevel (`should_map_as_popup`, `gdkwindow-wayland.c:3198-3199`). GDK refuses to map a
popup whose parent is not the last popup it mapped, warning "Tried to map a popup with a non-top most
parent" (`gdkwindow-wayland.c:3040-3046`), and the window stays invisible while wx believes it is shown.
GTK hides the tooltip on a button or key press, but only after the event has been propagated to the
widgets (`gtkmain.c:1949-1961`, `_gtk_tooltip_handle_event`). A dropdown opened from the click is therefore
mapped while the opener's tooltip is still up, and the click that opens it after the tooltip delay does
nothing. The same holds for a sub-dropdown opened on hover while the main dropdown shows an item tooltip.
GTK hides the current tooltip the same way before mapping its own menus (`gtk_menu_popup_internal`,
`gtkmenu.c:1837`), but through the private `_gtk_tooltip_hide_in_display` (`gtktooltip.c:1297`); apps have
no public call, so hide the window: `gtk_widget_hide` unmaps the `xdg_popup` at once, and GtkTooltip treats
the tooltip as no longer visible (`GTK_TOOLTIP_VISIBLE`, `gtktooltip.c:135`). Its own hide on the press
then returns early, before it times out browse mode (`gtk_tooltip_hide_tooltip`, `gtktooltip.c:1078`,
1092), so the next tooltip shows after the 60 ms browse delay instead of 500 ms. A tooltip GTK tries to
show while a popup is open fails to map with the same warning and stays hidden, unless its widget is in
the topmost popup (a dropdown's own item tooltip maps as that popup's child); that happens with or without
this step and is harmless. X11 has no popup stacking rule, so the step is gated on
`is_running_on_wayland()`. (Line numbers are GTK 3.24.52.)
```cpp
// Wrong: map the popup with the opener's tooltip still on top
drop.Popup(&drop);
// Right (wxGTK, Wayland): PopupWindow::Show does this before every map
GList* toplevels = gtk_window_list_toplevels();
for (GList* l = toplevels; l; l = l->next)
if (gtk_window_get_type_hint(GTK_WINDOW(l->data)) == GDK_WINDOW_TYPE_HINT_TOOLTIP && gtk_widget_get_visible(GTK_WIDGET(l->data)))
gtk_widget_hide(GTK_WIDGET(l->data));
g_list_free(toplevels);
```
Cite: `PopupWindow::Show` (#16595).
- **Rule:** On Wayland, don't dismiss a shown popup on a toplevel deactivation while a GTK tooltip of one of its
widgets is on screen.
**Why:** GTK makes a tooltip transient for the toplevel of the widget it describes (`gtktooltip.c:974`), which
for a widget inside a popup, or the popup itself (`DropDown` sets its item tooltips on itself), is the popup's
own `GtkWindow`. The popup's window holds the seat grab (§5), and `find_grab_input_seat` walks the transient
parents to it (`gdkwindow-wayland.c:3142-3147`), so GDK maps the tooltip with an explicit `xdg_popup.grab`
(3100); the walk passes through every popup in a chain, so a tooltip in a popup opened from inside another
popup grabs too. The compositor gives the keyboard to the topmost grabbing popup: KWin sends `wl_keyboard.leave`
for the main window and `enter` for the tooltip (observed with `WAYLAND_DEBUG=client`). wxGTK turns the
toplevel's focus-out into `wxEVT_ACTIVATE(false)` (`src/gtk/toplevel.cpp:192-205`), so a deactivation hook closes
the popup as the tooltip appears, and GDK warns "Tried to unmap the parent of a popup"
(`gdkwindow-wayland.c:3429`) because the tooltip is still mapped as its child. The focus returns to the toplevel
when the tooltip hides. Ask GDK whether the tooltip is mapped (`gdk_window_is_visible`): when the compositor
dismisses a tooltip, `xdg_popup_done` hides only its `GdkWindow` (`gdkwindow-wayland.c:2289`,
`gdkwindow.c:5684-5690`), and `gtk_widget_get_visible` stays TRUE until GTK hides the tooltip itself. Alt+Tab with
a tooltip showing still closes the popup (observed): the Alt press reaches the app, which hides the tooltip after
handling the key (`gtkmain.c:1949-1961`). X11 tooltips never take the focus, so the check is gated on
`is_running_on_wayland()`. (Line numbers are GTK 3.24.52.)
**Limit:** wxGTK sends `wxEVT_ACTIVATE(false)` only while it holds an active frame and then clears it
(`g_activeFrame`, `src/gtk/toplevel.cpp:196-202`), so a deactivation ignored this way is never repeated. If the
app loses the focus while the tooltip holds it, without Orca seeing a key or the pointer leave first (another
app's window taking the focus, a gesture), the popup stays open until the user returns, and the first click
closes it (observed with a dialog from another app). Closing that gap means waiting for the compositor to
reactivate the toplevel, which takes a timer or a blocking round trip.
```cpp
// Wrong: every toplevel deactivation dismisses, including the one the popup's own tooltip causes
if (!event.GetActive() && IsShown() && ShouldDismissOnTopWindowDeactivate())
DismissAndNotify();
// Right (wxGTK): Wayland only, skip it while a tooltip of this popup or of a popup opened from it is mapped
static bool own_tooltip_mapped(GtkWindow *popup)
{
bool mapped = false;
for_each_tooltip_window([popup, &mapped](GtkWindow *win) { // GDK_WINDOW_TYPE_HINT_TOOLTIP toplevels
GdkWindow *gdk_win = gtk_widget_get_window(GTK_WIDGET(win));
if (!gdk_win || !gdk_window_is_visible(gdk_win))
return;
for (GtkWindow *w = gtk_window_get_transient_for(win); w && !mapped; w = gtk_window_get_transient_for(w))
mapped = w == popup;
});
return mapped;
}
if (!event.GetActive() && IsShown() && ShouldDismissOnTopWindowDeactivate() &&
!(Slic3r::GUI::is_running_on_wayland() && own_tooltip_mapped(GTK_WINDOW(m_widget))))
DismissAndNotify();
```
Cite: `PopupWindow::topWindowActiavate` (#16800).
## 10. Frameless dialog instead of a popup
@@ -61,7 +61,8 @@ available; GTK2/WebKit1 is an opt-out configuration the GUI does not support.
11. A web host that re-themes in place handles `EVT_WEBVIEW_RECREATED` without `Skip()`; one that
needs a reload lets it through. §[Orca wrapper](#orca-webview-wrapper-widgetswebview)
12. Keep `WebViewWebKit`'s destructor removing the `"wx"` handler. §[Orca wrapper](#orca-webview-wrapper-widgetswebview)
13. Do not widen `WEBKIT_DISABLE_COMPOSITING_MODE` beyond Orca's default-path XWayland case, and never
13. Do not widen `WEBKIT_DISABLE_COMPOSITING_MODE` beyond the no-EGL default path where Orca forces
`GDK_BACKEND=x11`, for WebKitGTK older than 2.42, and never
make a page's progress depend only on a C++→JS callback. §[WebKitGTK on Linux](#webkitgtk-on-linux-sessions)
14. GL attribute lists: legacy `int[]` lists end with `0` and spell out `WX_GL_RGBA` and
`WX_GL_DOUBLEBUFFER`; `wxGLAttributes`/`wxGLContextAttrs` end with `EndList()`; MSAA is requested
@@ -567,33 +568,80 @@ vue-resize workaround script and sets a persistent SQLite cookie store on the vi
## WebKitGTK on Linux sessions
**Mechanism.** `CLI::run` (`src/OrcaSlicer.cpp`, under `#ifdef __WXGTK__`, before GTK initialises)
branches on `GDK_BACKEND`:
sets the DMABUF workarounds and then branches on `GDK_BACKEND`:
- **Both paths**, before the split: when `/proc/driver/nvidia/version` exists and the linked WebKitGTK
honours the switch (>= 2.44, `WebView::SupportsForceSharedMemory()`), it sets
`WEBKIT_DMABUF_RENDERER_FORCE_SHM=1` and `WEBKIT_FORCE_DMABUF_RENDERER=1` non-replacing. The
proprietary driver cannot back WebKit's hardware DMABUF renderer, so the shared-memory transport keeps
accelerated compositing instead of dropping it; `WEBKIT_FORCE_DMABUF_RENDERER` clears the
Debian/Ubuntu/openSUSE `isNVIDIA()` early return, which otherwise returns before the FORCE_SHM check.
- **Hypervisor guests**, same position: when `is_hypervisor_guest()` (the `hypervisor` flag in
`/proc/cpuinfo`) and WebKitGTK >= 2.44, it sets `WEBKIT_DMABUF_RENDERER_FORCE_SHM=1` non-replacing.
Virtual GPUs (VirtualBox VMSVGA, VMware, QEMU) cannot back the hardware DMABUF path either, and
FORCE_SHM alone was confirmed to fix web views in VirtualBox; the `WEBKIT_FORCE_DMABUF_RENDERER` pair
is not needed without the Debian `isNVIDIA()` patch. The flag is x86-only, so ARM guests are not covered.
- **Default path** (`GDK_BACKEND` unset or not starting with `x11`): if wx lacks EGL (`!wxHAS_EGL`) and
`WAYLAND_DISPLAY` is set, it forces `GDK_BACKEND=x11`; it sets `WEBKIT_DISABLE_COMPOSITING_MODE=1`
non-replacing **only** when both `DISPLAY` and `WAYLAND_DISPLAY` are non-empty (a Wayland session with
XWayland available — the session, not the backend GTK will pick); `XInitThreads()` runs only when
`DISPLAY` is set.
- **`GDK_BACKEND=x11…` opt-in path**: sets `DRI_PRIME=1` (and the NVIDIA PRIME variables when
`/proc/driver/nvidia/version` exists), calls `XInitThreads()`, and deliberately does **not** disable
compositing (the comment: the WebKit2GTK XWayland bug appears fixed in WebKit2GTK ≥ 2.42, and leaving
compositing on keeps hardware acceleration for Device / Setup Wizard / login pages).
`WAYLAND_DISPLAY` is set, it forces `GDK_BACKEND=x11`, and in that same branch it sets
`WEBKIT_DISABLE_COMPOSITING_MODE=1` non-replacing when the linked WebKitGTK predates 2.42
(`WebView::NeedsCompositingWorkaround()`). That forced X11 backend in a Wayland session is the only
default-path case that really runs through XWayland; `DISPLAY` and `WAYLAND_DISPLAY` alone do not
identify it, because a native Wayland app inherits both. `XInitThreads()` runs only when `DISPLAY` is
set.
- **`GDK_BACKEND=x11…` opt-in path**: calls `XInitThreads()` and deliberately does **not** disable
compositing, which keeps hardware acceleration for Device / Setup Wizard / login pages.
- **GPU selection** is independent of the backend. The Linux preference `prefer_discrete_gpu` ("Render on
the discrete GPU", default off) makes `apply_discrete_gpu_preference()` export `DRI_PRIME=1` and, when
`/proc/driver/nvidia/version` exists, the NVIDIA render-offload variables before GTK opens the display;
it reads the saved configuration through `AppConfig::peek_bool` because no `AppConfig` exists yet. The
desktop entries carry no `PrefersNonDefaultGPU` hint, so a menu launch renders on the display GPU like
a terminal launch; the hint made hybrid laptops on Wayland render through zink on the other GPU with
an empty 3D view.
Runtime backend detection elsewhere uses Orca's `is_running_on_wayland()` / `is_running_on_x11()`
(see `references/platforms.md`), not these environment variables.
**Pitfall.**
- **Rule:** Set `WEBKIT_DISABLE_COMPOSITING_MODE` only on the default path in Wayland sessions,
non-replacing (`setenv(..., false)`, so a value the user already exported wins), before GTK
initialises; never unconditionally. Keep JS-side fallbacks so a page never
- **Rule:** On NVIDIA and hypervisor guests reach for `WEBKIT_DMABUF_RENDERER_FORCE_SHM` before
`WEBKIT_DISABLE_COMPOSITING_MODE`. **Why:** the proprietary driver and virtual GPUs cannot back WebKit's
hardware DMABUF renderer, leaving web views blank or slow; FORCE_SHM keeps accelerated compositing and only
skips the hardware path, while disabling compositing drops it. Threaded scrolling is a separate,
release-dependent default (off in 2.44/2.45, on from 2.46). `WEBKIT_DISABLE_DMABUF_RENDERER` is not a
substitute — it is read first, leaves the transport set empty (no compositing from 2.44 on, where the
X11/Wayland fallback renderers were removed) and has a reported crash path. On Debian/Ubuntu and
openSUSE the `isNVIDIA()` patch returns before the FORCE_SHM check, so `WEBKIT_FORCE_DMABUF_RENDERER=1`
must clear it first; that variable exists only in those patches. WebKit reads all of these once per
process, before the first WebView.
The test is `/proc/driver/nvidia/version`, so a hybrid laptop that renders on its iGPU also takes the
shared-memory path, which is a per-frame GPU readback rather than zero-copy; exporting
`WEBKIT_DMABUF_RENDERER_FORCE_SHM=0` in the environment restores the hardware path.
```cpp
// Wrong: kills compositing and threaded scrolling (and can crash on modern WebKit)
::setenv("WEBKIT_DISABLE_DMABUF_RENDERER", "1", false);
// Right: keep compositing, skip only the hardware DMABUF path
if (::access("/proc/driver/nvidia/version", F_OK) == 0 && WebView::SupportsForceSharedMemory()) {
::setenv("WEBKIT_DMABUF_RENDERER_FORCE_SHM", "1", /*replace*/ false);
::setenv("WEBKIT_FORCE_DMABUF_RENDERER", "1", /*replace*/ false);
}
```
Cite: WebKit 2.52.6 `Source/WebKit/UIProcess/gtk/AcceleratedBackingStore.cpp`
(`rendererBufferTransportMode()`), Debian `disable-nvidia-dmabuf.patch`, WebKit bug 262607.
- **Rule:** Set `WEBKIT_DISABLE_COMPOSITING_MODE` only on the default path, in the branch where wx
lacks EGL and Orca forces `GDK_BACKEND=x11`, non-replacing (`setenv(..., false)`, so a value the user
already exported wins), before GTK
initialises; never unconditionally, and only for the WebKitGTK releases that need it (older than
2.42, `WebView::NeedsCompositingWorkaround()`). Keep JS-side fallbacks so a page never
waits forever for a C++→JS call.
**Why:** WebKit2GTK accelerated compositing could fail silently under XWayland, leaving web views
blank (Setup Wizard stuck on "Loading..."); disabling it everywhere needlessly drops hardware
acceleration; without the JS timeout the user is stuck when the signal is lost.
**Why:** WebKit2GTK accelerated compositing could fail silently under XWayland before 2.42, leaving
web views blank (Setup Wizard stuck on "Loading..."); the variable also turns off threaded scrolling,
so applying it on a newer WebKit needlessly drops both GPU compositing and async scrolling (the
Device tab loses its smoothness); without the JS timeout the user is stuck when the signal is lost.
```cpp
// Wrong: unconditional, kills HW acceleration everywhere
::setenv("WEBKIT_DISABLE_COMPOSITING_MODE", "1", false);
// Right (default path only): non-replacing, before GTK init, Wayland session with XWayland
if (display && *display && wayland && *wayland)
// Right (default path only): non-replacing, before GTK init, WebKitGTK < 2.42,
// and only in the branch that forces GDK_BACKEND=x11 (wx without EGL), the
// case that runs through XWayland
if (WebView::NeedsCompositingWorkaround() && wayland && *wayland)
::setenv("WEBKIT_DISABLE_COMPOSITING_MODE", "1", /*replace*/ false);
```
Cite: c12912e0df (`src/OrcaSlicer.cpp`; `resources/web/guide/0/load.js` `OnInit`
+108
View File
@@ -0,0 +1,108 @@
name: Approve PR checks
# The repository makes a maintainer approve workflow runs on pull requests from first-time
# contributors, and that setting covers every workflow at once. This approves the pending runs of
# Check profiles, Check locale and clang-tidy at the head of each open pull request from a fork, so
# they report without waiting; Build all and the other workflows still wait for a maintainer. It
# does not read the approval setting, so a stricter one does not hold these three back either.
#
# Its token can approve runs and pull_request_target needs no approval, so it must never check out
# or run pull request code. It reads run, pull request and git tree metadata only.
on:
# Approves the runs for a pull request's new head right away. No paths filter: clang_tidy.yml
# runs on every pull request into these branches.
pull_request_target:
branches:
- main
- release/*
# Looks at every pending run: one not listed yet when the job above looked, and all of them when
# pull_request_target is blocked by an Actions event policy.
schedule:
- cron: '7,17,27,37,47,57 * * * *'
workflow_dispatch:
permissions: {}
jobs:
approve:
name: Approve PR checks
runs-on: ubuntu-24.04
timeout-minutes: 10
permissions:
actions: write # list and approve workflow runs
contents: read # compare commits and read git trees
pull-requests: read # list open pull requests
steps:
- name: Approve pending runs
# A failed job would leave a red check on the pull request, which blocks pr-merge-bot.
# The sweep retries and reports the failure instead.
continue-on-error: ${{ github.event_name == 'pull_request_target' }}
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
# Both empty for the sweep, which then considers every pending run.
PR_NUMBER: ${{ github.event.pull_request.number }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
# The workflows approved here, found by file name.
workflows="check_profiles.yml check_locale.yml clang_tidy.yml"
# Prints the tree of a commit's .github/, or nothing if it has none; fails if the commit
# cannot be read.
github_tree() {
gh api "repos/${GH_REPO}/git/trees/$1" --jq '.tree[] | select(.path == ".github") | .sha'
}
# The approve endpoint is for pull requests from forks, so runs from this repository's own
# branches are left to a maintainer. Each workflow is listed on its own, so pending runs of
# other workflows cannot fill the endpoint's 1000-result window. A failed listing exits
# rather than passing for an empty one.
runs=$(for workflow in $workflows; do
gh api --paginate "repos/${GH_REPO}/actions/workflows/${workflow}/runs?event=pull_request&status=action_required&per_page=100${HEAD_SHA:+&head_sha=${HEAD_SHA}}" \
--jq '.workflow_runs[] | select(.head_repository.full_name != .repository.full_name) | [.id, .workflow_id, .head_sha, .name] | @tsv' \
|| exit 1
done)
if [ -z "$runs" ]; then
echo "No run of these workflows is waiting for approval."
exit 0
fi
# Runs for superseded commits and closed pull requests are left alone.
if [ -n "$PR_NUMBER" ]; then
open_heads=$(gh api "repos/${GH_REPO}/pulls/${PR_NUMBER}" --jq 'select(.state == "open") | .head.sha')
else
open_heads=$(gh api --paginate "repos/${GH_REPO}/pulls?state=open&per_page=100" --jq '.[].head.sha')
fi
failed=0
while IFS=$'\t' read -r run_id workflow_id sha name; do
grep -qx "$sha" <<< "$open_heads" || continue
# The approved run takes its workflow from the head merged into the base branch. A head
# whose .github/ is the one it branched from main with changes no workflow, so that
# merge runs only workflow code already on this repository's branches. A maintainer
# approves the rest.
if ! newest=$(gh api "repos/${GH_REPO}/actions/workflows/${workflow_id}/runs?event=pull_request&head_sha=${sha}&per_page=1" --jq '.workflow_runs[0].id') \
|| ! base=$(gh api "repos/${GH_REPO}/compare/main...${sha}" --jq .merge_base_commit.sha) \
|| ! head_tree=$(github_tree "$sha") || ! base_tree=$(github_tree "$base"); then
echo "::warning::Could not read the ${name} runs or the .github/ trees for ${sha}."
failed=1
continue
fi
# Reopening a pull request leaves an older run at the same head; only the newest runs.
[ "$newest" = "$run_id" ] || continue
if [ -z "$head_tree" ] || [ "$head_tree" != "$base_tree" ]; then
echo "::notice::Leaving ${name} run ${run_id} to a maintainer: ${sha} changes .github/."
continue
fi
if gh api -X POST "repos/${GH_REPO}/actions/runs/${run_id}/approve" > /dev/null; then
echo "Approved ${name} run ${run_id} for ${sha}."
# A maintainer or another run of this workflow may have approved it first.
elif ! conclusion=$(gh api "repos/${GH_REPO}/actions/runs/${run_id}" --jq .conclusion) \
|| [ "$conclusion" = action_required ]; then
echo "::warning::Could not approve ${name} run ${run_id} for ${sha}."
failed=1
else
echo "${name} run ${run_id} no longer waits for approval."
fi
done <<< "$runs"
exit "$failed"
+8
View File
@@ -19,6 +19,8 @@ on:
- 'build_linux.sh'
- 'build_win.bat'
- 'scripts/test_build_win.ps1'
- 'scripts/check_exception_throw_info.ps1'
- 'scripts/test_check_exception_throw_info.ps1'
- 'build_release_macos.sh'
- 'scripts/build_preset_cache.*'
- 'scripts/flatpak/**'
@@ -41,6 +43,8 @@ on:
- 'build_linux.sh'
- 'build_win.bat'
- 'scripts/test_build_win.ps1'
- 'scripts/check_exception_throw_info.ps1'
- 'scripts/test_check_exception_throw_info.ps1'
- 'build_release_macos.sh'
- 'scripts/build_preset_cache.*'
- 'scripts/flatpak/**'
@@ -84,6 +88,10 @@ jobs:
shell: powershell
run: .\scripts\test_build_win.ps1
- name: Run the exception throw info check tests
shell: powershell
run: .\scripts\test_check_exception_throw_info.ps1
build_linux:
strategy:
fail-fast: false
+15 -15
View File
@@ -65,15 +65,6 @@ jobs:
shell: bash
run: |
leg="${{ runner.os }}-${{ inputs.arch || 'amd64' }}${{ runner.os == 'Windows' && format('-{0}', inputs.compiler) || '' }}"
# clang-cl refuses a precompiled header from another cl.exe build and ccache
# does not hash that build, so each one gets its own cache. The build number
# is read from cl.exe itself; the toolset directory keeps its name across patches.
if [ "${{ runner.os }}" = Windows ]; then
vswhere='/c/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe'
toolset=$(tr -d '\r\n' < "$("$vswhere" -latest -products '*' -find 'VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt' | tr -d '\r')")
cl=$("$vswhere" -latest -products '*' -find 'VC\Tools\MSVC\'"$toolset"'\**\cl.exe' | tr -d '\r' | head -1)
leg="$leg-vc$("$cl" 2>&1 | grep -o -E 'Version [0-9.]+' | cut -d' ' -f2)"
fi
echo "CCACHE_LEG=$leg" >> "$GITHUB_ENV"
echo "CCACHE_ENTRY=ccache-$leg-${{ github.run_id }}-${{ github.run_attempt }}" >> "$GITHUB_ENV"
@@ -273,8 +264,9 @@ jobs:
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
CERTIFICATE_ID: ${{ secrets.MACOS_CERTIFICATE_ID }}
run: |
# Load the `retry` helper (retries flaky commands such as `hdiutil create`).
# Load the `retry` and `create_dmg` helpers.
source ${{ github.workspace }}/scripts/retry.sh
source ${{ github.workspace }}/scripts/create_dmg.sh
CERTIFICATE_PATH=$RUNNER_TEMP/build_certificate.p12
KEYCHAIN_PATH=$RUNNER_TEMP/app-signing.keychain-db
echo -n "$BUILD_CERTIFICATE_BASE64" | base64 --decode --output $CERTIFICATE_PATH
@@ -328,7 +320,7 @@ jobs:
rm -rf ${{ github.workspace }}/build/universal/OrcaSlicer_dmg/*
cp -R ${{ github.workspace }}/build/universal/OrcaSlicer/OrcaSlicer.app ${{ github.workspace }}/build/universal/OrcaSlicer_dmg/
ln -sfn /Applications ${{ github.workspace }}/build/universal/OrcaSlicer_dmg/Applications
retry hdiutil create -volname "OrcaSlicer" -srcfolder ${{ github.workspace }}/build/universal/OrcaSlicer_dmg -ov -format UDZO OrcaSlicer_Mac_universal_${{ env.ver }}.dmg
create_dmg "OrcaSlicer" ${{ github.workspace }}/build/universal/OrcaSlicer_dmg OrcaSlicer_Mac_universal_${{ env.ver }}.dmg
codesign --deep --force --verbose --options runtime --timestamp --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE_ID" OrcaSlicer_Mac_universal_${{ env.ver }}.dmg
# Create separate OrcaSlicer_profile_validator DMG if the app exists
@@ -337,7 +329,7 @@ jobs:
rm -rf ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg/*
cp -R ${{ github.workspace }}/build/universal/OrcaSlicer/OrcaSlicer_profile_validator.app ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg/
ln -sfn /Applications ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg/Applications
retry hdiutil create -volname "OrcaSlicer Profile Validator" -srcfolder ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg -ov -format UDZO OrcaSlicer_profile_validator_Mac_universal_${{ env.ver }}.dmg
create_dmg "OrcaSlicer Profile Validator" ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg OrcaSlicer_profile_validator_Mac_universal_${{ env.ver }}.dmg
codesign --deep --force --verbose --options runtime --timestamp --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE_ID" OrcaSlicer_profile_validator_Mac_universal_${{ env.ver }}.dmg
fi
@@ -355,13 +347,14 @@ jobs:
if: github.ref != 'refs/heads/main' && runner.os == 'macOS' && inputs.macos-combine-only
working-directory: ${{ github.workspace }}
run: |
# Load the `retry` helper (retries flaky commands such as `hdiutil create`).
# Load the `retry` and `create_dmg` helpers.
source ${{ github.workspace }}/scripts/retry.sh
source ${{ github.workspace }}/scripts/create_dmg.sh
mkdir -p ${{ github.workspace }}/build/universal/OrcaSlicer_dmg
rm -rf ${{ github.workspace }}/build/universal/OrcaSlicer_dmg/*
cp -R ${{ github.workspace }}/build/universal/OrcaSlicer/OrcaSlicer.app ${{ github.workspace }}/build/universal/OrcaSlicer_dmg/
ln -sfn /Applications ${{ github.workspace }}/build/universal/OrcaSlicer_dmg/Applications
retry hdiutil create -volname "OrcaSlicer" -srcfolder ${{ github.workspace }}/build/universal/OrcaSlicer_dmg -ov -format UDZO OrcaSlicer_Mac_universal_${{ env.ver }}.dmg
create_dmg "OrcaSlicer" ${{ github.workspace }}/build/universal/OrcaSlicer_dmg OrcaSlicer_Mac_universal_${{ env.ver }}.dmg
# Create separate OrcaSlicer_profile_validator DMG if the app exists
if [ -f "${{ github.workspace }}/build/universal/OrcaSlicer/OrcaSlicer_profile_validator.app/Contents/MacOS/OrcaSlicer_profile_validator" ]; then
@@ -369,7 +362,7 @@ jobs:
rm -rf ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg/*
cp -R ${{ github.workspace }}/build/universal/OrcaSlicer/OrcaSlicer_profile_validator.app ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg/
ln -sfn /Applications ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg/Applications
retry hdiutil create -volname "OrcaSlicer Profile Validator" -srcfolder ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg -ov -format UDZO OrcaSlicer_profile_validator_Mac_universal_${{ env.ver }}.dmg
create_dmg "OrcaSlicer Profile Validator" ${{ github.workspace }}/build/universal/OrcaSlicer_profile_validator_dmg OrcaSlicer_profile_validator_Mac_universal_${{ env.ver }}.dmg
fi
# Delete the per-arch bundles only after signing/DMG creation succeeded, so a
@@ -552,6 +545,13 @@ jobs:
name: OrcaSlicer_profile_validator_Windows_${{ env.ver }}
path: ${{ github.workspace }}/build/src/Release/OrcaSlicer_profile_validator.exe
- name: Check exception throw info Win
if: runner.os == 'Windows' && inputs.compiler == 'clang'
working-directory: ${{ github.workspace }}
# After the uploads, so a failure still leaves the build and its PDB to inspect, and before any deploy.
shell: pwsh
run: scripts\check_exception_throw_info.ps1 -BuildDir $env:BUILD_DIR
- name: Deploy Windows release portable
if: github.repository == 'OrcaSlicer/OrcaSlicer' && github.ref == 'refs/heads/main' && runner.os == 'Windows' && !vars.SELF_HOSTED
uses: ./.github/actions/deploy-nightly
+6 -1
View File
@@ -1,6 +1,8 @@
name: Check locale
on:
# approve_pr_checks.yml approves these runs for first-time contributors and finds this
# workflow by its file name.
pull_request:
branches:
- main
@@ -12,6 +14,9 @@ jobs:
check_translation:
name: Check translation
runs-on: ubuntu-latest
# approve_pr_checks.yml starts first-time contributors' runs without a maintainer looking
# at the pull request first. A run takes under a minute; this bounds one that msgfmt stalls on.
timeout-minutes: 10
steps:
- name: Checkout repository
uses: actions/checkout@v7
@@ -33,7 +38,7 @@ jobs:
if [ -f "$dir/OrcaSlicer_${lang}.po" ]; then
mkdir -p ./resources/i18n/${lang}/
msgfmt --check-format -o ./resources/i18n/${lang}/OrcaSlicer.mo $dir/OrcaSlicer_${lang}.po
msgfmt --check-format --check-header -o ./resources/i18n/${lang}/OrcaSlicer.mo $dir/OrcaSlicer_${lang}.po
# Check the exit status of the msgfmt command
if [ $? -ne 0 ]; then
echo "Error encountered with msgfmt command for language ${lang}."
+30
View File
@@ -1,5 +1,7 @@
name: Check profiles
on:
# approve_pr_checks.yml approves these runs for first-time contributors and finds this
# workflow by its file name.
pull_request:
# release/* is included because pr-merge-bot.yml lets delegates merge into
# it, and it gates on this workflow's result. Without it a delegated merge
@@ -37,6 +39,9 @@ jobs:
# delegated merge. Renaming it silently disables that gate.
name: Check profiles
runs-on: ubuntu-24.04
# approve_pr_checks.yml starts first-time contributors' runs without a maintainer looking
# at the pull request first. A run takes 2-6 minutes; this bounds a runaway one.
timeout-minutes: 30
steps:
- name: Checkout repository
uses: actions/checkout@v7
@@ -232,6 +237,31 @@ jobs:
mkdir -p ${{ runner.temp }}/profile-check-results
echo "${{ github.event.pull_request.number }}" > ${{ runner.temp }}/profile-check-results/pr_number.txt
# Builds a readable diff of the custom G-code the PR changes, which GitHub shows as
# one long line per setting, for check_profiles_comment.yml to post.
- name: Diff custom G-code
if: ${{ always() && github.event_name == 'pull_request' }}
continue-on-error: true
env:
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
git fetch --no-tags --depth=2 origin "$(git rev-parse HEAD)"
results=${{ runner.temp }}/profile-check-results
diff=${{ runner.temp }}/gcode_diff.md
# HEAD is the PR's merge commit, so HEAD^1 is the base it merges onto.
python3 ./scripts/orca_profile_tool.py gcode-diff --base HEAD^1 --head HEAD > "$diff"
if [ -s "$diff" ]; then
{
echo "<!-- profile-gcode-diff-comment -->"
cat "$diff"
echo ""
# The comment workflow finds this line as the only one starting with <sub>.
echo "<sub>For commit ${PR_HEAD_SHA} of this PR.</sub>"
} > "$results/gcode_diff.md"
fi
# Tells the comment workflow that a missing gcode_diff.md means no G-code changed.
touch "$results/gcode_diff_done.txt"
- name: Prepare comment artifact
if: ${{ always() && github.event_name == 'pull_request' && (steps.profile_tool.outcome == 'failure' || steps.legacy_compat.outcome == 'failure' || steps.validate_system.outcome == 'failure' || steps.validate_slice.outcome == 'failure' || steps.validate_filament_subtypes.outcome == 'failure' || steps.validate_custom.outcome == 'failure') }}
run: |
+58 -3
View File
@@ -38,6 +38,7 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
run: |
if [ ! -f pr_number.txt ]; then
echo "No pr_number.txt in artifact, skipping."
@@ -49,18 +50,72 @@ jobs:
echo "Invalid PR number: $PR_NUMBER"
exit 1
fi
# PR code wrote the artifact, so only a run for the named PR's current head may post.
if [ -z "$HEAD_SHA" ]; then
echo "The triggering run names no head commit."
exit 1
fi
if ! PR_HEAD=$(gh api "repos/${GH_REPO}/pulls/${PR_NUMBER}" --jq .head.sha); then
echo "Cannot look up PR #${PR_NUMBER}."
exit 1
fi
if [ "$HEAD_SHA" != "$PR_HEAD" ]; then
echo "${HEAD_SHA} is not the head of PR #${PR_NUMBER}; skipping."
exit 0
fi
# Lists every bot comment on the PR, one JSON object per line.
COMMENTS=$(gh api --paginate "repos/${GH_REPO}/issues/${PR_NUMBER}/comments" \
--jq '.[] | select(.user.login == "github-actions[bot]") | {id, body} | @json')
# Delete prior comments matching the marker (from check_profiles.yml) or the legacy heading.
OLD_IDS=$(gh api --paginate "repos/${GH_REPO}/issues/${PR_NUMBER}/comments" \
--jq '.[] | select(.user.login == "github-actions[bot]") | select((.body | startswith("<!-- profile-validation-comment -->")) or (.body | startswith("## :x: Profile Validation Errors"))) | .id')
OLD_IDS=$(printf '%s\n' "$COMMENTS" | jq -r 'select((.body | startswith("<!-- profile-validation-comment -->")) or (.body | startswith("## :x: Profile Validation Errors"))) | .id')
for comment_id in $OLD_IDS; do
echo "Deleting outdated profile-validation comment ${comment_id}"
gh api -X DELETE "repos/${GH_REPO}/issues/comments/${comment_id}" || true
done
# Post a new comment only when validation failed (pr_comment.md present).
# A failed post fails the job only after the G-code diff is handled.
failed=0
if [ -f pr_comment.md ]; then
gh pr comment "$PR_NUMBER" --body-file pr_comment.md
gh pr comment "$PR_NUMBER" --body-file pr_comment.md || failed=1
else
echo "Validation succeeded; cleaned up prior comments without posting."
fi
# Makes the G-code diff comment match gcode_diff.md, or deletes it if there is none.
update_gcode_diff_comment() {
if [ ! -f gcode_diff_done.txt ]; then
echo "The G-code diff step did not finish; leaving any G-code diff comment as it is."
return 0
fi
GCODE_IDS=$(printf '%s\n' "$COMMENTS" | jq -r 'select(.body | startswith("<!-- profile-gcode-diff-comment -->")) | .id')
if [ -f gcode_diff.md ] && [ "$(wc -c < gcode_diff.md)" -gt 65536 ]; then
echo "gcode_diff.md is over GitHub's comment limit; not posting it."
rm gcode_diff.md
fi
if [ -f gcode_diff.md ] && [ "$(echo "$GCODE_IDS" | wc -w)" -eq 1 ]; then
OLD_BODY=$(printf '%s\n' "$COMMENTS" | jq -r --argjson id "$GCODE_IDS" 'select(.id == $id) | .body' | tr -d '\r')
NEW_BODY=$(tr -d '\r' < gcode_diff.md)
if [ "$OLD_BODY" = "$NEW_BODY" ]; then
echo "G-code diff unchanged; keeping comment ${GCODE_IDS}."
return 0
fi
# Edits in place when only the <sub> line differs, since edits notify nobody.
if [ "$(grep -v '^<sub>' <<< "$OLD_BODY")" = "$(grep -v '^<sub>' <<< "$NEW_BODY")" ]; then
echo "G-code diff unchanged at a new commit; updating comment ${GCODE_IDS}."
gh api -X PATCH "repos/${GH_REPO}/issues/comments/${GCODE_IDS}" -F body=@gcode_diff.md > /dev/null
return 0
fi
fi
for comment_id in $GCODE_IDS; do
echo "Deleting outdated G-code diff comment ${comment_id}"
gh api -X DELETE "repos/${GH_REPO}/issues/comments/${comment_id}" || true
done
if [ -f gcode_diff.md ]; then
gh pr comment "$PR_NUMBER" --body-file gcode_diff.md
fi
}
update_gcode_diff_comment
exit "$failed"
+7
View File
@@ -8,6 +8,9 @@ name: clang-tidy
# No paths filter: the job is a required check, and a workflow skipped by a
# paths filter leaves a required check pending forever. A PR with no C++
# changes finishes after the first step.
#
# approve_pr_checks.yml approves this workflow's runs for first-time
# contributors and finds it by its file name.
on:
pull_request:
branches:
@@ -36,6 +39,10 @@ jobs:
# that gate.
name: clang-tidy
runs-on: ${{ vars.SELF_HOSTED && 'orca-lnx-server' || 'ubuntu-24.04' }}
# approve_pr_checks.yml starts first-time contributors' runs without a
# maintainer looking at the pull request first. The deps-cache wait alone may
# take 100 minutes; this bounds a runaway run without cutting a real one.
timeout-minutes: 180
steps:
- name: Checkout
uses: actions/checkout@v7
+7 -1
View File
@@ -50,6 +50,12 @@ jobs:
'documentation'
];
const pr = context.payload.pull_request;
// First-time contributors also get a link to the contributing guide
const greeting = ['FIRST_TIME_CONTRIBUTOR', 'FIRST_TIMER'].includes(pr.author_association)
? `Hi @${pr.user.login}, thanks for contributing to OrcaSlicer! ` +
`[How to Contribute](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute) explains what reviewers need from a PR.\n\n` +
`You can`
: `Hi @${pr.user.login}, you can`;
const labelsList = `${allowedLabels
.slice(0, -1)
.map((label) => `\`${label}\``)
@@ -72,7 +78,7 @@ jobs:
repo: context.repo.repo,
issue_number: pr.number,
body:
`Hi @${pr.user.login}, you can manage the labels for this PR by \`/bot add-label\` and \`/bot remove-label\`\n\n` +
`${greeting} manage the labels for this PR by \`/bot add-label\` and \`/bot remove-label\`.\n\n` +
`Allowed labels are:\n${labelsList}\n\n` +
`Examples:\n${examplesText}`
});
+6 -2
View File
@@ -58,6 +58,10 @@ ctest --test-dir ./tests/fff_print -C Release
- Profile/format changes need version migration handling
- Dependencies built separately in `deps/build/`, then linked to main app
## Pull requests
Before opening a pull request or posting on GitHub, read [CONTRIBUTING.md](CONTRIBUTING.md), including its "If you are an AI agent" section.
## Code review focus areas
- Changes must not cause regressions in existing functionality, defaults, profiles, or project compatibility.
@@ -91,7 +95,7 @@ See `.claude/skills/orca-translations/references/source-audit.md` for the full c
### Terminology
- Use the [Localization glossary](https://github.com/OrcaSlicer/OrcaSlicer_WIKI/blob/main/developer_reference/localization_glossary.md) as the source of truth for recurring terms, so the same English term is always rendered the same way within a language, and terms that must stay in English (brand/product names, acronyms, materials, file formats, G-code tokens, macros/variables/identifiers) are not translated.
- If a term's established translation changes, update both the affected `.po` files and the glossary (`localization_glossary.tsv`, then regenerate) so they stay in sync.
- If a term's established translation changes, update both the affected `.po` files and the glossary (`developer_reference/glossary/<lang>.tsv` in the wiki, then regenerate) so they stay in sync.
- Translate the *meaning*, not the words. Check what the string actually controls before translating it — English reuses one word for different things. `Flow ratio` (multiplier), `Flow Rate` (throughput) and `Flow Dynamics` (pressure compensation) are three different terms; `extruder` may mean the toolhead, the feeder motor, or the nozzle depending on the string.
- Reuse one template per recurring message shape (`Failed to connect to …`, `Are you sure you want to …?`), even where the English wording varies.
@@ -112,5 +116,5 @@ See `.claude/skills/orca-translations/references/source-audit.md` for the full c
### Verifying
- `scripts/run_gettext.bat --full` (Windows) regenerates the template, merges every catalog and compiles the `.mo` files. It must exit 0.
- Or check a single catalog with `msgfmt --check-format -o <out>.mo localization/i18n/<lang>/OrcaSlicer_<lang>.po`.
- Or check a single catalog with `msgfmt --check-format --check-header -o <out>.mo localization/i18n/<lang>/OrcaSlicer_<lang>.po`. Without `--check-header`, msgfmt skips the placeholder check in plural forms.
- Fuzzy entries are not shown to users. If you correct one, clear its `fuzzy` flag, otherwise the fix never ships.
+21 -3
View File
@@ -288,6 +288,19 @@ if (APPLE)
# Type"); Ninja/-Wall does not, and under -Werror it fails Xcode builds on code CI accepts.
set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_64_TO_32_BIT_CONVERSION "NO")
# The Xcode generator ignores CMAKE_<LANG>_COMPILER_LAUNCHER, so hand the launcher to
# Xcode's own Compiler Launcher setting, which wraps every clang compile (C, C++,
# Objective-C++ and the precompiled header) with one program: the C++ launcher wins when
# both are set. The setting takes a single program path, not a CMake launcher list.
# Xcode versions without it ignore it and build uncached.
if (CMAKE_GENERATOR STREQUAL "Xcode")
if (CMAKE_CXX_COMPILER_LAUNCHER)
set(CMAKE_XCODE_ATTRIBUTE_C_COMPILER_LAUNCHER "${CMAKE_CXX_COMPILER_LAUNCHER}")
elseif (CMAKE_C_COMPILER_LAUNCHER)
set(CMAKE_XCODE_ATTRIBUTE_C_COMPILER_LAUNCHER "${CMAKE_C_COMPILER_LAUNCHER}")
endif ()
endif ()
message(STATUS "Orca: IS_CROSS_COMPILE: ${IS_CROSS_COMPILE}")
elseif (CMAKE_SYSTEM_NAME STREQUAL "Linux")
set(CMAKE_INSTALL_RPATH "$ORIGIN")
@@ -308,6 +321,14 @@ if (IS_CROSS_COMPILE)
set(BUILD_TESTS OFF CACHE BOOL "" FORCE)
endif ()
# With a precompiled header, clang-cl can omit an exception type's copy constructor from its throw info,
# so copies of the exception share and double-free their data: https://github.com/llvm/llvm-project/issues/53486
if (MSVC AND CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
message(STATUS "clang-cl: building without the precompiled header (llvm/llvm-project#53486)")
set_property(CACHE SLIC3R_PCH PROPERTY HELPSTRING "Use precompiled headers (ignored with clang-cl, llvm/llvm-project#53486)")
set(SLIC3R_PCH OFF)
endif ()
# Print out the SLIC3R_* cache options
get_cmake_property(_cache_vars CACHE_VARIABLES)
list (SORT _cache_vars)
@@ -797,7 +818,6 @@ find_package(TBB REQUIRED)
find_package(OpenSSL REQUIRED)
find_package(CURL REQUIRED)
find_package(Freetype REQUIRED)
if (SLIC3R_GUI)
# LibDataChannel's installed export references its bundled dependencies,
@@ -1110,7 +1130,6 @@ function(orcaslicer_copy_dlls target config postfix output_dlls)
"SLIC3R_CAD setting as this project.")
endif ()
file(COPY ${_occt_dlls}
${CMAKE_PREFIX_PATH}/bin/freetype.dll
${CMAKE_PREFIX_PATH}/bin/avformat-61.dll
${CMAKE_PREFIX_PATH}/bin/avcodec-61.dll
${CMAKE_PREFIX_PATH}/bin/swresample-5.dll
@@ -1123,7 +1142,6 @@ function(orcaslicer_copy_dlls target config postfix output_dlls)
${_out_dir}/libmpfr-4.dll
${_out_dir}/WebView2Loader.dll
${_out_dir}/freetype.dll
${_out_dir}/avformat-61.dll
${_out_dir}/avcodec-61.dll
${_out_dir}/swresample-5.dll
+105
View File
@@ -0,0 +1,105 @@
# Contributing to OrcaSlicer
Thanks for wanting to help! OrcaSlicer is built by volunteers.
Review is the slowest part of getting a PR merged. A small group of reviewers works through hundreds of open PRs in their spare time. If a PR has what they need, it is reviewed sooner and is more likely to be merged. [How to Contribute](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute) on the wiki has the details for each kind of PR.
For questions about using OrcaSlicer, please ask on [Discord](https://discord.gg/P4VE9UY9gJ) or in [Discussions](https://github.com/OrcaSlicer/OrcaSlicer/discussions), not in an issue or PR.
Opening an issue? See [Opening an Issue](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#opening-an-issue).
## The short version
- Search open PRs and issues before you start. Someone may already be working on it.
- Keep each PR to one topic. Put changes that belong together in one PR, and unrelated changes in separate PRs. Focused PRs are reviewed and merged much faster.
- Don't open many PRs at once. If you already have several open, wait until some are merged.
- Explain why the change is needed, and show how you tested it. Add an automated test when the code can be tested.
- AI tools are welcome. You are still responsible for the change, so test it and make sure you understand it.
- Keep your PR up to date and reply to review comments.
## Write a description reviewers can use
Use the [PR template](.github/pull_request_template.md), and keep its "How to Download Pull Requests Artifacts" link as the last line. Testers use that link. In the template, answer these questions:
- **What does this change, and why is it needed?** If it fixes an issue, write `Fixes #1234` in the description, so GitHub closes the issue when the PR is merged. If it fixes only part of an issue, mention `#1234` without `Fixes`, so the issue stays open.
- **Are there related PRs or issues?** If another PR touches the same code or bug, explain how yours is different.
- **How did you test it?** Give the OS, the printer profile and the steps. Attach a project file if the result depends on a model or settings. Name any automated tests you added. The best test fails without your change and passes with it. See [tests/AGENTS.md](tests/AGENTS.md) for where a test goes.
- **What could you not test?** For example another OS, or a printer you don't own.
Use short, plain sentences, because many reviewers read English as a second language. Your own English is fine, and so is a translation tool.
## What each kind of PR needs
| Kind of PR | Label | Reviewers need to see |
|---|---|---|
| [Bug fix](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#bug-fixes) | `bug-fix`, `crash` | The cause, before and after, a test if possible |
| [Security fix](SECURITY.md) | `SECURITY` | A private report to the maintainers first |
| [New feature or setting](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#new-features-and-settings) | `enhancement`, `QoL` | Why users need it, that it is off by default, real results |
| [Performance](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#performance) | `optimization` | Measurements, and proof the output did not change |
| [Refactor](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#refactors) | `optimization` | That behavior and output did not change |
| [GUI change](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#gui-changes) | `UI/UX` | Screenshots before and after, on each platform you tested |
| [Printer profile](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#printer-profiles) | `profile` | The validator passing, the version bump, real print results |
| [Translation](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#translations) | `Localization` | Glossary terms used, placeholders unchanged |
| [Build, CI or dependencies](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#build-ci-and-dependencies) | `build`, `dependencies` | Which platforms you built on |
| [Tests](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#tests) | `test` | That the test fails when the behavior breaks |
| [Documentation](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#documentation) | `documentation` | That it matches the current code |
## Rules that are easy to miss
- **Don't reformat existing code or make unrelated edits.** `.clang-format` is for new files. In existing files, match the code around your change.
- **Include what you use.** Because of the precompiled header, a local build can succeed with a missing include. Run `scripts/run_clang_tidy.sh` (or `.ps1`) before you push.
- **New behavior is off by default.** When the new option is off, existing output must not change.
- **Keep old projects and profiles working.** Never change what an existing setting means. Add a new key, and convert old values in `handle_legacy`.
- **Write each UI message as one translatable string** with placeholders, never as joined fragments. See "Writing translatable strings in the source" in [AGENTS.md](AGENTS.md).
- **Only edit `msgstr` in translations.** Keep every placeholder and `\n` exactly as in the `msgid`.
- **Bump the vendor version when you change profiles.** Change `version` in `resources/profiles/<Vendor>.json` for every vendor you change, and run `scripts/check_profile.sh` (or `.bat`).
The code style and the full list of what reviewers check are in [AGENTS.md](AGENTS.md).
## Using AI tools
AI tools are welcome here, and many contributors and maintainers use them. Reviewers can only spend time on PRs that a person has already tested.
- **You are responsible for the change.** Before you ask for review, build the change, run it, and confirm that it works. Be ready to explain each change and why it is needed.
- **Keep it short and true.** AI tools tend to write long descriptions, and sometimes describe tests that never ran. Remove generated code that isn't needed, too. A short description of what you actually did helps more.
- **Read what you post.** Please don't paste a review comment into an AI tool and post its answer without checking it.
- **Don't let an agent open PRs or post comments on its own.** Read everything before it is posted.
- **Use the repository's skills.** `.claude/skills/` (also reachable as `.agents/skills/`) has instructions for AI tools on parts of OrcaSlicer. The top of each skill's `SKILL.md` describes when to use it. Some tools load them automatically. With others, point the tool to the skill that matches your change.
### If you are an AI agent
If you are an AI agent working for a contributor, please follow these steps:
1. Show the contributor this guide before you open a PR or post a comment.
2. Search open PRs for the same change before you start.
3. If the contributor already has several open PRs, wait until some are merged before you open another.
4. Before you change code, check `.claude/skills/` for a skill that matches the change, and follow it.
5. If the code can be tested, add an automated test, and check that it fails without the change and passes with it.
6. Ask the contributor to test the change by hand. For a bug fix, they should build the code without the change and reproduce the bug. Then they should build the branch and check that the bug is gone.
7. Write the PR description in the [PR template](.github/pull_request_template.md). A body passed with `gh pr create --body` replaces the template, so start from the template's text.
8. If you couldn't build or run something, say so in the PR.
## After you open the PR
- **Add labels.** A bot will comment with instructions. Reply with the labels from the table above, for example `/bot add-label bug-fix, UI/UX`.
- **Leave "Allow edits by maintainers" turned on**, so a reviewer can push small fixes directly.
- **Mark the PR ready for review when it's finished.** Draft PRs are not merged.
- **Push new commits to the same PR.** Please don't open a new PR for the same change.
- **Don't force-push once a reviewer has commented.** Add new commits instead, so reviewers can see what changed since they last looked. To fix merge conflicts, merge `main` into your branch. PRs are usually squash-merged, so extra commits are fine.
- **Reply to every review comment**, including automated ones. You don't have to agree, but please say why.
Reviewers are volunteers, and a first response can take a while. If you already have several PRs open, please wait until some are merged before you open more. Review comments on one PR often apply to the others too. While you wait, there are [other ways to help](https://www.orcaslicer.com/wiki/developer_reference/how_to_contribute#other-ways-to-help).
## If your PR is closed
There are more PRs than reviewers can handle, so we may close a PR that doesn't meet this guide. For example, it may have no explanation of how it was tested, duplicate another PR, or look generated and untested. When we close a PR, we'll say why in a comment.
You're welcome to open a new PR once the change meets this guide. Please link the old PR in the description, so reviewers can see the earlier discussion. Thank you for the time you put into it.
## Security issues
Please don't report security problems in a public issue. See [SECURITY.md](SECURITY.md).
## Thank you
Thanks again for helping. We're glad you're here.
+17 -3
View File
@@ -22,7 +22,7 @@ function usage() {
echo " -g: run the requested build steps inside a Docker/Podman Ubuntu 24.04 container similar to the GitHub Actions Linux runner"
echo " -h: prints this help text"
echo " -i: build the Orca Slicer AppImage (optional)"
echo " -p: boost ccache hit rate by disabling precompiled headers (default: ON)"
echo " -p: disable precompiled headers (on by default): more ccache hits after header changes, slower misses"
echo " -r: skip RAM and disk checks (low RAM compiling)"
echo " -s: build the Orca Slicer (optional)"
echo " -t: build tests (optional), requires -s flag"
@@ -473,8 +473,8 @@ fi
# cmake 4.x compatibility workaround
export CMAKE_POLICY_VERSION_MINIMUM=3.5
DISTRIBUTION=$(awk -F= '/^ID=/ {print $2}' /etc/os-release | tr -d '"')
DISTRIBUTION_LIKE=$(awk -F= '/^ID_LIKE=/ {print $2}' /etc/os-release | tr -d '"')
DISTRIBUTION=$(awk -F= '/^ID=/ {print $2}' /etc/os-release | tr -d "'\"")
DISTRIBUTION_LIKE=$(awk -F= '/^ID_LIKE=/ {print $2}' /etc/os-release | tr -d "'\"")
# Check for direct distribution match to Ubuntu/Debian
if [ "${DISTRIBUTION}" == "ubuntu" ] || [ "${DISTRIBUTION}" == "linuxmint" ] ; then
DISTRIBUTION="debian"
@@ -549,6 +549,20 @@ fi
if [ -n "${CMAKE_CCACHE}" ] ; then
echo "${CMAKE_CCACHE} found, enabling compiler caching..."
export CMAKE_CCACHE_ARGS=(-DCMAKE_C_COMPILER_LAUNCHER="${CMAKE_CCACHE}" -DCMAKE_CXX_COMPILER_LAUNCHER="${CMAKE_CCACHE}")
# The same ccache settings as the CI build. Without this sloppiness ccache refuses every
# compile that uses the precompiled header, which is most of OrcaSlicer, and skips headers
# a checkout has just written. It is added to the sloppiness already configured, and
# CCACHE_SLOPPINESS or CCACHE_(NO)DEPEND set in the environment win.
if [[ "$(basename "${CMAKE_CCACHE}")" == ccache ]] ; then
if [[ -z "${CCACHE_SLOPPINESS+x}" ]] ; then
CCACHE_SLOPPINESS=$("${CMAKE_CCACHE}" --get-config sloppiness 2>/dev/null || true)
export CCACHE_SLOPPINESS="${CCACHE_SLOPPINESS:+${CCACHE_SLOPPINESS},}pch_defines,time_macros,include_file_mtime,include_file_ctime"
fi
# Hash the includes the compiler reports instead of preprocessing every miss.
if [[ -z "${CCACHE_DEPEND+x}${CCACHE_NODEPEND+x}" ]] ; then
export CCACHE_DEPEND=1
fi
fi
else
echo "Note: ccache or sccache are not found. Install either of them for faster rebuilds."
fi
+82 -4
View File
@@ -47,26 +47,46 @@ while getopts ":dpa:snt:xbc:i:j:Tuh" opt; do
u )
export BUILD_TARGET="universal"
;;
h ) echo "Usage: ./build_release_macos.sh [-d]"
h ) echo "Usage: ./build_release_macos.sh [-d] [-- CMAKE_ARGS...]"
echo " -d: Build deps only"
echo " -a: Set ARCHITECTURE (arm64 or x86_64 or universal)"
echo " -s: Build slicer only"
echo " -u: Build universal app only (requires existing arm64 and x86_64 app bundles)"
echo " -n: Nightly build"
echo " -t: Specify minimum version of the target platform, default is 12.0"
echo " -x: Use Ninja Multi-Config CMake generator, default is Xcode"
echo " -x: Use Ninja Multi-Config CMake generator, default is Xcode (requires ninja; install with 'brew install ninja')"
echo " -b: Build without reconfiguring CMake"
echo " -c: Set CMake build configuration, default is Release"
echo " -i: Add a prefix to ignore during CMake dependency discovery (repeatable), defaults to /opt/local:/usr/local:/opt/homebrew"
echo " -j: Set the number of parallel build jobs (CMAKE_BUILD_PARALLEL_LEVEL)"
echo " -T: Build and run tests (set ORCA_TESTS_BUILD_ONLY=1 to build without running)"
echo " -- CMAKE_ARGS...: pass everything after '--' to the cmake configure step of the deps (-d) and slicer (-s) builds,"
echo " e.g. -DDESTDIR=<dir> for the deps, -DCMAKE_PREFIX_PATH=<dir>/usr/local -DSLIC3R_PCH=OFF for the slicer, --fresh."
echo " They come last on the cmake command line. Use absolute paths: cmake runs in the build directory."
exit 0
;;
: )
echo "Option -${OPTARG} requires an argument, aborting."
exit 1
;;
* )
echo "Unknown option -${OPTARG}, aborting. CMake arguments must follow '--'."
exit 1
;;
esac
done
# getopts stops at '--'; whatever follows is handed to cmake unchanged.
if [[ ${OPTIND} -le $# ]] ; then
separator_index=$((OPTIND-1))
if [[ "${!separator_index}" != "--" ]] ; then
echo "Unexpected argument '${!OPTIND}': cmake arguments must follow '--', aborting."
exit 1
fi
fi
shift $((OPTIND-1))
EXTRA_CMAKE_ARGS=("$@")
# Set defaults
if [ -z "$ARCH" ]; then
@@ -102,6 +122,12 @@ if [ -z "$CMAKE_IGNORE_PREFIX_PATH" ]; then
export CMAKE_IGNORE_PREFIX_PATH="/opt/local:/usr/local:/opt/homebrew"
fi
if [[ "$SLICER_CMAKE_GENERATOR" == Ninja* || "$DEPS_CMAKE_GENERATOR" == Ninja* ]] && ! command -v ninja >/dev/null 2>&1; then
echo "Error: Ninja is required when using the -x generator option."
echo "Install it with Homebrew: brew install ninja"
exit 1
fi
CMAKE_VERSION=$(cmake --version | head -1 | sed 's/[^0-9]*\([0-9]*\).*/\1/')
if [ "$CMAKE_VERSION" -ge 4 ] 2>/dev/null; then
export CMAKE_POLICY_VERSION_MINIMUM=3.10
@@ -111,6 +137,54 @@ else
export CMAKE_POLICY_COMPAT=""
fi
# Compiler cache, as in build_linux.sh. The program comes from CMAKE_CCACHE, else from a
# launcher already set in the environment (the CI build sets ccache there), else sccache or
# ccache from PATH; one program serves both languages. Each run applies its own choice to the
# build directories, replacing a launcher an earlier run or a hand-run configure recorded.
CMAKE_CCACHE_ARGS=()
CCACHE_VAR=""
for var in CMAKE_CCACHE CMAKE_CXX_COMPILER_LAUNCHER CMAKE_C_COMPILER_LAUNCHER; do
if [ -n "${!var:-}" ]; then
CCACHE_VAR=$var
break
fi
done
if [ -n "$CCACHE_VAR" ]; then
CCACHE_PROGRAM=${!CCACHE_VAR}
echo "Checking ${CCACHE_VAR} environment variable for compiler cache program..."
CMAKE_CCACHE=$(command -v "${CCACHE_PROGRAM}") || {
echo "${CCACHE_VAR} environment variable is set to '${CCACHE_PROGRAM}' but it was not found in PATH."
CMAKE_CCACHE=""
}
elif command -v sccache >/dev/null 2>&1 ; then
CMAKE_CCACHE=$(command -v sccache)
elif command -v ccache >/dev/null 2>&1 ; then
CMAKE_CCACHE=$(command -v ccache)
fi
if [ -n "${CMAKE_CCACHE}" ] ; then
echo "${CMAKE_CCACHE} found, enabling compiler caching..."
CMAKE_CCACHE_ARGS=(-DCMAKE_C_COMPILER_LAUNCHER="${CMAKE_CCACHE}" -DCMAKE_CXX_COMPILER_LAUNCHER="${CMAKE_CCACHE}")
# The same ccache settings as the CI build. Without this sloppiness ccache refuses every
# compile that uses the precompiled header, which is most of OrcaSlicer, and skips headers
# a checkout has just written. It is added to the sloppiness already configured, and
# CCACHE_SLOPPINESS or CCACHE_(NO)DEPEND set in the environment win.
if [[ "$(basename "${CMAKE_CCACHE}")" == ccache ]] ; then
if [[ -z "${CCACHE_SLOPPINESS+x}" ]] ; then
CCACHE_SLOPPINESS=$("${CMAKE_CCACHE}" --get-config sloppiness 2>/dev/null || true)
export CCACHE_SLOPPINESS="${CCACHE_SLOPPINESS:+${CCACHE_SLOPPINESS},}pch_defines,time_macros,include_file_mtime,include_file_ctime"
fi
# Hash the includes the compiler reports instead of preprocessing every miss.
if [[ -z "${CCACHE_DEPEND+x}${CCACHE_NODEPEND+x}" ]] ; then
export CCACHE_DEPEND=1
fi
fi
else
echo "Note: ccache or sccache are not found. Install either of them for faster rebuilds."
# Clear a launcher recorded by an earlier configure. The entries must be set empty rather
# than removed: CMake fills a missing launcher entry from the environment.
CMAKE_CCACHE_ARGS=(-DCMAKE_C_COMPILER_LAUNCHER:STRING= -DCMAKE_CXX_COMPILER_LAUNCHER:STRING=)
fi
echo "Build params:"
echo " - ARCH: $ARCH"
echo " - BUILD_CONFIG: $BUILD_CONFIG"
@@ -162,7 +236,9 @@ function build_deps() {
-DCMAKE_OSX_ARCHITECTURES:STRING="${_ARCH}" \
-DCMAKE_OSX_DEPLOYMENT_TARGET="${OSX_DEPLOYMENT_TARGET}" \
-DCMAKE_IGNORE_PREFIX_PATH="${CMAKE_IGNORE_PREFIX_PATH}" \
${CMAKE_POLICY_COMPAT}
"${CMAKE_CCACHE_ARGS[@]}" \
${CMAKE_POLICY_COMPAT} \
"${EXTRA_CMAKE_ARGS[@]}"
fi
cmake --build . --config "$BUILD_CONFIG" --target deps
)
@@ -264,7 +340,9 @@ function build_slicer() {
-DCMAKE_OSX_ARCHITECTURES="${_ARCH}" \
-DCMAKE_OSX_DEPLOYMENT_TARGET="${OSX_DEPLOYMENT_TARGET}" \
-DCMAKE_IGNORE_PREFIX_PATH="${CMAKE_IGNORE_PREFIX_PATH}" \
${CMAKE_POLICY_COMPAT}
"${CMAKE_CCACHE_ARGS[@]}" \
${CMAKE_POLICY_COMPAT} \
"${EXTRA_CMAKE_ARGS[@]}"
fi
cmake --build . --config "$BUILD_CONFIG" --target "$SLICER_BUILD_TARGET"
)
+7 -4
View File
@@ -53,7 +53,7 @@ call :add_section "Build configuration"
call :add_arg config string "" config "release, debug, relwithdebinfo or minsizerel (default: release)"
call :add_arg target_arch string "" arch "x64 or arm64 (default: the host architecture)"
call :add_arg slicer_asan bool a asan "Build the slicer with ASAN enabled"
call :add_arg no_pch bool "" no-pch "Build without the precompiled header, implied by --cache"
call :add_arg no_pch bool "" no-pch "Build without the precompiled header, implied by -l and --cache"
call :add_section "Toolchain"
call :add_arg use_clang_cl bool l clang-cl "Use clang-cl as the compiler"
@@ -388,6 +388,9 @@ if "%use_ninja%" == "ON" if "%use_msbuild%" == "ON" (
exit /b 1
)
REM CMakeLists turns the precompiled header off for clang-cl (llvm/llvm-project#53486).
if "%use_clang_cl%" == "ON" set "no_pch=ON"
set "generator=!vs_gen_%vs_version%!"
if "%use_ninja%" == "ON" (
set "generator=Ninja Multi-Config"
@@ -543,7 +546,7 @@ REM real path rather than one glued onto the repository root.
for %%p in ("!build_dir!") do set "build_full=%%~fp"
echo Configuration: %build_type%, %arch%
if not "%clang_exe%" == "" echo Compiler: %clang_exe%
if "%no_pch%" == "ON" echo Precompiled header: off
if "%build_slicer%" == "ON" if "%no_pch%" == "ON" echo Precompiled header: off
if not "%cache_args%" == "" echo Compiler cache: %cache_exe%
set "SIG_FLAG="
@@ -716,8 +719,8 @@ if "%build_slicer%" == "ON" (
set "slicer_args=!slicer_args! -DSLIC3R_ASAN=ON"
)
REM A later -DSLIC3R_PCH=ON in ORCA_SLICER_CMAKE_ARGS still wins, because
REM CMake takes the last definition on the command line.
REM Under cl, a later -DSLIC3R_PCH=ON in ORCA_SLICER_CMAKE_ARGS still wins,
REM because CMake takes the last definition on the command line.
if "%no_pch%" == "ON" (
set "slicer_args=!slicer_args! -DSLIC3R_PCH=OFF"
)
-8
View File
@@ -351,7 +351,6 @@ if(FLATPAK)
find_package(EXPAT)
find_package(CURL)
find_package(JPEG)
find_package(Freetype)
find_package(OpenSSL 1.1...<3.2)
find_package(CURL)
endif()
@@ -441,12 +440,6 @@ if (NOT FLATPAK)
set(WXWIDGETS_PKG "dep_wxWidgets")
endif()
set(FREETYPE_PKG "")
if(NOT FREETYPE_FOUND)
include(FREETYPE/FREETYPE.cmake)
set(FREETYPE_PKG "dep_FREETYPE")
endif()
execute_process(
COMMAND ${GIT_EXECUTABLE} rev-parse --is-inside-work-tree
RESULT_VARIABLE REV_PARSE_RESULT
@@ -482,7 +475,6 @@ set(_dep_list
dep_CGAL
dep_GLFW
dep_OCCT
${FREETYPE_PKG}
${PNG_PKG}
${ZLIB_PKG}
${EXPAT_PKG}
-29
View File
@@ -1,29 +0,0 @@
if(WIN32)
set(library_build_shared "1")
else()
set(library_build_shared "0")
endif()
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
set(_ft_disable_zlib "-D FT_DISABLE_ZLIB=FALSE")
else()
set(_ft_disable_zlib "-D FT_DISABLE_ZLIB=TRUE")
endif()
orcaslicer_add_cmake_project(FREETYPE
URL https://github.com/SoftFever/orca_deps/releases/download/freetype-2.12.1.tar.gz/freetype-2.12.1.tar.gz
URL_HASH SHA256=efe71fd4b8246f1b0b1b9bfca13cfff1c9ad85930340c27df469733bbb620938
#DEPENDS ${ZLIB_PKG}
#"${_patch_step}"
CMAKE_ARGS
-D BUILD_SHARED_LIBS=${library_build_shared}
${_ft_disable_zlib}
-D FT_DISABLE_BZIP2=TRUE
-D FT_DISABLE_PNG=TRUE
-D FT_DISABLE_HARFBUZZ=TRUE
-D FT_DISABLE_BROTLI=TRUE
)
if(MSVC)
add_debug_dep(dep_FREETYPE)
endif()
+6 -2
View File
@@ -59,9 +59,13 @@ else ()
set(_cross_compile_arg --host=${TOOLCHAIN_PREFIX})
endif ()
# 6.3.0 is the first release whose arm64 assembly avoids x18, which macOS
# reserves and zeroes on every return to user space; 6.2.1 crashes on Apple
# silicon whenever CGAL falls back to exact arithmetic.
ExternalProject_Add(dep_GMP
URL https://github.com/SoftFever/OrcaSlicer_deps/releases/download/gmp-6.2.1/gmp-6.2.1.tar.bz2
URL_HASH SHA256=eae9326beb4158c386e39a356818031bd28f3124cf915f8c5b1dc4c7a36b4d7c
URL https://ftp.gnu.org/gnu/gmp/gmp-6.3.0.tar.xz
https://github.com/SoftFever/OrcaSlicer_deps/releases/download/gmp-6.3.0/gmp-6.3.0.tar.xz
URL_HASH SHA256=a3c2b80201b89e68616f4ad30bc66aee4927c3ce50e33929ca819d5c43538898
DOWNLOAD_DIR ${DEP_DOWNLOAD_DIR}/GMP
PATCH_COMMAND git apply ${GMP_DIRECTORY_FLAG} --verbose ${CMAKE_CURRENT_LIST_DIR}/0001-GMP_GCC15.patch
BUILD_IN_SOURCE ON
+2 -17
View File
@@ -1,22 +1,7 @@
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
if (JPEG_VERSION STREQUAL "6")
message("Using Jpeg Lib 62")
set(jpeg_flag "")
elseif (JPEG_VERSION STREQUAL "7")
message("Using Jpeg Lib 70")
set(jpeg_flag "-DWITH_JPEG7=ON")
else ()
message("Using Jpeg Lib 80")
set(jpeg_flag "-DWITH_JPEG8=ON")
endif ()
endif()
orcaslicer_add_cmake_project(JPEG
URL https://github.com/libjpeg-turbo/libjpeg-turbo/archive/refs/tags/3.0.1.zip
URL_HASH SHA256=d6d99e693366bc03897677650e8b2dfa76b5d6c54e2c9e70c03f0af821b0a52f
DEPENDS ${ZLIB_PKG}
URL https://github.com/libjpeg-turbo/libjpeg-turbo/archive/refs/tags/3.2.0.zip
URL_HASH SHA256=1b4c2cb6cba1ca5e53b9e85eeeab02154cab4b70894c96e97a9c747a26d19d63
CMAKE_ARGS
-DENABLE_SHARED=OFF
-DENABLE_STATIC=ON
${jpeg_flag}
)
+1 -4
View File
@@ -36,7 +36,6 @@ orcaslicer_add_cmake_project(OCCT
# (Open-Cascade-SAS/OCCT#572); remove the patch once an OCCT release includes the fix.
PATCH_COMMAND git apply ${OCCT_DIRECTORY_FLAG} --verbose --ignore-space-change --whitespace=fix ${CMAKE_CURRENT_LIST_DIR}/0001-BRepMesh-seam-pcurve-at-edge-parameter.patch
#DEPENDS dep_Boost
DEPENDS ${FREETYPE_PKG}
CMAKE_ARGS
-DCMAKE_CXX_STANDARD=17
-DBUILD_LIBRARY_TYPE=${library_build_type}
@@ -49,7 +48,7 @@ orcaslicer_add_cmake_project(OCCT
-DINSTALL_DIR_CMAKE=lib/cmake/occt
-DUSE_TK=OFF
-DUSE_TBB=OFF
#-DUSE_FREETYPE=OFF
-DUSE_FREETYPE=OFF
-DUSE_FFMPEG=OFF
-DUSE_VTK=OFF
-DBUILD_DOC_Overview=OFF
@@ -62,5 +61,3 @@ orcaslicer_add_cmake_project(OCCT
-DBUILD_MODULE_Visualization=OFF
${_occt_compiler_args}
)
# add_dependencies(dep_OCCT ${FREETYPE_PKG})
-54
View File
@@ -1,54 +0,0 @@
diff --git a/cmake/OpenCVDetectCXXCompiler.cmake b/cmake/OpenCVDetectCXXCompiler.cmake
index 7f229cde96..d8e20f8fe9 100644
--- a/cmake/OpenCVDetectCXXCompiler.cmake
+++ b/cmake/OpenCVDetectCXXCompiler.cmake
@@ -171,8 +171,10 @@ elseif(MSVC)
set(OpenCV_RUNTIME vc15)
elseif(MSVC_VERSION MATCHES "^192[0-9]$")
set(OpenCV_RUNTIME vc16)
- elseif(MSVC_VERSION MATCHES "^193[0-9]$")
+ elseif(MSVC_VERSION MATCHES "^19[34][0-9]$")
set(OpenCV_RUNTIME vc17)
+ elseif(MSVC_VERSION MATCHES "^195[0-9]$")
+ set(OpenCV_RUNTIME vc18)
else()
message(WARNING "OpenCV does not recognize MSVC_VERSION \"${MSVC_VERSION}\". Cannot set OpenCV_RUNTIME")
endif()
diff --git a/cmake/templates/OpenCVConfig.root-WIN32.cmake.in b/cmake/templates/OpenCVConfig.root-WIN32.cmake.in
index b0f254ebe8..8f0178b0ae 100644
--- a/cmake/templates/OpenCVConfig.root-WIN32.cmake.in
+++ b/cmake/templates/OpenCVConfig.root-WIN32.cmake.in
@@ -137,7 +137,7 @@ elseif(MSVC)
set(OpenCV_RUNTIME vc14) # selecting previous compatible runtime version
endif()
endif()
- elseif(MSVC_VERSION MATCHES "^193[0-9]$")
+ elseif(MSVC_VERSION MATCHES "^19[34][0-9]$")
set(OpenCV_RUNTIME vc17)
check_one_config(has_VS2022)
if(NOT has_VS2022)
@@ -151,6 +151,24 @@ elseif(MSVC)
endif()
endif()
endif()
+ elseif(MSVC_VERSION MATCHES "^195[0-9]$")
+ set(OpenCV_RUNTIME vc18)
+ check_one_config(has_VS2026)
+ if(NOT has_VS2026)
+ set(OpenCV_RUNTIME vc17)
+ check_one_config(has_VS2022)
+ if(NOT has_VS2022)
+ set(OpenCV_RUNTIME vc16)
+ check_one_config(has_VS2019)
+ if(NOT has_VS2019)
+ set(OpenCV_RUNTIME vc15) # selecting previous compatible runtime version
+ check_one_config(has_VS2017)
+ if(NOT has_VS2017)
+ set(OpenCV_RUNTIME vc14) # selecting previous compatible runtime version
+ endif()
+ endif()
+ endif()
+ endif()
endif()
elseif(MINGW)
set(OpenCV_RUNTIME mingw)
-54
View File
@@ -1,54 +0,0 @@
From 893b8113f04d408cc6177c6de19c9889a48faa24 Mon Sep 17 00:00:00 2001
From: Zixu Wang <zixu_wang@apple.com>
Date: Thu, 18 Jan 2024 11:12:00 -0800
Subject: [PATCH] Fix unused platform check and configuration for macOS
In a similar manner as zlib (https://github.com/madler/zlib/pull/895),
libpng contains a header configuration that's no longer valid and
hasn't been exercised for the macOS target.
- The target OS conditional macros are misused. Specifically
`TARGET_OS_MAC` covers all Apple targets, including iOS, and it
should not be checked with `#if defined` as they would always be
defined (to either 1 or 0) on Apple platforms.
- `#include <fp.h>` no longer works for the macOS target and results
in a compilation failure. macOS ships all required functions in
`math.h`, and clients should use `math.h` instead.
This problem has not been noticed until a recent extension in clang
(https://github.com/llvm/llvm-project/pull/74676) exposed the issue
and broke libpng builds on Apple platforms. The failure can be
reproduced now by adding `#include <TargetConditionals.h>` before the
block.
Signed-off-by: Cosmin Truta <ctruta@gmail.com>
---
AUTHORS | 2 ++
pngpriv.h | 14 ++------------
2 files changed, 4 insertions(+), 12 deletions(-)
diff --git a/3rdparty/libpng/pngpriv.h b/3rdparty/libpng/pngpriv.h
index 6c7280cf53..190eb85cbf 100644
--- a/3rdparty/libpng/pngpriv.h
+++ b/3rdparty/libpng/pngpriv.h
@@ -556,18 +556,8 @@
*/
# include <float.h>
-# if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
- defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
- /* We need to check that <math.h> hasn't already been included earlier
- * as it seems it doesn't agree with <fp.h>, yet we should really use
- * <fp.h> if possible.
- */
-# if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
-# include <fp.h>
-# endif
-# else
-# include <math.h>
-# endif
+# include <math.h>
+
# if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
/* Amiga SAS/C: We must include builtin FPU functions when compiling using
* MATH=68881
+19 -8
View File
@@ -17,15 +17,18 @@ if ("${DEPS_ARCH}" STREQUAL "arm64" AND CMAKE_CXX_COMPILER_ID STREQUAL Clang)
set(_disable_carotene "-DWITH_CAROTENE=OFF")
endif ()
if (IN_GIT_REPO)
set(OpenCV_DIRECTORY_FLAG --directory ${BINARY_DIR_REL}/dep_OpenCV-prefix/src/dep_OpenCV)
# clang-cl parses template bodies at the end of each file. In softfloat.cpp that
# is after OpenCV's own float32_t, which then hides the NEON one in arm_neon.h.
set(_clang_cl_flags "")
if (MSVC AND CMAKE_CXX_COMPILER_ID STREQUAL Clang)
set(_clang_cl_flags "-DOPENCV_EXTRA_CXX_FLAGS=-fno-delayed-template-parsing")
endif ()
orcaslicer_add_cmake_project(OpenCV
${_options}
URL https://github.com/opencv/opencv/archive/refs/tags/4.6.0.tar.gz
URL_HASH SHA256=1ec1cba65f9f20fe5a41fda1586e01c70ea0c9a6d7b67c9e13edf0cfe2239277
PATCH_COMMAND git apply ${OpenCV_DIRECTORY_FLAG} --verbose --ignore-space-change --whitespace=fix ${CMAKE_CURRENT_LIST_DIR}/0001-vs.patch ${CMAKE_CURRENT_LIST_DIR}/0002-clang19-macos.patch
URL https://github.com/opencv/opencv/archive/refs/tags/4.14.0.tar.gz
URL_HASH SHA256=ee8fb9b30eb60850431b4656447080e3737b56e45719c92b67f245950609f86e
DEPENDS ${JPEG_PKG} ${PNG_PKG}
CMAKE_ARGS
-DBUILD_SHARED_LIBS=0
-DBUILD_PERE_TESTS=OFF
@@ -34,12 +37,13 @@ orcaslicer_add_cmake_project(OpenCV
-DBUILD_EXAMPLES=OFF
-DBUILD_JASPER=OFF
-DBUILD_JAVA=OFF
-DBUILD_JPEG=ON
# Share Orca's libjpeg and libpng to avoid conflicting codec symbols in the application.
-DBUILD_JPEG=OFF
-DBUILD_PNG=OFF
-DBUILD_APPS_LIST=version
-DBUILD_opencv_apps=OFF
-DBUILD_opencv_java=OFF
-DBUILD_OPENEXR=OFF
-DBUILD_PNG=ON
-DBUILD_TBB=OFF
-DBUILD_WEBP=OFF
-DBUILD_ZLIB=OFF
@@ -67,10 +71,16 @@ orcaslicer_add_cmake_project(OpenCV
-DWITH_OPENJPEG=OFF
-DWITH_QUIRC=OFF
-DWITH_VTK=OFF
-DWITH_JPEG=OFF
# Textured GLB/OBJ imports decode embedded and external JPEGs with cv::imdecode.
-DWITH_JPEG=ON
-DWITH_WEBP=OFF
-DWITH_TIFF=OFF
-DBUILD_TIFF=OFF
# Codecs and HALs added after 4.6 that default to ON. AVIF would link any
# system libavif it finds, and KleidiCV is downloaded at configure time.
-DWITH_AVIF=OFF
-DWITH_IMGCODEC_GIF=OFF
-DWITH_KLEIDICV=OFF
-DENABLE_PRECOMPILED_HEADERS=OFF
-DINSTALL_TESTS=OFF
-DINSTALL_C_EXAMPLES=OFF
@@ -91,5 +101,6 @@ orcaslicer_add_cmake_project(OpenCV
-DWITH_WIN32UI=OFF
-DHAVE_WIN32UI=FALSE
${_disable_carotene}
${_clang_cl_flags}
)
+17 -7
View File
@@ -16,6 +16,8 @@ else()
endif()
endif()
set(_openssl_dir ${DESTDIR})
if(WIN32)
set(_openssl_msvc_env CC=cl CXX=cl RC=rc CL=/FS)
# OpenSSL's perl Configure honors the CC environment variable, but the
@@ -43,6 +45,14 @@ if(WIN32)
else()
if(APPLE)
set(_conf_cmd export MACOSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET} && ./Configure -mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET})
# OPENSSLDIR is only where OpenSSL looks at runtime for cert.pem, certs/
# and openssl.cnf; install_sw installs nothing there. Point it at the
# system CA bundle, the one libcurl already uses here, so the bundled
# Python's ssl module can verify HTTPS. Elsewhere it stays the prefix:
# Windows Python reads the system certificate store, and on Linux, where
# the bundle's location differs by distro, CurlGlobalInit points
# SSL_CERT_FILE at it at startup.
set(_openssl_dir /etc/ssl)
else()
# A static library that is embedded into a shared object must not export
# its symbols. On Linux the running process also loads the system OpenSSL
@@ -81,7 +91,7 @@ ExternalProject_Add(dep_OpenSSL
# URL_HASH SHA256=8c776993154652d0bb393f506d850b811517c8bd8d24b1008aef57fbe55d3f31
DOWNLOAD_DIR ${DEP_DOWNLOAD_DIR}/OpenSSL
CONFIGURE_COMMAND ${_conf_cmd} ${_cross_arch}
"--openssldir=${DESTDIR}"
"--openssldir=${_openssl_dir}"
"--prefix=${DESTDIR}"
# OpenSSL's linux-x86_64 target sets multilib=64, so it installs to
# <prefix>/lib64 while every other dep uses <prefix>/lib. CPython's
@@ -115,12 +125,12 @@ ExternalProject_Add_Step(dep_OpenSSL install_cmake_files
WORKING_DIRECTORY "${CMAKE_CURRENT_LIST_DIR}"
)
if (NOT WIN32 AND NOT APPLE)
# OpenSSL's object rules do not depend on CFLAGS, so reconfiguring it (for
# example to add -fvisibility=hidden) relinks the archives from stale
# objects instead of recompiling them, and the change silently has no
# effect. Drop the objects whenever this recipe changes so the next build
# actually recompiles them.
if (NOT WIN32)
# OpenSSL's object rules do not depend on the configured flags or paths, so
# reconfiguring it (a new compiler flag, a different --openssldir) relinks
# the archives from stale objects instead of recompiling them, and the
# change silently has no effect. Drop the objects whenever this recipe
# changes so the next build actually recompiles them.
ExternalProject_Get_Property(dep_OpenSSL SOURCE_DIR)
ExternalProject_Add_Step(dep_OpenSSL clean_objects
DEPENDEES configure
-29
View File
@@ -1,29 +0,0 @@
--- a/pngpriv.h 2025-04-20 19:36:04.000000000
+++ b/pngpriv.h 2025-04-20 19:35:55.000000000
@@ -511,24 +511,14 @@
* DBL_DIG Maximum number of decimal digits (can be set to any constant)
* DBL_MIN Smallest normalized fp number (can be set to an arbitrary value)
* DBL_MAX Maximum floating point number (can be set to an arbitrary value)
*/
# include <float.h>
-# if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
- defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
- /* We need to check that <math.h> hasn't already been included earlier
- * as it seems it doesn't agree with <fp.h>, yet we should really use
- * <fp.h> if possible.
- */
-# if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
-# include <fp.h>
-# endif
-# else
-# include <math.h>
-# endif
+# include <math.h>
+
# if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
/* Amiga SAS/C: We must include builtin FPU functions when compiling using
* MATH=68881
*/
# include <m68881.h>
# endif
+3 -40
View File
@@ -1,51 +1,14 @@
if (APPLE)
# Only disable NEON extension for Apple ARM builds, leave it enabled for Raspberry PI.
set(_disable_neon_extension "-DPNG_ARM_NEON=off")
elseif ("${DEPS_ARCH}" STREQUAL "arm64" AND CMAKE_CXX_COMPILER_ID STREQUAL Clang)
# libpng's CMake ignores PNG_ARM_NEON on Windows ARM64 and skips the NEON
# sources, but pngpriv.h enables NEON anyway.
set(_disable_neon_extension "-DCMAKE_C_FLAGS=/DWIN32 /D_WINDOWS /DPNG_ARM_NEON_OPT=0")
else ()
set(_disable_neon_extension "")
endif ()
if(APPLE AND IS_CROSS_COMPILE)
# TODO: check if it doesn't create problem when compiling from arm to x86_64
orcaslicer_add_cmake_project(PNG
GIT_REPOSITORY https://github.com/glennrp/libpng.git
GIT_TAG v1.6.35
orcaslicer_add_cmake_project(PNG
URL https://github.com/glennrp/libpng/archive/refs/tags/v1.6.59.zip
URL_HASH SHA256=6fd97a1e5e2ac55cec0a538a9800a351eb3844086736291844ebd12db72ba433
DEPENDS ${ZLIB_PKG}
PATCH_COMMAND ${GIT_EXECUTABLE} checkout -f -- . && git clean -df &&
${GIT_EXECUTABLE} apply --whitespace=fix ${CMAKE_CURRENT_LIST_DIR}/macos-arm64.patch ${CMAKE_CURRENT_LIST_DIR}/0002-clang19-macos.patch
CMAKE_ARGS
-DPNG_SHARED=OFF
-DPNG_STATIC=ON
-DPNG_PREFIX=prusaslicer_
-DPNG_TESTS=OFF
-DDISABLE_DEPENDENCY_TRACKING=OFF
${_disable_neon_extension}
)
else ()
set(_patch_step "")
if (APPLE)
set(_patch_step PATCH_COMMAND ${PATCH_CMD} ${CMAKE_CURRENT_LIST_DIR}/PNG.patch ${CMAKE_CURRENT_LIST_DIR}/0002-clang19-macos.patch)
endif ()
orcaslicer_add_cmake_project(PNG
# GIT_REPOSITORY https://github.com/glennrp/libpng.git
# GIT_TAG v1.6.35
URL https://github.com/glennrp/libpng/archive/refs/tags/v1.6.35.zip
URL_HASH SHA256=3d22d46c566b1761a0e15ea397589b3a5f36ac09b7c785382e6470156c04247f
DEPENDS ${ZLIB_PKG}
"${_patch_step}"
CMAKE_ARGS
-DPNG_SHARED=OFF
-DPNG_STATIC=ON
-DPNG_PREFIX=prusaslicer_
-DPNG_TESTS=OFF
-DDISABLE_DEPENDENCY_TRACKING=OFF
${_disable_neon_extension}
)
endif()
if (MSVC)
add_debug_dep(dep_PNG)
-26
View File
@@ -1,26 +0,0 @@
Common subdirectories: ../libpng-1.6.35-orig/arm and ./arm
Common subdirectories: ../libpng-1.6.35-orig/contrib and ./contrib
Common subdirectories: ../libpng-1.6.35-orig/intel and ./intel
Common subdirectories: ../libpng-1.6.35-orig/mips and ./mips
Only in ./: PNG.patch
diff -u ../libpng-1.6.35-orig/pngrutil.c ./pngrutil.c
--- ../libpng-1.6.35-orig/pngrutil.c 2018-07-15 20:58:00.000000000 +0200
+++ ./pngrutil.c 2021-03-24 15:59:38.687108444 +0100
@@ -422,13 +422,6 @@
png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED;
}
-#if ZLIB_VERNUM >= 0x1290 && \
- defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_IGNORE_ADLER32)
- if (((png_ptr->options >> PNG_IGNORE_ADLER32) & 3) == PNG_OPTION_ON)
- /* Turn off validation of the ADLER32 checksum in IDAT chunks */
- ret = inflateValidate(&png_ptr->zstream, 0);
-#endif
-
if (ret == Z_OK)
png_ptr->zowner = owner;
Common subdirectories: ../libpng-1.6.35-orig/powerpc and ./powerpc
Common subdirectories: ../libpng-1.6.35-orig/projects and ./projects
Common subdirectories: ../libpng-1.6.35-orig/scripts and ./scripts
Common subdirectories: ../libpng-1.6.35-orig/tests and ./tests
-90
View File
@@ -1,90 +0,0 @@
Based on https://github.com/vespakoen/libpng to work around until
https://github.com/glennrp/libpng/pull/354 is resolved.
also added patch from PS2.4 (PNG.pach) in pngrutil.c
---
CMakeLists.txt | 28 ++++++++++++++++++++--------
pngrutil.c | 7 -------
2 files changed, 20 insertions(+), 15 deletions(-)
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4db9bb87d..9099d1edf 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -82,10 +82,22 @@ option(PNG_HARDWARE_OPTIMIZATIONS "Enable Hardware Optimizations" ON)
set(PNG_PREFIX "" CACHE STRING "Prefix to add to the API function names")
set(DFA_XTRA "" CACHE FILEPATH "File containing extra configuration settings")
+# CMake currently sets CMAKE_SYSTEM_PROCESSOR to one of x86_64 or arm64 on macOS,
+# based upon the OS architecture, not the target architecture. As such, we need
+# to check CMAKE_OSX_ARCHITECTURES to identify which hardware-specific flags to
+# enable. Note that this will fail if you attempt to build a universal binary in
+# a single cmake invokation.
+if (APPLE AND CMAKE_OSX_ARCHITECTURES)
+ set(TARGET_ARCH ${CMAKE_OSX_ARCHITECTURES})
+else()
+ set(TARGET_ARCH ${CMAKE_SYSTEM_PROCESSOR})
+endif()
+
+
if(PNG_HARDWARE_OPTIMIZATIONS)
# set definitions and sources for arm
-if(CMAKE_SYSTEM_PROCESSOR MATCHES "^arm" OR
- CMAKE_SYSTEM_PROCESSOR MATCHES "^aarch64")
+if(TARGET_ARCH MATCHES "^arm" OR
+ TARGET_ARCH MATCHES "^aarch64")
set(PNG_ARM_NEON_POSSIBLE_VALUES check on off)
set(PNG_ARM_NEON "check" CACHE STRING "Enable ARM NEON optimizations:
check: (default) use internal checking code;
@@ -114,8 +126,8 @@ if(CMAKE_SYSTEM_PROCESSOR MATCHES "^arm" OR
endif()
# set definitions and sources for powerpc
-if(CMAKE_SYSTEM_PROCESSOR MATCHES "^powerpc*" OR
- CMAKE_SYSTEM_PROCESSOR MATCHES "^ppc64*" )
+if(TARGET_ARCH MATCHES "^powerpc*" OR
+ TARGET_ARCH MATCHES "^ppc64*" )
set(PNG_POWERPC_VSX_POSSIBLE_VALUES on off)
set(PNG_POWERPC_VSX "on" CACHE STRING "Enable POWERPC VSX optimizations:
off: disable the optimizations.")
@@ -138,8 +150,8 @@ if(CMAKE_SYSTEM_PROCESSOR MATCHES "^powerpc*" OR
endif()
# set definitions and sources for intel
-if(CMAKE_SYSTEM_PROCESSOR MATCHES "^i?86" OR
- CMAKE_SYSTEM_PROCESSOR MATCHES "^x86_64*" )
+if(TARGET_ARCH MATCHES "^i?86" OR
+ TARGET_ARCH MATCHES "^x86_64*" )
set(PNG_INTEL_SSE_POSSIBLE_VALUES on off)
set(PNG_INTEL_SSE "on" CACHE STRING "Enable INTEL_SSE optimizations:
off: disable the optimizations")
@@ -162,8 +174,8 @@ if(CMAKE_SYSTEM_PROCESSOR MATCHES "^i?86" OR
endif()
# set definitions and sources for MIPS
-if(CMAKE_SYSTEM_PROCESSOR MATCHES "mipsel*" OR
- CMAKE_SYSTEM_PROCESSOR MATCHES "mips64el*" )
+if(TARGET_ARCH MATCHES "mipsel*" OR
+ TARGET_ARCH MATCHES "mips64el*" )
set(PNG_MIPS_MSA_POSSIBLE_VALUES on off)
set(PNG_MIPS_MSA "on" CACHE STRING "Enable MIPS_MSA optimizations:
off: disable the optimizations")
diff --git a/pngrutil.c b/pngrutil.c
index 7001f1976..91930f1f2 100644
--- a/pngrutil.c
+++ b/pngrutil.c
@@ -422,13 +422,6 @@ png_inflate_claim(png_structrp png_ptr, png_uint_32 owner)
png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED;
}
-#if ZLIB_VERNUM >= 0x1290 && \
- defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_IGNORE_ADLER32)
- if (((png_ptr->options >> PNG_IGNORE_ADLER32) & 3) == PNG_OPTION_ON)
- /* Turn off validation of the ADLER32 checksum in IDAT chunks */
- ret = inflateValidate(&png_ptr->zstream, 0);
-#endif
-
if (ret == Z_OK)
png_ptr->zowner = owner;
--
2.33.0.windows.1
+5 -4
View File
@@ -365,10 +365,11 @@ if(TARGET dep_ZLIB)
add_dependencies(dep_python3 dep_ZLIB)
endif()
if (NOT WIN32 AND NOT APPLE)
# CPython's Makefile rules for _ssl and _hashlib depend only on their own
# sources, not on the OpenSSL archives, so a rebuilt OpenSSL does not make
# them relink and they keep the previous symbols. On an incremental tree,
if (NOT WIN32)
# _ssl and _hashlib embed the static OpenSSL built in deps/ (Windows uses
# CPython's prebuilt OpenSSL instead). Their Makefile rules depend only on
# their own sources, not on the OpenSSL archives, so a rebuilt OpenSSL does
# not make them relink and they keep the previous one. On an incremental tree,
# drop the built modules and relink them against the current OpenSSL; a
# fresh build is left alone (its PGO target builds them). "make" alone is a
# no-op once PGO has run, so sharedmods is invoked explicitly.
@@ -1,29 +0,0 @@
diff --git a/src/osx/cocoa/colour.mm b/src/osx/cocoa/colour.mm
index 31515d146f..86b33e94a2 100644
--- a/src/osx/cocoa/colour.mm
+++ b/src/osx/cocoa/colour.mm
@@ -125,3 +125,3 @@
wxOSXEffectiveAppearanceSetter helper;
- if ( NSColor* colRGBA = [m_nsColour colorUsingColorSpaceName:NSCalibratedRGBColorSpace] )
+ if ( NSColor* colRGBA = [m_nsColour colorUsingColorSpace:[NSColorSpace sRGBColorSpace]] )
return [colRGBA redComponent];
@@ -134,3 +134,3 @@
wxOSXEffectiveAppearanceSetter helper;
- if ( NSColor* colRGBA = [m_nsColour colorUsingColorSpaceName:NSCalibratedRGBColorSpace] )
+ if ( NSColor* colRGBA = [m_nsColour colorUsingColorSpace:[NSColorSpace sRGBColorSpace]] )
return [colRGBA greenComponent];
@@ -143,3 +143,3 @@
wxOSXEffectiveAppearanceSetter helper;
- if ( NSColor* colRGBA = [m_nsColour colorUsingColorSpaceName:NSCalibratedRGBColorSpace] )
+ if ( NSColor* colRGBA = [m_nsColour colorUsingColorSpace:[NSColorSpace sRGBColorSpace]] )
return [colRGBA blueComponent];
@@ -152,3 +152,3 @@
wxOSXEffectiveAppearanceSetter helper;
- if ( NSColor* colRGBA = [m_nsColour colorUsingColorSpaceName:NSCalibratedRGBColorSpace] )
+ if ( NSColor* colRGBA = [m_nsColour colorUsingColorSpace:[NSColorSpace sRGBColorSpace]] )
return [colRGBA alphaComponent];
@@ -160,3 +160,3 @@
{
- return [m_nsColour colorUsingColorSpaceName:NSCalibratedRGBColorSpace] != nil;
+ return [m_nsColour colorUsingColorSpace:[NSColorSpace sRGBColorSpace]] != nil;
}
+9 -11
View File
@@ -21,25 +21,23 @@ else ()
set(_wx_edge "-DwxUSE_WEBVIEW_EDGE=OFF")
endif ()
set(_wx_patch_command "")
if (APPLE)
set(_wx_patch_command
${GIT_EXECUTABLE} checkout -f -- src/osx/cocoa/colour.mm
COMMAND ${GIT_EXECUTABLE} apply --verbose
${CMAKE_CURRENT_LIST_DIR}/0001-macos-use-srgb-colour-components.patch
)
# With a precompiled header, clang-cl can omit an exception type's copy constructor from its throw info,
# so copies of the exception share and double-free their data: https://github.com/llvm/llvm-project/issues/53486
if (MSVC AND CMAKE_C_COMPILER_ID STREQUAL "Clang")
set(_wx_precomp OFF)
else ()
set(_wx_precomp ON)
endif ()
orcaslicer_add_cmake_project(
wxWidgets
GIT_REPOSITORY "https://github.com/SoftFever/Orca-deps-wxWidgets"
GIT_TAG v3.3.2
GIT_REPOSITORY "https://github.com/OrcaSlicer/Orca-deps-wxWidgets"
GIT_TAG 5b7e8c0cde6b975d63613188d2ac6c1ab8769fbc
GIT_SHALLOW ON
GIT_SUBMODULES 3rdparty/catch 3rdparty/pcre 3rdparty/libwebp
PATCH_COMMAND ${_wx_patch_command}
DEPENDS ${PNG_PKG} ${ZLIB_PKG} ${EXPAT_PKG} ${JPEG_PKG}
CMAKE_ARGS
-DwxBUILD_PRECOMP=ON
-DwxBUILD_PRECOMP=${_wx_precomp}
${_wx_toolkit}
"-DCMAKE_DEBUG_POSTFIX:STRING=${_wx_debug_postfix}"
-DwxBUILD_DEBUG_LEVEL=0
@@ -78,6 +78,12 @@ public:
std::vector<int> extrude_ids;
int filament_temp_type = -1; // -1 means unset. otherwise should be {0,1,2}
double height{ 0 };
double z_min{ 0 };
double z_max{ 0 };
bool has_z_range{ false };
bool is_bed_exclusion{ false };
std::vector<int> bed_exclusion_extruder_ids;
int bed_exclusion_extruder_id{ -1 };
double print_temp{ 0 };
double bed_temp{ 0 };
double vitrify_temp{ 0 }; // vitrify temperature
@@ -123,6 +123,10 @@ struct NfpPConfig {
std::function<void(const ItemGroup &, NfpPConfig &config)> on_preload;
// Return false when a packed item does not constrain this candidate.
// By default every pair participates in the 2D collision calculation.
std::function<bool(const _Item<RawShape>&, const _Item<RawShape>&)> should_check_collision;
//BBS: sort function for selector
std::function<bool(_Item<RawShape>& i1, _Item<RawShape>& i2)> sortfunc;
//BBS: excluded region for V4 bed
@@ -579,7 +583,14 @@ private:
{
using namespace nfp;
Shapes nfps(items_.size());
std::vector<Item *> collision_items;
collision_items.reserve(items_.size());
for (Item &item : items_) {
if (!config_.should_check_collision || config_.should_check_collision(trsh, item))
collision_items.emplace_back(&item);
}
Shapes nfps(collision_items.size());
// /////////////////////////////////////////////////////////////////////
// TODO: this is a workaround and should be solved in Item with mutexes
@@ -590,21 +601,21 @@ private:
trsh.rightmostTopVertex();
trsh.leftmostBottomVertex();
for(Item& itm : items_) {
itm.transformedShape();
itm.referenceVertex();
itm.rightmostTopVertex();
itm.leftmostBottomVertex();
for (Item *item : collision_items) {
item->transformedShape();
item->referenceVertex();
item->rightmostTopVertex();
item->leftmostBottomVertex();
}
// /////////////////////////////////////////////////////////////////////
__parallel::enumerate(items_.begin(), items_.end(),
[&nfps, &trsh](const Item& sh, size_t n)
__parallel::enumerate(collision_items.begin(), collision_items.end(),
[&nfps, &trsh](Item *const &sh, size_t n)
{
auto& fixedp = sh.transformedShape();
auto& fixedp = sh->transformedShape();
auto& orbp = trsh.transformedShape();
auto subnfp_r = noFitPolygon<NfpLevel::CONVEX_ONLY>(fixedp, orbp);
correctNfpPosition(subnfp_r, sh, trsh);
correctNfpPosition(subnfp_r, *sh, trsh);
nfps[n] = subnfp_r.first;
});
+4 -2
View File
@@ -224,12 +224,14 @@ compare_prerelease (char *x, char *y) {
if (x == NULL && y) return 1;
// Orca: Special handling for 'dev'
// Nightly builds stay on x.y.z-dev after the alpha and beta are tagged, so 'dev'
// ranks above every other prerelease and below the release.
if (strcmp(x, "dev") == 0 && strcmp(y, "dev") == 0)
return 0;
if (strcmp(x, "dev") == 0 && strcmp(y, "dev") != 0)
return -1;
if (strcmp(x, "dev") != 0 && strcmp(y, "dev") == 0)
return 1;
if (strcmp(x, "dev") != 0 && strcmp(y, "dev") == 0)
return -1;
lastx = x;
lasty = y;
@@ -1,8 +1,8 @@
# Adaptive TPMS infill — High Level Design
# Adaptive infill — High Level Design
## Purpose and scope
`tpms_adaptive` grades the sparse infill of the Gyroid, TPMS-D and TPMS-FK
`adaptive_infill_mode` grades the sparse infill of the Gyroid, TPMS-D and TPMS-FK
patterns inside the object: the cells grow continuously from the surface
towards the center of the object. `distance_warp`, `smooth_blend` and
`stepped_shells` follow the distance to the nearest surface, including the top
@@ -10,8 +10,8 @@ and bottom, like concentric shells; `lobes` follows the whole 3D shape towards
the center of each lobe of the object; `normal_z`, `normal_y` and `normal_x`
follow each section of the object normal to that axis, so the grading does not
change along the axis, as suits a profile extruded along it.
`sparse_infill_density` is the density at the surface, `tpms_interior_density`
the density at the center, and `tpms_adaptive_gradient` picks how the density
`sparse_infill_density` is the density at the surface, `adaptive_infill_interior_density`
the density at the center, and `adaptive_infill_gradient` picks how the density
goes from one to the other. Only internal sparse infill is graded; the Gyroid
Z-buckling optimization does not apply to it.
@@ -22,9 +22,9 @@ split into shells or blended between densities.
## Radial field
`TpmsRadialField` gives every point of an object the center of its lobe and a
`AdaptiveInfillField` gives every point of an object the center of its lobe and a
radial coordinate: 0 at the center, 1 at the surface along the ray from the
center. `PrintObject::prepare_tpms_radial_fields()` builds it in
center. `PrintObject::prepare_adaptive_infill_fields()` builds it in
`bridge_over_infill()`, next to the adaptive cubic octree, because the anchoring
infill generated there has to match the printed infill. A field is built for
every mode a region uses, and is shared by the regions using that mode: the
@@ -202,7 +202,7 @@ built for them.
## Constraints
- With `tpms_adaptive` disabled, or for other patterns, the fill parameters are reset
- With `adaptive_infill_mode` disabled, or for other patterns, the fill parameters are reset
to their defaults, so they neither change the infill nor split fill batches.
- `Layer::get_sparse_infill_max_void_area()` uses the sparser of the two
densities, as the voids at the center are that large.
+52
View File
@@ -87,6 +87,58 @@ tasks, such as a tab, a dialog, the Prepare tab's settings page one option group
time, the Prepare page's layout at the size the book gives its pages, or the 3D view's GL
resources.
### Settings option restrictions
Each settings `Tab` owns an `OptionStateRegistry` independent of its page controls.
`toggle_line` records a hidden reason and `toggle_option` records a disabled reason
before looking for controls. Each restriction is stored only while its toggle is false;
setting it true removes that restriction without affecting the other one. Repeated calls
replace the previous reason, including an empty reason from a caller without explanatory
text. Loading a preset clears the previous preset's records.
Keys are the exact strings supplied to the public toggles. The registry does not expand
an option to its row siblings or distinguish indices passed separately from the key.
It records executed public calls, so direct field operations and rules that have not run
are outside its coverage. Keeping it with the Tab lets reasons survive page control
recycling without retaining a Field or window pointer.
The registry formats the current restrictions for both controls and their labels.
Public toggles refresh the active input's tooltip, and each page's `OG_CustomCtrl`
reads its owning Tab's registry when the pointer rests on a row label. The label
remains a hover target when the input is disabled. For rows with multiple options,
identical restriction descriptions appear once, in their first occurrence order.
Markdown tips prepend the same restriction text to their document and refresh
when that text changes, even when
the document identifier stays the same. Callers without a reason receive a generic
current-configuration explanation. Dependency rules supply complete translated
messages describing their prerequisites; compound rules can choose the message for
the failed prerequisite. The same recorded text reaches tooltips and search results.
Filament setting overrides record retraction-length dependency restrictions separately
from override selection. Leaving an override unchecked does not add a restriction reason.
Compatibility condition fields explain that the "All" checkbox must be selected before
editing a condition; both checkbox changes and reloads refresh the restriction.
The object table's settings form owns a separate registry because it builds option
groups outside a Tab. Its dependency callbacks retain their reasons and refresh
both input and native label tooltips. Rebuilding the form or reevaluating dependencies
clears its records, so restrictions follow the current object and effective configuration.
Settings search resolves the same owning Tab as option navigation: a matching model
Tab in object mode, otherwise the global preset Tab. Results show the first line of
the registry description beneath the option name, with the complete description in
the tooltip. Availability text is not part of fuzzy name matching. The Speed Dial
keeps settings with a recorded hidden reason in its catalog and prepends their
restrictions to its detail strip. Settings hidden only by an unrecorded row
restriction retain the Speed Dial's existing filtering.
A page's rules run only while that page is shown, and the registry keys carry no
extruder index, so a listed restriction reflects the configuration and extruder of
the last time its page was shown. Navigation therefore never trusts it: selecting a
setting from search or the Speed Dial opens its page (and extruder), reruns that
page's rules, and only a setting still hidden then displays its explanation instead
of focusing an invisible input.
### The 3D view's GL resources
OpenGL is loaded on the Prepare tab's canvas. When the start page is not Prepare, loading
+2 -2
View File
@@ -44,8 +44,8 @@ Two consequences follow from deriving rather than storing:
## Geometry kernel and dependency surface
The kernel is OCCT, which OrcaSlicer **already** links — `Format/STEP.cpp`, `Format/svg.cpp`
and `Shape/TextShape.cpp` use it upstream. The Design tab adds no third-party dependency; it
The kernel is OCCT, which OrcaSlicer **already** links — `Format/STEP.cpp` and `Format/svg.cpp`
use it upstream. The Design tab adds no third-party dependency; it
widens the existing OCCT build by one module flag in `deps/OCCT/OCCT.cmake`:
```cmake
+69
View File
@@ -0,0 +1,69 @@
# Bed exclusions and toolhead collision volumes
## Purpose and configuration
Bed exclusions have two distinct meanings. A material keep-out prevents model
placement without prohibiting deliberate machine travel, such as entering a
filament cutter. A toolhead collision volume represents an obstacle that travel
and extrusion must avoid. Keeping separate settings preserves existing printer
profiles, project files and command-line usage without enabling new motion
constraints implicitly.
- `bed_exclude_area` remains a points-array polygon and a shared, bed-fixed
material/placement keep-out.
- `bed_exclude_volumes` contains collision-volume polygons, with optional
`ZMIN..ZMAX;` prefixes and `|` separators. A polygon without a Z prefix applies
over the printable height.
- `bed_exclude_volume_mode` selects shared volumes, toolhead-relative volumes
derived from nozzle XY offsets, or individually configured extruder volumes.
- `extruder_bed_exclude_volumes` stores the individual definitions. These are
selected by physical extruder, not simply by filament slot.
Material keep-outs and collision volumes are additive. Nozzle offsets apply only
to collision volumes in toolhead-relative mode. The existing bed area never moves
or disappears when collision volumes are configured.
On belt printers, the region resolver projects material keep-outs onto the
tilted bed surface before placement and tower validation. Collision volumes
remain in model coordinates; the bed-surface projection is not applied to them.
The printer settings expose the bed area as a normal editable field with Orca's
standard reset controls. Collision volumes appear directly below it in Printable
space, as a separate field. A bed-area polygon can be manually copied into this
field to define a full-height collision volume. Pasted volume syntax in the
area field requires confirmation before it is added to the volume settings;
declining or invalid input leaves the stored area intact.
## Geometry and slicing
The region resolver retains the distinction between material keep-outs and
collision volumes, and supplies nozzle-specific regions to placement, arrangement,
generated geometry and motion consumers. An object is checked conservatively
against the collision volumes for every nozzle it uses, over its complete geometry
rather than only a painted portion. Shared support geometry likewise uses a
conservative union of the relevant nozzle and instance exclusions.
Collision-volume footprints are selected by their overlap with the applicable Z
slab. Brim and supported support-generation paths subtract these footprints before
extrusion generation. The travel router attempts to avoid active collision
volumes; the final G-code checker validates emitted motion independently.
The checker cannot infer movements inside opaque firmware macros. Homing leaves
the affected coordinates unknown until explicit coordinates establish them.
Skirts and draft shields are not rebuilt around obstacles, extrusion is not
rerouted, and the circular XY sweep of spiral Z-hop is not available to the travel
router when it plans the primary travel. The final checker can warn about these
violations; that warning is not an automatic repair or a guarantee of safe output.
## Preview
Ground footprints remain visible. Nozzle-specific collision volumes have thin
nozzle-coloured borders; shared volumes and single-nozzle configurations do not
imply ownership by a particular filament. Automatic 3D previews are limited to
nearby object height to avoid obscuring the workspace.
**View → Show all collision volumes** displays each volume over its complete
resolved Z range, including on an empty bed. Its default shortcut is Ctrl+Shift+K
(Command+Shift+K on macOS), configurable through Orca's shortcut settings. The
application remembers this display preference independently of printer presets;
it changes neither collision checking nor slicing results.
+5 -2
View File
@@ -350,8 +350,11 @@ identity default and translates nothing. `NetworkAgent` forwards both to the liv
comparison sites below reach them through `wxGetApp().getAgent()` and leave an id untranslated
while no agent is live. Whole documents are Bambu's business alone:
`BBLPrinterAgent::to_orca_payload` and `from_orca_payload` rewrite every string under
`tray_info_idx`, `filament_id` or `filamentId` at any depth; text that does not parse, or carries
none of those keys, comes back unchanged. The map is loaded once, lazily; a missing or malformed
`tray_info_idx`, `filament_id`, `filamentId`, `cate` or `fila_id` at any depth; text that does not
parse, or carries none of those keys, comes back unchanged. The last two are the H2C nozzle rack's:
`cate` in the auto nozzle mapping request, `fila_id` in the rack status. A new Bambu message that
carries a filament id under another key needs that key added to `filament_id_keys`, or the id
crosses the boundary untranslated. The map is loaded once, lazily; a missing or malformed
file degrades to identity with a log line rather than failing.
| Boundary | Where it translates |
+68
View File
@@ -0,0 +1,68 @@
# Infill corner smoothing — High Level Design
## Purpose and scope
`sparse_infill_smooth_factor` rounds the corners of the sparse infill paths of
the patterns `is_smoothable_infill_pattern()` lists, so the toolhead does not
slow to near a stop in every corner. `FillCornerSmoothing` does the rounding for
every pattern; the fills only call it on their paths before clipping and before
`multiline_fill()` copies them.
The design is shaped by how firmware plans speed. Klipper, Marlin 2 with
junction deviation and OrcaSlicer's estimator limit the speed at the junction of
two moves by how much the path turns there, and by the length of the moves for
the centripetal part. A curve is printed as straight moves, so its speed depends
on how it is cut into moves as much as on its shape, and the cut decides the size
of the G-code.
## The curve
Each corner is replaced by a curve that runs from `reach` before it along the
incoming leg to `reach` after it along the outgoing one, `reach` being the factor
times half of the shorter leg, so the curves of two corners never overlap.
The curve is a quintic Bézier curve whose first three control points on each leg
are equally spaced, 0.3 of the reach apart, which makes its curvature zero at the
legs: the toolhead eases into the turn. A circular arc takes fewer vertices within
the resolution and prints slower, and a septic curve, whose rate of curvature is
also zero at the legs, prints no faster than the quintic one and takes longer to
slice. Tuning the spacing to the turn angle lowers the peak curvature of sharp
turns but made no measurable difference to print time.
## The vertices
A corner is printed as the polygon of the curve's tangents taken at equal steps
of direction: every vertex turns by the same angle, which spends each vertex
where the planner needs it. Uniform steps of the curve parameter put vertices
where the curve is nearly straight and leave the sharpest turn in the middle.
The number of vertices follows the G-code resolution (`resolution`), as the rest
of the G-code does: it is the fewest that keep the polygon within the resolution
of its curve. The arc of the curve's peak curvature gives the first count, which
the flatter parts of the curve may raise. The count is never so high that a
vertex stands out of the chord of its neighbours by less than the resolution, as
`LayerRegion::simplify_*` simplifies the infill to it afterwards and would drop
that vertex again.
The vertices depend on the geometry and the resolution only, not on the printer.
A finer resolution splits a corner into more and gentler turns, which a planner
takes faster, for a larger G-code file.
A corner of a given turn and vertex count is the same shape at any reach and
resolution, scaled. Each thread builds a shape once at unit reach and all its
`CornerSmoother`s share it, as some fills start a smoother for every path, every
layer starts its own, some patterns (Octagram Spiral) change the reach at every
corner, and searching the tangents of the curve is what slicing spends its time
on.
## Constraints
- At 100% every corner gets the largest curve its legs allow: the factor sets
the shape of the corners, not their speed. A large curve split into few
vertices can print slower than the sharp corner, as every vertex is a slowdown
and the short moves between them leave no room to accelerate.
- With the factor at 0 the paths are unchanged, and the fills keep their order of
operations, so that rounding to the integer grid does not move a point.
- The plane-path fills (Hilbert Curve, Octagram Spiral) produce their path point
by point in units of the line distance, so `CornerSmoother` takes points one
at a time, with the resolution in the same units.
+32
View File
@@ -53,6 +53,38 @@ Space counts as typing. The speed dial's default is the one bare Space, and
`MainFrame` leaves it to a focused control that uses Space itself (text fields, buttons,
combo boxes), so it opens the dial from the canvases and the tab strip only.
`MainFrame::handle_global_shortcut` skips a chord that `KeyChord::edits_text()` reports
while a text field has the focus (a wx text entry, spin control, web view or ImGui
InputText), and skips every chord while an ImGui modal is open, as a wx modal dialog
would. `ImGuiWrapper::owns_key()` reads the text input request and the popup stack of the
last drawn frame, since `WantCaptureKeyboard` and `WantTextInput` only catch up when the
next frame starts, and is called only when the focus is on a visible canvas from
`OpenGLManager::create_wxglcanvas()`.
The `Plater`, `Preview` and `Painting` shortcuts act on the 3D view, so they run only while
the 3D view has the keyboard. `GLCanvas3D` feeds every key event to ImGui and asks
`ImGuiWrapper::claim_key_event()` whether to act on it as well. While an ImGui popup (a
dropdown, a menu or a modal) is open or an ImGui InputText is active, ImGui claims every key,
as a focused sidebar text field or an open native dropdown keeps every key from the canvas.
Esc then closes the topmost dropdown or menu, since this ImGui closes popups on Esc only
through keyboard navigation, which is off; a modal handles Esc itself. A second Esc reaches
the canvas once nothing claims it. A slider or button held with the mouse also claims every
key until it is released, since a shortcut that switches the view or closes the tool would
leave the drag behind. One side handles a key from its key-down to its release. Its
repeats, its char event and its release follow the key-down's decision even when a field or
modal opens or closes in between, so a key never both runs a shortcut and types, and a
keyboard move of the selection always sees the release of the key that started it.
Key-ups go to whatever window has the focus, so a shortcut that opens a dialog, such as
Ctrl+P, takes the release of its modifier with it. When the canvas loses the focus it sends
itself a key-up for each Shift, Ctrl or Alt still held, which ends a gizmo's Shift mode and
clears ImGui's own copy of the modifier, and then drops its record of held keys.
`ImGuiWrapper::update_mouse_data()` also takes ImGui's modifiers from each mouse event, which
carries the real state, since a stale Ctrl would turn every slider click into a Ctrl+click
and open the slider's text box. The macOS
Edit menu, whose key equivalents run before the canvas sees the key, follows the same rule
as the canvas.
## Which event a chord matches
Letters, digits and special keys match on `wxEVT_KEY_DOWN`. Its key codes do not depend
+17
View File
@@ -62,6 +62,23 @@ Clipper2 behaves differently by default, the wrapper adjusts it.
clip do not leave slivers.
- Open polylines are clipped with the non-zero rule and keep their direction.
### Tiled booleans
The sweep slows down with the number of edges crossing a scan line, so a layer
cut into thousands of pieces makes every whole-layer boolean expensive.
`diff_ex_by_piece()` and `intersection_ex_by_piece()` take a subject of
non-overlapping `ExPolygons`, group them into tiles with
`ClipperUtils::tile_expolygons()`, and run each tile in parallel against only
the clip polygons near it, cut to the tile's box. Below 128 pieces there is a
single tile, and they are the plain `diff_ex()` / `intersection_ex()`.
The result covers the same area as the plain call. Without the safety offset
the rings are the same. With it, each tile unites only the clip polygons near
it, so a clip edge that the whole-layer union splits where it crosses a distant
clip polygon stays whole, and a crossing with the subject can round 1 unit
differently. The tiles' results are concatenated in tile order, so the order of
the output `ExPolygons` differs from the plain call.
### Offsets
- Before offsetting, input vertices closer than
+252
View File
@@ -0,0 +1,252 @@
# Preset Plugin API — High Level Design
## Purpose and scope
The preset plugin API lets Python plugins update the presets OrcaSlicer is using,
so users do not have to perform every routine setting change by hand. It covers
process, printer, and filament presets. All three use one staged update lifecycle;
the way a target is selected is specific to the preset type.
The API edits Orca's managed edited preset, not a detached copy or a saved preset
behind the UI's back. It does not save to disk. Saving, discarding, and transferring
unsaved edits remain under Orca's existing preset workflow.
The API does not create or delete presets or provide off-tab editing. For filament,
choosing a different `preset_name` as the update target also selects that preset for
the requested slot, following the normal UI flow. A standalone slot-assignment or
preset-fork operation is outside this API's contract.
## Preset and slot model
Each preset collection maintains a managed edited copy for its selected preset.
Settings tabs apply changes to that copy and own the normal dirty-state, validation,
save/discard/transfer, and downstream refresh behavior. Plugin updates must use the
same path so that the settings tab, dirty indicators, and effective print
configuration observe a consistent state.
Filament selection adds a slot-to-preset mapping. `PresetBundle::filaments` is the
catalog, while `PresetBundle::filament_presets` maps each slot to a preset name.
Several slots may refer to the same preset. A filament update edits that shared
preset, so all slots referring to it are affected. Slot numbers exposed by the API
are 1-based, matching the UI.
## API shape
Each preset API exposes `begin_update()`, which selects and binds one target, and
returns a transaction. The transaction stages setting changes using `set()` and
applies them only on explicit `commit()`.
```python
# Filament is targeted by its 1-based slot. Omitting preset_name keeps the
# preset currently assigned to the slot; providing it selects that preset for
# the slot before staging updates.
tx = orca.host.preset.filament.begin_update(
slot_number=2,
preset_name="Generic PLA"
)
tx.set("filament_flow_ratio", "0.98")
tx.set("filament_retract_length", "0.8")
result = tx.commit()
# Process and printer default to their active presets. A caller can request a
# different preset that is selectable in the corresponding UI dropdown.
tx = orca.host.preset.process.begin_update(
preset_name="0.20mm Standard"
)
tx.set("layer_height", "0.2")
tx.commit()
```
The example is the API contract, and the Python bridge provides it. `begin_update()`
is synchronous: it blocks the background Script worker until the target selection and
any unsaved-edit dialog settle, then returns the bound transaction. Orca's UI thread
stays responsive because the Script capability runs on its own worker. `set()` and
`commit()` run synchronously on that same worker. The Script worker and its optional
coroutine loop are described in
[python-plugin-async-bridge.md](python-plugin-async-bridge.md).
### Target resolution
- **Filament:** `slot_number` identifies the slot. If `preset_name` is omitted,
the transaction targets the preset currently assigned to that slot. If supplied,
it requests that preset for the slot and selects it through the normal UI flow;
the name must be among the presets offered by that slot's dropdown, with one
exception: the preset currently assigned to the slot stays targetable even when the
slot's dropdown hides it (for example an incompatible-but-selected preset). Selecting
a different preset changes the slot-to-preset mapping. In both cases the transaction
edits the shared preset, not an isolated slot override.
- **Process and printer:** omitting `preset_name` targets the currently active
preset. Supplying `preset_name` requests the preset by the name shown in its
dropdown. It must be one of the choices the dropdown currently offers, rather
than merely any preset present in the collection. This is particularly important
for process presets, whose selectable choices can depend on the current context.
- A transaction targets exactly one preset. Multi-preset transactions are not
supported: applying them would require switching among targets while the
application has only one managed edited copy per collection.
Targets are resolved through Orca's normal preset-selection model. The API should
not accept raw preset pointers or filesystem paths as target identities. A missing,
unavailable, or ambiguous target fails explicitly instead of silently selecting a
different preset.
## Selection and user interaction
`begin_update()` resolves its target through shared binding helpers
(`bind_preset_target` for process/printer, `bind_filament_target` for filament) and
performs the selection only when the requested target differs from the active target;
otherwise it returns a transaction without switching. The helpers use Orca's normal
preset selection flow, `Tab::select_preset()`, including updating a filament slot
assignment when requested. If the normal selection flow requires user input, it opens
the relevant existing dialog(s), including unsaved-edit choices such as save, discard,
or transfer. The call remains blocked on the Script worker until those interactions
finish; it returns the bound transaction, or raises on a cancellation, without
applying staged settings. A canceled selection does not change the requested target or
filament slot assignment, but it does not roll back decisions the user already accepted
in an earlier dialog. The helpers then confirm that the requested preset actually
became the edited preset; a successful selection request alone is not sufficient. There
is no separate `switch_preset` plugin API.
If the requested target is already active, `begin_update()` returns without a
selection prompt, apart from the UI-thread dispatch needed to bind the transaction.
If a different preset is requested, Orca selects it through the normal UI flow. For
filament, this also updates the requested slot's assignment when `preset_name`
differs from its current assignment. When the current preset has unsaved changes,
the Script worker stays blocked until the user chooses among Orca's existing options,
such as transfer, discard, or cancel.
The API never suppresses that warning, chooses an option for the user, or switches
away from dirty edits silently. Cancel aborts the operation before any staged target
changes are applied. Process and printer updates follow this rule too when the
plugin requests a different `preset_name`; they normally return immediately when
the active preset is the target.
## Staging and commit semantics
`set(key, value)` stages a serialized config value and does not mutate the preset.
The transaction is the boundary for a related group of changes, avoiding
intermediate partially-updated states. `commit()` runs synchronously on the background
Script worker. At commit, the API validates keys and values against the target preset
type and applies the batch through `Tab::apply_preset_config_values`, the existing tab
and settings-group update path. Existing setting-specific validation, correction, and
callbacks remain authoritative; plugin updates do not create a parallel setter with
different behavior.
A successful commit updates dirty state and downstream configuration/Plater state
once for the batch. The edited preset remains unsaved; persistence continues through
Orca's normal save action. A validation or commit failure restores the edited preset's
config to its pre-batch state and recomputes the state derived from it (compatibility
marks, the preset selector, dependent tabs, the Plater and the printer agent), so no
staged setting is left partially applied. That guarantee is limited to the edited
preset and its config-derived state: an `on_change` callback is a GUI method, not a pure
function of the config, so the transaction does not reverse a preset or slot selection
made while resolving the target, a dialog decision the user already accepted, an undo
snapshot, a dependent preset's rewritten config, or anything already sent to a device.
Exact all-or-nothing across those external effects is not achievable while the
authoritative GUI callbacks run; the boundary is documented on
`Tab::apply_preset_config_values`. A filament slot assignment made as part of target
selection is likewise not a staged setting: after the user accepts the selection flow it
may remain changed even if a later commit fails, and the API does not switch back or
reverse the user's selection or any accepted transfer/discard decision for the previous
preset.
## Outcomes and consistency
The API distinguishes target resolution failures, invalid setting/value, user
cancellation, stale filament-slot mapping, and commit failure. A result identifies
the target preset, whether preset selection changed, and (for filament) whether the
slot assignment changed and which slots share the edited preset. A canceled
selection applies neither the requested slot assignment nor staged target changes;
a failed commit applies none of the staged target settings.
Filament slot assignments can change between `begin_update()` and `commit()`. The API
detects that and rejects a stale operation instead of silently editing the new
slot assignment. It must not hold raw preset pointers across reloads. Conflicting
duplicate writes to one setting in a transaction are rejected rather than resolved
by incidental call order.
The existing one-setting filament call,
`orca.host.preset.filament.update(slot_number, key, value)`, remains available as a
compatibility shorthand. It shares the staged API's target resolution, selection,
validation, and commit path, and it is synchronous like `begin_update()`: both block
the background Script worker while any selection dialog settles.
## Design principles
- **Reduce routine interaction, preserve agency.** Clean switches should be
seamless; unsaved user work must still receive the normal warning and decision.
- **One source of truth.** UI and plugins share the managed edited copy and setting
update path, including validation and callbacks.
- **The UI workflow is authoritative.** The API must enter through the same
selection and setting-change workflows as the UI, not reproduce their logic or
write config values directly. This keeps existing and future side effects active:
`on_change` handling for mutually exclusive, invalid, or out-of-range settings;
compatibility and dependent-preset updates; and printer-agent changes when the
selected printer changes.
- **Explicit target and explicit commit.** Plugins know which preset they edit and
when staged changes become visible.
- **No hidden persistence.** Plugin edits remain unsaved until the user saves them
through Orca.
- **Shared means shared.** Editing a filament preset through one slot affects every
slot assigned to it. Choosing another preset for a slot is explicit in
`preset_name`; slot-specific divergence would require a separate fork operation.
- **Consistent lifecycle, type-specific targeting.** Process, printer, and
filament share transaction and error semantics while respecting their existing
selection models.
## Implementation in the current codebase
The transaction API is implemented. The current plugin surface exposes `begin_update()`,
`PresetTransaction` with `set()`/`commit()`, and the per-setting `update()` compatibility
shorthand. For filament, `update_filament_slot()` resolves the preset already assigned
to a slot, selects it through `Tab::select_preset()`, and applies one setting through
`Tab::apply_preset_config_values()`; it does not change the slot assignment.
`begin_update()` and `update()` are synchronous blocking calls
(`begin_preset_update` / `begin_filament_update`). They marshal the target binding to
the UI thread and block the background Script worker until the selection settles, so
the wait never blocks the UI thread. They are valid only on that worker, never from the
UI thread or a slicing pipeline hook.
`Tab::select_preset()` is the basis for switching to process, printer, or filament
presets and for invoking the normal unsaved-edit flow. The flow is type-specific: a
process selection can trigger compatibility handling for filaments, and a printer
selection can involve technology changes and dependent preset compatibility. It may
therefore show more than one dialog. Cancellation of a later step does not necessarily
undo decisions the user already accepted in an earlier dialog. Target resolution
preserves those side effects and then verifies the resulting edited target.
Filament `preset_name` is an additional integration on top of `Tab::select_preset()`:
selecting a different name for a slot also updates the slot-to-preset mapping and its
dependent UI/configuration state, mirroring the filament branch of the Plater's normal
selection path (`PresetBundle::set_filament_preset()` plus the project/selection refresh,
the dynamic filament list, the conditional support-filament flushing recalc, the slot
combo refresh and its AMS sync badge). A mixed-color virtual slot is not targetable.
Process and printer dropdown choices are constrained by visibility and compatibility,
and compatibility may depend on the active context. Target resolution checks the tab
dropdown's actual items before the selection flow, so a target the user cannot pick
fails without raising that flow's unsaved-edit prompt; a name two entries carry is
rejected as ambiguous. A filament `preset_name` resolves against the requested slot's
own sidebar selector rather than the tab's, so that slot's compatibility filter is the
one that applies. A name the slot's dropdown does not show is rejected unless it names
that slot's current assignment (a hidden or incompatible-but-selected preset), which
stays targetable.
`commit()` applies its batch through `Tab::apply_preset_config_values`, which parses and
validates the whole batch before touching the edited preset and restores the edited
preset and its config-derived state on failure (see "Staging and commit semantics" for
the limit of that rollback). Since `begin_update()` performs target selection before the
caller stages values, invalid staged values can still follow a user-visible selection
prompt; that is a consequence of this API shape and remains explicit in its behavior.
## Integration boundary
The plugin API coordinates target resolution, preset selection, staged values, and
the settings commit path. It does not own or duplicate preset dirty-state logic,
selection prompts, setting validation, or persistence. Target changes flow through
the same UI selection path so dependent behavior—such as selecting the printer
agent—still runs. Setting changes flow through the same UI change path so `on_change`
and related validation/correction behavior still runs. The integration bridges UI
prompts to the Python operation through the blocking `begin_update()` and reuses
the normal Plater slot-selection behavior for explicit filament targets, and commits a
batch without losing existing per-setting behavior.
+351
View File
@@ -0,0 +1,351 @@
# Python plugin async bridge — High Level Design
## Purpose and scope
The embedded Python plugin runtime runs most capability calls synchronously: a C++ call site acquires
the GIL and the capability's Python method runs to completion on the calling thread. The staged preset
update (`begin_update()` in [preset-plugin-api.md](preset-plugin-api.md)) is also synchronous, but
its target selection can open unsaved-edit dialogs. It therefore blocks the Script worker, not the UI
thread, and returns only when the selection settles.
This document describes the Script capability's background execution path, including the optional
per-invocation asyncio loop for an `async def execute`, and the blocking UI marshalling that host calls
use from that worker. The bridge is deliberately narrow: only the Script capability gains a
background/async execution path. Every other capability — including the SlicingPipeline hooks — stays
synchronous on its caller's thread.
## Execution baseline
### How a capability call runs
A capability instance is a Python object owned through `Slic3r::PluginInstanceHandle`
(`src/slic3r/plugin/PythonPluginBridge.cpp`) and handed to the rest of the program as a
`std::shared_ptr<Slic3r::PluginCapabilityInterface>`. Its identity (`name()`, `type()`,
`audit_plugin_key()`) is resolved once at materialization and cached in C++
(`PluginCapabilityInterface` in `src/slic3r/plugin/PythonPluginInterface.hpp`).
Every C++→Python call crosses a trampoline method. `PyPluginCommonTrampoline` and
`PyPluginInterfaceTrampoline` (`src/slic3r/plugin/PyPluginTrampoline.hpp`), and the per-type subclass
`PyScriptPluginCapabilityTrampoline`
(`src/slic3r/plugin/pluginTypes/script/ScriptPluginCapabilityTrampoline.hpp`), wrap the call in the
`ORCA_PY_OVERRIDE_AUDITED` macro. For one synchronous call that macro, in order:
1. constructs a `PluginCapabilityInterface::RefCounter`, which `increment()`s the capability's
reference count for the call's duration;
2. constructs a `PythonGILState`, which first acquires a `PythonRuntimeLease` and then
`PyGILState_Ensure()`;
3. opens a `ScopedPluginAuditContext(audit_plugin_key(), name())`;
4. dispatches into Python via `PYBIND11_OVERRIDE`/`PYBIND11_OVERRIDE_PURE`;
and unwinds those guards when the call returns.
`PythonGILState` and `PythonRuntimeLease` live in `src/slic3r/plugin/PythonInterpreter.hpp`. A lease is
a `shared_lock` on `PythonInterpreter::m_runtime_mutex`; `PythonInterpreter::shutdown()` takes the
exclusive side, so a thread that holds a lease can safely touch Python objects, and interpreter
finalization cannot run underneath it. `ScopedPluginAuditContext`
(`src/slic3r/plugin/PluginAuditManager.hpp`) stores the previous thread-local plugin/capability pair
and scoped filesystem roots, sets this call's, and restores them on destruction; the audit hook then
attributes every filesystem/socket/process event to the plugin currently executing on that thread.
### The Script capability
`Slic3r::ScriptPluginCapability` (`src/slic3r/plugin/pluginTypes/script/ScriptPluginCapability.hpp`)
declares one pure virtual method, `ExecutionResult execute()`. The async runtime invokes it through
`invoke_script_execute` (`src/slic3r/plugin/PyPluginTrampoline.hpp`), which replicates the audited
trampoline call (ref counter, audit scope, traceback-preserving rethrow) but returns a
`ScriptExecuteInvocation` instead of forcing a cast:
- a plain `def execute` runs to completion in `invoke_script_execute` and yields
`ScriptExecuteInvocation::result`;
- an `async def execute` (or any override that returns a coroutine, detected with
`inspect.iscoroutine`) yields the coroutine object in `ScriptExecuteInvocation::awaitable` without
running it, so the runtime can drive it.
`ScriptExecuteInvocation` is defined in `PyPluginTrampoline.hpp`; `py_is_coroutine` is the detection
helper.
### UI marshalling
`PluginHostUi::run_on_ui_thread` (`src/slic3r/plugin/host/PluginHostUi.cpp`) forwards to the
file-local `run_on_ui_blocking`:
- if the caller is already on the wx main thread, it runs the callable inline after a
`py::gil_scoped_release`;
- otherwise it sets up a `std::promise`/`std::future`, releases the GIL, posts the callable with
`GUI::wxGetApp().CallAfter`, and blocks on `future.get()`.
That is a blocking handoff: the caller's stack is parked on a thread while the UI thread runs the
callable. It is the correct primitive for the synchronous `update()`/`commit()` path and for
`reload_local_bundle`/`list_bundle_ids`, but it cannot be used by an operation that must suspend.
### Slicing hooks
`Print::set_slicing_pipeline_hook_fn` is installed by `src/slic3r/plugin/PluginHooks.cpp`. The hook
runs on the slicing worker thread and dispatches to `SlicingPipelinePluginCapability::execute(ctx)`
per capability, acquiring a `PythonGILState` per capability. `SlicingPipelineContext`
(`SlicingPipelinePluginCapability.hpp`) holds raw pointers into the live slicing graph
(`ctx.print`, `ctx.object`) that are valid only for the duration of `execute(ctx)`. The UI thread can
be blocked waiting on the slicing worker (`BackgroundSlicingProcess::stop()` parks it), so a
marshalled UI call from a hook can deadlock; `PluginHostSlicing.cpp`, `SlicingPipelinePluginCapability.hpp`
and `PluginHostUi.hpp` all document this.
## Script-only async execution
### Per-invocation worker and loop
`ScriptAsyncRuntime` (declared in `src/slic3r/plugin/PluginManager.hpp`, implemented in
`PluginManager.cpp`) drives every Script invocation off the caller's thread. Its `start()` creates a
`Run` and launches a detached worker thread that runs `Impl::run_invocation`. There is one worker
thread per invocation, so no invocation ever blocks the UI thread and no invocation is queued behind
another plugin's.
`run_invocation` runs detection and execution on the worker:
- it re-checks `cancel_requested` before anything (a cancellation that arrived before the run
started is honored without running the plugin);
- it calls `invoke_script_execute`; a plain `def execute` result is used directly, and an `async def`
coroutine is driven on a loop created for that invocation:
`asyncio.new_event_loop()` → `asyncio.set_event_loop(loop)` → `loop.create_task(coroutine)` →
`loop.run_until_complete(task)` → `loop.close()`, then `asyncio.set_event_loop(None)`.
The loop is per invocation, not global, and no loop outlives its invocation. The loop for the
calling thread is published in the thread-local `tl_script_loop` and exposed through
`ScriptAsyncRuntime::current_loop()` (GIL held). A host call such as `begin_update()` does not suspend
the loop: it blocks the worker thread while the UI settles, then returns a value the coroutine uses
directly.
`PluginManager::launch_script_capability` is the entry point: it resolves the capability, hands it to
`ScriptAsyncRuntime::start`, and sets `ScriptLaunchResult::launched_async`. The completion callback
runs on the GUI thread (or inline when there is no wx app), and `launch_script_capability` records a
run error through `set_plugin_error` before invoking the caller's `ScriptCompletionFn`.
`PluginManager::run_script_capability` is kept as a compatibility wrapper: it waits for the
completion callback, pumping `wxYield()` when it is itself on the GUI thread, and returns the
`ExecutionResult`.
### Capability, runtime, GIL and audit lifetime across a suspension
For the whole invocation — including an `async def` suspended at an `await` — `run_invocation` holds:
- a `PluginCapabilityInterface::RefCounter` per invocation and a `shared_ptr` to the capability in the
`Run`, so the capability and its module stay alive across awaits and unload cannot drop them;
- a `PythonRuntimeLease` (acquired before the GIL). `PythonInterpreter::shutdown()` cannot finalize
the interpreter while any invocation worker holds a lease;
- the GIL, acquired with `pybind11::gil_scoped_acquire` on the worker;
- a `ScopedPluginAuditContext(audit_plugin_key(), name())`, so filesystem/socket/process events
raised by the coroutine are attributed to the plugin.
The capability reference is released inside the GIL scope (`run->capability.reset()`), because
dropping the pybind holder from a non-Python thread would `DECREF` without the GIL. The loop is
closed and `tl_script_loop` cleared before the worker exits.
A consequence of running Script on a non-main thread: the audit permission prompt is fail-closed off
the main thread. `request_permission` in `src/slic3r/plugin/PluginAuditManager.cpp` posts the dialog
with `CallAfter` and denies the current event, persisting the grant when the user accepts, so a
Script sees a denial on the first attempt and can succeed on a later one. This matches the existing
behavior for the plugin-load worker and the slicing worker.
### Blocking UI continuation
`PluginHostUi::run_on_ui_thread` (in `src/slic3r/plugin/host/PluginHostUi.cpp`) is the primitive host
calls use from the Script worker. It forwards to `run_on_ui_blocking`:
- if the caller is already on the wx main thread, it runs the callable inline after a
`py::gil_scoped_release`;
- otherwise it sets up a `std::promise`/`std::future`, releases the GIL, posts the callable with
`GUI::wxGetApp().CallAfter`, and blocks on `future.get()`.
Because the Script capability owns a worker thread, blocking there does not freeze the UI. The same
primitive is used by `begin_update()`, `set()`/`commit()`, `reload_local_bundle()` and
`list_bundle_ids()`.
### Synchronous `begin_update()`
`begin_preset_update` and `begin_filament_update` (`src/slic3r/plugin/host/PluginHostPresets.cpp`) run
on the Script worker with the GIL held and block it:
1. the binding enters through `PluginHostUi::run_on_ui_thread`, which fails with a `RuntimeError`
before posting when there is no wx application;
2. the UI thread runs the target binding with the GIL released — `bind_preset_target` for
process/printer, `bind_filament_target` for filament — including `Tab::select_preset()` and any
unsaved-edit prompt;
3. the worker resumes with the name-based `PresetTransaction`, and nothing is staged until the
caller's later `set()`/`commit()`.
An unavailable target is rejected before selection and changes no preset. A selection the user
declines raises `RuntimeError` and creates no transaction; decisions already accepted in an earlier
dialog are not rolled back. No GUI or preset pointer outlives the call: the transaction holds only
copied category/name/slot values.
`set()` stages a serialized value without mutating the preset, and `commit()` applies the batch
through `Tab::apply_preset_config_values` on the UI thread. Both are synchronous and, per their
bindings, valid only on the background Script worker.
### Cancellation
`ScriptAsyncRuntime::cancel_plugin(plugin_key)` sets `cancel_requested` on every active run for the
plugin and, when a loop is live (`has_loop`), cancels the task with
`loop.call_soon_threadsafe(task.cancel)` while holding the GIL. A synchronous `def execute`
invocation has no loop, so only the flag is set (checked before the run starts).
A task cancellation cannot interrupt a blocking `begin_update()` native call: the worker is inside
that call, so the loop does not run the scheduled `task.cancel()` until the selection settles and the
call returns. The transaction is therefore delivered, and any accepted UI selection stands; the
cancellation is observed at the coroutine's next suspension point. A user-declined selection is an
ordinary `RuntimeError`, not `asyncio.CancelledError`.
A plugin's own `asyncio.CancelledError` is treated as a cancellation only when `cancel_requested` was
set; otherwise it stays a genuine error (see `run_invocation`), so a plugin that cancels its own task
does not masquerade as an unload cancellation.
### Unload and shutdown drain
Unloading or shutting down must guarantee that no plugin Python code runs after its module is
unloaded, and that a blocking UI selection cannot mutate presets after teardown.
- `PluginManager::cancel_and_wait_for_capabilities` calls `on_cancelled()` first (so the plugin can
observe state while the run is intact), then `ScriptAsyncRuntime::cancel_plugin`, then drains.
The drain is **unbounded while a Script invocation worker is outstanding** — its loop-exit
condition is `all_released && !invocation_active`. `has_active_run()` distinguishes a run that was
cancelled before it started from one whose worker is still live, and a worker blocked in
`begin_update()` keeps the run active until its UI callback returns. On the GUI thread the drain
pumps `wxYield()` so a modal selection can settle instead of being starved by the blocking wait.
Only the non-Script path keeps the historical bounded 2-second grace: when no invocation is active,
the drain stops waiting for capability references at the grace deadline and logs any remaining
ones.
- `PluginManager::shutdown` detaches the libslic3r hooks (`plugin_hooks::uninstall`), stops new
loads, waits for in-flight loads, unloads every plugin (draining the async runs above), then calls
`ScriptAsyncRuntime::instance().shutdown()`, which refuses new runs and waits without a deadline
for every invocation worker to finish — nothing is torn down by force. `ScriptAsyncRuntime::reset()`
re-arms the runtime so a later `initialize()` in the same process can start runs again.
Cancellation triggered by unload or shutdown is a separate, expected completion, not a plugin
failure. `run_invocation` marks a run whose `cancel_requested` was set as `completion.cancelled` and
clears any error, whatever the coroutine body did. `launch_script_capability` records a plugin error
only when `!completion.cancelled && !completion.error.empty()`; `run_script_capability` reports an
empty error for a cancelled completion; and the two GUI launchers treat `cancelled` as neither error
nor success (the speed dial stays silent, the Plugins dialog updates no status). A plugin's own
`CancelledError` is not counted as this expected termination unless `cancel_requested` is set, so a
self-cancelled plugin still records its failure.
## Supported and unsupported capabilities
| Capability | Async support | Reason |
| --- | --- | --- |
| Script | `def execute` and `async def execute` both run on the per-invocation worker | The runtime owns the worker and, for a coroutine, a per-invocation loop; nothing about a Script invocation borrows C++ state. |
| SlicingPipeline | Synchronous only | `execute(ctx)` borrows `Print`/`PrintObject` for the callback's duration, and the UI thread can be blocked on the slicing worker. `PluginHooks.cpp` rejects an async override: `cap->execute()` casts its Python result to `ExecutionResult`, and a coroutine object cannot be cast, so it surfaces as a `SlicingError` rather than being scheduled. |
| PrinterConnection, Pages, Analysis, Importer, Exporter, Visualization, ResourceTexture | Unchanged | Not part of this bridge; they keep their existing synchronous contract. |
## Deadlock constraints
- **Never block the UI thread on plugin work.** Every Script launch path goes through
`launch_script_capability`; the speed-dial `ActionRegistry` action and the Plugins dialog launcher
return immediately and report the outcome later (see Examples).
- **Never call `orca.host.ui.*` from a slicing hook.** The slicing worker runs while the UI thread
can be parked on it.
- **Marshal host UI work from the Script worker only.** `PluginHostUi::run_on_ui_thread` blocks the
calling worker while the UI thread runs the callback; calling it from the UI thread itself would
deadlock the marshalling path.
- **No pointer crosses a call boundary.** `begin_update()` returns copied category/name/slot values;
the `SlicingPipelineContext` graph is valid only within one synchronous `execute(ctx)`.
## File and symbol map
Script execution runtime:
- `src/slic3r/plugin/PluginManager.hpp` / `.cpp` — `ScriptAsyncRuntime` (`instance`, `start`,
`cancel_plugin`, `has_active_run`, `shutdown`, `reset`, `current_loop`), `ScriptCompletion`,
`ScriptCompletionFn`, `ScriptLaunchResult`, `launch_script_capability`, `run_script_capability`.
- `src/slic3r/plugin/PyPluginTrampoline.hpp` — `invoke_script_execute`, `ScriptExecuteInvocation`,
`py_is_coroutine`.
- `src/slic3r/plugin/pluginTypes/script/ScriptPluginCapability.hpp` / `ScriptPluginCapabilityTrampoline.hpp`
— `ScriptPluginCapability::execute`, `PyScriptPluginCapabilityTrampoline`.
Lifetime and GIL primitives:
- `src/slic3r/plugin/PythonInterpreter.hpp` — `PythonInterpreter`, `PythonRuntimeLease`,
`PythonGILState`.
- `src/slic3r/plugin/PythonPluginInterface.hpp` — `PluginCapabilityInterface`, `RefCounter`,
`increment`/`decrement`/`ref_count`.
- `src/slic3r/plugin/PluginAuditManager.hpp` / `.cpp` — `ScopedPluginAuditContext`,
`request_filesystem_read_permissions`, `request_permission` (fail-closed off the main thread).
UI marshalling:
- `src/slic3r/plugin/host/PluginHostUi.hpp` / `.cpp` — `PluginHostUi::run_on_ui_thread`, the
file-local `run_on_ui_blocking`, and `close_windows_for_plugin`.
- `GUI::wxGetApp().CallAfter` — the post-to-UI-thread primitive.
Preset targets:
- `src/slic3r/plugin/host/PluginHostPresets.cpp` — `PresetEditor`, `PresetTransaction`,
`bind_preset_target`, `bind_filament_target`, `begin_preset_update`, `begin_filament_update`,
`SelectionCancelled`, `resolve_combo_preset`/`resolve_preset_in_combo`.
- `src/slic3r/GUI/Tab.hpp` / `.cpp` — `Tab::select_preset`, `Tab::apply_preset_config_values`,
`Tab::commit_preset_config_value`.
Launch paths:
- `src/slic3r/GUI/ActionRegistry.cpp` — `PluginScriptAction::run`, `notify_script_outcome`.
- `src/slic3r/GUI/PluginsDialog.cpp` — `PluginsDialog::run_script_plugin_capability`.
Slicing (synchronous only):
- `src/slic3r/plugin/PluginHooks.cpp` — `install_slicing_pipeline_hook`.
- `src/slic3r/plugin/pluginTypes/slicingPipeline/SlicingPipelinePluginCapability.hpp` —
`SlicingPipelineContext`, `execute`.
Unload/shutdown:
- `src/slic3r/plugin/PluginManager.cpp` — `unload_plugin`, `unload_all_plugins`,
`cancel_and_wait_for_capabilities`, `shutdown`.
## Examples
An `async def execute` that updates a preset. `execute` runs on the background Script worker with its
own asyncio loop; `begin_update()` blocks that worker until any selection / unsaved-edit dialog is
answered, without blocking the UI thread; `set()`/`commit()` then run synchronously on the same
worker. This is the shape used by `sandboxes/orca_preset_transaction_demo.py`:
```python
import asyncio
import orca
class AutoTune(orca.script.ScriptPluginCapabilityBase):
def get_name(self):
return "Auto tune"
async def execute(self):
# begin_update() blocks this worker until the user answers any
# selection / unsaved-edit dialog. The UI thread stays responsive.
tx = orca.host.preset.process.begin_update(preset_name="0.20mm Standard")
tx.set("layer_height", "0.2")
tx.commit()
return orca.ExecutionResult.success("process preset updated")
```
The window-driven demo shows the same pattern where the plugin's own UI must hand work to the worker:
`on_message` fires on the UI thread and only enqueues onto the worker loop with
`loop.call_soon_threadsafe`; `execute` consumes that queue and calls `begin_update()` per command.
Sequence for one `begin_update(...)`:
```text
Script worker (owned, per invocation) UI thread
loop.run_until_complete(task)
begin_update() ───────────────────────► CallAfter(run_on_ui_blocking)
(blocked; not suspended) bind_*_target →
Tab::select_preset() … dialog
settles
promise set; worker resumes with PresetTransaction
set(); commit() (UI thread for the batch)
coroutine resumes at its next await
execute() returns ExecutionResult
```
A plain `def execute` needs no loop and runs to completion on the same worker; both kinds are
launched with `launch_script_capability`, so the caller (UI thread) never blocks. A launch failure is
reported inline; a started run reports its outcome through the completion callback — the speed dial
shows "started" and pushes a completion notification, and the Plugins dialog updates its status when
`finish` runs.
+280
View File
@@ -0,0 +1,280 @@
# Seam alignment on the loop — High Level Design
## Purpose and scope
SeamPlacer selects candidates, connects neighboring layers into strings, fits each string and
places the resulting seam on its own contour. Painted ranges are reconstructed separately for
green enforcers and red blockers. These stages do not alter candidate ranking.
String construction and fitting apply to Aligned, Aligned Back and Back (`spRear`).
Nearest and Random bypass this stage, but share the paint reconstruction rules.
## Concepts
- **Candidate (C).** The seam candidate chosen for a perimeter in a string. Candidates are the
polygon vertices plus points inserted near paint (see Painted ranges), so the chosen candidate
can move in discrete steps from layer to layer.
- **Fitted point (F).** The value of the string's fitted curve at the layer height. It need not
lie on the loop: where the loop size changes quickly between layers, as near the bottom of a
sphere, it lies up to a few millimeters off it.
- **Measured angle.** `local_ccw_angle` of a candidate. It is measured at polygon vertices on arms
at least one nozzle diameter long; inserted points have angle 0.
- **Blend.** `target = t·C + (1 − t)·F`. The angle weight `t = min(1, (|angle C| / 55°)^3)` pulls
the seam onto sharp corners; at 55° and above the seam is the candidate itself.
- **Enforced run.** The maximal sequence of consecutive Enforced candidates of the perimeter that
contains C, or the whole loop when every candidate is Enforced. With exact painted ranges it
follows its geometric bounds and surface proximity; otherwise it approximates the painted area with the candidate spacing.
## Painted ranges
The paint is a set of small triangles on the model surface. Its **contour** is the set of their
edges that belong to one painted triangle only, taken from the painted triangles with their T-joints
split (`get_facets_strict`), so that edges inside the painted area pair up. Each contour edge keeps
the direction from it into the paint. The contour is built once per object and stored in an AABB
tree.
Green and red paint use separate instances of the same contour and interval reconstruction.
An interval bounds paint membership but does not establish it: every classified candidate must
also lie within one line width of a triangle of the corresponding paint. A contour can leave the
painted surface between projected endpoints, especially at concavities and nearby surface folds.
The same proximity check used by the fallback prevents such a detour from acquiring synthetic
paint; exact interval bounds still exclude the fringe beyond the projected ends.
Red ranges classify candidates as Blocked, including the boundary itself (1 µm membership
tolerance), overriding green paint at an overlap. Inserted samples include both red ends, a
range midpoint, a gap midpoint and permitted guard samples up to 2 µm outside the red ends.
The guard distance is reduced to one quarter of a shorter gap; gaps at or below the membership
tolerance can remain closed. Candidate marks closer than 1 µm merge.
These adjacent permitted samples limit fitted and optimized movement to the geometric red
edge, with the small outward guard, rather than to a distant original gray vertex. Red ranges add
no penalty and do not change candidate ranking. Precise Seam modifiers apply after paint
classification and take priority over it.
Random placement samples an outgoing edge of its selected candidate. On loops with exact
green ranges, an Enforced candidate followed by a non-Enforced candidate contributes no outgoing
edge length: the endpoint belongs to the paint, but the following segment leaves the permitted run.
This also respects weak modifiers that retype part of a painted run as Blocked or Neutral.
On loops with exact red ranges, a permitted candidate followed by a Blocked candidate contributes no outgoing
edge length, so Random cannot sample toward the closed red boundary. A zero-length selected
edge keeps the candidate position.
The cumulative-length selection stops at the last viable edge and clamps its
remaining distance to that edge, preventing float rounding from overrunning the
candidate list or the permitted segment.
Exact green and red ends bound the seam center position without expanding the painted range
along the contour by the line width. A seam can therefore reach a red edge with no line-width
clearance. Paint can be extended to request a larger clearance; the boundary does not
guarantee that the finite-width extrusion or a seam blemish stays entirely outside red paint.
If boundary crossings cannot be paired, the corresponding color falls back to the line-width
proximity classification, including its possible fringe beyond the paint edge. The fallback is
independent for each color and loop. For red this includes paint not crossing the layer,
ambiguous contours and a completely red surface without boundary crossings. In the all-blocked case
best-effort placement still produces a seam; red paint does not suppress extrusion.
An exact red reconstruction does not suppress proximity-based green oversampling when green
boundaries remain uncertain.
On a layer, the contour edges crossing the slicing plane give the exact ends of the painted band.
Each crossing within the line width of the loop is moved to its closest loop point; the direction
into the paint, against the loop direction there, tells whether paint lies ahead or behind. At a
vertex the loop direction is the mean of the two edges, skipping edges shorter than 1 µm such as
the repeated closing point and the shared ends of extrusion paths, so the result does not depend on
where the loop starts. Along the loop, ends where paint begins and ends must alternate; each
pair bounds a **painted range**. Such a loop has **exact ends**:
- a vertex is Enforced if it lies in a range (within 1 µm);
- points are inserted at the range ends, at the range middle and every 0.2 mm from the range begin,
and one in the middle of each gap between ranges, so that ranges with no vertex between them stay
separate patches;
- the central candidate of the longest patch is the middle of its range, unless the patch has a
sharp corner, which keeps priority.
Before generating candidates, a fully painted closed surface is treated like an unpainted surface:
it imposes no choice of seam position. A loop on a partly painted object can also be normalized when
there are no exact range ends, no active Precise Seam modifier, no non-green facet bounding box in
the loop's XY box expanded by line width and its Z slab of the same reach, and every entire loop edge
is proven within paint reach. Neutral and blocked facets both prevent this local proof. Segment
coverage uses the triangle inequality at its midpoint and at most eight bisections; failure retains
the ordinary conservative paint treatment. This is a sufficient test, not a claim to recognize every
fully covered contour near unrelated surfaces.
A normalized loop keeps the original candidates, without paint oversampling, Enforced status,
central enforcer, extra fitting or positional weights, painted-corner blending or paint fixation. Sharp-angle and Precise Seam rules remain authoritative. Whole-surface painting and no
painting therefore feed identical candidates into alignment.
Otherwise, which includes paint not crossing the layer (a dot between layers, the top and bottom of
a band), ends that do not alternate and a contour running along the
loop, a point is Enforced if paint lies within the line width of it, and edges near paint get points
every 0.2 mm from their start vertex. Such a run reaches past the paint by up to the line width,
depending on the vertices, and its central candidate is the middle one by count; on a smooth band
both shift the seam off the middle of the paint.
## Seam strings
A string starts at a seam and is extended upward layer by layer while the next layer has a seam
within reach. After the upward search ends, the downward search begins at the layer immediately
below the start. This keeps a matching neighboring seam in the same aligned string.
## Geometric contour continuation
Seam strings resolve the next layer's boundary before comparing seam preferences.
Each perimeter retains whether it bounds material or a hole, its layer-local index,
and immutable candidate geometry. Occupancy does not participate in correspondence: the radius search skips occupied
members of the permitted set without expanding it to unrelated walls.
Each layer builds an AABB tree of contour bounds once. Nearby-contour queries,
fast bounds matching, material containment and boundary proximity use this index
before applying their exact predicates. Query results are sorted by the
original contour index, preserving deterministic tie-breaking. Index construction
checks cancellation between layers. The index avoids scanning unrelated contours
for each seed; overlapping global bounds can still require many exact checks.
Only closed extrusion loops provide a reliable boundary role. Open paths and
collection fallbacks retain unknown geometry rather than deriving a physical role
from an artificial closing edge. An unknown source, or an unknown path whose
bounding box intersects the local query box in either layer, leaves the radius
search unrestricted. This conservative box test also covers the material probes;
it may disable the filter even when the path's segments are farther away.
Reverse confirmation applies only to candidates that pass the applicable distance
and normal checks, plus material checks on the local path outside the noise band.
Unknown geometry encountered around such a candidate's foot during reverse confirmation
also leaves the entire radius search unrestricted, rather than discarding only
that candidate. A reliable reverse rejection still excludes the candidate.
Unknown paths outside these query boxes do not disable reliable correspondence.
Bounding-box extents within one nozzle diameter plus a quarter-diameter reserve
identify a potential fast match of the same boundary type. Acceptance also requires
a closest segment within one eighth of the source line width, consistent air-facing
normals, no competing near-coincident local boundary, and a reverse set containing
the source. Thus the inexpensive path certifies only a near-coincident wall, rather
than treating global bounds and the full search radius as sufficient evidence.
The fallback uses the caller's KD search radius, normally four seed-line widths,
for nearby boundaries of either type. With unchanged boundary type it finds the
nearest segment whose air-facing normal is compatible with the source, so the
opposite side of a thin contour cannot hide its facing side. Across a type change
the closest patch itself must agree; choosing another side can confuse translated annuli.
An open exterior wall can become a hole when a slit closes; boundary type alone
cannot reject that physical continuation. It checks air-facing
normals within 60 degrees and samples the connector between closest boundary points.
Away from boundary noise, the connector must lie in material of exactly one adjacent
layer, representing a swept wall rather than a crossing through shared material or
air. Three samples are a bounded heuristic, not a topological proof.
Each local candidate must map back to a set containing the source boundary. A candidate
is discarded only if another has both a distance advantage of at least a quarter of
the source line width and a normal-angle advantage of at least five degrees. Equal or
conflicting criteria retain multiple candidates; seam preferences choose within
this set. Air-facing normals and material checks distinguish wall sides without imposing
an invariant exterior/hole label across topology changes. They are geometric gates,
not numerical preference weights.
If no geometric candidate survives, the radius search is left unrestricted. Continuation
then follows seam preferences alone and can switch walls where geometry cannot resolve
the case. A nonempty geometric set is never
expanded because its contours are occupied or fail later seam preference checks.
Correspondence queries are cached per source vertex, direction and search radius
for alternative string starts. Geometry construction and the seed loop check
cancellation to keep large multi-island objects interruptible. Correspondence does not alter candidate
preference weights or their tolerance.
## Final position
For each member of a string:
1. **Sharp candidate** (`t = 1`): the seam is C. This is the cheapest check and comes first.
2. **Painted corner pull** (Enforced C only): `t = max(t, 0.4·k)` with the corner influence
`k ∈ [0, 1]` below. Retaining the pull near measured corners protects corners; fading it on
smooth contours reduces transmission of discrete candidate steps into the seam. If C's own angle
reaches `A1`, `k = 1` without a search.
3. **Place on the loop.** The target is mapped onto the loop, within the allowed arc around C.
### Corner influence
`k` is the largest contribution `a_j · w_j` among candidates `j` of the same perimeter within `R1`
of C along the loop, `d_j` being the distance along the loop:
- `a_j` rises smoothly from 0 at a measured angle of `A0` to 1 at `A1`, so weak bends count partly
and smooth contours not at all;
- `w_j` is 1 up to `R0` and falls smoothly to 0 at `R1`, so a corner entering or leaving the
neighborhood does not switch `t` abruptly.
`R0` is the larger of the perimeter's line width and the largest configured nozzle diameter: the
measured angle of a vertex reflects geometry within at least one nozzle diameter, so a candidate
inserted next to a corner usually still sees that corner. Within `R0` of a corner of at least
`A1`, `t` and the target are the same as with a fixed minimum of 0.4.
### Placing the target on the loop
The target is generally off the loop. Its closest loop point is a polygon vertex over a whole range
of target positions, so it snaps to vertices and steps between layers when the vertices differ from
layer to layer.
Instead the loop gets a continuous normal field. Each vertex has the normalized sum of the normals
of its two edges, taken to the nearest points at a different position, so that duplicated points
(shared ends of extrusion paths, a repeated closing point) get one normal. Along an edge the normal
blends linearly between its vertex normals. A **solution** is a loop point whose normal line passes
through the target; on each edge this is a quadratic equation in the edge parameter.
The seam is the solution closest to the target over the whole loop. If it lies outside the allowed
arc, the seam is the end of that arc closer to the solution, so a solution leaving the arc stays at
the end it leaves through. Without any solution, which takes a degenerate loop, the seam is C.
The search walks outward from C on both sides, the shorter walked side first. An edge farther from
the target than the best solution so far is skipped without solving.
Properties:
- On a regular polygon every normal line passes through the center. For a target other than the
center, the closest solution is the nearer of the two intersections of the loop with the line
through the center and the target, wherever the vertices are; the seam equals it when it lies
inside the allowed arc. With an even number of vertices the two intersections are symmetric about
the center, so the nearer one is on the ray from the center through the target.
- When the closest solution is unique and lies inside the allowed arc, the result depends on the
target and that arc only, not on which candidate inside the arc was chosen. A candidate step
therefore does not pass into the seam directly. At an exact distance tie, the first solution found
from C is kept.
- A selected solution varies continuously while its root branch remains nondegenerate, and so does
the seam when the solution leaves or enters the allowed arc. The seam may jump when the closest
solution changes (two solutions equally close, or the closest one disappearing together with
another where the target crosses the curve of centers of the normal field), or when a solution
outside the arc becomes equally close to both arc ends. Changes of the candidate types between
layers change the allowed arc.
### Allowed arc
- For an Enforced C on a loop with exact ends: the Enforced run itself, which ends at the paint.
- For another Enforced C: the Enforced run, extended past each open end by the oversampling distance
(0.2 mm) but never into a Blocked candidate. The run ends sit on candidates and move in sampling
steps between layers, and Rear tends to choose the candidate right at an end; without the
extension a target just past an end would copy those steps into the seam.
- For another C: the part of the loop between the Blocked candidates around it.
- For a Blocked C, or a loop with no limiting candidate: the whole loop.
## Numerical constants
| Constant | Value | Meaning |
| --- | --- | --- |
| Blend minimum near corners | 0.4 | Pull toward C on a painted corner |
| `A0`, `A1` | 15°, 30° | Measured angle where corner contribution starts and becomes full |
| `R0` | max(line width, largest nozzle diameter); 0.5 mm if both are zero | Full corner protection along the loop |
| `R1` | 2·`R0` | Corner influence ends |
| Run extension | 0.2 mm (`enforcer_oversampling_distance`); 0 with exact ends | How far the seam may go past an end of the Enforced run |
| Painted range tolerance | 1 µm (`enforced_end_tolerance`) | Loop positions this close are one point |
| Range end reach | line width | How far from the loop a contour crossing may lie |
| Coverage proof depth | 8 bisections per edge | Finite conservative proof for complete paint on a partly painted object |
| Solver threshold | 1e-12 | Absolute threshold on the equation coefficients that tells degenerate equations apart; not a distance tolerance |
## Constraints
Strong Precise Seam coordinates remain immutable. Angles of at least 55 degrees retain the
selected candidate. Ambiguous paint boundaries use the proximity fallback; an entirely
blocked perimeter still needs a printed seam. Mesh topology and candidate sampling can change
which first-approximation string is selected. Painting a verified complete perimeter introduces
no artificial center preference.
## Implementation and verification
`SeamPlacer.cpp` implements paint reconstruction, candidate selection, string traversal, fitting
and contour placement. `test_seam_placer.cpp` covers geometry, paint, string traversal and strong
Precise Seam invariants. `tests/libslic3r/test_seam_contour.cpp` independently checks
geometric correspondence, ambiguity and search-radius behavior.
+159
View File
@@ -0,0 +1,159 @@
# Translucent filaments
## Purpose
A filament color can carry an opacity (`#RRGGBBAA`, see [color-picker.md](color-picker.md)). Prepare
draws the parts of such a filament see-through, and Preview their toolpaths, so the inside of a
translucent part and whatever lies behind it show through. Both tabs aim at the same look: the
opacity of the plastic the view ray crosses, matte without realistic view and glossy with it.
## Where the opacity applies
- Only the views that color toolpaths by filament: Filament, Summary and Tool. The other views
color by feature or by a value, and stay opaque.
- Only extrusions. Travels, wipes and option markers stay opaque, and so do the layers that hold a
pause or a custom G-code, which these views draw grey.
- A filament keeps its color down to 10% opacity, the floor `adjust_color_for_rendering()` gives it in
Prepare too, so that a fully clear filament is still drawn. A near-black filament is lifted to a grey
that rises with its transparency: a dark translucent surface shows nothing through itself, so without
the lift its layers blend into one flat black.
- The "Translucent filaments" preference (`preview_translucent_filaments`, on by default) turns all
of it off: every filament is then drawn opaque, the legend swatches included. It applies to the
loaded preview at once, through `Viewer::set_translucent_filaments()`.
- The legend swatches carry the same opacity, drawn over the white and grey checkerboard of the
sidebar's clear filament swatch so that they read on the dark legend.
- The opacity is that of 0.4 mm of the filament. Each translucent segment raises it to the length
of the view ray through the centre of its diamond section, `1 - (1 - a)^(path / 0.4)`, so thin
layers stacked under the camera add up as one thick layer would, and a wall seen side on keeps
about the filament's opacity whatever the layer height.
## Data
`libvgcode::convert_filament_colors()` decodes the filament color strings into a
`libvgcode::PaletteWithAlpha`. libvgcode keeps one RGBA8 color per vertex, in a `GL_RGBA8` texture
buffer, or in RGBA8 2D textures on OpenGL ES. The color depends on the view type, while the alpha
comes from the filament alone. The viewer also notes whether any vertex is translucent.
## Rendering
A segment takes the alpha of its first vertex. While any vertex is translucent,
`update_enabled_entities()` sorts the enabled segments by opacity, the opaque ones first, keeping
the print order within each group; on OpenGL ES, each texture of the list is sorted on its own.
Each pass draws its own group, from an offset into the list. Without a translucent vertex, the list
is not sorted and the second pass is skipped, so the first draws exactly what it drew before.
1. The opaque segments, with depth writes.
2. The option markers.
3. The translucent segments, in premultiplied color blended with `GL_ONE, GL_ONE_MINUS_SRC_ALPHA`,
depth tested but without depth writes. Opaque toolpaths and objects hide the translucent ones
behind them, and a translucent segment hides nothing. Drawing the markers first keeps those
inside a translucent part behind its surface, instead of on top of it.
`Viewer::render()` draws the first two; `Viewer::render_translucent()` draws the third, which
`GLCanvas3D::_render_gcode_translucent()` calls after the SSAO pass. Drawn that late, the pass turns the
depth test on itself, as the passes before it may leave it off. The occlusion that pass reads
from depth would otherwise shade a translucent surface as the surface behind it, as it would the
centre of mass marker. FXAA still comes after. The sequential view markers and the IDEX/IQEX
toolhead boxes, which `GCodeViewer::render_scene()` draws after the toolpaths, are translucent but
write depth, so while there are translucent toolpaths they wait for them, in
`GCodeViewer::render_translucent_toolpaths()`. Drawn before, they would hide the translucent toolpaths
behind them, and the print would show a hole around the tool position.
A translucent segment takes its diffuse light in its own color, scaled by its opacity. In
realistic view, whatever its other options, with its "Glossy toolpaths" setting on, every segment,
opaque or translucent, takes instead of the tinted highlight of the default shading an untinted one
computed per fragment, not scaled by the opacity, so that the filaments look alike and a clear one
keeps its gloss instead of fading into the background. `GLCanvas3D::_render_gcode()` switches it
with `Viewer::set_gloss()`. Without realistic view, or with the setting off, a translucent filament
is matte and an opaque one keeps the default shading. The
highlight takes the normal of the rounded extrusion a segment stands for, an ellipse of its height
and width around its centre line, rather than that of its facets: it then runs smoothly across a
joint, where the facets of two segments would catch it apart, and it fades out towards the tip of a
path end, whose normal runs along the extrusion. There
is no Fresnel term: an extrusion seen end-on would turn into a bright opaque stripe.
Each segment reaches half a line width past its ends, to fill the outside of a turn or round off a
path end, so two segments of a path overlap at their joint. Depth hides that between opaque ones,
but blending would draw the joint twice, and the highlight of realistic view shows the caps sticking
out of an opaque one. A translucent segment, and a glossy one, is therefore cut in the fragment
shader at the bisector plane of each joint of its path, keeping 0.02 mm past it: the
faces each segment turns to the camera do not quite meet without their caps. A vertex where two
segments of a path meet carries 0.5 on top of its layer in the w of its position, which the shaders
otherwise read as an int. That includes the joints across the vertex repeated in place that starts
a new path wherever the flow, acceleration or jerk changes (`starts_path()` in
`LibVGCodeWrapper.cpp`), which real G-code has at most of its joints: the shader then takes the
neighbour one vertex further, and the caps the angle of the joint, which the vertex data leaves at 0
there.
The translucent segments are not sorted by depth. The opaque pass draws the last printed segments
first when looking down, to cut overdraw. The direct translucent pass, which only some cases fall
back to (see below), draws them the other way round, so the farthest layers blend first.
## Order independent blending
Blended in print order, the order shows even with a single translucent color, since its surfaces are
shaded apart. A layer's infill, printed after its walls, blends over the walls in front of it: seen
from the side, the dark bridge under a deck draws a sawtooth over the hull's outer wall, as if a piece
of it were missing. So on desktop OpenGL the translucent segments blend order independently, in
`ViewerImpl::render_translucent_segments()`. The nearest
translucent surface of each pixel is drawn over a weighted blended order independent transparency
(McGuire and Bavoil, 2013) of the others. The mean alone would not do: the walls of a painted object
lie a fraction of a millimetre apart, so its depth weights barely differ, and the more opaque and more
numerous surfaces of one filament would hide the other filament's outer wall in front of them.
1. The depth of the scene drawn so far is copied into a texture. The fragment shader discards a
translucent fragment behind it, as there is no depth buffer to test against.
2. The translucent segments are drawn once into an `R32F` target cleared to 1, keeping with `GL_MIN`
the `gl_FragCoord.z` of the nearest. The segments shaders draw it built with `DEPTH_ONLY`, the same
geometry and joint cut without the shading and its varyings, so the nearest fragment of the next
pass finds its own depth there exactly.
3. They are drawn again. The nearest fragment of a pixel goes, premultiplied, to an `RGBA16F` target
of its own. Every other one adds its premultiplied color, times a weight, to an `RGBA16F` target,
and `-log(1 - alpha)` to an `R16F` target, with `GL_ONE, GL_ONE`. The weight is the opacity times
`max((1 - z)^3, 0.01)`, z being the depth across the extrusions' bounding box, so nearer surfaces
count more. Its ceiling keeps thousands of stacked surfaces within half float range, and its floor
keeps far ones out of the subnormals. A translucent segment's opacity stays below 1, else the
shader would take it for an opaque one and add it unweighted.
4. A full screen pass draws the nearest surface over the weighted mean color of the others, with
their coverage `1 - exp(-sum)`, over the scene.
Swapping the drawing order changes the result by at most 2 levels out of 255, against up to 246 in
the direct pass. The targets are single-sampled whatever the canvas, about 26 bytes per pixel.
Multisampled ones would take twice the time and four times the memory for edges FXAA can smooth, and
against a single-sampled depth pass an edge sample could miss its nearest depth and count twice.
OpenGL ES, whose float targets are optional, takes the direct pass, as does a multisampled framebuffer
object, whose depth cannot be copied into a texture.
## Cost and side effects
Without depth writes, every translucent surface on screen is shaded, so the cost of the second
pass grows with the number of translucent surfaces stacked on screen. Order independent blending
draws the translucent segments twice and writes 18 bytes of float data per pixel instead of 4, between
a tenth and two fifths more than the direct pass.
In realistic view, a translucent segment casts into a share of the shadow map texels as large as
its opacity, in an ordered 4x4 pattern that the 5x5 filter of the receivers reads as a lighter
shadow. The pattern shifts with the segment, so layers stacked along the light add up: a 1 mm
translucent box at 35% casts a shadow about 60% as dark as an opaque one, a 10 mm box nearly a full
one.
## Prepare
Prepare draws a part as a closed mesh, which would show a single surface at the filament's opacity,
far fainter and darker than the print of that part in Preview. The object shaders therefore shade a
visible model part whose filament color is translucent as the view ray crossing two shells of the
part, the front and the back one, of two 0.45 mm walls each, with the opacity rule of Preview:
`1 - (1 - a)^(1.8 / 0.4 / cos)`, cos being that of the angle between the view and the normal,
floored at 0.25. A filament at 35% is then about 86% opaque face on, and nearly opaque at the
silhouette, where the ray grazes the walls. See `translucent_filament_color()` in `gouraud.fs` and
`phong.fs`.
Such a part is drawn in premultiplied color, blended with `GL_ONE, GL_ONE_MINUS_SRC_ALPHA`, so that
in realistic view its highlight is not dimmed by its opacity; without realistic view it takes no
highlight. `GLVolumeCollection::render()` switches this per volume, and only with a shader that has
the `translucent_filament` uniform, the GLSL 1.40 ones: with the GLSL 1.10 and ES shaders, such a
part blends as a plain transparent volume. Modifiers, negative volumes and opaque parts are drawn as
they were.
The wireframe overlay draws translucent filament parts too, with blending off, so their lines stay
solid.
+216
View File
@@ -0,0 +1,216 @@
# Travel optimization — High Level Design
## Purpose and scope
Inside an island, the infill paths of each region are chained into one print
order by a greedy pass that joins the closest free path ends first. That pass
leaves its longest joins for last, and they often cross the whole island. Two
things shorten the travel between infill paths:
- the fill generators join their lines into as few paths as they can, since
every separate path needs a travel to it;
- the G-code export refines the greedy chain with a local search that shortens
the straight-line travel between the paths;
- a fill that keeps its order prints each piece of its gap fill where it passes
by, since the G-code export cannot reorder it.
The refinement covers every chain that `chain_and_reorder_extrusion_entities()`
builds from a start point: the infill and ironing of `GCode::extrude_infill()`
and the support of `GCode::extrude_support()`, as well as the order of objects
and islands under `print_order` Default. It changes only the order and the
direction of the paths, not the paths or the walls. Neither part has a setting.
## The chain
`ObjectByExtruder::Island::Region::append()` flattens every sortable fill
collection into its paths, so the paths of all the fills of a region in one
island are chained together. A collection that must keep its order (`no_sort`:
monotonic, concentric, a forced fill order, the flow calibration) stays a single
entry that cannot be reversed. Paths that must keep their direction cannot be
reversed either: Grid's, since it alternates their direction between layers for
strength, and those of a fill with a forced order. A loop starts and ends at the
same point, so reversing it changes nothing.
`extrude_infill()` chains each region from the current nozzle position with
`chain_and_reorder_extrusion_entities()`, and chains the paths inside a nested
sortable collection the same way; `extrude_support()` chains the support paths
of a layer so too, unless they keep their order. The overload without a start
point, used to chain collections while slicing, keeps the greedy chain. The
order the fill generators give their paths does not reach the G-code for a
sortable fill, which is chained again.
## Connecting the lines
Most patterns cut their lines at the infill boundary, and `Fill::connect_infill()`
joins pairs of line ends that are neighbors on a boundary contour by the arc of
wall between them, shortest arcs first, as long as neither end is joined yet and
the join closes no loop. An arc is joined when it is shorter than
`infill_anchor_max`, or than two anchors and a line width if that is longer:
two ends further apart each get an anchor toward the other, and where those
would meet, the join prints about as much wall as one path instead of two.
Regular patterns leave many arcs of the same length, and the order among them
decides the pairing. In an arbitrary order the pairs along one wall can fall out
of step, such as lines 1–2 and 3–4, then 6–7 and 8–9, which leaves the end of
line 5 loose, and every loose end starts or ends a separate path. So the arcs
are also sorted in steps of half the line spacing and, within a step, along each
contour forwards and backwards, which pairs the ends of a wall in one phase.
Each order is replayed on the flags and a union-find of the lines, without
building any path, and the one that joins the most lines is used; a tie keeps
the shortest-first order.
The replay includes the last pass, which joins any two open ends that are
neighbors on a contour. With multiline infill the main pass leaves the copies of
one line to that pass, so that each copy reaches a wall of its own. Two
neighboring groups cut at both walls can then be joined at either wall by arcs
of the same length: at one, their open ends stay next to their own copies, which
the last pass joins, so each line prints out and back; at the other, the copies
end up in separate paths printed apart.
A line end left unpaired gets an anchor, a piece of the wall at most
`infill_anchor` long. It runs toward the nearest open end of another path,
looking up to 64 ends along the contour, since the next path usually starts
there; without one it takes the side with more free wall. With multiline infill
an anchor toward a copy of the same line stops short of the copy rather than
printing over it. A copy is a neighboring end less than the group width
(`multiline` spacings) across the line, at any wall angle, while the next group
lies a whole line spacing away. Meeting the wall at an angle θ, the copy covers
half a width over sin θ of the wall on each side of its end, so the anchor stops
that far and half its own width before it, or is left out; the end still counts
as anchored, so the last pass pairs the other ends as before.
Last, `Fill::fill_surface_extrusion()` joins the sparse infill lines whose ends
are at most two line spacings apart with a straight piece. With the anchors off
(`infill_anchor_max` 0) nothing above runs and this is the only joining; with
them on, it takes what the steps above leave next to each other, such as two
anchors that stop just short of each other or a short piece cut off by a corner.
A gap that short leaves no room to print anything in between, and as a travel it
is the one hop a reordering can trade for a longer travel that retracts.
Multiline copies leave the most such ends: one spacing apart across the line,
their ends where it meets a wall at an angle θ are one spacing over sin θ apart
along it, so two spacings reach walls met at 30° and steeper.
Ends that meet are joined first, then the gaps between the leading ends of their
lines, along each line's overall direction, then the rest, shortest first within
each, without closing a loop or crossing a line or another join. Taking the
leading ends first joins every pair of copies at the same side, which leaves
their open ends next to each other; by length alone, neighboring pairs were
joined at different walls and the travel between them crossed the island. Lines
that cannot reverse, such as Grid's, only join the end of one to the start of the
next, and fills that keep their order are left alone.
## Gap fill in a fill that keeps its order
`Fill::_create_gap_fill()` adds the gap fill of a solid surface, where
`gap_fill_target` asks for it, after the lines of the fill. The chain mixes it
in with the lines of a sortable fill like any other path. A fill that keeps its
order, such as monotonic, would print all of its lines and then come back for
every piece of gap fill, most of which lies at the walls where the lines end.
So each piece, in turn, goes between the two extrusions of the fill where it
adds the least travel, flipped when that is shorter. A closed piece counts from
its point nearest the nozzle, where `GCode::extrude_loop()` starts it. The two
ends of the fill cost nothing, since the travel to and from them depends on what
is printed before and after. The fill's own extrusions keep their order and
direction, so a monotonic fill stays monotonic. When the result travels no less
than the gap fill printed after the lines in its own order, that order is kept.
## The search
A chain of up to eight paths is found exactly, by dynamic programming over the
subsets of paths: a state is the paths visited so far, the last one and its
direction, about four thousand states for eight paths. The shared greedy
chaining, `chain_segments_greedy_constrained_reversals_()`, does the same for two
to four segments, which also orders up to four islands of a layer and the loops
of a perimeter collection exactly. Either way the first path is no longer
always the one nearest the start; with a free end, a path near the start can be
worth leaving for last.
Objects (`print_order` Default) and the tour of islands across objects are
visited in the same order on every layer, so `chain_points_with_postprocessing()`
orders them as a closed tour rather than an open chain. Up to ten points the
shortest tour is found exactly by the same dynamic programming with the first
point fixed; with a start point the tour then begins at the point nearest it.
Larger sets take the greedy chain and alternate 2-opt, or-opt and crossing
removal; or-opt moves runs of up to three points next to one of the eight points
nearest an end of the run, found on the same grid as the chain's candidates.
For longer chains, the search refines the greedy chain. On an island cut into many short pieces,
such as infill without anchors, that chain can sweep away from the nozzle and
come back for the rest with one long jump, which no local move below removes.
So a nearest-next chain, going from the nozzle to the nearest free path end each
time, is built too; when it is already shorter than the refined greedy chain, it
is refined and used instead. Elsewhere it costs one grid query per path.
`improve_chain_by_local_search()` sees the chain as a sequence of segments with
an entry and an exit point each. Its cost is the straight distance from the
nozzle to the first entry plus the distance from every exit to the next entry;
the end of the chain is free. It applies three kinds of moves:
- 2-opt reverses a run of segments, which flips each of them and replaces the
two links at the ends of the run.
- Or-opt moves a run of up to three segments between two others, flipped or
not.
- A run of any length that starts or ends next to the nozzle moves to the front.
Local search can settle on a chain that starts with a block of paths far from
the nozzle while the paths next to it sit in the middle, and moving that block
takes more than three segments at once.
A move that would flip a segment that cannot be reversed is skipped, so such
segments are only reordered.
A move is tried only if every link it creates joins an end point to one of the
32 end points nearest to it, which covers every move on a chain of up to 17
segments, as most islands are; with 8 candidates the search missed most of the
gain on grid-like patterns such as Triangles. The candidates come from a uniform
grid of about two end points per cell, searched in rings of cells around the
query. `KDTreeIndirect` visits its subtrees in a fixed order rather than the
nearer one first, so a query for 32 points walks most of the tree, and on long
chains finding the candidates would cost more than the search itself.
The candidates of an end point are tried nearest first, and only while they are
closer to it than the link the move would replace there. A 2-opt move that pays
off creates a link shorter than the one it replaces at one of its two ends, so
this misses no 2-opt move. An or-opt move is tried only while its new link is
shorter than what taking the run out saves, which skips a few or-opt moves that
would still pay off but cuts the search on long chains to a fraction.
The search works through a queue of segments and applies the first move that
shortens the chain around the segment it examines. After a move, only the
segments next to a changed link are queued again. A new link can also make room
for a run elsewhere that no segment next to it would try, so when the queue
empties after any move, every segment is queued once more, and the search ends
when such a sweep finds no move.
Every move shortens the chain by more than `SCALED_EPSILON`, so the result is
never longer than the greedy or the nearest-next chain and the search ends; a
cap of 50 moves per segment only bounds its time. The search has no randomness
and visits the segments in a fixed order, so the same input always gives the
same G-code.
## Cost
Finding the candidates of an end point visits a few cells, and the nearest-next
chain makes one such query per path, which only grows where the paths around the
nozzle are used up and the chain jumps. Examining a segment tries at most a few
hundred candidate links, usually only the nearest few, plus a scan of the chain
for the move to the front when it is the first segment, and a move rewrites only
the range of the chain it changes, so the search stays close to linear in the
number of segments. Most islands hold a few to a few dozen paths; the cost shows
on infill cut into thousands of pieces per island, such as dense infill with the
anchors off. The straight joins only look at the line segments near a candidate
join for crossings.
## Limitations
The search minimizes straight-line distance. It does not know which travels
leave the infill area and retract under `reduce_infill_retraction`, nor the
detours of `reduce_crossing_wall`, and a travel's time is not proportional to
its length: a short travel is bound by acceleration, so its time grows about
with the square root of its length. A chain that is shorter in total but trades
very short travels for longer ones, or for ones past `retraction_minimum_travel`,
can occasionally take a little longer to print.
The end of the chain is free: it is not steered toward the next island or the
start of the next layer. The regions of an island are chained one after the
other, in region order, each from where the previous one ended.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1
View File
@@ -166,6 +166,7 @@ src/slic3r/GUI/NotificationManager.cpp
src/slic3r/GUI/ObjectDataViewModel.cpp
src/slic3r/GUI/OpenGLManager.cpp
src/slic3r/GUI/OptionsGroup.cpp
src/slic3r/GUI/OptionStateRegistry.cpp
src/slic3r/GUI/PrintOptionsDialog.cpp
src/slic3r/GUI/SafetyOptionsDialog.cpp
src/slic3r/GUI/ParamsPanel.cpp
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
<?xml version="1.0" encoding="UTF-8"?><svg id="a" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 15"><rect x="7" y="12" width="1" height="1" style="fill:#fefefe;"/><path d="M4.5,5.5c0-1.71,1.43-3.09,3.16-3,1.62.08,2.84,1.54,2.84,3.17h0c0,.61-.25,1.2-.69,1.62l-2.31,2.24v.97" style="fill:none; stroke:#fefefe; stroke-linecap:round; stroke-linejoin:round;"/></svg>
<?xml version="1.0" encoding="UTF-8"?><svg id="a" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 15"><rect x="1.5" y="3.5" width="12" height="8" rx="1" ry="1" style="fill:none; stroke:#fefefe; stroke-linecap:round; stroke-linejoin:round;"/><path d="M3,5h1v1h-1Z M5,5h1v1h-1Z M7,5h1v1h-1Z M9,5h1v1h-1Z M11,5h1v1h-1Z M4,7h1v1h-1Z M6,7h1v1h-1Z M8,7h1v1h-1Z M10,7h1v1h-1Z M5,9h5v1h-5Z" style="fill:#fefefe;"/></svg>

Before

Width:  |  Height:  |  Size: 366 B

After

Width:  |  Height:  |  Size: 415 B

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "Anker",
"version": "02.04.00.06",
"version": "02.04.00.07",
"force_update": "0",
"description": "Anker configurations",
"machine_model_list": [
@@ -6,7 +6,7 @@
"instantiation": "false",
"gcode_flavor": "marlin2",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\nG92 E0.0\n;[layer_z]\n\n",
"file_start_gcode": ";TIME:{print_time_sec}s",
"file_start_gcode": ";TIME:{print_time_sec}s\n;Filament weight: {total_weight}g\n;Filament used: {used_filament}m\n;Layer height: {layer_height}\n;material_print_temperature_layer_0: {first_layer_temperature[0]}",
"machine_start_gcode": "M4899 T3 ; Enable v3 jerk and S-curve acceleration \nM104 S150 ; Set hotend temp to 150 degrees to prevent ooze\nM190 S{first_layer_bed_temperature[0]} ; set and wait for bed temp to stabilize\nM109 S{first_layer_temperature[0]} ; set final nozzle temp to stabilize\nG28 ;Home\n;LAYER_COUNT:{total_layer_count}",
"machine_end_gcode": "M104 S0\nM140 S0\n;Retract the filament\nG92 E1\nG1 E-1 F300\nG28 X0 Y0\nM18",
"change_filament_gcode": "M600",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "Anycubic",
"version": "02.04.00.09",
"version": "02.04.00.10",
"force_update": "0",
"description": "Anycubic configurations",
"machine_model_list": [
@@ -108,7 +108,7 @@
],
"machine_start_gcode": "G90 ;Use absolute coordinates\nM83 ;Extruder relative mode\nM104 S[first_layer_temperature] ;Set extruder temp\nM140 S[first_layer_bed_temperature] ;Set bed temp\nM190 S[first_layer_bed_temperature] ;Wait for bed temp\nM109 S[first_layer_temperature] ;Wait for extruder temp\nG28 ;Move X/Y/Z to min endstops\nG1 Z0.28 ;Lift nozzle a bit\nG92 E0 ;Specify current extruder position as zero\nG1 Y3 F1800 ;Move Y to purge point\nG1 X60 E25 F500 ;Extrude 25mm of filament in a 5cm line\nG92 E0 ;Zero the extruded length again\nG1 E-2 F500 ;Retract a little\nG1 X70 F4000 ;Quickly wipe away from the filament line\nM117",
"machine_end_gcode": "M104 S0 ;Extruder off\nM140 S0 ;Heatbed off\nM107 ;Fan off\nG91 ;Relative positioning\nG1 E-5 F3000 ;Retract filament\nG1 Z+0.3 F3000 ;Lift print head\nG28 X0 F3000 ;Home X axis\nM84 ;Disable stepper motors",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n[layer_num] @ [layer_z]mm\nG92 E0",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n[layer_num] @ [layer_z]mm",
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_num] @ [layer_z]mm\nG92 E0",
"layer_change_gcode": ";AFTER_LAYER_CHANGE\n;[layer_num] @ [layer_z]mm",
"scan_first_layer": "0"
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "Bambulab",
"url": "http://www.bambulab.com/Parameters/vendor/BBL.json",
"version": "02.08.00.15",
"version": "02.08.00.16",
"force_update": "0",
"description": "the initial version of BBL configurations",
"machine_model_list": [
@@ -5,6 +5,11 @@
"from": "system",
"setting_id": "GFSB00_36",
"instantiation": "true",
"activate_air_filtration": [
"0",
"0",
"0"
],
"chamber_temperatures": [
"65"
],
@@ -468,6 +468,7 @@
"319",
"319"
],
"support_air_filtration": "1",
"support_cooling_filter": "1",
"support_chamber_temp_control": "1",
"support_object_skip_flush": "0",
@@ -372,6 +372,7 @@
"319",
"319"
],
"support_air_filtration": "1",
"support_cooling_filter": "1",
"support_chamber_temp_control": "1",
"support_object_skip_flush": "0",
@@ -267,6 +267,7 @@
"30",
"30"
],
"support_air_filtration": "1",
"support_chamber_temp_control": "1",
"support_cooling_filter": "1",
"support_object_skip_flush": "1",
@@ -210,6 +210,7 @@
"18",
"18"
],
"support_air_filtration": "1",
"wipe_distance": [
"2",
"2"
@@ -267,6 +267,7 @@
"18",
"18"
],
"support_air_filtration": "1",
"support_object_skip_flush": "1",
"wipe_distance": [
"2",
@@ -213,6 +213,7 @@
"18"
],
"scan_first_layer": "1",
"support_air_filtration": "1",
"wipe_distance": [
"2",
"2"
@@ -208,6 +208,7 @@
"18"
],
"scan_first_layer": "1",
"support_air_filtration": "1",
"wipe_distance": [
"2",
"2"
@@ -189,6 +189,7 @@
"20",
"20"
],
"support_air_filtration": "1",
"support_chamber_temp_control": "1",
"upward_compatible_machine": [
"Bambu Lab A1 0.4 nozzle",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "Flashforge",
"url": "",
"version": "02.04.00.11",
"version": "02.04.00.12",
"force_update": "0",
"description": "Flashforge configurations",
"machine_model_list": [
@@ -8,6 +8,7 @@
"compatible_printers": [
"Flashforge Adventurer 5M 0.4 Nozzle"
],
"exclude_object_tolerance": "0.2",
"filename_format": "{input_filename_base}_{filament_type[initial_tool]}_{print_time}.gcode",
"post_process": "",
"only_one_wall_top": "0",
@@ -8,6 +8,7 @@
"compatible_printers": [
"Flashforge Adventurer 5M Pro 0.4 Nozzle"
],
"exclude_object_tolerance": "0.2",
"filename_format": "{input_filename_base}_{filament_type[0]}_{print_time}.gcode",
"post_process": "",
"only_one_wall_top": "0",
Loaded 100 of 736 files, more files were not shown because too many files have changed in this diff. Show more