diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..daeab9e7 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,16 @@ +version: 2 +updates: + + # Maintain GitHub Actions workflows + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" + time: "06:00" + timezone: "America/New_York" + groups: + actions: + patterns: + - "*" + commit-message: + prefix: "ci(deps)" diff --git a/Cargo.lock b/Cargo.lock index b143ebde..b3d82592 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -957,6 +957,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6128eabbfb98e5fe486fa7ee4413724e2a4ca908#6128eabbfb98e5fe486fa7ee4413724e2a4ca908" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "craft-zip" version = "0.1.0" @@ -4474,6 +4484,7 @@ dependencies = [ "craft-mesh", "craft-tcraft", "craft-usd", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6128eabbfb98e5fe486fa7ee4413724e2a4ca908)", "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", "exr", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 88936e5f..11a6b539 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -70,6 +70,8 @@ craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0 craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } +# Isolated aligned writer; existing archive readers retain their pin and behavior. +craft-zip-usdz = { package = "craft-zip", git = "https://github.com/storytold/craft-libs", rev = "6128eabbfb98e5fe486fa7ee4413724e2a4ca908" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "b952ca0231867c8ad6749ac44cab5fc903c3ad52", default-features = false, features = ["stl", "ply", "fbx", "obj"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } diff --git a/ROADMAP.md b/ROADMAP.md index 2bdd4861..759dfde7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,62 +1,243 @@ # TextureCraft roadmap -TextureCraft aims for 1:1 parity with Adobe Substance 3D Painter's texturing workflow, with better -performance, a smaller footprint, every feature drivable by agents (MCP, CLI, control channel), and -builds for Windows, macOS, Linux, FreeBSD and the web. +Stage: alpha (readiness assessment) · next: beta, ~75% readiness plus scoped compatibility and integration gates; remaining effort unestimated -## Honest parity estimate (2026-11-04) +> Last reviewed: 2026-11-16 · Last updated: 2026-11-16 · Change: major (UI/functionality audit, possible format/package reworks, unfinished `.mcmat` integration and incoming ArtCraft UI/shared-library work) · Target: reference app 12.2.0 -Weighted by how much of a professional's daily work each area carries. "Done" counts what works -end to end today (engine + UI + automation + tests), not what is planned. +TextureCraft is a clean-room implementation of the professional texture-painting workflow. This +assessment covers **main at [62b2b13](https://github.com/storytold/texturecraft/commit/62b2b13fdd32740b6e118cd00c5e0d0c12b30815), +version 0.6.1**, compared with the installed reference app on 2026-11-16. It follows the +[PhotoCraft roadmap format](https://github.com/storytold/photocraft/blob/main/ROADMAP.md). +Detail: [UI gaps and functional task audit](docs/ui-parity.md), [features](docs/features.md), [menu checklist](docs/parity.md), +[architecture](docs/architecture.md), [automation](docs/control-protocol.md), +[localization](docs/localization-parity.md), [releasing](docs/releasing.md). -| Area | Weight | Done | What works | Main gaps | +**Format direction:** `.tcraft` remains the native editable project format. Read-only opening/import +of `.spp` is a future compatibility goal: leave the source untouched and save converted work as +`.tcraft`. Supported versions, recoverable layers/resources and handling of unsupported content +still need investigation; no `.spp` reader is implemented. Writing `.spp`, round-tripping edits +back into it and compatibility with other proprietary asset/preset formats are outside this goal. +Pipeline exchange uses USD, glTF/GLB, MaterialX and texture maps. + +The current `.tcraft` schema/container and output-package contracts may be reworked; their +present implementations are not a frozen design. MaterialCraft `.mcmat` import remains a goal +whose next format is unfinished upstream. ArtCraft UI refactoring and further shared-library +adoption also add integration and regression work. These dependencies are part of the remaining +roadmap, even where a current task already passes. + +## Headline numbers + +| | Value | Kind | +|---|---|---| +| Feature breadth | ~80% (75–85%) | Estimated across feature families; no exhaustive target inventory | +| Ready for real work | ~60% (50–70%) | Estimated readiness of the assessed revision; no completion credit for incoming reworks/integrations | +| Mainstream practitioner | ~60% (50–70%) | Estimated for regular asset texturing, baking, masking and pipeline delivery | +| Essentials user | ~75% (65–85%) | Estimated for a simple mesh, layered materials/paint and texture export | +| Desktop menu catalog | 59/59 live | Observed through the running app; this is TextureCraft's own catalog | +| Engine commands | 178 registered | Observed through the running app; registration does not prove every parameter path | +| Functional review | 20 scoped check groups | UI, mixed-surface and command cases [recorded separately](docs/ui-parity.md#functional-task-audit); not an exhaustive coverage score | +| Remaining to beta | Unestimated | Requires acceptance tasks, performance budgets and a decision on required format/package/UI migrations | +| Remaining to full scoped parity | Unestimated | Includes possible `.tcraft`/output reworks, upstream `.mcmat`, ArtCraft UI/shared-library adoption, `.spp` feasibility and workflow/fidelity work | + +The former ~94% figure mostly counted implementation paths. This review also asks whether an +artist gets equivalent controls, predictable output, responsive interaction and dependable +delivery. The change is a measurement rebaseline and an expanded import goal, not a measured +loss of functionality. Percentages are rounded judgments; ranges express uncertainty, not +statistical confidence intervals. The old “~6 h + baking TBD” remainder is withdrawn: this +review provides no calibrated engineering or agent-hour forecast. + +The percentages describe behavior at `62b2b13`, not how much of a settled delivery plan is +finished. Potential rework can revisit working code and require repeating the checks below. +Its scope and cost are not yet measured, so remaining effort cannot be calculated as +100 minus the readiness score. Incoming upstream work is not counted as landed functionality. + +### Readiness by audience + +| Audience | Ready % | Hours to ~95% | Work that dominates | +|---|---|---|---| +| Full scoped target | ~60% | Unestimated | Workflow depth, format/output-package decisions, `.mcmat`, ArtCraft UI/shared libraries, bake/display fidelity, color management, read-only `.spp` and platform validation | +| Mainstream practitioner | ~60% | Unestimated | Reliable masks/painting, MaterialCraft exchange once its contract is ready, project/package compatibility, larger projects and destination-app checks | +| Essentials user | ~75% | Unestimated | Discoverable controls, predictable startup/GPU selection and save/reopen reliability retained through format/UI migrations | + +Why alpha. Mouse/keyboard tasks verified 3D/2D painting, undo/redo, material drag and drop, mask +and generator editing, UV rectangle fill, UI baking, native saving and texture export. Separate +command checks covered high-to-low transfer, UDIM sizes/packing and scene/material exports. +The interface is recognizably close in its painting, bake and export workspaces, but still lacks +mask-thumbnail effect menus, several fill controls and a MaterialX export option. +Generator depth is limited, bake equivalence is open, +and hardware/performance coverage is incomplete. There were **96 open issues** on the review date; +these include requests and older reports, not 96 reproduced defects. The published +[v0.6.1 release](https://github.com/storytold/texturecraft/releases/tag/v0.6.1) already exists; +“first release v0.1.0” is no longer an upcoming milestone. + +Native/output contracts and the future MaterialCraft, ArtCraft UI and shared-library integrations +also remain unsettled. Passing a legacy reader or a standalone export check does not complete +those future workflows. + +A proposed beta gate is ~75% readiness plus repeatable artist tasks on representative assets: +high/low baking and smart masks, precise 3D/2D painting, a multi-set UDIM project, save/reopen +without lost work, and exports checked in destination tools. Startup failures and data-loss +blockers on the supported test matrix must be resolved. This audit does not establish that gate. +Beta scope must identify which reworks/integrations it requires and which remain later goals. +Every adopted project/package version needs a compatibility policy and regression checks; +MaterialCraft exchange must be validated against a named producer/consumer version pair before +it is advertised as ready. + +## By dimension + +All percentages below are estimates. The weights sum to 100; their additive result is 59.1%, +rounded to ~60%. Hardware, performance and stability scores include confidence discounts for +incomplete validation; they are not measured success rates or speed comparisons. + +| Dimension | % ready | Weight | Hours to full | Evidence / remaining work | |---|---:|---:|---|---| -| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project (in the browser too, and before the tab closes), recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, **MaterialX import** (`file.importMaterialX`: a `.mtlx` material with `open_pbr_surface`, `standard_surface` or `gltf_pbr` becomes one fill layer with its textures and values), **PBR folder import** (`file.importPbrFolder`: a folder, zip or dropped files of albedo / roughness / metallic / normal (OpenGL or DirectX) / height / occlusion / emissive / opacity / packed ORM maps become one fill layer, with a dialog and an optional library copy), image resources, remove unused resources, textured OBJ (MTL), GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | -| Texture sets | 6 | 100% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile** whose filters and height slopes keep their size in UV space, one texture per tile at its own size, `$udim` export), list with visibility (show or hide all, invert, **focus** on one set), sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | — | -| Layer stack | 16 | 98% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels (with a histogram of its input), invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; effects **dragged to reorder**, duplicated, and **copied, cut and pasted** across layers, masks and sets (Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+D and Delete act on a selected effect); smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **30 library filters** (adjustments incl. histogram scan, range and shift, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | -| Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, material picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) | -| Materials and assets | 8 | 92% | **MaterialCraft materials** (`.mcmat`, sent to the shelf from MaterialCraft) as fill layers whose graph inputs and presets stay editable, re-cooked at the set's resolution with its baked mesh maps; 63 procedural materials (incl. car paint, velvet, brushed steel, skin, wax, ice, snow, bark), 21 smart materials, 24 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 23 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | -| Baking | 10 | 90% | All ten mesh-map bakers; low-poly and high-to-low baking with CPU/GPU tracing; mesh-name matching, backface filtering, custom and distance-based cages, frontal/rear distances and average normals; undoable 2D cage/skew painting saved per texture set; rectangular output, antialiasing, dilation/diffusion, ID sources, ray filters, AO attenuation/ground plane, curvature controls and map normalization; per-texture-set selection, progress/cancel and mesh-map import | Residual Painter map differences; reference validation for Height, Bent Normal and Opacity and across additional assets; 3D cage-editing overlay | -| Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser**; picks a discrete GPU on multi-GPU machines (`--gpu`, `WGPU_ADAPTER_NAME`, `WGPU_POWER_PREF`), and display textures are made on demand so a mesh with many materials imports on a small GPU | Hardware ray tracing | -| Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — | -| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, **colour space** of the colour maps (sRGB, Linear Rec.709, ACEScg, ACES2065-1; data maps never converted; the chosen space is recorded in the file as an ICC profile in PNG, JPEG, TIFF and WebP and as chromaticities in EXR), `$udim` tiles, **MaterialX** (`file.exportTextures` with `materialX`: a `.mtlx` OpenPBR material per set, `` aware), OBJ with MTL and maps, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | -| UI and UX | 8 | 97% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **History** panel that jumps to any step (back or forward), a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts, a compact color picker (saturation/value square, hue strip, copyable RGB); all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | -| Platforms | 4 | 76% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish | -| **Total** | **100** | **≈ 94%** | Weighted workflow-completion estimate | | +| Features (depth) | ~65% | 30 | TBD | Core editing tasks and high/low/UDIM outputs exercised; generators, properties and specialized workflows need depth. Mask anchors landed after this assessment; live UI validation remains | +| UI/UX fidelity | ~65% | 20 | TBD | Current editing/bake/export UI checked; [gaps](docs/ui-parity.md), ArtCraft UI adoption and revalidation after refactoring remain | +| File formats / interchange | ~60% | 10 | TBD | Current native save and basic exports exercised; possible `.tcraft`/output-package reworks, unfinished upstream `.mcmat`, `.spp` and consumer validation remain | +| Hardware (GPU, pen, displays) | ~50% | 8 | TBD | One Windows GPU exercised; pen tilt, pressure across platforms and display coverage remain incomplete | +| Localization | ~35% | 4 | TBD | Ten picker languages in source; optional shared catalogs/fonts and native-language review need current measurement | +| Performance | ~40% | 10 | TBD | Dirty-tile/budgeted architecture and benchmark code exist; no matched performance budgets or large-project results from this review | +| Stability | ~55% | 10 | TBD | Small save/reopen and undo/redo passed; recovery, large projects and long sessions need coverage, including after format/library migrations | +| Platforms | ~65% | 3 | TBD | Desktop/web build and packaging paths exist; this review ran Windows only | +| Automation / ecosystem | ~75% | 5 | TBD | 178 commands and CLI/control/MCP architecture; shared-library adoption, command/UI compatibility and the future MaterialCraft contract need integration checks | -Baking’s 90% estimates workflow completion: all ten map types and exposed settings have implementation -paths, with the remaining work listed above. Pixel-level equivalence with Painter remains unverified. +## Features -Beyond the reference app: every command is available to agents through MCP, the CLI and the app's -control channel (MCP workspace tools cover every file action: projects, meshes, high polys and -the cage, resources, smart materials, textures and mesh export), and the whole engine runs headless. +These are approximate depth/readiness estimates, not percentages of matching pixels or completed +menu entries. Feature rows overlap and are not an additional additive score. -## Remaining effort +| Area | % ready | Hours | What works / main gaps | +|---|---:|---|---| +| Projects and files | ~80% | TBD | Current `.tcraft` new/save/reopen passed with layers, effects and baked maps retained. Schema/container rework remains possible; versioning/migration policy and renewed persistence/recovery tests are needed if adopted. Large cases, Alembic HDF5 and animation remain open; PBR folder/ZIP/selected-file import landed after this assessment: `file.importPbrFolder` creates one fill layer from named maps, including packed ORM and OpenGL/DirectX normals, with a UI dialog and optional native library copy; it is not credited in this score | +| Texture sets and UDIM | ~80% | TBD | Two tiles exported at independent 128/256 px sizes with expected packed-channel values; 21 channel kinds in source. Many-set/many-tile production coverage remains untested | +| Layers, masks and effects | ~75% | TBD | UI fill/black-mask creation, generator editing/duplication and native persistence passed at the assessed revision. Mask-thumbnail context actions remain missing; effect renaming and mask-stack anchors landed afterward, with live UI validation still open | +| Painting and precise 2D work | ~70% | TBD | Mouse painting in both views, keyboard undo/redo, view shortcuts, brush gesture and UV-island rectangle fill passed. Nine tool kinds exist; brush feel, pressure/tilt, other tool task suites and complete trim sheets need validation | +| Generators and smart masks | ~45% | TBD | Seven generator kinds and 24 smart-mask presets; Position/global-balance editing worked in the UI. Shared adjustments, resolution and input slots exist; richer generators, micro-detail workflows and saving user smart masks remain incomplete | +| Materials and asset library | ~60% | TBD | 72 procedural materials and 21 smart materials; shelf search/drop worked. Legacy MaterialCraft paths exist, but the planned `.mcmat` contract is unfinished upstream. Library variety, previews and cross-app integration remain work | +| MaterialCraft `.mcmat` integration | Incomplete; upstream-dependent | TBD after contract | Current reader accepts legacy v1/v2. The proposed MaterialX-based v3 still needs upstream completion, shared-library support, TextureCraft mapping/UI and tests with real producer outputs; this is not a completed material exchange workflow | +| Baking | ~60% | TBD | All ten maps completed through the UI on CPU at 256 px and through commands on GPU at 128 px. Separate high/low normal/height transfer produced varying maps; cross-app pixel equivalence, larger assets and resolution-stable wear remain unproven | +| Viewport, shading and rendering | ~70% | TBD | PBR/IBL, extra shading lobes, 3D/2D views, displacement and CPU/GPU path-tracing paths. Matching material/display behavior, larger scenes and hardware ray tracing remain open | +| Color management | ~35% | TBD | Linear/sRGB handling, fixed export spaces and profile metadata; display model has Linear/ACES-filmic tone mapping. Configurable OCIO project/display workflows are absent | +| Texture and scene export | ~75% | TBD | Current PNG/UDIM/USD/GLB/MaterialX checks passed within scope. Output-package layout/content may be reworked; package contracts and consumers need separate validation. MaterialX UI output, complex materials and larger UDIM assets remain incomplete | +| Read-only `.spp` compatibility | 0% | TBD after feasibility study | Planned; no reader, version matrix or import-fidelity corpus. `.tcraft` remains the save format | +| Workspace, panels and preferences | ~65% | TBD | Current views/layouts checked; narrow labels truncate. Incoming ArtCraft UI refactoring/shared components can change these surfaces; task, shortcut, accessibility and layout/preferences persistence checks must be repeated | +| Automation | ~80% | TBD | Command inspection and scripted editing/export work; UI, CLI and MCP surfaces share engine commands. This review exercised the control channel and CLI, not every MCP/tool path | -Estimated in wall-clock hours of Claude Opus 5.5 agent work, with three or four agents working in -parallel on separate crates: +Source checks matter here: [generator kinds](crates/core/src/layer.rs) number seven even though +their shared controls have grown; [polygon fill](crates/engine/src/fill_mode.rs) already includes +triangle, polygon, UV-island and mesh modes. Current [MaterialCraft import](crates/formats/src/mcmat.rs) +accepts v2 and recognizes the newer source archive layout. That is legacy compatibility, not +completion of the next `.mcmat` integration. The [upstream v3 proposal](https://github.com/storytold/materialcraft/issues/190) +describes MaterialX plus resources in equivalent folder/ZIP deliveries and excludes native source. +Its proposed exposed controls differ from re-cooking an embedded authoring graph. The final +supported subset, version policy and authoring/re-cook workflow must be agreed and tested; +the legacy promise must not be carried forward automatically. -| Milestone | Scope | Estimate | -|---|---|---:| -| M1 Layer stack depth | Done | 0 h | -| M2 Tools | Pen tilt, and pen pressure on Linux, macOS and desktop browsers, once the windowing layer reports them | 0.5 h | -| M3 Assets | Done | 0 h | -| M4 Baking | Validate outputs across reference assets, refine remaining map differences and add 3D cage editing | TBD | -| M5 Viewport | Hardware ray tracing: wgpu's ray queries are experimental and need an `unsafe` opt-in, which the workspace forbids (owner decision) | 1.5 h | -| M6 Shader | Done | 0 h | -| M7 Formats | Done | 0 h | -| M8 UX | Native review of translations | 1 h | -| M9 Release | The twelve signing secrets and the Default runner group (org admin); first signed release run on every platform (v0.1.0); web deployment; Flathub submission | 3 h | -| **Total** | | **≈ 6 h + baking TBD** | +The [UI gap inventory](docs/ui-parity.md#missing-controls-and-workflows) records reproduction +routes and acceptance checks: mask context/save/export actions; independent U/V tiling, +filtering/wrap, physical-size and warp/per-tile projections; MaterialX UI output; +and configurable color-management settings. Generator depth and narrow-layout readability are +tracked as partial areas. Direct hardness/angle controls and polygon/UV rectangle fill already +exist; older reports must not turn them into fresh missing-feature claims. -## Current focus +### Evidence from this review -1. Release v0.1.0 (M9): CI (fmt, clippy, the full test suite, layering and wasm on Linux and - Windows) is green on `main`, and the `release` environment and branch ruleset exist. Left: an - org admin syncs the twelve signing secrets and checks the Default runner group - ([docs/releasing.md](docs/releasing.md)), then the first release run on every platform. -2. Hardware ray tracing in Rendering mode (M5) waits on an owner decision: wgpu exposes ray - queries only as an experimental feature behind an `unsafe` opt-in, and the workspace forbids - `unsafe` (craftrules allows it only in an isolated, tested helper crate). -3. Pen tilt, and pen pressure on Linux, macOS and desktop browsers (M2), once the windowing - layer reports them; Alembic files in the HDF5 container and Alembic animation. +| Check | Result and limit | +|---|---| +| Baseline/build | Fetched `origin/main`; HEAD matched `62b2b13`. `cargo build -p texturecraft -p texturecraft-cli --profile verify` passed; binary reported 0.6.1 and that revision | +| Reference UI/functionality | On an original UV cube, pointer painting, paint/fill/black-mask creation and an empty generator slot worked; seven-map self-bake at 1024 px completed. Inspected fill/projection/scale menus, mask menu and export dialog. The “Read only” title did not prevent these edits; reference save/export and output equivalence remain unchecked | +| TextureCraft UI tasks | Mouse/keyboard new project, 3D/2D strokes, Ctrl+Z/Y, F1/F2/F3, brush gesture, shelf search/drop, black mask, Position generator/global balance and effect duplication worked. UV rectangle fill wrote 88 tiles per channel and undo removed it | +| Persistence | Native UI save of the deeper four-layer case followed by command reopen preserved layers, effects, 21 painted tiles per channel and ten baked maps. Earlier command save/reopen also passed. UI-only open-dialog completion was not established | +| Bake | GPU command check: ten maps at 128 px / 16 rays. UI check: ten maps at 256 px, logged CPU. Separate CPU high/low check: normal and height varied on a two-triangle low plane / 1,152-triangle analytic high surface. No matched reference quality or timing comparison | +| UI texture export | Settings/template/list tabs inspected and Export clicked; eight 1024 px PNGs decoded successfully, and base color was inspected visually. All eight matched command export byte for byte from the same project/options. Creating/editing templates was not exercised | +| UDIM and channel packing | Two tiles exported at 128 and 256 px. Both ORM maps sampled RGB (255,153,51), matching AO 1, roughness 0.6 and metallic 0.2; this is a small command-only case | +| Interchange | Five 256 px OpenPBR PNGs plus parsed MaterialX XML; textured GLB and USDA reopened through TextureCraft's CLI with the original 12 triangles, 24 vertices and material. No external renderer/material equivalence checked | +| Layout | Whole-window PNGs inspected at 1920 × 1032 and 1280 × 800. Narrow layout retained both views and toolbar scroll controls, with severe layer-label truncation; no full narrow-window task suite or pixel-by-pixel UI score | +| Rework/upstream scope | Possible `.tcraft`/output-package reworks and incoming ArtCraft UI/shared-library work are planning inputs, not completed changes. The `.mcmat` v3 proposal and current legacy reader were reviewed; no future contract or current MaterialCraft producer/consumer pair was validated | +| Not run | Full Rust tests, clippy, wasm, other operating systems, pen/display hardware matrix, large UDIM projects, long sessions, matched performance benchmarks and reference image-difference corpus | + +## Languages + +The [picker](crates/ui-egui/src/i18n.rs) contains ten languages. Shared catalogs are optional at +build time; missing entries fall back to English, and builds without catalogs offer English only. +The older [coverage table](docs/localization-parity.md) predates catalog migration, so its “100%” +rows are not a current measurement. This audit ran an English build without external catalogs. + +| Language | Code | UI strings | Status | +|---|---|---|---| +| English | `en` | Source language | Exercised in this audit | +| Simplified Chinese | `zh-Hans` | Not remeasured | Catalog/font dependent; native review pending | +| Spanish | `es` | Not remeasured | Catalog dependent; native review pending | +| Hindi | `hi` | No picker entry | Not offered | +| Arabic | `ar` | Not remeasured | Catalog/font dependent; shaping/layout needs current review | +| French | `fr` | Not remeasured | Catalog dependent; native review pending | +| Portuguese (Brazil) | `pt-BR` | Not remeasured | Catalog dependent; native review pending | +| Indonesian | `id` | No picker entry | Not offered | +| Japanese | `ja` | Not remeasured | Catalog/font dependent; native review pending | +| German | `de` | Not remeasured | Catalog dependent; native review pending | +| Korean | `ko` | Not remeasured | Catalog/font dependent; native review pending | +| Vietnamese | `vi` | No picker entry | Not offered | + +Also in the picker: Italian (`it`), with catalog coverage and native review not remeasured. +Engine error details remain English; UI-key coverage alone would not establish full localization. + +## Upcoming + +These are acceptance-oriented work areas, not claims that their linked reports were reproduced +here. Open pull requests are not credited until merged into the assessed main revision. + +| Rank | Milestone | Estimate | +|---|---|---| +| 1 | Reliable startup and project safety across the supported GPU/platform matrix; reproduce startup/GPU reports and exercise recovery/large saves ([#541](https://github.com/storytold/texturecraft/issues/541), [#489](https://github.com/storytold/texturecraft/issues/489)) | TBD after reproduction | +| 2 | Define `.tcraft` and output-package direction, scope any reworks, and establish versioning, migration and producer/consumer acceptance cases | Unestimated; design scope open | +| 3 | Plan/adopt the incoming ArtCraft UI refactor and shared-library changes; preserve command reachability and repeat UI/persistence/platform checks after adoption | TBD after upstream contracts and consumer scope | +| 4 | Bring in the completed MaterialCraft `.mcmat` contract: agree the supported MaterialX/resources/controls subset, implement the consumer through shared APIs and validate folder/archive outputs from named versions | Upstream-dependent; format unfinished | +| 5 | Bake fidelity and dependable smart-material wear: matched assets/settings at multiple resolutions, all ten maps, high/low pairs and documented differences ([#536](https://github.com/storytold/texturecraft/issues/536), [#538](https://github.com/storytold/texturecraft/issues/538)) | TBD after map corpus | +| 6 | Generator, anchor and property depth; finish the artist-facing control inventory while preserving existing shared controls ([#374](https://github.com/storytold/texturecraft/issues/374), [#389](https://github.com/storytold/texturecraft/issues/389), [#433](https://github.com/storytold/texturecraft/issues/433)) | TBD after control audit | +| 7 | Brush/pen precision, feedback and discoverability; complete 3D/2D/trim-sheet tasks and set responsiveness budgets ([#545](https://github.com/storytold/texturecraft/issues/545), [#485](https://github.com/storytold/texturecraft/issues/485), [#306](https://github.com/storytold/texturecraft/issues/306)) | TBD after task tests | +| 8 | Color-managed pipeline and destination checks for USD, glTF/GLB, MaterialX and texture maps, including UDIM, complex materials and the adopted output packages | TBD after consumer matrix | +| 9 | Read-only `.spp` discovery: clean-room feasibility, recoverable data and unsupported-content reporting; convert into the adopted native format without changing the source | Unestimated; feasibility unknown | +| 10 | Release/platform regression checks, web polish, current translation coverage and native review; expand the original asset library | TBD after validation | + +### Dependencies and possible rework + +These tracks add discovery, migration, integration and repeated validation work. A possible +rework is not an approved replacement design, and an upstream proposal/merge is not proof of +TextureCraft adoption. + +| Track | Current state | Completion / revalidation gate | +|---|---|---| +| Native `.tcraft` | Current save/load works in the audit; schema/container may change | Decide the native contract and compatibility policy. For any adopted rework, check existing projects and conversion explicitly: layers, masks, effects, resources, painted tiles, UDIM layouts and baked data; retain bounded reads, atomic saves and recovery behavior | +| Output packages | Current individual exports work within the recorded scope; future package format/content/layout is not settled | Define affected artifacts, manifests, naming, resource references and versioning. Test package relocation, folder/archive delivery where applicable, color/normal/displacement metadata and real consumers; repeat install/update checks if distribution artifacts change | +| MaterialCraft `.mcmat` | Legacy v1/v2 support exists; [v3](https://github.com/storytold/materialcraft/issues/190) is unfinished upstream | Agree the published contract and supported MaterialX subset, folder/ZIP equivalence, resources and exposed inputs. Adopt it through shared libraries and test actual MaterialCraft output in TextureCraft, including unsupported versions/features. Do not assume native-source recovery or the legacy re-cook behavior | +| ArtCraft UI refactor | Incoming suite/UI work; shared palette/theme proposals such as [craft-libs #102](https://github.com/storytold/craft-libs/pull/102) and [#397](https://github.com/storytold/craft-libs/pull/397) are examples, not the whole refactor or an adoption claim | Scope TextureCraft's adapters/components and design changes. Keep document behavior command-driven; repeat the [UI task audit](docs/ui-parity.md), input/accessibility checks, screenshots and layout/preferences persistence tests against the adopted design | +| Shared libraries | Several shared crates are already pinned in [Cargo.toml](Cargo.toml); [format migration work](https://github.com/storytold/craft-libs/issues/778) continues | Use reviewed public APIs and keep app-specific mapping/policy local. Each adoption needs consumer integration plus compatibility, security-limit, layering, wasm and regression checks; a library change alone does not complete the app's work | + +### Current focus + +Keep the current functional baseline while establishing project-safety and bake-fidelity checks. +Scope `.tcraft`/output-package changes and coordinate ArtCraft UI/shared-library adoption alongside +that work, so feature work budgets include possible migration and revalidation. Bring `.mcmat` +forward against the finished upstream contract rather than treating the legacy reader as completion. +Run `.spp` feasibility separately. Hardware ray tracing is a later enhancement; beta depends on +the scoped acceptance/integration gates above. [Release validation](docs/releasing.md) continues +for existing releases; there is no outstanding “first release” gate. + +## Progress log + +| Date | Entry | +|---|---| +| 2026-11-16 | Added possible native/output-package reworks, unfinished MaterialCraft `.mcmat` integration and incoming ArtCraft UI/shared-library work as explicit roadmap tracks. Current audit scores stay tied to the tested revision; migration scope and effort remain unestimated | +| 2026-11-16 | Deeper UI/functionality audit added in [docs/ui-parity.md](docs/ui-parity.md): twenty check groups, specific missing controls, reference editing/self-bake, UI export/save, analytic high/low transfer and UDIM packing. Overall percentages remain provisional estimates | +| 2026-11-16 | Approximate live review against main `62b2b13` and reference 12.2.0. Basic edit/save/reopen, GPU bake and interchange smoke checks passed. Rebaselined reporting to ~80% breadth / ~60% readiness and recorded validation limits | +| 2026-11-16 | Scoped reference-project compatibility to future read-only `.spp`; retained `.tcraft` for editing/saving and open pipeline exports. No importer or other implementation change in this review | +| 2026-11-12 | v0.6.1 published; supersedes the former first-release v0.1.0 focus | +| 2026-11-04 | Previous roadmap reported ~94% weighted implementation/workflow completion; retained here as historical context, not a comparable readiness measurement | + +## Revision history + +| Date | Change | Summary | +|---|---|---| +| 2026-11-16 | major | Added dependency/rework scope and adoption gates; distinguished legacy `.mcmat` support from the unfinished MaterialX-based proposal; expanded upcoming work without crediting unlanded integrations | +| 2026-11-16 | major | Expanded live UI tasks and output validation; added a separate UI gap inventory with acceptance checks; distinguished UI, mixed and command evidence and CPU/GPU bake paths | +| 2026-11-16 | major | Adopted headline/audience/dimension/feature/language/upcoming tables; added main-revision evidence and uncertainty, read-only `.spp` scope, current release status and acceptance gates; removed the unsupported six-hour remainder | diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index d427988f..e38aac84 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -11,8 +11,8 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Generator, - GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, - blend3, lum, mix3, per_unit, + GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, MicroDetail, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, + blend1, blend3, lum, mix3, per_unit, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; @@ -205,6 +205,8 @@ enum Content<'a> { } struct EffectPlan<'a> { + /// The effect id (an anchor point records under it). + id: LayerId, kind: &'a EffectKind, blend: BlendMode, opacity: f32, @@ -212,6 +214,8 @@ struct EffectPlan<'a> { preview: bool, /// The curvature detail sizes a generator with detail reads. curvature_sizes: Option>, + /// A filtered mask stage retained because an anchor above it records that stage. + filtered_mask: Option<&'a Field>, } struct MaskPlan<'a> { @@ -231,6 +235,8 @@ pub struct Field { h: u32, comps: usize, data: Vec, + /// Intermediate mask stages needed by anchors, owned by this drawn layer's final field. + anchor_stages: Vec<(LayerId, Field)>, } impl Field { @@ -498,7 +504,7 @@ fn blur_rows(data: &mut [i64], w: usize, r: usize) { fn box_line(src: &[i64], dst: &mut [i64], r: usize) { let n = (2 * r + 1) as i64; - // Rounded division of a window sum + // Rounded division of a window sum. let avg = |acc: i64| (2 * acc + n).div_euclid(2 * n); let mut acc: i64 = src.iter().take(r + 1).sum(); for (i, d) in dst.iter_mut().enumerate() { @@ -597,13 +603,31 @@ fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: J } let mut previous: Option<(usize, Field)> = None; + let mut anchor_stages = Vec::new(); for (&filter, &margin) in filters.iter().zip(&margins) { let region = region_around(inp, tiles, margin)?; let start = previous.as_ref().map(|(index, field)| (*index, field)); let filtered = filter_region(inp, channels, below, id, job, effects, filter, region, start)?; + + // Preserve only stages with anchors before the next filter overwrites their value + if let Some((previous_index, previous_field)) = previous.take() + && matches!(job, Job::Mask(_)) + { + let mut visible = effects.iter().filter(|effect| effect.visible).skip(previous_index); + let previous_effect = visible.next(); + let records_anchor = visible.take(filter.0 - previous_index - 1).any(|effect| matches!(effect.kind, EffectKind::Anchor)); + if records_anchor && let Some(previous_effect) = previous_effect { + anchor_stages.push((previous_effect.id, previous_field)); + } + } + previous = Some((filter.0, filtered)); } - previous.map(|(_, field)| field) + + previous.map(|(_, mut field)| { + field.anchor_stages = anchor_stages; + field + }) } /// The tile-aligned texel region `(x0, y0, w, h)` around `tiles` plus `margin` tiles, clipped to the set. @@ -744,6 +768,7 @@ fn filter_region( let texture_set = inputs.project.texture_set(inputs.ts).map_or(inputs.tile_res(), |set| set.resolution); return generator_region(generator, blend, opacity, &stack_values, &cover, (region_x, region_y, width, height), (tile_resolution, texture_set)); } + let scaled_radius = neighbourhood_filters(effects, tile_resolution) .find(|filter| filter.0 == index) .map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32); @@ -769,6 +794,7 @@ fn filter_region( let result = match op { Op::Blur(Some(amount)) => original + amount * (original - blurred), Op::HighPass if component < 3 => original - blurred + middle * coverage, + // Away from 0 by at most the value itself: 0 at the edge, full inside Op::Bevel if component < 3 => original.signum() * original.abs().min((2.0 * blurred * original.signum() - original.abs()).max(0.0)), Op::Glow(amount) if component < 3 => original + amount * blurred, @@ -809,7 +835,7 @@ fn filter_region( } unpremultiply(&mut result, field_components); - Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result }) + Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result, anchor_stages: Vec::new() }) } /// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp) per texel, sizes in texels per side. @@ -1035,12 +1061,14 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y _ => None, }; EffectPlan { + id: effect.id, kind: &effect.kind, blend: effect.blend, opacity: effect.opacity, data: if effect.kind.painted() { tile_of(inp, image, tile_x, tile_y, channel) } else { None }, preview: previews(inp, target), curvature_sizes, + filtered_mask: None, } }) .collect() @@ -1073,9 +1101,15 @@ fn mask_plan<'a>(inp: &Inputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32 if !mask.enabled { return None; } + let background = if mask.background == MaskBackground::White { 1.0 } else { 0.0 }; - let effects = effect_plans(inp, &mask.effects, tx, ty, None); - let start = fields.and_then(|f| f.get(&FieldKey::Mask(id))).and_then(|field| neighbourhood(&mask.effects, inp.gbuf.width).map(|(k, _, _)| (k, field))); + let mut effects = effect_plans(inp, &mask.effects, tx, ty, None); + let filtered = fields.and_then(|fields| fields.get(&FieldKey::Mask(id))); + for effect in &mut effects { + effect.filtered_mask = filtered.and_then(|field| field.anchor_stages.iter().find(|(id, _)| *id == effect.id).map(|(_, field)| field)); + } + + let start = filtered.and_then(|field| neighbourhood(&mask.effects, inp.gbuf.width).map(|(index, _, _)| (index, field))); Some(MaskPlan { background, effects, start }) } @@ -1100,11 +1134,13 @@ fn plan_node<'a>( kids: bool, ) -> Option> { let own: &'a Layer = inp.project.layers.get(&id)?; - // Instances draw their source's content (a missing source draws nothing). + + // Instances draw their source's content (a missing source draws nothing) let layer: &'a Layer = inp.project.content_layer(id)?; if !own.visible { return None; } + let paint = matches!(layer.kind, LayerKind::Paint); let fx = !layer.is_group() && layer.content_effects.iter().any(|e| e.visible); let fx_start = if fx { neighbourhood(&layer.content_effects, inp.gbuf.width).map(|n| n.0) } else { None }; @@ -1115,6 +1151,7 @@ fn plan_node<'a>( if b.mode == BlendMode::Disable || b.opacity <= 0.0 { return None; } + let data = if paint { tile_of(inp, inp.pixels.layer(layer.id, *c), tx, ty, Some(*c)) } else { None }; let effects = if fx { effect_plans(inp, &layer.content_effects, tx, ty, Some(*c)) } else { Vec::new() }; let start = fx_start.zip(fields.and_then(|f| f.get(&FieldKey::Content(id, *c)))); @@ -1125,23 +1162,31 @@ fn plan_node<'a>( LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) }, LayerKind::Fill(f) => Content::Fill(f), LayerKind::Group { children, .. } => Content::Group(if kids { plan(inp, children, channels, tx, ty, depth + 1, fields) } else { Vec::new() }), - // `content_layer` already followed instance links. + + // `content_layer` already followed instance links LayerKind::Instance { .. } => return None, }; - // A paint layer with nothing painted (and not being painted) or added by its content - // effects contributes nothing. + let mask = layer_mask(inp.project, id).and_then(|m| mask_plan(inp, id, m, tx, ty, fields)); + + // Anchors in the mask record even where the layer draws nothing + let mask_anchor = mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| matches!(e.kind, EffectKind::Anchor))); + + // An empty paint layer still matters if its mask records an anchor if let Content::Paint { preview: false } = content && chans.iter().all(|c| c.data.is_none() && c.effects.is_empty()) + && !mask_anchor { return None; } - if chans.is_empty() { + + if chans.is_empty() && !mask_anchor { return None; } - let mask = layer_mask(inp.project, id).and_then(|m| mask_plan(inp, id, m, tx, ty, fields)); + let anchors = if fx { anchor_cuts(&layer.content_effects) } else { Vec::new() }; - let has_anchor = !anchors.is_empty() || matches!(&content, Content::Group(nodes) if nodes.iter().any(|n| n.has_anchor)); - // The geometry mask is the layer's own (an instance in another set has other parts). + let has_anchor = !anchors.is_empty() || mask_anchor || matches!(&content, Content::Group(nodes) if nodes.iter().any(|n| n.has_anchor)); + + // The geometry mask is the layer's own (an instance in another set has other parts) let parts = own.geometry_mask.as_ref().map(|names| inp.mesh.submeshes.iter().map(|s| names.contains(&s.name)).collect()); Some(Node { id, content, chans, mask, anchors, has_anchor, height_mask: layer.height_mask, parts }) } @@ -1379,33 +1424,39 @@ impl<'a, 'b> Texel<'a, 'b> { let rgb = [sum[0], sum[1], sum[2]]; match kind { ChannelKind::Color if image.srgb => rgb.map(texturecraft_texel::srgb_to_linear), + // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips ChannelKind::NormalMap if *normal_format == NormalFormat::DirectX => [rgb[0], 1.0 - rgb[1], rgb[2]], ChannelKind::Color | ChannelKind::NormalMap => rgb, + // A one-value channel or mask reads the image's gray, so a color image works as a mask ChannelKind::Scalar => [lum(rgb); 3], ChannelKind::Signed => [lum(rgb) * 2.0 - 1.0; 3], } } - Source::Anchor { anchor, channel } => { - // An anchor not evaluated yet (above this layer, hidden) reads the channel default - let anchored = self.anchors.iter().rev().find(|(id, _)| id == anchor).and_then(|(_, values)| values.get(channel.index()).copied()); - let value = anchored.unwrap_or_else(|| channel.default_value()); - let gray = matches!(channel.kind(), ChannelKind::Color | ChannelKind::NormalMap) && matches!(kind, ChannelKind::Scalar | ChannelKind::Signed); - if gray { [lum(value); 3] } else { value } - } + Source::Anchor { anchor, channel } => self.anchor_value(*anchor, *channel, kind), } } - /// The generator's ramp at this texel, before its global blur, balance, contrast and invert. + /// The value anchor point `anchor` recorded for `channel`, read as `kind` (colors read as gray + /// where a scalar is needed). An anchor not evaluated yet (above this layer, hidden) reads the + /// channel default. + fn anchor_value(&self, anchor: LayerId, channel: Channel, kind: ChannelKind) -> [f32; 3] { + let value = self.anchors.iter().rev().find(|(id, _)| *id == anchor).and_then(|(_, channels)| channels.get(channel.index()).copied()); + let value = value.unwrap_or_else(|| channel.default_value()); + let needs_gray = matches!(channel.kind(), ChannelKind::Color | ChannelKind::NormalMap) && matches!(kind, ChannelKind::Scalar | ChannelKind::Signed); + if needs_gray { [lum(value); 3] } else { value } + } + fn generator_ramp(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let coords = self.coords(); + let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); let signal = match (generator.kind, &generator.detail) { (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => { // Detail sizes are blurred copies of the mesh map, so a replaced curvature input reads at its own size only let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; let curvature = self.generator_input(generator, BakedMap::Curvature); - self.curvature_detail(detail, sizes, curvature) + self.curvature_detail(detail, sizes, curvature, micro) } (GeneratorKind::EdgeWear, None) => (self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, (GeneratorKind::Curvature, None) => self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5), @@ -1415,6 +1466,8 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, }; + let signal = + if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) && generator.detail.is_some() { signal } else { signal + micro }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); if let (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) = (generator.kind, &generator.detail) { @@ -1435,6 +1488,22 @@ impl<'a, 'b> Texel<'a, 'b> { ramp * ramp * (3.0 - 2.0 * ramp) } + /// How a generator's micro detail moves its signal at this texel: the anchor's height (0 where + /// the anchor is not evaluated yet) as an edge where raised and a cavity where recessed. + fn micro_detail(&self, kind: GeneratorKind, micro: MicroDetail) -> f32 { + let height = self.anchor_value(micro.anchor, Channel::Height, ChannelKind::Signed)[0]; + let amount = if micro.amount.is_finite() { micro.amount.clamp(0.0, 1.0) } else { 0.0 }; + let response = height.clamp(-1.0, 1.0) * amount; + match kind { + GeneratorKind::Curvature | GeneratorKind::EdgeWear => response, + + // Dirt gathers in dents; dents are occluded + GeneratorKind::Dirt => -response, + GeneratorKind::AmbientOcclusion => response, + GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction => 0.0, + } + } + /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]). fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let ramp = self.generator_ramp(generator, curvature_sizes); @@ -1450,15 +1519,19 @@ impl<'a, 'b> Texel<'a, 'b> { } /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given. - fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option) -> f32 { - let combine = |edges: f32, cavities: f32| match detail.mode { - CurvatureMode::Edges => edges, - CurvatureMode::Cavities => cavities, - CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), - CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option, micro: f32) -> f32 { + let combine = |edges: f32, cavities: f32| { + let edges = 1.0 - (1.0 - edges) * (1.0 - micro.max(0.0)); + let cavities = 1.0 - (1.0 - cavities) * (1.0 + micro.min(0.0)); + match detail.mode { + CurvatureMode::Edges => edges, + CurvatureMode::Cavities => cavities, + CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), + CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), + } }; - // Without curvature to read the texel is flat: no edges or cavities + // Without baked curvature, only painted micro height supplies edges or cavities let Some(curvature) = curvature else { return combine(0.0, 0.0) }; let working_size = (self.res, self.inp.gbuf.height); @@ -1493,11 +1566,28 @@ impl<'a, 'b> Texel<'a, 'b> { skip = filtered_index + 1; } - for effect in plan.effects.iter().skip(skip) { + // Replay the prefix to record anchors skipped by the precomputed filter + if let Some(last) = plan.effects.iter().take(skip).rposition(|e| matches!(e.kind, EffectKind::Anchor)) { + self.mask_effects(plan, plan.background, 0, last + 1); + } + self.mask_effects(plan, value, skip, plan.effects.len()) + } + + /// Mask effects `from..to` of `plan` over `value`, recording the anchors among them. + fn mask_effects(&mut self, plan: &MaskPlan, mut value: f32, from: usize, to: usize) -> f32 { + // Avoid amplifying rounding error when unpremultiplying faint paint + const MIN_PAINT_COVERAGE: f32 = 1e-5; + + for effect in plan.effects.iter().take(to).skip(from) { + if let Some(filtered) = effect.filtered_mask.and_then(|field| field.get(self.x, self.y)).and_then(|texel| texel.first()) { + value = *filtered; + continue; + } + let opacity = effect.opacity.clamp(0.0, 1.0); match effect.kind { EffectKind::Paint | EffectKind::Path(_) => { - let (mut painted, mut cov) = match effect.data.as_deref() { + let (mut painted, mut coverage) = match effect.data.as_deref() { Some(data) => (from_u16(data.get(self.o * 2).copied().unwrap_or(0)), from_u16(data.get(self.o * 2 + 1).copied().unwrap_or(0))), None => (0.0, 0.0), }; @@ -1507,15 +1597,15 @@ impl<'a, 'b> Texel<'a, 'b> { let stroke = (self.stroke * preview.opacity).clamp(0.0, 1.0); if preview.erase { painted *= 1.0 - stroke; - cov *= 1.0 - stroke; + coverage *= 1.0 - stroke; } else { painted = preview.mask_value * stroke + painted * (1.0 - stroke); - cov = stroke + cov * (1.0 - stroke); + coverage = stroke + coverage * (1.0 - stroke); } } - if cov > 0.0 { - let layer_value = painted / cov.max(1e-5); - value += (blend1(effect.blend, value, layer_value) - value) * cov * opacity; + if coverage > 0.0 { + let layer_value = painted / coverage.max(MIN_PAINT_COVERAGE); + value += (blend1(effect.blend, value, layer_value) - value) * coverage * opacity; } } EffectKind::Fill { source, projection } => { @@ -1547,8 +1637,12 @@ impl<'a, 'b> Texel<'a, 'b> { let result = if pass { 1.0 } else { 0.0 }; value += (result - value) * opacity; } + + // Every channel of a mask anchor reads the mask's gray + EffectKind::Anchor => self.anchors.push((effect.id, [[value.clamp(0.0, 1.0); 3]; NCH])), + // Content-only effects - EffectKind::Material(_) | EffectKind::Anchor => {} + EffectKind::Material(_) => {} } } value.clamp(0.0, 1.0) @@ -2018,7 +2112,7 @@ fn composite_block( let level_count = split.map_or(0, <[Level]>::len); let defaults: Acc = Channel::ALL.map(Channel::default_value); - // Tiles split into bands of rows, so a handful of tiles still keeps every thread busy + // Tiles split into bands of rows, so a handful of tiles still keeps every thread busy. let bands = TILE / BAND; let tasks: Vec<((u32, u32), u32)> = tiles.iter().flat_map(|t| (0..bands).map(move |b| (*t, b))).collect(); let mut results: Vec = tasks @@ -2070,11 +2164,11 @@ fn composite_block( any = true; let mut texel = Texel::new(inp, x, y, tile_offset, stroke_at(preview_tile, tile_offset)); - // Reuse one anchor buffer per band + // Reuse one anchor buffer per band. texel.anchors = std::mem::take(&mut anchors); match &levels { Some(levels) => { - // The texel's stream starts with the stack at each level + // The texel's stream starts with the stack at each level. let start = match &mut tape { Tape::Record(t) => { t.resize(t.len() + slots, 0.0); @@ -2115,7 +2209,7 @@ fn composite_block( }) .collect(); - // Join the bands of each tile (in parallel; uncovered tiles are freed) + // Join the bands of each tile (in parallel; uncovered tiles are freed). let joined: Vec = results .par_chunks(bands as usize) .map(|parts| { @@ -2142,7 +2236,7 @@ fn composite_block( } } - // Tiles without covered texels cost nothing to composite: not worth caching + // Tiles without covered texels cost nothing to composite: not worth caching. if any && let Some(bands) = parts.iter_mut().map(|p| p.1.take()).collect::>>() { records.push(((tx, ty), bands)); } @@ -2606,49 +2700,71 @@ mod tests { #[test] fn retained_filter_buffers_release_after_the_last_tile() { - let mut fixture = fixture(); - const RESOLUTION: u32 = 128; - fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, RESOLUTION, RESOLUTION); - fixture.project.texture_sets[0] = TextureSet::new("Plane", 0, RESOLUTION); - let layer = fill_layer(&mut fixture.project, [0.4; 3], 0.5); - let mut mask = Mask::new(MaskBackground::White); - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 8.0 }))); - fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + for resolution in [128, 512] { + for record_anchors in [false, true] { + let mut fixture = fixture(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, resolution, resolution); + fixture.project.texture_sets[0] = TextureSet::new("Plane", 0, resolution); + for color in [0.4, 0.2] { + let layer = fill_layer(&mut fixture.project, [color; 3], 0.5); + let mut mask = Mask::new(MaskBackground::White); + for radius in [8.0, 4.0, 2.0] { + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius }))); + if record_anchors && radius != 2.0 { + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Anchor)); + } + } + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + } - let second_layer = fill_layer(&mut fixture.project, [0.2; 3], 0.7); - let mut second_mask = Mask::new(MaskBackground::White); - second_mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 4.0 }))); - fixture.project.layer_mut(second_layer).unwrap().mask = Some(second_mask); + let images = ImageStore::default(); + let input = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &fixture.pixels, + baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + let mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), resolution); + let mut cache = BelowCache::default(); + cache.ahead = all_tiles(resolution, resolution).into_iter().skip(1).collect(); - let images = ImageStore::default(); - let input = Inputs { - project: &fixture.project, - ts: 0, - mesh: &fixture.mesh, - gbuf: &fixture.gbuf, - pixels: &fixture.pixels, - baked: &fixture.baked, - block_scales: fixture.project.texture_sets[0].block_scales(), - preview: None, - images: &images, - bounds: fixture.mesh.bounds(), - }; - let mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), RESOLUTION); - let mut cache = BelowCache::default(); - cache.ahead = vec![(1, 0), (0, 1), (1, 1)]; + composite_tiles_cached(&input, &mut output, &[(0, 0)], Some(&mut cache)); + let retained = cache.held.as_ref().expect("filter fields should be retained while tiles follow"); + let fields = || retained.fields.values().flat_map(|field| std::iter::once(field).chain(field.anchor_stages.iter().map(|(_, stage)| stage))); + let field_bytes: usize = fields().map(|field| field.data.capacity() * std::mem::size_of::()).sum(); + let field_count = fields().count(); + let stage_index_bytes: usize = + retained.fields.values().map(|field| field.anchor_stages.capacity() * std::mem::size_of::<(LayerId, Field)>()).sum(); + let weak_fields = Arc::downgrade(&retained.fields); + let expected_fields = if record_anchors { 6 } else { 2 }; + assert_eq!(field_count, expected_fields, "only filter stages needed by anchors remain beside the final mask fields"); + assert_eq!(field_bytes, expected_fields * resolution as usize * resolution as usize * std::mem::size_of::()); + println!( + "resolution: {resolution}, mask layers: 2, anchors: {record_anchors}, fields: {field_count}, buffer capacity: {field_bytes} bytes, stage-index capacity: {stage_index_bytes} bytes" + ); - composite_tiles_cached(&input, &mut output, &[(0, 0)], Some(&mut cache)); - let retained = cache.held.as_ref().expect("filter fields should be retained while tiles follow"); - let field_bytes: usize = retained.fields.values().map(|field| field.data.capacity() * std::mem::size_of::()).sum(); - let field_count = retained.fields.len(); - let weak_fields = Arc::downgrade(&retained.fields); - assert_eq!(field_count, 2); - assert!(field_bytes > 0); - println!("retained fields: {field_count}, buffer capacity: {field_bytes} bytes"); + cache.ahead.clear(); + composite_tiles_cached(&input, &mut output, &[(1, 0)], Some(&mut cache)); + assert!(weak_fields.upgrade().is_none(), "the last tile must release retained field buffers"); - cache.ahead.clear(); - composite_tiles_cached(&input, &mut output, &[(1, 0)], Some(&mut cache)); - assert!(weak_fields.upgrade().is_none(), "the last tile must release retained field buffers"); + cache.ahead = all_tiles(resolution, resolution).into_iter().skip(1).collect(); + composite_tiles_cached(&input, &mut output, &[(0, 0)], Some(&mut cache)); + let weak_fields = Arc::downgrade(&cache.held.as_ref().unwrap().fields); + cache.clear(); + assert!(weak_fields.upgrade().is_none(), "invalidating the cache releases intermediate anchor stages too"); + + composite_tiles_cached(&input, &mut output, &[(0, 0)], Some(&mut cache)); + let weak_fields = Arc::downgrade(&cache.held.as_ref().unwrap().fields); + drop(cache); + assert!(weak_fields.upgrade().is_none(), "dropping the cache releases a cancelled run's fields"); + } + } } #[test] @@ -3371,6 +3487,151 @@ soft {soft:?}" assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.5; 3])); } + /// A white fill layer on top whose mask reads `anchor` (any channel: a mask anchor is gray). + fn anchor_reader(fixture: &mut Fixture, anchor: LayerId) -> LayerId { + let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5); + let mut mask = Mask::new(MaskBackground::Black); + let source = Source::Anchor { anchor, channel: Channel::Roughness }; + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })); + fixture.project.layer_mut(top).unwrap().mask = Some(mask); + top + } + + #[test] + fn mask_anchors_record_the_mask_value_at_their_place() { + let mut fixture = fixture(); + let low = fill_layer(&mut fixture.project, [0.0; 3], 0.5); + let (gray, anchor, full) = (fixture.project.alloc_id(), fixture.project.alloc_id(), fixture.project.alloc_id()); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(gray, EffectKind::Fill { source: Source::Uniform([0.4; 3]), projection: Projection::default() })); + mask.effects.push(Effect::new(anchor, EffectKind::Anchor)); + mask.effects.push(Effect::new(full, EffectKind::Fill { source: Source::Uniform([1.0; 3]), projection: Projection::default() })); + fixture.project.layer_mut(low).unwrap().mask = Some(mask.clone()); + anchor_reader(&mut fixture, anchor); + + // The low layer shows fully (black), the top one at the 0.4 the anchor recorded + assert!(close(run(&fixture, None).value(Channel::BaseColor, 5, 5), [0.4; 3])); + + // Under a blur precomputed over the region the anchor still records its own place + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0 }))); + fixture.project.layer_mut(low).unwrap().mask = Some(mask.clone()); + let color = run(&fixture, None).value(Channel::BaseColor, 5, 5); + assert!(close(color, [0.4; 3]), "{color:?}"); + + // An empty paint layer still records its mask anchor for the layer above + fixture.project.layer_mut(low).unwrap().kind = LayerKind::Paint; + let color = run(&fixture, None).value(Channel::BaseColor, 5, 5); + assert!(close(color, [0.7; 3]), "{color:?}"); + } + + #[test] + fn mask_anchor_between_filters_keeps_the_filtered_value() { + let mut fixture = fixture(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 128, 128); + fixture.project.texture_sets[0].resolution = 128; + let lower = fill_layer(&mut fixture.project, [0.0; 3], 1.0); + let anchor = fixture.project.alloc_id(); + let mut mask = Mask::new(MaskBackground::Black); + let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }; + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default() })); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 64.0 }))); + mask.effects.push(Effect::new(anchor, EffectKind::Anchor)); + fixture.project.layer_mut(lower).unwrap().mask = Some(mask.clone()); + let reader = anchor_reader(&mut fixture, anchor); + let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); + let expected = assert_sparse_mask_matches_image(&fixture, reader, &texels).unwrap(); + assert!(expected.iter().any(|value| *value > 0.1 && *value < 0.9), "the anchor records a softened checker"); + + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 128.0 }))); + fixture.project.layer_mut(lower).unwrap().mask = Some(mask); + let actual = assert_sparse_mask_matches_image(&fixture, reader, &texels).unwrap(); + + assert_eq!(actual, expected, "a filter above the anchor must not change its recorded value"); + } + + #[test] + fn generator_micro_detail_follows_the_anchor_height() { + let mut fixture = fixture(); + let low = fixture.project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::Height, Source::Uniform([0.5; 3])); + fixture.project.insert_layer(0, Layer::new(low, "Bumps", LayerKind::Fill(fill), &[Channel::Height]), None, false).unwrap(); + let anchor = content_fx(&mut fixture, low, EffectKind::Anchor); + let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5); + let mut generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: None, ..Generator::new(GeneratorKind::Curvature) }; + let with = |fixture: &mut Fixture, generator: &Generator| { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(LayerId(900), EffectKind::Generator(generator.clone()))); + fixture.project.layer_mut(top).unwrap().mask = Some(mask); + run(fixture, None).value(Channel::BaseColor, 5, 5)[0] + }; + + // No curvature map: flat mid gray, so the mask is 0.5 and the base color 0.75 + let flat = with(&mut fixture, &generator); + assert!((flat - 0.75).abs() < 0.02, "{flat}"); + + // Raised height reads as an edge + generator.micro = Some(MicroDetail { anchor, amount: 1.0 }); + assert!(with(&mut fixture, &generator) > flat + 0.2); + + // Recessed height reads as a cavity; dirt gathers there + if let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(low).unwrap().kind { + fill.sources.insert(Channel::Height, Source::Uniform([-0.5; 3])); + } + assert!(with(&mut fixture, &generator) < flat - 0.2); + let dirt = + Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, micro: Some(MicroDetail { anchor, amount: 1.0 }), ..Generator::new(GeneratorKind::Dirt) }; + let plain = Generator { micro: None, ..dirt.clone() }; + assert!(with(&mut fixture, &dirt) > with(&mut fixture, &plain) + 0.2); + + // A hostile amount does nothing + generator.micro = Some(MicroDetail { anchor, amount: f32::NAN }); + assert!((with(&mut fixture, &generator) - flat).abs() < 0.02); + } + + #[test] + fn curvature_modes_classify_raised_and_recessed_micro_height() { + let mut fixture = fixture(); + fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::Curvature, Arc::new(vec![0.5; 64 * 64]))].into() }; + let lower = fixture.project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::Height, Source::Uniform([0.5; 3])); + fixture.project.insert_layer(0, Layer::new(lower, "Bumps", LayerKind::Fill(fill), &[Channel::Height]), None, false).unwrap(); + let anchor = content_fx(&mut fixture, lower, EffectKind::Anchor); + let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5); + + for kind in [GeneratorKind::Curvature, GeneratorKind::EdgeWear] { + for (height, mode, responds) in [ + (0.5, CurvatureMode::Edges, true), + (-0.5, CurvatureMode::Edges, false), + (0.5, CurvatureMode::Cavities, false), + (-0.5, CurvatureMode::Cavities, true), + (0.5, CurvatureMode::Both, true), + (-0.5, CurvatureMode::Both, true), + ] { + if let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(lower).unwrap().kind { + fill.sources.insert(Channel::Height, Source::Uniform([height; 3])); + } + let detail = CurvatureDetail { mode, weights: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] }; + let generator = Generator { + level: 0.5, + softness: 0.5, + noise_amount: 0.0, + detail: Some(detail), + micro: Some(MicroDetail { anchor, amount: 1.0 }), + ..Generator::new(kind) + }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(top).unwrap().mask = Some(mask); + + let value = run(&fixture, None).value(Channel::BaseColor, 5, 5)[0]; + let expected = if responds { 0.75 } else { 0.5 }; + assert!((value - expected).abs() < 0.02, "{kind:?} {mode:?} height {height}: {value}"); + } + } + } + #[test] fn decal_fills_cover_only_their_frame_and_image_alpha() { let mut f = fixture(); diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 0e05255b..4eede134 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -9,12 +9,14 @@ use crate::{BakedMap, BlendMode, Channel, ChannelKind, lum}; mod curvature_detail; mod curvature_mode; mod generator_global; +mod micro_detail; mod output_resolution; mod resolution_mode; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; pub use generator_global::GeneratorGlobal; +pub use micro_detail::MicroDetail; pub use output_resolution::OutputResolution; pub use resolution_mode::ResolutionMode; @@ -578,6 +580,9 @@ pub struct Generator { /// What an input reads instead of its mesh map (an image, a uniform value or an anchor); inputs not listed read their mesh map. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub inputs: BTreeMap, + /// Painted height read from an anchor point below, added as micro detail (None: baked maps only). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub micro: Option, } impl Generator { @@ -615,6 +620,7 @@ impl Generator { global: GeneratorGlobal::default(), resolution: OutputResolution::default(), inputs: BTreeMap::new(), + micro: None, } } @@ -1027,8 +1033,10 @@ pub enum EffectKind { /// Content only: a material fill (one source per channel; channels without a source are /// left as they are). Material(Fill), - /// Content only: records the composited stack right after its layer (that layer and - /// everything below) so masks and fills above can read it ([`Source::Anchor`]). + /// Records the stack at its place so masks, fills and generators above can read it + /// ([`Source::Anchor`]). In a content stack it records the composited stack right after its + /// layer (that layer and everything below); in a mask, the mask value at that point (every + /// channel reads that gray). Anchor, } @@ -1074,9 +1082,9 @@ impl EffectKind { /// both (`None`). pub fn content_only(&self) -> Option { match self { - EffectKind::Material(_) | EffectKind::Anchor => Some(true), + EffectKind::Material(_) => Some(true), EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection { .. } | EffectKind::Compare { .. } => Some(false), - EffectKind::Paint | EffectKind::Path(_) | EffectKind::Levels(_) | EffectKind::Filter(_) => None, + EffectKind::Paint | EffectKind::Path(_) | EffectKind::Levels(_) | EffectKind::Filter(_) | EffectKind::Anchor => None, } } @@ -1090,7 +1098,7 @@ impl EffectKind { match self { EffectKind::Fill { source, .. } => source.anchor().is_some(), EffectKind::Material(fill) => fill.sources.values().any(|source| source.anchor().is_some()), - EffectKind::Generator(generator) => generator.inputs.values().any(|source| source.anchor().is_some()), + EffectKind::Generator(generator) => generator.micro.is_some() || generator.inputs.values().any(|source| source.anchor().is_some()), _ => false, } } @@ -1103,13 +1111,19 @@ impl EffectKind { EffectKind::Generator(generator) => generator.inputs.values().collect(), _ => Vec::new(), }; - sources + let mut anchors: Vec<_> = sources .into_iter() .filter_map(|source| match source { Source::Anchor { anchor, channel } => Some((*anchor, *channel)), _ => None, }) - .collect() + .collect(); + if let EffectKind::Generator(generator) = self + && let Some(micro) = generator.micro + { + anchors.push((micro.anchor, Channel::Height)); + } + anchors } /// The image resources this effect's sources read (a fill, material or generator input). @@ -1284,17 +1298,25 @@ mod tests { #[test] fn effect_targets_and_anchor_reads() { - assert_eq!(EffectKind::Anchor.content_only(), Some(true)); + assert_eq!(EffectKind::Anchor.content_only(), None, "anchors go on content and masks"); assert_eq!(EffectKind::Generator(Generator::new(GeneratorKind::Dirt)).content_only(), Some(false)); assert_eq!(EffectKind::Filter(Filter::Invert).content_only(), None); - let mut l = Layer::new(LayerId(1), "l", LayerKind::Paint, &[Channel::BaseColor]); - assert!(!l.reads_anchor()); + let mut fill_layer = Layer::new(LayerId(1), "l", LayerKind::Paint, &[Channel::BaseColor]); + assert!(!fill_layer.reads_anchor()); let source = Source::Anchor { anchor: LayerId(9), channel: Channel::Height }; - l.mask = Some(Mask { + fill_layer.mask = Some(Mask { effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default() })], ..Mask::new(MaskBackground::Black) }); - assert!(l.reads_anchor()); + assert!(fill_layer.reads_anchor()); + + // A generator with micro detail reads its anchor too + let mut generator_layer = Layer::new(LayerId(3), "g", LayerKind::Paint, &[Channel::BaseColor]); + let mut generator = Generator::new(GeneratorKind::Dirt); + generator.micro = Some(MicroDetail { anchor: LayerId(9), amount: 0.5 }); + assert_eq!(EffectKind::Generator(generator.clone()).anchors_read(), [(LayerId(9), Channel::Height)]); + generator_layer.mask = Some(Mask { effects: vec![Effect::new(LayerId(4), EffectKind::Generator(generator))], ..Mask::new(MaskBackground::Black) }); + assert!(generator_layer.reads_anchor()); } #[test] diff --git a/crates/core/src/layer/micro_detail.rs b/crates/core/src/layer/micro_detail.rs new file mode 100644 index 00000000..d7b13121 --- /dev/null +++ b/crates/core/src/layer/micro_detail.rs @@ -0,0 +1,16 @@ +use serde::{Deserialize, Serialize}; + +use super::LayerId; + +/// Painted height read from an anchor point below a generator +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct MicroDetail { + /// The anchor point effect id + pub anchor: LayerId, + /// Strength of the height signal from 0 to 1 + pub amount: f32, +} + +impl MicroDetail { + pub const DEFAULT_AMOUNT: f32 = 0.5; +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 4a17e89e..77a872f7 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -25,8 +25,8 @@ pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; pub use layer::{ ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorGlobal, GeneratorKind, HeightMask, - Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, OutputResolution, PathShape, Procedural, ProceduralKind, - Projection, ResolutionMode, Source, gradient, hsl_adjust, per_unit, + Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, PathShape, Procedural, + ProceduralKind, Projection, ResolutionMode, Source, gradient, hsl_adjust, per_unit, }; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 587968de..06b74adb 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -220,7 +220,7 @@ pub(crate) fn color_of(v: &Value) -> Option<[f32; 3]> { Value::Number(n) => n.as_f64().map(|v| [v as f32; 3]).filter(|v| v[0].is_finite()), Value::String(s) => { let s = s.trim_start_matches('#'); - if s.len() != 6 { + if s.len() != 6 || !s.bytes().all(|b| b.is_ascii_hexdigit()) { return None; } let c = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| texturecraft_texel::srgb_to_linear(v as f32 / 255.0)); @@ -276,4 +276,12 @@ mod tests { let overflow_scalar = json!({ "color": 1e40 }); assert!(color_param("test.cmd", &overflow_scalar, "color").is_err()); } + + #[test] + fn hex_color_rejects_signs_and_non_hex() { + assert_eq!(color_of(&json!("#+f+f+f")), None); + assert_eq!(color_of(&json!("#-00000")), None); + assert_eq!(color_of(&json!("#GGGGGG")), None); + assert!(color_of(&json!("#ff8000")).is_some()); + } } diff --git a/crates/engine/src/effect_clipboard.rs b/crates/engine/src/effect_clipboard.rs index 5aedd49b..fe79a383 100644 --- a/crates/engine/src/effect_clipboard.rs +++ b/crates/engine/src/effect_clipboard.rs @@ -82,6 +82,7 @@ fn paste(session: &mut Session, params: &Value) -> Result { Some(only) if only != content && asked => { return Err(bad(CMD, format!("{} effects go on the {}", effect.kind.name(), if only { "layer content" } else { "mask" }))); } + Some(only) => only, None => content, }; diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index a1140aa1..3a2e348c 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -83,6 +83,9 @@ fn generator_json(generator: &Generator) -> Value { out["mode"] = json!(format!("{:?}", detail.mode)); out["sizes"] = json!(detail.weights); } + if let Some(micro) = &generator.micro { + out["micro"] = json!({ "anchor": micro.anchor.0, "amount": micro.amount }); + } out } diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index 3a77ae50..603cd0fa 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -97,6 +97,9 @@ pub fn typed(param: &LinkParam, v: &Value) -> Option { ("bool", x) => json!(num(x)? != 0.0), ("color", Value::String(hex)) => { let h = hex.trim_start_matches('#'); + if h.len() != 6 || !h.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } let c = |i: usize| Some(f64::from(u8::from_str_radix(h.get(i..i + 2)?, 16).ok()?) / 255.0); // Hex colors are sRGB; values are linear. let lin = |x: f64| if x <= 0.04045 { x / 12.92 } else { ((x + 0.055) / 1.055).powf(2.4) }; @@ -551,3 +554,23 @@ esac let _ = std::fs::remove_dir_all(dir); } } + +#[cfg(test)] +mod tests { + use super::typed; + use serde_json::json; + use texturecraft_core::layer::LinkParam; + + fn color_param() -> LinkParam { + let c = json!({"t": "color", "v": [0.0, 0.0, 0.0, 1.0]}); + serde_json::from_value(json!({"id": "c", "label": "C", "value": c, "default": c})).unwrap() + } + + #[test] + fn hex_color_rejects_signs_and_extra_digits() { + let p = color_param(); + assert_eq!(typed(&p, &json!("#aabbccdd")), None); + assert_eq!(typed(&p, &json!("#+f+f+f")), None); + assert!(typed(&p, &json!("#ff8000")).is_some()); + } +} diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index c0887849..23095ef3 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use texturecraft_core::{ BakedMap, BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, - MaskBackground, OutputResolution, Procedural, ProceduralKind, Project, ResolutionMode, Source, + MaskBackground, MicroDetail, OutputResolution, Procedural, ProceduralKind, Project, ResolutionMode, Source, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, offset?: -1..1 added to the result, invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}", + "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, offset?: -1..1 added to the result, invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", has_layer, add_generator ), @@ -85,16 +85,16 @@ pub fn specs() -> Vec { "Add anchor point", ["Layers", "Effects"], None, - "{layer?, name?} (records the stack up to this layer for fills and masks above: effect.add.fill {anchor})", + "{layer?, target?: content|mask (content), name?} (on the content it records the stack up to this layer, in a mask the mask value at that point; fills, masks and generators above read it: effect.add.fill {anchor}, effect.add.generator {microAnchor})", has_layer, - |s, p| push_effect(s, p, EffectKind::Anchor, BlendMode::Normal) + add_anchor ), cmd!( "effect.set", "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -239,9 +239,11 @@ fn push_effect(s: &mut Session, p: &Value, kind: EffectKind, blend: BlendMode) - if kind.content_only().is_some_and(|c| c != content) { return Err(bad("effect.add", format!("{} effects go on masks, not on layer content", kind.name()))); } + let label = format!("Add {}", kind.name().to_ascii_lowercase()); let eid = with_mask(s, p, "effect.add", &label, |s, id| { let eid = s.doc.project.alloc_id(); + // An instance's content and inherited mask belong to its source let id = if content { s.doc.project.content_layer(id).map_or(id, |l| l.id) } else { s.doc.project.mask_owner(id) }; let l = s.doc.project.layer_mut(id)?; @@ -292,11 +294,14 @@ fn add_fill(s: &mut Session, p: &Value) -> Result { fill.projection = projection; return push_effect(s, p, EffectKind::Material(fill), blend); } + if let Some(a) = u64p(p, "anchor") { let channel = channel_param("effect.add.fill", p, "anchorChannel")?.unwrap_or(Channel::Height); - let source = anchor_source(s, "effect.add.fill", id, LayerId(a), channel)?; + let reader = s.doc.project.mask_owner(id); + let source = anchor_source(s, "effect.add.fill", reader, LayerId(a), channel)?; return push_effect(s, p, EffectKind::Fill { source, projection }, blend); } + let source = match strp(p, "procedural") { Some(k) => { let kind = ProceduralKind::parse(k).ok_or_else(|| bad("effect.add.fill", format!("unknown procedural `{k}`")))?; @@ -398,6 +403,45 @@ fn size_weights(command: &str, value: &Value) -> Result<[f32; CurvatureDetail::S Ok(weights) } +/// An anchor point on the layer content by default, preserving previous placement, or in its mask with `target: "mask"`. +fn add_anchor(session: &mut Session, params: &Value) -> Result { + // Params may be null or an object without a target: both default to the content + let mut params = params.as_object().cloned().unwrap_or_default(); + params.entry("target").or_insert_with(|| json!("content")); + push_effect(session, &Value::Object(params), EffectKind::Anchor, BlendMode::Normal) +} + +/// A generator's micro detail from `microAnchor` / `microAmount` for a generator on layer +/// `reader` (None: leave it as it is; `Some(None)`: remove it). +fn micro_param(session: &Session, command: &str, reader: LayerId, params: &Value, current: Option) -> Result>> { + let amount = match params.get("microAmount") { + Some(value) => { + Some(value.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(command, "`microAmount` must be a number 0..1"))?.clamp(0.0, 1.0) as f32) + } + None => None, + }; + let anchor = match params.get("microAnchor") { + None => current.map(|m| m.anchor), + Some(Value::Null) => return Ok(Some(None)), + Some(value) => Some(LayerId(value.as_u64().ok_or_else(|| bad(command, "`microAnchor` must be an anchor effect id or null"))?)), + }; + let Some(anchor) = anchor else { + return match amount { + Some(_) => Err(bad(command, "give `microAnchor` before `microAmount`: the generator has no micro detail")), + None => Ok(None), + }; + }; + + if params.get("microAnchor").is_none() && amount.is_none() { + return Ok(None); + } + + // The same rule as fills: an anchor below, in the same texture set + anchor_source(session, command, reader, anchor, Channel::Height)?; + let amount = amount.or(current.map(|m| m.amount)).unwrap_or(MicroDetail::DEFAULT_AMOUNT); + Ok(Some(Some(MicroDetail { anchor, amount }))) +} + /// The generator input named by `input` and what replaces it (None: its mesh map again), for a generator on layer `owner`. fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { const CMD: &str = "effect.set"; @@ -434,6 +478,11 @@ fn add_generator(session: &mut Session, params: &Value) -> Result { }; let mut generator = Generator::new(kind); generator_from("effect.add.generator", params, &mut generator)?; + let selected_layer = layer_param(session, "effect.add.generator", params)?; + let reader = session.doc.project.mask_owner(selected_layer); + if let Some(micro) = micro_param(session, "effect.add.generator", reader, params, None)? { + generator.micro = micro; + } let blend = blend_param("effect.add.generator", params, "blend")?.unwrap_or(BlendMode::Normal); push_effect(session, params, EffectKind::Generator(generator), blend) } @@ -530,6 +579,14 @@ fn set(session: &mut Session, params: &Value) -> Result { } _ => None, }; + let micro = match session.doc.project.effect(effect) { + Some((owner, Effect { kind: EffectKind::Generator(generator), .. })) => micro_param(session, CMD, owner, params, generator.micro)?, + _ if params.get("microAnchor").is_some() || params.get("microAmount").is_some() => { + return Err(bad(CMD, "`microAnchor` and `microAmount` edit generator effects only")); + } + + _ => None, + }; // `input` names a generator input that `inputImage`, `inputValue` or `inputAnchor` replaces, or `inputBaked` puts back let input = match session.doc.project.effect(effect) { @@ -579,10 +636,14 @@ fn set(session: &mut Session, params: &Value) -> Result { generator.inputs.retain(|map, _| kind.inputs().contains(map)); } generator_from(CMD, params, generator)?; + if let Some(micro) = micro { + generator.micro = micro; + } if let Some((map, source)) = input { if !generator.kind.inputs().contains(&map) { return Err(bad(CMD, format!("this generator has no `{}` input", map.id()))); } + match source { Some(source) => generator.inputs.insert(map, source), None => generator.inputs.remove(&map), @@ -591,6 +652,7 @@ fn set(session: &mut Session, params: &Value) -> Result { } _ if generator_kind.is_some() => return Err(bad(CMD, "`generator` requires a generator effect")), EffectKind::Levels(levels) => levels_from(params, levels), + // The swapped filter was built with the parameters already EffectKind::Filter(_) if swaps_filter => {} EffectKind::Filter(filter) => crate::filter_lib::apply(params, filter, CMD)?, diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index b5eedd1e..c0695a23 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -96,6 +96,89 @@ fn anchor_points_feed_masks_above() { assert!(inspect.to_string().contains(&format!("\"anchor\":{anchor}")), "{inspect}"); } +#[test] +fn anchor_points_in_masks_record_the_mask_for_layers_above() { + let mut s = session(); + let low = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 0.0]})).unwrap(), "layer"); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"value": 0.4})).unwrap(); + let anchor = id(execute(&mut s, "effect.add.anchor", &json!({"target": "mask", "name": "Wear"})).unwrap(), "effect"); + let layer = s.doc.project.layer(LayerId(low)).unwrap(); + assert!(layer.mask.as_ref().unwrap().effects.iter().any(|e| e.id.0 == anchor), "in the mask"); + assert!(layer.content_effects.is_empty(), "not on the content"); + + // Without a target (or with no params at all) it still goes on the content, as before + let content = id(execute(&mut s, "effect.add.anchor", &json!({"layer": low})).unwrap(), "effect"); + assert!(s.doc.project.layer(LayerId(low)).unwrap().content_effects.iter().any(|e| e.id.0 == content)); + let bare = id(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap(), "effect"); + assert!(s.doc.project.layer(LayerId(low)).unwrap().content_effects.iter().any(|e| e.id.0 == bare)); + + // Folders take anchors in their masks only + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer"); + assert!(execute(&mut s, "effect.add.anchor", &json!({"layer": folder})).is_err(), "folder content"); + execute(&mut s, "effect.add.anchor", &json!({"layer": folder, "target": "mask"})).unwrap(); + + execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"anchor": anchor})).unwrap(); + + // The low layer shows at 0.4 (black over the 0.5 default), the top one at the anchor's 0.4 + let low_shown = 0.5 * 0.6; + let expected = low_shown + (1.0 - low_shown) * 0.4; + assert!(close(center(&mut s, Channel::BaseColor), [expected; 3]), "{:?}", center(&mut s, Channel::BaseColor)); +} + +#[test] +fn generators_read_an_anchor_height_as_micro_detail() { + let mut s = session(); + let low = id(execute(&mut s, "layer.add.fill", &json!({"height": 0.5})).unwrap(), "layer"); + let anchor = id(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap(), "effect"); + let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(), "layer"); + + // The anchor must be below; `microAmount` needs an anchor; ids must be numbers + assert!(execute(&mut s, "effect.add.generator", &json!({"layer": low, "microAnchor": anchor})).is_err()); + assert!(execute(&mut s, "effect.add.generator", &json!({"microAmount": 0.5})).is_err()); + assert!(execute(&mut s, "effect.add.generator", &json!({"microAnchor": "x"})).is_err()); + assert!(execute(&mut s, "effect.add.generator", &json!({"microAnchor": low})).is_err(), "not an anchor point"); + + let generator = id(execute(&mut s, "effect.add.generator", &json!({"generator": "curvature", "noise": 0.0})).unwrap(), "effect"); + let plain = center(&mut s, Channel::BaseColor); + execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": anchor, "microAmount": 1.0})).unwrap(); + let raised = center(&mut s, Channel::BaseColor); + assert!(raised[0] > plain[0] + 0.1, "{plain:?} -> {raised:?}"); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + assert!(inspect.to_string().contains(&format!("\"micro\":{{\"amount\":1.0,\"anchor\":{anchor}}}")), "{inspect}"); + + // The amount alone keeps the anchor; null removes the micro detail + execute(&mut s, "effect.set", &json!({"effect": generator, "microAmount": 0.0})).unwrap(); + assert!(close(center(&mut s, Channel::BaseColor), plain)); + execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": null})).unwrap(); + assert!(s.doc.project.effect(LayerId(generator)).map(|(_, e)| matches!(&e.kind, EffectKind::Generator(g) if g.micro.is_none())).unwrap()); + assert!(execute(&mut s, "effect.set", &json!({"effect": anchor, "microAmount": 0.5})).is_err(), "generators only"); + + // A copied generator with micro detail needs the anchor below its new layer + execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": anchor})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": top, "target": generator})).unwrap(); + execute(&mut s, "effect.copy", &json!({"effect": generator})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": low})).unwrap(); + assert!(execute(&mut s, "effect.paste", &json!({"target": "mask"})).is_err()); + let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.project, s.doc.project); +} + +#[test] +fn anchor_effects_added_through_instance_validate_against_source() { + let mut session = session(); + let source = id(execute(&mut session, "layer.add.fill", &json!({"height": 0.5})).unwrap(), "layer"); + execute(&mut session, "layer.add.fill", &json!({"height": 0.5})).unwrap(); + let anchor = id(execute(&mut session, "effect.add.anchor", &Value::Null).unwrap(), "effect"); + let instance = id(execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap(), "layer"); + + assert!(execute(&mut session, "effect.add.generator", &json!({"layer": instance, "microAnchor": anchor})).is_err()); + assert!(execute(&mut session, "effect.add.fill", &json!({"layer": instance, "anchor": anchor})).is_err()); + assert!(session.doc.project.layer(LayerId(source)).unwrap().mask.is_none()); +} + #[test] fn painting_into_a_content_paint_effect() { let mut s = session(); diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index f7053917..a70198cf 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -17,6 +17,7 @@ craft-mesh = { workspace = true } craft-mcmat = { workspace = true } craft-tcraft = { workspace = true } craft-zip = { workspace = true } +craft-zip-usdz = { workspace = true } texturecraft-core = { workspace = true } texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index 2f57f7aa..9c737f16 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -6,7 +6,6 @@ //! UsdUVTexture shaders. Meters, Y up. use std::fmt::Write as _; -use std::io::Write as _; use texturecraft_core::{Channel, NormalFormat}; use texturecraft_geom::Mesh; @@ -344,14 +343,12 @@ pub(crate) fn material_maps(mesh: &Mesh, stem: &str, textures: &[Vec)]) -> Result> { - let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); - let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored).with_alignment(64); - let err = |e: zip::result::ZipError| FormatError::Invalid(format!("usdz package: {e}")); + let mut zip = craft_zip_usdz::Writer::new(); + let err = |e| FormatError::Invalid(format!("usdz package: {e}")); for (name, bytes) in std::iter::once((layer_name, layer)).chain(files.iter().map(|(n, b)| (n.as_str(), b.as_slice()))) { - zip.start_file(name, opts).map_err(err)?; - zip.write_all(bytes)?; + zip.add_stored_aligned(name, bytes, 64).map_err(err)?; } - Ok(zip.finish().map_err(err)?.into_inner()) + zip.finish().map_err(err) } /// Text of a value as usda writes it. @@ -439,3 +436,41 @@ pub(crate) fn usda(layer: &UsdLayer) -> String { usda_prim(&mut s, &layer.root, 0); s } + +#[cfg(test)] +mod aligned_package_tests { + use super::*; + use std::io::{Cursor, Read, Write}; + + #[test] + fn shared_usdz_keeps_layer_first_and_exact_archive_bytes() { + let files = vec![("textures/color.png".to_owned(), vec![0, 1, 255]), ("empty".to_owned(), Vec::new())]; + let bytes = usdz("scene.usdc", b"PXR-USDC", &files).unwrap(); + let mut previous = zip::ZipWriter::new(Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored).with_alignment(64); + for (name, data) in std::iter::once(("scene.usdc", b"PXR-USDC".as_slice())).chain(files.iter().map(|(n, b)| (n.as_str(), b.as_slice()))) { + previous.start_file(name, opts).unwrap(); + previous.write_all(data).unwrap(); + } + assert_eq!(bytes, previous.finish().unwrap().into_inner()); + let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).unwrap(); + assert_eq!(archive.len(), 3); + for (i, (name, data)) in + std::iter::once(("scene.usdc", b"PXR-USDC".as_slice())).chain(files.iter().map(|(n, b)| (n.as_str(), b.as_slice()))).enumerate() + { + let mut entry = archive.by_index(i).unwrap(); + assert_eq!(entry.name().unwrap(), name); + assert_eq!(entry.compression(), zip::CompressionMethod::Stored); + assert_eq!(entry.data_start().unwrap() % 64, 0); + let mut actual = Vec::new(); + entry.read_to_end(&mut actual).unwrap(); + assert_eq!(actual, data); + } + } + + #[test] + fn shared_usdz_rejects_duplicate_layer_name() { + let err = usdz("scene.usdc", b"PXR-USDC", &[("scene.usdc".to_owned(), Vec::new())]).unwrap_err(); + assert!(matches!(err, FormatError::Invalid(ref why) if why.starts_with("usdz package:"))); + } +} diff --git a/crates/formats/src/mesh_import/dae.rs b/crates/formats/src/mesh_import/dae.rs index bb104455..20d87a5a 100644 --- a/crates/formats/src/mesh_import/dae.rs +++ b/crates/formats/src/mesh_import/dae.rs @@ -6,7 +6,9 @@ use std::collections::HashMap; use std::rc::Rc; -use quick_xml::events::{BytesStart, Event}; +use quick_xml::XmlVersion; +use quick_xml::escape::resolve_predefined_entity; +use quick_xml::events::{BytesRef, BytesStart, Event}; use texturecraft_geom::glam::{Mat3, Mat4, Vec2, Vec3, Vec4}; use super::{Corner, PolygonSink, RawCamera, RawMesh, check_vertices}; @@ -52,7 +54,9 @@ impl El { fn element(e: &BytesStart) -> El { let text = |b: &[u8]| String::from_utf8_lossy(b).into_owned(); - let attrs = e.attributes().with_checks(false).flatten().map(|a| (text(a.key.local_name().as_ref()), text(&a.value))).collect(); + // Values come back still escaped; decode them, keeping the raw text if they are malformed. + let value = |a: &quick_xml::events::attributes::Attribute| a.normalized_value(XmlVersion::Implicit1_0).map_or_else(|_| text(&a.value), |v| v.into_owned()); + let attrs = e.attributes().with_checks(false).flatten().map(|a| (text(a.key.local_name().as_ref()), value(&a))).collect(); El { name: text(e.local_name().as_ref()), attrs, ..El::default() } } @@ -61,8 +65,11 @@ fn parse_xml(bytes: &[u8]) -> Result { let mut reader = quick_xml::Reader::from_reader(bytes); let mut stack = vec![El::default()]; let mut count = 0usize; + // Text and entity references arrive as separate events but form one run of text. + let mut in_text = false; loop { let event = reader.read_event().map_err(|e| malformed(KIND, e))?; + let glue = std::mem::replace(&mut in_text, matches!(event, Event::Text(_) | Event::GeneralRef(_))); if matches!(event, Event::Start(_) | Event::Empty(_)) { count += 1; if count > MAX_ELEMENTS || stack.len() > MAX_DEPTH { @@ -82,8 +89,9 @@ fn parse_xml(bytes: &[u8]) -> Result { parent.children.push(el); } } - Event::Text(t) => push_text(&mut stack, &t), - Event::CData(t) => push_text(&mut stack, &t), + Event::Text(t) => push_text(&mut stack, &String::from_utf8_lossy(&t), glue), + Event::GeneralRef(r) => push_text(&mut stack, &entity(&r), glue), + Event::CData(t) => push_text(&mut stack, &String::from_utf8_lossy(&t), false), Event::Eof => break, _ => {} } @@ -94,9 +102,22 @@ fn parse_xml(bytes: &[u8]) -> Result { } } -fn push_text(stack: &mut [El], t: &[u8]) { +/// The text an entity or character reference stands for (unknown ones stay as written). +fn entity(r: &BytesRef) -> String { + let name = String::from_utf8_lossy(r); + match r.resolve_char_ref() { + Ok(Some(c)) => c.to_string(), + _ => resolve_predefined_entity(&name).map_or_else(|| format!("&{name};"), str::to_string), + } +} + +/// Appends a text piece; `glue` joins it to the previous piece of the same run of text. +fn push_text(stack: &mut [El], t: &str, glue: bool) { if let Some(el) = stack.last_mut() { - el.text.push_str(&String::from_utf8_lossy(t)); + if glue && el.text.ends_with(' ') { + el.text.pop(); + } + el.text.push_str(t); // Whitespace keeps numbers split across text events apart. el.text.push(' '); } diff --git a/crates/formats/src/mesh_import/scene_tests.rs b/crates/formats/src/mesh_import/scene_tests.rs index 015724a1..573952c9 100644 --- a/crates/formats/src/mesh_import/scene_tests.rs +++ b/crates/formats/src/mesh_import/scene_tests.rs @@ -823,6 +823,24 @@ fn dae_polylist_z_up_units_and_node_transforms() { assert!(!cam.ortho && near(cam.fov, 30.0) && near(cam.yaw, 0.0) && near(cam.pitch, 0.0), "{cam:?}"); } +#[test] +fn dae_attribute_and_text_entities_are_decoded() { + let dae = DAE + .replace(r#""#, r#""#) + .replace(r#"name="Red""#, r#"name="R&D""#) + .replace(r#"30", "30"); + let r = import_mesh_bytes("scene.dae", dae.as_bytes()).unwrap(); + let m = &r.mesh; + let parts: Vec<&str> = m.submeshes.iter().map(|s| s.name.as_str()).collect(); + assert!(parts.contains(&"Tom & Jerry <\"'AB"), "{parts:?}"); + assert_eq!(m.materials, vec!["R&D".to_string(), "Blue".to_string()]); + assert_eq!(m.triangle_count(), 2 + 1 + 2); + let [cam] = r.cameras.as_slice() else { panic!("{:?}", r.cameras) }; + assert!((cam.fov - 30.0).abs() < 1e-3, "{cam:?}"); +} + #[test] fn glb_export_round_trips_with_textures() { let mesh = texturecraft_geom::primitives::material_ball(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 2d0bbdd4..5e29d054 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -230,7 +230,7 @@ fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { let target = if content { "content" } else { "mask" }; ui.label(caption(if content { tr("Add to the layer content") } else { tr("Add to the mask") })); - // Generators and compare masks always go to the mask, anchor points to the content + // Generators and compare masks always go to the mask; anchor points go where the others do let items = [ (tr("Add generator"), "effect.add.generator", json!({})), (tr("Add paint"), "effect.add.paint", json!({"target": target})), @@ -238,11 +238,10 @@ fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { (tr("Add levels"), "effect.add.levels", json!({"target": target})), (tr("Add compare mask"), "effect.add.compare", json!({})), (tr("Add filter"), "effect.add.filter", json!({"target": target, "filter": NEW_FILTER})), - (tr("Add anchor point"), "effect.add.anchor", json!({})), + (tr("Add anchor point"), "effect.add.anchor", json!({"target": target})), ]; for (label, command, params) in items { - let enabled = command != "effect.add.anchor" || !layer.is_group(); - if !ui.add_enabled(enabled, egui::Button::new(label)).clicked() { + if !ui.button(label).clicked() { continue; } @@ -251,6 +250,7 @@ fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { } let added = app.run(command, with(¶ms, json!({"layer": layer.id.0}))); + // The neutral filter is a placeholder: its slot opens the picker to choose the real one if command == "effect.add.filter" && let Some(effect) = added.as_ref().and_then(|result| result["effect"].as_u64()) @@ -298,6 +298,8 @@ const MIN_NAME_WIDTH: f32 = 20.0; /// Font sizes in an effect row: the eye, the name, the blend mode and its caret. const EYE_FONT_SIZE: f32 = 12.0; const EFFECT_NAME_FONT_SIZE: f32 = 11.5; +/// Height available to an effect name while it is edited. +const EFFECT_NAME_EDIT_HEIGHT: f32 = 20.0; const ROW_SMALL_FONT_SIZE: f32 = 11.0; const CARET_FONT_SIZE: f32 = 8.0; /// Room for the caret at the right of the blend mode's name. @@ -402,7 +404,7 @@ fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize, effect_group(app, ui, &layer, depth, true, false); } - // A line under the layer and its effects separates it from the next layer + // A line under the layer and its effects separates it from the next layer. let tokens = Tokens::get(ui.ctx()); let available = ui.available_rect_before_wrap(); ui.painter().hline(available.x_range(), available.top() - 0.5, Stroke::new(1.0, tokens.separator)); @@ -422,7 +424,7 @@ fn thumb_box(ui: &Ui, app: &mut TextureCraftApp, rect: Rect, target: ThumbTarget let painter = ui.painter(); painter.rect_filled(rect, THUMBNAIL_ROUNDING, tokens.field); - // A checkerboard shows through where the layer has nothing (transparent texels) + // A checkerboard shows through where the layer has nothing (transparent texels). let cell_size = rect.width() / THUMB_CHECKER_CELLS as f32; let check = tokens.field.lerp_to_gamma(tokens.row_hover, 0.6); for y in 0..THUMB_CHECKER_CELLS { @@ -431,7 +433,7 @@ fn thumb_box(ui: &Ui, app: &mut TextureCraftApp, rect: Rect, target: ThumbTarget } } - // Only rows on screen ask for a picture + // Only rows on screen ask for a picture. if ui.is_rect_visible(rect) && let Some(texture) = app.layer_panel.texture(ui.ctx(), &app.session, target) { @@ -519,7 +521,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize x += FOLDER_CARET_SIZE; } - // Content thumbnail: the layer's own result in the displayed channel + // Content thumbnail: the layer's own result in the displayed channel. let channel = app.ui.layer_channel; let thumbnail = Rect::from_min_size(pos2(x, rect.center().y - thumbnail_size * 0.5), vec2(thumbnail_size, thumbnail_size)); if !thumb_box(ui, app, thumbnail, ThumbTarget::Content { layer: layer.id, channel }, !layer.visible) { @@ -532,7 +534,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } x = thumbnail.right() + THUMBNAIL_SPACING; - // An instance draws its source's content, blending and (unless it has its own) mask + // An instance draws its source's content, blending and (unless it has its own) mask. let project = &app.session.doc.project; let source = layer.instance_source().map(|source| { let set = project.locate(source).and_then(|(set, _, _)| project.texture_sets.get(set)).map(|set| set.name.as_str()).unwrap_or("?"); @@ -541,7 +543,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.clone()); let blend = project.content_layer(layer.id).and_then(|content| content.blend(channel)); - // Mask thumbnail, selectable on its own; or the slot that adds one + // Mask thumbnail, selectable on its own; or the slot that adds one. let mask_rect; if let Some(mask) = &mask { let mask_target = selected && !targets_content(app); @@ -577,7 +579,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize ); } } else { - // The empty slot adds a mask to this layer + // The empty slot adds a mask to this layer. let slot_size = thumbnail_size.min(MASK_SLOT_SIZE); mask_rect = Rect::from_min_size(pos2(x, rect.center().y - slot_size * 0.5), vec2(slot_size, slot_size)); let slot = ui.interact(mask_rect, ui.scope_id().with(("mask_slot", layer.id.0)), Sense::click()).on_hover_text(tr("Add mask")); @@ -590,7 +592,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } x = mask_rect.right() + THUMBNAIL_GAP; - // Name (or rename editor) with the quieter subtitle under it + // Name (or rename editor) with the quieter subtitle under it. let (name_rect, show_blend) = layer_name_layout(rect, x); let show_name = name_rect.width() >= MIN_NAME_WIDTH; if !show_name { @@ -603,13 +605,13 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize if renaming { let mut editor_ui = ui.new_child(egui::UiBuilder::new().max_rect(name_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); if let Some((_, text)) = app.ui.rename.as_mut() { - // Escape reaches us instead of just unfocusing the field, so it can cancel + // Escape reaches us instead of just unfocusing the field, so it can cancel. let filter = egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, escape: true, ..Default::default() }; let editor = editor_ui.add(egui::TextEdit::singleline(text).desired_width(name_rect.width()).event_filter(filter)); if ui.input(|input| input.key_pressed(egui::Key::Escape)) { app.ui.rename = None; } else if editor.lost_focus() { - // Enter or a click elsewhere + // Enter or a click elsewhere. let name = text.trim().to_string(); app.ui.rename = None; if !name.is_empty() && name != layer.name { @@ -641,7 +643,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize painter.galley(pos2(name_rect.left(), rect.center().y + NAME_LINE_GAP), subtitle, tokens.text_dim); } - // Blend mode and opacity of the displayed channel, stacked at the right + // Blend mode and opacity of the displayed channel, stacked at the right. let mode_rect = Rect::from_min_size( pos2(rect.right() - RIGHT_COLUMN - ROW_CONTROL_GAP, rect.center().y - ROW_CONTROL_HEIGHT - ROW_STACK_GAP), vec2(RIGHT_COLUMN, ROW_CONTROL_HEIGHT), @@ -667,7 +669,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize painter.text(mode_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(ROW_SMALL_FONT_SIZE), tokens.text_dim); } - // Interaction: select, rename, drag & drop, context menu + // Interaction: select, rename, drag & drop, context menu. let on_control = eye_response.clicked() || content_response.clicked(); if row.clicked() && !on_control && !renaming { app.run("layer.select", json!({"layer": layer.id.0})); @@ -950,8 +952,15 @@ fn effect_row( let show_blend = controls_left - ROW_CONTROL_GAP - name_left >= MIN_NAME_WIDTH; let name_right = if show_blend { controls_left - ROW_CONTROL_GAP } else { rect.right() - ROW_RIGHT_PADDING }; let name_color = if visible { tokens.text } else { tokens.text_dim }; - let galley = elided(&painter, effect.name.clone(), EFFECT_NAME_FONT_SIZE, name_color, (name_right - name_left).max(MIN_NAME_WIDTH)); - painter.galley(pos2(name_left, rect.center().y - galley.size().y * 0.5), galley, tokens.text); + let renaming = app.ui.rename.as_ref().is_some_and(|(id, _)| *id == effect_id.0); + if renaming { + let half_height = EFFECT_NAME_EDIT_HEIGHT * 0.5; + let name_rect = Rect::from_min_max(pos2(name_left, rect.center().y - half_height), pos2(name_right, rect.center().y + half_height)); + effect_rename_editor(app, ui, name_rect, effect); + } else { + let galley = elided(&painter, effect.name.clone(), EFFECT_NAME_FONT_SIZE, name_color, (name_right - name_left).max(MIN_NAME_WIDTH)); + painter.galley(pos2(name_left, rect.center().y - galley.size().y * 0.5), galley, tokens.text); + } if show_blend { let mode_width = EFFECT_BLEND_WIDTH - ROW_CONTROL_GAP - EFFECT_OPACITY_WIDTH; let mode_rect = Rect::from_center_size(pos2(controls_left + mode_width * 0.5, rect.center().y), vec2(mode_width, ROW_CONTROL_HEIGHT)); @@ -970,6 +979,8 @@ fn effect_row( if eye_response.clicked() { app.run("effect.set", json!({"effect": effect_id.0, "visible": !visible})); + } else if row.double_clicked() && !renaming { + app.ui.rename = Some((effect_id.0, effect.name.clone())); } else if row.clicked() { app.run("layer.select", json!({"layer": layer.id.0, "target": effect_id.0})); } @@ -998,9 +1009,15 @@ fn effect_row( } row.context_menu(|ui| { + if ui.button(tr("Rename effect")).clicked() { + app.ui.rename = Some((effect_id.0, effect.name.clone())); + ui.close(); + } let keymap = app.ui.keymap.clone(); + // The row is selected before the paste runs, so a copied effect is all it needs let paste = texturecraft_engine::effect_clipboard::clipboard_effect(&app.session).is_some(); + // The clipboard items show the layer clipboard's shortcuts, which act on a selected effect for (label, command, keys, enabled) in [ (tr("Copy effect"), "effect.copy", Some("layer.copy"), true), @@ -1023,6 +1040,29 @@ fn effect_row( }); } +/// The name editor of `effect` in `rect`: Enter or a click elsewhere renames, Escape cancels. +fn effect_rename_editor(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, effect: &Effect) { + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(egui::Layout::left_to_right(egui::Align::Center))); + let Some((_, name_buffer)) = app.ui.rename.as_mut() else { return }; + + // Escape reaches us instead of just unfocusing the field, so it can cancel + let filter = egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, escape: true, ..Default::default() }; + let response = child + .add(egui::TextEdit::singleline(name_buffer).desired_width(rect.width()).font(egui::FontId::proportional(EFFECT_NAME_FONT_SIZE)).event_filter(filter)); + if ui.input(|input| input.key_pressed(egui::Key::Escape)) { + app.ui.rename = None; + } else if response.lost_focus() { + let name = name_buffer.trim().to_string(); + app.ui.rename = None; + if !name.is_empty() && name != effect.name { + app.run("effect.set", json!({"effect": effect.id.0, "name": name})); + } + } else if !response.has_focus() { + // Only until the field has focus (see the layer rename editor) + response.request_focus(); + } +} + /// The Geometry mask tool: what a click does, and the selected layer's parts. fn geometry_tool_section(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); @@ -1170,7 +1210,7 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { app.run("textureSet.uvTiles", json!({"ts": ts, "enabled": tiled})); } ui.end_row(); - // Each tile's own size (per-tile resolution) + // Each tile's own size (per-tile resolution). for &udim in &set.uv_tiles { let r = set.tile_resolution(udim); ui.label(RichText::new(format!(" {udim}")).color(tk.text_dim)); @@ -1250,7 +1290,7 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { .color(tk.text_dim), ); }); - // An image resource instead of a bake, or no map + // An image resource instead of a bake, or no map. ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.menu_button(RichText::new(ic::DOTS_THREE).size(13.0), |ui| { if let Some(name) = image_menu(app, ui) { @@ -1264,7 +1304,7 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { }); }); }); - // A shelf image dropped on the row becomes this mesh map + // A shelf image dropped on the row becomes this mesh map. let resp = row.response.interact(Sense::hover()).on_hover_text(tr("Drop an image from the Assets panel here to use it as this mesh map")); if let Some(name) = image_drop(ui, &resp) { app.run("textureSet.meshMap.set", json!({"ts": ts, "map": m.id(), "image": name})); @@ -2132,20 +2172,158 @@ fn with(base: &Value, extra: Value) -> Value { /// Anchor points below layer `reader` in its texture set: (effect id, "layer / anchor" label). pub(crate) fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String)> { - let p = &app.session.doc.project; - let Some((ts, _, _)) = p.locate(reader) else { return Vec::new() }; - p.walk(ts) + let project = &app.session.doc.project; + let Some((texture_set, _, _)) = project.locate(reader) else { return Vec::new() }; + project + .walk(texture_set) .into_iter() .map(|(id, _)| id) .take_while(|id| *id != reader) - .filter_map(|id| p.layers.get(&id)) - .flat_map(|l| l.content_effects.iter().filter(|e| matches!(e.kind, EffectKind::Anchor)).map(move |e| (e.id, format!("{} / {}", l.name, e.name)))) + .filter_map(|id| project.layers.get(&id)) + .flat_map(|layer| { + let mask = layer.mask.iter().flat_map(|mask| { + mask.effects.iter().filter(|effect| matches!(effect.kind, EffectKind::Anchor)).map(move |effect| { + let label = trf("{layer} / mask / {name}", &[("layer", &layer.name), ("name", &effect.name)]); + (effect.id, if mask.enabled { label } else { format!("{label} ({})", tr("Off")) }) + }) + }); + let content = layer + .content_effects + .iter() + .filter(|effect| matches!(effect.kind, EffectKind::Anchor)) + .map(|effect| (effect.id, format!("{} / {}", layer.name, effect.name))); + content.chain(mask).collect::>() + }) .collect() } +/// Anchor choices for an effect, valid for its owner and recorded below the displayed instance +pub(crate) fn effect_anchors_below(app: &TextureCraftApp, layer: LayerId, effect: LayerId) -> Vec<(LayerId, String)> { + let owner = app.session.doc.project.effect(effect).map_or(layer, |(owner, _)| owner); + let owner_anchors = anchors_below(app, owner); + if owner == layer { + return owner_anchors; + } + + let displayed_anchors = anchors_below(app, layer); + owner_anchors.into_iter().filter(|(id, _)| displayed_anchors.iter().any(|(displayed, _)| id == displayed)).collect() +} + +/// Whether anchor point `anchor` sits in a mask (it then records the mask's gray, whatever the channel). +fn anchor_in_mask(app: &TextureCraftApp, anchor: LayerId) -> bool { + let project = &app.session.doc.project; + project + .effect(anchor) + .and_then(|(owner, _)| project.layers.get(&owner)) + .is_some_and(|layer| layer.mask.iter().flat_map(|m| m.effects.iter()).any(|effect| effect.id == anchor)) +} + +/// Whether this mask anchor currently records a value +fn mask_anchor_enabled(app: &TextureCraftApp, anchor: LayerId) -> Option { + let project = &app.session.doc.project; + let (owner, _) = project.effect(anchor)?; + let mask = project.layers.get(&owner)?.mask.as_ref()?; + mask.effects.iter().any(|effect| effect.id == anchor).then_some(mask.enabled) +} + +/// The anchor points of `anchors` as menu entries under their own heading (a note when there +/// are none); returns the one clicked. +pub(crate) fn anchor_entries(ui: &mut Ui, anchors: &[(LayerId, String)], current: Option) -> Option { + ui.separator(); + ui.label(caption(tr("Anchor points"))); + if anchors.is_empty() { + ui.label(RichText::new(tr("No anchor point below this layer")).color(Tokens::get(ui.ctx()).text_dim)); + } + + let mut picked = None; + for (anchor, label) in anchors { + if ui.selectable_label(current == Some(*anchor), trf("Anchor: {name}", &[("name", label)])).clicked() { + picked = Some(*anchor); + } + } + picked +} + pub(crate) fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> String { let name = app.session.doc.project.effect(anchor).map(|(_, e)| e.name.clone()).unwrap_or_else(|| tr("missing").into()); - trf("Anchor: {name} ({channel})", &[("name", &name), ("channel", &tr(channel.label()))]) + let label = trf("Anchor: {name} ({channel})", &[("name", &name), ("channel", &tr(channel.label()))]); + if mask_anchor_enabled(app, anchor) == Some(false) { format!("{label} ({})", tr("Off")) } else { label } +} + +#[cfg(test)] +mod mask_anchor_label_tests { + use egui_kittest::Harness; + use serde_json::{Value, json}; + use texturecraft_engine::core::{Channel, LayerId}; + use texturecraft_engine::execute; + + use super::{anchor_label, anchors_below, effect_anchors_below}; + use crate::TextureCraftApp; + + #[test] + fn disabled_mask_anchors_keep_their_selection_and_show_off() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let lower = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({"layer": lower})).unwrap(); + let anchor = execute(&mut session, "effect.add.anchor", &json!({"layer": lower, "target": "mask"})).unwrap()["effect"].as_u64().unwrap(); + let upper = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.toggle", &json!({"layer": lower, "enabled": false})).unwrap(); + + let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let labels = anchors_below(harness.state(), LayerId(upper)); + assert!(labels.iter().any(|(id, label)| *id == LayerId(anchor) && label.contains("(Off)"))); + assert!(anchor_label(harness.state(), LayerId(anchor), Channel::Height).contains("(Off)")); + + execute(&mut harness.state_mut().session, "mask.toggle", &json!({"layer": lower, "enabled": true})).unwrap(); + let labels = anchors_below(harness.state(), LayerId(upper)); + assert!(labels.iter().any(|(id, label)| *id == LayerId(anchor) && !label.contains("(Off)"))); + assert!(!anchor_label(harness.state(), LayerId(anchor), Channel::Height).contains("(Off)")); + } + + #[test] + fn inherited_effect_pickers_list_anchors_below_the_owner() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let lower = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + let valid = execute(&mut session, "effect.add.anchor", &json!({"layer": lower})).unwrap()["effect"].as_u64().unwrap(); + let source = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({"layer": source})).unwrap(); + let fill = execute(&mut session, "effect.add.fill", &json!({"layer": source})).unwrap()["effect"].as_u64().unwrap(); + let generator = execute(&mut session, "effect.add.generator", &json!({"layer": source})).unwrap()["effect"].as_u64().unwrap(); + let middle = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + let invalid = execute(&mut session, "effect.add.anchor", &json!({"layer": middle})).unwrap()["effect"].as_u64().unwrap(); + let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].as_u64().unwrap(); + + assert!(execute(&mut session, "effect.set", &json!({"effect": fill, "anchor": invalid})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": generator, "microAnchor": invalid})).is_err()); + + let harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + assert!(anchors_below(harness.state(), LayerId(instance)).iter().any(|(id, _)| *id == LayerId(invalid))); + for effect in [fill, generator] { + let choices = effect_anchors_below(harness.state(), LayerId(instance), LayerId(effect)); + assert!(choices.iter().any(|(id, _)| *id == LayerId(valid))); + assert!(!choices.iter().any(|(id, _)| *id == LayerId(invalid))); + } + } + + #[test] + fn inherited_effect_pickers_hide_unrecorded_source_set_anchors() { + let mesh = texturecraft_engine::geom::primitives::material_ball(); + let mut session = texturecraft_engine::Session::new_project("test", mesh, "builtin:material_ball", None, 256).unwrap(); + let lower = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + let anchor = execute(&mut session, "effect.add.anchor", &json!({"layer": lower})).unwrap()["effect"].as_u64().unwrap(); + let source = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({"layer": source})).unwrap(); + let fill = execute(&mut session, "effect.add.fill", &json!({"layer": source, "anchor": anchor})).unwrap()["effect"].as_u64().unwrap(); + let generator = execute(&mut session, "effect.add.generator", &json!({"layer": source, "microAnchor": anchor})).unwrap()["effect"].as_u64().unwrap(); + let instance = execute(&mut session, "layer.instance", &json!({"layer": source, "ts": 1})).unwrap()["layer"].as_u64().unwrap(); + + let harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + assert!(anchors_below(harness.state(), LayerId(instance)).is_empty()); + for effect in [fill, generator] { + let choices = effect_anchors_below(harness.state(), LayerId(instance), LayerId(effect)); + assert!(choices.is_empty(), "source-set anchor {anchor} is not recorded for the instance"); + } + } } /// Space above a fill's Material caption, setting it apart from the projection @@ -2353,14 +2531,9 @@ fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Valu if let Some(name) = image_menu(app, ui) { app.run("layer.fill.set", set(json!({"image": name}))); } - if !anchors.is_empty() { - ui.separator(); - } - for (a, label) in anchors { - if ui.button(trf("Anchor: {name}", &[("name", label)])).clicked() { - app.run("layer.fill.set", set(json!({"anchor": a.0}))); - ui.close(); - } + if let Some(a) = anchor_entries(ui, anchors, fill.source(c).anchor()) { + app.run("layer.fill.set", set(json!({"anchor": a.0}))); + ui.close(); } }) .response @@ -2435,6 +2608,7 @@ fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Valu } } }); + // A shelf image dropped on the channel becomes its source if let Some(name) = image_drop(ui, &group.response.interact(Sense::hover())) { app.run("layer.fill.set", set(json!({"image": name}))); @@ -2454,7 +2628,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels), EffectKind::Fill { source, .. } => { ui.label(caption(tr("Fill"))); - let anchors = anchors_below(app, layer.id); + let anchors = effect_anchors_below(app, layer.id, effect_id); let current = match source { Source::Anchor { anchor, channel } => anchor_label(app, *anchor, *channel), Source::Uniform(_) => tr("Uniform value").to_string(), @@ -2465,10 +2639,8 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe if ui.selectable_label(matches!(source, Source::Uniform(_)), tr("Uniform value")).clicked() { app.run("effect.set", json!({"effect": id, "value": 1.0})); } - for (anchor, label) in &anchors { - if ui.selectable_label(source.anchor() == Some(*anchor), trf("Anchor: {name}", &[("name", label)])).clicked() { - app.run("effect.set", json!({"effect": id, "anchor": anchor.0})); - } + if let Some(anchor) = anchor_entries(ui, &anchors, source.anchor()) { + app.run("effect.set", json!({"effect": id, "anchor": anchor.0})); } }); match source { @@ -2478,6 +2650,10 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe app.run("effect.set", json!({"effect": id, "value": value, "merge": merge})); } } + Source::Anchor { anchor, .. } if anchor_in_mask(app, *anchor) => { + let note = if mask_anchor_enabled(app, *anchor) == Some(false) { tr("Off") } else { tr("A mask anchor reads as its mask's gray.") }; + ui.label(RichText::new(note).color(tokens.text_dim)); + } Source::Anchor { channel, .. } => { let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default(); combo(ui, tr("Channel"), tr(channel.label()), |ui| { @@ -2502,10 +2678,12 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe } EffectKind::Anchor => { ui.label(caption(tr("Anchor point"))); - ui.label( - RichText::new(tr("Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.")) - .color(tokens.text_dim), - ); + let text = if anchor_in_mask(app, effect_id) { + tr("Records the mask value at this point. Fill effects and generators in masks above can read it.") + } else { + tr("Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.") + }; + ui.label(RichText::new(text).color(tokens.text_dim)); } EffectKind::Paint => { let hint = if layer.content_effects.iter().any(|content| content.id == effect_id) { diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 63fe8008..d5246c68 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -3,10 +3,12 @@ use egui::{RichText, Ui}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; -use texturecraft_engine::core::{BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, OutputResolution, ResolutionMode, Source}; +use texturecraft_engine::core::{ + BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, MicroDetail, OutputResolution, ResolutionMode, Source, +}; use crate::TextureCraftApp; -use crate::dock::{anchor_label, anchors_below, image_drop, image_menu, mesh_map_color}; +use crate::dock::{anchor_entries, anchor_label, anchors_below, effect_anchors_below, image_drop, image_menu, mesh_map_color}; use crate::i18n::{baked_map_label, tr, trf}; use crate::theme::{Tokens, caption}; use crate::widgets::{combo, section, slider_edit}; @@ -47,6 +49,9 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { curvature_detail_properties(app, ui, id, generator.detail.as_ref()); } + if !matches!(generator.kind, GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction) { + micro_detail_properties(app, ui, id, generator.micro, layer); + } ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui.button(tr("Restore defaults")).clicked() { @@ -69,6 +74,34 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer } } +/// The painted height anchor and its influence on this generator +fn micro_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, micro: Option, layer: LayerId) { + let tokens = Tokens::get(ui.ctx()); + ui.label(caption(tr("Micro detail"))) + .on_hover_text(tr("Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.")); + let anchors = effect_anchors_below(app, layer, LayerId(id)); + let current = match micro { + Some(detail) => anchors.iter().find(|(anchor, _)| *anchor == detail.anchor).map_or_else(|| tr("missing").to_string(), |(_, label)| label.clone()), + None => tr("None").to_string(), + }; + combo(ui, tr("Anchor point"), current, |ui| { + if ui.selectable_label(micro.is_none(), tr("None")).clicked() { + app.run("effect.set", json!({"effect": id, "microAnchor": null})); + } + if let Some(anchor) = anchor_entries(ui, &anchors, micro.map(|detail| detail.anchor)) { + app.run("effect.set", json!({"effect": id, "microAnchor": anchor.0})); + } + }); + if let Some(detail) = micro { + let mut amount = detail.amount; + if let Some(merge) = slider_edit(ui, tr("Amount"), &mut amount, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "microAmount": amount, "merge": merge})); + } + } else if anchors.is_empty() { + ui.label(RichText::new(tr("Add an anchor point to a layer below to use its height as micro detail.")).color(tokens.text_dim)); + } +} + /// What a generator kind makes, its category and its tags (read only). fn attributes(ui: &mut Ui, kind: GeneratorKind) { let tokens = Tokens::get(ui.ctx()); @@ -251,6 +284,7 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { "resolution": format!("{:?}", defaults.resolution.mode), "customResolution": defaults.resolution.custom, "resolutionFactor": defaults.resolution.factor, + "microAnchor": null, }); if let Some(detail) = defaults.detail { params["mode"] = json!(format!("{:?}", detail.mode)); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index bf484086..39a77aca 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1131,6 +1131,21 @@ pub const TABLE: &[(&str, &str)] = &[ ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" لا يمكن تعبئتها: حدد طبقة رسم أو قناع طبقة"), ("The file dialog couldn't be shown: {error}", "تعذر عرض نافذة الملفات: {error}"), ("The project changed while the dialog was open, so nothing was done", "تغيّر المشروع أثناء فتح النافذة، لذا لم يُنفَّذ أي إجراء"), + ("A mask anchor reads as its mask's gray.", "تُقرأ نقطة الارتكاز في القناع كرمادي ذلك القناع."), + ("Add an anchor point to a layer below to use its height as micro detail.", "أضف نقطة ارتكاز إلى طبقة أدناه لاستخدام ارتفاعها كتفاصيل دقيقة."), + ("Anchor points", "نقاط الارتكاز"), + ("Micro detail", "تفاصيل دقيقة"), + ("No anchor point below this layer", "لا توجد نقطة ارتكاز أسفل هذه الطبقة"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "الارتفاع المرسوم من نقطة ارتكاز أدناه: تُقرأ المناطق البارزة كحواف والمنخفضة كتجاويف.", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "تسجّل قيمة القناع عند هذه النقطة. يمكن لتأثيرات التعبئة والمولّدات في الأقنعة أعلاه قراءتها.", + ), + ("Rename effect", "إعادة تسمية التأثير"), + ("{layer} / mask / {name}", "{layer} / القناع / {name}"), ("Cores kept for the UI", "أنوية محجوزة للواجهة"), ("Max RAM while saving", "أقصى ذاكرة عند الحفظ"), ( diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 9ece6168..0ee8bc63 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1177,6 +1177,24 @@ pub const TABLE: &[(&str, &str)] = &[ "The project changed while the dialog was open, so nothing was done", "Das Projekt hat sich geändert, während der Dialog geöffnet war, daher wurde nichts ausgeführt", ), + ("A mask anchor reads as its mask's gray.", "Ein Masken-Anker liest sich als das Grau seiner Maske."), + ( + "Add an anchor point to a layer below to use its height as micro detail.", + "Füge einer Ebene darunter einen Ankerpunkt hinzu, um ihre Höhe als Mikrodetail zu nutzen.", + ), + ("Anchor points", "Ankerpunkte"), + ("Micro detail", "Mikrodetail"), + ("No anchor point below this layer", "Kein Ankerpunkt unter dieser Ebene"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "Gemalte Höhe eines Ankerpunkts darunter: Erhöhungen wirken als Kanten, Vertiefungen als Hohlräume.", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "Zeichnet den Maskenwert an dieser Stelle auf. Füll-Effekte und Generatoren in Masken darüber können ihn lesen.", + ), + ("Rename effect", "Effekt umbenennen"), + ("{layer} / mask / {name}", "{layer} / Maske / {name}"), ("Cores kept for the UI", "Für die Oberfläche reservierte Kerne"), ("Max RAM while saving", "Max. RAM beim Speichern"), ( diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 12e27eff..fbb2d61e 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1168,6 +1168,24 @@ pub const TABLE: &[(&str, &str)] = &[ "The project changed while the dialog was open, so nothing was done", "El proyecto cambió mientras el cuadro de diálogo estaba abierto, así que no se hizo nada", ), + ("A mask anchor reads as its mask's gray.", "Un ancla de máscara se lee como el gris de su máscara."), + ( + "Add an anchor point to a layer below to use its height as micro detail.", + "Añade un punto de anclaje a una capa inferior para usar su altura como microdetalle.", + ), + ("Anchor points", "Puntos de anclaje"), + ("Micro detail", "Microdetalle"), + ("No anchor point below this layer", "Ningún punto de anclaje bajo esta capa"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "Altura pintada de un punto de anclaje inferior: las zonas elevadas se leen como bordes y las hundidas como cavidades.", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "Registra el valor de la máscara en este punto. Los efectos de relleno y los generadores de las máscaras superiores pueden leerlo.", + ), + ("Rename effect", "Renombrar efecto"), + ("{layer} / mask / {name}", "{layer} / máscara / {name}"), ("Cores kept for the UI", "Núcleos reservados para la interfaz"), ("Max RAM while saving", "RAM máx. al guardar"), ( diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index a1d24889..6ed0bd03 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1192,6 +1192,24 @@ pub const TABLE: &[(&str, &str)] = &[ "The project changed while the dialog was open, so nothing was done", "Le projet a changé pendant que la boîte de dialogue était ouverte ; rien n'a été fait", ), + ("A mask anchor reads as its mask's gray.", "Une ancre de masque se lit comme le gris de son masque."), + ( + "Add an anchor point to a layer below to use its height as micro detail.", + "Ajoutez un point d'ancrage à un calque inférieur pour utiliser sa hauteur comme micro-détail.", + ), + ("Anchor points", "Points d'ancrage"), + ("Micro detail", "Micro-détail"), + ("No anchor point below this layer", "Aucun point d'ancrage sous ce calque"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "Hauteur peinte d'un point d'ancrage inférieur : les zones en relief se lisent comme des arêtes, les creux comme des cavités.", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "Enregistre la valeur du masque à cet endroit. Les effets de remplissage et les générateurs des masques au-dessus peuvent la lire.", + ), + ("Rename effect", "Renommer l'effet"), + ("{layer} / mask / {name}", "{layer} / masque / {name}"), ("Cores kept for the UI", "Cœurs réservés à l'interface"), ("Max RAM while saving", "RAM max. à l'enregistrement"), ( diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 6033a746..aaa43fa1 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1174,6 +1174,24 @@ pub const TABLE: &[(&str, &str)] = &[ "The project changed while the dialog was open, so nothing was done", "Il progetto è cambiato mentre la finestra di dialogo era aperta, quindi non è stato fatto nulla", ), + ("A mask anchor reads as its mask's gray.", "Un'ancora di maschera si legge come il grigio della sua maschera."), + ( + "Add an anchor point to a layer below to use its height as micro detail.", + "Aggiungi un punto di ancoraggio a un livello sottostante per usarne l'altezza come microdettaglio.", + ), + ("Anchor points", "Punti di ancoraggio"), + ("Micro detail", "Microdettaglio"), + ("No anchor point below this layer", "Nessun punto di ancoraggio sotto questo livello"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "Altezza dipinta da un punto di ancoraggio sottostante: le zone in rilievo si leggono come bordi, quelle incavate come cavità.", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "Registra il valore della maschera in questo punto. Gli effetti di riempimento e i generatori nelle maschere sopra possono leggerlo.", + ), + ("Rename effect", "Rinomina effetto"), + ("{layer} / mask / {name}", "{layer} / maschera / {name}"), ("Cores kept for the UI", "Core riservati all'interfaccia"), ("Max RAM while saving", "RAM max durante il salvataggio"), ( diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 1123a70c..17a5e3b5 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1159,6 +1159,24 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("The file dialog couldn't be shown: {error}", "ファイルダイアログを表示できませんでした: {error}"), ("The project changed while the dialog was open, so nothing was done", "ダイアログを開いている間にプロジェクトが変更されたため、何も実行されませんでした"), + ("A mask anchor reads as its mask's gray.", "マスクのアンカーはマスクのグレーとして読み取られます。"), + ( + "Add an anchor point to a layer below to use its height as micro detail.", + "下のレイヤーにアンカーポイントを追加すると、その高さをマイクロディテールとして使えます。", + ), + ("Anchor points", "アンカーポイント"), + ("Micro detail", "マイクロディテール"), + ("No anchor point below this layer", "このレイヤーの下にアンカーポイントがありません"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "下のアンカーポイントのペイントされた高さ:盛り上がった部分はエッジ、くぼんだ部分はキャビティとして読み取られます。", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "この位置のマスク値を記録します。上のマスクの塗りつぶしエフェクトとジェネレーターが読み取れます。", + ), + ("Rename effect", "エフェクト名を変更"), + ("{layer} / mask / {name}", "{layer} / マスク / {name}"), ("Cores kept for the UI", "UI用に確保するコア数"), ("Max RAM while saving", "保存時のRAM上限"), ( diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 1257cdf2..14f3859a 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1144,6 +1144,24 @@ pub const TABLE: &[(&str, &str)] = &[ ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\"은(는) 채울 수 없습니다: 페인트 레이어나 레이어 마스크를 선택하세요"), ("The file dialog couldn't be shown: {error}", "파일 대화 상자를 표시할 수 없습니다: {error}"), ("The project changed while the dialog was open, so nothing was done", "대화 상자가 열려 있는 동안 프로젝트가 변경되어 아무 작업도 수행하지 않았습니다"), + ("A mask anchor reads as its mask's gray.", "마스크의 앵커는 마스크의 회색 값으로 읽힙니다."), + ( + "Add an anchor point to a layer below to use its height as micro detail.", + "아래 레이어에 앵커 포인트를 추가하면 그 높이를 마이크로 디테일로 사용할 수 있습니다.", + ), + ("Anchor points", "앵커 포인트"), + ("Micro detail", "마이크로 디테일"), + ("No anchor point below this layer", "이 레이어 아래에 앵커 포인트가 없습니다"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "아래 앵커 포인트의 페인트된 높이: 솟은 부분은 가장자리로, 들어간 부분은 캐비티로 읽힙니다.", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "이 지점의 마스크 값을 기록합니다. 위쪽 마스크의 채우기 효과와 생성기가 읽을 수 있습니다.", + ), + ("Rename effect", "효과 이름 바꾸기"), + ("{layer} / mask / {name}", "{layer} / 마스크 / {name}"), ("Cores kept for the UI", "UI용으로 남겨 둘 코어"), ("Max RAM while saving", "저장 시 최대 RAM"), ( diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 6e0bf984..7e376db9 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1162,6 +1162,24 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("The file dialog couldn't be shown: {error}", "Não foi possível mostrar a caixa de diálogo de arquivos: {error}"), ("The project changed while the dialog was open, so nothing was done", "O projeto mudou enquanto a caixa de diálogo estava aberta, então nada foi feito"), + ("A mask anchor reads as its mask's gray.", "Uma âncora de máscara é lida como o cinza da máscara."), + ( + "Add an anchor point to a layer below to use its height as micro detail.", + "Adicione um ponto de ancoragem a uma camada abaixo para usar a altura dela como microdetalhe.", + ), + ("Anchor points", "Pontos de ancoragem"), + ("Micro detail", "Microdetalhe"), + ("No anchor point below this layer", "Nenhum ponto de ancoragem abaixo desta camada"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "Altura pintada de um ponto de ancoragem abaixo: áreas elevadas são lidas como bordas, áreas rebaixadas como cavidades.", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "Grava o valor da máscara neste ponto. Efeitos de preenchimento e geradores em máscaras acima podem lê-lo.", + ), + ("Rename effect", "Renomear efeito"), + ("{layer} / mask / {name}", "{layer} / máscara / {name}"), ("Cores kept for the UI", "Núcleos reservados para a interface"), ("Max RAM while saving", "RAM máx. ao salvar"), ( diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 93e1ea81..966df28b 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1090,6 +1090,21 @@ pub const TABLE: &[(&str, &str)] = &[ ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "“{layer}”无法填充:请选择绘画图层或图层遮罩"), ("The file dialog couldn't be shown: {error}", "无法显示文件对话框:{error}"), ("The project changed while the dialog was open, so nothing was done", "对话框打开期间项目已更改,因此未执行任何操作"), + ("A mask anchor reads as its mask's gray.", "蒙版中的锚点读取为该蒙版的灰度。"), + ("Add an anchor point to a layer below to use its height as micro detail.", "在下方图层添加锚点,即可将其高度用作微细节。"), + ("Anchor points", "锚点"), + ("Micro detail", "微细节"), + ("No anchor point below this layer", "此图层下方没有锚点"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "下方锚点绘制的高度:凸起处读取为边缘,凹陷处读取为凹腔。", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "记录此处的蒙版值。上方蒙版中的填充效果和生成器可以读取它。", + ), + ("Rename effect", "重命名效果"), + ("{layer} / mask / {name}", "{layer} / 蒙版 / {name}"), ("Cores kept for the UI", "为界面保留的核心数"), ("Max RAM while saving", "保存时的最大内存"), ( diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index d09cfc0c..796051e8 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -4,7 +4,7 @@ use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; -use texturecraft_engine::core::{BakedMap, EffectKind, Generator, GeneratorKind, LayerId, Source}; +use texturecraft_engine::core::{BakedMap, EffectKind, Generator, GeneratorKind, LayerId, MicroDetail, Source}; use texturecraft_engine::{ViewMode, execute}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -68,11 +68,17 @@ fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { let (mut harness, effect) = harness(false); let edits = json!({"effect": effect.0, "level": 0.9, "blur": 0.5, "balance": 0.2, "resolutionFactor": -2, "seed": 99}); execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); + if let EffectKind::Generator(generator) = &mut harness.state_mut().session.doc.project.effect_mut(effect).unwrap().kind { + generator.micro = Some(MicroDetail { anchor: LayerId(999), amount: 0.8 }); + } + harness.run_steps(3); harness.get_by_label("Restore defaults").scroll_to_me(); harness.run_steps(2); + harness.get_by_label("Restore defaults").click(); harness.run_steps(3); + assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Curvature)); } diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 919f199c..46968c26 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -479,6 +479,37 @@ fn nested_layers_snapshot() { save(&mut harness, &output_dir, "panel-layers-narrow-nested"); } +/// The mask anchor and generator micro controls in the integrated properties panel +#[test] +#[ignore] +fn mask_anchor_micro_detail_snapshot() { + use serde_json::{Value, json}; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let lower = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({"layer": lower})).unwrap(); + execute(&mut session, "effect.add.fill", &json!({"layer": lower, "value": 0.4})).unwrap(); + let anchor = execute(&mut session, "effect.add.anchor", &json!({"layer": lower, "target": "mask", "name": "Wear"})).unwrap()["effect"].as_u64().unwrap(); + let upper = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + let generator = execute(&mut session, "effect.add.generator", &json!({"layer": upper, "generator": "dirt", "microAnchor": anchor})).unwrap()["effect"] + .as_u64() + .unwrap(); + execute(&mut session, "layer.select", &json!({"layer": upper, "target": generator})).unwrap(); + + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_pixels_per_point(1.0) + .wgpu() + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.dock.focus(Panel::Properties); + harness.run_steps(6); + harness.get_by_label("Micro detail").scroll_to_me(); + save(&mut harness, &output_dir, "mask-anchor-micro-detail"); +} + #[test] #[ignore] fn path_tool_snapshots() { diff --git a/docs/features.md b/docs/features.md index 6c68cf6e..925476c9 100644 --- a/docs/features.md +++ b/docs/features.md @@ -42,7 +42,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA blur, directional and slope blur, sharpen, high pass, bevel, glow, warp, directional warp, mosaic and four material finishes), fills and paint. **Levels** shows a histogram of what it reads (the mask below it, or a content channel you pick) with its input range marked. - **Anchor points** record the stack at a layer so masks and fills higher up can react to it. + **Anchor points** record the stack at a layer (or, inside a mask, the mask value at that point) + so masks, fills and generators higher up can react to it; a generator can take an anchor's + painted height as **micro detail**. Double-click an effect to rename it. - **Masks** with a white or black background and a stack of effects: painted strokes, fills, **mesh-map generators** (edge wear, dirt, thin areas, curvature, AO, position and direction gradients, all with world-space noise), filters, ID color selection and compare. Alt+click a diff --git a/docs/ui-parity.md b/docs/ui-parity.md new file mode 100644 index 00000000..e8d6f0bb --- /dev/null +++ b/docs/ui-parity.md @@ -0,0 +1,126 @@ +# UI parity and missing work + +Reviewed 2026-11-16 against **main `62b2b13`, TextureCraft 0.6.1**, and reference app 12.2.0. +The [roadmap](../ROADMAP.md) carries the overall readiness estimate. This document records +specific UI gaps, their evidence, and the functional tasks actually exercised. + +## Scope and method + +The desktop apps were operated with mouse and keyboard input. TextureCraft's read-only +`session.inspect` and `ui.inspect` results confirmed document changes; whole-window screenshots +were inspected after the actions. Export-directory text was entered through the UI's accessibility +control. This is distinct from setting UI state or issuing an editing command directly. + +The main UI case used the built-in cube at 1024 px, the default English interface, and a +1920 × 1032 client area. A 1280 × 800 layout was also inspected. The reference used an original +UV cube; its title showed “Read only”, but painting, layer/mask creation and baking worked. +These were qualitative workflow comparisons, not matched-camera, matched-brush or image-difference +tests. No reference artwork, presets or screenshots are bundled here. + +**Evidence labels:** *UI* means exercised or inspected in the running interface; *source* means +confirmed in the assessed revision; *commands* means exercised through CLI/control commands. +Source-only findings are not presented as reproduced UI errors. Passing a small task does not +establish complete parity for its feature family. + +## Missing controls and workflows + +P1 affects frequent editing or delivery tasks. P2 is important depth or usability work. IDs are +stable review references, not a complete inventory of the reference interface. + +| ID | Priority | Missing capability | Evidence and current workaround | Acceptance check | +|---|---|---|---|---| +| UI-01 | P1 | Effect menu on the mask thumbnail | **UI + source.** Right-clicking the thumbnail did not open its own menu. The reference exposes mask operations and effect creation there. TextureCraft's layer-name context menu does add effects to the selected mask; adding a generator through that route worked | Right-click a mask thumbnail, add a generator/filter, and verify the effect belongs to that mask without changing the target first | +| UI-03 | P1 | Independent U/V tiling and a link/unlink control | **UI + source.** The fill panel has one Scale / tiling value. `projection_transform` reads the first UV scale component and submits a scalar; the model stores two components. The reference exposes two linked values | Set U = 2 and V = 5, switch projections/selections, and reopen the project without silently coupling the values | +| UI-04 | P1 | Fill sampling/filtering and UV wrap controls | **UI + source.** The reference fill panel exposes filtering and wrapping. TextureCraft's fill editor exposes projection, transforms and channel sources without those controls. No per-fill UI workaround was established | Set filtering and wrapping per fill, inspect the difference at a UV border, and retain the settings across save/reopen | +| UI-05 | P2 | Physical-size fill scaling | **UI + source.** The reference Scale menu offers tiling or physical size. TextureCraft exposes dimensionless scale only | Give a pattern a physical size and show that it keeps that size on meshes with different dimensions | +| UI-06 | P2 | Warp and per-UV-tile fill projection choices | **UI + source.** Both choices were visible in the reference projection menu. TextureCraft's ordinary fill picker has UV, tri-planar, planar, spherical and cylindrical choices; decals have a separate editor. A warp filter is a different operation | Exercise the two projection workflows on a multi-tile asset, with explicit controls, persistence and command inspection | +| UI-08 | P2 | Save a reusable user smart mask | **UI + source.** The reference mask menu has a smart-mask creation action. TextureCraft offers built-in smart masks and Create smart material, but no equivalent action for saving just the edited mask | Save a multi-effect mask, apply it to another layer/project, and retain its parameters and resource dependencies | +| UI-09 | P2 | Export/copy a mask bitmap from its context menu | **UI.** The reference exposes file and clipboard mask export; these actions are absent from TextureCraft's inspected menu. Previewing a mask is available, and is not a full-resolution bitmap-export check | Export the evaluated grayscale mask at its texture/tile resolution with explicit bit depth and orientation; test the file and clipboard paths | +| UI-10 | P1 | MaterialX output from the texture-export dialog | **UI + source + commands.** The dialog has no MaterialX option and `export_params` does not forward `materialX`. Command export with the OpenPBR preset successfully wrote `.mtlx` and maps | Enable MaterialX in the UI, preview the manifest and texture outputs, export, and validate the same result as the command route | +| UI-11 | P1 | Configurable project/display color-management workflow | **Source.** `DisplaySettings` provides fixed Linear/ACES-filmic tone mapping; export has fixed color spaces and metadata. There is no OCIO configuration/display/view model to expose in project or display settings | Select a configuration, working space and display/view transform; retain them; distinguish color channels from data maps through painting, preview and export | + +UI-02 and UI-07 were findings at the assessed `62b2b13` revision and are no longer missing in +the integrated source. Effect rows now have a Rename action and editor, and anchors can record +intermediate mask values for higher layers. Engine and compositor regressions cover mask-anchor +consumption. The original UI task audit did not exercise these new controls; a live UI rename, +undo and save/reopen task remains to be repeated on the integrated build. + +The relevant implementations are [layer rows, menus and fill/brush editors](../crates/ui-egui/src/dock.rs), +[generator properties](../crates/ui-egui/src/generator_panel.rs), +[export settings and parameters](../crates/ui-egui/src/windows.rs), +[layer/effect/projection types](../crates/core/src/layer.rs), +[display settings](../crates/core/src/project.rs), and +[smart-mask commands](../crates/engine/src/smart_masks.rs). + +## Partial areas + +| ID | Area | Observed limit | Next check | +|---|---|---|---| +| UI-12 | Generator depth and property coverage | **UI + source.** The picker contains seven kinds. Switching to Position, changing Global balance and duplicating the effect worked. Shared global adjustments, resolution and input slots already exist; that does not establish the richer generator/control inventory in [#374](https://github.com/storytold/texturecraft/issues/374) | Audit each generator's inputs, micro-detail behavior and controls against the reference; do not count seven shared implementations as equivalent to its whole catalog | +| UI-13 | Narrow workspace readability | **UI.** At 1280 × 800 the app rendered, both views stayed visible and the toolbar exposed scroll arrows. Layer names/types became heavily truncated, the layer toolbar wrapped, and Properties needed scrolling. This was not an input-failure or docking-persistence test | Repeat the editing tasks at smaller sizes, widen/rearrange panels, check full-name tooltips and keyboard access, and retain the layout after restart | + +Broader properties/filter work remains tracked in +[#433](https://github.com/storytold/texturecraft/issues/433). Its individual rows need checking +against current code; an open issue is not proof that every control it lists is still missing. + +## Functional task audit + +These twenty check groups include UI, mixed-surface and command-only cases. They are an evidence +list, not a feature-completion denominator. + +| Check | Surface | Result | Observable evidence / limit | +|---|---|---|---| +| F01 New project | UI | Pass | Ctrl+N, built-in Cube, 1024 px, Create produced a new project with one empty paint layer. The native mesh-file selection path was not completed in this deeper pass | +| F02 Paint in 3D | UI | Pass | A mouse drag produced a visible stroke in 3D and its UV representation; inspection showed a Paint stroke undo step and painted tiles | +| F03 Paint in 2D | UI | Pass | A separate UV-view drag increased painted tiles from 7 to 21 per active channel and changed the visible image | +| F04 Undo and redo | UI | Pass | Ctrl+Z restored 7 tiles and history depth 2; Ctrl+Y restored 21 tiles and depth 3 | +| F05 View switching | UI | Pass | F2 selected Only3D, F3 Only2D and F1 Split; the screenshots changed accordingly | +| F06 Brush gesture | UI | Pass | Ctrl+right-drag changed size from 8 to about 12.94 and hardness from 50 to about 38. This also demonstrates that diagonal movement changes both parameters; pen precision was not tested | +| F07 Shelf search and material application | UI | Pass | Searching for car and dragging Car Paint onto the mesh added a red fill layer and an Add Car Paint history step | +| F08 Fill layer and black mask | UI | Pass | Layer toolbar added a fill; the layer-name context menu added a black mask and selected the mask target | +| F09 Generator editing | UI | Pass | Layer context menu added a generator to that mask. Selecting Position and dragging Global balance changed the mask/viewport; inspection recorded balance about 0.279 | +| F10 Duplicate an effect | UI | Pass | Ctrl+D produced a separate Generator copy with the same parameters and a Duplicate effect history step | +| F11 UV rectangle fill | UI | Pass | Tool 4, UV-island mode and a rectangle across two UV islands wrote 88 tiles per painted channel on a new paint layer. Undo removed that fill. Topology was visible in the tool | +| F12 Bake from the UI | UI | Pass | F8, 256 px, low mesh used as high mesh, Check All and Bake completed all ten map types. The UI log reported CPU execution; this is separate from the GPU command check | +| F13 Texture-export flow | UI + accessibility text entry | Pass | Inspected Settings, Output templates and List of exports, then clicked Export. Eight 1024 px PNGs decoded successfully; all eight were byte-identical to command exports from the same saved project/options. The base-color output was inspected visually. Template creation/editing was not exercised | +| F14 Save and reopen | Mixed | Pass within scope | Ctrl+S and the native Save As dialog saved four layers, two generator effects, 21 painted tiles per channel and ten 256 px baked maps. Reopening through `file.open` matched inspected layers, texture sets and mesh. This was not a complete keyboard-only open-dialog test | +| F15 Smaller window | Scripted resize + UI inspection | Partial | 1280 × 800 rendered with working layout structure; the readability limits are UI-13. No full task suite at that size | +| F16 Reference workflow | Reference UI | Pass within scope | Pointer painting, paint/fill-layer creation, a black mask and an empty generator slot worked. A seven-map self-bake at 1024 px completed with map thumbnails and completion entries. Reference save/export and output equivalence were not tested | +| F17 GPU bake | Commands, earlier pass | Pass | All ten maps at 128 px / 16 rays completed; result identified the GTX 1080 GPU tracer. This does not prove that the UI bake used that path | +| F18 High-to-low transfer | CLI | Pass within scope | A two-triangle plane received normal and height from a separate 1,152-triangle analytic surface at 128 px on the CPU. Both maps varied; this was not a reference comparison or absolute-height calibration | +| F19 UDIM sizes and packed channels | CLI | Pass | Tiles 1001/1002 exported at 128/256 px respectively. Both packed ORM maps sampled RGB (255,153,51), matching AO 1, roughness 0.6 and metallic 0.2 | +| F20 Scene/material interchange | Commands, earlier pass | Pass within scope | Textured GLB and USDA reopened in TextureCraft with the original geometry/material; OpenPBR MaterialX XML parsed and referenced exported maps. External consumers/renderers remain unchecked | + +F18 used an original surface over x,z ∈ [-1,1], with height +`y = 0.06 + 0.1 * exp(-6 * (x*x + z*z))`, a 24 × 24 quad grid, matching UVs and frontal/rear +distance settings of 0.3. Normal and height were exported as 16-bit PNG. Interior samples read +through an 8-bit display decoder ranged 103–152 in normal R/G and 176–255 in height. These ranges +establish nonconstant transfer only; they are not full-precision error bounds. F19 used the +built-in `udim_plane`, a uniform fill and a tile-1002 resolution override. + +## Avoid stale missing-feature claims + +- Polygon fill already has triangle, polygon, connected-mesh and UV-island modes, a rectangle + selection workflow and topology display. F11 exercised the UV rectangle route; a full trim-sheet + authoring task is still unverified. +- The 2D paint cursor was visible, and direct 2D painting worked. This does not reproduce the older + cursor/painting reports on this setup. +- Brush size/hardness and flow/angle gestures have a visible hint. Hardness is present under + Flow and opacity; Angle has its own section. Their absence must not be inferred from the initial + scrolled position. The broader precision/shortcut concerns in + [#545](https://github.com/storytold/texturecraft/issues/545) still need an input-device task test. +- The shelf displayed four columns at the larger size, with type controls and search. Do not + treat every older shelf-layout request as a currently missing implementation. +- A missing mask-thumbnail menu does not mean mask effects are unavailable: the layer-name menu + worked. A missing MaterialX UI option does not mean the exporter is absent. + +## Still unverified + +Pen pressure/tilt and other input hardware; brush-feel matching; projection/stencil, clone, +smudge, path and symmetry task suites; a complete trim-sheet task; creating and editing output +templates; docking/floating/restart persistence; history-panel navigation; many-set/many-tile +projects; long sessions and recovery; matched performance budgets; and destination-app image +fidelity. The new `.spp` reader is a future goal, not a tested capability. + +No implementation fixes were made in this assessment. The build from the earlier pass was +reused; the full Rust tests, clippy, wasm and other operating-system builds were not rerun.