Compare commits

..
Author SHA1 Message Date
SoftFever 693d6cbf6e Merge branch 'main' into image-gizmo 2026-10-13 19:51:55 +08:00
ExPikaPaka 053019261f Merge remote-tracking branch 'origin/image-gizmo' into image-gizmo
# Conflicts:
#	src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp
2026-10-13 08:47:58 +02:00
ExPikaPaka b0d586837b Merge upstream main into image-gizmo
Three conflicts, all in the texture displacement gizmo, all resolved by
keeping both sides:

- Two independent additions landed next to apply_standard_mode_presets():
  upstream's store_panel_state() and this branch's image-mode declarations.

- m_color_tex_source: upstream changed it from a raw const void* to a
  weak_ptr to the image bytes, so a freed and reallocated image can no longer
  pass for the old one. That is the better key and it is kept; the colour
  correction key this branch added sits beside it, and the cache test now
  checks the image, the smoothing and the correction.
2026-10-13 08:43:14 +02:00
ExPikaPaka 8ac8a75056 Include the headers GLGizmoImage.cpp uses directly
Adds the includes misc-include-cleaner named: libslic3r/Point.hpp for
Vec2d, Vec3f and Transform3d, GLGizmoTextureDisplacement.hpp for the
base class, IconManager.hpp for the icon lookup, and cmath, cstddef
and cstdlib for round, size_t and abs.
2026-10-12 15:31:21 +02:00
ExPikaPaka 60248cadd3 Move the Image tool's declarations off the line main now uses
store_panel_state() landed in the same place, from the .3mf persistence
branch. Same declarations, a few lines down, after bake_standard().
2026-10-12 15:14:22 +02:00
ExPikaPaka c07a082050 Add the pipette icon on a line of its own
Three other open texture-displacement branches add an icon to this list too.
Reflowing the lines they also touch is what turns four one-word additions
into four conflicts; a new line four lines away from the next one merges in
any order. Order in the list is irrelevant - the map keys by file name.
2026-10-12 14:03:43 +02:00
ExPikaPaka c92721cabf fix: Negative belongs with the colour corrections, not under Background
It sat below the Background section purely because of source order, which
read as if it were part of it. Reset moves out of both sections and becomes
Reset all, since it clears the corrections and the background key alike and
a reset living inside one of them would look like it only reached that far.
2026-10-12 13:30:31 +02:00
ExPikaPaka 47a4e7447f feat: a real dropper that reads the model, foldable sections, a scrolling panel
- The dropper has its own pipette icon instead of borrowing the placement
  handle's, drawn in the house style: 16 px canvas, 0.4 stroke in #949494,
  teal on the tip, which is the part that carries the meaning.

- It picks off the model as well as off the preview. A click on the 3D view
  while it is armed reads the picture's own colour at that point, through
  the same projection the bake uses, not the pixel on screen: the screen
  pixel carries the lighting and the filament the colour was already
  quantized to, so keying on it would remove the wrong thing. The patch
  frame comes from extract_painted_patch() plus
  texture_displacement_patch_frame(), so a cylindrical or spherical layer
  reads at the same place the bake will.

- Placement, Color and Background fold away, with the triangle-and-text the
  displacement panel's "More settings" link uses rather than ImGui's own
  filled bar, which is louder than anything else in this window. Folded,
  Background still says whether it is removing anything. Open by default and
  remembered for the session only: this is panel state, not something a
  project should carry.

- The body scrolls and the footer is pinned under it, the shape the
  displacement panel already uses. With the panel this tall, Apply and Close
  were the first things to go off the bottom of a short canvas.
2026-10-12 13:21:41 +02:00
ExPikaPaka 4286cb30ba feat: a colour count instead of Two colours, and a pickable background
Two colours was the N=2 case of a more useful control, so it is replaced by
a Colors slider: 0 for off, then 2 to 12. The picture is reduced to that many
colours before the filaments are matched to it, so it prints in at most that
many.

Reduced by k-means in RGB rather than by posterizing the range, because the
useful question is which colours the picture is actually made of. A tartan
asks for its own handful of greens and reds; an even split of the range would
hand it eight shades of mud. The clustering runs over a coarse 16-per-channel
histogram, 4096 weighted points instead of a million pixels, which is what
makes it cheap enough to sit on a slider, and it is seeded the k-means++ way
so a picture with one dominant colour does not get every centre inside it.

This is not the displacement tool's "Mixed colors", which caps how many mixed
filament slots a bake may create. Nothing like it existed.

Background removal can now be told which colour to remove. The four corners
stay the default, because a background that does not reach all four of them
is not a background and that makes the common case one click, but the panel
shows the colour as a swatch that is also a picker, and a dropper beside it
takes the colour from the preview. The dropper reads the decoded image rather
than the screen: the preview is scaled, and it already has the corrections
applied, so a screen read would key the corrected colour against itself.
"Corners" puts it back.

Measured on Tartan, a cube face, four filaments:

  run                    out tris  coloured  filaments  filament shares
  image, no correction      22534     14544          4  1:91% 3:8% 4:1%
  image, 2 colors           18232     10268          2  1:66% 3:34%
  image, 3 colors           24458     16459          3  1:78% 3:18% 4:5%
  image, 5 colors           23972     15978          4  1:90% 3:9% 4:1%

Asking for 2 gives 2 and asking for 3 gives 3. Asking for 5 gives 4, which is
the contract working the right way round: only four filaments are loaded, and
"at most" is the guarantee. No run moves the surface.
2026-10-12 13:01:06 +02:00
ExPikaPaka 3ee9c02acf feat: sharpen, two colours, and remove background in the Image tool
Three more corrections, chosen because the output is a handful of flat
filament colours rather than a continuous image: what helps is whatever
decides which filament an area lands in and where the boundary between two
of them falls.

- Sharpen. An unsharp mask over the colour, reusing the sliding-window blur
  the Smoothing slider already uses, run per channel. Worth more here than
  in a photo editor: a soft edge between two colours quantizes into a ragged
  band of both, and sharpening first makes it land in one place.

- Two colours. Thresholds on luma so a logo or line art prints in exactly
  two filaments instead of speckling across several, with the split point on
  a slider.

- Remove background. The one that is not an RGB transform. DecodedHeightTexture
  gains an alpha plane, filled from the source PNG's fourth channel when it
  has one, and the key additionally clears whatever colour the picture's four
  corners share. A transparent texel is not black: sample_layer_color()'s
  covered() now reports it the same way it reports being outside an untiled
  placement, so the triangle keeps the object's own colour and the bake needs
  no new concept. The preview follows: upload_color_texture() box-filters
  coverage into the alpha channel it used to fill with 255, and the shader
  leaves the surface alone where it is below half.

The corners rather than an eyedropper: a background that does not reach all
four of them is not a background, and a picker would be a second interaction
for the case this exists to make one click. The median of the four is taken
so one stray corner cannot decide it.

Measured on Tartan, a cube face, four filaments:

  run                    out tris  coloured  max offset mm  filament shares
  image, no correction      22534     14544       0.000005  1:91% 3:8% 4:1%
  image, sharpen 1.0        24780     16783       0.000004  1:84% 3:12% 4:3%
  image, two colors         14798      6837       0.000005  2:22% 4:78%
  image, bg removed         14120      2620       0.000005  1:29% 3:16% 4:55%

Background removal cuts the painted area from 14544 triangles to 2620, which
is the whole point of it; the threshold collapses to two filaments; sharpen
shifts the shares and adds boundary triangles. None of them moves the
surface. The probe's default scene is now Tartan rather than Colour Bricks,
which has too little luma range for the threshold to show anything.
2026-10-12 12:37:57 +02:00
ExPikaPaka 533aaaed28 feat: add Hue to the Image tool's colour correction
Turns every colour of the picture around the colour wheel without changing
how light it is. This matters more here than in a photo editor: the filament
set is fixed and arbitrary, so hue is what lets the picture meet the palette
rather than the other way round. With orange loaded but no red, a small turn
puts the reds onto the orange instead of onto whatever happens to be nearest.

Implemented as Rodrigues' rotation of the colour about the grey axis, then
the Rec. 709 luma is restored exactly: the rotation preserves R+G+B, not the
weighted luma, and without the correction turning the wheel would also change
which areas read as light and dark.

Measured, same scene and harness as the other corrections:

  run                      out tris   coloured  max offset mm  filament shares
  image, no correction        12066       4052       0.000005  1:71% 2:25% 3:4%
  image, hue +60               8208        268       0.000005  2:100%
  image, hue -120              8208        268       0.000005  3:100%

The reddish brick moves onto a different filament in each direction and the
surface does not move.
2026-10-12 12:22:30 +02:00
ExPikaPaka 4dc87e876e feat: show a drop zone while a file is dragged over the view
Dropping a picture already worked, but a drag had no feedback at all: the
only way to find out whether letting go would do anything was to let go.

While a drag is over the 3D view and the Image tool is open, the canvas now
dims and shows a dashed teal border with "Drop a picture to put it on the
model" in the middle. It goes away on leave and on drop.

Three things worth knowing about how it is wired:

- wxWidgets cannot hand us the file names before the drop on GTK, so the
  zone says nothing about what is actually being dragged. It is worded as an
  invitation rather than a promise, and anything that is not a picture still
  falls through to the model loader exactly as before.

- A drag is not a mouse move as far as the canvas is concerned, so nothing
  would repaint and the zone would appear only once something else happened
  to trigger a frame. set_file_drag_over() marks the canvas dirty and asks
  for an extra frame.

- OnEnter and OnLeave are declared virtual without override, matching the
  class's existing OnDropFiles. Marking only the new ones trips
  -Winconsistent-missing-override on that pre-existing line, which is an
  error here.

The zone is drawn on the foreground draw list from inside the panel's ImGui
frame, so it covers the panel as well as the view.
2026-10-12 12:05:22 +02:00
ExPikaPaka 8bb2a1eec5 feat: match the icon weight, drop a picture onto the view, handle on by default
- The toolbar icon's stroke is 0.4 at its 16 px canvas, which renders at
  1.00 px on the 40 px sprite. Measured rather than judged: every icon on the
  gizmo bar was rasterized at 10x and the median thin run length taken, and
  1.00 px is what thirteen of the seventeen use. The previous 0.75 came out
  at 1.90, the heaviest on the bar.

- Dropping a picture on the 3D view loads it, when the Image tool is the one
  open. It is imported into the user's library on the way, as the panel's
  Import tile does, so it is there next time. With the tool closed a dropped
  PNG goes on doing whatever it did before. This mirrors the SVG drop that
  already fed the text tool, and sits next to it.

- The placement handle comes up by itself the first moment there is something
  to anchor it to, so a picture can be nudged straight after the click that
  placed it. Armed once, so turning it off stays off.

Two things had to change for that last one to be usable rather than annoying:

- A click that misses the handle now falls through to placing the picture.
  on_mouse() used to return false there and swallow it, which is right for
  the displacement tool, where the user turned the mode on deliberately, and
  wrong here, where it is on from the start and would have disabled the
  tool's one gesture.

- update_model_object() re-anchors the handle after a stroke that moved the
  paint. Previously the anchor was only refreshed on a layer switch or
  reorder, so clicking a different face left the handle behind on the old
  one.
2026-10-12 11:48:33 +02:00
ExPikaPaka 518f961640 feat: empty start, user images only, untiled preview, dockable Image panel
Five fixes to the Image tool, from using it:

- The layer now starts with no picture on it, so the panel opens on its empty
  frame with a plus in it. It used to seed the first shipped colour texture,
  which put somebody else's picture on screen before the user had chosen one.
  The frame is the only state the panel has until a picture is loaded, and
  clicking it is what creates the layer.

- Its picker offers only the user's own images. The shipped library is
  grayscale height maps, which is what the displacement tool wants and the
  opposite of what an image bake can use: it prints colour, and a height map
  has none. The Built-in section is left out rather than shown full of things
  that would all warn when picked, and the import hints now talk about
  pictures instead of height maps.

- The preview stopped tiling a layer that is not tiled. The shader had no
  tile_enabled uniform and wrapped the image unconditionally, so an untiled
  picture previewed as a repeating pattern the bake would never produce.
  in_tile() now draws the same line DecodedHeightTexture::sample() does, and
  gates the colour and all three relief paths on it. Both the 140 and the 110
  variant; glslangValidator passes on each.

- The panel docks against the right edge of the canvas, where the
  displacement panel is, with the same undock toggle in its title row, so the
  two tools do not put their controls in different corners.

- The toolbar icon's frame is square and its stroke thinner. At 16 px scaled
  to the toolbar a 1 px stroke came out at 2.5 px, heavier than every
  neighbour; 0.75 px matches them.
2026-10-12 11:31:33 +02:00
ExPikaPaka 680a597567 feat: show the picture whole in the Image panel, add tile, move and detail
Five changes to the Image tool, all in its own window bar the presets:

- The picture is shown whole, the full width of the window, instead of a row
  sized thumbnail beside a file name: it is the thing being placed, so that
  was the wrong size for it. The box shows the corrected colour texture, so
  moving a correction slider is visible in the panel as well as on the model;
  a grayscale picture has no colour texture and falls back to the height
  thumbnail. The file name stays underneath as a caption.

- Before anything is loaded the same box is an empty frame with a plus in it,
  in the same place and the same size, rather than a button of its own.
  Clicking either state opens the library, which is also where Import lives.

- Tile, off by default. A photo or a logo goes on once, so a new layer the
  Image tool creates starts with a single copy and Size sets how big that
  copy is. It is a default and not a pin, so the checkbox can turn it on.

- Move, the on-canvas placement handle the displacement tool has: drag the
  handle on the surface to slide the picture, or one of its arrows to slide
  it along one axis.

- Detail, the bake resolution, with the budget pinned to a million triangles.
  Each triangle prints in one filament, so this is how sharp an edge between
  two colours can come out, and it is the only thing left that decides it.
  The auto budget is 750 k, chosen for relief where triangles buy shape;
  here they buy the whole output, so it is worth spending more. The slider is
  seeded with the resolution Auto would have picked for the model, and warns
  when what it asks for no longer fits the budget.

Also fixes a short circuit in the panel: apply_standard_mode_presets(mv) ||
apply_image_mode_presets(mv) skipped the image presets on any frame the
standard ones changed something.

Measured with the texture-bake harness on the tool's shipped configuration
(tiling off, million-triangle budget, the seeded resolution), one cube face,
four filaments:

  run                      out tris   coloured  max offset mm  filament shares
  relief, depth 0.4 mm        41040      33902       0.216000  1:91% 2:6% 3:3%
  image, no correction        12066       4052       0.000005  1:71% 2:25% 3:4%
  image, brightness +0.5       8208        268       0.000005  4:100%
  image, contrast +0.8        11980       3910       0.000005  1:78% 2:20% 3:1%
  image, saturation 0          8208        268       0.000005  3:100%
  image, gamma 2.2            13176       5175       0.000004  1:67% 4:33%
  image, negative              8208        268       0.000005  4:100%

Fewer coloured triangles than the previous run of the same scene because
tiling is now off: one copy covers part of the face rather than repeating
across it. The surface still does not move and every correction still changes
which filaments the picture prints in.
2026-10-12 11:12:57 +02:00
ExPikaPaka e003b61e17 feat: make the Image gizmo a minimal load, click, correct, apply tool
The first cut was the displacement panel with depth hidden, which left the
brushes, the eight layer slots, the UV editor, seams, tiling and the
mesh-preparation sections in a tool that needs none of them, and offered no
way to correct the picture at all. This replaces that panel and adds the
corrections.

The flow is now: load a picture, click the model to put it there, adjust it,
press Apply.

- The Image tool gets its own window, render_image_input_window(), defined in
  GLGizmoImage.cpp. on_render_input_window() dispatches to it on the first
  line, so the displacement panel goes back to exactly what it was rather
  than being threaded with tests for which tool is drawing.

- A click places the picture: the tool pins SMART_FILL with a pointer cursor,
  so one click floods the surface it lands on out to the first fold sharper
  than the Spread angle. No brush, no erase toggle.

- Projection keeps Flat, Around, Ball and From view. Unwrap is left out and a
  layer arriving on it falls back to Flat: seams, islands and the UV pane are
  an editor's worth of interface for a tool that wants a click and a slider.

- The preview is pinned to the fast one. With no relief to build it is both
  instant and exactly the final colour, since the shader's colour path does
  not depend on depth_mm.

- The window shows only what this case needs: the picture, Spread, the four
  projections, Size, Rotation, the corrections, Apply and Close.

Colour correction is new in libslic3r. TextureDisplacementLayer gains
brightness, contrast, saturation, gamma and color_invert, all defaulting to
the identity, and apply_color_adjustments() applies them to an image's RGB
only, never to the height: a brightness slider has no business moving
geometry. It runs at the single point every bake and preview job reads a
layer's colour from, prepare_sampleable_layers(), and at the two caches that
would otherwise miss a change the image_data pointer does not show: the fast
preview's GPU texture and the mix ranking.

Measured with the texture-bake harness, one cube face painted with a colour
image, four filaments:

  run                      out tris   coloured  max offset mm  filament shares
  relief, depth 0.4 mm        41040      33902       0.216000  1:91% 2:6% 3:3%
  image, no correction        24226      17090       0.000007  1:71% 2:25% 3:4%
  image, brightness +0.5       8204       1068       0.000004  4:100%
  image, contrast +0.8        22688      15552       0.000007  1:75% 2:24% 3:1%
  image, saturation 0          8204       1068       0.000004  3:100%
  image, gamma 2.2            24754      17618       0.000007  1:66% 4:34%
  image, negative              8204       1068       0.000004  4:100%

Max offset is the distance from every output vertex to the original surface,
not a vertex-array diff: the bake refines, so a new vertex only counts as
unmoved if it lies in the old surface. Every correction moves which filaments
the picture prints in, and none of them moves the surface.
2026-10-12 10:20:44 +02:00
ExPikaPaka a800e0c186 feat: add an Image gizmo for zero-displacement colour
A separate toolbar tool for the simple case of texture displacement: put a
colour picture on the model with no relief at all.

It is a thin wrapper, not a fork. GLGizmoImage subclasses
GLGizmoTextureDisplacement and overrides one new protected virtual,
image_mode(). Painting, the layer stack, the paint masks, the texture
library, the previews and the bake are the same code reached the same way;
a zero-depth bake refines the painted area and writes the per-triangle
filament indices exactly as a relief bake does, it just displaces by
nothing.

In the base gizmo, image_mode() does three things:

- apply_image_mode_presets() pins every layer to depth 0 and turns colour on
  wherever the image has any, alongside the existing Standard-mode presets.
- The panel leaves out Depth, Midlevel, Invert, Edge fade and Blend, and the
  Standard/Pro switch, which is what keeps the mesh-preparation sections
  hidden. Bake is disabled when no image carries colour, since that bake
  would refine the mesh and produce nothing.
- add_texture_layer() seeds a new layer from the first library texture that
  has colour, rather than the first one, because most of the shipped library
  is grayscale height maps.

The two tools share one layer stack, so opening the Image tool on a volume
whose layers carry relief flattens them. Only depth changes: the paint, the
image, the tiling, the mapping and any relief already baked into the mesh
are untouched.

The toolbar icon follows Orca's menu-icon style: 16 px, 1 px #949494 frame,
#009688 on the picture inside.

The shortcut is registered but unbound: every single letter the Plater
context can reach is already taken, and a default that shadows one of them
is worse than none. docs/HLSD/keyboard-shortcuts.md now documents that an
empty default chord is a supported choice.

Measured with a probe built against this tree in the texture-bake harness:
a depth-0 bake of a painted cube face leaves every output vertex within
7 nm of the original surface (tolerance 1 um) while colouring 17090 of
24226 output triangles across 3 filaments; the same scene at depth 0.4 mm
moves vertices up to 0.216 mm.
2026-10-12 08:29:10 +02:00
244 changed files with 20842 additions and 101756 deletions
-220
View File
@@ -1,220 +0,0 @@
---
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.
---
# OrcaSlicer translations
The UI strings live in gettext catalogs: `localization/i18n/OrcaSlicer.pot` is the template, and
`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.
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).
It lists empty entries with the glossary terms they contain and validates each translation. It writes
only the entries it changes, in the layout `msgmerge --no-wrap` produces, and adds the AI comments.
Run commands from the repository root, with `python3` (`python` or `py -3` on Windows):
```bash
T=.claude/skills/orca-translations/scripts/po_tool.py
python3 $T --help
```
Read [translation-rules.md](references/translation-rules.md) before translating. It holds the
mechanical rules, how to pick words, style, and when to flag an entry for review. To find hard-coded
English, strings that need a plural form or a context, or files missing from the extraction list, read
[source-audit.md](references/source-audit.md); that work changes C++ and comes before a translation pass.
## Workflow: fill every empty translation
Unless the user asks for something narrower, a translation pass means the steps below, in order.
### 1. Find the glossary
The tool looks for an `OrcaSlicer_WIKI` clone in `--wiki`, then `$ORCA_WIKI_DIR`, then next to this
repository.
- **A clone is found:** `git -C <wiki> fetch` and make sure it is on an up-to-date `main`. The tool
notes when it reads another branch, or a clone that is behind.
- **No clone:** the tool reads the published glossary read-only. That is enough to translate, but not
to add terms (see step 3).
### 2. Run the full gettext
This comes first, always. It regenerates the template from the sources and merges it into every
catalog:
```bash
./scripts/run_gettext.sh --full # Linux/macOS: needs gettext and python3 on PATH
scripts\run_gettext.bat --full # Windows (PowerShell: & .\scripts\run_gettext.bat --full)
```
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.
Then take stock: `python3 $T status`.
### 3. Settle new glossary terms before translating anything
Terms are decided once, for every language, so all the catalogs agree.
1. `python3 $T candidates` lists recurring phrases in the empty entries that the glossary lacks. Read it
together with the new msgids themselves.
2. Pick the real terms: feature and mode names, labels that tooltips repeat, and anything translators
would otherwise render in several ways.
3. Brand names and acronyms belong in the glossary page's hand-written *Kept in English* table instead.
4. Skip ordinary words.
5. For each term, choose a rendering per language: check `lookup` for existing usage, and follow each
language's conventions. Then record it:
```bash
python3 $T glossary-set --term "Belt printer" \
--description "One sentence saying what it is, and what it is not." \
--set de=... --set es=... --set pt_BR=...
```
The command adds or updates the row, keeps the TSV's BOM and line endings, and regenerates the page.
- **An established cell:** it refuses to change it without `--replace`. Changing an established term
also means fixing every catalog entry that uses it, so do that only on request.
- **An empty cell:** fill it the same way when a pending string establishes the term for that
language.
**No clone, and a new term is needed: stop.** Tell the user the glossary must be updated with these
terms, and list each one with its description and proposed renderings (`glossary-set` prints them too).
Ask them to clone `https://github.com/OrcaSlicer/OrcaSlicer_WIKI` next to this repository, or to give
its path. Translate nothing that uses those terms until they answer.
### 4. Translate, language by language, in batches
For each language:
1. Read its glossary column and notes once: `python3 $T glossary --lang <L>`.
2. Loop over the empty entries:
```bash
python3 $T pending --lang <L> --limit 60 --out <scratch>/<L>.json
# write <scratch>/<L>-tr.json: [{"id": "...", "msgstr": "..."}, ...], "msgstr_plural" for plurals,
# plus "review": "<what to check>" where unsure
python3 $T apply --lang <L> --input <scratch>/<L>-tr.json
```
- **Batch files go in a scratch directory, not the repository.**
- **Each entry's `id` identifies it,** so the translation file need not repeat the English. `apply`
also accepts `msgid` with `msgctxt`, or the pending file itself with its `msgstr` fields filled.
- **Translate every entry in the batch.** A blank `msgstr` is skipped, not cleared.
- **Next batch:** applied entries leave the list, so run `pending` again at offset 0. Use `--offset`
only to step past entries you deliberately leave blank.
- **What each entry carries:**
- `glossary`: the terms it contains, with the language's rendering.
- `note`: the developer's `TRN` comment.
- `flags`: `c-format` or `boost-format`.
- `description`: present when a sense has to be chosen.
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.
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.
**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.
- 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.
Add the terms they report yourself, then have the affected languages revisit the entries.
### 5. Verify
```bash
python3 $T check --lang <L> --warnings # every AI-translated entry, plus msgfmt --check-format
```
- **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
same change.
### 6. Report
Report:
- the entries filled, per language;
- the review notes added;
- 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
separate changes in separate repositories. The wiki change should land with, or before, the catalog
change. Commit or open PRs only when asked.
## Rules
1. **Run the full gettext first.** Translate against the regenerated template, never a stale one.
2. **The glossary is binding.** Use the language's rendering for each term, in the right sense. When a
rendering looks wrong, use it and flag the entry. Then raise the change with the user, rather than
deviating in one string.
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.
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).
7. **Write catalogs only through `po_tool.py` or gettext.** PO libraries such as polib reflow unrelated
entries, and hand edits skip the validation.
## Changing an established term
A glossary cell is usually copied from the catalog's own label. When the label is wrong, the glossary
inherits the mistake, so fix both in the same change:
1. **Check the catalog's usage first.** `lookup --lang <L> "<term>"` searches the English, and with
`--msgstr` it searches the translations.
- When most entries already use the correct form, move the cell to it.
- When the wrong form is used consistently throughout, leave both as they are and ask a
translator.
2. **Update the cell:** `glossary-set --term "<Term>" --replace --set <L>=<value>`.
3. **Rewrite the entries that still use the old form,** only where the term has that meaning.
- Write `[{"id": "<id from lookup>", "msgstr": "<full corrected text>"}]` and run
`apply --overwrite`.
- The rewritten entries are marked `# AI Translated`.
## Reviewing a translation change
Review it for these:
- glossary compliance (`check --scope all --warnings` on the language, then read the hits);
- placeholders and line breaks (`check` errors);
- `# AI Translated` kept on text a person rewrote, or added to text a person wrote;
- purged obsolete entries;
- reflowed unrelated entries;
- plural forms short of `nplurals`.
When a reviewer disputes a term, compare it with the glossary first. A machine translation that follows
the glossary is correct even if the term itself is debatable. Then the fix is a glossary change, made
with the translators, followed by the catalogs.
## Source of truth
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;
- `AGENTS.md` (Localization & translations) for the repository's conventions.
## Editing this skill
State rules and procedures, not the state of the catalogs: no counts, lists of untranslated strings or
per-language defects. Language-specific terminology belongs in the glossary's *Language specifics*
section, not here.
@@ -1,64 +0,0 @@
# Auditing the source for translatable text
Use this when asked to find hard-coded English, strings that need a context, or strings that need plural
forms. It changes C++ and the `.pot`, so it runs before a translation pass and is followed by one.
## How a string reaches translators
- `xgettext` reads only the files named in `localization/i18n/list.txt`, and only the macros
`L`, `_L`, `_u8L`, `L_CONTEXT`, `_L_CONTEXT`, `_u8L_CONTEXT` and `_L_PLURAL`.
- A file that marks strings but is missing from `list.txt` is silently never extracted. Find such
files by comparing `grep -l` for the macros with the list.
- `_()`, `_utf8()` and `wxGetTranslation()` do not extract. Calls that rely on them need an `L()`
or `_L()` somewhere xgettext sees.
- **GUI code:** `_L` gives a `wxString`, `_u8L` a UTF-8 `std::string` (use it for ImGui). `L` only
marks the string; the display site must translate it.
- **libslic3r:** the macro is whatever the file defines. Some files `#define L(s)
Slic3r::I18N::translate(s)`, so `L()` translates at runtime there. Others, such as `PrintConfig.cpp`,
define it as a no-op marker, and the GUI translates the text later. Read the top of the file before
judging a `format(L(...))` call. libslic3r has no plural or context lookup at runtime.
- The libslic3r translate callback is installed in `GUI_App::on_init_inner`. Text produced before it
is installed stays in English.
## What to look for
1. **Visible English with no macro:** labels, tooltips, menu items, dialog text, notifications and
ImGui text. `scripts/find_untranslated.py OUT_DIR` lists candidates; most are noise, so trace each
one to the place it is shown.
2. **Sentences built from translated pieces:** `_L("A") + name + _L(" is B")`, or a translated word
spliced into another sentence. Translators cannot reorder or inflect these. Replace each with one
msgid with placeholders. A spliced fragment with a leading or trailing space is the usual sign.
3. **Counts next to words that must agree:** `(s)`, "%d objects", a verb that follows a number. Use
`_L_PLURAL(singular, plural, n)`. If the singular and plural are identical on purpose, translators
still inflect each form.
4. **One English word with several meanings:** a short msgid used in files with different meanings
(a verb in one place, a noun in another, a mode name, a CAD term). Generate locations with
`xgettext` *without* `--no-location` and list short msgids that occur in two or more files.
5. **Code that compares translated text with English,** or decides behaviour from a message text.
Translation breaks it. Compare ids or flags instead.
6. **Tests that quote message text:** `grep` the tests for a message before rewording it.
## What not to translate
Keys, config values and identifiers; log and debug output; assertion and check messages; developer-only
UI behind debug switches; undo/redo snapshot names (the history is never shown); text returned to a
plugin's code; HTML, JS and desktop-file content in string literals; brand, printer-model and format
names.
## Adding a context
- Keep the most common sense without a context, so its existing translations stay valid. Give the
other senses a short, readable context.
- A context cannot be carried through code that translates generically: enum labels that
`Field.cpp` translates with `_()`, tables translated by a loop, and anything in libslic3r. Leave that
sense on the plain entry and give the contexts to the other uses.
## After the edits
1. Build and run the tests (`libslic3r_tests` in particular).
2. Run `run_gettext --full`. Reworded strings become new empty entries and the old ones become
obsolete, which keeps their translations as a memory. Strings that gain a plural form leave a fuzzy
entry.
3. Run the translation pass from SKILL.md. `po_tool.py pending` suggests the closest earlier translation
for each entry.
4. Fix English typos *before* the translation pass; fixing one afterwards orphans every translation.
@@ -1,102 +0,0 @@
# Translation rules
The rules a translation must follow, condensed from the wiki's
[Localization guide](https://github.com/OrcaSlicer/OrcaSlicer_WIKI/blob/main/developer_reference/localization_guide.md),
the [glossary](https://github.com/OrcaSlicer/OrcaSlicer_WIKI/blob/main/developer_reference/localization_glossary.md)
and the localization section of `AGENTS.md`. `po_tool.py apply` rejects the mechanical violations it
can detect; everything else is on the translator.
## Mechanical: enforced by `apply`
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.
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.
- **Leading and trailing spaces** are kept. A leading space usually means the string is appended to another.
- **HTML tags** are kept, and the text between them is translated: `Click <a>here</a> to install it.`
- **`℃`** (U+2103) stays one character, written exactly as in the source: `%d℃`, never `°C`, `° C` or
`%d ℃`.
- **Tokens stay verbatim:** `{placeholders}`, `[macros]`, G-code commands (`M141`, `G28`). Setting keys
in snake_case (`use_relative_e_distances`) are flagged as warnings, because a few snake_case msgids
are really labels (`top_front`). Keep a key unless the string uses it as a display name.
- **Plural entries** need every form from the catalog's `Plural-Forms` header (`nplurals`: 1 for
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.
## Mechanical: not detectable, still required
- Edit only `msgstr`. Never change `msgid`, `msgctxt`, the header or another entry's text.
- **Ending punctuation follows the source:** no added period, and no dropped one. `apply` warns.
- Units follow the SI convention of the language: `s`, not `sec`. A parameter description holds no
unit, because the field shows it.
- **A button or short label holds one translation:** no alternatives in parentheses. They widen the
control.
- Don't use `fuzzy` for uncertainty. Fuzzy entries are hidden, and users then see English.
## Choosing the words
- **The glossary is binding.** Use the language's rendering for every glossary term the `pending`
output lists, inflected as the sentence needs.
- **Rows that share a base term are different senses:** `Seam` (the print seam) versus `Seam (UV)`
(the unwrap cut), and `Instance` versus `Instance (application)`. Pick by the description.
- **A qualified row may be a false match.** `Feature (Design)` does not apply to "features of the
app".
- **A cell marked ⚠ (or holding two renderings) is unsettled.** Use the form the catalog already
uses for that sense (`lookup`), and flag the entry for review.
- **Kept in English:** brand and product names (OrcaSlicer, Bambu Lab, Orca Cloud, AMS, Micro-Lidar),
acronyms (FDM, LAN, HTTPS), file formats, material codes (PLA, PETG-CF), G-code, macros and variables
stay as written. In "Adaptive Pressure Advance", only "Pressure Advance" stays English. See the
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.
- **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.
- **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.
- **Don't expand.** A machine translation adds no facts the English doesn't state. Expanding
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.
## 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.
- 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.
Say exactly what to look at and where: *"Row name in the Design tab tool-offer menu; check it reads
right for the whole row."*
## Problems that belong in the source, not the translation
Report these; don't work around them in a catalog.
- **The English is wrong.** Never "fix" it in the translation only.
- **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
translation.
@@ -1,113 +0,0 @@
"""List C++ string literals that look like user-facing English but are not marked for translation.
Usage: find_untranslated.py OUT_DIR (one hits file per source area; each line is file:line: [call] "text" | code)
Works on whole files, so literals continuing a translation macro call from an earlier line are
recognised. Skips comments, log/assert/check calls, includes, printer model lists and markup."""
import re, sys
from pathlib import Path
REPO = Path(__file__).resolve().parents[4]
OUT = Path(sys.argv[1]); OUT.mkdir(parents=True, exist_ok=True)
MACROS = {"_L", "_u8L", "L", "_L_CONTEXT", "_u8L_CONTEXT", "L_CONTEXT", "_L_PLURAL", "_devL", "_omitL",
"_CHB", "_utf8", "_", "translate", "translate_utf8", "wxGetTranslation", "T"}
NOISE_CALLS = {"BOOST_LOG_TRIVIAL", "wxCHECK", "wxCHECK_MSG", "wxCHECK_RET", "wxASSERT", "wxASSERT_MSG", "wxFAIL_MSG",
"assert", "static_assert", "printf", "fprintf", "sprintf", "snprintf", "wxLogDebug", "wxLogTrace",
"wxLogMessage", "wxLogError", "wxLogWarning", "OutputDebugStringA", "OutputDebugStringW", "DEBUG_LOG",
"glsafe", "GLShaderProgram", "find", "count", "contains", "starts_with", "ends_with", "get_value",
"has", "opt_bool", "opt_int", "opt_float", "opt_string", "option", "get", "set_key_value", "at",
"boost_log", "LOGD", "LOGE", "LOGI", "LOGW", "SPDLOG", "CLI_LOG"}
LIT = re.compile(r'"((?:[^"\\\n]|\\.)*)"')
WORD = re.compile(r"[A-Za-z]{2,}")
def strip_comments(text):
# Replace comments with spaces, keeping offsets and string literals intact.
out, i, n = [], 0, len(text)
while i < n:
c = text[i]
if c == '"' or c == "'":
j = i + 1
while j < n and text[j] != c and text[j] != "\n":
j += 2 if text[j] == "\\" else 1
out.append(text[i:j + 1]); i = j + 1
elif text.startswith("//", i):
j = text.find("\n", i); j = n if j < 0 else j
out.append(" " * (j - i)); i = j
elif text.startswith("/*", i):
j = text.find("*/", i + 2); j = n if j < 0 else j + 2
out.append(re.sub(r"[^\n]", " ", text[i:j])); i = j
else:
out.append(c); i += 1
return "".join(out)
def enclosing_call(text, pos):
depth = 0
i = pos - 1
while i >= 0:
c = text[i]
if c == '"': # skip over a literal backwards
i -= 1
while i >= 0 and not (text[i] == '"' and text[i - 1] != "\\"):
i -= 1
elif c in ")]}":
depth += 1
elif c in "([{":
if depth == 0:
if c != "(":
return None
m = re.search(r"([A-Za-z_][\w:]*)\s*$", text[max(0, i - 80):i])
return m.group(1).split("::")[-1] if m else None
depth -= 1
elif c == ";" and depth == 0:
return None
i -= 1
return None
def looks_user_facing(s):
if len(WORD.findall(s)) < 2 and not re.fullmatch(r"[A-Z][a-z]{2,}[.!?:]?", s):
return False
if " " not in s and re.fullmatch(r"[\w./\\:#%-]+", s):
return False
if re.search(r"https?://|<\w+[^>]*>|\.(png|svg|json|ini|3mf|stl|gcode|bbl|js|html|css|txt|xml|zip)\b|=\s*\w+;|^\s*[-\w]+\s*:\s*[\w#]", s):
return False
if re.fullmatch(r"[a-z0-9_ ]+", s) and "_" in s:
return False
return bool(re.search(r"[A-Za-z]{2,} [a-z]{2,}|^[A-Z][a-z]{2,}", s))
groups = {}
for path in sorted((REPO / "src").rglob("*.[ch]pp")):
rel = path.relative_to(REPO).as_posix()
if "/dev-utils/" in rel or "/libvgcode/" in rel or rel.startswith("src/libnest2d") or "/tests/" in rel:
continue
raw = path.read_text(encoding="utf-8", errors="replace")
text = strip_comments(raw)
line_starts = [0] + [m.end() for m in re.finditer("\n", text)]
lines = raw.splitlines()
hits = []
for m in LIT.finditer(text):
s = m.group(1)
if not looks_user_facing(s):
continue
call = enclosing_call(text, m.start())
if call in MACROS or call in NOISE_CALLS:
continue
ln = next(k for k in range(len(line_starts) - 1, -1, -1) if line_starts[k] <= m.start()) + 1
src = lines[ln - 1].strip()
if re.search(r"BOOST_LOG|#\s*include|<<\s*\"|\"\s*<<|std::cerr|std::cout", src):
continue
# printer model / vendor tables
if len(LIT.findall(src)) >= 4 and not re.search(r"_L|_u8L", src):
continue
hits.append(f"{rel}:{ln}: [{call or '-'}] \"{s[:150]}\" | {src[:170]}")
if hits:
parts = rel.split("/")
if parts[1] == "slic3r":
key = f"GUI/{parts[3] if len(parts) > 4 else 'root'}" if parts[2] == "GUI" else f"slic3r/{parts[2]}"
else:
key = parts[1].replace(".cpp", "")
groups.setdefault(key, []).extend(hits)
total = 0
for key, hits in sorted(groups.items()):
(OUT / (key.replace("/", "_") + ".txt")).write_text("\n".join(hits) + "\n", encoding="utf-8")
total += len(hits)
print(f"{len(hits):5} {key}")
print("total", total)
@@ -1,870 +0,0 @@
#!/usr/bin/env python3
"""Translation helper for the OrcaSlicer gettext catalogs and the wiki glossary.
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)
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
candidates [--min-count N] [--limit N] recurring untranslated phrases not in the glossary
glossary-set --term T [--description D] --set L=VALUE ... [--replace]
The glossary is read from an OrcaSlicer_WIKI clone (--wiki, $ORCA_WIKI_DIR, or a
sibling of this repository). Without one it is downloaded read-only, and
glossary-set refuses to run.
"""
import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
import tempfile
import time
import unicodedata
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_MD = Path("developer_reference") / "localization_glossary.md"
MISSING = {"", "—"}
RAW_URL = "https://raw.githubusercontent.com/OrcaSlicer/OrcaSlicer_WIKI/main/"
AI_TAG = "AI Translated"
REVIEW_TAG = "Needs human review:"
# ---------------------------------------------------------------------------
# PO parsing and writing
_UNESCAPE = {"n": "\n", "t": "\t", "r": "\r", "a": "\a", "b": "\b", "f": "\f", "v": "\v", '"': '"', "\\": "\\"}
_ESCAPE = {v: "\\" + k for k, v in _UNESCAPE.items()}
def unescape(s):
return re.sub(r'\\(.)', lambda m: _UNESCAPE.get(m.group(1), m.group(0)), s)
def escape(s):
return "".join(_ESCAPE.get(c, c) for c in s)
def format_field(keyword, value, prefix=""):
"""Lines for `keyword "value"` as msgmerge --no-wrap writes them."""
parts = value.split("\n")
segments = [p + "\n" for p in parts[:-1]] + ([parts[-1]] if parts[-1] else [])
if len(segments) <= 1:
return [f'{prefix}{keyword} "{escape(value)}"']
return [f'{prefix}{keyword} ""'] + [f'{prefix}"{escape(s)}"' for s in segments]
class Entry:
"""One blank-line-delimited block of a PO file."""
def __init__(self, lines, first_line):
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.fields = {} # keyword -> [value, start, end)
self.order = []
current = None
for i, raw in enumerate(lines):
line = raw
if self.obsolete and line.startswith("#~"):
line = line[2:].lstrip(" ")
if line.startswith("|"):
current = None
continue
elif line.startswith("#"):
current = None
if line.startswith("#."):
self.xcomments.append(line[2:].strip())
elif line.startswith("#,"):
self.flags += [f.strip() for f in line[2:].split(",") if f.strip()]
elif line == "#" or line.startswith("# "):
self.tcomments.append(line[2:])
continue
m = re.match(r'^(msgctxt|msgid_plural|msgid|msgstr(?:\[\d+\])?)\s+"(.*)"\s*$', line)
if m:
current = m.group(1)
self.fields[current] = [unescape(m.group(2)), i, i + 1]
self.order.append(current)
elif line.startswith('"') and current:
self.fields[current][0] += unescape(line.strip()[1:-1])
self.fields[current][2] = i + 1
def get(self, key, default=None):
f = self.fields.get(key)
return f[0] if f else default
@property
def msgctxt(self):
return self.get("msgctxt")
@property
def msgid(self):
return self.get("msgid", "")
@property
def msgid_plural(self):
return self.get("msgid_plural")
@property
def is_header(self):
return self.msgid == "" and "msgid" in self.fields and not self.msgctxt
def msgstrs(self):
if self.msgid_plural is None:
return [self.get("msgstr", "")]
idx = sorted(int(k[7:-1]) for k in self.fields if k.startswith("msgstr["))
return [self.get(f"msgstr[{i}]", "") for i in range(max(idx) + 1)] if idx else []
@property
def fuzzy(self):
return "fuzzy" in self.flags
@property
def ai(self):
return any(c.strip() == AI_TAG for c in self.tcomments)
@property
def review(self):
return [c for c in self.tcomments if c.startswith(REVIEW_TAG)]
def key(self):
return (self.msgctxt, self.msgid)
def id(self):
"""Short stable handle, so a translation file need not repeat the English."""
return hashlib.sha1(f"{self.msgctxt or ''}\x04{self.msgid}".encode("utf-8")).hexdigest()[:10]
def rewrite(self, msgstrs, ai=True, review=None):
"""Replace the translation; add the AI and review comments; clear fuzzy."""
lines = list(self.lines)
# translations
keys = [k for k in self.order if k.startswith("msgstr")]
start = min(self.fields[k][1] for k in keys)
end = max(self.fields[k][2] for k in keys)
if self.msgid_plural is None:
new = format_field("msgstr", msgstrs[0])
else:
new = [l for i, s in enumerate(msgstrs) for l in format_field(f"msgstr[{i}]", s)]
lines[start:end] = new
# flags and previous-msgid lines of a fuzzy entry
out = []
for line in lines:
if line.startswith("#,"):
flags = [f.strip() for f in line[2:].split(",") if f.strip() and f.strip() != "fuzzy"]
if flags:
out.append("#, " + ", ".join(flags))
continue
if line.startswith("#|") and self.fuzzy:
continue
out.append(line)
lines = out
# translator comments go first, before #. #: #,
pos = 0
while pos < len(lines) and (lines[pos] == "#" or lines[pos].startswith("# ")):
pos += 1
add = []
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
while pos < len(lines) and (lines[pos] == "#" or lines[pos].startswith("# ")):
pos += 1
if ai and not any(l == "# " + AI_TAG for l in lines[:pos]):
add.append("# " + AI_TAG)
if review:
add.append(f"# {REVIEW_TAG} {' '.join(review.split())}")
lines[pos:pos] = add
return lines
class Catalog:
def __init__(self, path):
self.path = Path(path)
data = self.path.read_bytes()
self.bom = data.startswith(b"\xef\xbb\xbf")
text = data.decode("utf-8-sig")
self.newline = "\r\n" if "\r\n" in text else "\n"
self.trailing = text.endswith(("\n", "\r"))
self.lines = text.splitlines()
self.entries = []
block, first = [], 0
for i, line in enumerate(self.lines + [""]):
if line.strip() == "":
if block:
self.entries.append(Entry(block, first))
block = []
else:
if not block:
first = i
block.append(line)
self.header = next((e for e in self.entries if e.is_header), None)
m = re.search(r"nplurals\s*=\s*(\d+)", self.header.msgstrs()[0] if self.header else "")
self.nplurals = int(m.group(1)) if m else 2
self.changes = {} # entry index -> new lines
def active(self):
return [e for e in self.entries if not e.obsolete and not e.is_header]
def index(self):
return {e.key(): i for i, e in enumerate(self.entries) if not e.obsolete and not e.is_header}
def save(self):
lines = list(self.lines)
for i in sorted(self.changes, reverse=True):
e = self.entries[i]
lines[e.first_line:e.first_line + len(e.lines)] = self.changes[i]
text = self.newline.join(lines) + (self.newline if self.trailing else "")
self.path.write_bytes((b"\xef\xbb\xbf" if self.bom else b"") + text.encode("utf-8"))
def needs_translation(e, nplurals, include_fuzzy=False):
strs = e.msgstrs()
if e.msgid_plural is not None and len(strs) < nplurals:
return True
return any(s == "" for s in strs) or (include_fuzzy and e.fuzzy)
def catalog_path(lang):
p = I18N / lang / f"OrcaSlicer_{lang}.po"
if not p.exists():
sys.exit(f"no catalog for '{lang}': {p}")
return p
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)
# ---------------------------------------------------------------------------
# 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():
return Path(cand)
return None
def _download(rel):
cache = Path(tempfile.gettempdir()) / ("orca_glossary_" + rel.name)
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())
return cache
class Glossary:
def __init__(self, wiki_arg=None, quiet=False):
self.wiki = find_wiki(wiki_arg)
if self.wiki:
self.tsv, self.md = self.wiki / GLOSSARY_TSV, 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.load()
def report_clone_state(self):
git = lambda *args: subprocess.run(["git", "-C", str(self.wiki), *args], capture_output=True, text=True).stdout.strip()
try:
branch = git("rev-parse", "--abbrev-ref", "HEAD")
behind = git("rev-list", "--count", "HEAD..origin/main")
except OSError:
return
if branch and branch != "main":
print(f"note: glossary read from wiki branch '{branch}', not main", file=sys.stderr)
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 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:]]
self.matchers = []
for row in self.rows:
base = re.sub(r"\s*\([^)]*\)\s*$", "", row[0]).strip()
alts = [a.strip() for a in base.split(" / ") if a.strip()]
pats = [re.compile(r"(?<![\w-])" + r"[\s-]+".join(map(re.escape, a.split())) + r"(?:s|es)?(?![\w-])", re.I) for a in alts]
self.matchers.append((row, pats))
def column(self, lang):
return self.header.index(lang) if lang in self.header else None
def matches(self, text):
"""Glossary rows found in text, without terms only seen inside a longer match."""
spans = []
for row, pats in self.matchers:
for p in pats:
spans += [(m.start(), m.end(), row) for m in p.finditer(text)]
keep = []
for row in {id(r): r for _, _, r in spans}.values():
mine = [(s, e) for s, e, r in spans if r is row]
if any(not any(s2 <= s and e <= e2 and (e2 - s2) > (e - s) for s2, e2, r2 in spans if r2 is not row) for s, e in mine):
keep.append(row)
return keep
def hints(self, text, lang):
col = self.column(lang)
return [{"term": r[0], "translation": (r[col] if col is not None else "") or None, "description": r[1]} for r in self.matches(text)]
def language_notes(self, lang):
text = self.md.read_text(encoding="utf-8-sig")
m = re.search(r"^### [^\n]*\(" + re.escape(lang) + r"\)\s*$(.*?)(?=^##|\Z)", text, re.M | re.S)
return m.group(0).strip() if m else None
def _norm(s):
s = unicodedata.normalize("NFD", s.casefold())
return "".join(c for c in s if unicodedata.category(c) != "Mn")
def glossary_ok(msgstr, translation):
"""Loose check that a glossary rendering appears in msgstr, tolerating inflection."""
target = _norm(msgstr)
for alt in re.split(r"\s*/\s*", re.sub(r"\([^)]*\)|⚠", "", translation)):
words = [w for w in re.findall(r"\w+", _norm(alt)) if len(w) > 2] or re.findall(r"\w+", _norm(alt))
if not words:
return True
if all(w in target or (len(w) > 4 and w[:max(4, len(w) * 2 // 3)] in target) for w in words):
return True
return False
# ---------------------------------------------------------------------------
# Validation
C_FMT = re.compile(r"%(?:(\d+)\$)?[-+ #0']*(?:\d+|\*)?(?:\.(?:\d+|\*))?(?:hh|h|ll|l|L|q|j|z|Z|t)?[diouxXeEfFgGaAcspn]")
BOOST_FMT = re.compile(r"%\d+%")
TAG = re.compile(r"</?[A-Za-z][^<>]*>")
SNAKE = re.compile(r"[a-z][a-z0-9]*(?:_[a-z0-9]+)+")
IDENT = re.compile(r"\b[a-z][a-z0-9]*(?:_[a-z0-9]+)+\b|\b[GM]\d{1,4}\b|\{[A-Za-z_][\w.\[\]]*\}|\[[a-z_]+\]")
END = re.compile(r"[.:?!。:?!]$")
def _placeholders(s, flags):
s = s.replace("%%", "")
boost = BOOST_FMT.findall(s)
s2 = BOOST_FMT.sub("", s) if "boost-format" in flags or boost else s
c = [m.group(0) for m in C_FMT.finditer(s2)] if "no-c-format" not in flags else []
return boost, c
def validate(e, msgstrs, nplurals, glossary=None, lang=None):
"""Return (errors, warnings) for a proposed translation of entry e."""
errors, warnings = [], []
flags = set(e.flags)
if e.msgid_plural is not None and len(msgstrs) != nplurals:
errors.append(f"plural entry needs {nplurals} forms, got {len(msgstrs)}")
for i, s in enumerate(msgstrs):
src = e.msgid if (e.msgid_plural is None or (i == 0 and nplurals > 1)) else e.msgid_plural
tag = f"[{i}] " if e.msgid_plural is not None else ""
if not s:
errors.append(f"{tag}empty translation")
continue
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
bad = []
if sorted(b1) != sorted(b2):
bad.append(f"boost placeholders {b1} -> {b2}")
if c_bad:
bad.append(f"printf placeholders {c1} -> {c2}" + ("" if positional else " (order must match)"))
if bad:
strict = flags & {"c-format", "boost-format"} and not (e.msgid_plural is not None and i == 0 and nplurals > 1 and not c2 and not b2)
(errors if strict else warnings).extend(tag + b for b in bad)
if s.count("%%") != src.count("%%") and "c-format" in flags:
errors.append(f"{tag}'%%' count differs")
if src.count("\n") != s.count("\n"):
errors.append(f"{tag}line breaks: {src.count(chr(10))} in source, {s.count(chr(10))} in translation")
else:
lead = lambda t: len(t) - len(t.lstrip("\n"))
trail = lambda t: len(t) - len(t.rstrip("\n"))
if lead(src) != lead(s) or trail(src) != trail(s):
errors.append(f"{tag}leading/trailing line breaks differ")
ls = lambda t: re.match(r"[ \t]*", t.strip("\n")).group(0)
ts = lambda t: re.search(r"[ \t]*$", t.strip("\n")).group(0)
if ls(src) != ls(s) or ts(src) != ts(s):
errors.append(f"{tag}leading/trailing spaces differ")
if sorted(TAG.findall(src)) != sorted(TAG.findall(s)):
errors.append(f"{tag}HTML tags {TAG.findall(src)} -> {TAG.findall(s)}")
if src.count("℃") != s.count("℃"):
errors.append(f"{tag}'℃' count differs (keep U+2103, not °C)")
missing = [t for t in set(IDENT.findall(src)) if t not in s]
tokens = [t for t in missing if not SNAKE.fullmatch(t)]
if tokens:
errors.append(f"{tag}tokens must stay verbatim: {tokens}")
if len(tokens) < len(missing): # snake_case is usually a setting key, sometimes a label
warnings.append(f"{tag}snake_case kept? {[t for t in missing if SNAKE.fullmatch(t)]}")
e1, e2 = END.search(src.rstrip()), END.search(s.rstrip())
if bool(e1) != bool(e2) and lang != "th": # Thai has no sentence-final period
warnings.append(f"{tag}ending punctuation: source {'ends with ' + repr(e1.group(0)) if e1 else 'has none'}, translation {'ends with ' + repr(e2.group(0)) if e2 else 'has none'}")
if s == src and len(src.split()) >= 3:
warnings.append(f"{tag}identical to the English")
if glossary and lang:
# Rows sharing a base term ("Seam", "Seam (UV)") are competing senses; one is enough.
# A match on qualified rows only ("Feature (Design)") may be another sense entirely.
for base, senses in group_senses(glossary.hints(src, lang)).items():
if all(h["term"] != base for h in senses) or not strong_match(src, base):
continue
if not any(glossary_ok(s, h["translation"]) for h in senses):
wanted = " or ".join(f"'{h['translation']}' ({h['term']})" for h in senses)
warnings.append(f"{tag}glossary: expected {wanted}")
return errors, warnings
def strong_match(src, base):
"""Whether a term is surely meant as the glossary term, not as everyday English
("each part of a frame"): a multi-word term, a short label, or capitalised mid-sentence."""
if any(" " in alt for alt in base.split(" / ")) or len(src.split()) <= 5:
return True
for alt in base.split(" / "):
for m in re.finditer(r"(?<![\w-])" + re.escape(alt) + r"(?:s|es)?(?![\w-])", src, re.I):
if m.group(0)[0].isupper() and not re.search(r"(^|[.!?:]\s+|\n)$", src[:m.start()]):
return True
return False
def base_term(term):
return re.sub(r"\s*\([^)]*\)\s*$", "", term).strip()
def group_senses(hints):
groups = {}
for h in hints:
if h["translation"]:
groups.setdefault(base_term(h["term"]), []).append(h)
return groups
# ---------------------------------------------------------------------------
# Commands
def out_json(obj, path):
text = json.dumps(obj, ensure_ascii=False, indent=1)
if path:
Path(path).write_text(text + "\n", encoding="utf-8")
print(f"wrote {path}")
else:
sys.stdout.write(text + "\n")
def cmd_status(a):
print(f"{'lang':7} {'active':>7} {'empty':>6} {'plural':>6} {'fuzzy':>6} {'AI':>6} {'review':>6}")
for lang in a.lang or all_langs():
c = Catalog(catalog_path(lang))
act = c.active()
empty = sum(1 for e in act if needs_translation(e, c.nplurals) and e.msgid_plural is None)
plural = sum(1 for e in act if needs_translation(e, c.nplurals) and e.msgid_plural is not None)
print(f"{lang:7} {len(act):7} {empty:6} {plural:6} {sum(e.fuzzy for e in act):6} {sum(e.ai for e in act):6} {sum(bool(e.review) for e in act):6}")
def similar_entries(c, e, pool, cutoff=0.72):
"""The closest earlier translation of a similar English text: obsolete entries and translated
active ones. A reworded or split string usually still has one, and reusing it keeps the wording."""
import difflib
sm = difflib.SequenceMatcher(autojunk=False)
sm.set_seq2(e.msgid)
best = []
for other, msgstr, obsolete 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.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]]
def cmd_pending(a):
c = Catalog(catalog_path(a.lang))
g = Glossary(a.wiki)
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]
items = []
for e in batch:
item = {"id": e.id(), "msgctxt": e.msgctxt, "msgid": e.msgid}
if e.msgid_plural is not None:
item["msgid_plural"] = e.msgid_plural
item["msgstr_plural"] = (e.msgstrs() + [""] * c.nplurals)[:c.nplurals]
else:
item["msgstr"] = e.msgstrs()[0]
if e.xcomments:
item["note"] = " ".join(e.xcomments)
flags = [f for f in e.flags if f != "fuzzy"]
if flags:
item["flags"] = flags
if e.fuzzy:
item["fuzzy"] = True
if e.msgstrs()[0]:
item["previous_translation"] = e.msgstrs()[0]
if len(e.msgid) > 8:
sim = similar_entries(c, e, pool)
if sim:
item["similar"] = sim
hints = g.hints(e.msgid + "\n" + (e.msgid_plural or ""), a.lang)
if hints:
# Descriptions only where the sense must be chosen or no rendering exists yet.
bases = [base_term(h["term"]) for h in hints]
item["glossary"] = [{k: v for k, v in h.items() if k != "description" or not h["translation"] or bases.count(b) > 1 or b != h["term"]}
for h, b in zip(hints, bases)]
items.append({k: v for k, v in item.items() if v is not None})
out_json({"lang": a.lang, "nplurals": c.nplurals, "plural_forms": re.search(r"Plural-Forms: ([^\n]*)", c.header.msgstrs()[0]).group(1) if c.header else None,
"total_pending": len(todo), "offset": a.offset, "count": len(items), "entries": items}, a.out)
def cmd_apply(a):
c = Catalog(catalog_path(a.lang))
g = None if a.no_glossary else Glossary(a.wiki, quiet=True)
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()}
applied, skipped, rejected, warned = 0, 0, [], []
for it in items:
if "msgid" in it:
key = (it.get("msgctxt"), it["msgid"])
i = idx.get(key)
label = (f"[{key[0]}] " if key[0] else "") + key[1][:70].replace("\n", "\\n")
else:
i = by_id.get(it.get("id"))
label = f"id {it.get('id')}" if i is None else c.entries[i].msgid[:70].replace("\n", "\\n")
if i is None:
rejected.append((label, ["no such entry in the catalog (give its id, or msgid and msgctxt)"]))
continue
e = c.entries[i]
if e.msgid_plural is not None and "msgstr_plural" not in it:
rejected.append((label, [f"plural entry: give msgstr_plural with {c.nplurals} forms"]))
continue
strs = it["msgstr_plural"] if e.msgid_plural is not None else [it.get("msgstr", "")]
if not strs or all(not s for s in strs):
skipped += 1
continue
if not a.overwrite and not needs_translation(e, c.nplurals, include_fuzzy=True):
rejected.append((label, ["already translated (pass --overwrite to replace)"]))
continue
errors, warnings = validate(e, strs, c.nplurals, g, a.lang)
if errors:
rejected.append((label, errors))
continue
if warnings:
warned.append((label, warnings))
c.changes[i] = e.rewrite(strs, ai=not a.human, review=it.get("review"))
applied += 1
if not a.dry_run and c.changes:
c.save()
for label, msgs in rejected:
print(f"REJECTED {label}\n " + "\n ".join(msgs))
for label, msgs in warned:
print(f"WARNING {label}\n " + "\n ".join(msgs))
print(f"{'would apply' if a.dry_run else 'applied'} {applied}, rejected {len(rejected)}, warnings {len(warned)}, blank skipped {skipped}")
return 1 if rejected else 0
def find_msgfmt():
exe = REPO / "tools" / "msgfmt.exe"
if os.name == "nt" and exe.exists():
return str(exe)
from shutil import which
return which("msgfmt")
def cmd_check(a):
g = None if a.no_glossary else Glossary(a.wiki, quiet=True)
msgfmt = find_msgfmt()
status = 0
for lang in a.lang or all_langs():
c = Catalog(catalog_path(lang))
errs = warns = 0
for e in c.active():
if a.scope == "ai" and not e.ai:
continue
strs = e.msgstrs()
if all(s == "" for s in strs) or e.fuzzy:
continue
errors, warnings = validate(e, strs, c.nplurals, g, lang)
if errors or (warnings and a.warnings):
label = (f"[{e.msgctxt}] " if e.msgctxt else "") + e.msgid[:70].replace("\n", "\\n")
print(f"{lang} line {e.first_line + 1}: {label}")
for m in errors:
print(f" ERROR {m}")
for m in warnings if a.warnings else []:
print(f" warn {m}")
errs += bool(errors)
warns += bool(warnings)
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)
os.unlink(mo)
if r.returncode:
print(f"{lang}: msgfmt --check-format failed\n{r.stderr.strip()}")
status = 1
print(f"{lang}: {errs} entries with errors, {warns} with warnings (scope: {a.scope})")
status |= bool(errs)
if not msgfmt:
print("note: msgfmt not found; skipped --check-format", file=sys.stderr)
return status
def cmd_lookup(a):
c = Catalog(catalog_path(a.lang))
rx = re.compile(a.pattern, re.I)
n = 0
for e in c.entries:
strs = [s for s in e.msgstrs() if s]
if e.is_header or not strs:
continue
texts = strs if a.msgstr else [e.msgid, e.msgid_plural or ""]
if not any(rx.search(t) for t in texts):
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)}")
n += 1
if n >= a.limit:
print("... (limit reached)")
break
def cmd_glossary(a):
g = Glossary(a.wiki)
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}=...")
rx = re.compile(a.term, re.I) if a.term else None
for r in g.rows:
if rx and not rx.search(r[0]):
continue
val = r[col] if col is not None and r[col] else "—"
print(f"{r[0]} => {val}\n {r[1]}")
notes = g.language_notes(a.lang)
if notes and not a.term:
print("\n" + notes)
STOP = set("""a an and are as at be been but by can could do does for from has have how if in into is it its
may more most must no not of on once one only or other out over same set should so some such than that the
their them then there these this those to too two up use used uses using very was when where whether which
while will with without would you your yet all any each every per both also between before after first last
off new now get gets let lets just already instead still even back down here make makes made via""".split())
def _singular(key):
return " ".join(re.sub(r"(?<=[a-z]{3})(es|s)$", "", w) for w in key.split())
def kept_in_english(g):
"""Names from the glossary page's "Kept in English" table."""
text = g.md.read_text(encoding="utf-8-sig")
m = re.search(r"^## Kept in English.*?$(.*?)(?=^## )", text, re.M | re.S)
names = set()
for row in re.findall(r"^\| (.*?) \|", m.group(1) if m else "", re.M):
for piece in re.split(r"[,/:]|\bplus\b", row.replace("**", "").replace("`", "")):
if piece.strip():
names.add(_norm(piece.strip()))
return names
def cmd_candidates(a):
g = Glossary(a.wiki)
known = kept_in_english(g)
for row, _ in g.matchers:
known |= {_norm(x.strip()) for x in base_term(row[0]).split(" / ")}
known |= {_singular(k) for k in known}
known |= {w for k in known if " " in k for w in k.split()} # "tower" of "prime tower"
pending = {}
labels = set()
for lang in all_langs():
c = Catalog(catalog_path(lang))
for e in c.active():
labels.add(_norm(e.msgid))
if needs_translation(e, c.nplurals):
pending.setdefault(e.key(), set()).add(lang)
counts = {} # phrase -> [strings, max langs, display, example, capitalised mid-sentence]
for (ctx, msgid), langs in pending.items():
seen = set()
for chunk in re.split(r"[.,;:!?()\[\]\"\n—–]+|\s-\s", msgid):
words = [re.sub(r"'s$", "", w) for w in re.findall(r"[A-Za-z][A-Za-z0-9-]*(?:'s)?", chunk)]
# Capitals only mean a name inside an ordinary sentence, not in a Title Case label.
sentence = len(words) >= 4 and sum(w[0].isupper() for w in words) * 2 < len(words)
for n in (1, 2, 3):
for i in range(len(words) - n + 1):
gram = words[i:i + n]
if gram[0].lower() in STOP or gram[-1].lower() in STOP or len("".join(gram)) < 4 \
or any(w.lower() in STOP and w.lower() != "of" for w in gram):
continue
key = _norm(" ".join(gram))
if key in seen or key in known or _singular(key) in known:
continue
seen.add(key)
d = counts.setdefault(key, [0, 0, " ".join(gram), msgid, False])
d[0] += 1
d[1] = max(d[1], len(langs))
d[4] |= sentence and i > 0 and all(w[0].isupper() for w in gram)
# A term is a phrase, or a word capitalised mid-sentence or written as an acronym.
keep = {k: v for k, v in counts.items()
if v[0] >= a.min_count and (" " in k or v[4] or v[2].isupper())}
# Drop fragments only ever seen inside a longer candidate ("IQEX parallel" in "IDEX IQEX parallel").
keep = {k: v for k, v in keep.items()
if not any(k != k2 and re.search(r"(^| )" + re.escape(k) + r"( |$)", k2) and v2[0] >= v[0] for k2, v2 in keep.items())}
rows = sorted(keep.items(), key=lambda kv: (-kv[1][0], -len(kv[0].split())))
print("strings langs phrase [label = also a msgid of its own] e.g.")
for k, (cnt, langs, text, example, _) in rows[:a.limit]:
ex = example.replace("\n", " ")
print(f"{cnt:7} {langs:6} {text}{' [label]' if k in labels else ''} e.g. {ex[:70]}{'…' if len(ex) > 70 else ''}")
def cmd_glossary_set(a):
wiki = find_wiki(a.wiki)
if not wiki:
print("No OrcaSlicer_WIKI clone found (looked at --wiki, $ORCA_WIKI_DIR and next to this repository).\n"
"The glossary must be updated with these terms before the translations that use them ship:\n"
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")
for _ in range(100):
try:
fd = os.open(lock, os.O_CREAT | os.O_EXCL)
break
except FileExistsError:
time.sleep(0.1)
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]
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"))
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
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--wiki", help="path to an OrcaSlicer_WIKI clone")
p.add_argument("--i18n", help="catalog root to use instead of localization/i18n")
sub = p.add_subparsers(dest="cmd", required=True)
s = sub.add_parser("status")
s.add_argument("--lang", action="append")
s.set_defaults(func=cmd_status)
s = sub.add_parser("pending")
s.add_argument("--lang", required=True)
s.add_argument("--offset", type=int, default=0)
s.add_argument("--limit", type=int, default=60)
s.add_argument("--out")
s.add_argument("--include-fuzzy", action=argparse.BooleanOptionalAction, default=True,
help="list fuzzy entries too (default): users never see them")
s.set_defaults(func=cmd_pending)
s = sub.add_parser("apply")
s.add_argument("--lang", required=True)
s.add_argument("--input", required=True)
s.add_argument("--overwrite", action="store_true", help="also replace existing translations")
s.add_argument("--human", action="store_true", help="do not add '# AI Translated' (a person wrote these)")
s.add_argument("--dry-run", action="store_true")
s.add_argument("--no-glossary", action="store_true")
s.set_defaults(func=cmd_apply)
s = sub.add_parser("check")
s.add_argument("--lang", action="append")
s.add_argument("--scope", choices=["ai", "all"], default="ai")
s.add_argument("--warnings", action="store_true", help="also print warnings")
s.add_argument("--no-glossary", action="store_true")
s.set_defaults(func=cmd_check)
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.set_defaults(func=cmd_lookup)
s = sub.add_parser("glossary")
s.add_argument("--lang", required=True)
s.add_argument("term", nargs="?")
s.set_defaults(func=cmd_glossary)
s = sub.add_parser("candidates")
s.add_argument("--min-count", type=int, default=3)
s.add_argument("--limit", type=int, default=80)
s.set_defaults(func=cmd_candidates)
s = sub.add_parser("glossary-set")
s.add_argument("--term", required=True)
s.add_argument("--description")
s.add_argument("--set", action="append", default=[], metavar="LANG=VALUE")
s.add_argument("--replace", action="store_true")
s.set_defaults(func=cmd_glossary_set)
a = p.parse_args()
if a.i18n:
global I18N
I18N = Path(a.i18n)
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
sys.exit(a.func(a) or 0)
if __name__ == "__main__":
main()
@@ -570,11 +570,6 @@ Details [source] (`Widgets/PopupWindow.cpp`).
- On GTK the sub binds an idle handler. While both are shown and the cursor is over main but not over the
sub, it builds a `wxMouseEvent(wxEVT_MOTION)` from `wxGetMousePosition()`, calls `mainDropDown->mouseMove(ev)`
**directly** (nothing is posted), and calls `e.RequestMore()` to keep polling.
- On GTK the sub also receives the wheel events the user raises over main: GDK sends a `wl_pointer.axis` only
to the surface the pointer is over, and GTK then hands that `GDK_SCROLL` to the chain's grab widget, which is
the sub. The sub installs a `GtkWidget::event` handler that replays the event on main with
`gtk_propagate_event(main->GetConnectWidget(), event)` when the event's GDK window belongs to main
(`DropDown::messureSize`).
- **GTK wrapper sizing.** `messureSize` calls `gtk_window_resize` on `m_widget` after `SetSize`, because wxGTK's
`DoSetSize` only uses `gtk_widget_set_size_request` ("gtk_window_resize does not work for GTK_WINDOW_POPUP",
`src/gtk/popupwin.cpp:181-188`).
@@ -612,32 +607,6 @@ Details [source] (`Widgets/PopupWindow.cpp`).
```
Cite: c0ae2bda99, b9ff15054f (`DropDown::mouseMove`, `DropDown::messureSize`, `DropDown::ShouldDismissOnTopWindowDeactivate`,
`PopupWindow::ShouldDismissOnTopWindowDeactivate`).
- **Rule:** On GTK, route a chained popup's wheel event by the GDK window it names, not by the grab widget and not
by the global cursor position.
**Why:** While the sub holds the grab, `gtk_main_do_event` hands every `GDK_SCROLL` of the chain to the grab
widget (the sub) with its original, un-rebased coordinates [source] (`gtkmain.c:1789-1792`, 1923-1924), while
GDK Wayland sends the axis to the surface under the pointer only (`pointer_handle_axis` → `create_scroll_event`,
`gdkdevice-wayland.c:1929, 1527`). The sub therefore sees and consumes wheel events raised over main, so the
main list never scrolls, on X11 and Wayland alike. A hit test against `wxGetMousePosition()` cannot replace the
window test: global coordinates are unreliable on Wayland (`mouse-keyboard-focus.md`). `DropDown` connects a
`GtkWidget::event` handler on the sub's `GtkWindow` (its `m_widget`), which is emitted before wx's
`::scroll-event` handler on the same widget and suppresses it when it returns TRUE (`gtkwidget.c:7696`), then
delivers the event with `gtk_propagate_event(main->GetConnectWidget(), event)`. Returning TRUE there also stops
the parent-chain propagation.
```cpp
// Wrong: emitted on the popup's outer GtkWindow, where wx has no handlers at all
g_signal_emit_by_name(main->m_widget, "scroll-event", event, &handled);
// Right (wxGTK): replay GTK's own delivery on the widget wx listens to
gtk_propagate_event(main->GetConnectWidget(), event);
```
**Where wx listens [source].** `wxPopupWindow::Create` builds a popup from two widgets: `m_widget` is the outer
`GtkWindow` and `m_wxwindow` is a `wxPizza` child added to it. `wxWindowGTK::GetConnectWidget()` is
`m_wxwindow ? m_wxwindow : m_widget`, and `ConnectWidget()` — which binds `button_press_event`, `motion_notify_event`
and `scroll_event` — is called on that widget (`src/gtk/window.cpp` `Create`, `GetConnectWidget`). A signal emitted
on the outer `GtkWindow` therefore reaches no wx handler; only events GTK delivers to the inner widget, or to a
descendant of the grab widget, are seen by wx. `GTKGetConnectWindow()`/`GTKGetMainWindow()` are the matching
GdkWindows.
Cite: `DropDown::messureSize`, `DropDown::mouseWheelMoved`.
- **Rule:** When shrinking a dropdown to fit above the display bottom, give up if fewer than two rows would
remain.
**Why:** On Wayland the popup can land where almost no vertical space is left. Clamping to that sliver made an
+2 -29
View File
@@ -13,7 +13,6 @@ on:
# both it and its tests live in scripts/, so a PR touching only those must still run
# this workflow.
- 'resources/printers/**'
- 'resources/info/legacy_compatible_printers.json'
- 'scripts/**'
# orca_profile_tool.py reads the variant key sets from PrintConfig.cpp, and its
# tests the obsolete keys, so a PR changing either must be checked against the profiles.
@@ -60,21 +59,6 @@ jobs:
python3 ./scripts/orca_profile_tool.py check 2>&1 | tee ${{ runner.temp }}/profile_tool.log
exit ${PIPESTATUS[0]}
# The app migrates user filament presets made against 2.4.2 back to the printers their
# parent listed then, from resources/info/legacy_compatible_printers.json. A PR that
# renames a filament preset or narrows its compatible_printers changes what that map
# must say, so it has to regenerate it.
- name: Check the legacy compatible printers map
id: legacy_compat
continue-on-error: true
run: |
set -o pipefail
base="${{ runner.temp }}/v2.4.2"
git fetch --no-tags --depth=1 origin refs/tags/v2.4.2:refs/tags/v2.4.2
mkdir -p "$base"
git archive v2.4.2 resources/profiles | tar -x -C "$base"
python3 ./scripts/orca_profile_tool.py legacy-compat --base "$base/resources/profiles" --check 2>&1 | tee ${{ runner.temp }}/legacy_compat.log
# download
- name: Download
working-directory: ${{ github.workspace }}
@@ -233,7 +217,7 @@ jobs:
echo "${{ github.event.pull_request.number }}" > ${{ runner.temp }}/profile-check-results/pr_number.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') }}
if: ${{ always() && github.event_name == 'pull_request' && (steps.profile_tool.outcome == 'failure' || steps.validate_system.outcome == 'failure' || steps.validate_slice.outcome == 'failure' || steps.validate_filament_subtypes.outcome == 'failure' || steps.validate_custom.outcome == 'failure') }}
run: |
{
# Marker matched by check_profiles_comment.yml to delete prior comments.
@@ -250,17 +234,6 @@ jobs:
echo ""
fi
if [ "${{ steps.legacy_compat.outcome }}" = "failure" ]; then
echo "### Legacy Compatible Printers Map Out of Date"
echo ""
echo '```'
head -c 30000 ${{ runner.temp }}/legacy_compat.log || echo "No output captured"
echo '```'
echo ""
echo 'Regenerate it: `git archive v2.4.2 resources/profiles | tar -x -C /tmp/v2.4.2`, then `python3 scripts/orca_profile_tool.py legacy-compat --base /tmp/v2.4.2/resources/profiles`.'
echo ""
fi
if [ "${{ steps.validate_system.outcome }}" = "failure" ]; then
echo "### System Profile Validation Failed"
echo ""
@@ -310,7 +283,7 @@ jobs:
retention-days: 1
- name: Fail if any check failed
if: ${{ always() && (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') }}
if: ${{ always() && (steps.profile_tool.outcome == 'failure' || steps.validate_system.outcome == 'failure' || steps.validate_slice.outcome == 'failure' || steps.validate_filament_subtypes.outcome == 'failure' || steps.validate_custom.outcome == 'failure') }}
run: |
echo "One or more profile checks failed; see the step logs above."
echo 'Reproduce the whole run locally with scripts/check_profile.sh (scripts\check_profile.bat on Windows).'
-14
View File
@@ -67,7 +67,6 @@ ctest --test-dir ./tests/fff_print -C Release
- Keep code concise and clear. Manually simplify AI generated bloated codes before review.
- Include targeted tests or documented verification for behavior changes, especially in slicing logic, profiles, formats, and GUI defaults.
- For profile changes (`resources/profiles/<Vendor>/**`), check that `version` in the sibling `resources/profiles/<Vendor>.json` was bumped.
- For new or changed UI strings, check they follow [Writing translatable strings in the source](#writing-translatable-strings-in-the-source): no concatenated fragments, plural forms for counts, contexts for ambiguous words.
- For translation changes (`localization/i18n/**/*.po`), check that recurring terms match the [Localization glossary](https://github.com/OrcaSlicer/OrcaSlicer_WIKI/blob/main/developer_reference/localization_glossary.md) for that language.
## Localization & translations
@@ -75,19 +74,6 @@ ctest --test-dir ./tests/fff_print -C Release
Catalogs live in `localization/i18n/<lang>/OrcaSlicer_<lang>.po`; the template is `OrcaSlicer.pot`.
See the [Localization guide](https://github.com/OrcaSlicer/OrcaSlicer_WIKI/blob/main/developer_reference/localization_guide.md) for the human-facing version of these principles.
### Writing translatable strings in the source
Translators see one msgid at a time and cannot change the code around it, so each message must be complete in a single msgid. Use the wrapper that fits instead of assembling text from pieces:
- **One msgid per sentence, with placeholders.** Never build a message by concatenating translated fragments (`_L("A") + name + _L(" is B")`) or by splicing a translated word such as `_L("left")` into another sentence: the translator can't reorder or inflect the parts. Write `format(_L("%1% is too close to others"), name)`.
- **A count needs a plural form.** Don't write `file(s)` or leave a verb unchanged after a number. Use `_L_PLURAL("%1% object", "%1% objects", n)`. libslic3r has no plural lookup, so word the message so it doesn't depend on a count, or build it in the GUI.
- **An ambiguous word needs a context.** When a short string means different things in different places (verb or noun, a mode name, a CAD term), give each sense its own context with `_L_CONTEXT`/`_u8L_CONTEXT`/`L_CONTEXT`. Keep the most common sense without a context so its existing translations stay valid.
- **Mark every user-visible string** (`_L`/`_u8L`, or `L` where it is translated later) and list new source files in `localization/i18n/list.txt`: files that aren't listed are never extracted.
- Add a `// TRN` comment above a new string whose meaning or placeholders aren't obvious.
- Never choose behavior by comparing translated text; compare ids or flags.
See `.claude/skills/orca-translations/references/source-audit.md` for the full checklist.
### 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.
@@ -88,6 +88,18 @@ struct NfpPConfig {
*/
bool explore_holes = false;
/**
* @brief Keep the final pile on the bin.
*
* The final alignment centres the pile on the alignment target. A target
* near an edge (a belt printer starts its parts at the leading end of the
* belt) would push part of a pile that is larger than the room around that
* point off the bed; with this set the pile stops at the edge instead, and a
* pile that does not fit along an axis is centred on it. Off by default, so
* the alignment of every other printer is unchanged.
*/
bool clamp_to_bin = false;
/**
* @brief If true, use all CPUs available. Run on a single core otherwise.
*/
@@ -1113,22 +1125,22 @@ private:
auto d = cb - ci;
// Keep the pile on the bin. Centring it on a target near an edge (a belt
// printer starts its parts at the leading end of the belt) would push a pile
// larger than the room around that point off the bed, so it stops at the
// edge instead; a pile that does not fit along an axis is centred on it.
// The items' boxes carry their inflation, which is the margin left at the edge.
auto on_bin = [](Coord lo, Coord hi, Coord bin_lo, Coord bin_hi, Coord shift) {
if (hi - lo >= bin_hi - bin_lo)
return (bin_lo + bin_hi) / 2 - (lo + hi) / 2;
if (lo + shift < bin_lo)
shift = bin_lo - lo;
if (hi + shift > bin_hi)
shift = bin_hi - hi;
return shift;
};
setX(d, on_bin(getX(bb.minCorner()), getX(bb.maxCorner()), getX(bbin.minCorner()), getX(bbin.maxCorner()), getX(d)));
setY(d, on_bin(getY(bb.minCorner()), getY(bb.maxCorner()), getY(bbin.minCorner()), getY(bbin.maxCorner()), getY(d)));
// Keep the pile on the bin (see Config::clamp_to_bin). The items' boxes carry
// their inflation, which is the margin left at the edge.
if (config_.clamp_to_bin) {
auto on_bin = [](Coord lo, Coord hi, Coord bin_lo, Coord bin_hi, Coord shift) {
if (hi - lo >= bin_hi - bin_lo)
return (bin_lo + bin_hi) / 2 - (lo + hi) / 2;
if (lo + shift < bin_lo)
shift = bin_lo - lo;
if (hi + shift > bin_hi)
shift = bin_hi - hi;
return shift;
};
setX(d, on_bin(getX(bb.minCorner()), getX(bb.maxCorner()), getX(bbin.minCorner()), getX(bbin.maxCorner()), getX(d)));
setY(d, on_bin(getY(bb.minCorner()), getY(bb.maxCorner()), getY(bbin.minCorner()), getY(bbin.maxCorner()), getY(d)));
cb = ci + d;
}
// BBS make sure the item won't clash with excluded regions
// do we have wipe tower after arranging?
@@ -1157,7 +1169,9 @@ private:
return;
}
Item objs_convex_hull_item(objs_convex_hull);
Vertex ref_aligned = objs_convex_hull_item.referenceVertex() + d;
Vertex objs_convex_hull_ref = objs_convex_hull_item.referenceVertex();
Vertex diff = objs_convex_hull_ref - sl::boundingBox(objs_convex_hull).center();
Vertex ref_aligned = cb + diff; // reference point when pile center aligned with bed center
bool ref_aligned_is_ok = std::any_of(nfps.begin(), nfps.end(), [&ref_aligned](auto& nfp) {return sl::isInside(ref_aligned, nfp); });
if (!ref_aligned_is_ok) {
// ref_aligned is not good, then find a nearest point on nfp boundary
+3 -1
View File
@@ -124,7 +124,9 @@ Control on the Global page, and from the `?` key on the page of the view that re
the dialog should list it; the row's section heading is the `section_table` entry
above it, so a new section needs an entry there too. Pick a default that does not
collide inside its contexts; the `[Shortcuts]` tests check every default against the
others.
others. A default `KeyChord{}` leaves the action unbound: it is listed in the dialog
for the user to bind and matches nothing until they do, which is the honest answer
when every key its contexts can reach is already spoken for.
2. Handle it in the dispatcher of its context: `MainFrame::handle_global_shortcut`,
`GLCanvas3D::handle_shortcut`, `ObjectList::dispatch_shortcut`, or a gizmo's
`on_tool_shortcut`. A gizmo that opens on a key sets `m_shortcut` in its constructor.
+22 -38
View File
@@ -82,7 +82,9 @@ there.
strong point is placed, no later strong modifier and no weak modifier is
processed for that perimeter.
- **Weak:** every weak modifier applies. They are applied from the lowest
priority to the highest, so the highest one overwrites overlapping zones.
priority to the highest, so the highest one overwrites overlapping zones. A
Blocked modifier that fully contains a perimeter is the exception: it is
skipped there (see [Full containment](#full-containment)).
A strong modifier without a usable segment, even one whose fragments were all
discarded, passes the turn to the next one.
@@ -230,23 +232,20 @@ begin and end positions on the source contour.
### Full containment
A modifier that covers the whole perimeter has no boundaries on it. The policy
follows seam painting, where a whole perimeter can be painted in either color:
follows seam painting, where painting a whole perimeter green is a meaningful
choice and forbidding the seam all round is not:
- **Seam Enforced** types the whole perimeter, like a perimeter painted green all
round, with subdivision applied as described under [Weak modifiers](#weak-modifiers).
- **Seam Neutral** types the whole perimeter Neutral, like an unmarked perimeter,
clearing painting and lower zones.
- **Seam Blocked** types the whole perimeter Blocked, like a perimeter painted
red all round, overriding painting and lower zones. The seam cannot avoid such
a perimeter: the seam placer compares Blocked candidates with each other like
Neutral ones, so the seam is placed as on an unmarked perimeter. If the
perimeter stays Blocked after all weak zones, it is reported in the user
warning (see [Diagnostics and warnings](#diagnostics-and-warnings)), so the
user can check the modifier.
- **Seam Center, Left and Right** are skipped with the full-containment warning:
there is no intersection to place the point on.
- **Seam Blocked** is skipped for the perimeter, with the full-containment
warning. The seam cannot avoid the whole perimeter, so the modifier does not
override anything below it: lower zones and painting stay in effect.
- **Seam Center, Left and Right** are skipped with the same warning: there is no
intersection to place the point on.
Enforced, Neutral and Blocked take part in the usual priority order (see
Enforced and Neutral take part in the usual priority order (see
[Weak modifiers](#weak-modifiers)).
The perimeter is fully contained when the united intervals cover every source
@@ -312,9 +311,9 @@ into every perimeter that has a strong seam.
`collect_weak_modifier_segments()` extracts the segments of every weak modifier
before the polygon is modified, so all positions refer to the same contour. Each
segment becomes a zone with a type and two boundaries, kept in application
order, lowest priority first. Full containment of a weak modifier becomes a
whole-perimeter zone at its place in that order: it has no boundaries and takes
part in no insertion or helper step below. The boundaries
order, lowest priority first. Full containment of an Enforced or Neutral
modifier becomes a whole-perimeter zone at its place in that order: it has no
boundaries and takes part in no insertion or helper step below. The boundaries
carry their positions on the source contour; these remain as provenance after
insertion and are not indices into the modified polygon.
@@ -385,10 +384,9 @@ G-code export issues it as one non-critical warning with the ID
`SlicingPreciseSeamWarning`. It is a single line, "Precise Seam: <causes>. Seam
placement may differ from expected.", because the export warnings dialog shows
only the first line of each warning. Repeated warning events replace the
notification instead of appending to it. Except for the "covers an entire
perimeter" and "had no effect" causes, the causes name the modifier types
involved, as the menu names them, in menu order and each type once, for example
"(Seam Left, Seam Enforced)".
notification instead of appending to it. Except for the "had no effect" cause,
the causes name the modifier types involved, as the menu names them, in menu
order and each type once, for example "(Seam Left, Seam Enforced)".
The causes are:
- **failed to process some intersections (types):** at least one fragment was
@@ -397,18 +395,8 @@ The causes are:
a Seam Center, Left or Right modifier had more than one segment on a
perimeter (see [Strong modifiers](#strong-modifiers)).
- **a perimeter is fully inside a modifier, the modifier was not applied to it
(types):** a Seam Center, Left or Right modifier was skipped for a
(types):** a Seam Center, Left, Right or Blocked modifier was skipped for a
perimeter (see [Full containment](#full-containment)).
- **Seam Blocked modifier "<name>" of "<object>" covers an entire perimeter:**
a Seam Blocked modifier covered a whole perimeter (see
[Full containment](#full-containment)). Only perimeters whose candidates are
all Blocked after all weak zones contribute to this warning, and only through
the zone in effect there: `apply_weak_modifiers_to_perimeter()` checks the
final types and flags the modifier of the highest whole-perimeter zone when it
is Blocked. A lower whole zone is overwritten by it and is not reported. Only
the first flagged modifier in print and volume order is named, followed by
"(N in total)" when there are several. The type name reuses the menu's
translation.
- **modifier "<name>" of "<object>" had no effect on the seam (it might not reach
the centerline of the printed perimeter):** a modifier was evaluated on at
least one perimeter and never gave a segment, full containment or a discarded
@@ -432,8 +420,6 @@ The log records the following diagnostic markers:
- `[PreciseSeamNoEffect]` for every modifier of the "had no effect" cause, with
the object and modifier names. Unlike the user warning, the log lists all of
them.
- `[PreciseSeamFullyBlocked]` for every modifier of the "covers an entire
perimeter" cause, listed the same way.
Failures and recoveries are counted separately. The first 10 of each per
`init()` call are logged in detail, in parallel processing order; if a limit is
@@ -577,14 +563,12 @@ last modifier would.
priorities, weak boundaries that coincide or share an edge, enforced
subdivision, whole-perimeter weak zones with painting and priorities, weak
zones over painting's oversampled candidates, the warning type masks, usage
tracking for the "had no effect" and whole-perimeter Blocked warnings, volume
sorting of strong and weak groups, restoration of strong points after
alignment, raft layer indexing and structured slices. End-to-end tests slice
a real object with Precise Seam
tracking for the "had no effect" warning, volume sorting of strong and weak
groups, restoration of strong points after alignment, raft layer indexing and
structured slices. End-to-end tests slice a real object with Precise Seam
volumes and check the outer wall starts in the exported G-code: every strong
mode under several seam positions and with a raft, Enforced and Blocked zones,
a perimeter blocked all round under every seam position, a modifier with a
hole, and the user warning.
a modifier with a hole, and the user warning.
- [Seam placer tests](../../tests/fff_print/test_seam_placer.cpp) cover
enforced-patch selection independent of the contour start, fully painted
contours, duplicate removal, and `Print::apply()` synchronization through type
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
-28
View File
@@ -72,8 +72,6 @@ src/slic3r/GUI/Gizmos/GizmoObjectManipulation.cpp
src/slic3r/GUI/Gizmos/GLGizmoCut.cpp
src/slic3r/GUI/Gizmos/GLGizmoCut.hpp
src/slic3r/GUI/Gizmos/GLGizmoSimplify.cpp
src/slic3r/GUI/Gizmos/GLGizmoSimplify.hpp
src/slic3r/GUI/Gizmos/GLGizmoUtils.cpp
src/slic3r/GUI/Gizmos/GLGizmoSeam.cpp
src/slic3r/GUI/Gizmos/GLGizmoSeam.hpp
src/slic3r/GUI/Gizmos/GLGizmoEmboss.cpp
@@ -112,7 +110,6 @@ src/slic3r/GUI/Jobs/ArrangeJob.cpp
src/slic3r/GUI/Jobs/OrientJob.cpp
src/slic3r/GUI/Jobs/FillBedJob.cpp
src/slic3r/GUI/Jobs/RotoptimizeJob.cpp
src/slic3r/GUI/Jobs/RotoptimizeJob.hpp
src/slic3r/GUI/Jobs/BindJob.cpp
src/slic3r/GUI/Jobs/PrintJob.cpp
src/slic3r/GUI/Jobs/SendJob.cpp
@@ -141,7 +138,6 @@ src/slic3r/GUI/DeviceErrorDialog.cpp
src/slic3r/GUI/ExtraRenderers.cpp
src/slic3r/GUI/EditGCodeDialog.cpp
src/slic3r/GUI/Field.cpp
src/slic3r/GUI/Field.hpp
src/slic3r/GUI/GCodeViewer.cpp
src/slic3r/GUI/GLCanvas3D.cpp
src/slic3r/GUI/Calibration.cpp
@@ -169,7 +165,6 @@ src/slic3r/GUI/PrintOptionsDialog.cpp
src/slic3r/GUI/SafetyOptionsDialog.cpp
src/slic3r/GUI/ParamsPanel.cpp
src/slic3r/GUI/IMEXModesCtrl.cpp
src/slic3r/GUI/IMEXFilamentPickerPopover.cpp
src/slic3r/GUI/PartPlate.cpp
src/slic3r/GUI/Plater.cpp
src/slic3r/GUI/Preferences.cpp
@@ -217,14 +212,10 @@ src/libslic3r/GCode/SeamPlacer.cpp
src/libslic3r/ExtrusionEntity.cpp
src/libslic3r/Flow.cpp
src/libslic3r/Format/AMF.cpp
src/libslic3r/Format/3mf.cpp
src/libslic3r/Format/bbs_3mf.cpp
src/libslic3r/miniz_extension.cpp
src/libslic3r/IMEXHelpers.cpp
src/libslic3r/Preset.cpp
src/libslic3r/Print.cpp
src/libslic3r/BeltPurge.cpp
src/libslic3r/AppConfig.cpp
src/libslic3r/PrintBase.cpp
src/libslic3r/PrintConfig.cpp
src/libslic3r/Zipper.cpp
@@ -262,7 +253,6 @@ src/slic3r/Utils/MKS.cpp
src/slic3r/Utils/Moonraker.cpp
src/slic3r/Utils/OctoPrint.cpp
src/slic3r/Utils/Repetier.cpp
src/slic3r/Utils/ESP3D.cpp
src/slic3r/GUI/SendMultiMachinePage.cpp
src/slic3r/GUI/MultiMachinePage.cpp
src/slic3r/GUI/MultiMachineManagerPage.cpp
@@ -317,8 +307,6 @@ src/slic3r/GUI/AuxiliaryDataViewModel.cpp
src/slic3r/GUI/AuxiliaryDialog.cpp
src/slic3r/GUI/BBLStatusBarPrint.cpp
src/slic3r/GUI/BBLStatusBarSend.cpp
src/slic3r/GUI/BBLStatusBar.cpp
src/slic3r/GUI/BeltPurgeTower.cpp
src/slic3r/GUI/BaseTransparentDPIFrame.cpp
src/slic3r/GUI/CloneDialog.cpp
src/slic3r/GUI/ColorDecomposeDialog.cpp
@@ -359,27 +347,11 @@ src/slic3r/GUI/WebViewDialog.cpp
src/slic3r/GUI/Widgets/AMSItem.cpp
src/slic3r/GUI/Widgets/DialogButtons.cpp
src/slic3r/Utils/NetworkAgentFactory.cpp
src/slic3r/Utils/MoonrakerPrinterAgent.cpp
src/slic3r/Utils/BBLNetworkPlugin.cpp
src/slic3r/Utils/OrcaCloudServiceAgent.cpp
src/slic3r/plugin/PluginAuditManager.cpp
src/slic3r/plugin/PluginConfig.cpp
src/slic3r/plugin/PluginResolver.cpp
src/slic3r/plugin/CloudPluginService.cpp
src/slic3r/plugin/PluginFsUtils.cpp
src/slic3r/plugin/PluginHooks.cpp
src/slic3r/plugin/PluginLoader.cpp
src/slic3r/plugin/PluginManager.cpp
src/slic3r/plugin/PythonPluginBridge.cpp
src/libslic3r/CAD/SketchEngine.cpp
src/libslic3r/CAD/GeometryEngine.cpp
src/libslic3r/FilamentMixer.cpp
src/libslic3r/Config.cpp
src/libslic3r/Format/STEP.cpp
src/libslic3r/Format/svg.cpp
src/libslic3r/Extruder.cpp
src/libslic3r/MeshBoolean.cpp
src/libslic3r/utils.cpp
src/slic3r/GUI/CAD/DesignOffer.hpp
src/slic3r/GUI/CAD/DesignSketchTool.cpp
src/slic3r/GUI/EncodedFilament.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
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><g transform="rotate(-45 8 8)"><path d="M8 14.4 6.5 11.2 9.5 11.2 Z" style="fill:#009688"/><path d="M6.5 7.3 6.5 11.2 8 14.4 9.5 11.2 9.5 7.3" style="fill:none;stroke:#949494;stroke-width:0.4;stroke-linejoin:round;stroke-linecap:round"/><rect x="5.5" y="3.8" width="5" height="3.5" rx="0.9" style="fill:none;stroke:#949494;stroke-width:0.4;stroke-linejoin:round"/></g></svg>

After

Width:  |  Height:  |  Size: 458 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><circle cx="5.9" cy="6.3" r="1.25" style="fill:#009688"/><path d="M3.4 11.9 6.4 7.7 8.8 10.7 10.4 8.6 12.6 11.9 Z" style="fill:#009688"/><rect x="2.375" y="2.375" width="11.25" height="11.25" rx="1.25" style="fill:none;stroke:#949494;stroke-width:0.4;stroke-linecap:round;stroke-linejoin:round"/></svg>

After

Width:  |  Height:  |  Size: 386 B

@@ -1,795 +0,0 @@
{
"presets": {
"Anycubic Generic ABS": [
"Anycubic Kobra 3 0.4 nozzle"
],
"Anycubic Generic TPU": [
"Anycubic Kobra 3 0.4 nozzle"
],
"Bambu ABS @BBL P1P": [
"Bambu Lab P1P 0.6 nozzle"
],
"Bambu ABS @BBL X1C": [
"Bambu Lab P1S 0.4 nozzle",
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab X1 Carbon 0.6 nozzle"
],
"Bambu ASA @BBL X2D": [
"Bambu Lab X2D 0.8 nozzle"
],
"Bambu PA6-CF @BBL H2D": [
"Bambu Lab H2D 0.6 nozzle",
"Bambu Lab H2D 0.8 nozzle"
],
"Bambu PA6-CF @BBL H2DP": [
"Bambu Lab H2D Pro 0.6 nozzle",
"Bambu Lab H2D Pro 0.8 nozzle"
],
"Bambu PA6-CF @BBL H2S": [
"Bambu Lab H2S 0.6 nozzle",
"Bambu Lab H2S 0.8 nozzle"
],
"Bambu PA6-CF @BBL P2S": [
"Bambu Lab P2S 0.6 nozzle",
"Bambu Lab P2S 0.8 nozzle"
],
"Bambu PA6-CF @BBL X1C": [
"Bambu Lab P1P 0.6 nozzle",
"Bambu Lab P1P 0.8 nozzle",
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab P1S 0.8 nozzle",
"Bambu Lab X1 Carbon 0.6 nozzle",
"Bambu Lab X1 Carbon 0.8 nozzle"
],
"Bambu PA6-CF @BBL X2D": [
"Bambu Lab X2D 0.8 nozzle"
],
"Bambu PAHT-CF @BBL H2D": [
"Bambu Lab H2D 0.6 nozzle",
"Bambu Lab H2D 0.8 nozzle"
],
"Bambu PAHT-CF @BBL H2DP": [
"Bambu Lab H2D Pro 0.6 nozzle",
"Bambu Lab H2D Pro 0.8 nozzle"
],
"Bambu PAHT-CF @BBL H2S": [
"Bambu Lab H2S 0.6 nozzle",
"Bambu Lab H2S 0.8 nozzle"
],
"Bambu PAHT-CF @BBL P1P": [
"Bambu Lab P1P 0.6 nozzle",
"Bambu Lab P1P 0.8 nozzle"
],
"Bambu PAHT-CF @BBL P2S": [
"Bambu Lab P2S 0.6 nozzle",
"Bambu Lab P2S 0.8 nozzle"
],
"Bambu PAHT-CF @BBL X1C": [
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab P1S 0.8 nozzle",
"Bambu Lab X1 Carbon 0.6 nozzle",
"Bambu Lab X1 Carbon 0.8 nozzle"
],
"Bambu PAHT-CF @BBL X2D": [
"Bambu Lab X2D 0.8 nozzle"
],
"Bambu PC @BBL P1P": [
"Bambu Lab P1P 0.6 nozzle"
],
"Bambu PETG @0.2 nozzle": [
"Qidi Q1 Pro 0.2 nozzle"
],
"Bambu PETG Basic @BBL H2D 0.6 nozzle": [
"Bambu Lab H2D 0.8 nozzle"
],
"Bambu PETG Basic @BBL H2DP 0.6 nozzle": [
"Bambu Lab H2D Pro 0.8 nozzle"
],
"Bambu PETG Basic @BBL H2S": [
"Bambu Lab H2S 0.6 nozzle",
"Bambu Lab H2S 0.8 nozzle"
],
"Bambu PETG Basic @BBL P2S 0.6 nozzle": [
"Bambu Lab P2S 0.8 nozzle"
],
"Bambu PETG Basic @BBL X2D": [
"Bambu Lab X2D 0.8 nozzle"
],
"Bambu PETG HF @BBL P2S 0.6 nozzle": [
"Bambu Lab P2S 0.8 nozzle"
],
"Bambu PETG HF @BBL X1C": [
"Bambu Lab P1P 0.4 nozzle",
"Bambu Lab P1S 0.4 nozzle"
],
"Bambu PETG HF @BBL X1C 0.8 nozzle": [
"Bambu Lab X1 Carbon 0.6 nozzle"
],
"Bambu PETG HF @BBL X2D": [
"Bambu Lab X2D 0.8 nozzle"
],
"Bambu PETG Translucent @BBL H2D 0.6 nozzle": [
"Bambu Lab H2D 0.8 nozzle"
],
"Bambu PETG Translucent @BBL H2DP 0.6 nozzle": [
"Bambu Lab H2D Pro 0.8 nozzle"
],
"Bambu PETG Translucent @BBL H2S": [
"Bambu Lab H2S 0.6 nozzle",
"Bambu Lab H2S 0.8 nozzle"
],
"Bambu PETG Translucent @BBL P2S 0.6 nozzle": [
"Bambu Lab P2S 0.8 nozzle"
],
"Bambu PETG Translucent @BBL X1C 0.8 nozzle": [
"Bambu Lab P1P 0.6 nozzle",
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab X1 Carbon 0.6 nozzle"
],
"Bambu PETG-CF @BBL H2D 0.6 nozzle": [
"Bambu Lab H2D 0.8 nozzle"
],
"Bambu PETG-CF @BBL H2DP 0.6 nozzle": [
"Bambu Lab H2D Pro 0.8 nozzle"
],
"Bambu PETG-CF @BBL H2S": [
"Bambu Lab H2S 0.6 nozzle",
"Bambu Lab H2S 0.8 nozzle"
],
"Bambu PETG-CF @BBL P2S 0.6 nozzle": [
"Bambu Lab P2S 0.8 nozzle"
],
"Bambu PLA Basic @BBL P1P": [
"Bambu Lab P1P 0.6 nozzle"
],
"Bambu PLA Basic @BBL X1C": [
"Bambu Lab P1S 0.4 nozzle",
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab X1 Carbon 0.6 nozzle"
],
"Bambu PLA Basic @BBL X2D": [
"Bambu Lab X2D 0.8 nozzle"
],
"Bambu PLA Dynamic @BBL P1P": [
"Bambu Lab P1P 0.6 nozzle"
],
"Bambu PLA Dynamic @BBL X1C": [
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab X1 Carbon 0.6 nozzle"
],
"Bambu PLA Galaxy @BBL P1P": [
"Bambu Lab P1P 0.6 nozzle"
],
"Bambu PLA Galaxy @BBL X1C": [
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab X1 Carbon 0.6 nozzle"
],
"Bambu PLA Glow @BBL P1P": [
"Bambu Lab P1P 0.6 nozzle"
],
"Bambu PLA Glow @BBL X1C": [
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab X1 Carbon 0.6 nozzle"
],
"Bambu PLA Lite @BBL H2D": [
"Bambu Lab H2D 0.6 nozzle"
],
"Bambu PLA Lite @BBL H2S": [
"Bambu Lab H2S 0.6 nozzle",
"Bambu Lab H2S 0.8 nozzle"
],
"Bambu PLA Lite @BBL P1P": [
"Bambu Lab P1P 0.6 nozzle"
],
"Bambu PLA Lite @BBL X1C": [
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab X1 Carbon 0.6 nozzle"
],
"Bambu PLA Lite @BBL X2D": [
"Bambu Lab X2D 0.8 nozzle"
],
"Bambu PLA Marble @BBL P1P": [
"Bambu Lab P1P 0.6 nozzle",
"Bambu Lab P1P 0.8 nozzle"
],
"Bambu PLA Marble @BBL X1C": [
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab X1 Carbon 0.6 nozzle"
],
"Bambu PLA Matte @BBL P1P": [
"Bambu Lab P1P 0.6 nozzle"
],
"Bambu PLA Matte @BBL X1C": [
"Bambu Lab P1S 0.4 nozzle",
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab X1 Carbon 0.6 nozzle"
],
"Bambu PLA Matte @BBL X2D": [
"Bambu Lab X2D 0.8 nozzle"
],
"Bambu PLA Metal @BBL P1P": [
"Bambu Lab P1P 0.6 nozzle"
],
"Bambu PLA Metal @BBL X1C": [
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab X1 Carbon 0.6 nozzle"
],
"Bambu PLA Silk+ @BBL H2D": [
"Bambu Lab H2D 0.6 nozzle",
"Bambu Lab H2D 0.8 nozzle"
],
"Bambu PLA Silk+ @BBL H2DP": [
"Bambu Lab H2D Pro 0.6 nozzle",
"Bambu Lab H2D Pro 0.8 nozzle"
],
"Bambu PLA Silk+ @BBL H2S": [
"Bambu Lab H2S 0.6 nozzle",
"Bambu Lab H2S 0.8 nozzle"
],
"Bambu PLA Silk+ @BBL P1P": [
"Bambu Lab P1P 0.6 nozzle"
],
"Bambu PLA Silk+ @BBL X1C": [
"Bambu Lab P1S 0.4 nozzle",
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab X1 Carbon 0.6 nozzle"
],
"Bambu PLA Silk+ @BBL X2D": [
"Bambu Lab X2D 0.8 nozzle"
],
"Bambu PLA Sparkle @BBL P1P": [
"Bambu Lab P1P 0.6 nozzle"
],
"Bambu PLA Sparkle @BBL X1C": [
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab X1 Carbon 0.6 nozzle"
],
"Bambu PLA Tough+ @BBL P1P": [
"Bambu Lab P1P 0.6 nozzle"
],
"Bambu PLA Tough+ @BBL X1C": [
"Bambu Lab X1 Carbon 0.6 nozzle"
],
"Bambu PLA Tough+ @BBL X2D": [
"Bambu Lab X2D 0.8 nozzle"
],
"Bambu PLA Translucent @BBL H2D 0.8 nozzle": [
"Bambu Lab H2D 0.6 nozzle"
],
"Bambu PLA Translucent @BBL H2DP 0.8 nozzle": [
"Bambu Lab H2D Pro 0.6 nozzle"
],
"Bambu PLA Translucent @BBL H2S": [
"Bambu Lab H2S 0.6 nozzle",
"Bambu Lab H2S 0.8 nozzle"
],
"Bambu PLA Wood @BBL P1P": [
"Bambu Lab P1P 0.6 nozzle"
],
"Bambu PLA Wood @BBL X1C": [
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab X1 Carbon 0.6 nozzle"
],
"Bambu PLA-CF @BBL H2D 0.6 nozzle": [
"Bambu Lab H2D 0.8 nozzle"
],
"Bambu PLA-CF @BBL H2DP 0.6 nozzle": [
"Bambu Lab H2D Pro 0.8 nozzle"
],
"Bambu PLA-CF @BBL H2S": [
"Bambu Lab H2S 0.6 nozzle",
"Bambu Lab H2S 0.8 nozzle"
],
"Bambu PLA-CF @BBL P2S 0.6 nozzle": [
"Bambu Lab P2S 0.8 nozzle"
],
"Bambu PLA-CF @BBL X2D": [
"Bambu Lab X2D 0.8 nozzle"
],
"Bambu PPA-CF @BBL X1C": [
"Bambu Lab P1P 0.6 nozzle",
"Bambu Lab P1P 0.8 nozzle",
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab P1S 0.8 nozzle",
"Bambu Lab X1 Carbon 0.6 nozzle",
"Bambu Lab X1 Carbon 0.8 nozzle"
],
"Bambu PVA @BBL H2D": [
"Bambu Lab H2D 0.6 nozzle",
"Bambu Lab H2D 0.8 nozzle"
],
"Bambu PVA @BBL H2DP": [
"Bambu Lab H2D Pro 0.6 nozzle",
"Bambu Lab H2D Pro 0.8 nozzle"
],
"Bambu PVA @BBL H2S": [
"Bambu Lab H2S 0.6 nozzle",
"Bambu Lab H2S 0.8 nozzle"
],
"Bambu PVA @BBL P2S": [
"Bambu Lab P2S 0.6 nozzle",
"Bambu Lab P2S 0.8 nozzle"
],
"Bambu PVA @BBL X2D": [
"Bambu Lab X2D 0.8 nozzle"
],
"Bambu Support For PLA @BBL H2D": [
"Bambu Lab H2D 0.6 nozzle",
"Bambu Lab H2D 0.8 nozzle"
],
"Bambu Support For PLA @BBL H2DP": [
"Bambu Lab H2D Pro 0.6 nozzle",
"Bambu Lab H2D Pro 0.8 nozzle"
],
"Bambu Support For PLA @BBL H2S": [
"Bambu Lab H2S 0.6 nozzle",
"Bambu Lab H2S 0.8 nozzle"
],
"Bambu Support For PLA @BBL P2S": [
"Bambu Lab P2S 0.6 nozzle",
"Bambu Lab P2S 0.8 nozzle"
],
"Bambu Support For PLA @BBL X2D": [
"Bambu Lab X2D 0.8 nozzle"
],
"Bambu Support For PLA/PETG @BBL H2D": [
"Bambu Lab H2D 0.6 nozzle",
"Bambu Lab H2D 0.8 nozzle"
],
"Bambu Support For PLA/PETG @BBL H2DP": [
"Bambu Lab H2D Pro 0.6 nozzle",
"Bambu Lab H2D Pro 0.8 nozzle"
],
"Bambu Support For PLA/PETG @BBL H2S": [
"Bambu Lab H2S 0.6 nozzle",
"Bambu Lab H2S 0.8 nozzle"
],
"Bambu Support For PLA/PETG @BBL P2S": [
"Bambu Lab P2S 0.6 nozzle",
"Bambu Lab P2S 0.8 nozzle"
],
"Bambu Support For PLA/PETG @BBL X2D": [
"Bambu Lab X2D 0.8 nozzle"
],
"Bambu Support for ABS @BBL H2D": [
"Bambu Lab H2D 0.6 nozzle",
"Bambu Lab H2D 0.8 nozzle"
],
"Bambu Support for ABS @BBL H2DP": [
"Bambu Lab H2D Pro 0.6 nozzle",
"Bambu Lab H2D Pro 0.8 nozzle"
],
"Bambu Support for ABS @BBL H2S": [
"Bambu Lab H2S 0.6 nozzle",
"Bambu Lab H2S 0.8 nozzle"
],
"Bambu Support for ABS @BBL P2S": [
"Bambu Lab P2S 0.6 nozzle",
"Bambu Lab P2S 0.8 nozzle"
],
"Bambu Support for ABS @BBL X2D": [
"Bambu Lab X2D 0.8 nozzle"
],
"Bambu TPU 90A @BBL H2D": [
"Bambu Lab H2D 0.6 nozzle",
"Bambu Lab H2D 0.8 nozzle"
],
"Bambu TPU 90A @BBL H2DP": [
"Bambu Lab H2D Pro 0.6 nozzle",
"Bambu Lab H2D Pro 0.8 nozzle"
],
"Bambu TPU 95A HF @BBL H2D": [
"Bambu Lab H2D 0.4 nozzle",
"Bambu Lab H2D 0.8 nozzle"
],
"Bambu TPU 95A HF @BBL H2DP": [
"Bambu Lab H2D Pro 0.4 nozzle",
"Bambu Lab H2D Pro 0.8 nozzle"
],
"Bambu TPU 95A HF @BBL H2S": [
"Bambu Lab H2S 0.6 nozzle",
"Bambu Lab H2S 0.8 nozzle"
],
"Bambu TPU 95A HF @BBL P2S": [
"Bambu Lab P2S 0.6 nozzle",
"Bambu Lab P2S 0.8 nozzle"
],
"Bambu TPU 95A HF @BBL X2D": [
"Bambu Lab X2D 0.8 nozzle"
],
"Bambu TPU for AMS @BBL H2D": [
"Bambu Lab H2D 0.6 nozzle",
"Bambu Lab H2D 0.8 nozzle"
],
"Bambu TPU for AMS @BBL H2DP": [
"Bambu Lab H2D Pro 0.6 nozzle",
"Bambu Lab H2D Pro 0.8 nozzle"
],
"Bambu TPU for AMS @BBL H2S": [
"Bambu Lab H2S 0.6 nozzle",
"Bambu Lab H2S 0.8 nozzle"
],
"Bambu TPU for AMS @BBL P1P": [
"Bambu Lab P1P 0.6 nozzle"
],
"Bambu TPU for AMS @BBL P2S": [
"Bambu Lab P2S 0.6 nozzle",
"Bambu Lab P2S 0.8 nozzle"
],
"Bambu TPU for AMS @BBL X1C": [
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab X1 Carbon 0.6 nozzle"
],
"Bambu TPU for AMS @BBL X2D": [
"Bambu Lab X2D 0.8 nozzle"
],
"Blocks Generic ABS": [
"BLOCKS RF50 0.4 nozzle",
"BLOCKS RF50 0.6 nozzle",
"BLOCKS RF50 0.8 nozzle"
],
"Blocks Generic ASA": [
"BLOCKS RF50 0.4 nozzle",
"BLOCKS RF50 0.6 nozzle",
"BLOCKS RF50 0.8 nozzle"
],
"Blocks Generic ASA-CF": [
"BLOCKS RF50 0.4 nozzle",
"BLOCKS RF50 0.6 nozzle",
"BLOCKS RF50 0.8 nozzle"
],
"Blocks Generic PA": [
"BLOCKS RF50 0.4 nozzle",
"BLOCKS RF50 0.6 nozzle",
"BLOCKS RF50 0.8 nozzle"
],
"Blocks Generic PA-CF": [
"BLOCKS RF50 0.4 nozzle",
"BLOCKS RF50 0.6 nozzle",
"BLOCKS RF50 0.8 nozzle"
],
"Blocks Generic PC": [
"BLOCKS RF50 0.4 nozzle",
"BLOCKS RF50 0.6 nozzle",
"BLOCKS RF50 0.8 nozzle"
],
"Blocks Generic PETG": [
"BLOCKS RD50 V2 0.4 nozzle",
"BLOCKS RD50 V2 0.6 nozzle",
"BLOCKS RD50 V2 0.8 nozzle",
"BLOCKS RF50 0.4 nozzle",
"BLOCKS RF50 0.6 nozzle",
"BLOCKS RF50 0.8 nozzle"
],
"Blocks Generic PLA": [
"BLOCKS RD50 V2 0.4 nozzle",
"BLOCKS RD50 V2 0.6 nozzle",
"BLOCKS RD50 V2 0.8 nozzle",
"BLOCKS RF50 0.4 nozzle",
"BLOCKS RF50 0.6 nozzle",
"BLOCKS RF50 0.8 nozzle"
],
"Blocks Generic PLA-CF": [
"BLOCKS RF50 0.4 nozzle",
"BLOCKS RF50 0.6 nozzle",
"BLOCKS RF50 0.8 nozzle"
],
"Blocks Generic PVA": [
"BLOCKS RF50 0.4 nozzle",
"BLOCKS RF50 0.6 nozzle",
"BLOCKS RF50 0.8 nozzle"
],
"Blocks Generic TPU": [
"BLOCKS RD50 V2 0.4 nozzle",
"BLOCKS RD50 V2 0.6 nozzle",
"BLOCKS RD50 V2 0.8 nozzle",
"BLOCKS RF50 0.4 nozzle",
"BLOCKS RF50 0.6 nozzle",
"BLOCKS RF50 0.8 nozzle"
],
"Creality Generic ABS": [
"Creality CR-10 SE 0.2 nozzle",
"Creality CR-10 SE 0.4 nozzle",
"Creality CR-10 SE 0.6 nozzle",
"Creality CR-10 SE 0.8 nozzle",
"Creality CR-6 SE 0.2 nozzle",
"Creality CR-6 SE 0.4 nozzle",
"Creality CR-6 SE 0.6 nozzle",
"Creality CR-6 SE 0.8 nozzle",
"Creality CR-M4 0.4 nozzle",
"Creality Ender-3 V2 0.4 nozzle"
],
"Creality Generic ABS @Ender-3V3-all": [
"Creality Ender-3 V3 Plus 0.4 nozzle",
"Creality Ender-3 V3 Plus 0.6 nozzle"
],
"Creality Generic ABS @Hi-all": [
"Creality Hi 0.4 nozzle"
],
"Creality Generic ABS @K1-all": [
"Creality K1 SE 0.4 nozzle",
"Creality K1C 0.4 nozzle"
],
"Creality Generic ABS @K2-all": [
"Creality K2 0.4 nozzle",
"Creality K2 Plus 0.4 nozzle",
"Creality K2 Plus 0.6 nozzle",
"Creality K2 Plus 0.8 nozzle",
"Creality K2 Pro 0.4 nozzle"
],
"Creality Generic ASA @Ender-3V3-all": [
"Creality Ender-3 V3 Plus 0.4 nozzle",
"Creality Ender-3 V3 Plus 0.6 nozzle"
],
"Creality Generic ASA @K1-all": [
"Creality K1 SE 0.4 nozzle",
"Creality K1C 0.4 nozzle"
],
"Creality Generic ASA @K2-all": [
"Creality K2 0.4 nozzle",
"Creality K2 Plus 0.4 nozzle",
"Creality K2 Pro 0.4 nozzle"
],
"Creality Generic PA-CF @Ender-3V3-all": [
"Creality Ender-3 V3 Plus 0.4 nozzle",
"Creality Ender-3 V3 Plus 0.6 nozzle"
],
"Creality Generic PA-CF @K1-all": [
"Creality K1C 0.4 nozzle"
],
"Creality Generic PA-CF @K2-all": [
"Creality K2 Plus 0.4 nozzle",
"Creality K2 Plus 0.6 nozzle",
"Creality K2 Plus 0.8 nozzle"
],
"Creality Generic PC @K1-all": [
"Creality K1C 0.4 nozzle"
],
"Creality Generic PETG": [
"Creality CR-6 SE 0.2 nozzle",
"Creality CR-6 SE 0.4 nozzle",
"Creality CR-6 SE 0.6 nozzle",
"Creality CR-6 SE 0.8 nozzle",
"Creality CR-M4 0.4 nozzle"
],
"Creality Generic PETG @Ender-3V3-all": [
"Creality Ender-3 V3 0.4 nozzle",
"Creality Ender-3 V3 0.6 nozzle",
"Creality Ender-3 V3 Plus 0.4 nozzle",
"Creality Ender-3 V3 Plus 0.6 nozzle",
"Creality Ender-3 V3 SE 0.2 nozzle",
"Creality Ender-3 V3 SE 0.4 nozzle",
"Creality Ender-3 V3 SE 0.6 nozzle",
"Creality Ender-3 V3 SE 0.8 nozzle"
],
"Creality Generic PETG @Hi-all": [
"Creality Hi 0.4 nozzle"
],
"Creality Generic PETG @K1-all": [
"Creality K1 SE 0.4 nozzle",
"Creality K1C 0.4 nozzle"
],
"Creality Generic PETG @K2-all": [
"Creality K2 0.4 nozzle",
"Creality K2 Plus 0.4 nozzle",
"Creality K2 Plus 0.6 nozzle",
"Creality K2 Plus 0.8 nozzle",
"Creality K2 Pro 0.4 nozzle"
],
"Creality Generic PLA": [
"Creality CR-10 SE 0.2 nozzle",
"Creality CR-10 SE 0.4 nozzle",
"Creality CR-10 SE 0.6 nozzle",
"Creality CR-10 SE 0.8 nozzle",
"Creality CR-6 SE 0.2 nozzle",
"Creality CR-6 SE 0.4 nozzle",
"Creality CR-6 SE 0.6 nozzle",
"Creality CR-6 SE 0.8 nozzle",
"Creality CR-M4 0.4 nozzle"
],
"Creality Generic PLA @Ender-3V3-all": [
"Creality Ender-3 V3 0.4 nozzle",
"Creality Ender-3 V3 0.6 nozzle",
"Creality Ender-3 V3 Plus 0.4 nozzle",
"Creality Ender-3 V3 Plus 0.6 nozzle"
],
"Creality Generic PLA @K1-all": [
"Creality K1 SE 0.4 nozzle",
"Creality K1C 0.4 nozzle"
],
"Creality Generic PLA @K2-all": [
"Creality K2 0.4 nozzle",
"Creality K2 Plus 0.4 nozzle",
"Creality K2 Plus 0.6 nozzle",
"Creality K2 Plus 0.8 nozzle",
"Creality K2 Pro 0.4 nozzle"
],
"Creality Generic PLA-CF @K1-all": [
"Creality K1 SE 0.4 nozzle",
"Creality K1C 0.4 nozzle"
],
"Creality Generic PLA-CF @K2-all": [
"Creality K2 0.4 nozzle",
"Creality K2 Plus 0.4 nozzle",
"Creality K2 Pro 0.4 nozzle"
],
"Creality Generic TPU": [
"Creality CR-10 SE 0.2 nozzle",
"Creality CR-10 SE 0.4 nozzle",
"Creality CR-10 SE 0.6 nozzle",
"Creality CR-10 SE 0.8 nozzle"
],
"Creality Generic TPU @Ender-3V3-all": [
"Creality Ender-3 V3 0.4 nozzle",
"Creality Ender-3 V3 0.6 nozzle",
"Creality Ender-3 V3 Plus 0.4 nozzle",
"Creality Ender-3 V3 Plus 0.6 nozzle",
"Creality Ender-3 V3 SE 0.2 nozzle",
"Creality Ender-3 V3 SE 0.4 nozzle",
"Creality Ender-3 V3 SE 0.6 nozzle",
"Creality Ender-3 V3 SE 0.8 nozzle"
],
"Creality Generic TPU @K1-all": [
"Creality K1 SE 0.4 nozzle",
"Creality K1C 0.4 nozzle"
],
"Creality Generic TPU @K2-all": [
"Creality K2 0.4 nozzle",
"Creality K2 Plus 0.4 nozzle",
"Creality K2 Pro 0.4 nozzle"
],
"Cubicon ABS @base": [
"Cubicon xCeler-Plus 0.4 nozzle"
],
"Cubicon ABS-A100 @base": [
"Cubicon xCeler-Plus 0.4 nozzle"
],
"Cubicon ABSk @base": [
"Cubicon xCeler-Plus 0.4 nozzle"
],
"Cubicon PA-CF @base": [
"Cubicon xCeler-Plus 0.4 nozzle"
],
"Cubicon PC @base": [
"Cubicon xCeler-Plus 0.4 nozzle"
],
"Cubicon PETG @base": [
"Cubicon xCeler-Plus 0.4 nozzle"
],
"Cubicon PLA @base": [
"Cubicon xCeler-Plus 0.4 nozzle"
],
"Cubicon PLA+ @base": [
"Cubicon xCeler-Plus 0.4 nozzle"
],
"Cubicon PLAi21 @base": [
"Cubicon xCeler-Plus 0.4 nozzle"
],
"Flashforge Generic ABS @G3U": [
"Flashforge Guider 3 Ultra 0.6 Nozzle"
],
"Flashforge Generic ASA @G3U": [
"Flashforge Guider 3 Ultra 0.6 Nozzle"
],
"Flashforge Generic HIPS": [
"Flashforge Guider 3 Ultra 0.6 Nozzle"
],
"Flashforge Generic PETG @G3U": [
"Flashforge Guider 3 Ultra 0.6 Nozzle",
"Flashforge Guider 3 Ultra 0.8 Nozzle"
],
"Flashforge Generic PETG-CF @G3U": [
"Flashforge Guider 3 Ultra 0.6 Nozzle",
"Flashforge Guider 3 Ultra 0.8 Nozzle"
],
"Flashforge Generic PLA @G3U": [
"Flashforge Guider 3 Ultra 0.6 Nozzle",
"Flashforge Guider 3 Ultra 0.8 Nozzle"
],
"Flashforge Generic PLA-CF @G3U": [
"Flashforge Guider 3 Ultra 0.6 Nozzle",
"Flashforge Guider 3 Ultra 0.8 Nozzle"
],
"Flashforge HS PLA": [
"Flashforge AD5X 0.4 nozzle",
"Flashforge AD5X 0.6 nozzle",
"Flashforge AD5X 0.8 nozzle"
],
"Flashforge PETG-CF": [
"Flashforge AD5X 0.4 nozzle",
"Flashforge AD5X 0.6 nozzle",
"Flashforge AD5X 0.8 nozzle"
],
"Flashforge PLA-CF": [
"Flashforge AD5X 0.4 nozzle",
"Flashforge AD5X 0.6 nozzle",
"Flashforge AD5X 0.8 nozzle"
],
"Flashforge TPU 95A": [
"Flashforge AD5X 0.4 nozzle",
"Flashforge AD5X 0.6 nozzle",
"Flashforge AD5X 0.8 nozzle"
],
"FusRock Generic PAHT-CF": [
"Flashforge Guider 3 Ultra 0.6 Nozzle"
],
"FusRock Generic PET-CF": [
"Flashforge Guider 3 Ultra 0.6 Nozzle"
],
"Generic PETG HF @BBL X1C": [
"Bambu Lab P1S 0.4 nozzle",
"Bambu Lab P1S 0.6 nozzle",
"Bambu Lab X1 0.4 nozzle",
"Bambu Lab X1 0.6 nozzle",
"Bambu Lab X1 0.8 nozzle"
],
"Generic PLA @Hi-all": [
"Creality Hi 0.4 nozzle",
"Creality Hi 0.6 nozzle"
],
"HATCHBOX PETG @0.2 nozzle": [
"Qidi Q1 Pro 0.2 nozzle"
],
"Prusa Generic PA": [
"Prusa MINIIS 0.25 nozzle",
"Prusa MINIIS 0.4 nozzle",
"Prusa MINIIS 0.6 nozzle",
"Prusa MINIIS 0.8 nozzle"
],
"Prusa Generic PA-CF": [
"Prusa MINIIS 0.25 nozzle",
"Prusa MINIIS 0.4 nozzle",
"Prusa MINIIS 0.6 nozzle",
"Prusa MINIIS 0.8 nozzle"
],
"Prusa Generic PLA-CF": [
"Prusa MINIIS 0.25 nozzle",
"Prusa MINIIS 0.4 nozzle",
"Prusa MINIIS 0.6 nozzle",
"Prusa MINIIS 0.8 nozzle"
],
"QIDI PETG Basic @0.2 nozzle": [
"Qidi Q1 Pro 0.2 nozzle"
],
"QIDI PETG Rapido @0.2 nozzle": [
"Qidi Q1 Pro 0.2 nozzle"
],
"QIDI PETG Translucent @0.2 nozzle": [
"Qidi Q1 Pro 0.2 nozzle"
],
"Sovol Zero PETG HS Nozzle": [
"Sovol Zero 0.4 nozzle"
],
"Sovol Zero PLA Basic HS Nozzle": [
"Sovol Zero 0.4 nozzle"
],
"Sovol Zero PLA Silk HS Nozzle": [
"Sovol Zero 0.4 nozzle"
],
"re3D Greengate rPETG": [
"re3D GigabotX 2 1.75 nozzle",
"re3D GigabotX 2 XLT 1.75 nozzle",
"re3D TerabotX 2 1.75 nozzle"
],
"re3D PC": [
"re3D Gigabot 4 0.8 nozzle",
"re3D Gigabot 4 XLT 0.8 nozzle",
"re3D Terabot 4 0.8 nozzle"
],
"re3D PETG": [
"re3D Gigabot 4 0.8 nozzle",
"re3D Gigabot 4 XLT 0.8 nozzle",
"re3D Terabot 4 0.8 nozzle"
],
"re3D PLA": [
"re3D Gigabot 4 0.8 nozzle",
"re3D Gigabot 4 XLT 0.8 nozzle",
"re3D Terabot 4 0.8 nozzle"
],
"re3D rPP": [
"re3D GigabotX 2 1.75 nozzle",
"re3D GigabotX 2 XLT 1.75 nozzle",
"re3D TerabotX 2 1.75 nozzle"
]
}
}
@@ -51,6 +51,11 @@ uniform float tex_aspect;
uniform float rotation_rad;
uniform vec2 uv_offset;
uniform bool invert;
// False means the layer places a single copy rather than repeating: outside that copy there is
// simply no texture. DecodedHeightTexture::sample() has always returned 0 there, so the bake got
// this right while the preview wrapped the image and showed a tiled pattern that was never going
// to be printed.
uniform bool tile_enabled;
uniform float midlevel; // the height that means "don't move"; needed by the parallax step
uniform vec3 eye_model_pos; // camera position in the texture frame (world minus tex_anchor)
uniform vec3 tex_anchor; // the volume's origin in world space: the texture frame's origin
@@ -230,6 +235,14 @@ int nearest_palette_entry(vec3 rgb)
return best;
}
// True where this uv has texture on it: everywhere when the layer repeats, and only inside the
// single placed copy when it does not. The bake's own sampler draws the same line (see
// DecodedHeightTexture::sample), so the preview now stops at the same edge it does.
bool in_tile(vec2 uv)
{
return tile_enabled || (uv.x >= 0.0 && uv.x <= 1.0 && uv.y >= 0.0 && uv.y <= 1.0);
}
void main()
{
if (any(lessThan(clipping_planes_dots, ZERO)))
@@ -255,9 +268,9 @@ void main()
? vec2(dot(island_delta_lin.xy, vertex_uv), dot(island_delta_lin.zw, vertex_uv)) + island_delta_tr
: vertex_uv;
color_uv = uv;
have_uv = true;
have_uv = in_tile(uv);
float h = texture2D(height_tex, uv).r;
float k = (invert ? -1.0 : 1.0) * depth_mm * clamp(weight, 0.0, 1.0);
float k = (invert ? -1.0 : 1.0) * depth_mm * clamp(weight, 0.0, 1.0) * (have_uv ? 1.0 : 0.0);
vec3 sigmaS = dFdx(world_pos.xyz);
vec3 sigmaT = dFdy(world_pos.xyz);
vec3 R1 = cross(sigmaT, triangle_normal);
@@ -274,10 +287,12 @@ void main()
// Parallax occlusion mapping: march the view ray through the height shell and shade at the
// first point where it drops below the displaced surface (see header).
float amp = (invert ? -1.0 : 1.0) * depth_mm * clamp(weight, 0.0, 1.0);
// uv first: outside a single placed copy there is no shell to march through.
vec2 uv = project_uv(tex_pos, triangle_normal);
float amp = (invert ? -1.0 : 1.0) * depth_mm * clamp(weight, 0.0, 1.0) *
(in_tile(uv) ? 1.0 : 0.0);
vec3 view_dir = normalize(eye_model_pos - tex_pos);
float v_dot_n = dot(view_dir, triangle_normal);
vec2 uv = project_uv(tex_pos, triangle_normal);
// The shell the displaced surface lives inside, as signed heights along the normal. Taken from
// both ends of h in [0, 1] so it stays correct for an inverted layer or a raised midlevel,
@@ -314,7 +329,7 @@ void main()
}
color_uv = uv; // after the parallax march, so colour and relief stay registered
have_uv = true;
have_uv = in_tile(uv);
float hL = texture2D(height_tex, uv - vec2(height_tex_texel.x, 0.0)).r;
float hR = texture2D(height_tex, uv + vec2(height_tex_texel.x, 0.0)).r;
@@ -323,7 +338,8 @@ void main()
vec2 dh_duv = vec2((hR - hL) / (2.0 * height_tex_texel.x), (hU - hD) / (2.0 * height_tex_texel.y));
float inv_tiling = (tiling_scale > 1e-6) ? (1.0 / tiling_scale) : 1.0;
float amplitude = (invert ? -1.0 : 1.0) * depth_mm * inv_tiling * clamp(weight, 0.0, 1.0);
float amplitude = (invert ? -1.0 : 1.0) * depth_mm * inv_tiling * clamp(weight, 0.0, 1.0) *
(have_uv ? 1.0 : 0.0);
float cs = cos(rotation_rad);
float sn = sin(rotation_rad);
@@ -353,7 +369,12 @@ void main()
// Only the albedo - the specular term (intensity.y) stays white - so a coloured fragment reads as
// the same material under the same light, and the relief this preview exists to show is unaffected.
vec3 albedo = uniform_color.rgb;
if (palette_count > 0 && has_color_tex && have_uv && weight > 0.0)
albedo = palette_rgb[nearest_palette_entry(texture2D(color_tex, color_uv).rgb)];
// The fourth channel is coverage: where the picture is not there, the surface keeps its own
// colour rather than being painted the black that a transparent texel's rgb reads as.
if (palette_count > 0 && has_color_tex && have_uv && weight > 0.0) {
vec4 tex_rgba = texture2D(color_tex, color_uv);
if (tex_rgba.a >= 0.5)
albedo = palette_rgb[nearest_palette_entry(tex_rgba.rgb)];
}
gl_FragColor = vec4(vec3(intensity.y) + albedo * intensity.x, uniform_color.a);
}
@@ -110,6 +110,11 @@ uniform float tex_aspect;
uniform float rotation_rad;
uniform vec2 uv_offset;
uniform bool invert;
// False means the layer places a single copy rather than repeating: outside that copy there is
// simply no texture. DecodedHeightTexture::sample() has always returned 0 there, so the bake got
// this right while the preview wrapped the image and showed a tiled pattern that was never going
// to be printed.
uniform bool tile_enabled;
uniform float midlevel; // the height that means "don't move"; needed by the parallax step
uniform vec3 eye_model_pos; // camera position in the texture frame (world minus tex_anchor)
uniform vec3 tex_anchor; // the volume's origin in world space: the texture frame's origin
@@ -296,6 +301,14 @@ int nearest_palette_entry(vec3 rgb)
return best;
}
// True where this uv has texture on it: everywhere when the layer repeats, and only inside the
// single placed copy when it does not. The bake's own sampler draws the same line (see
// DecodedHeightTexture::sample), so the preview now stops at the same edge it does.
bool in_tile(vec2 uv)
{
return tile_enabled || (uv.x >= 0.0 && uv.x <= 1.0 && uv.y >= 0.0 && uv.y <= 1.0);
}
void main()
{
if (any(lessThan(clipping_planes_dots, ZERO)))
@@ -333,9 +346,9 @@ void main()
? vec2(dot(island_delta_lin.xy, vertex_uv), dot(island_delta_lin.zw, vertex_uv)) + island_delta_tr
: vertex_uv;
color_uv = uv;
have_uv = true;
have_uv = in_tile(uv);
float h = texture(height_tex, uv).r;
float k = (invert ? -1.0 : 1.0) * depth_mm * clamp(weight, 0.0, 1.0);
float k = (invert ? -1.0 : 1.0) * depth_mm * clamp(weight, 0.0, 1.0) * (have_uv ? 1.0 : 0.0);
vec3 sigmaS = dFdx(world_pos.xyz);
vec3 sigmaT = dFdy(world_pos.xyz);
vec3 R1 = cross(sigmaT, triangle_normal);
@@ -355,10 +368,12 @@ void main()
// Parallax occlusion mapping: march the view ray through the height shell and shade at the
// first point where it drops below the displaced surface (see header).
float amp = (invert ? -1.0 : 1.0) * depth_mm * clamp(weight, 0.0, 1.0);
// uv first: outside a single placed copy there is no shell to march through.
vec2 uv = project_uv(tex_pos, triangle_normal);
float amp = (invert ? -1.0 : 1.0) * depth_mm * clamp(weight, 0.0, 1.0) *
(in_tile(uv) ? 1.0 : 0.0);
vec3 view_dir = normalize(eye_model_pos - tex_pos);
float v_dot_n = dot(view_dir, triangle_normal);
vec2 uv = project_uv(tex_pos, triangle_normal);
// The shell the displaced surface lives inside, as signed heights along the normal. Taken from
// both ends of h in [0, 1] so it stays correct for an inverted layer or a raised midlevel,
@@ -395,7 +410,7 @@ void main()
}
color_uv = uv; // after the parallax march, so colour and relief stay registered
have_uv = true;
have_uv = in_tile(uv);
float hL = texture(height_tex, uv - vec2(height_tex_texel.x, 0.0)).r;
float hR = texture(height_tex, uv + vec2(height_tex_texel.x, 0.0)).r;
@@ -408,7 +423,8 @@ void main()
// uv -> mm is 1/tiling_scale for the triplanar projection, so this turns the uv-space
// gradient into a real surface slope.
float inv_tiling = (tiling_scale > 1e-6) ? (1.0 / tiling_scale) : 1.0;
float amplitude = (invert ? -1.0 : 1.0) * depth_mm * inv_tiling * clamp(weight, 0.0, 1.0);
float amplitude = (invert ? -1.0 : 1.0) * depth_mm * inv_tiling * clamp(weight, 0.0, 1.0) *
(have_uv ? 1.0 : 0.0);
// uv was rotated by project_uv() while t/b are the unrotated model axes, so rotate the
// gradient back into the axes' frame.
float cs = cos(rotation_rad);
@@ -441,7 +457,12 @@ void main()
// Only the albedo - the specular term (intensity.y) stays white - so a coloured fragment reads as
// the same material under the same light, and the relief this preview exists to show is unaffected.
vec3 albedo = uniform_color.rgb;
if (palette_count > 0 && has_color_tex && have_uv && weight > 0.0)
albedo = palette_rgb[nearest_palette_entry(texture(color_tex, color_uv).rgb)];
// The fourth channel is coverage: where the picture is not there, the surface keeps its own
// colour rather than being painted the black that a transparent texel's rgb reads as.
if (palette_count > 0 && has_color_tex && have_uv && weight > 0.0) {
vec4 tex_rgba = texture(color_tex, color_uv);
if (tex_rgba.a >= 0.5)
albedo = palette_rgb[nearest_palette_entry(tex_rgba.rgb)];
}
out_color = vec4(vec3(intensity.y) + albedo * intensity.x, uniform_color.a);
}
@@ -11,7 +11,7 @@
<script type="text/javascript" src="../../include/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/json2.js"></script>
<script type="text/javascript" src="../../include/i18n.js"></script>
<script type="text/javascript" src="../../include/globalapi.js"></script>
<script type="text/javascript" src="../js/globalapi.js"></script>
<script type="text/javascript" src="../js/common.js"></script>
<script src="./index.js"></script>
</head>
@@ -13,7 +13,7 @@
<script type="text/javascript" src="../../include/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/json2.js"></script>
<script type="text/javascript" src="../../include/i18n.js"></script>
<script type="text/javascript" src="../../include/globalapi.js"></script>
<script type="text/javascript" src="../js/globalapi.js"></script>
<script type="text/javascript" src="../js/common.js"></script>
<script src="../js/plugin-config-ui.js"></script>
<script src="./index.js"></script>
@@ -12,7 +12,7 @@
<script type="text/javascript" src="../../include/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/json2.js"></script>
<script type="text/javascript" src="../../include/i18n.js"></script>
<script type="text/javascript" src="../../include/globalapi.js"></script>
<script type="text/javascript" src="../js/globalapi.js"></script>
<script type="text/javascript" src="../js/common.js"></script>
<!-- <script type="text/javascript" src="./23.js"></script> -->
<script src="./index.js"></script>
@@ -61,7 +61,7 @@
<!-- Context Menu -->
<div id="ctxMenu" class="ctx" hidden>
<button class="ctx-item" data-action="open_folder" data-i18n="open_folder">Show in folder</button>
<button class="ctx-item" data-action="open_folder" data-i18n="open_folder">Open folder in explorer</button>
<button id = "delete_btn" class="ctx-item-delete" data-action="delete_bundle" data-i18n="delete_bundle" hidden>Delete bundle</button>
<button id = "unsubscribe_btn" class="ctx-item-subscribed" data-action="unsubscribe_bundle" data-i18n="unsubscribe_bundle" hidden>Unsubscribe bundle</button>
</div>
+1 -1
View File
@@ -676,7 +676,7 @@ function labelParts(actions) {
// Accessible label "Title from Pretty Source", disambiguated with the opaque action id when another
// action shares the same title+source (case/separator-insensitive) - so two rows never read out identically.
function actionLabel(action, actions) {
var label = T("sd_action_from", "%s from %s", action.title, prettySource(action.source || action.group || ""));
var label = action.title + " from " + prettySource(action.source || action.group || "");
if (actions && actions.length) {
var cache = labelParts(actions);
var mine = cache.sig[action.id];
@@ -12,7 +12,7 @@
<script type="text/javascript" src="../../include/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/json2.js"></script>
<script type="text/javascript" src="../../include/i18n.js"></script>
<script type="text/javascript" src="../../include/globalapi.js"></script>
<script type="text/javascript" src="../js/globalapi.js"></script>
<script type="text/javascript" src="../../include/xterm/xterm.js"></script>
<script type="text/javascript" src="../../include/xterm/xterm-addon-fit.js"></script>
<script src="./index.js"></script>
+339
View File
@@ -0,0 +1,339 @@
/*------------------ Date Function ------------------------*/
function GetFullToday( )
{
var d=new Date();
var nday=d.getDate();
var nmonth=d.getMonth()+1;
var nyear=d.getFullYear();
var strM=nmonth+'';
if( nmonth<10 )
strM='0'+nmonth;
var strD=nday+'';
if( nday<10 )
strD='0'+nday;
return nyear+'-'+strM+'-'+strD;
}
function GetFullDate()
{
var d=new Date();
var tDate={};
tDate.nyear=d.getFullYear();
tDate.nmonth=d.getMonth()+1;
tDate.nday=d.getDate();
tDate.nhour=d.getHours();
tDate.nminute=d.getMinutes();
tDate.nsecond=d.getSeconds();
tDate.nweek=d.getDay();
tDate.ndate=d.getDate();
var strM=tDate.nmonth+'';
if( tDate.nmonth<10 )
strM='0'+tDate.nmonth;
var strD=tDate.nday+'';
if( tDate.nday<10 )
strD='0'+tDate.nday;
var strH=tDate.nhour+'';
if( tDate.nhour<10 )
strH='0'+tDate.nhour;
var strMin=tDate.nminute+'';
if( tDate.nminute<10 )
strMin='0'+tDate.nminute;
var strS=tDate.nsecond+'';
if( tDate.nsecond<10 )
strS='0'+tDate.nsecond;
tDate.strdate=tDate.nyear+'-'+strM+'-'+strD;
tDate.strFulldate=tDate.strdate+' '+strH+':'+strMin+':'+strS;
return tDate;
}
function Unixtimestamp2Date( nSecond )
{
var d=new Date(nSecond*1000);
var tDate={};
tDate.nyear=d.getFullYear();
tDate.nmonth=d.getMonth()+1;
tDate.nday=d.getDate();
tDate.nhour=d.getHours();
tDate.nminute=d.getMinutes();
tDate.nsecond=d.getSeconds();
tDate.nweek=d.getDay();
tDate.ndate=d.getDate();
var strM=tDate.nmonth+'';
if( tDate.nmonth<10 )
strM='0'+tDate.nmonth;
var strD=tDate.nday+'';
if( tDate.nday<10 )
strD='0'+tDate.nday;
tDate.strdate=tDate.nyear+'-'+strM+'-'+strD;
return tDate.strdate;
}
//------------Array Function-------------
Array.prototype.in_array = function (e) {
let sArray= ',' + this.join(this.S) + ',';
let skey=','+e+',';
if(sArray.indexOf(skey)>=0)
return true;
else
return false;
}
//------------String Function------------------
/**
* Delete Left/Right Side Blank
*/
String.prototype.trim=function()
{
return this.replace(/(^\s*)|(\s*$)/g, '');
}
/**
* Delete Left Side Blank
*/
String.prototype.ltrim=function()
{
return this.replace(/(^\s*)/g,'');
}
/**
* Delete Right Side Blank
*/
String.prototype.rtrim=function()
{
return this.replace(/(\s*$)/g,'');
}
//----------------Get Param-------------
function GetQueryString(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r!=null)
{
return unescape(r[2]);
}
else
{
return null;
}
}
function GetGetStr()
{
let strGet="";
//获取当前URL
let url = document.location.href;
//获取?的位置
let index = url.indexOf("?")
if(index != -1) {
//截取出?后面的字符串
strGet = url.substr(index + 1);
}
return strGet;
}
/*--------------------JSON Function------------*/
/*
功能:检查一个字符串是不是标准的JSON格式
参数: strJson 被检查的字符串
返回值: 如果字符串是一个标准的JSON格式,则返回JSON对象
如果字符串不是标准JSON格式,则返回null
*/
function IsJson( strJson )
{
var tJson=null;
try
{
tJson=JSON.parse(strJson);
}
catch(exception)
{
return null;
}
return tJson;
}
/*-----------------------Ajax Function--------------------*/
/*对JQuery的Ajax函数的封装,只支持异步
参数说明:
url 目标地址
action post/get
data 字符串格式的发送内容
asyn true---异步模式;false-----同步模式;
*/
function HttpReq( url,action, data,callbackfunc)
{
var strAction=action.toLowerCase();
if( strAction=="post")
{
$.post(url,data,callbackfunc);
}
else if( strAction=="get")
{
$.get(url,callbackfunc);
}
}
/*---------------Cookie Function-------------------*/
function setCookie(name, value, time='',path='') {
if(time && path){
var strsec = time * 1000;
var exp = new Date();
exp.setTime(exp.getTime() + strsec * 1);
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path="+path;
}else if(time){
var strsec = time * 1000;
var exp = new Date();
exp.setTime(exp.getTime() + strsec * 1);
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}else if(path){
document.cookie = name + "=" + escape(value) + ";path="+path;
}else{
document.cookie = name + "=" + escape(value);
}
}
function getCookie(c_name)
{
if(document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");//获取字符串的起点
if(c_start != -1) {
c_start = c_start + c_name.length + 1;//获取值的起点
c_end = document.cookie.indexOf(";", c_start);//获取结尾处
if(c_end == -1) c_end = document.cookie.length;//如果是最后一个,结尾就是cookie字符串的结尾
return decodeURI(document.cookie.substring(c_start, c_end));//截取字符串返回
}
}
return "";
}
function checkCookie(c_name) {
username = getCookie(c_name);
console.log(username);
if (username != null && username != "")
{ return true; }
else
{ return false; }
}
function clearCookie(name) {
setCookie(name, "", -1);
}
/*--------Studio WX Message-------*/
function IsInSlicer()
{
let bMatch=navigator.userAgent.match( RegExp('BBL-Slicer','i') );
return bMatch;
}
function SendWXMessage( strMsg )
{
let bCheck=IsInSlicer();
if(bCheck!=null)
{
window.wx.postMessage(strMsg);
}
}
/*------CSS Link Control----*/
function RemoveCssLink( LinkPath )
{
let pNow=$("head link[href='"+LinkPath+"']");
let nTotal=pNow.length;
for( let n=0;n<nTotal;n++ )
{
pNow[n].remove();
}
}
function AddCssLink( LinkPath )
{
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.href = LinkPath;
link.rel = 'stylesheet';
link.type = 'text/css';
head.appendChild(link);
}
function CheckCssLinkExist( LinkPath )
{
let pNow=$("head link[href='"+LinkPath+"']");
let nTotal=pNow.length;
return nTotal;
}
/*------Dark Mode------*/
function SwitchDarkMode( DarkCssPath )
{
ExecuteDarkMode( DarkCssPath );
setInterval("ExecuteDarkMode('"+DarkCssPath+"')",1000);
}
function ExecuteDarkMode( DarkCssPath )
{
let nMode=0;
let bDarkMode=navigator.userAgent.match( RegExp('dark','i') );
if( bDarkMode!=null )
nMode=1;
let nNow=CheckCssLinkExist(DarkCssPath);
if( nMode==0 )
{
if(nNow>0)
RemoveCssLink(DarkCssPath);
}
else
{
if(nNow==0)
AddCssLink(DarkCssPath);
}
}
// Dialog pages are themed by the injected --orca-* contract + theme.css; the legacy dark.css poll is fully retired.
+1 -2
View File
@@ -2,7 +2,6 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="../include/i18n.js"></script>
<style>
* {
user-select: none;
@@ -526,7 +525,7 @@
for (let j = 0; j < m_number_of_filaments; j++) {
if (j == 0) {
var tag = document.createElement("th")
tag.innerHTML = "<div style='font-size:12px'>" + T("from_to", "from/to") + "</div>"
tag.innerHTML = "<div style='font-size:12px'>from/to</div>"
thead.appendChild(tag)
}
let th = document.createElement("th");
+1 -1
View File
@@ -10,7 +10,7 @@
<script type="text/javascript" src="../../include/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/json2.js"></script>
<script type="text/javascript" src="../../include/i18n.js"></script>
<script type="text/javascript" src="../../include/globalapi.js"></script>
<script type="text/javascript" src="../js/globalapi.js"></script>
<script type="text/javascript" src="../js/common.js"></script>
<script type="text/javascript" src="load.js"></script>
</head>
+1 -1
View File
@@ -10,7 +10,7 @@
<link rel="stylesheet" type="text/css" href="1.css" />
<script type="text/javascript" src="../../include/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../../include/i18n.js"></script>
<script type="text/javascript" src="../../include/globalapi.js"></script>
<script type="text/javascript" src="../js/globalapi.js"></script>
<script type="text/javascript" src="../js/common.js"></script>
</head>
<body onLoad="TranslatePage()">
+1 -1
View File
@@ -11,7 +11,7 @@
<script type="text/javascript" src="../../include/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/json2.js"></script>
<script type="text/javascript" src="../../include/i18n.js"></script>
<script type="text/javascript" src="../../include/globalapi.js"></script>
<script type="text/javascript" src="../js/globalapi.js"></script>
<script type="text/javascript" src="../js/common.js"></script>
<script type="text/javascript" src="11.js"></script>
</head>
+2 -4
View File
@@ -337,10 +337,8 @@ function UpdateSidebarVendors()
{
let SidebarHTML = "";
$(`.OneVendorBlock`).each((i, el)=>{
let vendor = el.getAttribute('vendor');
UpdateVendorCheckbox(vendor);
let label = vendor == "Custom" ? T("custom_vendor", "Custom") : vendor;
SidebarHTML +=`<div class="SidebarItem" vendor="${vendor}" onclick="scrollToVendor(this.getAttribute('vendor'))">${label}</div>`;
UpdateVendorCheckbox(el.getAttribute("vendor"));
SidebarHTML +=`<div class="SidebarItem" onclick="scrollToVendor(this.textContent)">${el.getAttribute('vendor')}</div>`;
});
$('#SidebarVendors').html(SidebarHTML)
}
+1 -1
View File
@@ -13,7 +13,7 @@
<script type="text/javascript" src="../../include/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/json2.js"></script>
<script type="text/javascript" src="../../include/i18n.js"></script>
<script type="text/javascript" src="../../include/globalapi.js"></script>
<script type="text/javascript" src="../js/globalapi.js"></script>
<script type="text/javascript" src="../js/common.js"></script>
<script type="text/javascript" src="../21/common.js"></script> <!-- ORCA use common sources for setup guide and standalone dialog -->
<script type="text/javascript" src="21.js"></script>
+1 -1
View File
@@ -13,7 +13,7 @@
<script type="text/javascript" src="../../include/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/json2.js"></script>
<script type="text/javascript" src="../../include/i18n.js"></script>
<script type="text/javascript" src="../../include/globalapi.js"></script>
<script type="text/javascript" src="../js/globalapi.js"></script>
<script type="text/javascript" src="../js/common.js"></script>
<script type="text/javascript" src="../22/common.js"></script> <!-- ORCA use common sources for setup guide and standalone dialog -->
<script type="text/javascript" src="./22.js"></script>
+1 -1
View File
@@ -12,7 +12,7 @@
<script type="text/javascript" src="../../include/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/json2.js"></script>
<script type="text/javascript" src="../../include/i18n.js"></script>
<script type="text/javascript" src="../../include/globalapi.js"></script>
<script type="text/javascript" src="../js/globalapi.js"></script>
<script type="text/javascript" src="../js/common.js"></script>
<script type="text/javascript" src="../22/common.js"></script> <!-- ORCA use common sources for setup guide and standalone dialog -->
<script type="text/javascript" src="./23.js"></script>
+1 -1
View File
@@ -13,7 +13,7 @@
<script type="text/javascript" src="../../include/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/json2.js"></script>
<script type="text/javascript" src="../../include/i18n.js"></script>
<script type="text/javascript" src="../../include/globalapi.js"></script>
<script type="text/javascript" src="../js/globalapi.js"></script>
<script type="text/javascript" src="../js/common.js"></script>
<script type="text/javascript" src="../21/common.js"></script> <!-- ORCA use common sources for setup guide and standalone dialog -->
<script type="text/javascript" src="24.js"></script>
+1 -1
View File
@@ -11,7 +11,7 @@
<script type="text/javascript" src="../../include/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/json2.js"></script>
<script type="text/javascript" src="../../include/i18n.js"></script>
<script type="text/javascript" src="../../include/globalapi.js"></script>
<script type="text/javascript" src="../js/globalapi.js"></script>
<script type="text/javascript" src="../js/common.js"></script>
<script type="text/javascript" src="4orca.js"></script>
</head>
+1 -1
View File
@@ -11,7 +11,7 @@
<script type="text/javascript" src="../../include/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/json2.js"></script>
<script type="text/javascript" src="../../include/i18n.js"></script>
<script type="text/javascript" src="../../include/globalapi.js"></script>
<script type="text/javascript" src="../js/globalapi.js"></script>
<script type="text/javascript" src="../js/common.js"></script>
<script type="text/javascript" src="5.js"></script>
</head>
+339
View File
@@ -0,0 +1,339 @@
/*------------------ Date Function ------------------------*/
function GetFullToday( )
{
var d=new Date();
var nday=d.getDate();
var nmonth=d.getMonth()+1;
var nyear=d.getFullYear();
var strM=nmonth+'';
if( nmonth<10 )
strM='0'+nmonth;
var strD=nday+'';
if( nday<10 )
strD='0'+nday;
return nyear+'-'+strM+'-'+strD;
}
function GetFullDate()
{
var d=new Date();
var tDate={};
tDate.nyear=d.getFullYear();
tDate.nmonth=d.getMonth()+1;
tDate.nday=d.getDate();
tDate.nhour=d.getHours();
tDate.nminute=d.getMinutes();
tDate.nsecond=d.getSeconds();
tDate.nweek=d.getDay();
tDate.ndate=d.getDate();
var strM=tDate.nmonth+'';
if( tDate.nmonth<10 )
strM='0'+tDate.nmonth;
var strD=tDate.nday+'';
if( tDate.nday<10 )
strD='0'+tDate.nday;
var strH=tDate.nhour+'';
if( tDate.nhour<10 )
strH='0'+tDate.nhour;
var strMin=tDate.nminute+'';
if( tDate.nminute<10 )
strMin='0'+tDate.nminute;
var strS=tDate.nsecond+'';
if( tDate.nsecond<10 )
strS='0'+tDate.nsecond;
tDate.strdate=tDate.nyear+'-'+strM+'-'+strD;
tDate.strFulldate=tDate.strdate+' '+strH+':'+strMin+':'+strS;
return tDate;
}
function Unixtimestamp2Date( nSecond )
{
var d=new Date(nSecond*1000);
var tDate={};
tDate.nyear=d.getFullYear();
tDate.nmonth=d.getMonth()+1;
tDate.nday=d.getDate();
tDate.nhour=d.getHours();
tDate.nminute=d.getMinutes();
tDate.nsecond=d.getSeconds();
tDate.nweek=d.getDay();
tDate.ndate=d.getDate();
var strM=tDate.nmonth+'';
if( tDate.nmonth<10 )
strM='0'+tDate.nmonth;
var strD=tDate.nday+'';
if( tDate.nday<10 )
strD='0'+tDate.nday;
tDate.strdate=tDate.nyear+'-'+strM+'-'+strD;
return tDate.strdate;
}
//------------Array Function-------------
Array.prototype.in_array = function (e) {
let sArray= ',' + this.join(this.S) + ',';
let skey=','+e+',';
if(sArray.indexOf(skey)>=0)
return true;
else
return false;
}
//------------String Function------------------
/**
* Delete Left/Right Side Blank
*/
String.prototype.trim=function()
{
return this.replace(/(^\s*)|(\s*$)/g, '');
}
/**
* Delete Left Side Blank
*/
String.prototype.ltrim=function()
{
return this.replace(/(^\s*)/g,'');
}
/**
* Delete Right Side Blank
*/
String.prototype.rtrim=function()
{
return this.replace(/(\s*$)/g,'');
}
//----------------Get Param-------------
function GetQueryString(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r!=null)
{
return unescape(r[2]);
}
else
{
return null;
}
}
function GetGetStr()
{
let strGet="";
//获取当前URL
let url = document.location.href;
//获取?的位置
let index = url.indexOf("?")
if(index != -1) {
//截取出?后面的字符串
strGet = url.substr(index + 1);
}
return strGet;
}
/*--------------------JSON Function------------*/
/*
功能:检查一个字符串是不是标准的JSON格式
参数: strJson 被检查的字符串
返回值: 如果字符串是一个标准的JSON格式,则返回JSON对象
如果字符串不是标准JSON格式,则返回null
*/
function IsJson( strJson )
{
var tJson=null;
try
{
tJson=JSON.parse(strJson);
}
catch(exception)
{
return null;
}
return tJson;
}
/*-----------------------Ajax Function--------------------*/
/*对JQuery的Ajax函数的封装,只支持异步
参数说明:
url 目标地址
action post/get
data 字符串格式的发送内容
asyn true---异步模式;false-----同步模式;
*/
function HttpReq( url,action, data,callbackfunc)
{
var strAction=action.toLowerCase();
if( strAction=="post")
{
$.post(url,data,callbackfunc);
}
else if( strAction=="get")
{
$.get(url,callbackfunc);
}
}
/*---------------Cookie Function-------------------*/
function setCookie(name, value, time='',path='') {
if(time && path){
var strsec = time * 1000;
var exp = new Date();
exp.setTime(exp.getTime() + strsec * 1);
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path="+path;
}else if(time){
var strsec = time * 1000;
var exp = new Date();
exp.setTime(exp.getTime() + strsec * 1);
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}else if(path){
document.cookie = name + "=" + escape(value) + ";path="+path;
}else{
document.cookie = name + "=" + escape(value);
}
}
function getCookie(c_name)
{
if(document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");//获取字符串的起点
if(c_start != -1) {
c_start = c_start + c_name.length + 1;//获取值的起点
c_end = document.cookie.indexOf(";", c_start);//获取结尾处
if(c_end == -1) c_end = document.cookie.length;//如果是最后一个,结尾就是cookie字符串的结尾
return decodeURI(document.cookie.substring(c_start, c_end));//截取字符串返回
}
}
return "";
}
function checkCookie(c_name) {
username = getCookie(c_name);
console.log(username);
if (username != null && username != "")
{ return true; }
else
{ return false; }
}
function clearCookie(name) {
setCookie(name, "", -1);
}
/*--------Studio WX Message-------*/
function IsInSlicer()
{
let bMatch=navigator.userAgent.match( RegExp('BBL-Slicer','i') );
return bMatch;
}
function SendWXMessage( strMsg )
{
let bCheck=IsInSlicer();
if(bCheck!=null)
{
window.wx.postMessage(strMsg);
}
}
/*------CSS Link Control----*/
function RemoveCssLink( LinkPath )
{
let pNow=$("head link[href='"+LinkPath+"']");
let nTotal=pNow.length;
for( let n=0;n<nTotal;n++ )
{
pNow[n].remove();
}
}
function AddCssLink( LinkPath )
{
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.href = LinkPath;
link.rel = 'stylesheet';
link.type = 'text/css';
head.appendChild(link);
}
function CheckCssLinkExist( LinkPath )
{
let pNow=$("head link[href='"+LinkPath+"']");
let nTotal=pNow.length;
return nTotal;
}
/*------Dark Mode------*/
function SwitchDarkMode( DarkCssPath )
{
ExecuteDarkMode( DarkCssPath );
setInterval("ExecuteDarkMode('"+DarkCssPath+"')",1000);
}
function ExecuteDarkMode( DarkCssPath )
{
let nMode=0;
let bDarkMode=navigator.userAgent.match( RegExp('dark','i') );
if( bDarkMode!=null )
nMode=1;
let nNow=CheckCssLinkExist(DarkCssPath);
if( nMode==0 )
{
if(nNow>0)
RemoveCssLink(DarkCssPath);
}
else
{
if(nNow==0)
AddCssLink(DarkCssPath);
}
}
SwitchDarkMode( "../css/dark.css" );
+340
View File
@@ -0,0 +1,340 @@
/*------------------ Date Function ------------------------*/
function GetFullToday( )
{
var d=new Date();
var nday=d.getDate();
var nmonth=d.getMonth()+1;
var nyear=d.getFullYear();
var strM=nmonth+'';
if( nmonth<10 )
strM='0'+nmonth;
var strD=nday+'';
if( nday<10 )
strD='0'+nday;
return nyear+'-'+strM+'-'+strD;
}
function GetFullDate()
{
var d=new Date();
var tDate={};
tDate.nyear=d.getFullYear();
tDate.nmonth=d.getMonth()+1;
tDate.nday=d.getDate();
tDate.nhour=d.getHours();
tDate.nminute=d.getMinutes();
tDate.nsecond=d.getSeconds();
tDate.nweek=d.getDay();
tDate.ndate=d.getDate();
var strM=tDate.nmonth+'';
if( tDate.nmonth<10 )
strM='0'+tDate.nmonth;
var strD=tDate.nday+'';
if( tDate.nday<10 )
strD='0'+tDate.nday;
var strH=tDate.nhour+'';
if( tDate.nhour<10 )
strH='0'+tDate.nhour;
var strMin=tDate.nminute+'';
if( tDate.nminute<10 )
strMin='0'+tDate.nminute;
var strS=tDate.nsecond+'';
if( tDate.nsecond<10 )
strS='0'+tDate.nsecond;
tDate.strdate=tDate.nyear+'-'+strM+'-'+strD;
tDate.strFulldate=tDate.strdate+' '+strH+':'+strMin+':'+strS;
return tDate;
}
function Unixtimestamp2Date( nSecond )
{
var d=new Date(nSecond*1000);
var tDate={};
tDate.nyear=d.getFullYear();
tDate.nmonth=d.getMonth()+1;
tDate.nday=d.getDate();
tDate.nhour=d.getHours();
tDate.nminute=d.getMinutes();
tDate.nsecond=d.getSeconds();
tDate.nweek=d.getDay();
tDate.ndate=d.getDate();
var strM=tDate.nmonth+'';
if( tDate.nmonth<10 )
strM='0'+tDate.nmonth;
var strD=tDate.nday+'';
if( tDate.nday<10 )
strD='0'+tDate.nday;
tDate.strdate=tDate.nyear+'-'+strM+'-'+strD;
return tDate.strdate;
}
//------------Array Function-------------
Array.prototype.in_array = function (e) {
let sArray= ',' + this.join(this.S) + ',';
let skey=','+e+',';
if(sArray.indexOf(skey)>=0)
return true;
else
return false;
}
//------------String Function------------------
/**
* Delete Left/Right Side Blank
*/
String.prototype.trim=function()
{
return this.replace(/(^\s*)|(\s*$)/g, '');
}
/**
* Delete Left Side Blank
*/
String.prototype.ltrim=function()
{
return this.replace(/(^\s*)/g,'');
}
/**
* Delete Right Side Blank
*/
String.prototype.rtrim=function()
{
return this.replace(/(\s*$)/g,'');
}
//----------------Get Param-------------
function GetQueryString(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r!=null)
{
return unescape(r[2]);
}
else
{
return null;
}
}
function GetGetStr()
{
let strGet="";
//获取当前URL
let url = document.location.href;
//获取?的位置
let index = url.indexOf("?")
if(index != -1) {
//截取出?后面的字符串
strGet = url.substr(index + 1);
}
return strGet;
}
/*--------------------JSON Function------------*/
/*
功能:检查一个字符串是不是标准的JSON格式
参数: strJson 被检查的字符串
返回值: 如果字符串是一个标准的JSON格式,则返回JSON对象
如果字符串不是标准JSON格式,则返回null
*/
function IsJson( strJson )
{
var tJson=null;
try
{
tJson=JSON.parse(strJson);
}
catch(exception)
{
return null;
}
return tJson;
}
/*-----------------------Ajax Function--------------------*/
/*对JQuery的Ajax函数的封装,只支持异步
参数说明:
url 目标地址
action post/get
data 字符串格式的发送内容
asyn true---异步模式;false-----同步模式;
*/
function HttpReq( url,action, data,callbackfunc)
{
var strAction=action.toLowerCase();
if( strAction=="post")
{
$.post(url,data,callbackfunc);
}
else if( strAction=="get")
{
$.get(url,callbackfunc);
}
}
/*---------------Cookie Function-------------------*/
function setCookie(name, value, time='',path='') {
if(time && path){
var strsec = time * 1000;
var exp = new Date();
exp.setTime(exp.getTime() + strsec * 1);
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path="+path;
}else if(time){
var strsec = time * 1000;
var exp = new Date();
exp.setTime(exp.getTime() + strsec * 1);
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}else if(path){
document.cookie = name + "=" + escape(value) + ";path="+path;
}else{
document.cookie = name + "=" + escape(value);
}
}
function getCookie(c_name)
{
if(document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");//获取字符串的起点
if(c_start != -1) {
c_start = c_start + c_name.length + 1;//获取值的起点
c_end = document.cookie.indexOf(";", c_start);//获取结尾处
if(c_end == -1) c_end = document.cookie.length;//如果是最后一个,结尾就是cookie字符串的结尾
return decodeURI(document.cookie.substring(c_start, c_end));//截取字符串返回
}
}
return "";
}
function checkCookie(c_name) {
username = getCookie(c_name);
console.log(username);
if (username != null && username != "")
{ return true; }
else
{ return false; }
}
function clearCookie(name) {
setCookie(name, "", -1);
}
/*--------Studio WX Message-------*/
function IsInSlicer()
{
let bMatch=navigator.userAgent.match( RegExp('BBL-Slicer','i') );
return bMatch;
}
function SendWXMessage( strMsg )
{
let bCheck=IsInSlicer();
if(bCheck!=null)
{
window.wx.postMessage(strMsg);
}
}
/*------CSS Link Control----*/
function RemoveCssLink( LinkPath )
{
let pNow=$("head link[href='"+LinkPath+"']");
let nTotal=pNow.length;
for( let n=0;n<nTotal;n++ )
{
pNow[n].remove();
}
}
function AddCssLink( LinkPath )
{
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.href = LinkPath;
link.rel = 'stylesheet';
link.type = 'text/css';
head.appendChild(link);
}
function CheckCssLinkExist( LinkPath )
{
let pNow=$("head link[href='"+LinkPath+"']");
let nTotal=pNow.length;
return nTotal;
}
/*------Dark Mode------*/
function SwitchDarkMode( DarkCssPath )
{
ExecuteDarkMode( DarkCssPath );
setInterval("ExecuteDarkMode('"+DarkCssPath+"')",1000);
}
function ExecuteDarkMode( DarkCssPath )
{
let nMode=0;
let bDarkMode=navigator.userAgent.match( RegExp('dark','i') );
if( bDarkMode!=null )
nMode=1;
let nNow=CheckCssLinkExist(DarkCssPath);
if( nMode==0 )
{
if(nNow>0)
RemoveCssLink(DarkCssPath);
}
else
{
if(nNow==0)
AddCssLink(DarkCssPath);
}
}
SwitchDarkMode("css/dark.css");
+1 -1
View File
@@ -315,7 +315,7 @@ function ShowRecentFileList( pList )
//let index=sPath.lastIndexOf('\\')>0?sPath.lastIndexOf('\\'):sPath.lastIndexOf('\/');
//let sShortName=sPath.substring(index+1,sPath.length);
let sBadge=sPublished? '<span class="FilePublishedBadge">'+T("published_badge", "PUB")+'</span>':'';
let sBadge=sPublished? '<span class="FilePublishedBadge">PUB</span>':'';
let sLogoBadge=sPublished? '<img class="FileLogoBadge" src="../../images/OrcaSlicer_gradient_circle.svg" alt="" />':'';
let TmpHtml='<div class="FileItem" fpath="'+sPath+'" >'+
+427 -373
View File
@@ -1,373 +1,427 @@
/*------------------ Date Function ------------------------*/
function GetFullToday( )
{
var d=new Date();
var nday=d.getDate();
var nmonth=d.getMonth()+1;
var nyear=d.getFullYear();
var strM=nmonth+'';
if( nmonth<10 )
strM='0'+nmonth;
var strD=nday+'';
if( nday<10 )
strD='0'+nday;
return nyear+'-'+strM+'-'+strD;
}
function GetFullDate()
{
var d=new Date();
var tDate={};
tDate.nyear=d.getFullYear();
tDate.nmonth=d.getMonth()+1;
tDate.nday=d.getDate();
tDate.nhour=d.getHours();
tDate.nminute=d.getMinutes();
tDate.nsecond=d.getSeconds();
tDate.nweek=d.getDay();
tDate.ndate=d.getDate();
var strM=tDate.nmonth+'';
if( tDate.nmonth<10 )
strM='0'+tDate.nmonth;
var strD=tDate.nday+'';
if( tDate.nday<10 )
strD='0'+tDate.nday;
var strH=tDate.nhour+'';
if( tDate.nhour<10 )
strH='0'+tDate.nhour;
var strMin=tDate.nminute+'';
if( tDate.nminute<10 )
strMin='0'+tDate.nminute;
var strS=tDate.nsecond+'';
if( tDate.nsecond<10 )
strS='0'+tDate.nsecond;
tDate.strdate=tDate.nyear+'-'+strM+'-'+strD;
tDate.strFulldate=tDate.strdate+' '+strH+':'+strMin+':'+strS;
return tDate;
}
function Unixtimestamp2Date( nSecond )
{
var d=new Date(nSecond*1000);
var tDate={};
tDate.nyear=d.getFullYear();
tDate.nmonth=d.getMonth()+1;
tDate.nday=d.getDate();
tDate.nhour=d.getHours();
tDate.nminute=d.getMinutes();
tDate.nsecond=d.getSeconds();
tDate.nweek=d.getDay();
tDate.ndate=d.getDate();
var strM=tDate.nmonth+'';
if( tDate.nmonth<10 )
strM='0'+tDate.nmonth;
var strD=tDate.nday+'';
if( tDate.nday<10 )
strD='0'+tDate.nday;
tDate.strdate=tDate.nyear+'-'+strM+'-'+strD;
return tDate.strdate;
}
//------------Array Function-------------
Array.prototype.in_array = function (e) {
let sArray= ',' + this.join(this.S) + ',';
let skey=','+e+',';
if(sArray.indexOf(skey)>=0)
return true;
else
return false;
}
//------------String Function------------------
/**
* Delete Left/Right Side Blank
*/
String.prototype.trim=function()
{
return this.replace(/(^\s*)|(\s*$)/g, '');
}
/**
* Delete Left Side Blank
*/
String.prototype.ltrim=function()
{
return this.replace(/(^\s*)/g,'');
}
/**
* Delete Right Side Blank
*/
String.prototype.rtrim=function()
{
return this.replace(/(\s*$)/g,'');
}
//----------------Get Param-------------
function GetQueryString(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r!=null)
{
return unescape(r[2]);
}
else
{
return null;
}
}
function GetGetStr()
{
let strGet="";
//获取当前URL
let url = document.location.href;
//获取?的位置
let index = url.indexOf("?")
if(index != -1) {
//截取出?后面的字符串
strGet = url.substr(index + 1);
}
return strGet;
}
/*--------------File Function--------------*/
function getFileName(path)
{
var pos1 = path.lastIndexOf('/');
var pos2 = path.lastIndexOf('\\');
var pos = Math.max(pos1, pos2);
if (pos < 0) {
return null;
}
else
{
return path.substring(pos + 1);
}
}
function getFileTail(path)
{
var pos = path.lastIndexOf('.');
if (pos < 0) {
return null;
}
else
{
return path.substring(pos + 1);
}
}
/*--------------String Function-----------*/
function html_encode(str)
{
var s = "";
if (str.length == 0) return "";
s = str.replace(/&/g, "&amp;");
s = s.replace(/</g, "&lt;");
s = s.replace(/>/g, "&gt;");
s = s.replace(/ /g, "&nbsp;");
s = s.replace(/\'/g, "&#39;");
s = s.replace(/\"/g, "&quot;");
s = s.replace(/\n/g, "<br/>");
return s;
}
function html_decode(str)
{
var s = "";
if (str.length == 0) return "";
s = str.replace(/&amp;/g, "&");
s = s.replace(/&lt;/g, "<");
s = s.replace(/&gt;/g, ">");
s = s.replace(/&nbsp;/g, " ");
s = s.replace(/&#39;/g, "\'");
s = s.replace(/&quot;/g, "\"");
s = s.replace(/<br\/>/g, "\n");
return s;
}
/*--------------------JSON Function------------*/
/*
功能:检查一个字符串是不是标准的JSON格式
参数: strJson 被检查的字符串
返回值: 如果字符串是一个标准的JSON格式,则返回JSON对象
如果字符串不是标准JSON格式,则返回null
*/
function IsJson( strJson )
{
var tJson=null;
try
{
tJson=JSON.parse(strJson);
}
catch(exception)
{
return null;
}
return tJson;
}
function DecodeJsonObject( pJson )
{
let tmpJson=JSON.stringify(pJson);
tmpJson=decodeURIComponent(tmpJson);
pJson=JSON.parse(tmpJson);
return pJson;
}
/*-----------------------Ajax Function--------------------*/
/*对JQuery的Ajax函数的封装,只支持异步
参数说明:
url 目标地址
action post/get
data 字符串格式的发送内容
asyn true---异步模式;false-----同步模式;
*/
function HttpReq( url,action, data,callbackfunc)
{
var strAction=action.toLowerCase();
if( strAction=="post")
{
$.post(url,data,callbackfunc);
}
else if( strAction=="get")
{
$.get(url,callbackfunc);
}
}
/*---------------Cookie Function-------------------*/
function setCookie(name, value, time='',path='') {
if(time && path){
var strsec = time * 1000;
var exp = new Date();
exp.setTime(exp.getTime() + strsec * 1);
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path="+path;
}else if(time){
var strsec = time * 1000;
var exp = new Date();
exp.setTime(exp.getTime() + strsec * 1);
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}else if(path){
document.cookie = name + "=" + escape(value) + ";path="+path;
}else{
document.cookie = name + "=" + escape(value);
}
}
function getCookie(c_name)
{
if(document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");//获取字符串的起点
if(c_start != -1) {
c_start = c_start + c_name.length + 1;//获取值的起点
c_end = document.cookie.indexOf(";", c_start);//获取结尾处
if(c_end == -1) c_end = document.cookie.length;//如果是最后一个,结尾就是cookie字符串的结尾
return decodeURI(document.cookie.substring(c_start, c_end));//截取字符串返回
}
}
return "";
}
function checkCookie(c_name) {
username = getCookie(c_name);
console.log(username);
if (username != null && username != "")
{ return true; }
else
{ return false; }
}
function clearCookie(name) {
setCookie(name, "", -1);
}
/*--------Studio WX Message-------*/
function IsInSlicer()
{
// window.wx is the host's message handler, registered on every webview OrcaSlicer creates.
return !!(window.wx && window.wx.postMessage);
}
function SendWXMessage( strMsg )
{
if( IsInSlicer() )
window.wx.postMessage(strMsg);
}
function SendWXDebugInfo( strMsg )
{
var tSend={};
tSend['sequence_id']=Math.round(new Date() / 1000);
tSend['command']="debug_info";
tSend['msg']=strMsg;
SendWXMessage( JSON.stringify(tSend) );
}
function OpenUrlInLocalBrowser( strUrl )
{
var tSend={};
tSend['sequence_id']=Math.round(new Date() / 1000);
tSend['command']="common_openurl";
tSend['url']=strUrl;
SendWXMessage( JSON.stringify(tSend) );
}
/*------Dark Mode------*/
// The host sets window.__orcaTheme at document start (WebView::AddHostThemeScript) and reloads the
// page when the theme changes. Every legacy page links its dark.css up front; it is switched on and
// off here instead of being added and removed, so the page's own path to it does not matter.
function ExecuteDarkMode()
{
let bDarkMode = window.__orcaTheme === "dark";
document.querySelectorAll('head link[href$="dark.css"]').forEach( function(link) { link.disabled = !bDarkMode; } );
}
ExecuteDarkMode();
/*------------------ Date Function ------------------------*/
function GetFullToday( )
{
var d=new Date();
var nday=d.getDate();
var nmonth=d.getMonth()+1;
var nyear=d.getFullYear();
var strM=nmonth+'';
if( nmonth<10 )
strM='0'+nmonth;
var strD=nday+'';
if( nday<10 )
strD='0'+nday;
return nyear+'-'+strM+'-'+strD;
}
function GetFullDate()
{
var d=new Date();
var tDate={};
tDate.nyear=d.getFullYear();
tDate.nmonth=d.getMonth()+1;
tDate.nday=d.getDate();
tDate.nhour=d.getHours();
tDate.nminute=d.getMinutes();
tDate.nsecond=d.getSeconds();
tDate.nweek=d.getDay();
tDate.ndate=d.getDate();
var strM=tDate.nmonth+'';
if( tDate.nmonth<10 )
strM='0'+tDate.nmonth;
var strD=tDate.nday+'';
if( tDate.nday<10 )
strD='0'+tDate.nday;
var strH=tDate.nhour+'';
if( tDate.nhour<10 )
strH='0'+tDate.nhour;
var strMin=tDate.nminute+'';
if( tDate.nminute<10 )
strMin='0'+tDate.nminute;
var strS=tDate.nsecond+'';
if( tDate.nsecond<10 )
strS='0'+tDate.nsecond;
tDate.strdate=tDate.nyear+'-'+strM+'-'+strD;
tDate.strFulldate=tDate.strdate+' '+strH+':'+strMin+':'+strS;
return tDate;
}
function Unixtimestamp2Date( nSecond )
{
var d=new Date(nSecond*1000);
var tDate={};
tDate.nyear=d.getFullYear();
tDate.nmonth=d.getMonth()+1;
tDate.nday=d.getDate();
tDate.nhour=d.getHours();
tDate.nminute=d.getMinutes();
tDate.nsecond=d.getSeconds();
tDate.nweek=d.getDay();
tDate.ndate=d.getDate();
var strM=tDate.nmonth+'';
if( tDate.nmonth<10 )
strM='0'+tDate.nmonth;
var strD=tDate.nday+'';
if( tDate.nday<10 )
strD='0'+tDate.nday;
tDate.strdate=tDate.nyear+'-'+strM+'-'+strD;
return tDate.strdate;
}
//------------Array Function-------------
Array.prototype.in_array = function (e) {
let sArray= ',' + this.join(this.S) + ',';
let skey=','+e+',';
if(sArray.indexOf(skey)>=0)
return true;
else
return false;
}
//------------String Function------------------
/**
* Delete Left/Right Side Blank
*/
String.prototype.trim=function()
{
return this.replace(/(^\s*)|(\s*$)/g, '');
}
/**
* Delete Left Side Blank
*/
String.prototype.ltrim=function()
{
return this.replace(/(^\s*)/g,'');
}
/**
* Delete Right Side Blank
*/
String.prototype.rtrim=function()
{
return this.replace(/(\s*$)/g,'');
}
//----------------Get Param-------------
function GetQueryString(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r!=null)
{
return unescape(r[2]);
}
else
{
return null;
}
}
function GetGetStr()
{
let strGet="";
//获取当前URL
let url = document.location.href;
//获取?的位置
let index = url.indexOf("?")
if(index != -1) {
//截取出?后面的字符串
strGet = url.substr(index + 1);
}
return strGet;
}
/*--------------File Function--------------*/
function getFileName(path)
{
var pos1 = path.lastIndexOf('/');
var pos2 = path.lastIndexOf('\\');
var pos = Math.max(pos1, pos2);
if (pos < 0) {
return null;
}
else
{
return path.substring(pos + 1);
}
}
function getFileTail(path)
{
var pos = path.lastIndexOf('.');
if (pos < 0) {
return null;
}
else
{
return path.substring(pos + 1);
}
}
/*--------------String Function-----------*/
function html_encode(str)
{
var s = "";
if (str.length == 0) return "";
s = str.replace(/&/g, "&amp;");
s = s.replace(/</g, "&lt;");
s = s.replace(/>/g, "&gt;");
s = s.replace(/ /g, "&nbsp;");
s = s.replace(/\'/g, "&#39;");
s = s.replace(/\"/g, "&quot;");
s = s.replace(/\n/g, "<br/>");
return s;
}
function html_decode(str)
{
var s = "";
if (str.length == 0) return "";
s = str.replace(/&amp;/g, "&");
s = s.replace(/&lt;/g, "<");
s = s.replace(/&gt;/g, ">");
s = s.replace(/&nbsp;/g, " ");
s = s.replace(/&#39;/g, "\'");
s = s.replace(/&quot;/g, "\"");
s = s.replace(/<br\/>/g, "\n");
return s;
}
/*--------------------JSON Function------------*/
/*
功能:检查一个字符串是不是标准的JSON格式
参数: strJson 被检查的字符串
返回值: 如果字符串是一个标准的JSON格式,则返回JSON对象
如果字符串不是标准JSON格式,则返回null
*/
function IsJson( strJson )
{
var tJson=null;
try
{
tJson=JSON.parse(strJson);
}
catch(exception)
{
return null;
}
return tJson;
}
function DecodeJsonObject( pJson )
{
let tmpJson=JSON.stringify(pJson);
tmpJson=decodeURIComponent(tmpJson);
pJson=JSON.parse(tmpJson);
return pJson;
}
/*-----------------------Ajax Function--------------------*/
/*对JQuery的Ajax函数的封装,只支持异步
参数说明:
url 目标地址
action post/get
data 字符串格式的发送内容
asyn true---异步模式;false-----同步模式;
*/
function HttpReq( url,action, data,callbackfunc)
{
var strAction=action.toLowerCase();
if( strAction=="post")
{
$.post(url,data,callbackfunc);
}
else if( strAction=="get")
{
$.get(url,callbackfunc);
}
}
/*---------------Cookie Function-------------------*/
function setCookie(name, value, time='',path='') {
if(time && path){
var strsec = time * 1000;
var exp = new Date();
exp.setTime(exp.getTime() + strsec * 1);
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path="+path;
}else if(time){
var strsec = time * 1000;
var exp = new Date();
exp.setTime(exp.getTime() + strsec * 1);
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}else if(path){
document.cookie = name + "=" + escape(value) + ";path="+path;
}else{
document.cookie = name + "=" + escape(value);
}
}
function getCookie(c_name)
{
if(document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");//获取字符串的起点
if(c_start != -1) {
c_start = c_start + c_name.length + 1;//获取值的起点
c_end = document.cookie.indexOf(";", c_start);//获取结尾处
if(c_end == -1) c_end = document.cookie.length;//如果是最后一个,结尾就是cookie字符串的结尾
return decodeURI(document.cookie.substring(c_start, c_end));//截取字符串返回
}
}
return "";
}
function checkCookie(c_name) {
username = getCookie(c_name);
console.log(username);
if (username != null && username != "")
{ return true; }
else
{ return false; }
}
function clearCookie(name) {
setCookie(name, "", -1);
}
/*--------Studio WX Message-------*/
function IsInSlicer()
{
let bMatch=navigator.userAgent.match( RegExp('BBL-Slicer','i') );
return bMatch;
}
function SendWXMessage( strMsg )
{
let bCheck=IsInSlicer();
if(bCheck!=null)
{
window.wx.postMessage(strMsg);
}
}
function SendWXDebugInfo( strMsg )
{
var tSend={};
tSend['sequence_id']=Math.round(new Date() / 1000);
tSend['command']="debug_info";
tSend['msg']=strMsg;
SendWXMessage( JSON.stringify(tSend) );
}
function OpenUrlInLocalBrowser( strUrl )
{
var tSend={};
tSend['sequence_id']=Math.round(new Date() / 1000);
tSend['command']="common_openurl";
tSend['url']=strUrl;
SendWXMessage( JSON.stringify(tSend) );
}
/*------CSS Link Control----*/
function RemoveCssLink( LinkPath )
{
let pNow=$("head link[href='"+LinkPath+"']");
let nTotal=pNow.length;
for( let n=0;n<nTotal;n++ )
{
pNow[n].remove();
}
}
function AddCssLink( LinkPath )
{
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.href = LinkPath;
link.rel = 'stylesheet';
link.type = 'text/css';
head.appendChild(link);
}
function CheckCssLinkExist( LinkPath )
{
let pNow=$("head link[href='"+LinkPath+"']");
let nTotal=pNow.length;
return nTotal;
}
/*------Dark Mode------*/
function SwitchDarkMode( DarkCssPath )
{
ExecuteDarkMode( DarkCssPath );
setInterval("ExecuteDarkMode('"+DarkCssPath+"')",1000);
}
function ExecuteDarkMode( DarkCssPath )
{
let nMode=0;
let bDarkMode=navigator.userAgent.match( RegExp('dark','i') );
if( bDarkMode!=null )
nMode=1;
let nNow=CheckCssLinkExist(DarkCssPath);
if( nMode==0 )
{
if(nNow>0)
RemoveCssLink(DarkCssPath);
}
else
{
if(nNow==0)
AddCssLink(DarkCssPath);
}
}
SwitchDarkMode( "./css/dark.css" );
+1 -1
View File
@@ -55,7 +55,7 @@
<div id="Model_Name_Area" class="Text_TitleBoard">
<div id="Model_Name_Line" class="Text_TitleArea">
<div class="Text_Title" id="ModelNameBar" ><div data-i18n="model_name">Model name</div><div>:</div><div title="xxxxxxxxxx" id="ModelName" style="margin-left: 8px;">xxxxxxxxxx</div></div>
<div><span id="ModelAuthorType" data-i18n="created_by">Created by</span><span>:</span><span id="ModelAuthorName" style="margin-left: 8px;" class="Text_Value">xxxxxxx</span></div>
<div><span id="ModelAuthorType">Created by</span><span>:</span><span id="ModelAuthorName" style="margin-left: 8px;" class="Text_Value">xxxxxxx</span></div>
</div>
<div id="ModelLicenceImg"><img src="img/by-nc-nd.png"></div>
</div>
+1 -1
View File
@@ -9,7 +9,7 @@
<script type="text/javascript" src="../include/i18n.js"></script>
<script type="text/javascript" src="../include/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../homepage/js/json2.js"></script>
<script type="text/javascript" src="../include/globalapi.js"></script>
<script type="text/javascript" src="../homepage/js/globalapi.js"></script>
<script type="text/javascript" src="../homepage/js/home.js"></script>
</head>
<body onLoad="OnInit()">
+2 -5
View File
@@ -12,11 +12,8 @@ docker run \
--net=host \
`# Some X installs will not have permissions to talk to sockets for shared memory` \
--ipc host \
`# Run as your workstations UID and GID to keep permissions the same.` \
`# Numeric IDs work even when the image has no user with your name` \
-u "$(id -u):$(id -g)" \
-e HOME="/home/$USER" \
-w "/home/$USER" \
`# Run as your workstations username to keep permissions the same` \
-u "$USER" \
`# Bind mount your home directory into the container for loading/saving files` \
-v "$HOME:/home/$USER" \
`# Pass the X display number to the container` \
+6 -56
View File
@@ -5,13 +5,11 @@
.DESCRIPTION
The Windows counterpart of scripts/check_profile.sh, and kept deliberately close to it.
Runs the same six checks, in the same order, with the same validator flags, and with the
Runs the same five checks, in the same order, with the same validator flags, and with the
same semantics: every check runs even after an earlier one fails (the workflow's
continue-on-error), then the script exits non-zero once at the end.
profile_tool scripts/orca_profile_tool.py check
legacy_compat scripts/orca_profile_tool.py legacy-compat --check against
the v2.4.2 profiles
validate_system validator -p <profiles> -l <level>
validate_slice validator -p <profiles> -s -l <level>
validate_filament_subtypes validator -p <profiles> -l <level> -f
@@ -22,9 +20,8 @@
never sees a profile no <vendor>.json indexes, a preset name two files claim, or a file
normalize and update-index would still rewrite.
Everything that has to be downloaded - the profile validator, the custom-preset fixture
archives and the v2.4.2 profile tree - lands under a per-user cache directory
(%LOCALAPPDATA%\orca-profile-check) and
Everything that has to be downloaded - the profile validator and the custom-preset fixture
archives - lands under a per-user cache directory (%LOCALAPPDATA%\orca-profile-check) and
is reused on the next run. Being outside the checkout, that directory is shared by every
worktree on the machine. It also holds one log per check plus a copy of the comment CI would
post on the PR.
@@ -51,8 +48,7 @@
check it cannot narrow is validate_slice for a vendor that ships no printers; the summary
reports that one as skipped, and naming it explicitly still runs it. profile_tool keeps its
two cross-vendor checks (setting_id and filament_id) tree-wide, so a scoped run can still
fail on another vendor's files, and legacy_compat is tree-wide too: the map it checks covers
every vendor.
fail on another vendor's files.
.PARAMETER Validator
OrcaSlicer_profile_validator.exe to use; also $env:ORCA_PROFILE_VALIDATOR. Default: the local
@@ -120,7 +116,7 @@ $HostArch = switch ($HostArch) {
default { 'x86' }
}
$AllChecks = @('profile_tool', 'legacy_compat', 'validate_system', 'validate_slice', 'validate_filament_subtypes', 'validate_custom')
$AllChecks = @('profile_tool', 'validate_system', 'validate_slice', 'validate_filament_subtypes', 'validate_custom')
$script:LogWriter = $null
$script:Python = ''
@@ -443,43 +439,6 @@ function Expand-VendorPresets([string] $Zip, [string] $Tree, [string] $Prefix) {
return $kept
}
# The profile tree of the release resources\info\legacy_compatible_printers.json is generated
# against. The tag is immutable, so the extracted tree is cached in the work dir and -Refresh
# re-extracts it. A checkout without the tag (a shallow clone, a fork that never fetched tags)
# gets it from upstream, as CI does. git archive writes a file rather than a pipe, which
# PowerShell would re-encode, and tar.exe ships with Windows 10 and later.
$LegacyBaseTag = 'v2.4.2'
$LegacyBaseUrl = 'https://github.com/OrcaSlicer/OrcaSlicer.git'
function Get-LegacyBaseProfiles {
$ErrorActionPreference = 'Continue'
$base = Join-Path (Join-Path $WorkDir 'legacy-base') $LegacyBaseTag
$profiles = Join-Path (Join-Path $base 'resources') 'profiles'
if ($Refresh -or -not (Test-Path -LiteralPath $profiles -PathType Container)) {
& git -C $RepoRoot rev-parse -q --verify "refs/tags/$LegacyBaseTag^{commit}" 2>$null | Out-Null
if ($LASTEXITCODE -ne 0) {
Write-Host "fetching tag $LegacyBaseTag from $LegacyBaseUrl ..."
& git -C $RepoRoot fetch --no-tags $LegacyBaseUrl "refs/tags/${LegacyBaseTag}:refs/tags/${LegacyBaseTag}"
if ($LASTEXITCODE -ne 0) { throw "cannot fetch tag $LegacyBaseTag" }
}
# Extracted beside its final place and moved there whole, so an interrupted extraction is
# never mistaken for the tree on the next run.
$partial = "$base.partial"
foreach ($dir in $base, $partial) {
if (Test-Path -LiteralPath $dir) { Remove-Item -LiteralPath $dir -Recurse -Force }
}
New-Item -ItemType Directory -Force -Path $partial | Out-Null
$archive = Join-Path $partial 'profiles.tar'
& git -C $RepoRoot archive -o $archive $LegacyBaseTag resources/profiles
if ($LASTEXITCODE -ne 0) { throw "cannot archive resources/profiles of $LegacyBaseTag" }
& tar -xf $archive -C $partial
if ($LASTEXITCODE -ne 0) { throw "cannot extract $archive" }
Remove-Item -LiteralPath $archive -Force
Move-Item -LiteralPath $partial -Destination $base
}
return $profiles
}
# ---------------------------------------------------------------------------- checks
$CheckBodies = @{
@@ -488,14 +447,6 @@ $CheckBodies = @{
Invoke-Tool -Exe (Resolve-Python) -Arguments (@((Join-Path $RepoRoot 'scripts\orca_profile_tool.py'), 'check', '--profiles', $ProfilesDir) + $VendorPyArgs)
}
# The map says which printers a user filament preset made against 2.4.2 can be migrated
# back to, so a profile change that renames a filament preset or narrows its
# compatible_printers has to regenerate it (the CI comment gives the command).
legacy_compat = {
$base = Get-LegacyBaseProfiles
Invoke-Tool -Exe (Resolve-Python) -Arguments @((Join-Path $RepoRoot 'scripts\orca_profile_tool.py'), 'legacy-compat', '--profiles', $ProfilesDir, '--base', $base, '--check')
}
validate_system = {
Invoke-Tool -Exe $Validator -Arguments (@('-p', $ProfilesDir) + $VendorArgs + @('-l', "$LogLevel"))
}
@@ -630,7 +581,6 @@ $CheckBodies = @{
# Heading CI puts above this check's log in the PR comment.
$CommentHeadings = @{
profile_tool = '### Profile Check Failed (orca_profile_tool.py)'
legacy_compat = '### Legacy Compatible Printers Map Out of Date'
validate_system = '### System Profile Validation Failed'
validate_slice = '### Slice Validation Failed (custom g-code expansion)'
validate_filament_subtypes = '### Filament Subtype Validation Failed'
@@ -677,7 +627,7 @@ try {
[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)
Push-UserPresets
if ($Checks | Where-Object { $_ -ne 'profile_tool' -and $_ -ne 'legacy_compat' }) { $Validator = Resolve-Validator }
if ($Checks | Where-Object { $_ -ne 'profile_tool' }) { $Validator = Resolve-Validator }
# An empty printer set is a failure to the sweep, so validate_slice is recorded as skipped
# rather than run for a vendor that ships no printers (the filament-only OrcaFilamentLibrary);
+5 -48
View File
@@ -2,13 +2,12 @@
#
# Local twin of the "Check profiles" CI job (.github/workflows/check_profiles.yml).
#
# Runs the same six checks, in the same order, with the same validator flags, and with the
# Runs the same five checks, in the same order, with the same validator flags, and with the
# same semantics: every check runs even after an earlier one fails (the workflow's
# continue-on-error), then the script exits non-zero once at the end.
#
# Everything that has to be downloaded - the profile validator, the custom-preset fixture
# archives and the v2.4.2 profile tree - lands under a per-user cache directory and is reused on
# the next run. Being outside
# Everything that has to be downloaded - the profile validator and the custom-preset fixture
# archives - lands under a per-user cache directory and is reused on the next run. Being outside
# the checkout, that directory is shared by every worktree on the machine. It also holds one log
# per check plus a copy of the comment CI would post on the PR.
#
@@ -59,7 +58,7 @@ LOG_LEVEL=2
PREFER_DOWNLOAD=0
REFRESH=0
ALL_CHECKS=(profile_tool legacy_compat validate_system validate_slice validate_filament_subtypes validate_custom)
ALL_CHECKS=(profile_tool validate_system validate_slice validate_filament_subtypes validate_custom)
CHECKS=()
# "<check><TAB>pass|fail" per check that ran, plus "<check><TAB>skip<TAB>why" for one a vendor
# scope left out; a string rather than an array because bash 3.2 (still the /bin/bash on macOS)
@@ -74,8 +73,6 @@ Usage: scripts/check_profile.sh [OPTION]... [CHECK]...
Checks (default: all, in this order):
profile_tool scripts/orca_profile_tool.py check
legacy_compat scripts/orca_profile_tool.py legacy-compat --check against the
v2.4.2 profiles
validate_system validator -p <profiles> -l <level>
validate_slice validator -p <profiles> -s -l <level>
validate_filament_subtypes validator -p <profiles> -l <level> -f
@@ -103,8 +100,7 @@ Note: --vendor narrows validate_custom too, by keeping only that vendor's preset
fixture tree. The one check it cannot narrow is validate_slice for a vendor that ships no
printers; the summary reports that one as skipped, and naming it explicitly still runs it.
profile_tool keeps its two cross-vendor checks (setting_id and filament_id) tree-wide, so a
scoped run can still fail on another vendor's files, and legacy_compat is tree-wide too: the map
it checks covers every vendor.
scoped run can still fail on another vendor's files.
EOF
}
@@ -383,44 +379,6 @@ check_profile_tool() {
python3 "${REPO_ROOT}/scripts/orca_profile_tool.py" check --profiles "${PROFILES_DIR}" --vendor "${VENDOR}"
}
# The profile tree of the release resources/info/legacy_compatible_printers.json is generated
# against. The tag is immutable, so the extracted tree is cached in the work dir and --refresh
# re-extracts it. A checkout without the tag (a shallow clone, a fork that never fetched tags)
# gets it from upstream, as CI does.
LEGACY_BASE_TAG="v2.4.2"
LEGACY_BASE_URL="https://github.com/OrcaSlicer/OrcaSlicer.git"
legacy_base_profiles() {
local base="${WORK_DIR}/legacy-base/${LEGACY_BASE_TAG}"
if [ "${REFRESH}" -eq 1 ] || [ ! -d "${base}/resources/profiles" ]; then
if ! git -C "${REPO_ROOT}" rev-parse -q --verify "refs/tags/${LEGACY_BASE_TAG}^{commit}" >/dev/null; then
msg "fetching tag ${LEGACY_BASE_TAG} from ${LEGACY_BASE_URL} ..."
git -C "${REPO_ROOT}" fetch --no-tags "${LEGACY_BASE_URL}" \
"refs/tags/${LEGACY_BASE_TAG}:refs/tags/${LEGACY_BASE_TAG}" || return 1
fi
# Extracted beside its final place and moved there whole, so an interrupted extraction is
# never mistaken for the tree on the next run.
local partial="${base}.partial"
rm -rf "${base}" "${partial}"
mkdir -p "${partial}" || return 1
if ! git -C "${REPO_ROOT}" archive "${LEGACY_BASE_TAG}" resources/profiles | tar -x -C "${partial}"; then
rm -rf "${partial}"
return 1
fi
mv "${partial}" "${base}" || return 1
fi
printf '%s\n' "${base}/resources/profiles"
}
# The map says which printers a user filament preset made against 2.4.2 can be migrated back
# to, so a profile change that renames a filament preset or narrows its compatible_printers has
# to regenerate it (the CI comment gives the command).
check_legacy_compat() {
local base
base="$(legacy_base_profiles)" || return 1
python3 "${REPO_ROOT}/scripts/orca_profile_tool.py" legacy-compat --profiles "${PROFILES_DIR}" --base "${base}" --check
}
check_validate_system() {
"${VALIDATOR}" -p "${PROFILES_DIR}" -v "${VENDOR}" -l "${LOG_LEVEL}"
}
@@ -605,7 +563,6 @@ EOF
comment_heading() {
case "$1" in
profile_tool) echo "### Profile Check Failed (orca_profile_tool.py)" ;;
legacy_compat) echo "### Legacy Compatible Printers Map Out of Date" ;;
validate_system) echo "### System Profile Validation Failed" ;;
validate_slice) echo "### Slice Validation Failed (custom g-code expansion)" ;;
validate_filament_subtypes) echo "### Filament Subtype Validation Failed" ;;
-163
View File
@@ -11,7 +11,6 @@ commands:
normalize rewrite profile files into their canonical shape
trim delete profile files no <vendor>.json list references
update-index regenerate the *_list sections of <vendor>.json
legacy-compat write the printers user presets can be migrated back to
options shared by several commands:
--vendor VENDOR act on one vendor bundle only; repeatable, empty means all
@@ -25,9 +24,6 @@ After adding, renaming or deleting profile files, run:
normalize -> update-index -> generate-id -> check
normalize supplies missing types; update-index registers presets before id
generation.
After renaming filament presets or narrowing their compatible_printers, also
rerun legacy-compat --base <2.4.2 profiles> so user presets made against 2.4.2
can be migrated back to their printers; CI runs it with --check.
Use trim only for deliberate cleanup, previewed with --dry-run: it judges against
the current index and can delete newly added, unindexed presets.
@@ -3076,139 +3072,6 @@ def fix_variant_arrays(profiles_dir=PROFILES_DIR, vendors=None, dry_run=False, s
return len(changed), errors
# ---------------------------------------------------------------------------
# legacy-compat
# ---------------------------------------------------------------------------
LEGACY_COMPAT_PATH = os.path.normpath(
os.path.join(SCRIPTS_DIR, "..", "resources", "info", "legacy_compatible_printers.json"))
def _renamed_from(data):
"""A preset's renamed_from names. Profiles write one ';'-separated string, as the
loader's unescape_strings_cstyle reads it; none of them quote or escape a name."""
value = data.get("renamed_from") or []
return [n for v in _as_list(value) for n in v.split(";") if n]
def _flatten_presets(profiles_dir):
"""Every bundle's composed filament and printer presets, for legacy-compat.
Returns (filaments, printers): filaments maps (vendor, name) to a dict with the
resolved compatible_printers, filament_id, extruder variants, renamed_from and
whether it is instantiated; printers maps each instantiated printer name to a
dict with its renamed_from and extruder variants. instantiation is read from the
preset's own file, as the loader requires every file to state it.
"""
def instantiated(data):
return str(data.get("instantiation", "")).lower() == "true"
ofl = load_vendor_configs(profiles_dir, OFL)["filament"]
filaments, printers = {}, {}
for vendor in list_vendor_names(profiles_dir):
configs = load_vendor_configs(profiles_dir, vendor)
cache = {}
for name, (_rel, data) in configs["filament"].items():
config = compose_config(name, configs["filament"], ofl, cache, vendor == OFL)
filaments[(vendor, name)] = {
"compatible_printers": set(_as_list(config.get("compatible_printers", ([],))[0])),
"filament_id": config.get("filament_id", (None,))[0],
"variants": set(_as_list(config.get("filament_extruder_variant", ([],))[0])),
"instantiation": instantiated(data),
"renamed_from": _renamed_from(data),
}
cache = {}
for name, (_rel, data) in configs["machine"].items():
if instantiated(data):
config = compose_config(name, configs["machine"], {}, cache)
printers[name] = {
"renamed_from": _renamed_from(data),
"variants": set(_as_list(config.get("printer_extruder_variant", ([],))[0])),
}
return filaments, printers
def legacy_compatible_printers(base_dir, profiles_dir=PROFILES_DIR):
"""Printers each filament preset of the base release covered but the current
preset it loads as no longer lists, kept only where a current preset with
the same filament_id still covers that printer.
User presets store only their diff, so they inherit their parent's
compatible_printers; when a profile change narrows that list, a user preset
made against the base release disappears from printers it was used on. The
app offers to write these printers into such user presets. Requiring a same-id
successor leaves out printers a filament was deliberately taken off, and
requiring a shared extruder variant keeps a printer from picking up another
variant's values.
Keyed by the base release's preset name, which is what such a user preset's
inherits still says. One current preset can stand in for several old ones
through renamed_from, each with its own old list, so the key tells them
apart. An old name resolves as the loader resolves an inherits: to the
current selectable preset of that name, else to one listing it in
renamed_from. A preset that is not instantiated never enters the loader's
collection, so it does not stop the renamed_from lookup. Printer names are
translated through the printers' renamed_from. Returns
{old preset name: sorted printer names}.
"""
old_filaments, _ = _flatten_presets(base_dir)
new_filaments, new_printers = _flatten_presets(profiles_dir)
renamed_printer = {old: new for new, rec in new_printers.items() for old in rec["renamed_from"]}
by_name, by_old_name = {}, {}
for (vendor, name), rec in new_filaments.items():
if rec["instantiation"]:
by_name.setdefault(name, []).append((vendor, rec))
for old_name in rec["renamed_from"]:
by_old_name.setdefault(old_name, []).append((vendor, rec))
covering = {} # filament_id -> printers some current instantiated preset covers
for rec in new_filaments.values():
if rec["instantiation"] and rec["filament_id"]:
covering.setdefault(rec["filament_id"], set()).update(rec["compatible_printers"])
def shares_variant(filament, printer):
variants = new_printers[printer]["variants"]
return not filament["variants"] or not variants or bool(filament["variants"] & variants)
result = {}
for (vendor, name), old in sorted(old_filaments.items()):
# Only a selectable preset can be a user preset's parent.
if not old["instantiation"]:
continue
candidates = by_name.get(name) or by_old_name.get(name, [])
same_vendor = [r for v, r in candidates if v == vendor]
rec = (same_vendor or [r for _, r in candidates] or [None])[0]
# An empty list means every printer, so nothing can have been lost.
if rec is None or not rec["compatible_printers"]:
continue
lost = {renamed_printer.get(p, p) for p in old["compatible_printers"]} - rec["compatible_printers"]
lost &= covering.get(rec["filament_id"], set()) & set(new_printers)
lost = {p for p in lost if shares_variant(rec, p)}
if lost:
result.setdefault(name, set()).update(lost)
return {name: sorted(printers) for name, printers in result.items()}
def run_legacy_compat(base_dir, profiles_dir, output, check):
presets = legacy_compatible_printers(base_dir, profiles_dir)
if check:
try:
with open(output, encoding="utf-8") as f:
current = json.load(f).get("presets")
except (OSError, ValueError, AttributeError):
current = None
if current != presets:
print_error(f"{output} is out of date; rerun legacy-compat --base {base_dir}")
return 1
print_success(f"{output} is up to date")
return 0
with open(output, "w", encoding="utf-8", newline="\n") as f:
f.write(json.dumps({"presets": presets}, indent=4, sort_keys=True, ensure_ascii=False) + "\n")
print_info(f"wrote {len(presets)} presets / {sum(map(len, presets.values()))} printers to {output}")
return 0
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
@@ -3230,17 +3093,11 @@ examples:
preview resizing the variant arrays check rejects in that bundle
orca_profile_tool.py check --strict --vendor BBL
also hold every preset's inherited variant arrays to its own width
orca_profile_tool.py legacy-compat --base /tmp/v2.4.2/resources/profiles
rewrite resources/info/legacy_compatible_printers.json against 2.4.2's
profiles (git archive v2.4.2 resources/profiles | tar -x -C /tmp/v2.4.2)
after adding, renaming or deleting profile files, run in this order:
normalize -> update-index -> generate-id -> check
normalize supplies missing types; update-index registers presets before id
generation.
After renaming filament presets or narrowing their compatible_printers, also
rerun legacy-compat --base <2.4.2 profiles> so user presets made against 2.4.2
can be migrated back to their printers; CI runs it with --check.
Use trim only for deliberate cleanup, previewed with --dry-run: it judges against
the current index and can delete newly added, unindexed presets.
"""
@@ -3370,23 +3227,6 @@ def build_parser():
"Use trim only for deliberate unindexed-file cleanup, previewed with\n"
"--dry-run; it can also delete newly authored presets.")
legacy_cmd = add(
"legacy-compat", [profiles_opt],
"write the printers user presets can be migrated back to",
"Compare the tree with an older release's profiles and write, per filament\n"
"preset of that release, the printers it covered then that the preset it now\n"
"loads as no longer lists, where a preset with the same filament_id still\n"
"covers them. The app offers to write these into user presets that inherit\n"
"that preset by its old name and do not set compatible_printers, so a\n"
"narrowed list does not hide them on printers they were made for.")
legacy_cmd.add_argument("--base", required=True, metavar="DIR",
help="the older release's resources/profiles directory")
legacy_cmd.add_argument("--output", default=LEGACY_COMPAT_PATH, metavar="FILE",
help="map to write (default: resources/info/"
"legacy_compatible_printers.json)")
legacy_cmd.add_argument("--check", action="store_true",
help="fail if the map differs from what --base implies; write nothing")
return parser
@@ -3420,9 +3260,6 @@ def main(argv=None):
return run_generate_id(profiles_dir, vendors, args.filament_id, args.setting_id,
args.dry_run)
if args.command == "legacy-compat":
return run_legacy_compat(args.base, profiles_dir, args.output, args.check)
if args.command == "fix-variant":
_changed, errors = fix_variant_arrays(profiles_dir, vendors, dry_run=args.dry_run,
strict=args.strict)
-112
View File
@@ -1258,118 +1258,6 @@ class TestVariantNames(TreeCase):
self.assertIn('holds the legacy variant "Direct Drive Normal"', out)
# ---------------------------------------------------------------------------
# legacy-compat
# ---------------------------------------------------------------------------
class TestLegacyCompat(unittest.TestCase):
"""A base release and the current tree, each with one vendor."""
def setUp(self):
self.base, self.cur = Tree(), Tree()
self.addCleanup(self.base.cleanup)
self.addCleanup(self.cur.cleanup)
@staticmethod
def printer(tree, name, **extra):
tree.write("V", f"machine/{name}.json",
{"type": "machine", "name": name, "instantiation": "true", **extra})
tree.index("V", "machine", name, f"machine/{name}.json")
@staticmethod
def filament(tree, name, printers, filament_id="OFpetg01", **extra):
tree.write("V", f"filament/{name}.json",
{"type": "filament", "name": name, "instantiation": "true",
"filament_id": filament_id, "compatible_printers": printers, **extra})
tree.index("V", "filament", name, f"filament/{name}.json")
def generate(self):
return apt.legacy_compatible_printers(self.base.profiles, self.cur.profiles)
def test_renamed_and_narrowed_preset_keeps_printers_a_same_id_sibling_covers(self):
for tree in (self.base, self.cur):
for p in ("A 0.4", "A 0.6", "B 0.4"):
self.printer(tree, p)
self.filament(self.base, "PETG @A-all", ["A 0.4", "A 0.6", "B 0.4"])
self.filament(self.cur, "PETG @V A-all", ["A 0.6"], renamed_from="PETG @A-all;PETG A-all")
self.filament(self.cur, "PETG @A 0.4", ["A 0.4"])
self.assertEqual(self.generate(), {"PETG @A-all": ["A 0.4"]})
def test_each_old_name_gets_back_only_its_own_list(self):
# The current "PC @0.4" existed in the base and also replaces the split "PC".
for tree in (self.base, self.cur):
for p in ("A 0.4", "A 0.8"):
self.printer(tree, p)
self.filament(self.base, "PC", ["A 0.4", "A 0.8"])
self.filament(self.base, "PC @0.4", ["A 0.4"])
self.filament(self.cur, "PC @0.4", ["A 0.4"], renamed_from="PC")
self.filament(self.cur, "PC @0.8", ["A 0.8"])
self.assertEqual(self.generate(), {"PC": ["A 0.8"]})
def test_old_name_now_a_base_preset_resolves_through_renamed_from(self):
for tree in (self.base, self.cur):
for p in ("I 0.4", "Plus 0.4"):
self.printer(tree, p)
self.filament(self.base, "PLA @base", ["I 0.4", "Plus 0.4"])
self.filament(self.cur, "PLA @base", [], instantiation="false")
self.filament(self.cur, "PLA @I 0.4", ["I 0.4"], renamed_from="PLA @base")
self.filament(self.cur, "PLA @Plus 0.4", ["Plus 0.4"])
self.assertEqual(self.generate(), {"PLA @base": ["Plus 0.4"]})
def test_printer_without_a_successor_is_left_out(self):
for tree in (self.base, self.cur):
for p in ("A 0.4", "A 0.6"):
self.printer(tree, p)
self.filament(self.base, "PETG @A", ["A 0.4", "A 0.6"])
self.filament(self.cur, "PETG @A", ["A 0.6"])
self.filament(self.cur, "Other @A", ["A 0.4"], filament_id="OFother1")
self.assertEqual(self.generate(), {})
def test_printer_names_follow_printer_renames(self):
self.printer(self.base, "Old 0.4")
self.printer(self.base, "A 0.6")
self.printer(self.cur, "New 0.4", renamed_from="Old 0.4")
self.printer(self.cur, "A 0.6")
self.filament(self.base, "PETG @A", ["Old 0.4", "A 0.6"])
self.filament(self.cur, "PETG @A", ["A 0.6"])
self.filament(self.cur, "PETG @New", ["New 0.4"])
self.assertEqual(self.generate(), {"PETG @A": ["New 0.4"]})
def test_printer_without_a_shared_extruder_variant_is_left_out(self):
for tree in (self.base, self.cur):
self.printer(tree, "Direct 0.4", printer_extruder_variant=["Direct Drive Standard"])
self.printer(tree, "Bowden 0.4", printer_extruder_variant=["Bowden Standard"])
self.filament(self.base, "PETG @all", ["Direct 0.4", "Bowden 0.4"])
self.filament(self.cur, "PETG @all", ["Direct 0.4"],
filament_extruder_variant=["Direct Drive Standard"])
self.filament(self.cur, "PETG @Bowden", ["Bowden 0.4"])
self.assertEqual(self.generate(), {})
def test_preset_now_listing_no_printer_is_skipped(self):
for tree in (self.base, self.cur):
self.printer(tree, "A 0.4")
self.filament(self.base, "PETG @A", ["A 0.4"])
self.filament(self.cur, "PETG @A", [])
self.assertEqual(self.generate(), {})
def test_check_passes_on_a_current_map_and_fails_on_a_stale_one(self):
for tree in (self.base, self.cur):
for p in ("A 0.4", "A 0.6"):
self.printer(tree, p)
self.filament(self.base, "PETG @A", ["A 0.4", "A 0.6"])
self.filament(self.cur, "PETG @A", ["A 0.6"])
self.filament(self.cur, "PETG @A 0.4", ["A 0.4"])
output = os.path.join(self.cur.dir, "map.json")
argv = ["legacy-compat", "--base", self.base.profiles, "--profiles", self.cur.profiles,
"--output", output]
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(apt.main(argv), 0)
self.assertEqual(apt.main(argv + ["--check"]), 0)
with open(output, "w", encoding="utf-8") as f:
json.dump({"presets": {}}, f)
self.assertEqual(apt.main(argv + ["--check"]), 1)
class TestDispatch(TreeCase):
def test_each_command_reaches_its_own_writer(self):
self.t.write("V", "filament/A.json", {"type": "filament", "name": "A"})
-20
View File
@@ -1374,26 +1374,6 @@ bool AppConfig::write_config_file(const std::string &path, std::string body, con
return true;
}
void AppConfig::clear_local_machine_access_code(const std::string& dev_id, const std::string& agent_id)
{
// Unscoped credentials predate printer agents and belong to the legacy BBL agent.
const bool is_bbl_agent = agent_id.empty() || agent_id == "bbl";
auto it = m_local_machines.find(dev_id);
if (it != m_local_machines.end()) {
const std::string& stored_agent = it->second.printer_agent_id;
if (stored_agent == agent_id || (is_bbl_agent && (stored_agent.empty() || stored_agent == "bbl"))) {
if (!it->second.access_code.empty()) {
it->second.access_code.clear();
m_dirty = true;
}
}
}
if (is_bbl_agent) {
erase("access_code", dev_id);
erase("user_access_code", dev_id);
}
}
bool AppConfig::get_variant(const std::string &vendor, const std::string &model, const std::string &variant) const
{
const auto it_v = m_vendors.find(vendor);
-2
View File
@@ -306,8 +306,6 @@ public:
}
}
void clear_local_machine_access_code(const std::string& dev_id, const std::string& agent_id);
const std::vector<std::string> &get_filament_presets() const { return m_filament_presets; }
void set_filament_presets(const std::vector<std::string> &filament_presets){
m_filament_presets = filament_presets;
+3 -1
View File
@@ -300,10 +300,12 @@ template<class PConf>
void fill_config(PConf& pcfg, const ArrangeParams &params) {
if (params.is_belt) {
// Pack from the end of the belt that prints first.
// Pack from the end of the belt that prints first, and keep the pile on the
// bed when it is larger than the room around that end.
pcfg.starting_point = !params.belt_reversed ? PConf::Alignment::BOTTOM_LEFT :
params.belt_axis == 1 ? PConf::Alignment::TOP_LEFT :
PConf::Alignment::BOTTOM_RIGHT;
pcfg.clamp_to_bin = true;
}
else if (params.is_seq_print) {
// Start placing the items from the center of the print bed
+1 -1
View File
@@ -166,7 +166,7 @@ void Print::_plan_belt_purge()
m_wipe_tower_data.tool_ordering.sort_and_build_data(*this, (unsigned int) -1, false);
if (m_wipe_tower_data.tool_ordering.empty() || m_wipe_tower_data.tool_ordering.last_extruder() == unsigned(-1))
throw Slic3r::SlicingError(_u8L("The print is empty. The model is not printable with current print settings."));
throw Slic3r::SlicingError("The print is empty. The model is not printable with current print settings.");
// Is there any filament change at all? Not ToolOrdering::has_wipe_tower(): that reads the
// FIRST layer's flag, and on a belt the first layer may be a brim apron band, which carries
+23 -26
View File
@@ -1807,8 +1807,7 @@ std::vector<std::pair<std::string, SketchPlane>> CadDocument::resolve_datum_plan
}
// TRN Datum plane entry in the reference plane list. %1% is the plane name.
out.emplace_back(base_missing ? format(_u8L("%1% (base plane missing)"), f.name) : f.name, result);
out.emplace_back(base_missing ? f.name + " (base plane missing)" : f.name, result);
}
return out;
}
@@ -2091,8 +2090,8 @@ static int pick_body(int ref, int nb)
{
if (ref == -1) return nb - 1;
if (ref < 0 || ref >= nb)
throw std::runtime_error(format(_u8L("a feature works on body %1%, which does not exist at that point in the history"),
ref + 1));
throw std::runtime_error("a feature works on body " + std::to_string(ref + 1)
+ ", which does not exist at that point in the history");
return ref;
}
@@ -2155,11 +2154,11 @@ static void settle_body_refs(CadFeature& f, const std::vector<CadBody>& v, bool
CadFeature::BodyId& id = f.body_ref_ids[k++];
if (kind != running) return;
if (ref == kBodyGone)
throw std::runtime_error(format(_u8L("\"%1%\" works on a body made by a feature that was deleted or hidden"), f.name));
throw std::runtime_error("\"" + f.name + "\" works on a body made by a feature that was deleted or hidden");
if (f.body_refs_pending && id.src >= 0) {
const int i = find_body(v, id);
if (i < 0)
throw std::runtime_error(format(_u8L("\"%1%\" works on a body that does not exist at that point in the history"), f.name));
throw std::runtime_error("\"" + f.name + "\" works on a body that does not exist at that point in the history");
ref = i;
}
id = ref >= 0 ? body_id_of(v, ref) : CadFeature::BodyId{};
@@ -2385,8 +2384,7 @@ bool CadDocument::move_feature(int index, int delta)
check(f.sketch_ref); check(f.sweep_path_ref); check(f.pattern_curve_sketch); check(f.rib_sketch_ref);
for (int& r : f.loft_profile_refs) check(r);
if (!bad.empty()) {
// TRN Feature reorder error. %1% is the moved feature, %2% the feature it depends on.
error = format(_u8L("\"%1%\" uses \"%2%\", so it cannot come before it"), f.name, bad);
error = "\"" + f.name + "\" uses \"" + bad + "\", so it cannot come before it";
features.swap(snapshot);
return false;
}
@@ -2465,8 +2463,7 @@ static std::string open_loop_message(const CadFeature& sketch,
for (size_t i = 0; i < shown; ++i)
msg += "\n " + format(_u8L("Open at (%.3f, %.3f)"), open[i].x(), open[i].y());
if (open.size() > shown)
// TRN Follows a list of open sketch ends. %1% is how many more were not listed.
msg += "\n " + format(_u8L("Open ends not shown: %1%"), open.size() - shown);
msg += "\n " + format(_u8L("...and %1% more open end(s)"), open.size() - shown);
}
return msg;
}
@@ -2478,11 +2475,11 @@ static gp_Ax1 revolve_axis_of(const CadFeature& f, const CadFeature& sk)
if (f.revolve_axis_entity >= 0) {
if (f.revolve_axis_entity >= int(sk.entities.size())
|| sk.entities[f.revolve_axis_entity].type != SketchEntity::Type::Line)
throw std::runtime_error(_u8L("revolve: the axis line is no longer in the sketch — pick the axis again"));
throw std::runtime_error("revolve: the axis line is no longer in the sketch — pick the axis again");
const SketchEntity& e = sk.entities[f.revolve_axis_entity];
const Vec3d a = sk.plane.to_world(e.p0), b = sk.plane.to_world(e.p1);
if ((b - a).norm() < 1e-9)
throw std::runtime_error(_u8L("revolve: the axis line has no length"));
throw std::runtime_error("revolve: the axis line has no length");
const Vec3d d = (b - a).normalized();
return gp_Ax1(gp_Pnt(a.x(), a.y(), a.z()), gp_Dir(d.x(), d.y(), d.z()));
}
@@ -3027,17 +3024,17 @@ void CadDocument::apply_feature(TopoDS_Shape& result, bool& have_body,
// ISO external thread depth is ~0.61*P, so allow up to 0.7*P (0.49 wrongly rejected
// every real thread -> nothing rendered). Still bound it well under a full pitch.
// R >= 0.5 (not >): M1, the smallest size in the standards table, is exactly 0.5.
const char* why = R < 0.5 ? L("thread: the diameter must be at least 1 mm")
: P <= 0.1 ? L("thread: the pitch must be more than 0.1 mm")
: (D <= 1e-3 || D >= 0.7 * P) ? L("thread: the depth must be between 0 and 0.7 x the pitch")
: D >= 0.45 * R ? L("thread: the depth is too large for this diameter")
: H <= 0.5 * P ? L("thread: the length must be more than half a pitch")
: H / P >= 400.0 ? L("thread: too many turns (length / pitch must stay under 400)")
const char* why = R < 0.5 ? "thread: the diameter must be at least 1 mm"
: P <= 0.1 ? "thread: the pitch must be more than 0.1 mm"
: (D <= 1e-3 || D >= 0.7 * P) ? "thread: the depth must be between 0 and 0.7 x the pitch"
: D >= 0.45 * R ? "thread: the depth is too large for this diameter"
: H <= 0.5 * P ? "thread: the length must be more than half a pitch"
: H / P >= 400.0 ? "thread: too many turns (length / pitch must stay under 400)"
: nullptr;
// Legacy recipes keep their old outcome (the body left as it was) so a project that
// opened before still opens; every thread made now reports the reason instead.
if (why != nullptr) {
if (f.thread_major_nominal) throw std::runtime_error(Slic3r::I18N::translate(why));
if (f.thread_major_nominal) throw std::runtime_error(why);
break;
}
}
@@ -3081,7 +3078,7 @@ void CadDocument::apply_feature(TopoDS_Shape& result, bool& have_body,
// Tapped hole: bore to the minor radius R - D, then cut the groove out to the
// major radius R. The bore sits 10 um inside the minor radius so that, threading
// an existing tap-drill hole, it does not coincide with that hole's wall.
if (!have_body) throw std::runtime_error(_u8L("internal thread needs a body"));
if (!have_body) throw std::runtime_error("internal thread needs a body");
const double bore_r = R - D - 0.01;
cut_from(result, BRepPrimAPI_MakeCylinder(ax2, bore_r, f.thread_height).Shape());
TopoDS_Shape groove;
@@ -3244,12 +3241,12 @@ void CadDocument::apply_boolean(std::vector<CadBody>& bodies, const CadFeature&
const int tool = f.bool_tool_body == -1 ? -1 : pick_body(f.bool_tool_body, nb);
// Same rule as Cut, Mirror and Transform: an operation that cannot run says why, rather
// than leaving the bodies as they were and reporting success.
if (tgt < 0) throw std::runtime_error(_u8L("boolean: no target body"));
if (tool < 0) throw std::runtime_error(_u8L("boolean: no tool body — pick a second body"));
if (tgt == tool) throw std::runtime_error(_u8L("boolean: the target and the tool are the same body"));
if (tgt < 0) throw std::runtime_error("boolean: no target body");
if (tool < 0) throw std::runtime_error("boolean: no tool body — pick a second body");
if (tgt == tool) throw std::runtime_error("boolean: the target and the tool are the same body");
const TopoDS_Shape A = bodies[tgt].shape; // target survives
const TopoDS_Shape B = bodies[tool].shape; // tool, consumed unless kept
if (A.IsNull() || B.IsNull()) throw std::runtime_error(_u8L("boolean: a body has no geometry"));
if (A.IsNull() || B.IsNull()) throw std::runtime_error("boolean: a body has no geometry");
NCollection_List<TopoDS_Shape> args, tools;
args.Append(A);
@@ -3557,7 +3554,7 @@ void CadDocument::apply_thicken_surface(std::vector<CadBody>& bodies, const CadF
if (props.Mass() < 0.0) solid.Reverse();
}
bodies.push_back({solid, f.name.empty() ? _u8L("Thicken Surface") : f.name});
bodies.push_back({solid, f.name.empty() ? std::string("ThickenSurface") : f.name});
}
void CadDocument::apply_surface_offset(std::vector<CadBody>& bodies, const CadFeature& f) const
@@ -3576,7 +3573,7 @@ void CadDocument::apply_surface_offset(std::vector<CadBody>& bodies, const CadFe
TopoDS_Shape off_shape = mos.Shape();
if (off_shape.IsNull()) throw std::runtime_error(_u8L("surface-offset: produced no geometry"));
bodies.push_back({off_shape, f.name.empty() ? _u8L("Surface Offset") : f.name});
bodies.push_back({off_shape, f.name.empty() ? std::string("SurfaceOffset") : f.name});
}
// Project `edges` of a shape onto `plane`, appending the resulting 2D entities to `out`.
+6 -6
View File
@@ -325,10 +325,10 @@ std::vector<TopoDS_Edge> GeometryEngine::collect_edges(const TopoDS_Shape& solid
// handing the solid back unchanged, which recompute then reported as a success.
TopoDS_Shape GeometryEngine::apply_fillet(const TopoDS_Shape& solid, double radius, FaceGroup faces)
{
if (radius <= 0.001) throw std::runtime_error(_u8L("the fillet radius must be greater than 0"));
if (radius <= 0.001) throw std::runtime_error("the fillet radius must be greater than 0");
std::vector<TopoDS_Edge> edges = collect_edges(solid, faces);
if (edges.empty()) throw std::runtime_error(_u8L("no edges to fillet in that group"));
if (edges.empty()) throw std::runtime_error("no edges to fillet in that group");
BRepFilletAPI_MakeFillet fillet(solid);
for (const auto& edge : edges)
@@ -344,10 +344,10 @@ TopoDS_Shape GeometryEngine::apply_fillet(const TopoDS_Shape& solid, double radi
TopoDS_Shape GeometryEngine::apply_chamfer(const TopoDS_Shape& solid, double distance, FaceGroup faces)
{
if (distance <= 0.001) throw std::runtime_error(_u8L("the chamfer distance must be greater than 0"));
if (distance <= 0.001) throw std::runtime_error("the chamfer distance must be greater than 0");
std::vector<TopoDS_Edge> edges = collect_edges(solid, faces);
if (edges.empty()) throw std::runtime_error(_u8L("no edges to chamfer in that group"));
if (edges.empty()) throw std::runtime_error("no edges to chamfer in that group");
BRepFilletAPI_MakeChamfer chamfer(solid);
for (const auto& edge : edges)
@@ -370,7 +370,7 @@ TopoDS_Shape GeometryEngine::apply_chamfer(const TopoDS_Shape& solid, double dis
TopoDS_Shape GeometryEngine::apply_fillet(const TopoDS_Shape& solid, double radius, const std::vector<int>& edge_ids)
{
if (radius <= 0.001) throw std::runtime_error(_u8L("the fillet radius must be greater than 0"));
if (radius <= 0.001) throw std::runtime_error("the fillet radius must be greater than 0");
if (edge_ids.empty()) throw std::runtime_error("apply_fillet: no edge picked");
BRepFilletAPI_MakeFillet mk(solid);
@@ -387,7 +387,7 @@ TopoDS_Shape GeometryEngine::apply_fillet(const TopoDS_Shape& solid, double radi
TopoDS_Shape GeometryEngine::apply_chamfer(const TopoDS_Shape& solid, double distance, const std::vector<int>& edge_ids)
{
if (distance <= 0.001) throw std::runtime_error(_u8L("the chamfer distance must be greater than 0"));
if (distance <= 0.001) throw std::runtime_error("the chamfer distance must be greater than 0");
if (edge_ids.empty()) throw std::runtime_error("apply_chamfer: no edge picked");
BRepFilletAPI_MakeChamfer mk(solid);
+3 -3
View File
@@ -379,7 +379,7 @@ TopoDS_Shape SketchEngine::make_revolve(const TopoDS_Wire& wire, const gp_Ax1& a
}
}
if (pos && neg)
throw std::runtime_error(_u8L("the profile crosses the revolve axis — it must lie on one side of it"));
throw std::runtime_error("the profile crosses the revolve axis — it must lie on one side of it");
}
gp_Ax1 axis = axis_in;
double angle_rad = angle_deg * M_PI / 180.0;
@@ -390,7 +390,7 @@ TopoDS_Shape SketchEngine::make_revolve(const TopoDS_Wire& wire, const gp_Ax1& a
if (!rev.IsDone())
throw std::runtime_error(_u8L("Failed to revolve"));
if (!BRepCheck_Analyzer(rev.Shape()).IsValid())
throw std::runtime_error(_u8L("the profile crosses the revolve axis — it must lie on one side of it"));
throw std::runtime_error("the profile crosses the revolve axis — it must lie on one side of it");
return rev.Shape();
}
@@ -923,7 +923,7 @@ static TopoDS_Face checked_profile_face(const TopoDS_Face& f)
{
BRepCheck_Analyzer an(f);
if (!an.IsValid())
throw std::runtime_error(_u8L("the profile crosses or folds back on itself, so it does not bound one region"));
throw std::runtime_error("the profile crosses or folds back on itself, so it does not bound one region");
return f;
}
+8 -9
View File
@@ -2,7 +2,6 @@
#include "Exception.hpp"
#include "Point.hpp"
#include "format.hpp"
#include "I18N.hpp"
#include "Utils.hpp"
#include "LocalesUtils.hpp"
#include "Preset.hpp"
@@ -614,7 +613,7 @@ bool ConfigBase::set_deserialize_nothrow(const t_config_option_key &opt_key_src,
void ConfigBase::set_deserialize(const t_config_option_key &opt_key_src, const std::string &value_src, ConfigSubstitutionContext& substitutions_ctxt, bool append)
{
if (! this->set_deserialize_nothrow(opt_key_src, value_src, substitutions_ctxt, append))
throw BadOptionValueException(format(_u8L("Invalid value provided for parameter %1%: %2%"), opt_key_src, value_src));
throw BadOptionValueException(format("Invalid value provided for parameter %1%: %2%", opt_key_src, value_src));
}
void ConfigBase::set_deserialize(std::initializer_list<SetDeserializeItem> items, ConfigSubstitutionContext& substitutions_ctxt)
@@ -1174,7 +1173,7 @@ ConfigSubstitutions ConfigBase::load_from_ini(const std::string &file, ForwardCo
boost::property_tree::read_ini(ifs, tree);
return this->load(tree, compatibility_rule);
} catch (const ConfigurationError &e) {
throw ConfigurationError(format(_u8L("Failed loading configuration file \"%1%\": %2%"), file, e.what()));
throw ConfigurationError(format("Failed loading configuration file \"%1%\": %2%", file, e.what()));
}
}
@@ -1431,8 +1430,9 @@ ConfigSubstitutions ConfigBase::load_from_gcode_file(const std::string &file, Fo
}
}
if (!header_found) {
// TRN %1% is the application name.
std::string error_message = format(_u8L("Not a gcode file generated by %1%."), SLIC3R_APP_FULL_NAME);
std::string error_message = "Not a gcode file generated by ";
error_message += SLIC3R_APP_FULL_NAME;
error_message += ".";
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << error_message;
throw Slic3r::RuntimeError(error_message.c_str());
}
@@ -1458,8 +1458,7 @@ ConfigSubstitutions ConfigBase::load_from_gcode_file(const std::string &file, Fo
}
if (!begin_found) {
//BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << format("Configuration block closing tag \"; CONFIG_BLOCK_START\" not found when reading %1%", file);
// TRN %1% is a tag in the G-code file that must not be translated.
throw Slic3r::RuntimeError(format(_u8L("Config tag \"%1%\" not found"), "; CONFIG_BLOCK_START"));
throw Slic3r::RuntimeError(format("Config tag \"; CONFIG_BLOCK_START\" not found"));
}
std::string key, value;
while (std::getline(ifs, line)) {
@@ -1484,7 +1483,7 @@ ConfigSubstitutions ConfigBase::load_from_gcode_file(const std::string &file, Fo
}
if (!end_found) {
//BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << format("Configuration block opening tag \"; CONFIG_BLOCK_END\" not found when reading %1%", file);
throw Slic3r::RuntimeError(format(_u8L("Config tag \"%1%\" not found"), "; CONFIG_BLOCK_END"));
throw Slic3r::RuntimeError(format("Config tag \"; CONFIG_BLOCK_END\" not found"));
}
}
else
@@ -1504,7 +1503,7 @@ ConfigSubstitutions ConfigBase::load_from_gcode_file(const std::string &file, Fo
if (key_value_pairs < 80) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << format("Suspiciously low number of configuration values extracted from %1%: %2%", file, key_value_pairs);
throw Slic3r::RuntimeError(format(_u8L("Suspiciously low number of configuration values extracted from %1%: %2%"), file, key_value_pairs));
throw Slic3r::RuntimeError(format("Suspiciously low number of configuration values extracted from %1%: %2%", file, key_value_pairs));
}
// Do legacy conversion on a completely loaded dictionary.
+2 -3
View File
@@ -7,7 +7,6 @@
#include <algorithm>
#include <cmath>
#include "Config.hpp"
#include "I18N.hpp"
namespace Slic3r {
@@ -125,9 +124,9 @@ double Extruder::unretract()
void Extruder::set_retracted(double retracted, double restart_extra)
{
if (retracted < - EPSILON)
throw Slic3r::RuntimeError(_u8L("Custom G-code reports negative z_retracted."));
throw Slic3r::RuntimeError("Custom G-code reports negative z_retracted.");
if (restart_extra < - EPSILON)
throw Slic3r::RuntimeError(_u8L("Custom G-code reports negative z_restart_extra."));
throw Slic3r::RuntimeError("Custom G-code reports negative z_restart_extra.");
if (retracted > EPSILON) {
m_retracted = retracted;
+28 -28
View File
@@ -19,8 +19,6 @@
#include "ColorDecomposeRecipe.hpp"
#include "Config.hpp"
#include "I18N.hpp"
#include "format.hpp"
#include "FilamentMixerModel.hpp"
#include "LocalesUtils.hpp"
@@ -635,36 +633,36 @@ bool try_parse_mixed_components_strict(const std::string &str,
{
components.clear();
if (str.empty()) {
err = _u8L("empty component list");
err = "empty component list";
return false;
}
std::istringstream ss(str);
std::string token;
while (std::getline(ss, token, ',')) {
if (token.empty()) {
err = _u8L("empty component index");
err = "empty component index";
return false;
}
try {
const long val = std::stol(token);
if (val < 1) {
err = format(_u8L("component index must be >= 1 (got %1%)"), token);
err = "component index must be >= 1 (got " + token + ")";
return false;
}
components.push_back(static_cast<unsigned int>(val));
} catch (...) {
err = format(_u8L("invalid component index \"%1%\""), token);
err = "invalid component index \"" + token + "\"";
return false;
}
}
if (components.size() < 2) {
err = format(_u8L("at least 2 components required (got %1%)"), components.size());
err = "at least 2 components required (got " + std::to_string(components.size()) + ")";
return false;
}
std::set<unsigned int> seen;
for (unsigned int c : components) {
if (!seen.insert(c).second) {
err = format(_u8L("duplicate component index %1%"), c);
err = "duplicate component index " + std::to_string(c);
return false;
}
}
@@ -684,24 +682,24 @@ bool try_parse_mixed_ratios_strict(const std::string &str,
std::string token;
while (std::getline(ss, token, ',')) {
if (token.empty()) {
err = _u8L("empty ratio value");
err = "empty ratio value";
return false;
}
try {
const double val = std::stod(token);
if (!(val > 0.0)) {
err = format(_u8L("ratio must be positive (got %1%)"), token);
err = "ratio must be positive (got " + token + ")";
return false;
}
ratios.push_back(val);
} catch (...) {
err = format(_u8L("invalid ratio \"%1%\""), token);
err = "invalid ratio \"" + token + "\"";
return false;
}
}
if (ratios.size() != n_components) {
// TRN %1% is the expected number of ratios, %2% the number found.
err = format(_u8L("the ratio count must match the component count: expected %1%, got %2%"), n_components, ratios.size());
err = "expected " + std::to_string(n_components) + " ratio(s), got "
+ std::to_string(ratios.size());
return false;
}
return true;
@@ -715,11 +713,11 @@ bool validate_gradient_range_strict(const std::string &str, std::string &err)
CNumericLocalesSetter c_locale_setter;
float v0 = 0.f, v1 = 0.f;
if (std::sscanf(str.c_str(), "%f,%f", &v0, &v1) != 2) {
err = _u8L("expected two comma-separated floats, e.g. \"0.10,0.90\"");
err = "expected two comma-separated floats, e.g. \"0.10,0.90\"";
return false;
}
if (!(v0 > 0.f && v0 < 1.f && v1 > 0.f && v1 < 1.f)) {
err = _u8L("start and end ratios must be in (0, 1)");
err = "start and end ratios must be in (0, 1)";
return false;
}
return true;
@@ -773,7 +771,8 @@ static void check_mixed_array_size_required(std::map<std::string, std::string> &
{
if (actual_size != expected_size) {
append_error(errors, opt_key,
format(_u8L("array size %1% does not match filament slot count %2%"), actual_size, expected_size));
"array size " + std::to_string(actual_size)
+ " does not match filament slot count " + std::to_string(expected_size));
}
}
@@ -790,7 +789,7 @@ std::map<std::string, std::string> validate_mixed_filament_params(
if (has_mixed_sub_params_specified(comp_strs, ratio_strs, gradient_flags)
&& !has_any_mixed_filament(is_mixed)) {
append_error(errors, "filament_is_mixed",
_u8L("must be set when mixed filament parameters are specified"));
"must be set when mixed filament parameters are specified");
return errors;
}
@@ -823,33 +822,34 @@ std::map<std::string, std::string> validate_mixed_filament_params(
if (!is_mixed[i])
continue;
const size_t slot = i + 1;
const std::string slot = "slot " + std::to_string(i + 1);
const std::string comp_str = i < comp_strs.size() ? comp_strs[i] : "";
std::vector<unsigned int> components;
std::string comp_err;
if (!try_parse_mixed_components_strict(comp_str, components, comp_err)) {
// TRN Mixed filament validation error. %1% is the filament slot number, %2% the reason.
append_error(errors, "filament_mixed_components", format(_u8L("slot %1%: %2%"), slot, comp_err));
append_error(errors, "filament_mixed_components", slot + ": " + comp_err);
continue;
}
for (unsigned int c : components) {
if (c > num_physical) {
append_error(errors, "filament_mixed_components",
format(_u8L("slot %1%: component %2% out of range (max physical filament index is %3%)"),
slot, c, num_physical));
slot + ": component " + std::to_string(c)
+ " out of range (max physical filament index is "
+ std::to_string(num_physical) + ")");
break;
}
if (c == i + 1) {
append_error(errors, "filament_mixed_components",
format(_u8L("slot %1%: cannot reference itself as a component"), slot));
slot + ": cannot reference itself as a component");
break;
}
const size_t idx0 = static_cast<size_t>(c - 1);
if (idx0 < is_mixed.size() && is_mixed[idx0]) {
append_error(errors, "filament_mixed_components",
format(_u8L("slot %1%: component %2% references a mixed filament slot"), slot, c));
slot + ": component " + std::to_string(c)
+ " references a mixed filament slot");
break;
}
}
@@ -857,27 +857,27 @@ std::map<std::string, std::string> validate_mixed_filament_params(
std::string ratio_err;
const std::string ratio_str = i < ratio_strs.size() ? ratio_strs[i] : "";
if (!try_parse_mixed_ratios_strict(ratio_str, components.size(), ratio_err))
append_error(errors, "filament_mixed_sublayer_ratios", format(_u8L("slot %1%: %2%"), slot, ratio_err));
append_error(errors, "filament_mixed_sublayer_ratios", slot + ": " + ratio_err);
const bool gradient_on = i < gradient_flags.size() && gradient_flags[i];
if (gradient_on) {
if (components.size() != 2) {
append_error(errors, "filament_mixed_gradient",
format(_u8L("slot %1%: gradient requires exactly 2 components"), slot));
slot + ": gradient requires exactly 2 components");
}
if (gradient_specified) {
std::string range_err;
const std::string range_str = i < gradient_range_strs.size() ? gradient_range_strs[i] : "";
if (!validate_gradient_range_strict(range_str, range_err))
append_error(errors, "filament_mixed_gradient_range", format(_u8L("slot %1%: %2%"), slot, range_err));
append_error(errors, "filament_mixed_gradient_range", slot + ": " + range_err);
}
if (curve_specified) {
const std::string curve_str = i < gradient_curve_strs.size() ? gradient_curve_strs[i] : "";
if (!curve_str.empty() && parse_gradient_curve(curve_str).empty())
append_error(errors, "filament_mixed_gradient_curve",
format(_u8L("slot %1%: invalid curve (need at least 2 valid control points)"), slot));
slot + ": invalid curve (need at least 2 valid control points)");
}
}
}
+4 -6
View File
@@ -10,7 +10,6 @@
#include <string>
#include <math.h>
#include "PrintConfig.hpp"
#include "I18N.hpp"
// Mark string for localization and translate.
#define L(s) Slic3r::I18N::translate(s)
@@ -18,10 +17,10 @@
namespace Slic3r {
FlowErrorNegativeSpacing::FlowErrorNegativeSpacing() :
FlowError(L("Flow::spacing() produced negative spacing. Did you set some extrusion width too small?")) {}
FlowError("Flow::spacing() produced negative spacing. Did you set some extrusion width too small?") {}
FlowErrorNegativeFlow::FlowErrorNegativeFlow() :
FlowError(L("Flow::mm3_per_mm() produced negative flow. Did you set some extrusion width too small?")) {}
FlowError("Flow::mm3_per_mm() produced negative flow. Did you set some extrusion width too small?") {}
// This static method returns a sane extrusion width default.
float Flow::auto_extrusion_width(FlowRole role, float nozzle_diameter)
@@ -67,8 +66,7 @@ static inline FlowRole opt_key_to_flow_role(const std::string &opt_key)
static inline void throw_on_missing_variable(const std::string &opt_key, const char *dependent_opt_key)
{
// TRN %1% and %2% are names of settings.
throw FlowErrorMissingVariable((boost::format(L("Failed to calculate line width of %1%. Cannot get value of \"%2%\".")) % opt_key % dependent_opt_key).str());
throw FlowErrorMissingVariable((boost::format("Failed to calculate line width of %1%. Cannot get value of \u201c%2%\u201d.") % opt_key % dependent_opt_key).str());
}
// Used to provide hints to the user on default extrusion width values, and to provide reasonable values to the PlaceholderParser.
@@ -164,7 +162,7 @@ Flow Flow::with_spacing(float new_spacing) const
assert(m_width >= m_height);
out.m_width += new_spacing - m_spacing;
if (out.m_width < out.m_height)
throw Slic3r::InvalidArgument(L("Invalid spacing supplied to Flow::with_spacing(), check your layer height and extrusion width."));
throw Slic3r::InvalidArgument("Invalid spacing supplied to Flow::with_spacing(), check your layer height and extrusion width.");
}
out.m_spacing = new_spacing;
return out;
+2 -3
View File
@@ -4,7 +4,6 @@
#include "libslic3r/Utils.hpp"
#include "libslic3r/Point.hpp"
#include "libslic3r/Thread.hpp"
#include "libslic3r/I18N.hpp"
#include "STEP.hpp"
@@ -69,7 +68,7 @@ bool StepPreProcessor::preprocess(const char* path, std::string &output_path)
{
boost::nowide::ifstream infile(path);
if (!infile.good()) {
throw Slic3r::RuntimeError(_u8L("Load step file failed.\nCannot open file for reading.\n"));
throw Slic3r::RuntimeError(std::string("Load step file failed.\nCannot open file for reading.\n"));
return false;
}
@@ -117,7 +116,7 @@ bool StepPreProcessor::isUtf8File(const char* path)
{
boost::nowide::ifstream infile(path);
if (!infile.good()) {
throw Slic3r::RuntimeError(_u8L("Load step file failed.\nCannot open file for reading.\n"));
throw Slic3r::RuntimeError(std::string("Load step file failed.\nCannot open file for reading.\n"));
return false;
}
+30 -54
View File
@@ -987,7 +987,6 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
MetadataList metadata;
VolumeMetadataList volumes;
bool auto_drop { true };
};
struct CutObjectInfo
@@ -1368,7 +1367,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
bool _handle_start_text_configuration(const char** attributes, unsigned int num_attributes);
bool _handle_start_shape_configuration(const char **attributes, unsigned int num_attributes);
bool _create_object_instance(std::string const & path, int object_id, const Transform3d& transform, const bool printable, unsigned int recur_counter);
bool _create_object_instance(std::string const & path, int object_id, const Transform3d& transform, const bool printable, const bool auto_drop, unsigned int recur_counter);
void _apply_transform(ModelInstance& instance, const Transform3d& transform);
@@ -2260,8 +2259,6 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
if (obj_metadata != m_objects_metadata.end()) {
// config data has been found, this model was saved using slic3r pe
model_object->auto_drop = obj_metadata->second.auto_drop;
// apply object's name and config data
for (const Metadata& metadata : obj_metadata->second.metadata) {
if (metadata.key == "name")
@@ -4120,7 +4117,9 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
std::string path = bbs_get_attribute_value_string(attributes, num_attributes, PPATH_ATTR);
Transform3d transform = bbs_get_transform_from_3mf_specs_string(bbs_get_attribute_value_string(attributes, num_attributes, TRANSFORM_ATTR));
int printable = bbs_get_attribute_value_bool(attributes, num_attributes, PRINTABLE_ATTR);
return !m_load_model || _create_object_instance(path, object_id, transform, printable, 1);
int auto_drop = bbs_get_attribute_value_bool(attributes, num_attributes, AUTO_DROP_ATTR);
return !m_load_model || _create_object_instance(path, object_id, transform, printable, auto_drop, 1);
}
bool _BBS_3MF_Importer::_handle_end_item()
@@ -4348,7 +4347,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
return true;
}
bool _BBS_3MF_Importer::_create_object_instance(std::string const & path, int object_id, const Transform3d& transform, const bool printable, unsigned int recur_counter)
bool _BBS_3MF_Importer::_create_object_instance(std::string const & path, int object_id, const Transform3d& transform, const bool printable, const bool auto_drop, unsigned int recur_counter)
{
static const unsigned int MAX_RECURSIONS = 10;
@@ -4385,6 +4384,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
return false;
}
instance->printable = printable;
instance->auto_drop = auto_drop;
m_instances.emplace_back(instance, transform);
@@ -4417,6 +4417,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
return false;
}
instance->printable = printable;
instance->auto_drop = auto_drop;
m_instances.emplace_back(instance, transform);
}
@@ -4487,9 +4488,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
// Added because of github #3435, currently not used by PrusaSlicer
// int instances_count_id = bbs_get_attribute_value_int(attributes, num_attributes, INSTANCESCOUNT_ATTR);
ObjectMetadata metadata;
metadata.auto_drop = bbs_get_attribute_value_bool(attributes, num_attributes, AUTO_DROP_ATTR);
m_objects_metadata.insert({ object_id, std::move(metadata) });
m_objects_metadata.insert({ object_id, ObjectMetadata() });
m_curr_config.object_id = object_id;
return true;
}
@@ -6165,12 +6164,14 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
unsigned int id;
Transform3d transform;
bool printable;
bool auto_drop;
BuildItem(std::string const & path, unsigned int id, const Transform3d& transform, const bool printable)
BuildItem(std::string const & path, unsigned int id, const Transform3d& transform, const bool printable, const bool auto_drop)
: path(path)
, id(id)
, transform(transform)
, printable(printable)
, auto_drop(auto_drop)
{
}
};
@@ -6261,9 +6262,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
std::vector<std::string> const &targets = {},
std::vector<std::string> const &types = {},
PackingTemporaryData data = PackingTemporaryData(),
int export_plate_idx = -1,
bool plate_thumbnail_written = false,
bool plate_small_thumbnail_written = false) const;
int export_plate_idx = -1) const;
bool _add_model_file_to_archive(const std::string& filename, mz_zip_archive& archive, const Model& model, ObjectToObjectDataMap& objects_data, Export3mfProgressFn proFn = nullptr, BBLProject* project = nullptr) const;
bool _add_object_to_model_stream(mz_zip_writer_staged_context &context, ObjectData const &object_data) const;
void _add_object_components_to_stream(std::stringstream &stream, ObjectData const &object_data) const;
@@ -6473,11 +6472,6 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ":" <<__LINE__ << boost::format(",top&&pick thumbnails, count %1%")%top_thumbnail_data.size();
//BBS: add thumbnail for each plate
//ORCA: the relationships file points at plate 1's thumbnail for a whole-project export,
// otherwise at the exported plate's. Track whether that thumbnail was written.
const size_t rels_plate_idx = (export_plate_idx < 0) ? 0 : static_cast<size_t>(export_plate_idx);
bool rels_thumbnail_written = false;
bool rels_small_thumbnail_written = false;
if (!m_skip_static) {
std::vector<bool> thumbnail_status(plate_data_list.size(), false);
std::vector<bool> no_light_thumbnail_status(plate_data_list.size(), false);
@@ -6526,11 +6520,6 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ":" <<__LINE__ << boost::format(",add thumbnail %1%'s data into 3mf")%(index+1);
thumbnail_status[index] = true;
if (static_cast<size_t>(index) == rels_plate_idx) {
//ORCA: this call also writes the _small companion
rels_thumbnail_written = true;
rels_small_thumbnail_written = true;
}
}
}
@@ -6577,9 +6566,6 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ":" << __LINE__ << boost::format(", add thumbnail %1% from file %2% failed\n") % (i+1) %plate_data->thumbnail_file;
return false;
}
//ORCA: copied from file, so there is no _small companion for this plate
if (static_cast<size_t>(i) == rels_plate_idx)
rels_thumbnail_written = true;
}
if (!no_light_thumbnail_status[i] && !plate_data->no_light_thumbnail_file.empty() && (boost::filesystem::exists(plate_data->no_light_thumbnail_file))){
@@ -6874,7 +6860,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
// Adds relationships file ("_rels/.rels").
// The content of this file is the same for each OrcaSlicer 3mf.
// The relationshis file contains a reference to the geometry file "3D/3dmodel.model", the name was chosen to be compatible with CURA.
if (!_add_relationships_file_to_archive(archive, {}, {}, {}, temp_data, export_plate_idx, rels_thumbnail_written, rels_small_thumbnail_written)) {
if (!_add_relationships_file_to_archive(archive, {}, {}, {}, temp_data, export_plate_idx)) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ":" <<__LINE__ << boost::format(", _add_relationships_file_to_archive failed\n");
return false;
}
@@ -7049,8 +7035,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
}
bool _BBS_3MF_Exporter::_add_relationships_file_to_archive(
mz_zip_archive &archive, std::string const &from, std::vector<std::string> const &targets, std::vector<std::string> const &types, PackingTemporaryData data, int export_plate_idx,
bool plate_thumbnail_written, bool plate_small_thumbnail_written) const
mz_zip_archive &archive, std::string const &from, std::vector<std::string> const &targets, std::vector<std::string> const &types, PackingTemporaryData data, int export_plate_idx) const
{
std::stringstream stream;
stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
@@ -7061,9 +7046,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
if (export_plate_idx < 0) {
//use cover image if have
if (data._3mf_thumbnail.empty()) {
// ORCA: only reference the plate thumbnail if it was written
if (plate_thumbnail_written)
stream << " <Relationship Target=\"/Metadata/plate_1.png"
stream << " <Relationship Target=\"/Metadata/plate_1.png"
<< "\" Id=\"rel-2\" Type=\"http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail\"/>\n";
} else {
stream << " <Relationship Target=\"/" << xml_escape(data._3mf_thumbnail)
@@ -7071,24 +7054,22 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
}
if (data._3mf_printer_thumbnail_middle.empty()) {
if (plate_thumbnail_written)
stream << " <Relationship Target=\"/Metadata/plate_1.png"
<< "\" Id=\"rel-4\" Type=\"http://schemas.bambulab.com/package/2021/cover-thumbnail-middle\"/>\n";
stream << " <Relationship Target=\"/Metadata/plate_1.png"
<< "\" Id=\"rel-4\" Type=\"http://schemas.bambulab.com/package/2021/cover-thumbnail-middle\"/>\n";
} else {
stream << " <Relationship Target=\"/" << xml_escape(data._3mf_printer_thumbnail_middle)
<< "\" Id=\"rel-4\" Type=\"http://schemas.bambulab.com/package/2021/cover-thumbnail-middle\"/>\n";
}
if (data._3mf_printer_thumbnail_small.empty()) {
if (plate_small_thumbnail_written)
stream << "<Relationship Target=\"/Metadata/plate_1_small.png"
<< "\" Id=\"rel-5\" Type=\"http://schemas.bambulab.com/package/2021/cover-thumbnail-small\"/>\n";
stream << "<Relationship Target=\"/Metadata/plate_1_small.png"
<< "\" Id=\"rel-5\" Type=\"http://schemas.bambulab.com/package/2021/cover-thumbnail-small\"/>\n";
} else {
stream << " <Relationship Target=\"/" << xml_escape(data._3mf_printer_thumbnail_small)
<< "\" Id=\"rel-5\" Type=\"http://schemas.bambulab.com/package/2021/cover-thumbnail-small\"/>\n";
}
}
else if (plate_thumbnail_written) {
else {
//always use plate thumbnails
std::string thumbnail_file_str = (boost::format("Metadata/plate_%1%.png") % (export_plate_idx + 1)).str();
stream << " <Relationship Target=\"/" << xml_escape(thumbnail_file_str)
@@ -7098,11 +7079,9 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
stream << " <Relationship Target=\"/" << xml_escape(thumbnail_file_str)
<< "\" Id=\"rel-4\" Type=\"http://schemas.bambulab.com/package/2021/cover-thumbnail-middle\"/>\n";
if (plate_small_thumbnail_written) {
thumbnail_file_str = (boost::format("Metadata/plate_%1%_small.png") % (export_plate_idx + 1)).str();
stream << " <Relationship Target=\"/" << xml_escape(thumbnail_file_str)
<< "\" Id=\"rel-5\" Type=\"http://schemas.bambulab.com/package/2021/cover-thumbnail-small\"/>\n";
}
thumbnail_file_str = (boost::format("Metadata/plate_%1%_small.png") % (export_plate_idx + 1)).str();
stream << " <Relationship Target=\"/" << xml_escape(thumbnail_file_str)
<< "\" Id=\"rel-5\" Type=\"http://schemas.bambulab.com/package/2021/cover-thumbnail-small\"/>\n";
}
}
else if (targets.empty()) {
@@ -7411,7 +7390,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
// instance_id is just a 1 indexed index in build_items.
//assert(m_skip_static || curr_id == build_items.size() + 1);
build_items.emplace_back("", object_it->second.object_id, t, instance->printable);
build_items.emplace_back("", object_it->second.object_id, t, instance->printable, instance->auto_drop);
count++;
}
@@ -7861,7 +7840,8 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
stream << "\" " << PPATH_ATTR << "=\"" << xml_escape(item.path);
stream << "\" " << TRANSFORM_ATTR << "=\"";
add_transformation(stream, item.transform);
stream << "\" " << PRINTABLE_ATTR << "=\"" << item.printable << "\"/>\n";
stream << "\" " << PRINTABLE_ATTR << "=\"" << item.printable;
stream << "\" " << AUTO_DROP_ATTR << "=\"" << item.auto_drop << "\"/>\n";
}
stream << " </" << BUILD_TAG << ">\n";
@@ -8298,8 +8278,7 @@ bool _BBS_3MF_Exporter::_add_model_config_file_to_archive(mz_zip_archive& archiv
if (obj != nullptr) {
// Output of instances count added because of github #3435, currently not used by PrusaSlicer
//stream << " <" << OBJECT_TAG << " " << ID_ATTR << "=\"" << obj_metadata.first << "\" " << INSTANCESCOUNT_ATTR << "=\"" << obj->instances.size() << "\">\n";
stream << " <" << OBJECT_TAG << " " << ID_ATTR << "=\"" << object_data.object_id
<< "\" " << AUTO_DROP_ATTR << "=\"" << obj->auto_drop << "\">\n";
stream << " <" << OBJECT_TAG << " " << ID_ATTR << "=\"" << object_data.object_id << "\">\n";
// stores object's name
if (!obj->name.empty())
@@ -9776,10 +9755,7 @@ bool has_restore_data(std::string & path, std::string& origin)
origin = "<lock>";
return false;
}
// ORCA: non-throwing probes; ec is deliberately unread, a backup path that cannot be
// probed is treated as having no restore data rather than aborting the application.
boost::system::error_code ec;
if (boost::filesystem::exists(path + "/lock.txt", ec)) {
if (boost::filesystem::exists(path + "/lock.txt")) {
std::string pid;
load_string_file(path + "/lock.txt", pid);
try {
@@ -9794,10 +9770,10 @@ bool has_restore_data(std::string & path, std::string& origin)
}
}
std::string file3mf = path + "/.3mf";
if (!boost::filesystem::exists(file3mf, ec))
if (!boost::filesystem::exists(file3mf))
return false;
try {
if (boost::filesystem::exists(path + "/origin.txt", ec))
if (boost::filesystem::exists(path + "/origin.txt"))
load_string_file(path + "/origin.txt", origin);
}
catch (...) {
+2 -3
View File
@@ -4,7 +4,6 @@
#include "../libslic3r.h"
#include "../Model.hpp"
#include "../TriangleMesh.hpp"
#include "../I18N.hpp"
#include "svg.hpp"
#include "nanosvg/nanosvg.h"
@@ -144,11 +143,11 @@ bool get_svg_profile(const char *path, std::vector<Element_Info> &element_infos,
NSVGimage *svg_data = nullptr;
svg_data = nsvgParseFromFile(path, "mm", 96.0f);
if (svg_data == nullptr) {
message = _u8L("import svg failed: could not open svg.");
message = "import svg failed: could not open svg.";
return false;
}
if (svg_data->shapes == nullptr) {
message = _u8L("import svg failed: could not parse imported svg data.");
message = "import svg failed: could not parse imported svg data.";
return false;
}
+9 -13
View File
@@ -1979,7 +1979,7 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
if (gcodegen.writer().need_toolchange(extruder_id) || finish_layer) {
if (m_layer_idx < (int) m_tool_changes.size()) {
if (!(size_t(m_tool_change_idx) < m_tool_changes[m_layer_idx].size()))
throw Slic3r::RuntimeError(_(L("Wipe tower generation failed, possibly due to empty first layer.")));
throw Slic3r::RuntimeError("Wipe tower generation failed, possibly due to empty first layer.");
// Calculate where the wipe tower layer will be printed. -1 means that print z will not change,
// resulting in a wipe tower with sparse layers.
@@ -2018,7 +2018,7 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
if (gcodegen.writer().need_toolchange(extruder_id) || finish_layer) {
if (!(size_t(m_tool_change_idx) < m_tool_changes[m_layer_idx].size()))
throw Slic3r::RuntimeError(_(L("Wipe tower generation failed, possibly due to empty first layer.")));
throw Slic3r::RuntimeError("Wipe tower generation failed, possibly due to empty first layer.");
if (!ignore_sparse)
gcode += append_tcr(gcodegen, m_tool_changes[m_layer_idx][m_tool_change_idx++], extruder_id, wipe_tower_z);
@@ -2044,7 +2044,7 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
if (gcodegen.writer().need_toolchange(extruder_id) || finish_layer) {
if (!(size_t(m_tool_change_idx) < m_tool_changes[m_layer_idx].size()))
throw Slic3r::RuntimeError(_(L("Wipe tower generation failed, possibly due to empty first layer.")));
throw Slic3r::RuntimeError("Wipe tower generation failed, possibly due to empty first layer.");
if (!ignore_sparse) {
return false;
@@ -2792,13 +2792,11 @@ void GCode::do_export(Print* print, const char* path, GCodeProcessorResult* resu
m_processor.set_print(print);
GCodeOutputStream file(boost::nowide::fopen(path_tmp.c_str(), "wb"), m_processor);
if (! file.is_open()) {
// TRN %1% is a file path.
std::string err_msg = Slic3r::format(_(L("G-code export to %1% failed.\nCannot open the file for writing.")), path) + "\n";
std::string err_msg = std::string("G-code export to ") + path + " failed.\nCannot open the file for writing.\n";
BOOST_LOG_TRIVIAL(error) << err_msg << std::endl;
if (!fs::exists(folder)) {
//fs::create_directory(folder);
// TRN %1% is a folder path.
std::string add_err_msg = Slic3r::format(_(L("The folder %1% does not exist.")), folder.string());
std::string add_err_msg = "the parent path " + folder.string() +" is not there!!!";
BOOST_LOG_TRIVIAL(error) << add_err_msg << std::endl;
err_msg += add_err_msg;
}
@@ -2820,8 +2818,7 @@ void GCode::do_export(Print* print, const char* path, GCodeProcessorResult* resu
if (file.is_error()) {
file.close();
boost::nowide::remove(path_tmp.c_str());
// TRN %1% is a file path.
throw Slic3r::RuntimeError(Slic3r::format(_(L("G-code export to %1% failed.\nIs the disk full?")), path) + "\n");
throw Slic3r::RuntimeError(std::string("G-code export to ") + path + " failed\nIs the disk full?\n");
}
} catch (std::exception &ex) {
// Rethrow on any exception. std::runtime_exception and CanceledException are expected to be thrown.
@@ -2952,9 +2949,8 @@ void GCode::do_export(Print* print, const char* path, GCodeProcessorResult* resu
fire_lifecycle_event(LifecycleEvent::GCodeExportFinished, ctx);
}
throw Slic3r::RuntimeError(
// TRN %1% is the temporary file path, %2% the output file path, %3% the system error message.
Slic3r::format(_(L("Failed to rename the output G-code file from %1% to %2%.\nError: %3%\nIs %1% locked?")),
path_tmp, path, ret.message()) + '\n');
std::string("Failed to rename the output G-code file from ") + path_tmp + " to " + path + '\n' + "error code " + ret.message() + '\n' +
"Is " + path_tmp + " locked?" + '\n');
}
else {
BOOST_LOG_TRIVIAL(info) << boost::format("rename_file from %1% to %2% successfully")% path_tmp % path;
@@ -4165,7 +4161,7 @@ void GCode::_do_export(Print& print, GCodeOutputStream &file, ThumbnailsGenerato
auto [thumbnails, errors] = GCodeThumbnails::make_and_check_thumbnail_list(print.full_print_config());
if (errors != enum_bitmask<ThumbnailError>()) {
std::string error_str = _(L("Invalid thumbnails value:"));
std::string error_str = format("Invalid thumbnails value:");
error_str += GCodeThumbnails::get_error_string(errors);
throw Slic3r::ExportError(error_str);
}
+11 -11
View File
@@ -22,8 +22,6 @@
#include "libslic3r/Config.hpp"
#include "libslic3r/GCodeWriter.hpp"
#include "libslic3r/PrintConfig.hpp"
#include "libslic3r/I18N.hpp"
#include "libslic3r/format.hpp"
namespace Slic3r {
@@ -323,7 +321,8 @@ std::string AdaptivePAProcessor::validate_adaptive_pa_model(const std::string& m
// Only numbers, commas and dots are allowed (no letters or other characters)
for (char c : line) {
if (!std::isdigit(static_cast<unsigned char>(c)) && c != ',' && c != '.') {
return Slic3r::format(_u8L("Line %1%: only numbers, commas and dots are allowed"), line_number);
return "Line " + std::to_string(line_number) +
": only numbers, commas and dots are allowed";
}
}
@@ -334,7 +333,8 @@ std::string AdaptivePAProcessor::validate_adaptive_pa_model(const std::string& m
}
if (comma_count != 2) {
return Slic3r::format(_u8L("Line %1%: must contain exactly 3 comma-separated values (PA, flow, acceleration)"), line_number);
return "Line " + std::to_string(line_number) +
": must contain exactly 3 comma-separated values (PA, flow, acceleration)";
}
// Parse and validate the values
@@ -344,31 +344,31 @@ std::string AdaptivePAProcessor::validate_adaptive_pa_model(const std::string& m
// Parse PA
if (!std::getline(line_stream, value, ','))
return Slic3r::format(_u8L("Line %1%: missing PA value"), line_number);
return "Line " + std::to_string(line_number) + ": missing PA value";
double pa = std::stod(value);
// Parse flow
if (!std::getline(line_stream, value, ','))
return Slic3r::format(_u8L("Line %1%: missing flow value"), line_number);
return "Line " + std::to_string(line_number) + ": missing flow value";
double flow = std::stod(value);
// Parse acceleration
if (!std::getline(line_stream, value, ','))
return Slic3r::format(_u8L("Line %1%: missing acceleration value"), line_number);
return "Line " + std::to_string(line_number) + ": missing acceleration value";
double accel = std::stod(value);
// Validate constraints
if (pa >= 2.0) {
return Slic3r::format(_u8L("Line %1%: PA value must be less than 2"), line_number);
return "Line " + std::to_string(line_number) + ": PA value must be less than 2";
}
if (flow <= pa) {
return Slic3r::format(_u8L("Line %1%: flow value must be greater than PA value"), line_number);
return "Line " + std::to_string(line_number) + ": flow value must be greater than PA value";
}
if (accel <= flow) {
return Slic3r::format(_u8L("Line %1%: acceleration value must be greater than flow value"), line_number);
return "Line " + std::to_string(line_number) + ": acceleration value must be greater than flow value";
}
} catch (const std::exception&) {
return Slic3r::format(_u8L("Line %1%: invalid numeric value"), line_number);
return "Line " + std::to_string(line_number) + ": invalid numeric value";
}
}
+23 -25
View File
@@ -18,7 +18,6 @@
#include "libslic3r/ClipperUtils.hpp"
#include "libslic3r/LocalesUtils.hpp"
#include "libslic3r/format.hpp"
#include "libslic3r/I18N.hpp"
#include "libslic3r_version.h"
#include "GCodeProcessor.hpp"
@@ -1067,13 +1066,13 @@ void GCodeProcessor::run_post_process()
{
FilePtr in{ boost::nowide::fopen(m_result.filename.c_str(), "rb") };
if (in.f == nullptr)
throw Slic3r::RuntimeError(_u8L("G-code processor post-process export failed.\nCannot open file for reading.\n"));
throw Slic3r::RuntimeError(std::string("GCode processor post process export failed.\nCannot open file for reading.\n"));
// temporary file to contain modified gcode
std::string out_path = m_result.filename + ".postprocess";
FilePtr out{ boost::nowide::fopen(out_path.c_str(), "wb") };
if (out.f == nullptr)
throw Slic3r::RuntimeError(_u8L("G-code processor post-process export failed.\nCannot open file for writing.\n"));
throw Slic3r::RuntimeError(std::string("GCode processor post process export failed.\nCannot open file for writing.\n"));
std::vector<double> filament_mm(m_result.filaments_count, 0.0);
std::vector<double> filament_cm3(m_result.filaments_count, 0.0);
@@ -1468,10 +1467,10 @@ void GCodeProcessor::run_post_process()
// found an invalid value, clamp it to a valid one
tool_number = std::clamp<int>(0, m_filament_nozzle_temp.size() - 1, tool_number);
// emit warning
std::string warning = _u8L("The G-code post-processor encountered an invalid tool change, maybe from custom G-code:");
std::string warning = "GCode Post-Processor encountered an invalid toolchange, maybe from a custom gcode:";
warning += "\n> ";
warning += gcode_line;
warning += _u8L("Generated M104 lines may be incorrect.");
warning += "Generated M104 lines may be incorrect.";
BOOST_LOG_TRIVIAL(error) << warning;
// Orca todo
if (m_print != nullptr)
@@ -1713,7 +1712,7 @@ void GCodeProcessor::run_post_process()
for (;;) {
size_t cnt_read = ::fread(buffer.data(), 1, buffer.size(), in.f);
if (::ferror(in.f))
throw Slic3r::RuntimeError(_u8L("G-code processor post-process export failed.\nError while reading from file.\n"));
throw Slic3r::RuntimeError(std::string("GCode processor post process export failed.\nError while reading from file.\n"));
bool eof = cnt_read == 0;
auto it = buffer.begin();
auto it_bufend = buffer.begin() + cnt_read;
@@ -1878,9 +1877,8 @@ void GCodeProcessor::run_post_process()
}
if (rename_file(out_path, result_filename))
// TRN %1% is the temporary file path, %2% the output file path.
throw Slic3r::RuntimeError(Slic3r::format(_u8L("Failed to rename the output G-code file from %1% to %2%.\nIs %1% locked?"),
out_path, result_filename) + '\n');
throw Slic3r::RuntimeError(std::string("Failed to rename the output G-code file from ") + out_path + " to " + result_filename + '\n' +
"Is " + out_path + " locked?" + '\n');
}
// Additive second file-rewrite pass for the pre-heat/pre-cool injector. The single-pass
@@ -1981,12 +1979,12 @@ void GCodeProcessor::run_second_pass_injection()
FilePtr in{ boost::nowide::fopen(m_result.filename.c_str(), "rb") };
if (in.f == nullptr)
throw Slic3r::RuntimeError(_u8L("G-code processor pre-heat injection pass failed.\nCannot open file for reading.\n"));
throw Slic3r::RuntimeError(std::string("GCode processor pre-heat injection pass failed.\nCannot open file for reading.\n"));
const std::string out_path = m_result.filename + ".preheat";
FilePtr out{ boost::nowide::fopen(out_path.c_str(), "wb") };
if (out.f == nullptr)
throw Slic3r::RuntimeError(_u8L("G-code processor pre-heat injection pass failed.\nCannot open file for writing.\n"));
throw Slic3r::RuntimeError(std::string("GCode processor pre-heat injection pass failed.\nCannot open file for writing.\n"));
// The rewrite may shift byte positions (once the injector inserts lines), so rebuild lines_ends from scratch.
// With an empty map the scanned '\n' offsets reproduce the current lines_ends exactly.
@@ -2004,7 +2002,7 @@ void GCodeProcessor::run_second_pass_injection()
for (;;) {
size_t cnt_read = ::fread(buffer.data(), 1, buffer.size(), in.f);
if (::ferror(in.f))
throw Slic3r::RuntimeError(_u8L("G-code processor pre-heat injection pass failed.\nError while reading from file.\n"));
throw Slic3r::RuntimeError(std::string("GCode processor pre-heat injection pass failed.\nError while reading from file.\n"));
bool eof = cnt_read == 0;
auto it = buffer.begin();
auto it_bufend = buffer.begin() + cnt_read;
@@ -2055,9 +2053,8 @@ void GCodeProcessor::run_second_pass_injection()
handle_offsets_of_second_process(inserted_operation_lines);
if (rename_file(out_path, m_result.filename))
// TRN %1% is the temporary file path, %2% the output file path.
throw Slic3r::RuntimeError(Slic3r::format(_u8L("Failed to rename the output G-code file from %1% to %2%.\nIs %1% locked?"),
out_path, m_result.filename) + '\n');
throw Slic3r::RuntimeError(std::string("Failed to rename the output G-code file from ") + out_path + " to " + m_result.filename + '\n' +
"Is " + out_path + " locked?" + '\n');
}
// Every move whose gcode_id sits at or after an inserted line is pushed down by the running count of
@@ -3730,7 +3727,6 @@ void GCodeProcessor::reset()
m_detect_layer_based_on_tag = false;
m_seams_count = 0;
m_g29_time_added = false;
m_preheat_time = 0.f;
m_preheat_steps = 1;
}
@@ -3752,8 +3748,7 @@ DynamicConfig GCodeProcessor::export_config_for_render() const
config.set_key_value("filament_is_support", new ConfigOptionBools(m_parser.get_config().filament_is_support.values));
config.set_key_value("filament_type", new ConfigOptionStrings(m_parser.get_config().filament_type.values));
config.set_key_value("filament_map", new ConfigOptionInts(m_parser.get_config().filament_map.values));
// += clones the options; apply() would need a definition this config does not have.
config += m_belt_render_config;
config.apply(m_belt_render_config);
return config;
}
@@ -3946,7 +3941,7 @@ ConfigSubstitutions load_from_superslicer_gcode_file(const std::string& filename
key_value_pairs = ConfigBase::load_from_gcode_string_legacy(config, data.data(), substitutions_ctxt);
if (key_value_pairs < 80)
throw Slic3r::RuntimeError(format(_u8L("Suspiciously low number of configuration values extracted from %1%: %2%"), filename, key_value_pairs));
throw Slic3r::RuntimeError(format("Suspiciously low number of configuration values extracted from %1%: %2%", filename, key_value_pairs));
return std::move(substitutions_ctxt.substitutions);
}
@@ -6133,12 +6128,15 @@ void GCodeProcessor::process_G4(const GCodeReader::GCodeLine& line)
//BBS
void GCodeProcessor::process_G29(const GCodeReader::GCodeLine& line)
{
// Firmware may split one bed-leveling sequence across multiple G29 subcommands.
constexpr float g29_time = 260.0f;
const bool should_add_time = !s_IsBBLPrinter || m_measure_g29_time;
if (should_add_time && !m_g29_time_added) {
simulate_st_synchronize(g29_time);
m_g29_time_added = true;
//BBS: hardcode 260 seconds for G29
//Todo: use a machine related setting when we have second kind of BBL printer
const float value_s = 260.0;
if (s_IsBBLPrinter){
if(m_measure_g29_time)
simulate_st_synchronize(value_s);
}
else{
simulate_st_synchronize(value_s);
}
}
-1
View File
@@ -1280,7 +1280,6 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f;
bool m_detect_layer_based_on_tag {false};
int m_seams_count;
bool m_measure_g29_time {false};
bool m_g29_time_added {false};
bool m_single_extruder_multi_material;
float m_preheat_time;
int m_preheat_steps;
+19 -23
View File
@@ -673,7 +673,7 @@ static void refine_at_vertex(
}
}
// Records one extraction for the warnings: the type of a modifier with a discarded fragment, the
// Records one extraction for the warnings: the type of a modifier with a discarded fragment, and the
// evaluated/reached flags for "had no effect" (a discarded fragment counts as reached, a contact not).
static void record_extraction(PreciseSeamWarnings *warnings, const ModelVolume *modifier,
const SegmentExtraction &extracted)
@@ -685,10 +685,13 @@ static void record_extraction(PreciseSeamWarnings *warnings, const ModelVolume *
const auto it = warnings->modifier_usage.find(modifier);
if (it == warnings->modifier_usage.end())
return;
// Load before store: most calls find the flag already set, so shared cache lines stay clean.
PreciseSeamWarnings::ModifierUsage &usage = it->second;
PreciseSeamWarnings::set(usage.checked);
if (!extracted.segments.empty() || extracted.full_containment || extracted.discarded_fragments > 0)
PreciseSeamWarnings::set(usage.reached);
if (!usage.checked.load(std::memory_order_relaxed))
usage.checked.store(true, std::memory_order_relaxed);
const bool reached = !extracted.segments.empty() || extracted.full_containment || extracted.discarded_fragments > 0;
if (reached && !usage.reached.load(std::memory_order_relaxed))
usage.reached.store(true, std::memory_order_relaxed);
}
// Strong priority is per modifier, never a global maximum across different modifiers.
@@ -950,15 +953,22 @@ std::vector<WeakModifierSegment> collect_weak_modifier_segments(
const SegmentExtraction extracted = extract_perimeter_segments(prepared, it->second[layer_id], modifier_volume->type(), context);
record_extraction(warnings, modifier_volume, extracted);
const auto type = convert_weak_modifier_type(modifier_volume->type());
// Full containment works like seam painting all round: the whole perimeter takes the type.
// A perimeter left whole Blocked also gets a warning (see apply_weak_modifiers_to_perimeter()).
// Full containment works like seam painting: Enforced and Neutral type the whole perimeter;
// Blocked is skipped with a warning, since the seam cannot avoid the whole perimeter.
if (extracted.full_containment) {
result.push_back({type, Point(), PerimeterPosition{0, 0.}, Point(), PerimeterPosition{0, 0.}, true, modifier_volume});
if (type == EnforcedBlockedSeamPoint::Blocked) {
if (warnings)
PreciseSeamWarnings::mark(warnings->full_containment, modifier_volume->type());
continue;
}
WeakModifierSegment whole{type, Point(), PerimeterPosition{0, 0.}, Point(), PerimeterPosition{0, 0.}};
whole.whole_perimeter = true;
result.push_back(whole);
continue;
}
for (const PerimeterSegment &segment : extracted.segments) {
result.push_back({type, segment.polyline.points.front(), segment.begin,
segment.polyline.points.back(), segment.end, false, modifier_volume});
segment.polyline.points.back(), segment.end});
}
}
// Boundary insertion, refinement and last-write-wins priority use the established path.
@@ -969,8 +979,7 @@ void apply_weak_modifiers_to_perimeter(
const std::vector<WeakModifierSegment> &weak_segments,
PrintObjectSeamData::LayerSeams &result,
const SeamPlacerImpl::Perimeter &perimeter,
bool &some_point_enforced,
PreciseSeamWarnings *warnings)
bool &some_point_enforced)
{
// Get z-coordinate for unscaling boundary points
const float z_coord = result.points[perimeter.start_index].position.z();
@@ -1020,19 +1029,6 @@ void apply_weak_modifiers_to_perimeter(
some_point_enforced = true;
}
}
// Only the highest whole zone is in effect, and a higher band may still unblock part of it.
if (warnings == nullptr)
return;
const auto last_whole = std::find_if(weak_segments.rbegin(), weak_segments.rend(),
[](const WeakModifierSegment &segment) { return segment.whole_perimeter; });
if (last_whole == weak_segments.rend() || last_whole->type != EnforcedBlockedSeamPoint::Blocked)
return;
for (size_t i = perimeter.start_index; i < perimeter.end_index; ++i)
if (result.points[i].type != EnforcedBlockedSeamPoint::Blocked)
return;
if (const auto usage = warnings->modifier_usage.find(last_whole->modifier); usage != warnings->modifier_usage.end())
PreciseSeamWarnings::set(usage->second.fully_blocked);
}
// Restore precise seam positions that may have been modified
+10 -20
View File
@@ -49,20 +49,18 @@ struct PreciseSeamWarnings {
// Masks of the Precise Seam types that caused each warning reason, one bit per type (type_bit()).
// The user warning lists the types instead of naming modifiers.
std::atomic<unsigned> multiple_intersections{0}; // Center/Left/Right with several segments on a perimeter.
std::atomic<unsigned> full_containment{0}; // Skipped for a perimeter fully inside: Center/Left/Right.
std::atomic<unsigned> full_containment{0}; // Skipped for a perimeter fully inside: Center/Left/Right, Blocked.
std::atomic<unsigned> failed_types{0}; // Types with at least one discarded fragment.
std::atomic<size_t> failed_fragments{0}; // Total discarded fragments, for the log summary.
// Fragments saved by the rare-case fallback or accepted as contacts; log only, no user warning.
// Clipper is deterministic, so a prismatic model can repeat the same case on every layer.
std::atomic<size_t> recovered_fragments{0};
// Per-modifier flags for the "had no effect" and "covers an entire perimeter" warnings. Modifiers are
// registered before the parallel phase, so workers only set flags; unregistered ones (e.g. in tests)
// are not tracked.
// Per-modifier flags for the "had no effect" warning. Modifiers are registered before the parallel
// phase, so workers only set flags; unregistered ones (e.g. in tests) are not tracked.
struct ModifierUsage {
std::atomic<bool> checked{false}; // Extracted on at least one perimeter.
std::atomic<bool> reached{false}; // Gave a segment, full containment or a discarded fragment.
std::atomic<bool> fully_blocked{false}; // Seam Blocked whole zone in effect on a perimeter left Blocked.
std::atomic<bool> checked{false}; // Extracted on at least one perimeter.
std::atomic<bool> reached{false}; // Gave a segment, full containment or a discarded fragment.
};
std::unordered_map<const ModelVolume*, ModifierUsage> modifier_usage;
@@ -72,18 +70,13 @@ struct PreciseSeamWarnings {
assert(is_precise_seam(type));
return 1u << (int(type) - int(ModelVolumeType::PRECISE_SEAM_CENTER));
}
// Load before writing: most calls find the bit or flag already set, so shared cache lines stay clean.
// Load before fetch_or: most calls find the bit already set, so shared cache lines stay clean.
static void mark(std::atomic<unsigned> &mask, ModelVolumeType type)
{
const unsigned bit = type_bit(type);
if ((mask.load(std::memory_order_relaxed) & bit) == 0)
mask.fetch_or(bit, std::memory_order_relaxed);
}
static void set(std::atomic<bool> &flag)
{
if (!flag.load(std::memory_order_relaxed))
flag.store(true, std::memory_order_relaxed);
}
};
// Optional caller identity for concise diagnostics when an intersection is discarded.
@@ -146,10 +139,9 @@ struct WeakModifierSegment {
PerimeterPosition left_position; // Position on the source perimeter before insertion/refinement.
Point right_point; // Coordinates of right (last) point of segment
PerimeterPosition right_position; // Retained provenance, not an index into the modified polygon.
// Full containment of a weak modifier: the zone is the whole perimeter, without boundaries
// (the points and positions above are unused and nothing is inserted for it).
// Full containment of an Enforced or Neutral modifier: the zone is the whole perimeter, without
// boundaries (the points and positions above are unused and nothing is inserted for it).
bool whole_perimeter = false;
const ModelVolume *modifier = nullptr; // Source modifier, for the warnings.
};
// Collects the object's Precise Seam volumes: strong ones in priority order, weak ones in application
@@ -181,14 +173,12 @@ std::vector<WeakModifierSegment> collect_weak_modifier_segments(
PreciseSeamWarnings* warnings = nullptr);
// Retypes the candidates inside each zone in the given order (pass zones lowest priority first);
// sets some_point_enforced when an Enforced zone applies. When the whole perimeter ends up Blocked and
// the highest whole-perimeter zone is Blocked, flags that zone's modifier for the warning.
// sets some_point_enforced when an Enforced zone applies.
void apply_weak_modifiers_to_perimeter(
const std::vector<WeakModifierSegment> &weak_segments,
PrintObjectSeamData::LayerSeams &result,
const SeamPlacerImpl::Perimeter &perimeter,
bool &some_point_enforced,
PreciseSeamWarnings *warnings = nullptr);
bool &some_point_enforced);
// Restore precise seam positions that may have been modified by alignment
// Iterates through all perimeters and restores precise_seam_point positions
+20 -41
View File
@@ -608,7 +608,7 @@ void process_perimeter_polygon(const Polygon &orig_polygon, float z_coord, const
// Apply weak modifiers if no strong modifier was inserted
if (!inserted_seam_position.has_value() && !weak_segments.empty()) {
PreciseSeam::apply_weak_modifiers_to_perimeter(
weak_segments, result, perimeter, some_point_enforced, warnings);
weak_segments, result, perimeter, some_point_enforced);
}
if (some_point_enforced) {
@@ -896,15 +896,18 @@ struct SeamComparator {
return a.central_enforcer;
}
if (a.type != b.type) {
return a.type > b.type;
}
// Two Blocked points fall through like Neutral ones, so a perimeter blocked all round still gets a proper seam.
if (a.type == EnforcedBlockedSeamPoint::Enforced) {
return true;
}
if (a.type == EnforcedBlockedSeamPoint::Blocked) {
return false;
}
if (a.type != b.type) {
return a.type > b.type;
}
//avoid overhangs
if ((a.overhang > 0.0f || b.overhang > 0.0f)
&& abs(a.overhang - b.overhang) > (0.1f * a.perimeter.flow_width)) {
@@ -1657,42 +1660,18 @@ void SeamPlacer::init(const Print &print, std::function<void(void)> throw_if_can
parts.push_back((boost::format(_u8L("multiple intersections with a perimeter, only one was used (%1%)")) % type_list(mi)).str());
if (fc != 0)
parts.push_back((boost::format(_u8L("a perimeter is fully inside a modifier, the modifier was not applied to it (%1%)")) % type_list(fc)).str());
// Modifiers whose usage flags match, in print and volume order, so the named one is deterministic.
const auto collect_modifiers = [&print, &precise_seam_warnings](const auto &matches) {
std::vector<const ModelVolume*> found;
for (const PrintObject *po : print.objects())
for (const ModelVolume *volume : po->model_object()->volumes) {
const auto it = precise_seam_warnings.modifier_usage.find(volume);
if (it != precise_seam_warnings.modifier_usage.end() && matches(it->second) &&
std::find(found.begin(), found.end(), volume) == found.end())
found.push_back(volume);
}
return found;
};
// Seam Blocked modifiers whose whole perimeter stayed Blocked; the user warning names only the
// first one, the log lists them all.
const std::vector<const ModelVolume*> fully_blocked = collect_modifiers(
[](const PreciseSeam::PreciseSeamWarnings::ModifierUsage &usage) { return usage.fully_blocked.load(std::memory_order_relaxed); });
for (const ModelVolume *volume : fully_blocked)
BOOST_LOG_TRIVIAL(warning) << "[PreciseSeamFullyBlocked] object=\"" << volume->get_object()->name
<< "\" modifier=\"" << volume->name << "\"";
if (!fully_blocked.empty()) {
const ModelVolume *first = fully_blocked.front();
if (fully_blocked.size() == 1) {
// TRN: %1% is the modifier type "Seam Blocked" as in the menu, %2% the modifier name, %3% the object name.
parts.push_back((boost::format(_u8L("%1% modifier \"%2%\" of \"%3%\" covers an entire perimeter"))
% _u8L("Seam Blocked") % first->name % first->get_object()->name).str());
} else {
// TRN: %1% is the modifier type "Seam Blocked" as in the menu, %2% the modifier name, %3% the object name, %4% the number of modifiers.
parts.push_back((boost::format(_u8L("%1% modifier \"%2%\" of \"%3%\" (%4% in total) covers an entire perimeter"))
% _u8L("Seam Blocked") % first->name % first->get_object()->name % fully_blocked.size()).str());
}
}
// Modifiers evaluated somewhere that never reached a perimeter; never-evaluated ones are not reported.
const std::vector<const ModelVolume*> no_effect = collect_modifiers(
[](const PreciseSeam::PreciseSeamWarnings::ModifierUsage &usage) {
return usage.checked.load(std::memory_order_relaxed) && !usage.reached.load(std::memory_order_relaxed);
});
// Print and volume order make the named one deterministic; the log lists them all.
std::vector<const ModelVolume*> no_effect;
for (const PrintObject *po : print.objects())
for (const ModelVolume *volume : po->model_object()->volumes) {
const auto it = precise_seam_warnings.modifier_usage.find(volume);
if (it != precise_seam_warnings.modifier_usage.end() &&
it->second.checked.load(std::memory_order_relaxed) &&
!it->second.reached.load(std::memory_order_relaxed) &&
std::find(no_effect.begin(), no_effect.end(), volume) == no_effect.end())
no_effect.push_back(volume);
}
// The user warning names only the first one; the log lists them all.
for (const ModelVolume *volume : no_effect)
BOOST_LOG_TRIVIAL(warning) << "[PreciseSeamNoEffect] object=\"" << volume->get_object()->name
@@ -20,8 +20,6 @@
#include "libslic3r/Exception.hpp"
#include "libslic3r/GCode/PchipInterpolatorHelper.hpp"
#include "libslic3r/ExtrusionEntity.hpp"
#include "libslic3r/I18N.hpp"
#include "libslic3r/format.hpp"
#include "SmallAreaInfillFlowCompensator.hpp"
#include <boost/log/trivial.hpp>
@@ -57,8 +55,10 @@ SmallAreaInfillFlowCompensator::SmallAreaInfillFlowCompensator(const Slic3r::GCo
flowComps.push_back(std::stod(value_str));
}
} catch (...) {
// TRN %1% is the line of the model that could not be parsed.
throw Slic3r::InvalidArgument(Slic3r::format(_u8L("Small Area Flow Compensation: Error parsing data point in small area infill compensation model: %1%"), line) + "\n");
std::stringstream ss;
ss << "Small Area Flow Compensation: Error parsing data point in small area infill compensation model:" << line << std::endl;
throw Slic3r::InvalidArgument(ss.str());
}
}
}
@@ -66,26 +66,26 @@ SmallAreaInfillFlowCompensator::SmallAreaInfillFlowCompensator(const Slic3r::GCo
for (size_t i = 0; i < eLengths.size(); i++) {
if (i == 0) {
if (!nearly_equal(eLengths[i], 0.0)) {
throw Slic3r::InvalidArgument(_u8L("Small Area Flow Compensation: First extrusion length for small area infill compensation model must be 0"));
throw Slic3r::InvalidArgument("Small Area Flow Compensation: First extrusion length for small area infill compensation model must be 0");
}
} else {
if (nearly_equal(eLengths[i], 0.0)) {
throw Slic3r::InvalidArgument(_u8L("Small Area Flow Compensation: Only the first extrusion length for small area infill compensation model can be 0"));
throw Slic3r::InvalidArgument("Small Area Flow Compensation: Only the first extrusion length for small area infill compensation model can be 0");
}
if (eLengths[i] <= eLengths[i - 1]) {
throw Slic3r::InvalidArgument(_u8L("Small Area Flow Compensation: Extrusion lengths for subsequent points must be increasing"));
throw Slic3r::InvalidArgument("Small Area Flow Compensation: Extrusion lengths for subsequent points must be increasing");
}
}
}
for (size_t i = 1; i < flowComps.size(); ++i) {
if (flowComps[i] <= flowComps[i - 1]) {
throw Slic3r::InvalidArgument(_u8L("Small Area Flow Compensation: Flow compensation factors must strictly increase with extrusion length"));
throw Slic3r::InvalidArgument("Small Area Flow Compensation: Flow compensation factors must strictly increase with extrusion length");
}
}
if (!flowComps.empty() && !nearly_equal(flowComps.back(), 1.0)) {
throw Slic3r::InvalidArgument(_u8L("Small Area Flow Compensation: Final compensation factor for small area infill flow compensation model must be 1.0"));
throw Slic3r::InvalidArgument("Small Area Flow Compensation: Final compensation factor for small area infill flow compensation model must be 1.0");
}
flowModel = std::make_unique<PchipInterpolatorHelper>(eLengths, flowComps);
+3 -4
View File
@@ -5,7 +5,6 @@
#include "libslic3r/Config.hpp"
#include "libslic3r/enum_bitmask.hpp"
#include "format.hpp"
#include "libslic3r/I18N.hpp"
#include <boost/algorithm/string/case_conv.hpp>
#include <qoi/qoi.h>
@@ -611,11 +610,11 @@ std::string get_error_string(const ThumbnailErrors& errors)
std::string error_str;
if (errors.has(ThumbnailError::InvalidVal))
error_str += "\n - " + Slic3r::format(_u8L("Invalid input format. Expected vector of dimensions in the following format: \"%1%\""), "XxY/EXT, XxY/EXT, ...");
error_str += "\n - " + Slic3r::format("Invalid input format. Expected vector of dimensions in the following format: \"%1%\"", "XxY/EXT, XxY/EXT, ...");
if (errors.has(ThumbnailError::OutOfRange))
error_str += "\n - " + _u8L("Input value is out of range");
error_str += "\n - Input value is out of range";
if (errors.has(ThumbnailError::InvalidExt))
error_str += "\n - " + _u8L("Some extension in the input is invalid");
error_str += "\n - Some extension in the input is invalid";
return error_str;
}
+1 -1
View File
@@ -1646,7 +1646,7 @@ static FilamentGroupContext build_filament_group_context(
context.nozzle_info.extruder_nozzle_list = build_extruder_nozzle_list(context.nozzle_info.nozzle_list);
if (context.nozzle_info.nozzle_list.empty())
throw Slic3r::RuntimeError(_L("No valid nozzle found. Please check nozzle count."));
throw Slic3r::RuntimeError("No valid nozzle found. Please check nozzle count.");
if (!nozzle_status.empty())
context.nozzle_info.nozzle_status = nozzle_status;
+1 -11
View File
@@ -4,7 +4,6 @@
#include "WipeTower.hpp"
#include "WipeTower2.hpp"
#include "../Config.hpp"
#include "../FilamentMixer.hpp"
#include "../PrintConfig.hpp"
#include "../libslic3r.h"
@@ -75,19 +74,10 @@ Polygon estimate_wipe_tower_first_layer_outline(const ConfigBase &config, WipeTo
return WipeTower2::cone_base_polygon(width, depth, height, cone ? cone_angle->getFloat() : 0.);
}
WipeTowerFootprint estimate_wipe_tower_footprint(const ConfigBase &config, WipeTowerType tower_type, const std::vector<unsigned int> &filament_slots, double layer_height, double max_object_height)
WipeTowerFootprint estimate_wipe_tower_footprint(const ConfigBase &config, WipeTowerType tower_type, const std::vector<unsigned int> &filament_ids, double layer_height, double max_object_height)
{
WipeTowerFootprint footprint;
footprint.height = max_object_height;
// A mixed slot is virtual: the tool ordering resolves it to one of its physical components
// on every layer, with or without colour sublayers, so the tower only ever purges those.
// Validation passes the slots as Print::extruders() lists them; the GUI and CLI placement
// expand them beforehand, which repeating here leaves unchanged.
std::vector<unsigned int> filament_ids = filament_slots;
const auto *is_mixed_opt = dynamic_cast<const ConfigOptionBools *>(option_of(config, "filament_is_mixed"));
const auto *components_opt = dynamic_cast<const ConfigOptionStrings *>(option_of(config, "filament_mixed_components"));
if (is_mixed_opt != nullptr && components_opt != nullptr && has_any_mixed_filament(is_mixed_opt->values))
filament_ids = expand_mixed_filaments(filament_slots, is_mixed_opt->values, components_opt->values);
const size_t filaments_cnt = filament_ids.size();
if (filaments_cnt == 0 || layer_height < EPSILON)
return footprint;
@@ -34,8 +34,6 @@ Polygon estimate_wipe_tower_first_layer_outline(const ConfigBase &config, WipeTo
// filament_ids: 0-based filaments purged on the plate. The config cannot see custom G-code tool
// changes, so ids derived from the model must include them
// (Print::extruders(true)) or a real tower is sized as if it were never built.
// A mixed slot may be passed as itself or already expanded: it is sized as its
// physical components either way, since those are all the tower ever purges.
// layer_height: thinnest layer the objects are sliced at. The first layer is folded in here.
//
// A raft is deliberately not a reason: normalize_fdm_2 clears enable_prime_tower for a plate
+2 -4
View File
@@ -198,12 +198,10 @@ std::string imex_multicolor_block_reason(const std::string& parallel_mode,
// Filaments are numbered from 1 as the sidebar shows them, heads by their T index; the map
// decides which head a filament is on, so with MMU lanes the two numbers differ.
if (phys < 0)
// TRN %1% is a list of tools such as "T0/T1", %2% a filament number.
return (boost::format(L("In this Span mode, colors are printed only by %1%, but filament %2% isn't routed to any "
return (boost::format(L("In this Span mode only %1% print colors, but filament %2% isn't routed to any "
"tool. Use filaments routed to %1%, or switch this plate to Primary mode.")) %
tools % (filament + 1)).str();
// TRN %1% is a list of tools such as "T0/T1", %2% a filament number, %3% a tool number.
return (boost::format(L("In this Span mode, colors are printed only by %1%, but filament %2% is routed to T%3%. Use "
return (boost::format(L("In this Span mode only %1% print colors, but filament %2% is routed to T%3%. Use "
"filaments routed to %1%, or switch this plate to Primary mode.")) %
tools % (filament + 1) % phys).str();
}
+9 -8
View File
@@ -472,7 +472,7 @@ Model Model::read_from_file(const std::string&
boost::algorithm::iends_with(input_file, ".abc") || boost::algorithm::iends_with(input_file, ".ply")) {
std::string temp_stl = make_temp_stl_with_modelio(input_file);
if (temp_stl.empty()) {
throw Slic3r::RuntimeError(_L("Failed to convert asset to STL via ModelIO."));
throw Slic3r::RuntimeError("Failed to convert asset to STL via ModelIO.");
}
result = load_stl(temp_stl.c_str(), &model);
delete_temp_file(temp_stl);
@@ -1280,7 +1280,6 @@ ModelObject& ModelObject::assign_copy(const ModelObject &rhs)
this->layer_config_ranges = rhs.layer_config_ranges;
this->layer_height_profile = rhs.layer_height_profile;
this->printable = rhs.printable;
this->auto_drop = rhs.auto_drop;
this->origin_translation = rhs.origin_translation;
this->cut_id.copy(rhs.cut_id);
this->copy_transformation_caches(rhs);
@@ -1321,7 +1320,6 @@ ModelObject& ModelObject::assign_copy(ModelObject &&rhs)
this->layer_config_ranges = std::move(rhs.layer_config_ranges);
this->layer_height_profile = std::move(rhs.layer_height_profile);
this->printable = std::move(rhs.printable);
this->auto_drop = rhs.auto_drop;
this->origin_translation = std::move(rhs.origin_translation);
this->copy_transformation_caches(rhs);
@@ -1891,9 +1889,6 @@ void ModelObject::center_around_origin(bool include_modifiers)
void ModelObject::ensure_on_bed(bool allow_negative_z)
{
if (!auto_drop)
return;
double z_offset = 0.0;
if (allow_negative_z) {
@@ -1912,8 +1907,14 @@ void ModelObject::ensure_on_bed(bool allow_negative_z)
else
z_offset = -this->min_z();
if (z_offset != 0.0)
translate_instances(z_offset * Vec3d::UnitZ());
if (z_offset != 0.0) {
for (size_t i = 0; i < instances.size(); ++i) {
if (!instances[i]->auto_drop)
continue;
translate_instance(i, z_offset * Vec3d::UnitZ());
}
}
}
void ModelObject::translate_instances(const Vec3d& vector)
+6 -7
View File
@@ -400,9 +400,6 @@ public:
LayerHeightProfile layer_height_profile;
// Whether or not this object is printable
bool printable { true };
// Whether this object is snapped to the build plate after transformations.
// Instance Z offsets are shared by all instances of an object.
bool auto_drop { true };
// This vector holds position of selected support points for SLA. The data are
// saved in mesh coordinates to allow using them for several instances.
@@ -709,7 +706,7 @@ private:
Internal::StaticSerializationWrapper<ModelConfigObject const> config_wrapper(config);
Internal::StaticSerializationWrapper<LayerHeightProfile const> layer_heigth_profile_wrapper(layer_height_profile);
ar(name, module_name, input_file, instances, volumes, config_wrapper, layer_config_ranges, layer_heigth_profile_wrapper,
sla_support_points, sla_points_status, sla_drain_holes, printable, auto_drop, origin_translation, brim_points,
sla_support_points, sla_points_status, sla_drain_holes, printable, origin_translation, brim_points,
m_bounding_box_approx, m_bounding_box_approx_valid,
m_bounding_box_exact, m_bounding_box_exact_valid, m_min_max_z_valid,
m_raw_bounding_box, m_raw_bounding_box_valid, m_raw_mesh_bounding_box, m_raw_mesh_bounding_box_valid,
@@ -722,7 +719,7 @@ private:
// BBS: add backup, check modify
SaveObjectGaurd gaurd(*this);
ar(name, module_name, input_file, instances, volumes, config_wrapper, layer_config_ranges, layer_heigth_profile_wrapper,
sla_support_points, sla_points_status, sla_drain_holes, printable, auto_drop, origin_translation, brim_points,
sla_support_points, sla_points_status, sla_drain_holes, printable, origin_translation, brim_points,
m_bounding_box_approx, m_bounding_box_approx_valid,
m_bounding_box_exact, m_bounding_box_exact_valid, m_min_max_z_valid,
m_raw_bounding_box, m_raw_bounding_box_valid, m_raw_mesh_bounding_box, m_raw_mesh_bounding_box_valid,
@@ -1430,6 +1427,7 @@ public:
ModelInstanceEPrintVolumeState print_volume_state;
// Whether or not this instance is printable
bool printable;
bool auto_drop;
bool use_loaded_id_for_label {false};
int arrange_order = 0; // BBS
size_t loaded_id = 0; // BBS
@@ -1559,7 +1557,7 @@ private:
// Constructor, which assigns a new unique ID.
explicit ModelInstance(ModelObject* object)
: print_volume_state(ModelInstancePVS_Inside), printable(true), object(object), m_assemble_initialized(false)
: print_volume_state(ModelInstancePVS_Inside), printable(true), auto_drop(true), object(object), m_assemble_initialized(false)
{
assert(this->id().valid());
}
@@ -1570,6 +1568,7 @@ private:
, m_offset_to_assembly(other.m_offset_to_assembly)
, print_volume_state(ModelInstancePVS_Inside)
, printable(other.printable)
, auto_drop(other.auto_drop)
, object(object)
, m_assemble_initialized(false) { assert(this->id().valid() && this->id() != other.id()); }
@@ -1583,7 +1582,7 @@ private:
ModelInstance() : ObjectBase(-1), object(nullptr) { assert(this->id().invalid()); }
// BBS. Add added members to archive.
template<class Archive> void serialize(Archive& ar) {
ar(m_transformation, print_volume_state, printable, m_assemble_transformation, m_offset_to_assembly, m_assemble_initialized);
ar(m_transformation, print_volume_state, printable, auto_drop, m_assemble_transformation, m_offset_to_assembly, m_assemble_initialized);
}
};
+132 -133
View File
@@ -5,8 +5,6 @@
#include "PrintConfig.hpp"
#include "Point.hpp"
#include "Utils.hpp"
#include "I18N.hpp"
#include "format.hpp"
#include "libslic3r_version.h"
#include <cassert>
#include <boost/range/iterator_range_core.hpp>
@@ -385,7 +383,7 @@ namespace client
case TYPE_DOUBLE:
return expr(- this->d(), start_pos, this->it_range.end());
default:
this->throw_exception(L("Cannot apply unary minus operator."));
this->throw_exception("Cannot apply unary minus operator.");
}
assert(false);
// Suppress compiler warnings.
@@ -403,7 +401,7 @@ namespace client
case TYPE_DOUBLE:
return expr(static_cast<int>(this->d()), start_pos, this->it_range.end());
default:
this->throw_exception(L("Cannot convert to integer."));
this->throw_exception("Cannot convert to integer.");
}
assert(false);
// Suppress compiler warnings.
@@ -421,7 +419,7 @@ namespace client
case TYPE_DOUBLE:
return expr(static_cast<int>(std::round(this->d())), start_pos, this->it_range.end());
default:
this->throw_exception(L("Cannot round a non-numeric value."));
this->throw_exception("Cannot round a non-numeric value.");
}
assert(false);
// Suppress compiler warnings.
@@ -436,7 +434,7 @@ namespace client
case TYPE_DOUBLE:
return expr(static_cast<int>(std::floor(this->d())), start_pos, this->it_range.end());
default:
this->throw_exception(L("Cannot floor a non-numeric value."));
this->throw_exception("Cannot floor a non-numeric value.");
}
assert(false);
// Suppress compiler warnings.
@@ -451,7 +449,7 @@ namespace client
case TYPE_DOUBLE:
return expr(static_cast<int>(std::ceil(this->d())), start_pos, this->it_range.end());
default:
this->throw_exception(L("Cannot ceil a non-numeric value."));
this->throw_exception("Cannot ceil a non-numeric value.");
}
assert(false);
// Suppress compiler warnings.
@@ -467,7 +465,7 @@ namespace client
case TYPE_BOOL:
return expr(! this->b(), start_pos, this->it_range.end());
default:
this->throw_exception(L("Cannot apply a not operator."));
this->throw_exception("Cannot apply a not operator.");
}
assert(false);
// Suppress compiler warnings.
@@ -485,7 +483,7 @@ namespace client
// Conver the left hand side to string, append rhs.
this->set_s(this->to_string() + rhs.s());
} else {
const char *err_msg = L("Cannot add non-numeric types.");
const char *err_msg = "Cannot add non-numeric types.";
this->throw_if_not_numeric(err_msg);
rhs.throw_if_not_numeric(err_msg);
if (this->type() == TYPE_DOUBLE || rhs.type() == TYPE_DOUBLE)
@@ -503,7 +501,7 @@ namespace client
// Inside an if / else block to be skipped.
this->reset();
} else {
const char *err_msg = L("Cannot subtract non-numeric types.");
const char *err_msg = "Cannot subtract non-numeric types.";
this->throw_if_not_numeric(err_msg);
rhs.throw_if_not_numeric(err_msg);
if (this->type() == TYPE_DOUBLE || rhs.type() == TYPE_DOUBLE)
@@ -521,7 +519,7 @@ namespace client
// Inside an if / else block to be skipped.
this->reset();
} else {
const char *err_msg = L("Cannot multiply with non-numeric type.");
const char *err_msg = "Cannot multiply with non-numeric type.";
this->throw_if_not_numeric(err_msg);
rhs.throw_if_not_numeric(err_msg);
if (this->type() == TYPE_DOUBLE || rhs.type() == TYPE_DOUBLE)
@@ -539,10 +537,10 @@ namespace client
// Inside an if / else block to be skipped.
this->reset();
} else {
this->throw_if_not_numeric(L("Cannot divide a non-numeric type."));
rhs.throw_if_not_numeric(L("Cannot divide with a non-numeric type."));
this->throw_if_not_numeric("Cannot divide a non-numeric type.");
rhs.throw_if_not_numeric("Cannot divide with a non-numeric type.");
if (rhs.type() == TYPE_INT ? (rhs.i() == 0) : (rhs.d() == 0.))
rhs.throw_exception(L("Division by zero"));
rhs.throw_exception("Division by zero");
if (this->type() == TYPE_DOUBLE || rhs.type() == TYPE_DOUBLE)
this->set_d_lite(this->as_d() / rhs.as_d());
else
@@ -558,10 +556,10 @@ namespace client
// Inside an if / else block to be skipped.
this->reset();
} else {
this->throw_if_not_numeric(L("Cannot divide a non-numeric type."));
rhs.throw_if_not_numeric(L("Cannot divide with a non-numeric type."));
this->throw_if_not_numeric("Cannot divide a non-numeric type.");
rhs.throw_if_not_numeric("Cannot divide with a non-numeric type.");
if (rhs.type() == TYPE_INT ? (rhs.i() == 0) : (rhs.d() == 0.))
rhs.throw_exception(L("Division by zero"));
rhs.throw_exception("Division by zero");
if (this->type() == TYPE_DOUBLE || rhs.type() == TYPE_DOUBLE)
this->set_d_lite(std::fmod(this->as_d(), rhs.as_d()));
else
@@ -583,7 +581,7 @@ namespace client
if (self.type() != TYPE_EMPTY) {
// Not inside an if / else block to be skipped
if (self.type() != TYPE_BOOL)
self.throw_exception(L("Not a boolean expression"));
self.throw_exception("Not a boolean expression");
out = self.b();
}
}
@@ -592,7 +590,7 @@ namespace client
{
assert(self.type() != TYPE_EMPTY);
if (self.type() != TYPE_BOOL)
self.throw_exception(L("Not a boolean expression"));
self.throw_exception("Not a boolean expression");
out = self.b() ? "true" : "false";
}
@@ -624,7 +622,7 @@ namespace client
// Both type are bool.
if (op != '=')
boost::throw_exception(qi::expectation_failure<Iterator>(
lhs.it_range.begin(), rhs.it_range.end(), spirit::info(std::string("*") + L("Cannot compare the types."))));
lhs.it_range.begin(), rhs.it_range.end(), spirit::info("*Cannot compare the types.")));
value = lhs.b() == rhs.b();
} else if (lhs.type() == TYPE_STRING || rhs.type() == TYPE_STRING) {
// One type is string, the other could be converted to string.
@@ -632,7 +630,7 @@ namespace client
(op == '<') ? (lhs.to_string() < rhs.to_string()) : (lhs.to_string() > rhs.to_string());
} else {
boost::throw_exception(qi::expectation_failure<Iterator>(
lhs.it_range.begin(), rhs.it_range.end(), spirit::info(std::string("*") + L("Cannot compare the types."))));
lhs.it_range.begin(), rhs.it_range.end(), spirit::info("*Cannot compare the types.")));
}
lhs.reset();
lhs.set_b_lite(invert ? ! value : value);
@@ -647,7 +645,7 @@ namespace client
static void throw_if_not_numeric(const expr &param)
{
const char *err_msg = L("Not a numeric type.");
const char *err_msg = "Not a numeric type.";
param.throw_if_not_numeric(err_msg);
}
@@ -709,10 +707,10 @@ namespace client
return;
throw_if_not_numeric(param1);
if (param2.type() != TYPE_INT)
param2.throw_exception(L("digits: second parameter must be integer"));
param2.throw_exception("digits: second parameter must be integer");
bool has_decimals = param3.type() != TYPE_EMPTY;
if (has_decimals && param3.type() != TYPE_INT)
param3.throw_exception(L("digits: third parameter must be integer"));
param3.throw_exception("digits: third parameter must be integer");
char buf[256];
int ndigits = std::clamp(param2.as_i(), 0, 64);
@@ -736,7 +734,7 @@ namespace client
// One type is string, the other could be converted to string.
subject = &lhs.s();
} else {
lhs.throw_exception(L("Left hand side of a regex match must be a string."));
lhs.throw_exception("Left hand side of a regex match must be a string.");
}
try {
std::string pattern(++ rhs.begin(), -- rhs.end());
@@ -747,7 +745,7 @@ namespace client
} catch (SLIC3R_REGEX_NAMESPACE::regex_error &ex) {
// Syntax error in the regular expression
boost::throw_exception(qi::expectation_failure<Iterator>(
rhs.begin(), rhs.end(), spirit::info("*" + Slic3r::format(_u8L("Regular expression compilation failed: %1%"), ex.what()))));
rhs.begin(), rhs.end(), spirit::info(std::string("*Regular expression compilation failed: ") + ex.what())));
}
}
@@ -762,7 +760,7 @@ namespace client
// Inside an if / else block to be skipped
return;
if (subject.type() != TYPE_STRING)
subject.throw_exception(L("regex_replace() first parameter must be a string."));
subject.throw_exception("regex_replace() first parameter must be a string.");
try {
std::string re(++ pattern.begin(), -- pattern.end());
std::string result = SLIC3R_REGEX_NAMESPACE::regex_replace(subject.s(), SLIC3R_REGEX_NAMESPACE::regex(re), replacement.to_string());
@@ -770,7 +768,7 @@ namespace client
} catch (SLIC3R_REGEX_NAMESPACE::regex_error &ex) {
// Syntax error in the regular expression
boost::throw_exception(qi::expectation_failure<Iterator>(
pattern.begin(), pattern.end(), spirit::info("*" + Slic3r::format(_u8L("Regular expression compilation failed: %1%"), ex.what()))));
pattern.begin(), pattern.end(), spirit::info(std::string("*Regular expression compilation failed: ") + ex.what())));
}
}
@@ -786,15 +784,15 @@ namespace client
}
if (! out.b()) {
if (match.type() != TYPE_STRING)
match.throw_exception(L("one_of(): First parameter (the string to match against) has to be a string value"));
match.throw_exception("one_of(): First parameter (the string to match against) has to be a string value");
if (pattern.type() != TYPE_STRING)
match.throw_exception(L("one_of(): Pattern has to be a string value"));
match.throw_exception("one_of(): Pattern has to be a string value");
if (RegEx) {
try {
out.set_b(SLIC3R_REGEX_NAMESPACE::regex_match(match.s(), SLIC3R_REGEX_NAMESPACE::regex(pattern.s())));
} catch (SLIC3R_REGEX_NAMESPACE::regex_error &) {
// Syntax error in the regular expression
pattern.throw_exception(L("Regular expression compilation failed"));
pattern.throw_exception("Regular expression compilation failed");
}
} else
out.set_b(match.s() == pattern.s());
@@ -808,7 +806,7 @@ namespace client
}
if (! out.b()) {
if (match.type() != TYPE_STRING)
match.throw_exception(L("one_of(): First parameter (the string to match against) has to be a string value"));
match.throw_exception("one_of(): First parameter (the string to match against) has to be a string value");
regex_op(match, pattern, '=', out);
}
}
@@ -823,7 +821,7 @@ namespace client
value = (op == '|') ? (lhs.b() || rhs.b()) : (lhs.b() && rhs.b());
} else {
boost::throw_exception(qi::expectation_failure<Iterator>(
lhs.it_range.begin(), rhs.it_range.end(), spirit::info(std::string("*") + L("Cannot apply logical operation to non-boolean operands."))));
lhs.it_range.begin(), rhs.it_range.end(), spirit::info("*Cannot apply logical operation to non-boolean operators.")));
}
lhs.set_b_lite(value);
}
@@ -986,30 +984,30 @@ namespace client
opt = ctx->resolve_symbol(opt_key_str.substr(0, idx));
if (opt != nullptr) {
if (! opt->is_vector())
ctx->throw_exception(L("Trying to index a scalar variable"), opt_key);
ctx->throw_exception("Trying to index a scalar variable", opt_key);
char *endptr = nullptr;
idx = strtol(opt_key_str.c_str() + idx + 1, &endptr, 10);
if (endptr == nullptr || *endptr != 0)
ctx->throw_exception(L("Invalid vector index"), IteratorRange(opt_key.begin() + idx + 1, opt_key.end()));
ctx->throw_exception("Invalid vector index", IteratorRange(opt_key.begin() + idx + 1, opt_key.end()));
}
}
}
if (opt == nullptr)
ctx->throw_exception(ctx->skipping() ? L("Variable does not exist (in an inactive branch)") : L("Variable does not exist"), opt_key);
ctx->throw_exception(ctx->skipping() ? "Variable does not exist (in an inactive branch)" : "Variable does not exist", opt_key);
if (ctx->skipping())
return;
if (opt->is_scalar()) {
if (opt->is_nil())
ctx->throw_exception(L("Trying to reference an undefined (nil) optional variable"), opt_key);
ctx->throw_exception("Trying to reference an undefined (nil) optional variable", opt_key);
output = opt->serialize();
} else {
const ConfigOptionVectorBase *vec = static_cast<const ConfigOptionVectorBase*>(opt);
if (vec->empty())
ctx->throw_exception(L("Indexing an empty vector variable"), opt_key);
ctx->throw_exception("Indexing an empty vector variable", opt_key);
if (idx >= vec->size())
idx = 0;
if (vec->is_nil(idx))
ctx->throw_exception(L("Trying to reference an undefined (nil) element of vector of optional values"), opt_key);
ctx->throw_exception("Trying to reference an undefined (nil) element of vector of optional values", opt_key);
output = vec->vserialize()[idx];
}
}
@@ -1023,7 +1021,7 @@ namespace client
if (ctx->skipping() && ! ctx->check_inactive_names())
return;
const char *not_found = ctx->skipping() ? L("Variable does not exist (in an inactive branch)") : L("Variable does not exist");
const char *not_found = ctx->skipping() ? "Variable does not exist (in an inactive branch)" : "Variable does not exist";
std::string opt_key_str(opt_key.begin(), opt_key.end());
const ConfigOption *opt = ctx->resolve_symbol(opt_key_str);
if (opt == nullptr) {
@@ -1036,24 +1034,24 @@ namespace client
ctx->throw_exception(not_found, opt_key);
}
if (! opt->is_vector())
ctx->throw_exception(L("Trying to index a scalar variable"), opt_key);
ctx->throw_exception("Trying to index a scalar variable", opt_key);
const ConfigOption *opt_index = ctx->resolve_symbol(std::string(opt_vector_index.begin(), opt_vector_index.end()));
if (opt_index == nullptr)
ctx->throw_exception(not_found, opt_key);
if (opt_index->type() != coInt)
ctx->throw_exception(L("Indexing variable has to be integer"), opt_key);
ctx->throw_exception("Indexing variable has to be integer", opt_key);
if (ctx->skipping())
return;
const ConfigOptionVectorBase *vec = static_cast<const ConfigOptionVectorBase*>(opt);
if (vec->empty())
ctx->throw_exception(L("Indexing an empty vector variable"), opt_key);
ctx->throw_exception("Indexing an empty vector variable", opt_key);
int idx = opt_index->getInt();
if (idx < 0)
ctx->throw_exception(L("Negative vector index"), opt_key);
ctx->throw_exception("Negative vector index", opt_key);
if (idx >= (int)vec->size())
idx = 0;
if (vec->is_nil(idx))
ctx->throw_exception(L("Trying to reference an undefined (nil) element of vector of optional values"), opt_key);
ctx->throw_exception("Trying to reference an undefined (nil) element of vector of optional values", opt_key);
output = vec->vserialize()[idx];
}
@@ -1068,7 +1066,7 @@ namespace client
if (opt == nullptr) {
opt = ctx->resolve_output_symbol(key);
if (opt == nullptr)
ctx->throw_exception(L("Not a variable name"), opt_key);
ctx->throw_exception("Not a variable name", opt_key);
output.writable = true;
}
output.opt = opt;
@@ -1078,7 +1076,7 @@ namespace client
if (ctx->resolve_symbol(key) == nullptr && ctx->resolve_output_symbol(key) == nullptr &&
ctx->inactive_local_variables.count(key) == 0 &&
(ctx->context_data == nullptr || ctx->context_data->inactive_global_variables.count(key) == 0))
ctx->throw_exception(L("Not a variable name (in an inactive branch)"), opt_key);
ctx->throw_exception("Not a variable name (in an inactive branch)", opt_key);
}
output.it_range = opt_key;
}
@@ -1112,7 +1110,7 @@ namespace client
assert(opt.opt->is_scalar());
if (opt.opt->is_nil())
ctx->throw_exception(L("Trying to reference an undefined (nil) optional variable"), opt.it_range);
ctx->throw_exception("Trying to reference an undefined (nil) optional variable", opt.it_range);
switch (opt.opt->type()) {
case coFloat: output.set_d(opt.opt->getFloat()); break;
@@ -1139,7 +1137,7 @@ namespace client
for (;;) {
const ConfigOption *opt_parent = opt_def->ratio_over.empty() ? nullptr : ctx->resolve_symbol(opt_def->ratio_over);
if (opt_parent == nullptr)
ctx->throw_exception(L("FloatOrPercent variable failed to resolve the \"ratio_over\" dependencies"), opt.it_range);
ctx->throw_exception("FloatOrPercent variable failed to resolve the \"ratio_over\" dependencies", opt.it_range);
if (boost::ends_with(opt_def->ratio_over, "line_width")) {
// Line width supports defaults and a complex graph of dependencies.
assert(opt_parent->type() == coFloatOrPercent);
@@ -1161,7 +1159,7 @@ namespace client
break;
}
default:
ctx->throw_exception(L("Unsupported scalar variable type"), opt.it_range);
ctx->throw_exception("Unsupported scalar variable type", opt.it_range);
}
}
@@ -1175,7 +1173,7 @@ namespace client
assert(opt.opt->is_vector());
const ConfigOptionVectorBase* vec = static_cast<const ConfigOptionVectorBase*>(opt.opt);
if (vec->empty())
ctx->throw_exception(L("Indexing an empty vector variable"), opt.it_range);
ctx->throw_exception("Indexing an empty vector variable", opt.it_range);
// Helper to resolve a FloatOrPercent value (handles ratio_over chain for percent values).
// elem_index: the element index used to access this vector element, so that
@@ -1196,7 +1194,7 @@ namespace client
for (;;) {
const ConfigOption *opt_parent = opt_def->ratio_over.empty() ? nullptr : ctx->resolve_symbol(opt_def->ratio_over);
if (opt_parent == nullptr)
ctx->throw_exception(L("FloatOrPercent variable failed to resolve the \"ratio_over\" dependencies"), opt.it_range);
ctx->throw_exception("FloatOrPercent variable failed to resolve the \"ratio_over\" dependencies", opt.it_range);
if (boost::ends_with(opt_def->ratio_over, "line_width")) {
// Line width supports defaults and a complex graph of dependencies.
assert(opt_parent->type() == coFloatOrPercent);
@@ -1279,12 +1277,12 @@ namespace client
}
break;
}
default: ctx->throw_exception(L("Referencing a vector variable when scalar is expected"), opt.it_range);
default: ctx->throw_exception("Referencing a vector variable when scalar is expected", opt.it_range);
}
} else {
size_t idx = (opt.index < 0) ? 0 : (opt.index >= int(vec->size())) ? 0 : size_t(opt.index);
if (vec->is_nil(idx))
ctx->throw_exception(L("Trying to reference an undefined (nil) element of vector of optional values"), opt.it_range);
ctx->throw_exception("Trying to reference an undefined (nil) element of vector of optional values", opt.it_range);
switch (opt.opt->type()) {
case coFloats: output.set_d(static_cast<const ConfigOptionFloats*>(opt.opt)->values[idx]); break;
case coInts: output.set_i(static_cast<const ConfigOptionInts*>(opt.opt)->values[idx]); break;
@@ -1303,27 +1301,27 @@ namespace client
break;
}
default:
ctx->throw_exception(L("Unsupported vector variable type"), opt.it_range);
ctx->throw_exception("Unsupported vector variable type", opt.it_range);
}
}
}
static void check_writable(const MyContext *ctx, OptWithPos &opt) {
if (! opt.writable)
ctx->throw_exception(L("Cannot modify a read-only variable"), opt.it_range);
ctx->throw_exception("Cannot modify a read-only variable", opt.it_range);
}
static void check_numeric(const expr &param) {
if (! param.numeric_type())
param.throw_exception(L("Right side is not a numeric expression"));
param.throw_exception("Right side is not a numeric expression");
};
static size_t evaluate_count(const expr &expr_count) {
if (expr_count.type() != expr::TYPE_INT)
expr_count.throw_exception(L("Expected number of elements to fill a vector with."));
expr_count.throw_exception("Expected number of elements to fill a vector with.");
int count = expr_count.i();
if (count < 0)
expr_count.throw_exception(L("Negative number of elements specified."));
expr_count.throw_exception("Negative number of elements specified.");
return size_t(count);
};
@@ -1351,11 +1349,11 @@ namespace client
break;
case coBool:
if (rhs.type() != expr::TYPE_BOOL)
ctx->throw_exception(L("Right side is not a boolean expression"), rhs.it_range);
ctx->throw_exception("Right side is not a boolean expression", rhs.it_range);
static_cast<ConfigOptionBool*>(wropt)->value = rhs.b();
break;
default:
ctx->throw_exception(L("Unsupported output scalar variable type"), lhs.it_range);
ctx->throw_exception("Unsupported output scalar variable type", lhs.it_range);
}
}
@@ -1365,12 +1363,12 @@ namespace client
assert(lhs.opt->is_vector());
check_writable(ctx, lhs);
if (! lhs.has_index())
ctx->throw_exception(L("Referencing an output vector variable when scalar is expected"), lhs.it_range);
ctx->throw_exception("Referencing an output vector variable when scalar is expected", lhs.it_range);
ConfigOptionVectorBase *vec = const_cast<ConfigOptionVectorBase*>(static_cast<const ConfigOptionVectorBase*>(lhs.opt));
if (vec->empty())
ctx->throw_exception(L("Indexing an empty vector variable"), lhs.it_range);
ctx->throw_exception("Indexing an empty vector variable", lhs.it_range);
if (lhs.index >= int(vec->size()))
ctx->throw_exception(L("Index out of range"), lhs.it_range);
ctx->throw_exception("Index out of range", lhs.it_range);
switch (lhs.opt->type()) {
case coFloats:
check_numeric(rhs);
@@ -1389,11 +1387,11 @@ namespace client
break;
case coBools:
if (rhs.type() != expr::TYPE_BOOL)
ctx->throw_exception(L("Right side is not a boolean expression"), rhs.it_range);
ctx->throw_exception("Right side is not a boolean expression", rhs.it_range);
static_cast<ConfigOptionBools*>(vec)->values[lhs.index] = rhs.b();
break;
default:
ctx->throw_exception(L("Unsupported output vector variable type"), lhs.it_range);
ctx->throw_exception("Unsupported output vector variable type", lhs.it_range);
}
}
@@ -1416,7 +1414,7 @@ namespace client
break;
case coBools:
if (rhs_value.type() != expr::TYPE_BOOL)
rhs_value.throw_exception(L("Right side is not a boolean expression"));
rhs_value.throw_exception("Right side is not a boolean expression");
static_cast<ConfigOptionBools*>(opt)->values.assign(count, rhs_value.b());
break;
default: assert(false);
@@ -1441,10 +1439,10 @@ namespace client
if (ctx->skipping()) {
} else if (opt.opt->is_vector()) {
if (! opt.has_index())
ctx->throw_exception(L("Referencing a vector variable when scalar is expected"), opt.it_range);
ctx->throw_exception("Referencing a vector variable when scalar is expected", opt.it_range);
const ConfigOptionVectorBase *vec = static_cast<const ConfigOptionVectorBase*>(opt.opt);
if (vec->empty())
ctx->throw_exception(L("Indexing an empty vector variable"), opt.it_range);
ctx->throw_exception("Indexing an empty vector variable", opt.it_range);
output.set_b(static_cast<const ConfigOptionVectorBase*>(opt.opt)->is_nil(opt.index >= int(vec->size()) ? 0 : size_t(opt.index)));
} else {
assert(opt.opt->is_scalar());
@@ -1468,19 +1466,19 @@ namespace client
if (! ctx->skipping()) {
t_config_option_key key(std::string(it_range.begin(), it_range.end()));
if (const ConfigOption* opt = ctx->resolve_symbol(key); opt)
ctx->throw_exception(L("Symbol is already defined in read-only system dictionary"), it_range);
ctx->throw_exception("Symbol is already defined in read-only system dictionary", it_range);
if (ctx->config_outputs && ctx->config_outputs->optptr(key))
ctx->throw_exception(L("Symbol is already defined as system output variable"), it_range);
ctx->throw_exception("Symbol is already defined as system output variable", it_range);
bool has_global_dictionary = ctx->context_data != nullptr && ctx->context_data->global_config;
if (global_variable) {
if (! has_global_dictionary)
ctx->throw_exception(L("Global variables are not available in this context"), it_range);
ctx->throw_exception("Global variables are not available in this context", it_range);
if (ctx->config_local.optptr(key))
ctx->throw_exception(L("Variable name already defined in local scope"), it_range);
ctx->throw_exception("Variable name already defined in local scope", it_range);
out.opt = ctx->context_data->global_config->optptr(key);
} else {
if (has_global_dictionary && ctx->context_data->global_config->optptr(key))
ctx->throw_exception(L("Variable name already defined in global scope"), it_range);
ctx->throw_exception("Variable name already defined in global scope", it_range);
out.opt = ctx->config_local.optptr(key);
}
out.name = std::move(key);
@@ -1516,7 +1514,7 @@ namespace client
if (ctx->skipping()) {
} else if (lhs.opt) {
if (lhs.opt->is_vector())
rhs.throw_exception(L("Cannot assign a scalar value to a vector variable."));
rhs.throw_exception("Cannot assign a scalar value to a vector variable.");
OptWithPos lhs_opt{ lhs.opt, lhs.it_range, true };
scalar_variable_assign_scalar(ctx, lhs_opt, rhs);
} else {
@@ -1542,7 +1540,7 @@ namespace client
if (ctx->skipping()) {
} else if (lhs.opt) {
if (lhs.opt->is_scalar())
rhs_value.throw_exception(L("Cannot assign a vector value to a scalar variable."));
rhs_value.throw_exception("Cannot assign a vector value to a scalar variable.");
OptWithPos lhs_opt{ lhs.opt, lhs.it_range, true };
vector_variable_assign_expr_with_count(ctx, lhs_opt, rhs_count, rhs_value);
} else {
@@ -1568,7 +1566,7 @@ namespace client
if (! ctx->skipping()) {
check_writable(ctx, lhs);
if (lhs.opt->is_scalar())
rhs_value.throw_exception(L("Cannot assign a vector value to a scalar variable."));
rhs_value.throw_exception("Cannot assign a vector value to a scalar variable.");
vector_variable_assign_expr_with_count(ctx, lhs, rhs_count, rhs_value);
}
}
@@ -1597,13 +1595,13 @@ namespace client
// scalar_var = ()
// or
// scalar_var = ( scalar, scalar, ... )
ctx->throw_exception(L("Cannot assign a vector value to a scalar variable."), lhs.it_range);
ctx->throw_exception("Cannot assign a vector value to a scalar variable.", lhs.it_range);
}
auto check_numeric_vector = [](const std::vector<expr> &il) {
for (auto &i : il)
if (! i.numeric_type())
i.throw_exception(L("Right side is not a numeric expression"));
i.throw_exception("Right side is not a numeric expression");
};
ConfigOption *opt = const_cast<ConfigOption*>(lhs.opt);
@@ -1622,7 +1620,7 @@ namespace client
case coBools:
for (auto &i : il)
if (i.type() != expr::TYPE_BOOL)
i.throw_exception(L("Right side is not a boolean expression"));
i.throw_exception("Right side is not a boolean expression");
fill_vector_from_initializer_list<ConfigOptionBools>(opt, il, [](auto &v){ return v.b(); });
break;
default: assert(false);
@@ -1644,7 +1642,7 @@ namespace client
vector_variable_assign_initializer_list(ctx, lhs_opt, il);
} else {
if (il.empty())
ctx->throw_exception(L("Cannot create vector variable from an empty initializer list, because its type cannot be deduced."), lhs.it_range);
ctx->throw_exception("Cannot create vector variable from an empty initializer list, because its type cannot be deduced.", lhs.it_range);
// Allocate a new vector variable.
// First guesstimate type of the output vector.
size_t num_bool = 0;
@@ -1665,7 +1663,7 @@ namespace client
opt_new = std::make_unique<ConfigOptionStrings>();
else if (num_bool > 0) {
if (num_double + num_int > 0)
ctx->throw_exception(L("Right side is not valid: Mixing numeric and boolean types."), IteratorRange{ il.front().it_range.begin(), il.back().it_range.end() });
ctx->throw_exception("Right side is not valid: Mixing numeric and boolean types.", IteratorRange{ il.front().it_range.begin(), il.back().it_range.end() });
opt_new = std::make_unique<ConfigOptionBools>();
} else {
// Output is numeric.
@@ -1697,22 +1695,22 @@ namespace client
check_writable(ctx, lhs);
assert(lhs.opt->is_vector());
if (rhs.has_index() || ! rhs.opt->is_vector())
ctx->throw_exception(L("Cannot assign scalar to a vector"), lhs.it_range);
ctx->throw_exception("Cannot assign scalar to a vector", lhs.it_range);
if (rhs.opt->is_nil())
ctx->throw_exception(L("Some elements of the right hand side vector variable of optional values are undefined (nil)"), rhs.it_range);
ctx->throw_exception("Some elements of the right hand side vector variable of optional values are undefined (nil)", rhs.it_range);
if (lhs.opt->type() != rhs.opt->type()) {
// Vector types are not compatible.
switch (lhs.opt->type()) {
case coFloats:
ctx->throw_exception(L("Left hand side is a float vector, while the right hand side is not."), lhs.it_range);
ctx->throw_exception("Left hand side is a float vector, while the right hand side is not.", lhs.it_range);
case coInts:
ctx->throw_exception(L("Left hand side is an int vector, while the right hand side is not."), lhs.it_range);
ctx->throw_exception("Left hand side is an int vector, while the right hand side is not.", lhs.it_range);
case coStrings:
ctx->throw_exception(L("Left hand side is a string vector, while the right hand side is not."), lhs.it_range);
ctx->throw_exception("Left hand side is a string vector, while the right hand side is not.", lhs.it_range);
case coBools:
ctx->throw_exception(L("Left hand side is a bool vector, while the right hand side is not."), lhs.it_range);
ctx->throw_exception("Left hand side is a bool vector, while the right hand side is not.", lhs.it_range);
default:
ctx->throw_exception(L("Left hand side / right hand side vectors are not compatible."), lhs.it_range);
ctx->throw_exception("Left hand side / right hand side vectors are not compatible.", lhs.it_range);
}
}
const_cast<ConfigOption*>(lhs.opt)->set(rhs.opt);
@@ -1737,7 +1735,7 @@ namespace client
// Stop parsing, let the other rules resolve this case.
return false;
if (rhs.opt->is_nil())
ctx->throw_exception(L("Some elements of the right hand side vector variable of optional values are undefined (nil)"), rhs.it_range);
ctx->throw_exception("Some elements of the right hand side vector variable of optional values are undefined (nil)", rhs.it_range);
// Clone the vector variable.
std::unique_ptr<ConfigOption> opt_new;
if (one_of(rhs.opt->type(), { coFloats, coInts, coStrings, coBools }))
@@ -1745,7 +1743,7 @@ namespace client
else if (rhs.opt->type() == coPercents)
opt_new = std::make_unique<ConfigOptionFloats>(static_cast<const ConfigOptionPercents*>(rhs.opt)->values);
else
ctx->throw_exception(L("Duplicating this type of vector variable is not supported"), rhs.it_range);
ctx->throw_exception("Duplicating this type of vector variable is not supported", rhs.it_range);
const_cast<MyContext*>(ctx)->store_new_variable(lhs.name, std::move(opt_new), global_variable);
}
// Continue parsing.
@@ -1763,7 +1761,7 @@ namespace client
{
if (! ctx->skipping()) {
if (opt.has_index() || ! opt.opt->is_vector())
ctx->throw_exception(L("parameter of empty() is not a vector variable"), opt.it_range);
ctx->throw_exception("parameter of empty() is not a vector variable", opt.it_range);
out.set_b(static_cast<const ConfigOptionVectorBase*>(opt.opt)->size() == 0);
}
out.it_range = opt.it_range;
@@ -1773,7 +1771,7 @@ namespace client
{
if (! ctx->skipping()) {
if (opt.has_index() || ! opt.opt->is_vector())
ctx->throw_exception(L("parameter of size() is not a vector variable"), opt.it_range);
ctx->throw_exception("parameter of size() is not a vector variable", opt.it_range);
out.set_i(int(static_cast<const ConfigOptionVectorBase*>(opt.opt)->size()));
}
out.it_range = opt.it_range;
@@ -1785,7 +1783,7 @@ namespace client
{
if (expr_index.type() != expr::TYPE_EMPTY) {
if (expr_index.type() != expr::TYPE_INT)
expr_index.throw_exception(L("Non-integer index is not allowed to address a vector variable."));
expr_index.throw_exception("Non-integer index is not allowed to address a vector variable.");
output = expr_index.i();
}
}
@@ -1796,7 +1794,7 @@ namespace client
return;
if (ctx->context_data == nullptr)
ctx->throw_exception(L("Random number generator not available in this context."),
ctx->throw_exception("Random number generator not available in this context.",
IteratorRange(param1.it_range.begin(), param2.it_range.end()));
expr::random(param1, param2, ctx->context_data->rng);
}
@@ -1834,20 +1832,21 @@ namespace client
auto error_line = std::string(first, first_pos) + std::string(last, 0, last_pos);
// Position of the it_error from the start of its line.
auto error_pos = (it_error - it_begin) - first_pos;
msg += "Parsing error at line " + std::to_string(line_nr);
if (! info.tag.empty() && info.tag.front() == '*') {
// The gat contains an explanatory string.
// TRN Custom G-code error. %1% is the line number, %2% the reason.
msg += Slic3r::format(_u8L("Parsing error at line %1%: %2%"), line_nr, Slic3r::I18N::translate(info.tag.substr(1)));
msg += ": ";
msg += info.tag.substr(1);
} else {
auto it = tag_to_error_message.find(info.tag);
if (it == tag_to_error_message.end()) {
// A generic error report based on the nonterminal or terminal symbol name.
// TRN Custom G-code error. %1% is the line number, %2% the name of a grammar rule.
msg += Slic3r::format(_u8L("Parsing error at line %1%. Expecting tag %2%"), line_nr, info.tag);
msg += ". Expecting tag ";
msg += info.tag;
} else {
// Use the human readable error message.
// TRN Custom G-code error. %1% is the line number, %2% the reason.
msg += Slic3r::format(_u8L("Parsing error at line %1%. %2%"), line_nr, Slic3r::I18N::translate(it->second));
msg += ". ";
msg += it->second;
}
}
msg += '\n';
@@ -1878,15 +1877,15 @@ namespace client
static void init(const expr &x) {
if (x.type() != expr::TYPE_EMPTY) {
if (!x.numeric_type())
x.throw_exception(L("Interpolation value must be a number."));
x.throw_exception("Interpolation value must be a number.");
}
}
static void add_pair(const expr &x, const expr &y, InterpolateTableContext &table) {
if (x.type() != expr::TYPE_EMPTY) {
if (! x.numeric_type())
x.throw_exception(L("X value of a table point must be a number."));
x.throw_exception("X value of a table point must be a number.");
if (! y.numeric_type())
y.throw_exception(L("Y value of a table point must be a number."));
y.throw_exception("Y value of a table point must be a number.");
table.table.push_back({ x.as_d(), x.it_range, y.as_d() });
}
}
@@ -1903,7 +1902,7 @@ namespace client
double x1 = table.table[i].x;
if (x0 > x1)
boost::throw_exception(qi::expectation_failure(
table.table[i - 1].it_range_x.begin(), table.table[i].it_range_x.end(), spirit::info(std::string("*") + L("X coordinates of the table must be increasing"))));
table.table[i - 1].it_range_x.begin(), table.table[i].it_range_x.end(), spirit::info("X coordinates of the table must be increasing")));
if (! evaluated && x >= x0 && x <= x1) {
double y0 = table.table[i - 1].y;
double y1 = table.table[i].y;
@@ -1926,7 +1925,7 @@ namespace client
out.set_d(table.table.back().y);
else
// The value is really outside the table range.
expr_x.throw_exception(L("Interpolation value is outside the table range"));
expr_x.throw_exception("Interpolation value is outside the table range");
}
}
};
@@ -1940,30 +1939,30 @@ namespace client
// Table to translate symbol tag to a human readable error message.
std::map<std::string, std::string> MyContext::tag_to_error_message = {
{ "eoi", L("Unknown syntax error") },
{ "start", L("Unknown syntax error") },
{ "text", L("Invalid text.") },
{ "text_block", L("Invalid text block.") },
{ "macro", L("Invalid macro.") },
{ "repeat", L("Unknown syntax error") },
{ "if_else_output", L("Not an {if}{else}{endif} macro.") },
{ "switch_output", L("Not a {switch} macro.") },
{ "legacy_variable_expansion", L("Expecting a legacy variable expansion format") },
{ "identifier", L("Expecting an identifier.") },
{ "conditional_expression", L("Expecting a conditional expression.") },
{ "logical_or_expression", L("Expecting a boolean expression.") },
{ "logical_and_expression", L("Expecting a boolean expression.") },
{ "equality_expression", L("Expecting an expression.") },
{ "bool_expr_eval", L("Expecting a boolean expression.")},
{ "relational_expression", L("Expecting an expression.") },
{ "additive_expression", L("Expecting an expression.") },
{ "multiplicative_expression", L("Expecting an expression.") },
{ "unary_expression", L("Expecting an expression.") },
{ "optional_parameter", L("Expecting a closing brace or an optional parameter.") },
{ "one_of_list", L("Expecting a list of string patterns (simple text or regexp)") },
{ "variable_reference", L("Expecting a variable reference.")},
{ "variable", L("Expecting a variable name.")},
{ "regular_expression", L("Expecting a regular expression.")}
{ "eoi", "Unknown syntax error" },
{ "start", "Unknown syntax error" },
{ "text", "Invalid text." },
{ "text_block", "Invalid text block." },
{ "macro", "Invalid macro." },
{ "repeat", "Unknown syntax error" },
{ "if_else_output", "Not an {if}{else}{endif} macro." },
{ "switch_output", "Not a {switch} macro." },
{ "legacy_variable_expansion", "Expecting a legacy variable expansion format" },
{ "identifier", "Expecting an identifier." },
{ "conditional_expression", "Expecting a conditional expression." },
{ "logical_or_expression", "Expecting a boolean expression." },
{ "logical_and_expression", "Expecting a boolean expression." },
{ "equality_expression", "Expecting an expression." },
{ "bool_expr_eval", "Expecting a boolean expression."},
{ "relational_expression", "Expecting an expression." },
{ "additive_expression", "Expecting an expression." },
{ "multiplicative_expression", "Expecting an expression." },
{ "unary_expression", "Expecting an expression." },
{ "optional_parameter", "Expecting a closing brace or an optional parameter." },
{ "one_of_list", "Expecting a list of string patterns (simple text or rexep)" },
{ "variable_reference", "Expecting a variable reference."},
{ "variable", "Expecting a variable name."},
{ "regular_expression", "Expecting a regular expression."}
};
// For debugging the boost::spirit parsers. Print out the string enclosed in it_range.
@@ -2032,7 +2031,7 @@ namespace client
first = it;
return true;
err:
MyContext::throw_exception(L("Invalid utf8 sequence"), IteratorRange(first, last));
MyContext::throw_exception("Invalid utf8 sequence", IteratorRange(first, last));
return false;
}
@@ -2058,7 +2057,7 @@ namespace client
return false;
char c = *first;
if (it - first > 1 || c < 0)
MyContext::throw_exception(L("Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks."), IteratorRange(first, it));
MyContext::throw_exception("Non-ASCII7 characters are only allowed inside text blocks and string literals, not inside code blocks.", IteratorRange(first, it));
if (c == '\r' || c == '\n' || c == '\t' || c == ' ') {
// Skip the whitespaces
++ first;
@@ -2117,7 +2116,7 @@ namespace client
if (*it == '\\') {
if (++ it == end ||
(*it != 'r' && *it != 'n' && *it != '"' && *it != '\\'))
ctx->throw_exception(L("Invalid escape sequence"), {std::prev(it), std::next(it) });
ctx->throw_exception("Invalid escape sequence", {std::prev(it), std::next(it) });
++ len;
++ it;
} else {
+2 -116
View File
@@ -36,7 +36,6 @@
#include "Semver.hpp"
#include "PrintConfig.hpp"
#include "libslic3r_version.h"
#include "I18N.hpp"
#ifdef _MSC_VER
#define WIN32_LEAN_AND_MEAN
@@ -82,7 +81,6 @@
#include "LifecycleEvents.hpp"
#include "Utils.hpp"
#include "InstanceLock.hpp"
#include "nlohmann/json.hpp"
#include <sstream>
#include "PlaceholderParser.hpp"
@@ -2759,118 +2757,6 @@ void PresetCollection::update_after_user_presets_loaded()
return;
}
// A user preset file as written: it holds only the keys the preset sets itself, and an inherits that names a
// renamed parent by the old name the preset was made against. Throws if the file can not be read or parsed.
static json read_user_preset_file(const std::string &file)
{
boost::nowide::ifstream in(file);
return json::parse(in);
}
std::vector<LegacyUserFilamentPreset> PresetCollection::legacy_user_filament_presets(const std::map<std::string, std::vector<std::string>> &printers_by_parent)
{
auto has_entry = [&printers_by_parent](const std::string &name) { return printers_by_parent.count(name) > 0; };
std::vector<LegacyUserFilamentPreset> legacy_presets;
// The preset sync thread can add or delete presets meanwhile.
lock();
for (const Preset &preset : m_presets) {
if (!preset.is_user() || preset.inherits().empty())
continue;
const Preset *parent = get_preset_parent(preset);
if (parent == nullptr || !parent->is_system)
continue;
// An empty list already covers every printer.
const std::vector<std::string> &own = preset.config.option<ConfigOptionStrings>("compatible_printers")->values;
if (own.empty())
continue;
// The parent's name in the older release is its current name or one in its renamed_from, so only the
// files of presets whose parent has an entry under one of those are read.
if (!has_entry(parent->name) && std::none_of(parent->renamed_from.begin(), parent->renamed_from.end(), has_entry))
continue;
LegacyUserFilamentPreset legacy{preset.name, parent->name, {}, {}, preset.file, own};
try {
const json j = read_user_preset_file(preset.file);
// A preset whose file sets compatible_printers, even to an empty list, was given its printers on
// purpose and keeps exactly those.
if (j.contains("compatible_printers"))
continue;
legacy.inherits = j.value(BBL_JSON_KEY_INHERITS, std::string());
} catch (const std::exception &err) {
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": can not read " << preset.file << ": " << err.what();
continue;
}
auto it = printers_by_parent.find(legacy.inherits);
if (it == printers_by_parent.end())
continue;
for (const std::string &printer : it->second)
if (std::find(own.begin(), own.end(), printer) == own.end()) {
legacy.printers.push_back(printer);
legacy.compatible_printers.push_back(printer);
}
if (!legacy.printers.empty())
legacy_presets.push_back(std::move(legacy));
}
unlock();
return legacy_presets;
}
bool PresetCollection::write_legacy_user_filament_preset(const LegacyUserFilamentPreset &legacy)
{
// Only compatible_printers changes in the file. Saving the whole preset would also rewrite an inherits that
// names a renamed parent by its old name, the only name older releases know it by.
try {
json j = read_user_preset_file(legacy.file);
// Changed by hand or by another instance since the preset was found: a list of its own stands, and
// another parent would need other printers.
if (j.contains("compatible_printers") || j.value(BBL_JSON_KEY_INHERITS, std::string()) != legacy.inherits)
return false;
j["compatible_printers"] = legacy.compatible_printers;
if (const std::error_code ec = write_file_atomically(legacy.file, j.dump(1, '\t') + "\n")) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": failed to save " << legacy.file << ": " << ec.message();
return false;
}
} catch (const std::exception &err) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": can not migrate " << legacy.file << ": " << err.what();
return false;
}
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": user preset " << legacy.preset << " gets " << legacy.printers.size()
<< " printer(s) its parent listed in an older release";
return true;
}
void PresetCollection::apply_legacy_user_filament_presets(const std::vector<LegacyUserFilamentPreset> &written)
{
lock();
for (const LegacyUserFilamentPreset &legacy : written) {
auto it = this->find_preset_internal(legacy.preset);
if (it == m_presets.end() || it->name != legacy.preset)
continue; // deleted by the preset sync thread meanwhile
std::vector<std::string> &saved = it->config.option<ConfigOptionStrings>("compatible_printers", true)->values;
std::vector<std::string> &edited = m_edited_preset.config.option<ConfigOptionStrings>("compatible_printers", true)->values;
// Added to the list the preset holds now rather than replacing it: the cloud sync may have given the
// preset a newer list since it was found, and that list is still to be written out.
std::vector<std::string> printers = saved;
for (const std::string &printer : legacy.printers)
if (std::find(printers.begin(), printers.end(), printer) == printers.end())
printers.push_back(printer);
// A change to the list pending in the settings tab stays pending. Without one, the edited copy and the
// snapshot unsaved changes are measured against take the written list, so nothing reads as modified.
if (m_idx_selected == static_cast<size_t>(it - m_presets.begin()) && edited == saved) {
edited = printers;
if (m_saved_preset.name == it->name)
m_saved_preset.config.option<ConfigOptionStrings>("compatible_printers", true)->values = printers;
}
saved = printers;
// Push the change to the cloud copy, as an edit in the settings tab would. A sync already pending for
// the preset (a download waiting to be saved, a deletion) keeps its state.
if (!it->setting_id.empty() && it->sync_info.empty()) {
it->sync_info = "update";
it->save_info();
}
}
unlock();
}
//BBS: validate_preset
bool PresetCollection::validate_preset(const std::string &preset_name, std::string &inherit_name)
{
@@ -4754,10 +4640,10 @@ void PhysicalPrinterCollection::load_printers(
printer.loaded = true;
}
catch (const std::ifstream::failure& err) {
throw Slic3r::RuntimeError((boost::format(_u8L("The selected preset cannot be loaded: %1%\n\tReason: %2%")) % printer.file % err.what()).str());
throw Slic3r::RuntimeError(std::string("The selected preset cannot be loaded: ") + printer.file + "\n\tReason: " + err.what());
}
catch (const std::runtime_error& err) {
throw Slic3r::RuntimeError((boost::format(_u8L("Failed loading the preset file: %1%\n\tReason: %2%")) % printer.file % err.what()).str());
throw Slic3r::RuntimeError(std::string("Failed loading the preset file: ") + printer.file + "\n\tReason: " + err.what());
}
printers_loaded.emplace_back(printer);
}

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