mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-23 16:00:45 +01:00
Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts: # apps/texturecraft-cli/tests/cli.rs
This commit is contained in:
commit
1fc73bc87d
101 files changed
+6028
-280
No files matched your search
+1
-1
@@ -32,7 +32,7 @@ These come from Rust crate dependencies (not files in this repository) and keep
|
||||
| Asset | Used for | Author | Source | License |
|
||||
|---|---|---|---|---|
|
||||
| Phosphor Icons (regular), via the `egui-phosphor` crate (vendored in `vendor/egui-phosphor` for egui 0.37) | Every UI icon (tools, layers, panels) | Phosphor Icons (Helena Zhang, Tobias Fried) | https://phosphoricons.com, https://github.com/amPerl/egui-phosphor | MIT (icons); crate MIT OR Apache-2.0 |
|
||||
| egui default fonts (Ubuntu-Light, Hack, Noto Emoji, emoji-icon-font), via `epaint_default_fonts` | UI text | Canonical / Source Foundry / Google / Jessie Jung | https://github.com/emilk/egui | Ubuntu Font Licence 1.0, MIT + Bitstream Vera License, OFL 1.1, MIT |
|
||||
| egui default fonts (Ubuntu-Light, Hack, Noto Emoji, emoji-icon-font), via `epaint_default_fonts` | UI text; Ubuntu Light and Hack also as the built-in fonts for text alphas and decals | Canonical / Source Foundry / Google / Jessie Jung | https://github.com/emilk/egui | Ubuntu Font Licence 1.0, MIT + Bitstream Vera License, OFL 1.1, MIT |
|
||||
| Only in builds made with `CRAFT_FONTS_DIR`: Inter Regular and SemiBold (desktop and web), from storytold/craft-fonts' Latin catalog (`crates/ui-egui/build.rs`) | Interface text | The Inter Project Authors | https://github.com/storytold/craft-fonts (pinned sources in its `fonts/latin-manifest.txt` and `ATTRIBUTION.md`) | OFL 1.1 |
|
||||
| Only in builds made with `CRAFT_FONTS_DIR`: BIZ UDPGothic Regular (desktop and web), Noto Sans CJK SC Regular (desktop) and Noto Sans Arabic Regular (desktop and web), from storytold/craft-fonts (`crates/ui-egui/build.rs`) | Japanese, Chinese and Arabic UI text | The BIZ UDGothic Project Authors (Morisawa Inc.); The Noto Project Authors | https://github.com/storytold/craft-fonts (pinned sources in its `fonts/manifest.txt` and `ATTRIBUTION.md`) | OFL 1.1 |
|
||||
|
||||
|
||||
Generated
+6
@@ -3896,6 +3896,7 @@ dependencies = [
|
||||
name = "texturecraft-engine"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"epaint_default_fonts",
|
||||
"image",
|
||||
"rayon",
|
||||
"serde",
|
||||
@@ -3949,8 +3950,11 @@ dependencies = [
|
||||
name = "texturecraft-paint"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"epaint_default_fonts",
|
||||
"harfrust",
|
||||
"rayon",
|
||||
"serde",
|
||||
"skrifa 0.44.0",
|
||||
"texturecraft-compose",
|
||||
"texturecraft-core",
|
||||
"texturecraft-geom",
|
||||
@@ -3964,6 +3968,7 @@ dependencies = [
|
||||
"bytemuck",
|
||||
"half",
|
||||
"image",
|
||||
"log",
|
||||
"pollster 0.4.0",
|
||||
"rayon",
|
||||
"texturecraft-bake",
|
||||
@@ -3971,6 +3976,7 @@ dependencies = [
|
||||
"texturecraft-core",
|
||||
"texturecraft-geom",
|
||||
"texturecraft-texel",
|
||||
"wasm-bindgen-futures",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
|
||||
@@ -32,6 +32,11 @@ serde_json = "1"
|
||||
glam = { version = "0.30", features = ["serde", "bytemuck"] }
|
||||
bytemuck = { version = "1", features = ["derive"] }
|
||||
rayon = "1"
|
||||
# Text alphas: shaping and glyph outlines, the versions egui's text layout already builds.
|
||||
harfrust = "0.12"
|
||||
skrifa = { version = "0.44", default-features = false, features = ["std"] }
|
||||
# The UI's built-in fonts (Ubuntu Light, Hack): text alphas fall back to them without system fonts.
|
||||
epaint_default_fonts = "0.37"
|
||||
log = "0.4"
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tga", "tiff", "exr", "hdr", "bmp", "webp"] }
|
||||
half = "2"
|
||||
|
||||
@@ -151,7 +151,7 @@ cd apps/texturecraft-web && trunk serve # web build
|
||||
cargo xtask ci # fmt, clippy, tests, layering, wasm
|
||||
```
|
||||
|
||||
You need Rust 1.95 or newer. The app opens with a baked sample project; **File ▸ New project** starts
|
||||
You need Rust 1.95 or newer. The app opens with a baked sample project and a start window (new project, open, recent projects); **File ▸ New project** starts
|
||||
from a built-in mesh, a project template or your own mesh file (UVs are generated if it has none).
|
||||
|
||||
Japanese, Chinese, Korean and Arabic interface text uses the fonts of
|
||||
|
||||
+11
-11
@@ -4,25 +4,25 @@ TextureCraft aims for 1:1 parity with Adobe Substance 3D Painter's texturing wor
|
||||
performance, a smaller footprint, every feature drivable by agents (MCP, CLI, control channel), and
|
||||
builds for Windows, macOS, Linux, FreeBSD and the web.
|
||||
|
||||
## Honest parity estimate (2026-11-01)
|
||||
## Honest parity estimate (2026-11-02)
|
||||
|
||||
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.
|
||||
|
||||
| Area | Weight | Done | What works | Main gaps |
|
||||
|---|---:|---:|---|---|
|
||||
| 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, recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) |
|
||||
| Texture sets | 6 | 95% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile**, one texture per tile at its own size, `$udim` export), list with visibility, sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | Filter radii and height slopes of a tile smaller than its atlas block follow the block |
|
||||
| Layer stack | 16 | 96% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels, invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; smart masks; mask view (Alt+click); 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; **27 library filters** (adjustments, 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 | 88% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color 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, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **particle brush** | Pen tilt (not exposed by the windowing layer) |
|
||||
| Materials and assets | 8 | 86% | 48 procedural materials (incl. car paint, velvet, brushed steel, skin, wax), 21 smart materials, 18 smart masks, **67 procedural brush alphas**, 22 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 |
|
||||
| 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**, image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) |
|
||||
| Texture sets | 6 | 95% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile**, 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 | Filter radii and height slopes of a tile smaller than its atlas block follow the block |
|
||||
| Layer stack | 16 | 97% | 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; 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 | 90% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color 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, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt (not exposed by the windowing layer) |
|
||||
| Materials and assets | 8 | 90% | 63 procedural materials (incl. car paint, velvet, brushed steel, skin, wax, ice, snow, bark), 21 smart materials, 18 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 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — |
|
||||
| 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, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes, 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** | Hardware ray tracing |
|
||||
| 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** | 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, `$udim` tiles, OBJ, 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 | 95% | 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, **shortcut editor** with conflict detection, tooltips with shortcuts; 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 | 75% | 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** | **≈ 93%** | | |
|
||||
| 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), `$udim` tiles, **MaterialX** (`file.exportTextures` with `materialX`: a `.mtlx` OpenPBR material per set, `<UDIM>` aware), OBJ, 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 | 96% | 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 **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%** | | |
|
||||
|
||||
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
|
||||
|
||||
@@ -35,10 +35,13 @@ USAGE:
|
||||
camera saved in the project (camera.add); --samples path traces it instead (Rendering
|
||||
mode), on the GPU when it has compute shaders, else (or with --cpu) on the CPU.
|
||||
texturecraft-cli new <mesh file | builtin:<id>> <out.tcraft> [--resolution <px>] [--sample]
|
||||
New project; --sample bakes and applies a smart material to every texture set.
|
||||
New project; --sample bakes and applies a smart material to every texture set. The
|
||||
sample's mesh maps are baked at the resolution up to 1024 px (most of the file's size),
|
||||
so a 2048 sample project is as large as a 1024 one.
|
||||
texturecraft-cli mcp [--bridge <port>] [--token <token>] [--read-root <dir>] [--write-root <dir>]
|
||||
MCP server on stdio: headless (file access only below the roots), or bridged to
|
||||
`texturecraft --control <port>`.
|
||||
`texturecraft --control <port>`. --automation-read-root / --automation-write-root are
|
||||
the same as --read-root / --write-root (mcp and serve).
|
||||
texturecraft-cli serve [--port <port>] [--read-root <dir>] [--write-root <dir>]
|
||||
JSON lines ({\"id\",\"method\",\"params\"}) on stdio, or on 127.0.0.1:<port> with a token.
|
||||
|
||||
@@ -57,8 +60,8 @@ const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[
|
||||
("export", &["--preset", "--format", "--padding", "--size"], &[]),
|
||||
("render", &["--size", "--view", "--camera", "--yaw", "--pitch", "--samples", "--bounces"], &["--cpu"]),
|
||||
("new", &["--resolution"], &["--sample"]),
|
||||
("mcp", &["--bridge", "--token", "--read-root", "--write-root"], &[]),
|
||||
("serve", &["--port", "--read-root", "--write-root"], &[]),
|
||||
("mcp", &["--bridge", "--token", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]),
|
||||
("serve", &["--port", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]),
|
||||
];
|
||||
|
||||
struct Args {
|
||||
@@ -375,7 +378,9 @@ fn new(a: &Args) -> R {
|
||||
}
|
||||
|
||||
fn workspace(a: &Args) -> Result<Filesystem, String> {
|
||||
let (r, w) = (a.get("--read-root").map(Path::new), a.get("--write-root").map(Path::new));
|
||||
// `--automation-*-root` is the spelling the other crafting apps use.
|
||||
let root = |k: &str| a.get(&format!("--automation-{k}")).or_else(|| a.get(&format!("--{k}"))).map(Path::new);
|
||||
let (r, w) = (root("read-root"), root("write-root"));
|
||||
if r.is_none() && w.is_none() {
|
||||
return Ok(Filesystem::Denied);
|
||||
}
|
||||
|
||||
@@ -97,6 +97,24 @@ fn info_on_a_mesh_reports_uvs() {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_takes_the_automation_root_spelling_too() {
|
||||
use std::io::Write as _;
|
||||
let d = tmp("automation-root");
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_texturecraft-cli"))
|
||||
.args(["serve", "--automation-write-root", p(&d)])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
child.stdin.take().unwrap().write_all(b"{\"id\":1,\"method\":\"project.save\",\"params\":{\"path\":\"a.tcraft\"}}\n").unwrap();
|
||||
let out = child.wait_with_output().unwrap();
|
||||
let reply: Value = serde_json::from_slice(&out.stdout).unwrap();
|
||||
assert_eq!(reply["ok"], true, "{reply}");
|
||||
assert!(d.join("a.tcraft").is_file());
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_on_a_builtin_mesh() {
|
||||
let info = json(&["info", "builtin:cube"]);
|
||||
|
||||
@@ -24,4 +24,4 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location", "KeyboardEvent", "EventTarget", "AddEventListenerOptions"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location", "KeyboardEvent", "BeforeUnloadEvent", "EventTarget", "AddEventListenerOptions"] }
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The eframe web runner: canvas lookup, backend selection, the loading screen's startup steps,
|
||||
//! browser shortcuts the app takes over, and startup errors shown in the page.
|
||||
//! browser shortcuts the app takes over, the unsaved-changes guard on close, and startup errors
|
||||
//! shown in the page.
|
||||
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
@@ -14,6 +15,7 @@ const PROGRESS_ID: &str = "texturecraft_progress";
|
||||
pub fn start() {
|
||||
eframe::WebLogger::init(log::LevelFilter::Info).ok();
|
||||
capture_app_shortcuts();
|
||||
guard_unsaved_changes();
|
||||
wasm_bindgen_futures::spawn_local(async {
|
||||
let Some(document) = web_sys::window().and_then(|w| w.document()) else {
|
||||
log::error!("no document");
|
||||
@@ -54,6 +56,7 @@ async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> {
|
||||
options,
|
||||
Box::new(|cc| {
|
||||
let mut app = TextureCraftApp::new(cc, session);
|
||||
app.ui.windows.start = app.ui.prefs.start_window;
|
||||
if let Some(rs) = &cc.wgpu_render_state {
|
||||
let backend = rs.adapter.get_info().backend;
|
||||
log::info!("TextureCraft: wgpu backend {backend:?}");
|
||||
@@ -117,6 +120,23 @@ fn capture_app_shortcuts() {
|
||||
on_key.forget();
|
||||
}
|
||||
|
||||
/// Closing or reloading the tab with unsaved changes makes the browser ask first (it shows its
|
||||
/// own message; pages can't word it).
|
||||
fn guard_unsaved_changes() {
|
||||
let Some(window) = web_sys::window() else { return };
|
||||
let on_unload = Closure::<dyn FnMut(web_sys::BeforeUnloadEvent)>::new(|e: web_sys::BeforeUnloadEvent| {
|
||||
if texturecraft_ui_egui::web_files::unsaved() {
|
||||
e.prevent_default();
|
||||
// Browsers that predate `preventDefault` here read the return value.
|
||||
e.set_return_value("unsaved");
|
||||
}
|
||||
});
|
||||
if let Err(e) = window.add_event_listener_with_callback("beforeunload", on_unload.as_ref().unchecked_ref()) {
|
||||
log::warn!("couldn't guard unsaved changes on close: {e:?}");
|
||||
}
|
||||
on_unload.forget();
|
||||
}
|
||||
|
||||
/// The baked sample project, or an empty material ball if that fails. Texture and bake sizes are
|
||||
/// kept small: the web build composites and bakes on one thread (bake 256 took ~12 s to start on a
|
||||
/// fast desktop CPU, 128 ~7.5 s).
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
//! Graphics adapter selection and multi-GPU configuration (#49).
|
||||
//!
|
||||
//! On machines with multiple GPUs (e.g. hybrid laptops or dual-GPU desktops with Intel/AMD iGPU and
|
||||
//! NVIDIA/AMD dGPU), TextureCraft must allow users to select which graphics processor renders the
|
||||
//! 3D viewport, and default to the high-performance discrete GPU for real-time PBR shading.
|
||||
//!
|
||||
//! Selection priority:
|
||||
//! 1. Window surface support: adapters that cannot present to the surface are ranked last.
|
||||
//! 2. Explicit filter: `--gpu <name>` CLI option or `WGPU_ADAPTER_NAME` environment variable (case-insensitive substring).
|
||||
//! 3. Hardware before software: physical GPUs before software/CPU rasterizers (llvmpipe, lavapipe, WARP).
|
||||
//! 4. Power preference: [`wgpu::PowerPreference::HighPerformance`] (default for 3D painting) prefers discrete GPUs,
|
||||
//! [`wgpu::PowerPreference::LowPower`] prefers integrated GPUs, and [`wgpu::PowerPreference::None`] preserves system order.
|
||||
//! 5. Backend preference: native backends (Vulkan, Metal, DX12) before OpenGL.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use eframe::NativeOptions;
|
||||
use eframe::egui_wgpu::WgpuSetup;
|
||||
use eframe::wgpu::{self, Backend, DeviceType, PowerPreference};
|
||||
|
||||
/// Environment variable for choosing an adapter by name or substring.
|
||||
pub const ADAPTER_NAME_ENV: &str = "WGPU_ADAPTER_NAME";
|
||||
|
||||
/// Environment variable for power preference (`high`, `low`, `none`).
|
||||
pub const POWER_PREF_ENV: &str = "WGPU_POWER_PREF";
|
||||
|
||||
/// Parses a power preference string from CLI or environment variable.
|
||||
pub fn parse_power_preference(s: &str) -> Result<PowerPreference, String> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"high" | "highperformance" | "high-performance" => Ok(PowerPreference::HighPerformance),
|
||||
"low" | "lowpower" | "low-power" => Ok(PowerPreference::LowPower),
|
||||
"none" | "default" => Ok(PowerPreference::None),
|
||||
other => Err(format!("invalid power preference `{other}`: expected `high`, `low`, or `none`")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A graphics adapter candidate inspected during adapter selection.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Candidate {
|
||||
pub name: String,
|
||||
pub vendor: u32,
|
||||
pub device: u32,
|
||||
pub device_type: DeviceType,
|
||||
pub backend: Backend,
|
||||
pub surface_supported: bool,
|
||||
}
|
||||
|
||||
impl Candidate {
|
||||
pub fn new(adapter: &wgpu::Adapter, surface: Option<&wgpu::Surface<'_>>) -> Self {
|
||||
let info = adapter.get_info();
|
||||
Self {
|
||||
name: info.name,
|
||||
vendor: info.vendor,
|
||||
device: info.device,
|
||||
device_type: info.device_type,
|
||||
backend: info.backend,
|
||||
surface_supported: surface.is_none_or(|s| adapter.is_surface_supported(s)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this candidate matches the given search filter (by name or backend).
|
||||
pub fn matches_filter(&self, filter: &str) -> bool {
|
||||
let filter_lower = filter.to_ascii_lowercase();
|
||||
self.name.to_ascii_lowercase().contains(&filter_lower) || format!("{:?}", self.backend).to_ascii_lowercase().contains(&filter_lower)
|
||||
}
|
||||
|
||||
/// Whether this is a CPU or software rasterizer.
|
||||
pub fn is_software(&self) -> bool {
|
||||
self.device_type == DeviceType::Cpu
|
||||
|| self.name.to_ascii_lowercase().contains("llvmpipe")
|
||||
|| self.name.to_ascii_lowercase().contains("lavapipe")
|
||||
|| self.name.to_ascii_lowercase().contains("warp")
|
||||
}
|
||||
}
|
||||
|
||||
/// Chooses the best adapter index from the candidates based on filter, power preference, and surface support.
|
||||
pub fn pick_adapter_index(candidates: &[Candidate], named_filter: Option<&str>, power: PowerPreference) -> Option<usize> {
|
||||
if candidates.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
candidates
|
||||
.iter()
|
||||
.enumerate()
|
||||
.min_by_key(|(orig_idx, c)| {
|
||||
// Surface support is required; unsupported adapters rank last.
|
||||
let surface_penalty = !c.surface_supported;
|
||||
|
||||
// Explicit named filter (e.g. --gpu nvidia, WGPU_ADAPTER_NAME=3080).
|
||||
let name_penalty = match named_filter {
|
||||
Some(filter) => !c.matches_filter(filter),
|
||||
None => false,
|
||||
};
|
||||
|
||||
// Hardware GPUs before software/CPU rasterizers.
|
||||
let software_penalty = c.is_software();
|
||||
|
||||
// Native backends before OpenGL (except when preserving system order).
|
||||
let backend_rank = match (power, c.backend) {
|
||||
(PowerPreference::None, _) => 0,
|
||||
(_, Backend::Vulkan | Backend::Metal | Backend::Dx12) => 0,
|
||||
(_, Backend::Gl) => 1,
|
||||
_ => 2,
|
||||
};
|
||||
|
||||
// Power preference ranking.
|
||||
let power_rank = match power {
|
||||
PowerPreference::HighPerformance => match c.device_type {
|
||||
DeviceType::DiscreteGpu => 0,
|
||||
DeviceType::IntegratedGpu => 1,
|
||||
DeviceType::Other => 2,
|
||||
DeviceType::VirtualGpu => 3,
|
||||
DeviceType::Cpu => 4,
|
||||
},
|
||||
PowerPreference::LowPower => match c.device_type {
|
||||
DeviceType::IntegratedGpu => 0,
|
||||
DeviceType::DiscreteGpu => 1,
|
||||
DeviceType::Other => 2,
|
||||
DeviceType::VirtualGpu => 3,
|
||||
DeviceType::Cpu => 4,
|
||||
},
|
||||
PowerPreference::None => match c.device_type {
|
||||
DeviceType::Cpu => 1,
|
||||
_ => 0,
|
||||
},
|
||||
};
|
||||
|
||||
(surface_penalty, name_penalty, software_penalty, power_rank, backend_rank, *orig_idx)
|
||||
})
|
||||
.map(|(idx, _)| idx)
|
||||
}
|
||||
|
||||
/// Configures `options` with adapter selection honoring `--gpu`, `WGPU_ADAPTER_NAME`, and `WGPU_POWER_PREF`.
|
||||
pub fn configure(options: &mut NativeOptions, cli_gpu: Option<String>, cli_power: Option<PowerPreference>) -> Result<(), String> {
|
||||
let effective_filter = cli_gpu.or_else(|| std::env::var(ADAPTER_NAME_ENV).ok());
|
||||
let effective_power = match cli_power {
|
||||
Some(p) => p,
|
||||
None => match std::env::var(POWER_PREF_ENV) {
|
||||
Ok(val) => parse_power_preference(&val)?,
|
||||
Err(_) => PowerPreference::HighPerformance,
|
||||
},
|
||||
};
|
||||
|
||||
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
|
||||
create.power_preference = effective_power;
|
||||
|
||||
let filter = effective_filter.clone();
|
||||
create.native_adapter_selector = Some(Arc::new(move |adapters, surface| {
|
||||
let candidates: Vec<Candidate> = adapters.iter().map(|a| Candidate::new(a, surface)).collect();
|
||||
|
||||
for (idx, c) in candidates.iter().enumerate() {
|
||||
log::info!("graphics adapter #{idx}: {} ({:?}, {:?}, surface supported: {})", c.name, c.device_type, c.backend, c.surface_supported);
|
||||
}
|
||||
|
||||
let chosen_idx = pick_adapter_index(&candidates, filter.as_deref(), effective_power)
|
||||
.ok_or_else(|| "no graphics adapter found that can present to the window".to_string())?;
|
||||
|
||||
let chosen = &candidates[chosen_idx];
|
||||
if !chosen.surface_supported {
|
||||
return Err("no graphics adapter found that can present to the window".to_string());
|
||||
}
|
||||
|
||||
if let Some(ref f) = filter
|
||||
&& !chosen.matches_filter(f)
|
||||
{
|
||||
log::warn!("no graphics adapter matched filter `{f}`; fell back to {}", chosen.name);
|
||||
}
|
||||
|
||||
log::info!("selected graphics adapter: {} ({:?}, {:?})", chosen.name, chosen.device_type, chosen.backend);
|
||||
|
||||
adapters.get(chosen_idx).cloned().ok_or_else(|| "selected adapter index out of range".to_string())
|
||||
}));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn dummy_candidate(name: &str, device_type: DeviceType, backend: Backend, surface_supported: bool) -> Candidate {
|
||||
Candidate { name: name.to_string(), vendor: 0, device: 0, device_type, backend, surface_supported }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_power_preferences_correctly() {
|
||||
assert_eq!(parse_power_preference("high").unwrap(), PowerPreference::HighPerformance);
|
||||
assert_eq!(parse_power_preference("high-performance").unwrap(), PowerPreference::HighPerformance);
|
||||
assert_eq!(parse_power_preference("low").unwrap(), PowerPreference::LowPower);
|
||||
assert_eq!(parse_power_preference("low-power").unwrap(), PowerPreference::LowPower);
|
||||
assert_eq!(parse_power_preference("none").unwrap(), PowerPreference::None);
|
||||
assert_eq!(parse_power_preference("default").unwrap(), PowerPreference::None);
|
||||
assert!(parse_power_preference("invalid").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn high_performance_default_prefers_discrete_gpu() {
|
||||
let candidates = vec![
|
||||
dummy_candidate("AMD Radeon 660M", DeviceType::IntegratedGpu, Backend::Vulkan, true),
|
||||
dummy_candidate("NVIDIA GeForce RTX 2050", DeviceType::DiscreteGpu, Backend::Vulkan, true),
|
||||
];
|
||||
|
||||
let selected = pick_adapter_index(&candidates, None, PowerPreference::HighPerformance);
|
||||
assert_eq!(selected, Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn low_power_prefers_integrated_gpu() {
|
||||
let candidates = vec![
|
||||
dummy_candidate("AMD Radeon 660M", DeviceType::IntegratedGpu, Backend::Vulkan, true),
|
||||
dummy_candidate("NVIDIA GeForce RTX 2050", DeviceType::DiscreteGpu, Backend::Vulkan, true),
|
||||
];
|
||||
|
||||
let selected = pick_adapter_index(&candidates, None, PowerPreference::LowPower);
|
||||
assert_eq!(selected, Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn none_power_preference_preserves_enumerated_order() {
|
||||
let candidates = vec![
|
||||
dummy_candidate("GPU A (GL)", DeviceType::DiscreteGpu, Backend::Gl, true),
|
||||
dummy_candidate("GPU B (Vulkan)", DeviceType::DiscreteGpu, Backend::Vulkan, true),
|
||||
];
|
||||
|
||||
let selected = pick_adapter_index(&candidates, None, PowerPreference::None);
|
||||
assert_eq!(selected, Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_filter_selects_specific_gpu() {
|
||||
let candidates = vec![
|
||||
dummy_candidate("Intel(R) UHD Graphics 770", DeviceType::IntegratedGpu, Backend::Vulkan, true),
|
||||
dummy_candidate("NVIDIA GeForce RTX 3080", DeviceType::DiscreteGpu, Backend::Vulkan, true),
|
||||
dummy_candidate("AMD Radeon RX 7900 XTX", DeviceType::DiscreteGpu, Backend::Vulkan, true),
|
||||
];
|
||||
|
||||
// Match by "3080"
|
||||
let selected = pick_adapter_index(&candidates, Some("3080"), PowerPreference::HighPerformance);
|
||||
assert_eq!(selected, Some(1));
|
||||
|
||||
// Match by "intel"
|
||||
let selected_intel = pick_adapter_index(&candidates, Some("intel"), PowerPreference::HighPerformance);
|
||||
assert_eq!(selected_intel, Some(0));
|
||||
|
||||
// Match by "7900"
|
||||
let selected_amd = pick_adapter_index(&candidates, Some("7900"), PowerPreference::HighPerformance);
|
||||
assert_eq!(selected_amd, Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_surface_is_ranked_last() {
|
||||
let candidates = vec![
|
||||
dummy_candidate("NVIDIA GeForce RTX 3080", DeviceType::DiscreteGpu, Backend::Vulkan, false),
|
||||
dummy_candidate("Intel(R) UHD Graphics 770", DeviceType::IntegratedGpu, Backend::Vulkan, true),
|
||||
];
|
||||
|
||||
// Even with HighPerformance, RTX 3080 cannot present to the surface, so Intel is chosen.
|
||||
let selected = pick_adapter_index(&candidates, None, PowerPreference::HighPerformance);
|
||||
assert_eq!(selected, Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hardware_gpu_preferred_over_software() {
|
||||
let candidates = vec![
|
||||
dummy_candidate("llvmpipe (LLVM 18.1.8, 256 bits)", DeviceType::Cpu, Backend::Vulkan, true),
|
||||
dummy_candidate("Intel(R) UHD Graphics 620", DeviceType::IntegratedGpu, Backend::Vulkan, true),
|
||||
];
|
||||
|
||||
let selected = pick_adapter_index(&candidates, None, PowerPreference::HighPerformance);
|
||||
assert_eq!(selected, Some(1));
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod control_server;
|
||||
mod gpu;
|
||||
mod window_frame;
|
||||
|
||||
use texturecraft_engine::Session;
|
||||
@@ -32,11 +33,17 @@ struct Args {
|
||||
file: Option<String>,
|
||||
control: Option<u16>,
|
||||
empty: bool,
|
||||
gpu: Option<String>,
|
||||
power_pref: Option<eframe::wgpu::PowerPreference>,
|
||||
}
|
||||
|
||||
fn parse_args() -> Result<Option<Args>, String> {
|
||||
let mut args = Args { file: None, control: None, empty: false };
|
||||
let mut it = std::env::args().skip(1);
|
||||
parse_args_from(std::env::args().skip(1))
|
||||
}
|
||||
|
||||
fn parse_args_from<I: IntoIterator<Item = String>>(it: I) -> Result<Option<Args>, String> {
|
||||
let mut args = Args { file: None, control: None, empty: false, gpu: None, power_pref: None };
|
||||
let mut it = it.into_iter();
|
||||
while let Some(a) = it.next() {
|
||||
match a.as_str() {
|
||||
"--version" | "-V" => {
|
||||
@@ -44,13 +51,24 @@ fn parse_args() -> Result<Option<Args>, String> {
|
||||
return Ok(None);
|
||||
}
|
||||
"--help" | "-h" => {
|
||||
println!("{}\n\nUsage: texturecraft [project.tcraft | mesh file] [--control <port>] [--empty]", version());
|
||||
println!(
|
||||
"{}\n\nUsage: texturecraft [project.tcraft | mesh file] [--control <port>] [--gpu <name>] [--power-pref <high|low|none>] [--empty]",
|
||||
version()
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
"--control" => {
|
||||
let p = it.next().ok_or("--control needs a port")?;
|
||||
args.control = Some(p.parse().map_err(|_| format!("invalid port `{p}`"))?);
|
||||
}
|
||||
"--gpu" => {
|
||||
let g = it.next().ok_or("--gpu needs a GPU name or pattern")?;
|
||||
args.gpu = Some(g);
|
||||
}
|
||||
"--power-pref" => {
|
||||
let p = it.next().ok_or("--power-pref needs high, low, or none")?;
|
||||
args.power_pref = Some(gpu::parse_power_preference(&p)?);
|
||||
}
|
||||
"--empty" => args.empty = true,
|
||||
f if !f.starts_with('-') => args.file = Some(f.to_string()),
|
||||
other => return Err(format!("unknown option `{other}`")),
|
||||
@@ -168,8 +186,14 @@ fn main() {
|
||||
viewport = viewport.with_icon(i);
|
||||
}
|
||||
let viewport = title_bar.viewport(viewport);
|
||||
let options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() };
|
||||
let mut options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() };
|
||||
if let Err(e) = gpu::configure(&mut options, args.gpu, args.power_pref) {
|
||||
eprintln!("texturecraft: {e}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
let control = args.control;
|
||||
// The start window offers new, open and recent projects, unless a file was given or a script drives the app.
|
||||
let start = args.file.is_none() && control.is_none();
|
||||
let r = eframe::run_native(
|
||||
APP_NAME,
|
||||
options,
|
||||
@@ -181,6 +205,7 @@ fn main() {
|
||||
let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_)));
|
||||
let mut app = TextureCraftApp::new(cc, session);
|
||||
app.title_bar = title_bar;
|
||||
app.ui.windows.start = start && app.ui.prefs.start_window;
|
||||
if let Some(port) = control {
|
||||
app.control = Some(control_server::start(port, cc.egui_ctx.clone()));
|
||||
}
|
||||
@@ -202,6 +227,27 @@ fn main() {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_gpu_and_power_preference_args() {
|
||||
let args = parse_args_from(["--gpu".to_string(), "nvidia".to_string()]).unwrap().unwrap();
|
||||
assert_eq!(args.gpu.as_deref(), Some("nvidia"));
|
||||
assert_eq!(args.power_pref, None);
|
||||
|
||||
let args = parse_args_from(["--power-pref".to_string(), "high".to_string()]).unwrap().unwrap();
|
||||
assert_eq!(args.power_pref, Some(eframe::wgpu::PowerPreference::HighPerformance));
|
||||
|
||||
let args = parse_args_from(["--power-pref".to_string(), "low".to_string(), "--gpu".to_string(), "3080".to_string()]).unwrap().unwrap();
|
||||
assert_eq!(args.power_pref, Some(eframe::wgpu::PowerPreference::LowPower));
|
||||
assert_eq!(args.gpu.as_deref(), Some("3080"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_or_invalid_gpu_args() {
|
||||
assert!(parse_args_from(["--gpu".to_string()]).is_err());
|
||||
assert!(parse_args_from(["--power-pref".to_string()]).is_err());
|
||||
assert!(parse_args_from(["--power-pref".to_string(), "unrecognized".to_string()]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_system_title_bar_setting_is_read_from_eframes_settings_file() {
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id()));
|
||||
|
||||
@@ -77,7 +77,7 @@ impl Gpu {
|
||||
_ => None,
|
||||
};
|
||||
if let Some(rgba) = aux {
|
||||
h.renderer.upload_aux(&h.queue, ts, res, &rgba);
|
||||
h.renderer.upload_aux(&h.device, &h.queue, ts, res, &rgba);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,13 +169,23 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3
|
||||
let (n, sheen_rough) = (get(Channel::Normal), scalar8(Channel::SheenRoughness));
|
||||
for i in 0..TILE_AREA {
|
||||
let px = &mut out[i * 4..i * 4 + 4];
|
||||
match n {
|
||||
Some(t) => {
|
||||
// The baked normal is the base the painted normal details sit on (as in export).
|
||||
let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE));
|
||||
let base = baked.sample(BakedMap::Normal, x, y, res);
|
||||
match (n, base) {
|
||||
(Some(t), None) => {
|
||||
for (k, d) in px.iter_mut().take(3).enumerate() {
|
||||
*d = u8_of(t.get(i * 3 + k).copied().unwrap_or(0));
|
||||
}
|
||||
}
|
||||
None => px[..3].copy_from_slice(&[128, 128, 255]),
|
||||
(detail, Some(base)) => {
|
||||
let detail = detail.map_or([0.5, 0.5, 1.0], |t| [0, 1, 2].map(|k| t.get(i * 3 + k).map_or(0.0, |v| *v as f32 / 65535.0)));
|
||||
let v = texturecraft_core::blend::rnm(base, detail);
|
||||
for (d, v) in px.iter_mut().zip(v) {
|
||||
*d = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
|
||||
}
|
||||
}
|
||||
(None, None) => px[..3].copy_from_slice(&[128, 128, 255]),
|
||||
}
|
||||
px[3] = sheen_rough(i);
|
||||
}
|
||||
@@ -231,6 +241,23 @@ mod tests {
|
||||
assert_eq!(half::f16::from_le_bytes([h[2], h[3]]).to_f32(), half::f16::from_f32(0.04).to_f32(), "default F0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_baked_normal_is_the_base_of_the_shown_normal() {
|
||||
// A baked normal tilted to +X (packed), 64² like the set.
|
||||
let tilted = [0.8f32, 0.5, 0.9];
|
||||
let baked = BakedMaps { resolution: 64, maps: [(BakedMap::Normal, std::sync::Arc::new(tilted.repeat(64 * 64)))].into_iter().collect() };
|
||||
let shown = |comp: &Composite| tile_bytes(comp, &baked, DisplayKind::Normal, 0, 0)[..3].to_vec();
|
||||
let pack = |v: [f32; 3]| v.map(|x| (x * 255.0 + 0.5) as u8).to_vec();
|
||||
// No normal channel: the baked normal as it is.
|
||||
assert_eq!(shown(&Composite::new(&[], 64)), pack(tilted));
|
||||
// A flat painted normal leaves it; a painted detail is re-oriented onto it.
|
||||
let mut comp = Composite::new(&[Channel::Normal], 64);
|
||||
comp.channels.get_mut(&Channel::Normal).unwrap().set(0, 0, &[to_u16(0.5), to_u16(0.5), to_u16(1.0)]);
|
||||
assert!(shown(&comp).iter().zip(pack(tilted)).all(|(a, b)| (*a as i32 - b as i32).abs() <= 1), "{:?}", shown(&comp));
|
||||
comp.channels.get_mut(&Channel::Normal).unwrap().set(0, 0, &[to_u16(0.5), to_u16(0.8), to_u16(0.9)]);
|
||||
assert_eq!(shown(&comp), pack(texturecraft_core::blend::rnm(tilted, [0.5, 0.8, 0.9])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glossiness_shows_as_roughness_and_specular_rides_in_height() {
|
||||
let mut comp = Composite::new(&[Channel::Glossiness, Channel::Specular], 64);
|
||||
|
||||
@@ -1846,6 +1846,101 @@ pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option<Vec<u8>> {
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Tiles [`effect_histogram`] samples at most (a million texels).
|
||||
const HISTOGRAM_TILES: usize = 256;
|
||||
|
||||
/// The tiles [`effect_histogram`] reads: an even sample of at most [`HISTOGRAM_TILES`], which
|
||||
/// keeps the cost flat up to 8K. The stride is odd: a power of two would divide the row length
|
||||
/// and sample the same few columns.
|
||||
fn histogram_tiles(width: u32, height: u32) -> Vec<(u32, u32)> {
|
||||
let all = all_tiles(width, height);
|
||||
let stride = all.len().div_ceil(HISTOGRAM_TILES).max(1) | 1;
|
||||
all.into_iter().step_by(stride).collect()
|
||||
}
|
||||
|
||||
/// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's mask
|
||||
/// below it, or (a content effect) the layer's `channel` below it where the layer has content,
|
||||
/// color components pooled and signed values mapped to 0..1. Over the texels the mesh covers
|
||||
/// (in an even sample of tiles on large sets); None for an unknown effect.
|
||||
pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: usize) -> Option<Vec<u32>> {
|
||||
let (owner, _) = inp.project.effect(effect)?;
|
||||
let bins = bins.max(1);
|
||||
// Evaluate the layer forced visible, its mask enabled, cut just below the effect.
|
||||
let mut cut = inp.project.clone();
|
||||
let l = cut.layers.get_mut(&owner)?;
|
||||
l.visible = true;
|
||||
let in_mask = match l.mask.as_mut().and_then(|m| m.effects.iter().position(|e| e.id == effect).map(|k| (m, k))) {
|
||||
Some((m, k)) => {
|
||||
m.enabled = true;
|
||||
m.effects.truncate(k);
|
||||
true
|
||||
}
|
||||
None => {
|
||||
let k = l.content_effects.iter().position(|e| e.id == effect)?;
|
||||
l.content_effects.truncate(k);
|
||||
false
|
||||
}
|
||||
};
|
||||
let cut_inp = Inputs { project: &cut, preview: None, ..*inp };
|
||||
let channels = cut.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default();
|
||||
let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height);
|
||||
// A field covers the bounding box of the tiles it is built for, which for a scattered sample
|
||||
// is the whole set: with a neighbourhood filter below, each tile gets its own.
|
||||
let probe = neighbourhood_fields(&cut_inp, &channels, tiles.get(..1).unwrap_or_default());
|
||||
let shared = probe.is_empty().then_some(probe);
|
||||
let bin = |v: f32| ((v.clamp(0.0, 1.0) * bins as f32) as usize).min(bins - 1);
|
||||
let hist = tiles
|
||||
.par_iter()
|
||||
.map(|&(tx, ty)| {
|
||||
let own;
|
||||
let fields = match &shared {
|
||||
Some(f) => f,
|
||||
None => {
|
||||
own = neighbourhood_fields(&cut_inp, &channels, &[(tx, ty)]);
|
||||
&own
|
||||
}
|
||||
};
|
||||
let mut h = vec![0u32; bins];
|
||||
// The mask is planned on its own: a layer with nothing drawn plans no node.
|
||||
let mask = if in_mask { layer_mask(&cut, owner).and_then(|m| mask_plan(&cut_inp, owner, m, tx, ty, Some(fields))) } else { None };
|
||||
let nodes = if in_mask { Vec::new() } else { plan(&cut_inp, &[owner], &channels, tx, ty, 0, Some(fields)) };
|
||||
let content = nodes.first().and_then(|n| n.chans.iter().find(|c| Channel::ALL.get(c.ch) == Some(&channel)).map(|c| (n, c)));
|
||||
if mask.is_none() && content.is_none() {
|
||||
return h;
|
||||
}
|
||||
let full = anchor_plan(&cut_inp, owner, &channels, tx, ty, Some(fields));
|
||||
for (x, y, o) in tile_texels(inp.gbuf, tx, ty) {
|
||||
let mut tex = Texel::new(&cut_inp, x, y, o, 0.0);
|
||||
if !full.is_empty() {
|
||||
tex.anchors_below(&full, owner);
|
||||
}
|
||||
if let Some(m) = &mask {
|
||||
if let Some(b) = h.get_mut(bin(tex.mask(m))) {
|
||||
*b += 1;
|
||||
}
|
||||
} else if let Some((n, c)) = content
|
||||
&& let Some((v, _)) = tex.content(&n.content, c)
|
||||
{
|
||||
// As levels reads them (`per_unit`); normal maps pass through levels unchanged.
|
||||
let (vals, signed) = match c.kind {
|
||||
ChannelKind::Color => (&v[..], false),
|
||||
ChannelKind::Scalar => (&v[..1], false),
|
||||
ChannelKind::Signed => (&v[..1], true),
|
||||
ChannelKind::NormalMap => (&v[..0], false),
|
||||
};
|
||||
for x in vals {
|
||||
if let Some(b) = h.get_mut(bin(if signed { x * 0.5 + 0.5 } else { *x })) {
|
||||
*b += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
h
|
||||
})
|
||||
.reduce(|| vec![0u32; bins], |a, b| a.iter().zip(&b).map(|(x, y)| x.saturating_add(*y)).collect());
|
||||
Some(hist)
|
||||
}
|
||||
|
||||
/// One flattened tile of one channel: (channel, tile, premultiplied value + coverage data).
|
||||
pub type FlatTile = (Channel, (u32, u32), Vec<u16>);
|
||||
|
||||
@@ -1962,6 +2057,17 @@ mod tests {
|
||||
(0..3).all(|i| (a[i] - b[i]).abs() < 2e-4)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn histogram_samples_spread_over_every_column() {
|
||||
assert_eq!(histogram_tiles(1024, 1024), all_tiles(1024, 1024), "small sets are read whole");
|
||||
for size in [2048, 4096, 8192] {
|
||||
let tiles = histogram_tiles(size, size);
|
||||
let columns: std::collections::BTreeSet<u32> = tiles.iter().map(|t| t.0).collect();
|
||||
assert!(tiles.len() <= HISTOGRAM_TILES, "{size}: {} tiles", tiles.len());
|
||||
assert!(columns.len() as u32 >= size / TILE / 2, "{size}: only {} columns", columns.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_stack_gives_channel_defaults() {
|
||||
let f = fixture();
|
||||
|
||||
@@ -16,7 +16,7 @@ pub mod store;
|
||||
pub use below::{BelowCache, StackKey};
|
||||
pub use display::{DisplayKind, tile_bytes};
|
||||
pub use eval::{
|
||||
Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, flatten_layer, mask_image,
|
||||
pad_tiles,
|
||||
Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer,
|
||||
mask_image, pad_tiles,
|
||||
};
|
||||
pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore};
|
||||
@@ -67,17 +67,22 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 {
|
||||
let d = f.x.min(1.0 - f.x).min(f.y.min(1.0 - f.y));
|
||||
smoothstep(0.015, 0.035, d) * (0.9 + 0.1 * noise::cell_hash(c.x as i32, c.y as i32, 0, seed))
|
||||
}
|
||||
ProceduralKind::Weave => {
|
||||
// Plain weave: in each cell the thread on top alternates (warp along X, weft along Y);
|
||||
// the top thread shows its round cross-section, bulging mid-span.
|
||||
ProceduralKind::Weave | ProceduralKind::Twill => {
|
||||
// Warp along X, weft along Y: in each cell the thread on top shows its round
|
||||
// cross-section, bulging mid-span. A plain weave alternates every cell; a 2/2 twill
|
||||
// floats over two cells and steps one cell per row, so the floats line up in diagonal
|
||||
// ribs, the weft darker than the warp.
|
||||
let c = (p * 2.0).floor();
|
||||
let f = p * 2.0 - c;
|
||||
let pi = std::f32::consts::PI;
|
||||
let warp_on_top = (c.x as i32 + c.y as i32).rem_euclid(2) == 0;
|
||||
let twill = kind == ProceduralKind::Twill;
|
||||
let (period, warp_cells) = if twill { (4, 2) } else { (2, 1) };
|
||||
let warp_on_top = (c.x as i32).wrapping_add(c.y as i32).rem_euclid(period) < warp_cells;
|
||||
let (across, along) = if warp_on_top { (f.y, f.x) } else { (f.x, f.y) };
|
||||
let thread = (pi * across).sin().max(0.0).sqrt() * (0.8 + 0.2 * (pi * along).sin());
|
||||
let tone = if twill && !warp_on_top { 0.55 } else { 1.0 };
|
||||
let fiber = noise::value([p.x * 40.0, p.y * 40.0, p.z], seed);
|
||||
(thread * (0.88 + 0.12 * fiber)).clamp(0.0, 1.0)
|
||||
(thread * tone * (0.88 + 0.12 * fiber)).clamp(0.0, 1.0)
|
||||
}
|
||||
ProceduralKind::Leather => {
|
||||
let w = noise::perlin((p * 0.7).to_array(), seed ^ 0x2D) - 0.5;
|
||||
@@ -351,6 +356,21 @@ mod tests {
|
||||
assert!(decal_uv(&Decal { size: [f32::NAN; 2], ..d }, Vec3::ZERO, z).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twill_floats_run_in_diagonal_ribs() {
|
||||
// The value at the centre of cell (x, y); cells are half a unit.
|
||||
let at = |k, x: i32, y: i32| raw(k, Vec3::new(x as f32 * 0.5 + 0.25, y as f32 * 0.5 + 0.25, 0.0), 3);
|
||||
for y in 1..8 {
|
||||
let warp: Vec<bool> = (0..8).map(|x| at(ProceduralKind::Twill, x, y) > 0.7).collect();
|
||||
assert_eq!(warp.iter().filter(|w| **w).count(), 4, "row {y}: half the floats are warp");
|
||||
for x in 0..7 {
|
||||
assert_eq!(warp[x as usize], at(ProceduralKind::Twill, x + 1, y - 1) > 0.7, "the rib continues diagonally at ({x}, {y})");
|
||||
}
|
||||
}
|
||||
// A plain weave shows every top thread alike.
|
||||
assert!((0..8).all(|x| at(ProceduralKind::Weave, x, 0) > 0.7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_pattern_varies() {
|
||||
for k in ProceduralKind::ALL {
|
||||
|
||||
@@ -313,8 +313,9 @@ fn pack(n: [f32; 3]) -> [f32; 3] {
|
||||
n.map(|v| v / len * 0.5 + 0.5)
|
||||
}
|
||||
|
||||
/// Reoriented normal mapping (Barré-Brisebois & Hill): `detail` re-oriented onto `base`.
|
||||
fn rnm(base: [f32; 3], detail: [f32; 3]) -> [f32; 3] {
|
||||
/// Reoriented normal mapping (Barré-Brisebois & Hill): `detail` re-oriented onto `base` (both
|
||||
/// packed into 0..1, as is the result).
|
||||
pub fn rnm(base: [f32; 3], detail: [f32; 3]) -> [f32; 3] {
|
||||
let t = unpack(base);
|
||||
let t = [t[0], t[1], t[2] + 1.0];
|
||||
let u = unpack(detail);
|
||||
|
||||
@@ -228,6 +228,8 @@ pub enum ProceduralKind {
|
||||
Tiles,
|
||||
/// Plain fabric weave.
|
||||
Weave,
|
||||
/// 2/2 twill: diagonal ribs, the warp brighter than the weft (denim, carbon fiber).
|
||||
Twill,
|
||||
/// Leather grain: pebbled cells with creases.
|
||||
Leather,
|
||||
/// Hammered metal dimples.
|
||||
@@ -249,7 +251,7 @@ pub enum ProceduralKind {
|
||||
}
|
||||
|
||||
impl ProceduralKind {
|
||||
pub const ALL: [ProceduralKind; 22] = [
|
||||
pub const ALL: [ProceduralKind; 23] = [
|
||||
ProceduralKind::Clouds,
|
||||
ProceduralKind::Perlin,
|
||||
ProceduralKind::Noise,
|
||||
@@ -263,6 +265,7 @@ impl ProceduralKind {
|
||||
ProceduralKind::Bricks,
|
||||
ProceduralKind::Tiles,
|
||||
ProceduralKind::Weave,
|
||||
ProceduralKind::Twill,
|
||||
ProceduralKind::Leather,
|
||||
ProceduralKind::Hammered,
|
||||
ProceduralKind::Brushed,
|
||||
@@ -288,6 +291,7 @@ impl ProceduralKind {
|
||||
ProceduralKind::Bricks => "Bricks",
|
||||
ProceduralKind::Tiles => "Tiles",
|
||||
ProceduralKind::Weave => "Fabric weave",
|
||||
ProceduralKind::Twill => "Twill weave",
|
||||
ProceduralKind::Leather => "Leather grain",
|
||||
ProceduralKind::Hammered => "Hammered",
|
||||
ProceduralKind::Brushed => "Brushed lines",
|
||||
@@ -531,6 +535,21 @@ pub enum Filter {
|
||||
min: f32,
|
||||
max: f32,
|
||||
},
|
||||
/// A ramp slid through the values: those above `position` go towards white, those below
|
||||
/// towards black, over a width `contrast` (0..1) narrows to a hard step.
|
||||
HistogramScan {
|
||||
position: f32,
|
||||
contrast: f32,
|
||||
},
|
||||
/// The values squeezed towards `position`: `range` 1 keeps them, 0 sets them all to it.
|
||||
HistogramRange {
|
||||
range: f32,
|
||||
position: f32,
|
||||
},
|
||||
/// The values offset by `offset` (−1..1), wrapping around past white and black.
|
||||
HistogramShift {
|
||||
offset: f32,
|
||||
},
|
||||
/// Shift each texel's lookup along a noise vector field: `intensity` in texels at 2K,
|
||||
/// `scale` noise features per UV unit.
|
||||
Warp {
|
||||
@@ -738,6 +757,24 @@ impl Filter {
|
||||
let (lo, hi) = (min.min(*max), min.max(*max));
|
||||
per_unit(kind, v, |x| x.max(lo).min(hi))
|
||||
}
|
||||
// Full contrast is a threshold: the position itself goes to white.
|
||||
Filter::HistogramScan { position, contrast } if *contrast >= 1.0 => per_unit(kind, v, |x| if x >= *position { 1.0 } else { 0.0 }),
|
||||
Filter::HistogramScan { position, contrast } => {
|
||||
let width = (1.0 - contrast.clamp(0.0, 1.0)).max(1e-3);
|
||||
per_unit(kind, v, |x| unit((x - position) / width + 0.5))
|
||||
}
|
||||
Filter::HistogramRange { range, position } => per_unit(kind, v, |x| unit(position + (x - position) * range)),
|
||||
Filter::HistogramShift { offset } => per_unit(kind, v, |x| {
|
||||
// Wrapped by hand: `rem_euclid` would also send white (1 + 0) to black.
|
||||
let y = unit(x) + offset.clamp(-1.0, 1.0);
|
||||
unit(if y > 1.0 {
|
||||
y - 1.0
|
||||
} else if y < 0.0 {
|
||||
y + 1.0
|
||||
} else {
|
||||
y
|
||||
})
|
||||
}),
|
||||
Filter::Grayscale => match kind {
|
||||
ChannelKind::Color => [lum(v); 3],
|
||||
_ => v,
|
||||
@@ -789,6 +826,9 @@ impl Filter {
|
||||
Filter::GradientMap { .. } => "Gradient Map",
|
||||
Filter::Posterize { .. } => "Posterize",
|
||||
Filter::Clamp { .. } => "Clamp",
|
||||
Filter::HistogramScan { .. } => "Histogram Scan",
|
||||
Filter::HistogramRange { .. } => "Histogram Range",
|
||||
Filter::HistogramShift { .. } => "Histogram Shift",
|
||||
Filter::Warp { .. } => "Warp",
|
||||
Filter::DirectionalBlur { .. } => "Blur Directional",
|
||||
Filter::SlopeBlur { .. } => "Slope Blur",
|
||||
@@ -964,6 +1004,17 @@ mod tests {
|
||||
assert_eq!(Filter::GradientMap { colors: vec![] }.point(c, [0.3; 3]), None, "an empty gradient changes nothing");
|
||||
assert!(close(Filter::Posterize { levels: 2.0 }.point(c, [0.2, 0.6, 0.9]).unwrap(), [0.0, 1.0, 1.0]));
|
||||
assert!(close(Filter::Clamp { min: 0.8, max: 0.3 }.point(c, [0.1, 0.5, 0.9]).unwrap(), [0.3, 0.5, 0.8]), "swapped bounds never panic");
|
||||
let scan = |position, contrast| Filter::HistogramScan { position, contrast }.point(c, [0.2, 0.5, 0.9]).unwrap();
|
||||
assert!(close(scan(0.5, 0.0), [0.2, 0.5, 0.9]), "a full-width ramp at the middle keeps the values");
|
||||
assert!(close(scan(0.4, 1.0), [0.0, 1.0, 1.0]), "full contrast is a step at the position");
|
||||
assert!(close(scan(0.5, 1.0), [0.0, 1.0, 1.0]), "the position itself goes to white");
|
||||
assert!(close(scan(0.7, 0.5), [0.0, 0.1, 0.9]));
|
||||
let range = |range, position| Filter::HistogramRange { range, position }.point(c, [0.2, 0.5, 0.9]).unwrap();
|
||||
assert!(close(range(1.0, 0.3), [0.2, 0.5, 0.9]) && close(range(0.0, 0.3), [0.3; 3]));
|
||||
assert!(close(range(0.5, 0.5), [0.35, 0.5, 0.7]));
|
||||
let shift = |offset| Filter::HistogramShift { offset }.point(c, [0.0, 0.5, 1.0]).unwrap();
|
||||
assert!(close(shift(0.0), [0.0, 0.5, 1.0]), "no offset keeps white white");
|
||||
assert!(close(shift(0.25), [0.25, 0.75, 0.25]) && close(shift(-0.25), [0.75, 0.25, 0.75]));
|
||||
let cb = Filter::ColorBalance { shadows: [0.2, 0.0, 0.0], midtones: [0.0; 3], highlights: [0.0, 0.0, 0.2] };
|
||||
assert!(cb.point(c, [0.05; 3]).unwrap()[0] > 0.2 && cb.point(c, [0.95; 3]).unwrap()[2] > 0.99);
|
||||
assert!(close(Filter::Invert.point(ChannelKind::Signed, [0.5; 3]).unwrap(), [-0.5; 3]));
|
||||
|
||||
@@ -230,7 +230,8 @@ impl Default for BakeSettings {
|
||||
ao: RaySettings::default(),
|
||||
ao_ignore_backface: false,
|
||||
ao_self_occlusion: SelfOcclusion::Always,
|
||||
thickness: RaySettings::default(),
|
||||
// Thickness is hit distance / max distance: long rays turn thin parts almost black.
|
||||
thickness: RaySettings { max_distance: 0.1, ..RaySettings::default() },
|
||||
bent_normal: RaySettings::default(),
|
||||
curvature_strength: 1.0,
|
||||
curvature_from_normal: false,
|
||||
@@ -568,6 +569,9 @@ impl Default for Camera {
|
||||
}
|
||||
}
|
||||
|
||||
/// Built-in environments, in menu order.
|
||||
pub const ENVIRONMENTS: [&str; 6] = ["Studio Soft", "Studio Contrast", "Overcast", "Sunset", "Warehouse", "Night"];
|
||||
|
||||
/// Prefix of [`DisplaySettings::environment`] naming an image resource.
|
||||
pub const ENV_RESOURCE_PREFIX: &str = "resource:";
|
||||
|
||||
@@ -613,6 +617,10 @@ pub struct Project {
|
||||
pub name: String,
|
||||
/// Path of the mesh inside the project file (or a built-in primitive id `builtin:<name>`).
|
||||
pub mesh: String,
|
||||
/// File name the mesh was imported from (`quad.gltf`). The stored mesh is read again under
|
||||
/// it, so parts the file leaves unnamed get the same name (from it) as on import.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub mesh_file: String,
|
||||
pub normal_format: NormalFormat,
|
||||
pub texture_sets: Vec<TextureSet>,
|
||||
pub layers: BTreeMap<LayerId, Layer>,
|
||||
@@ -629,6 +637,7 @@ impl Project {
|
||||
format_version: FORMAT_VERSION,
|
||||
name: name.into(),
|
||||
mesh: mesh.into(),
|
||||
mesh_file: String::new(),
|
||||
normal_format: NormalFormat::OpenGl,
|
||||
texture_sets: Vec::new(),
|
||||
layers: BTreeMap::new(),
|
||||
|
||||
@@ -17,6 +17,7 @@ texturecraft-paint = { workspace = true }
|
||||
texturecraft-bake = { workspace = true }
|
||||
texturecraft-formats = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
epaint_default_fonts = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
//! Brush presets: the built-in ones, and the user's own saved as `.tcbrush` files (the brush
|
||||
//! settings as JSON). Applying or loading one changes the stroke and keeps the brush's size.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_paint::BrushSettings;
|
||||
use texturecraft_paint::presets::{PRESETS, find_preset, with_stroke_of};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, strp};
|
||||
use crate::tool_cmds::brush_json;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
/// File extension of a saved brush preset.
|
||||
pub const BRUSH_EXT: &str = "tcbrush";
|
||||
/// Largest preset file read.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_BYTES: u64 = 1 << 20;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("brush.preset.list", "List brush presets", [], None, "{} — the built-in presets: id, label, category", always, |_, _| Ok(list())),
|
||||
cmd!(
|
||||
"brush.preset.apply",
|
||||
"Apply brush preset",
|
||||
[],
|
||||
None,
|
||||
"{preset: id or label (brush.preset.list)} — sets the stroke (alpha, spacing, flow, hardness, jitters…), keeps the size",
|
||||
always,
|
||||
apply
|
||||
),
|
||||
cmd!("brush.preset.save", "Save brush preset", [], None, "{path} — the current brush as a .tcbrush file", always, save),
|
||||
cmd!("brush.preset.load", "Load brush preset", [], None, "{path} — a .tcbrush file's stroke on the brush, keeping the size", always, load),
|
||||
]
|
||||
}
|
||||
|
||||
fn list() -> Value {
|
||||
json!(PRESETS.iter().map(|p| json!({"id": p.id, "label": p.label, "category": p.category})).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = strp(p, "preset").ok_or_else(|| bad("brush.preset.apply", "`preset` is required"))?;
|
||||
let preset = find_preset(name).ok_or_else(|| bad("brush.preset.apply", format!("unknown brush preset `{name}` (see brush.preset.list)")))?;
|
||||
set(s, preset.applied(&s.tool.brush))
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, brush: BrushSettings) -> Result<Value> {
|
||||
s.tool.brush = brush;
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(brush_json(s))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = strp(p, "path").ok_or_else(|| bad("brush.preset.save", "`path` is required"))?;
|
||||
let bytes = serde_json::to_vec_pretty(&s.tool.brush).map_err(|e| bad("brush.preset.save", e.to_string()))?;
|
||||
std::fs::write(path, bytes).map_err(|e| bad("brush.preset.save", format!("cannot write {path}: {e}")))?;
|
||||
Ok(json!({ "path": path }))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use std::io::Read as _;
|
||||
let cmd = "brush.preset.load";
|
||||
let path = strp(p, "path").ok_or_else(|| bad(cmd, "`path` is required"))?;
|
||||
let mut bytes = Vec::new();
|
||||
std::fs::File::open(path).and_then(|f| f.take(MAX_BYTES + 1).read_to_end(&mut bytes)).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?;
|
||||
if bytes.len() as u64 > MAX_BYTES {
|
||||
return Err(bad(cmd, format!("{path} is too large for a brush preset")));
|
||||
}
|
||||
let mut from: BrushSettings = serde_json::from_slice(&bytes).map_err(|e| bad(cmd, format!("{path} is not a brush preset: {e}")))?;
|
||||
// An image alpha belongs to the project that saved it.
|
||||
if from.alpha_image.as_ref().is_some_and(|n| !s.images.contains_key(n)) {
|
||||
from.alpha_image = None;
|
||||
}
|
||||
set(s, with_stroke_of(&s.tool.brush, &from))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn save(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(bad("brush.preset.save", "file paths are not available in the browser"))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn load(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(bad("brush.preset.load", "file paths are not available in the browser"))
|
||||
}
|
||||
@@ -56,12 +56,15 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::layer_ops::specs());
|
||||
v.extend(crate::instance_cmds::specs());
|
||||
v.extend(crate::mask_cmds::specs());
|
||||
v.extend(crate::effect_clipboard::specs());
|
||||
v.extend(crate::tool_cmds::specs());
|
||||
v.extend(crate::brush_preset_cmds::specs());
|
||||
v.extend(crate::path_tool::specs());
|
||||
v.extend(crate::view_cmds::specs());
|
||||
v.extend(crate::camera_cmds::specs());
|
||||
v.extend(crate::quick_mask::specs());
|
||||
v.extend(crate::set_cmds::specs());
|
||||
v.extend(crate::meshmap_cmds::specs());
|
||||
v.extend(crate::uv_tile_cmds::specs());
|
||||
v.extend(crate::template_cmds::specs());
|
||||
v.extend(crate::project_cmds::specs());
|
||||
@@ -73,6 +76,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::smart_masks::specs());
|
||||
v.extend(crate::filter_lib::specs());
|
||||
v.extend(crate::decal_cmds::specs());
|
||||
v.extend(crate::text_cmds::specs());
|
||||
v
|
||||
})
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add decal",
|
||||
[],
|
||||
None,
|
||||
"{image: resource name, x?, y?: viewport pixels (default: the view center), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z], size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} — a fill layer projecting the image from a frame placed on the surface",
|
||||
"{image: resource name, x?, y?: viewport pixels (default: the view center), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z], up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round",
|
||||
always,
|
||||
add
|
||||
),
|
||||
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit decal",
|
||||
[],
|
||||
None,
|
||||
"{layer?, x?, y?, viewport? | position?, normal? (re-place it), size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?, merge?: true continues the previous Edit decal undo step (drags)}",
|
||||
"{layer?, x?, y?, viewport? | position?, normal? (re-place it), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?, merge?: true continues the previous Edit decal undo step (drags)}",
|
||||
has_layer,
|
||||
set
|
||||
),
|
||||
@@ -81,9 +81,16 @@ fn size_param(p: &Value, aspect: f32, diag: f32) -> Option<[f32; 2]> {
|
||||
size.iter().all(|x| x.is_finite()).then(|| size.map(|x| x.clamp(diag * 1e-4, diag * 10.0)))
|
||||
}
|
||||
|
||||
/// The camera's up direction (decals are placed upright on screen).
|
||||
fn screen_up(s: &Session) -> Vec3 {
|
||||
s.camera.view().inverse().transform_vector3(Vec3::Y)
|
||||
/// The decal's up direction: `up` when given, else the camera's (decals are placed upright on
|
||||
/// screen), or where the camera looks when that is along `normal` (a top face seen from the
|
||||
/// front: its far edge is up, as on a table).
|
||||
fn decal_up(s: &Session, cmd: &str, p: &Value, normal: Vec3) -> Result<Vec3> {
|
||||
if p.get("up").is_some() {
|
||||
return vec3(p, "up").filter(|u| u.cross(normal).length_squared() > 1e-8).ok_or_else(|| bad(cmd, "`up` must be [x, y, z], not along the normal"));
|
||||
}
|
||||
let to_world = s.camera.view().inverse();
|
||||
let up = to_world.transform_vector3(Vec3::Y);
|
||||
Ok(if up.normalize_or_zero().cross(normal).length_squared() > 1e-4 { up } else { to_world.transform_vector3(Vec3::NEG_Z) })
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -97,7 +104,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let decal = Decal {
|
||||
center: center.to_array(),
|
||||
normal: normal.to_array(),
|
||||
up: screen_up(s).to_array(),
|
||||
up: decal_up(s, cmd, p, normal)?.to_array(),
|
||||
size,
|
||||
rotation: f32p(p, "rotation").unwrap_or(0.0).rem_euclid(360.0),
|
||||
offset: [0.0; 2],
|
||||
@@ -132,6 +139,9 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some((center, normal)) = placement(s, cmd, p, true)? {
|
||||
(d.center, d.normal, d.offset) = (center.to_array(), normal.to_array(), [0.0; 2]);
|
||||
}
|
||||
if p.get("up").is_some() {
|
||||
d.up = decal_up(s, cmd, p, Vec3::from(d.normal))?.to_array();
|
||||
}
|
||||
if let Some(size) = size_param(p, d.size[0] / d.size[1].max(1e-6), diag) {
|
||||
d.size = size;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Copy and paste effects between layers, masks and texture sets. The clipboard is the layer
|
||||
//! clipboard: it holds a layer or an effect.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground, Source};
|
||||
|
||||
use crate::commands::{CommandSpec, bad, has_layer, layer_param, strp};
|
||||
use crate::layer_ops::{empty_texel, fit};
|
||||
use crate::mask_cmds::{anchor_source, content_target, effect_id};
|
||||
use crate::session::StackTarget;
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("effect.copy", "Copy effect", [], None, "{effect?: the selected effect}", has_layer, copy),
|
||||
cmd!("effect.cut", "Cut effect", [], None, "{effect?: the selected effect}", has_layer, cut),
|
||||
cmd!(
|
||||
"effect.paste",
|
||||
"Paste effect",
|
||||
[],
|
||||
None,
|
||||
"{layer?, target?: mask|content (default: the selection's stack)} → {effect} — above the selected effect, or on top of the stack",
|
||||
can_paste,
|
||||
paste
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The copied effect, if the clipboard holds one.
|
||||
fn clipboard_effect(s: &Session) -> Option<LayerId> {
|
||||
s.clipboard.as_ref().and_then(|(doc, id)| doc.project.effect(*id).map(|_| *id))
|
||||
}
|
||||
|
||||
fn can_paste(s: &Session) -> std::result::Result<(), String> {
|
||||
match clipboard_effect(s) {
|
||||
Some(_) if s.selected_layer().is_some() => Ok(()),
|
||||
Some(_) => Err("select a layer to paste the effect on".into()),
|
||||
None => Err("the clipboard holds no effect".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "effect.copy";
|
||||
let eid = effect_id(s, p, CMD)?;
|
||||
if s.doc.project.effect(eid).is_none() {
|
||||
return Err(bad(CMD, format!("no effect {}", eid.0)));
|
||||
}
|
||||
s.clipboard = Some((s.doc.clone(), eid));
|
||||
Ok(json!({ "copied": eid.0 }))
|
||||
}
|
||||
|
||||
fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let eid = copy(s, p)?["copied"].clone();
|
||||
crate::execute(s, "effect.remove", &json!({ "effect": eid }))?;
|
||||
Ok(json!({ "cut": eid }))
|
||||
}
|
||||
|
||||
fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "effect.paste";
|
||||
let (src, eid) = s.clipboard.clone().ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?;
|
||||
let effect = src.project.effect(eid).map(|(_, e)| e.clone()).ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?;
|
||||
let layer = layer_param(s, CMD, p)?;
|
||||
// The selected effect's stack, or the content or mask the selection targets.
|
||||
let selected = match s.target {
|
||||
StackTarget::Effect(x) if s.selected_layer() == Some(layer) => Some(x),
|
||||
_ => None,
|
||||
};
|
||||
let in_content = |s: &Session, x: LayerId| {
|
||||
s.doc.project.effect(x).and_then(|(o, _)| s.doc.project.layers.get(&o)).is_some_and(|l| l.content_effects.iter().any(|e| e.id == x))
|
||||
};
|
||||
let asked = strp(p, "target").is_some();
|
||||
let content = match selected {
|
||||
_ if asked => content_target(p, CMD)?,
|
||||
Some(x) => in_content(s, x),
|
||||
None => s.target == StackTarget::Content && s.selected_layer() == Some(layer),
|
||||
};
|
||||
// Effects that fit one stack only go there, unless another was asked for.
|
||||
let content = match effect.kind.content_only() {
|
||||
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,
|
||||
};
|
||||
// An instance's content and (unless it has its own) mask belong to its source.
|
||||
let owner = if content { s.doc.project.content_layer(layer).map_or(layer, |l| l.id) } else { s.doc.project.mask_owner(layer) };
|
||||
let owner_layer = s.doc.project.layer(owner)?;
|
||||
if content && owner_layer.is_group() {
|
||||
return Err(EngineError::Other(format!("\"{}\" is a folder: content effects go on paint and fill layers", owner_layer.name)));
|
||||
}
|
||||
// A fill reading an anchor point needs one below its new layer.
|
||||
if let EffectKind::Fill { source: Source::Anchor { anchor, channel }, .. } = &effect.kind {
|
||||
anchor_source(s, CMD, owner, *anchor, *channel)?;
|
||||
}
|
||||
let (ts, _, _) = s.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the layer is not in a stack"))?;
|
||||
let (size, channels) = s.doc.project.texture_set(ts).map(|t| (t.size(), t.channel_list()))?;
|
||||
let new = s.edit("Paste effect", |s| {
|
||||
let new = s.doc.project.alloc_id();
|
||||
let l = s.doc.project.layer_mut(owner)?;
|
||||
let list = if content {
|
||||
&mut l.content_effects
|
||||
} else {
|
||||
let bg = if matches!(effect.kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White };
|
||||
&mut l.mask.get_or_insert_with(|| Mask::new(bg)).effects
|
||||
};
|
||||
let at = selected.and_then(|x| list.iter().position(|e| e.id == x)).map_or(list.len(), |i| i + 1);
|
||||
list.insert(at, texturecraft_core::Effect { id: new, ..effect.clone() });
|
||||
// Painted pixels come along, resampled to the set's size (a mask's paint stays a mask's).
|
||||
if let Some(img) = src.pixels.masks.get(&eid).filter(|_| !content) {
|
||||
s.doc.pixels.masks.insert(new, fit(img, size, &[0, 0]));
|
||||
}
|
||||
for c in channels.iter().copied().filter(|_| content) {
|
||||
if let Some(img) = src.pixels.layer(eid, c) {
|
||||
s.doc.pixels.layers.insert((new, c), fit(img, size, &empty_texel(c)));
|
||||
}
|
||||
}
|
||||
if let Some((lts, _, _)) = s.doc.project.locate(layer) {
|
||||
s.selected.insert(lts, layer);
|
||||
}
|
||||
s.target = StackTarget::Effect(new);
|
||||
Ok(new)
|
||||
})?;
|
||||
Ok(json!({ "effect": new.0 }))
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
use serde_json::{Value, json};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use texturecraft_core::PROJECT_EXT;
|
||||
use texturecraft_core::{NormalFormat, TextureSet};
|
||||
use texturecraft_core::{NormalFormat, Project, TextureSet};
|
||||
use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, Padding, ProjectFile};
|
||||
use texturecraft_geom::{Mesh, primitives};
|
||||
|
||||
@@ -42,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export textures",
|
||||
["File"],
|
||||
None,
|
||||
"{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX}",
|
||||
"{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)}",
|
||||
always,
|
||||
export_textures
|
||||
),
|
||||
@@ -60,7 +60,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List export outputs",
|
||||
[],
|
||||
None,
|
||||
"{preset?: name or preset object, ts?, format?, bitDepth?, size?} → [{ts, map, file, format, bitDepth, warnings}]",
|
||||
"{preset?: name or preset object, ts?, format?, bitDepth?, size?, colorSpace?} → [{ts, map, file, format, bitDepth, warnings}]",
|
||||
always,
|
||||
plan
|
||||
),
|
||||
@@ -79,6 +79,18 @@ fn stem_of(name: &str) -> String {
|
||||
std::path::Path::new(name).file_stem().and_then(|e| e.to_str()).unwrap_or("Untitled").to_string()
|
||||
}
|
||||
|
||||
/// The leaf of an imported mesh file's name (kept in [`Project::mesh_file`]).
|
||||
fn leaf_of(name: &str) -> String {
|
||||
std::path::Path::new(name).file_name().and_then(|e| e.to_str()).unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
/// Read the project's stored mesh `bytes` (extension `ext`) under the name it was imported
|
||||
/// with, so its unnamed parts keep their names (and the geometry masks that use them).
|
||||
fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8]) -> Result<texturecraft_formats::ImportedMesh> {
|
||||
let stem = std::path::Path::new(&project.mesh_file).file_stem().and_then(|s| s.to_str()).filter(|s| !s.is_empty()).unwrap_or("mesh");
|
||||
texturecraft_formats::import_mesh_bytes(&format!("{stem}.{ext}"), bytes).map_err(fe)
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The working mesh as Wavefront OBJ (with its own UVs, UDIM tiles included).
|
||||
pub fn mesh_obj_bytes(&self) -> Vec<u8> {
|
||||
@@ -122,6 +134,7 @@ impl Session {
|
||||
let imported = texturecraft_formats::import_mesh_bytes(file_name, bytes).map_err(fe)?;
|
||||
let ext = ext_of(file_name);
|
||||
let mut s = Session::new_project_tiled(name, imported.mesh, &format!("mesh.{ext}"), Some((ext, bytes.to_vec())), resolution, uv_tiles)?;
|
||||
s.doc.project.mesh_file = leaf_of(file_name);
|
||||
s.doc.project.cameras = imported.cameras;
|
||||
s.log.extend(imported.report.warnings.iter().cloned());
|
||||
s.log.push(format!(
|
||||
@@ -143,7 +156,7 @@ impl Session {
|
||||
pub fn from_project_file(pf: ProjectFile) -> Result<Session> {
|
||||
let mesh = match (&pf.mesh, pf.project.mesh.strip_prefix("builtin:")) {
|
||||
(_, Some(id)) => primitives::builtin(id).ok_or_else(|| EngineError::Other(format!("unknown built-in mesh `{id}`")))?,
|
||||
(Some((ext, bytes)), None) => texturecraft_formats::import_mesh_bytes(&format!("mesh.{ext}"), bytes).map_err(fe)?.mesh,
|
||||
(Some((ext, bytes)), None) => read_stored_mesh(&pf.project, ext, bytes)?.mesh,
|
||||
(None, None) => return Err(EngineError::Other("the project has no mesh".into())),
|
||||
};
|
||||
check_materials(&pf.project, &mesh)?;
|
||||
@@ -256,6 +269,12 @@ pub fn export_options(s: &Session, p: &Value, cmd: &str) -> Result<ExportOptions
|
||||
Some(other) => return Err(bad(cmd, format!("unknown normal format `{other}`"))),
|
||||
None => None,
|
||||
};
|
||||
if let Some(name) = strp(p, "colorSpace") {
|
||||
o.color_space = Some(
|
||||
texturecraft_texel::ColorSpace::from_name(name)
|
||||
.ok_or_else(|| bad(cmd, format!("unknown colorSpace `{name}` (sRGB, Linear Rec.709, ACEScg or ACES2065-1)")))?,
|
||||
);
|
||||
}
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
@@ -384,14 +403,14 @@ impl Session {
|
||||
/// With `preserve_strokes`, painted pixels follow the surface where the UVs changed. Replies
|
||||
/// like `file.reimportMesh`: `{preserved?}`.
|
||||
pub fn reimport_mesh(&mut self, file: Option<texturecraft_formats::MeshFile>, preserve_strokes: bool) -> Result<Value> {
|
||||
let (mesh, source, warnings) = match file {
|
||||
let (mesh, source, warnings, mesh_file) = match file {
|
||||
Some(f) => {
|
||||
let m = texturecraft_formats::import_mesh_bytes(&f.name, &f.bytes).map_err(fe)?.mesh;
|
||||
(m, Some((ext_of(&f.name), f.bytes)), f.warnings)
|
||||
(m, Some((ext_of(&f.name), f.bytes)), f.warnings, leaf_of(&f.name))
|
||||
}
|
||||
None => match &self.mesh_source {
|
||||
Some((ext, bytes)) => {
|
||||
(texturecraft_formats::import_mesh_bytes(&format!("mesh.{ext}"), bytes).map_err(fe)?.mesh, self.mesh_source.clone(), Vec::new())
|
||||
(read_stored_mesh(&self.doc.project, ext, bytes)?.mesh, self.mesh_source.clone(), Vec::new(), self.doc.project.mesh_file.clone())
|
||||
}
|
||||
None => return Err(bad("file.reimportMesh", "built-in meshes can't be reimported; give `path`")),
|
||||
},
|
||||
@@ -400,6 +419,7 @@ impl Session {
|
||||
let mut doc = self.doc.clone();
|
||||
if let Some((ext, _)) = &source {
|
||||
doc.project.mesh = format!("mesh.{ext}");
|
||||
doc.project.mesh_file = mesh_file;
|
||||
}
|
||||
let mut next = Session::new(doc, mesh, source)?;
|
||||
next.log.extend(warnings);
|
||||
@@ -417,12 +437,66 @@ fn export_textures(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sets = sets_param(s, p, "file.exportTextures")?;
|
||||
std::fs::create_dir_all(&dir).map_err(|e| bad("file.exportTextures", format!("cannot create {dir}: {e}")))?;
|
||||
let files = s.export_files(&sets, &opts)?;
|
||||
let warnings: Vec<String> = files.iter().flat_map(|f| f.warnings.iter().cloned()).collect();
|
||||
let written = texturecraft_formats::write_files(&files, std::path::Path::new(&dir)).map_err(fe)?;
|
||||
let mut warnings: Vec<String> = files.iter().flat_map(|f| f.warnings.iter().cloned()).collect();
|
||||
let mut written = texturecraft_formats::write_files(&files, std::path::Path::new(&dir)).map_err(fe)?;
|
||||
if p.get("materialX").and_then(Value::as_bool).unwrap_or(false) {
|
||||
written.extend(write_materialx(s, &sets, &opts, std::path::Path::new(&dir), &mut warnings)?);
|
||||
}
|
||||
s.log.push(format!("Exported {} textures to {dir}", written.len()));
|
||||
Ok(json!({ "files": written.iter().map(|p| p.display().to_string()).collect::<Vec<_>>(), "warnings": warnings }))
|
||||
}
|
||||
|
||||
/// One `<mesh>_<set>.mtlx` per texture set, next to the textures `opts` just wrote: the
|
||||
/// OpenPBR inputs those textures feed (see `texturecraft_formats::materialx`). UDIM sets name
|
||||
/// their files with the `<UDIM>` token. Sets with no recognised map, or whose name gives the
|
||||
/// same file name as an earlier set's, are skipped with a warning.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std::path::Path, warnings: &mut Vec<String>) -> Result<Vec<std::path::PathBuf>> {
|
||||
use texturecraft_formats::materialx::{self, Texture};
|
||||
let mesh_name = stem_of(s.doc.project.mesh.trim_start_matches("builtin:"));
|
||||
if opts.normal_format == Some(NormalFormat::DirectX) {
|
||||
warnings.push("MaterialX: the normalmap node reads OpenGL (+Y) normals; this export wrote DirectX normals, so flip the green channel".into());
|
||||
}
|
||||
if opts.color_space == Some(texturecraft_texel::ColorSpace::Aces2065) {
|
||||
warnings.push("MaterialX: version 1.39 has no ACES2065-1 colour space; the colour maps are tagged lin_ap0_scene, its name in later versions, which older readers may not know".into());
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut stems = std::collections::HashSet::new();
|
||||
for &ts in sets {
|
||||
let set = s.doc.project.texture_set(ts).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let mut textures: Vec<Texture> = Vec::new();
|
||||
for f in texturecraft_formats::list_outputs(&s.doc.project, ts, &mesh_name, opts).map_err(fe)? {
|
||||
let Some(input) = opts.preset.maps.get(f.map).and_then(|m| materialx::input_of_template(&m.file)) else { continue };
|
||||
// The first tile stands for all of them: 1001 -> <UDIM>.
|
||||
let file = match f.tile {
|
||||
Some(t) => f.name.replacen(&format!(".{t}."), ".<UDIM>.", 1),
|
||||
None => f.name.clone(),
|
||||
};
|
||||
let colorspace = materialx::colorspace_name(opts.space_for(f.format));
|
||||
if !textures.iter().any(|t| t.input == input) {
|
||||
textures.push(Texture { input: input.to_owned(), file, colorspace });
|
||||
}
|
||||
}
|
||||
if textures.is_empty() {
|
||||
warnings.push(format!("MaterialX: texture set \"{}\" has no OpenPBR maps; use the \"OpenPBR (separate maps)\" preset", set.name));
|
||||
continue;
|
||||
}
|
||||
let stem = texturecraft_formats::export::sanitize_file_stem(&format!("{mesh_name}_{}", set.name));
|
||||
// Case-insensitive: Windows and macOS file systems are.
|
||||
if !stems.insert(stem.to_ascii_lowercase()) {
|
||||
warnings.push(format!(
|
||||
"MaterialX: texture set \"{}\" exports as \"{stem}\" like an earlier set, so its .mtlx was not written; rename one of them",
|
||||
set.name
|
||||
));
|
||||
continue;
|
||||
}
|
||||
let path = dir.join(format!("{stem}.mtlx"));
|
||||
texturecraft_formats::write_atomic(&path, materialx::write(&format!("{mesh_name}_{}", set.name), &textures, None).as_bytes()).map_err(fe)?;
|
||||
out.push(path);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn export_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = native::path_param(p, "path", "file.exportMesh")?;
|
||||
@@ -555,4 +629,49 @@ mod tests {
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unnamed_parts_keep_their_names_and_masks_through_save_and_reopen() {
|
||||
// A GLB quad whose mesh and node have no name: its one part is named after the file.
|
||||
let mut bin: Vec<u8> = [-1.0f32, -1.0, 0.0, 1.0, -1.0, 0.0, 1.0, 1.0, 0.0, -1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]
|
||||
.iter()
|
||||
.flat_map(|f| f.to_le_bytes())
|
||||
.chain([0u16, 1, 2, 0, 2, 3].iter().flat_map(|i| i.to_le_bytes()))
|
||||
.collect();
|
||||
bin.resize(92, 0);
|
||||
let mut gltf = json!({
|
||||
"asset": {"version": "2.0"}, "buffers": [{"byteLength": 92}],
|
||||
"bufferViews": [{"buffer": 0, "byteOffset": 0, "byteLength": 48}, {"buffer": 0, "byteOffset": 48, "byteLength": 32}, {"buffer": 0, "byteOffset": 80, "byteLength": 12}],
|
||||
"accessors": [{"bufferView": 0, "componentType": 5126, "count": 4, "type": "VEC3", "min": [-1, -1, 0], "max": [1, 1, 0]},
|
||||
{"bufferView": 1, "componentType": 5126, "count": 4, "type": "VEC2"}, {"bufferView": 2, "componentType": 5123, "count": 6, "type": "SCALAR"}],
|
||||
"meshes": [{"primitives": [{"attributes": {"POSITION": 0, "TEXCOORD_0": 1}, "indices": 2}]}],
|
||||
"nodes": [{"mesh": 0}], "scenes": [{"nodes": [0]}], "scene": 0
|
||||
})
|
||||
.to_string()
|
||||
.into_bytes();
|
||||
gltf.resize(gltf.len().div_ceil(4) * 4, b' ');
|
||||
let mut glb = b"glTF".to_vec();
|
||||
glb.extend(2u32.to_le_bytes());
|
||||
glb.extend(((12 + 8 + gltf.len() + 8 + bin.len()) as u32).to_le_bytes());
|
||||
glb.extend((gltf.len() as u32).to_le_bytes());
|
||||
glb.extend(b"JSON");
|
||||
glb.extend(gltf);
|
||||
glb.extend((bin.len() as u32).to_le_bytes());
|
||||
glb.extend(b"BIN\0");
|
||||
glb.extend(bin);
|
||||
let mut s = Session::from_mesh_bytes("dir/quad.glb", &glb, 128, "quad").unwrap();
|
||||
let parts = |s: &mut Session| crate::execute(s, "textureSet.parts", &Value::Null).unwrap();
|
||||
assert_eq!(parts(&mut s), json!(["quad"]));
|
||||
crate::execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap();
|
||||
crate::execute(&mut s, "layer.set", &json!({"geometryMask": ["quad"]})).unwrap();
|
||||
let mut back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
|
||||
assert_eq!(parts(&mut back), json!(["quad"]), "the reopened mesh names its part as the import did");
|
||||
crate::execute(&mut back, "file.reimportMesh", &Value::Null).unwrap();
|
||||
assert_eq!(parts(&mut back), json!(["quad"]), "and so does a reimport of the stored mesh");
|
||||
// Projects saved before the file name was kept read the mesh as before.
|
||||
let mut old = back.project_file();
|
||||
old.project.mesh_file.clear();
|
||||
let mut old = Session::from_project_bytes(&texturecraft_formats::save_project_bytes(&old).unwrap()).unwrap();
|
||||
assert_eq!(parts(&mut old), json!(["mesh"]));
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,9 @@ pub const FILTERS: &[FilterDef] = &[
|
||||
def("gradientMap", "Gradient Map", "Adjustments", true),
|
||||
def("posterize", "Posterize", "Adjustments", true),
|
||||
def("clamp", "Clamp", "Adjustments", true),
|
||||
def("histogramScan", "Histogram Scan", "Adjustments", true),
|
||||
def("histogramRange", "Histogram Range", "Adjustments", true),
|
||||
def("histogramShift", "Histogram Shift", "Adjustments", true),
|
||||
def("invert", "Invert", "Adjustments", true),
|
||||
def("threshold", "Threshold", "Adjustments", true),
|
||||
def("grayscale", "Grayscale", "Adjustments", false),
|
||||
@@ -96,6 +99,9 @@ pub fn build(id: &str, p: &Value) -> Result<EffectKind> {
|
||||
"gradientMap" => Filter::GradientMap { colors: vec![[0.02, 0.02, 0.04], [0.45, 0.16, 0.05], [1.0, 0.85, 0.55]] },
|
||||
"posterize" => Filter::Posterize { levels: 4.0 },
|
||||
"clamp" => Filter::Clamp { min: 0.2, max: 0.8 },
|
||||
"histogramScan" => Filter::HistogramScan { position: 0.5, contrast: 0.5 },
|
||||
"histogramRange" => Filter::HistogramRange { range: 0.5, position: 0.5 },
|
||||
"histogramShift" => Filter::HistogramShift { offset: 0.25 },
|
||||
"warp" => Filter::Warp { intensity: 16.0, scale: 4.0, seed: 1 },
|
||||
"blurDirectional" => Filter::DirectionalBlur { radius: 16.0, angle: 0.0 },
|
||||
"slopeBlur" => Filter::SlopeBlur { radius: 16.0, scale: 4.0, seed: 1 },
|
||||
@@ -151,6 +157,9 @@ pub fn scalar_params(f: &Filter) -> Vec<(&'static str, &'static str, f32, f32, f
|
||||
}
|
||||
Filter::Posterize { levels } => vec![("levels", "Steps", *levels, 2.0, 64.0)],
|
||||
Filter::Clamp { min, max } => vec![("min", "Minimum", *min, 0.0, 1.0), ("max", "Maximum", *max, 0.0, 1.0)],
|
||||
Filter::HistogramScan { position, contrast } => vec![("position", "Position", *position, 0.0, 1.0), ("contrast", "Contrast", *contrast, 0.0, 1.0)],
|
||||
Filter::HistogramRange { range, position } => vec![("range", "Range", *range, 0.0, 1.0), ("position", "Position", *position, 0.0, 1.0)],
|
||||
Filter::HistogramShift { offset } => vec![("offset", "Offset", *offset, -1.0, 1.0)],
|
||||
Filter::Warp { intensity, scale, seed } => {
|
||||
vec![
|
||||
("intensity", "Intensity (texels at 2K)", *intensity, 0.0, 128.0),
|
||||
@@ -250,6 +259,15 @@ pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> {
|
||||
set(min, "min", 0.0, 1.0);
|
||||
set(max, "max", 0.0, 1.0);
|
||||
}
|
||||
Filter::HistogramScan { position, contrast } => {
|
||||
set(position, "position", 0.0, 1.0);
|
||||
set(contrast, "contrast", 0.0, 1.0);
|
||||
}
|
||||
Filter::HistogramRange { range, position } => {
|
||||
set(range, "range", 0.0, 1.0);
|
||||
set(position, "position", 0.0, 1.0);
|
||||
}
|
||||
Filter::HistogramShift { offset } => set(offset, "offset", -1.0, 1.0),
|
||||
Filter::Warp { intensity, scale, seed: s } => {
|
||||
set(intensity, "intensity", 0.0, 256.0);
|
||||
set(scale, "scale", 0.01, 1000.0);
|
||||
|
||||
@@ -69,6 +69,7 @@ fn instance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn can_paste_instance(s: &Session) -> std::result::Result<(), String> {
|
||||
match &s.clipboard {
|
||||
Some((_, id)) if s.doc.project.locate(*id).is_some() => Ok(()),
|
||||
Some((doc, id)) if doc.project.effect(*id).is_some() => Err("the clipboard holds an effect (effect.paste)".into()),
|
||||
Some(_) => Err("the copied layer is no longer in the project (paste it instead)".into()),
|
||||
None => Err("the layer clipboard is empty".into()),
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set fill source",
|
||||
[],
|
||||
None,
|
||||
"{layer? | effect?: content fill effect id, channel, color?|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?|image?|anchor?: anchor effect id, anchorChannel?, enabled?}",
|
||||
"{layer? | effect?: content fill effect id, channel, color?|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?|image?|anchor?: anchor effect id, anchorChannel?, enabled?, solo?: true (this channel on, every other one off)}",
|
||||
has_layer,
|
||||
fill_set
|
||||
),
|
||||
@@ -303,7 +303,9 @@ fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> {
|
||||
fn fill_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let target = fill_target(s, p, "layer.fill.set")?;
|
||||
let ch = channel_param("layer.fill.set", p, "channel")?.ok_or_else(|| bad("layer.fill.set", "`channel` is required"))?;
|
||||
let enabled = boolp(p, "enabled");
|
||||
// `solo`: this channel on, every other one off.
|
||||
let solo = boolp(p, "solo") == Some(true);
|
||||
let enabled = if solo { Some(true) } else { boolp(p, "enabled") };
|
||||
let source = if let Some(kind) = strp(p, "procedural") {
|
||||
let kind = ProceduralKind::parse(kind).ok_or_else(|| bad("layer.fill.set", format!("unknown procedural `{kind}`")))?;
|
||||
let mut pr = Procedural::new(kind);
|
||||
@@ -336,7 +338,7 @@ fn fill_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else if enabled.is_some() {
|
||||
None
|
||||
} else {
|
||||
return Err(bad("layer.fill.set", "give `color`, `value`, `procedural`, `image`, `anchor` or `enabled`"));
|
||||
return Err(bad("layer.fill.set", "give `color`, `value`, `procedural`, `image`, `anchor`, `enabled` or `solo`"));
|
||||
};
|
||||
s.edit("Set fill", |s| {
|
||||
let f = fill_mut(s, target)?;
|
||||
@@ -348,6 +350,9 @@ fn fill_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
FillTarget::Effect(_) => {
|
||||
let src = source.unwrap_or_else(|| f.source(ch));
|
||||
f.sources.insert(ch, src);
|
||||
if solo {
|
||||
f.sources.retain(|c, _| *c == ch);
|
||||
}
|
||||
}
|
||||
FillTarget::Layer(id) => {
|
||||
if let Some(src) = source {
|
||||
@@ -359,6 +364,9 @@ fn fill_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
l.channels.entry(ch).or_default();
|
||||
}
|
||||
if solo {
|
||||
l.channels.retain(|c, _| *c == ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -36,7 +36,11 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
fn can_paste(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.clipboard.is_some() { Ok(()) } else { Err("the layer clipboard is empty".into()) }
|
||||
match &s.clipboard {
|
||||
Some((doc, id)) if doc.project.layers.contains_key(id) => Ok(()),
|
||||
Some(_) => Err("the clipboard holds an effect (effect.paste)".into()),
|
||||
None => Err("the layer clipboard is empty".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Encoded "nothing painted" texel for a channel image (value 0, coverage 0).
|
||||
@@ -47,7 +51,7 @@ pub(crate) fn empty_texel(c: Channel) -> Vec<u16> {
|
||||
v
|
||||
}
|
||||
|
||||
fn fit(img: &TileImage, (w, h): (u32, u32), empty: &[u16]) -> TileImage {
|
||||
pub(crate) fn fit(img: &TileImage, (w, h): (u32, u32), empty: &[u16]) -> TileImage {
|
||||
if (img.width(), img.height()) == (w, h) { img.clone() } else { img.resampled(w, h, empty) }
|
||||
}
|
||||
|
||||
@@ -194,21 +198,8 @@ impl Session {
|
||||
/// Layer `id` of texture set `ts` alone (content times mask) as premultiplied tiles per
|
||||
/// channel over the set's covered tiles. None for folders or a set not ready.
|
||||
pub(crate) fn flatten(&self, ts: usize, id: LayerId) -> Option<Vec<texturecraft_compose::eval::FlatTile>> {
|
||||
let cache = self.caches.get(ts)?;
|
||||
let tiles: Vec<(u32, u32)> = cache.covered_tiles.iter().copied().collect();
|
||||
let empty = Default::default();
|
||||
let inputs = texturecraft_compose::Inputs {
|
||||
project: &self.doc.project,
|
||||
ts,
|
||||
mesh: &self.mesh,
|
||||
gbuf: &cache.gbuf,
|
||||
pixels: &self.doc.pixels,
|
||||
baked: self.doc.baked.get(&ts).unwrap_or(&empty),
|
||||
preview: None,
|
||||
images: &self.images,
|
||||
bounds: self.mesh.bounds(),
|
||||
};
|
||||
texturecraft_compose::flatten_layer(&inputs, id, &tiles)
|
||||
let tiles: Vec<(u32, u32)> = self.caches.get(ts)?.covered_tiles.iter().copied().collect();
|
||||
self.with_inputs(ts, |inp| texturecraft_compose::flatten_layer(inp, id, &tiles))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,9 +9,11 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod bake_cmds;
|
||||
pub mod brush_preset_cmds;
|
||||
pub mod camera_cmds;
|
||||
pub mod commands;
|
||||
pub mod decal_cmds;
|
||||
pub mod effect_clipboard;
|
||||
pub mod file_cmds;
|
||||
pub mod filter_lib;
|
||||
pub mod inspect;
|
||||
@@ -21,6 +23,7 @@ pub mod layer_ops;
|
||||
pub mod mask_cmds;
|
||||
pub mod material_lib;
|
||||
pub mod materials;
|
||||
pub mod meshmap_cmds;
|
||||
pub mod painting;
|
||||
pub mod path_tool;
|
||||
// Mesh reimport reads files: native only.
|
||||
@@ -35,6 +38,7 @@ pub mod session;
|
||||
pub mod set_cmds;
|
||||
pub mod smart_masks;
|
||||
pub mod template_cmds;
|
||||
pub mod text_cmds;
|
||||
pub mod tool_cmds;
|
||||
pub mod uv_tile_cmds;
|
||||
pub mod view_cmds;
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{
|
||||
BlendMode, Channel, CompareOp, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, Procedural, ProceduralKind,
|
||||
Source,
|
||||
Project, Source,
|
||||
};
|
||||
|
||||
use crate::commands::{CommandSpec, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p};
|
||||
use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p};
|
||||
use crate::layer_cmds::projection_from;
|
||||
use crate::session::StackTarget;
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add filter",
|
||||
["Layers", "Effects"],
|
||||
None,
|
||||
"{layer?, target?: mask|content, name?, filter?: id from filter.list (invert, threshold, blur, sharpen, hsl, levels, contrastLuminosity, colorBalance, gradientMap, posterize, clamp, warp, blurDirectional, slopeBlur, matFinishGrind|Raw|Sanded|Hammered), level?, radius?, amount?, hue?: turns -1..1, saturation?, lightness?, contrast?, luminosity?, shadows?|midtones?|highlights?: [r,g,b] -1..1, colors?: [[r,g,b]|\"#rrggbb\", ...], levels?, min?, max?, intensity?, scale?, seed?, angle?} — material finishes go on the content",
|
||||
"{layer?, target?: mask|content, name?, filter?: id from filter.list (invert, threshold, blur, sharpen, hsl, levels, contrastLuminosity, colorBalance, gradientMap, posterize, clamp, histogramScan|Range|Shift, warp, blurDirectional, slopeBlur, matFinishGrind|Raw|Sanded|Hammered), level?, radius?, amount?, hue?: turns -1..1, saturation?, lightness?, contrast?, luminosity?, shadows?|midtones?|highlights?: [r,g,b] -1..1, colors?: [[r,g,b]|\"#rrggbb\", ...], levels?, min?, max?, position?, range?, offset?, intensity?, scale?, seed?, angle?} — material finishes go on the content",
|
||||
has_layer,
|
||||
add_filter
|
||||
),
|
||||
@@ -98,7 +98,26 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_layer,
|
||||
set
|
||||
),
|
||||
cmd!("effect.remove", "Remove effect", [], None, "{effect}", has_layer, remove_effect),
|
||||
cmd!("effect.remove", "Remove effect", [], None, "{effect?: the selected effect}", has_layer, remove_effect),
|
||||
cmd!(
|
||||
"effect.duplicate",
|
||||
"Duplicate effect",
|
||||
[],
|
||||
None,
|
||||
"{effect?: the selected effect} → {effect} (the copy, just above it, pixels included)",
|
||||
has_layer,
|
||||
duplicate_effect
|
||||
),
|
||||
cmd!("effect.move", "Move effect", [], None, "{effect, index: position in its stack, 0 = bottom (applied first)}", has_layer, move_effect),
|
||||
cmd!(
|
||||
"effect.histogram",
|
||||
"Effect input histogram",
|
||||
[],
|
||||
None,
|
||||
"{effect, channel?: for content effects (default: the layer's first channel), bins?: 2..256 (64)} → {target: mask|content, channel?, bins: [count per bucket over 0..1]}",
|
||||
always,
|
||||
histogram
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -200,7 +219,7 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// Whether `effect.add.*` targets the layer content (`target: "content"`) or its mask (the
|
||||
/// default).
|
||||
fn content_target(p: &Value, cmd: &str) -> Result<bool> {
|
||||
pub(crate) fn content_target(p: &Value, cmd: &str) -> Result<bool> {
|
||||
match strp(p, "target") {
|
||||
None | Some("mask") => Ok(false),
|
||||
Some("content") => Ok(true),
|
||||
@@ -369,12 +388,33 @@ fn add_compare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
push_effect(s, p, kind, BlendMode::Normal)
|
||||
}
|
||||
|
||||
fn effect_id(p: &Value, cmd: &str) -> Result<LayerId> {
|
||||
u64p(p, "effect").map(LayerId).ok_or_else(|| bad(cmd, "`effect` id is required"))
|
||||
/// The `effect` param, or the selected effect.
|
||||
pub(crate) fn effect_id(s: &Session, p: &Value, cmd: &str) -> Result<LayerId> {
|
||||
match (u64p(p, "effect"), s.target) {
|
||||
(Some(e), _) => Ok(LayerId(e)),
|
||||
(None, StackTarget::Effect(e)) => Ok(e),
|
||||
(None, _) => Err(bad(cmd, "`effect` is required (no effect is selected)")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The distribution of the values entering an effect (what a levels effect remaps).
|
||||
fn histogram(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "effect.histogram";
|
||||
let eid = effect_id(s, p, CMD)?;
|
||||
let (owner, _) = s.doc.project.effect(eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?;
|
||||
let l = s.doc.project.layer(owner)?;
|
||||
let content = l.content_effects.iter().any(|e| e.id == eid);
|
||||
let channel = match channel_param(CMD, p, "channel")? {
|
||||
Some(c) => c,
|
||||
None => l.channels.keys().next().copied().unwrap_or(Channel::BaseColor),
|
||||
};
|
||||
let bins = u64p(p, "bins").unwrap_or(64).clamp(2, 256) as usize;
|
||||
let counts = s.effect_histogram(eid, channel, bins).ok_or_else(|| bad(CMD, "the texture set is not ready"))?;
|
||||
Ok(if content { json!({"target": "content", "channel": channel.id(), "bins": counts}) } else { json!({"target": "mask", "bins": counts}) })
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let eid = effect_id(p, "effect.set")?;
|
||||
let eid = effect_id(s, p, "effect.set")?;
|
||||
let blend = blend_param("effect.set", p, "blend")?;
|
||||
// A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone
|
||||
// re-targets the current one.
|
||||
@@ -431,8 +471,60 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// The stack (a mask's or a layer's content effects) holding effect `eid`, and its position there.
|
||||
fn stack_of(project: &mut Project, eid: LayerId) -> Option<(&mut Vec<Effect>, usize)> {
|
||||
project.layers.values_mut().find_map(|l| {
|
||||
l.mask.iter_mut().map(|m| &mut m.effects).chain(std::iter::once(&mut l.content_effects)).find_map(|list| {
|
||||
let i = list.iter().position(|e| e.id == eid)?;
|
||||
Some((list, i))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn duplicate_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "effect.duplicate";
|
||||
let eid = effect_id(s, p, CMD)?;
|
||||
let new = s.edit("Duplicate effect", |s| {
|
||||
let new = s.doc.project.alloc_id();
|
||||
let (list, i) = stack_of(&mut s.doc.project, eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?;
|
||||
let mut e = list.get(i).cloned().ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?;
|
||||
e.id = new;
|
||||
e.name = format!("{} copy", e.name);
|
||||
list.insert(i + 1, e);
|
||||
// Painted effects keep their pixels (copy-on-write tiles: cheap).
|
||||
let px = &mut s.doc.pixels;
|
||||
if let Some(img) = px.masks.get(&eid).cloned() {
|
||||
px.masks.insert(new, img);
|
||||
}
|
||||
for c in Channel::ALL {
|
||||
if let Some(img) = px.layer(eid, c).cloned() {
|
||||
px.layers.insert((new, c), img);
|
||||
}
|
||||
}
|
||||
Ok(new)
|
||||
})?;
|
||||
if s.target == StackTarget::Effect(eid) {
|
||||
s.target = StackTarget::Effect(new);
|
||||
}
|
||||
Ok(json!({ "effect": new.0 }))
|
||||
}
|
||||
|
||||
fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "effect.move";
|
||||
let eid = effect_id(s, p, CMD)?;
|
||||
let index = u64p(p, "index").ok_or_else(|| bad(CMD, "`index` is required"))?;
|
||||
s.edit("Move effect", |s| {
|
||||
let (list, i) = stack_of(&mut s.doc.project, eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?;
|
||||
let e = list.remove(i);
|
||||
let to = usize::try_from(index).unwrap_or(usize::MAX).min(list.len());
|
||||
list.insert(to, e);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn remove_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let eid = effect_id(p, "effect.remove")?;
|
||||
let eid = effect_id(s, p, "effect.remove")?;
|
||||
s.edit("Remove effect", |s| {
|
||||
let content = match s.doc.project.effect(eid) {
|
||||
Some((owner, _)) => s.doc.project.layer(owner)?.content_effects.iter().any(|e| e.id == eid),
|
||||
|
||||
@@ -65,6 +65,9 @@ pub const MATERIALS: &[SmartMaterial] = &[
|
||||
m("chrome", "Chrome", METAL, [0.55, 0.556, 0.554], 1.0, 0.05),
|
||||
m("titanium", "Titanium", METAL, [0.542, 0.497, 0.449], 1.0, 0.32),
|
||||
m("nickel", "Nickel", METAL, [0.66, 0.609, 0.526], 1.0, 0.25),
|
||||
m("platinum", "Platinum", METAL, [0.673, 0.637, 0.585], 1.0, 0.2),
|
||||
m("zinc", "Zinc", METAL, [0.664, 0.824, 0.85], 1.0, 0.38),
|
||||
m("cobalt", "Cobalt", METAL, [0.662, 0.655, 0.634], 1.0, 0.3),
|
||||
m("galvanized", "Steel Galvanized", METAL, [0.69, 0.71, 0.72], 1.0, 0.4),
|
||||
m("rust", "Rust", METAL, [0.3, 0.1, 0.03], 0.0, 0.85),
|
||||
// Woods.
|
||||
@@ -73,6 +76,7 @@ pub const MATERIALS: &[SmartMaterial] = &[
|
||||
m("wood_walnut", "Walnut", WOOD, [0.12, 0.06, 0.03], 0.0, 0.5),
|
||||
m("wood_pine", "Pine", WOOD, [0.52, 0.33, 0.16], 0.0, 0.65),
|
||||
m("plywood", "Plywood", WOOD, [0.55, 0.38, 0.21], 0.0, 0.75),
|
||||
m("bark", "Bark", WOOD, [0.14, 0.1, 0.07], 0.0, 0.9),
|
||||
m("wood_painted", "Wood Painted", WOOD, [0.61, 0.59, 0.54], 0.0, 0.48),
|
||||
// Stone, masonry and earth.
|
||||
m("concrete", "Concrete", STONE, [0.27, 0.26, 0.25], 0.0, 0.9),
|
||||
@@ -86,6 +90,8 @@ pub const MATERIALS: &[SmartMaterial] = &[
|
||||
m("slate", "Slate", STONE, [0.11, 0.115, 0.13], 0.0, 0.72),
|
||||
m("sandstone", "Sandstone", STONE, [0.52, 0.38, 0.23], 0.0, 0.9),
|
||||
m("terrazzo", "Terrazzo", STONE, [0.7, 0.69, 0.66], 0.0, 0.3),
|
||||
m("sand", "Sand", STONE, [0.52, 0.41, 0.26], 0.0, 0.95),
|
||||
m("mud", "Mud", STONE, [0.12, 0.08, 0.05], 0.0, 0.6),
|
||||
// Plastics, rubber, composites.
|
||||
m("plastic_glossy", "Plastic Glossy", PLASTIC, [0.8, 0.12, 0.08], 0.0, 0.16),
|
||||
m("plastic_matte", "Plastic Matte", PLASTIC, [0.18, 0.18, 0.19], 0.0, 0.6),
|
||||
@@ -102,12 +108,15 @@ pub const MATERIALS: &[SmartMaterial] = &[
|
||||
m("ceramic", "Ceramic White", GLASS, [0.8, 0.8, 0.78], 0.0, 0.08),
|
||||
m("glass", "Glass Clear", GLASS, [0.88, 0.9, 0.9], 0.0, 0.03),
|
||||
m("glass_frosted", "Glass Frosted", GLASS, [0.84, 0.88, 0.88], 0.0, 0.45),
|
||||
m("ice", "Ice", GLASS, [0.72, 0.82, 0.88], 0.0, 0.12),
|
||||
m("car_paint", "Car Paint", PLASTIC, [0.45, 0.025, 0.03], 0.0, 0.4),
|
||||
// Organic.
|
||||
m("skin", "Skin", ORGANIC, [0.56, 0.35, 0.27], 0.0, 0.5),
|
||||
m("wax", "Candle Wax", ORGANIC, [0.8, 0.72, 0.55], 0.0, 0.35),
|
||||
m("cork", "Cork", ORGANIC, [0.36, 0.21, 0.1], 0.0, 0.85),
|
||||
m("paper", "Paper", ORGANIC, [0.82, 0.81, 0.77], 0.0, 0.92),
|
||||
m("snow", "Snow", ORGANIC, [0.85, 0.87, 0.9], 0.0, 0.6),
|
||||
m("bone", "Bone", ORGANIC, [0.7, 0.63, 0.5], 0.0, 0.55),
|
||||
// Smart materials.
|
||||
sm("steel_painted_worn", "Steel Painted Worn", METAL, [0.42, 0.06, 0.04], 0.2, 0.45),
|
||||
sm("steel_painted_rust", "Steel Painted Rust Leaks", METAL, [0.62, 0.62, 0.6], 0.1, 0.5),
|
||||
@@ -232,10 +241,11 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
|
||||
let clouds_rough = |seed: u32| gray(P::Clouds, 6.0, seed, r * 0.85, (r * 1.2).min(1.0));
|
||||
match m.id {
|
||||
// ---- Metals -------------------------------------------------------------------------
|
||||
"steel" | "steel_dark" | "iron" | "copper" | "brass" | "bronze" | "gold_polished" | "silver" | "aluminium" | "chrome" | "nickel" => {
|
||||
plain_metal(b, clouds_rough(7))
|
||||
}
|
||||
"steel" | "steel_dark" | "iron" | "copper" | "brass" | "bronze" | "gold_polished" | "silver" | "aluminium" | "chrome" | "nickel" | "platinum"
|
||||
| "cobalt" => plain_metal(b, clouds_rough(7)),
|
||||
"steel_stainless" | "aluminium_brushed" | "titanium" => plain_metal(b, gray(P::Brushed, 3.0, 3, r * 0.75, r * 1.25)),
|
||||
// Zinc plate: large crystalline spangles.
|
||||
"zinc" => one(b, metal(pat(P::Voronoi, 6.0, 21, 1.0, m.base.map(|v| v * 0.8), m.base), gray(P::Voronoi, 6.0, 21, r * 1.5, r * 0.6))),
|
||||
// Brushing lines run along X; the highlights stretch across them (a quarter turn).
|
||||
"steel_brushed_aniso" => one(
|
||||
b,
|
||||
@@ -275,6 +285,19 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
|
||||
}
|
||||
// Stone chips in a pale binder, polished flat.
|
||||
"terrazzo" => one(b, dielectric(pat(P::Voronoi, 18.0, 9, 1.0, [0.55, 0.55, 0.53], [0.85, 0.84, 0.8]), gray(P::Voronoi, 18.0, 9, 0.34, 0.26))),
|
||||
// Fine grains in soft wind ripples.
|
||||
"sand" => one(
|
||||
b,
|
||||
plus(dielectric(pat(P::Noise, 12.0, 27, 1.0, [0.42, 0.32, 0.19], [0.6, 0.48, 0.31]), u(0.95)), height(gray(P::Perlin, 4.0, 27, -0.012, 0.0))),
|
||||
),
|
||||
// Glossy wet patches over rougher, drier mud.
|
||||
"mud" => one(
|
||||
b,
|
||||
plus(
|
||||
dielectric(pat(P::Clouds, 3.0, 29, 1.0, [0.05, 0.035, 0.02], [0.17, 0.12, 0.075]), gray(P::Grunge, 3.0, 29, 0.85, 0.2)),
|
||||
height(gray(P::Clouds, 3.0, 29, -0.03, 0.0)),
|
||||
),
|
||||
),
|
||||
"cork" => {
|
||||
one(b, plus(dielectric(pat(P::Noise, 6.0, 17, 1.0, [0.25, 0.14, 0.06], [0.45, 0.28, 0.13]), u(0.85)), height(gray(P::Pores, 20.0, 17, -0.01, 0.0))))
|
||||
}
|
||||
@@ -310,6 +333,11 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
|
||||
),
|
||||
),
|
||||
"plywood" => one(b, dielectric(pat(P::Wood, 1.2, 15, 0.6, [0.42, 0.27, 0.13], [0.66, 0.47, 0.27]), gray(P::Wood, 1.2, 15, 0.8, 0.7))),
|
||||
// Dark, deep furrows between gray-brown ridges.
|
||||
"bark" => one(
|
||||
b,
|
||||
plus(dielectric(pat(P::Streaks, 8.0, 25, 1.4, [0.13, 0.105, 0.08], [0.03, 0.022, 0.015]), u(0.9)), height(gray(P::Streaks, 8.0, 25, 0.0, -0.06))),
|
||||
),
|
||||
"wood_painted" => one(
|
||||
b,
|
||||
plus(
|
||||
@@ -357,15 +385,21 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
|
||||
"plastic_glossy" | "plastic_matte" | "ceramic" => one(b, dielectric(rgb(m.base), clouds_rough(9))),
|
||||
"plastic_textured" => one(b, plus(dielectric(rgb(m.base), gray(P::Leather, 40.0, 5, 0.66, 0.5)), height(gray(P::Leather, 40.0, 5, -0.01, 0.0)))),
|
||||
"rubber" => one(b, dielectric(pat(P::Noise, 0.5, 3, 1.0, [0.025; 3], [0.035; 3]), gray(P::Noise, 0.5, 3, 0.84, 0.94))),
|
||||
"carbon_fiber" => {
|
||||
one(b, plus(dielectric(pat(P::Weave, 24.0, 1, 1.0, [0.01, 0.01, 0.012], [0.06, 0.06, 0.065]), u(r)), height(gray(P::Weave, 24.0, 1, 0.0, 0.006))))
|
||||
}
|
||||
// Twill-woven tows under a clear coat: the warp catches the light, the weft stays dark.
|
||||
"carbon_fiber" => one(
|
||||
b,
|
||||
plus(
|
||||
dielectric(pat(P::Twill, 12.0, 1, 1.0, [0.004, 0.004, 0.005], [0.08, 0.08, 0.085]), gray(P::Twill, 12.0, 1, 0.5, 0.28)),
|
||||
[(CoatWeight, u(1.0)), (CoatRoughness, u(r * 0.2)), (Height, gray(P::Twill, 12.0, 1, 0.0, 0.002))],
|
||||
),
|
||||
),
|
||||
// ---- Fabric and leather -------------------------------------------------------------
|
||||
"fabric" => {
|
||||
one(b, plus(dielectric(pat(P::Weave, 18.0, 2, 1.0, [0.27, 0.29, 0.34], [0.6, 0.62, 0.7]), u(r)), height(gray(P::Weave, 18.0, 2, -0.01, 0.0))))
|
||||
}
|
||||
// Indigo twill: diagonal ribs.
|
||||
"denim" => {
|
||||
one(b, plus(dielectric(pat(P::Weave, 22.0, 5, 1.0, [0.02, 0.03, 0.08], [0.12, 0.16, 0.3]), u(r)), height(gray(P::Weave, 22.0, 5, -0.01, 0.0))))
|
||||
one(b, plus(dielectric(pat(P::Twill, 22.0, 5, 1.0, [0.015, 0.025, 0.07], [0.15, 0.2, 0.38]), u(r)), height(gray(P::Twill, 22.0, 5, -0.01, 0.0))))
|
||||
}
|
||||
"leather" => one(
|
||||
b,
|
||||
@@ -384,8 +418,9 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
|
||||
"velvet" => one(
|
||||
b,
|
||||
plus(
|
||||
dielectric(pat(P::Weave, 30.0, 3, 1.0, [0.07, 0.008, 0.05], m.base), u(r)),
|
||||
[(SheenWeight, u(1.0)), (SheenColor, rgb([0.95, 0.55, 0.85])), (SheenRoughness, u(0.35)), (Height, gray(P::Weave, 30.0, 3, -0.004, 0.0))],
|
||||
// A pile, not a weave: soft crushed patches under a bright sheen.
|
||||
dielectric(pat(P::Clouds, 3.0, 3, 1.0, [0.06, 0.006, 0.045], m.base), u(r)),
|
||||
[(SheenWeight, u(1.0)), (SheenColor, rgb([0.95, 0.55, 0.85])), (SheenRoughness, u(0.35)), (Height, gray(P::Noise, 1.0, 3, -0.002, 0.0))],
|
||||
),
|
||||
),
|
||||
// ---- Coated and translucent ---------------------------------------------------------
|
||||
@@ -406,6 +441,27 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
|
||||
"wax" => one(b, plus(dielectric(pat(P::Clouds, 2.0, 11, 1.0, [0.74, 0.66, 0.5], m.base), clouds_rough(11)), [(ScatterWeight, u(1.0))])),
|
||||
// ---- Glass (the Transmission channel; the base color tints the light going through) ----
|
||||
"glass" => one(b, plus(dielectric(rgb(m.base), u(r)), [(Transmission, u(1.0))])),
|
||||
// Clear with cloudy patches of trapped air.
|
||||
"ice" => one(
|
||||
b,
|
||||
plus(dielectric(pat(P::Clouds, 4.0, 31, 1.0, m.base, [0.84, 0.88, 0.9]), clouds_rough(31)), [(Transmission, gray(P::Clouds, 4.0, 31, 0.9, 0.5))]),
|
||||
),
|
||||
// Bright, rough and slightly translucent.
|
||||
"snow" => one(
|
||||
b,
|
||||
plus(
|
||||
dielectric(pat(P::Clouds, 4.0, 33, 1.0, [0.8, 0.82, 0.86], [0.88, 0.89, 0.9]), gray(P::Noise, 1.0, 33, 0.5, 0.7)),
|
||||
[(ScatterWeight, u(0.5)), (Height, gray(P::Perlin, 3.0, 33, -0.02, 0.0))],
|
||||
),
|
||||
),
|
||||
// Porous, ivory to tan, with a little light under the surface.
|
||||
"bone" => one(
|
||||
b,
|
||||
plus(
|
||||
dielectric(pat(P::Clouds, 5.0, 35, 1.0, [0.58, 0.5, 0.37], m.base), clouds_rough(35)),
|
||||
[(ScatterWeight, u(0.3)), (Height, gray(P::Pores, 16.0, 35, -0.006, 0.0))],
|
||||
),
|
||||
),
|
||||
"glass_frosted" => one(b, plus(dielectric(rgb(m.base), gray(P::Noise, 1.0, 2, 0.4, 0.5)), [(Transmission, u(1.0))])),
|
||||
// ---- Smart materials ----------------------------------------------------------------
|
||||
"steel_painted_worn" => {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
//! Mesh map slots of the Texture Set Settings: use an image resource as a mesh map (baked in
|
||||
//! another app, or edited by hand) instead of baking it, or clear a slot.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use rayon::prelude::*;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_compose::ImageRes;
|
||||
use texturecraft_core::{BakedMap, MAX_RESOLUTION, NormalFormat};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, strp};
|
||||
use crate::set_cmds::ts_param;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"textureSet.meshMap.set",
|
||||
"Use image as mesh map",
|
||||
[],
|
||||
None,
|
||||
"{ts?, map: mesh map id (normal_base, ambient_occlusion, curvature, id, height…), image: resource name} → {map, resolution} — resampled to the size of the set's other mesh maps (or its bake size); a normal map is read in the project's normal format",
|
||||
always,
|
||||
set
|
||||
),
|
||||
cmd!("textureSet.meshMap.clear", "Clear mesh map", [], None, "{ts?, map}", always, clear),
|
||||
]
|
||||
}
|
||||
|
||||
fn map_param(p: &Value, cmd: &str) -> Result<BakedMap> {
|
||||
let id = strp(p, "map").ok_or_else(|| bad(cmd, "`map` is required"))?;
|
||||
BakedMap::parse(id).ok_or_else(|| bad(cmd, format!("unknown mesh map `{id}`")))
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "textureSet.meshMap.set";
|
||||
let ts = ts_param(s, p, CMD)?;
|
||||
let map = map_param(p, CMD)?;
|
||||
let name = strp(p, "image").ok_or_else(|| bad(CMD, "`image` (an image resource name) is required"))?;
|
||||
let img = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?;
|
||||
let set = s.doc.project.texture_set(ts)?;
|
||||
// shortcut: one image spans the whole set; UV-tiled sets would need one image per tile.
|
||||
if !set.uv_tiles.is_empty() {
|
||||
return Err(bad(CMD, format!("\"{}\" has UV tiles: mesh maps from images need a set without them", set.name)));
|
||||
}
|
||||
// Every mesh map of a set shares one size: the other maps', or what a bake would make.
|
||||
let res = s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()).map_or(set.bake.resolution, |b| b.resolution);
|
||||
if !(1..=MAX_RESOLUTION).contains(&res) {
|
||||
return Err(bad(CMD, format!("mesh map size {res} is not in 1..={MAX_RESOLUTION}")));
|
||||
}
|
||||
let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX;
|
||||
let data = resample(&img, map.components(), res, directx);
|
||||
s.edit("Use image as mesh map", |s| {
|
||||
let entry = s.doc.baked.entry(ts).or_default();
|
||||
entry.resolution = res;
|
||||
entry.maps.insert(map, Arc::new(data));
|
||||
s.doc.project.texture_set_mut(ts)?.baked.insert(map);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "map": map.id(), "resolution": res }))
|
||||
}
|
||||
|
||||
/// `img` as `res` × `res` texels of `comps` values each, as stored in the file (mesh maps hold
|
||||
/// data, not colors, so nothing is linearized); `flip_green` reads a DirectX normal map.
|
||||
fn resample(img: &ImageRes, comps: usize, res: u32, flip_green: bool) -> Vec<f32> {
|
||||
let n = res as usize;
|
||||
let mut out = vec![0.0; n * n * comps];
|
||||
out.par_chunks_mut(n * comps).enumerate().for_each(|(y, row)| {
|
||||
let v = (y as f32 + 0.5) / res as f32;
|
||||
for (x, texel) in row.chunks_exact_mut(comps).enumerate() {
|
||||
let mut c = img.sample((x as f32 + 0.5) / res as f32, v);
|
||||
if flip_green {
|
||||
c[1] = 1.0 - c[1];
|
||||
}
|
||||
for (o, c) in texel.iter_mut().zip(c) {
|
||||
*o = c;
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "textureSet.meshMap.clear";
|
||||
let ts = ts_param(s, p, CMD)?;
|
||||
let map = map_param(p, CMD)?;
|
||||
if !s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) {
|
||||
return Err(bad(CMD, format!("texture set {ts} has no {} map", map.label())));
|
||||
}
|
||||
s.edit("Clear mesh map", |s| {
|
||||
if let Some(b) = s.doc.baked.get_mut(&ts) {
|
||||
b.maps.remove(&map);
|
||||
}
|
||||
s.doc.project.texture_set_mut(ts)?.baked.remove(&map);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
@@ -57,7 +57,10 @@ impl Session {
|
||||
let content = self.doc.project.layer(owner)?.content_effects.iter().any(|x| x.id == e);
|
||||
Ok(if content { PaintTarget::Layer(e) } else { PaintTarget::Mask(e) })
|
||||
}
|
||||
_ => Err(EngineError::Other("the selected effect is not a paint effect".into())),
|
||||
// A filter (or another effect) is selected, e.g. just added from the shelf: paint
|
||||
// what lies beneath it, so the new paint goes through it.
|
||||
Some((owner, _)) => self.paint_target_below(owner, e),
|
||||
None => Err(EngineError::Other("the selected effect is not a paint effect".into())),
|
||||
},
|
||||
StackTarget::Mask => {
|
||||
let eid = self.doc.project.alloc_id();
|
||||
@@ -72,6 +75,36 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a stroke paints while non-paint effect `effect` of layer `owner` is selected: the
|
||||
/// nearest paint effect below it in the same stack, else the paint layer's own pixels (for
|
||||
/// content) or a new paint effect inserted just below it (for a mask).
|
||||
fn paint_target_below(&mut self, owner: LayerId, effect: LayerId) -> Result<PaintTarget> {
|
||||
let eid = self.doc.project.alloc_id();
|
||||
let layer = self.doc.project.layer_mut(owner)?;
|
||||
let below = |effects: &[Effect], at: usize| effects.get(..at).and_then(|b| b.iter().rev().find(|x| matches!(x.kind, EffectKind::Paint))).map(|x| x.id);
|
||||
if let Some(at) = layer.content_effects.iter().position(|x| x.id == effect) {
|
||||
if let Some(id) = below(&layer.content_effects, at) {
|
||||
return Ok(PaintTarget::Layer(id));
|
||||
}
|
||||
return if matches!(layer.kind, LayerKind::Paint) {
|
||||
Ok(PaintTarget::Layer(owner))
|
||||
} else {
|
||||
Err(EngineError::Other(format!(
|
||||
"\"{}\" is a {} layer: paint on a paint layer or on its mask (a filter changes what lies below it)",
|
||||
layer.name,
|
||||
layer.kind.name()
|
||||
)))
|
||||
};
|
||||
}
|
||||
let mask = layer.mask.as_mut().ok_or_else(|| EngineError::Other("the selected effect is not a paint effect".into()))?;
|
||||
let at = mask.effects.iter().position(|x| x.id == effect).ok_or_else(|| EngineError::Other("the selected effect is not a paint effect".into()))?;
|
||||
if let Some(id) = below(&mask.effects, at) {
|
||||
return Ok(PaintTarget::Mask(id));
|
||||
}
|
||||
mask.effects.insert(at, Effect::new(eid, EffectKind::Paint));
|
||||
Ok(PaintTarget::Mask(eid))
|
||||
}
|
||||
|
||||
fn stroke_values(&self, target: PaintTarget) -> BTreeMap<Channel, [f32; 3]> {
|
||||
let ts = self.ts();
|
||||
let Ok(set) = self.doc.project.texture_set(ts) else { return BTreeMap::new() };
|
||||
@@ -483,13 +516,18 @@ impl Session {
|
||||
FillMode::Triangle => [tri].into_iter().collect(),
|
||||
FillMode::Mesh => m.triangles_of(material).map(|t| t as u32).collect(),
|
||||
FillMode::UvIsland => {
|
||||
// Triangles sharing vertex indices form a UV island (seams split vertices).
|
||||
let mut by_vertex: BTreeMap<usize, Vec<u32>> = BTreeMap::new();
|
||||
// Triangles sharing an edge in UV space form a UV island: imported meshes often
|
||||
// split vertices along hard edges (or per face) where the UVs run on, so shared
|
||||
// vertex indices alone break an island into its polygons.
|
||||
let corner = |i: usize| m.uvs.get(i).map(|uv| [(uv.x * 1e5).round() as i64, (uv.y * 1e5).round() as i64]);
|
||||
let edges = |t: usize| match m.tri(t).map(|v| v.map(corner)) {
|
||||
Some([Some(a), Some(b), Some(c)]) => [(a, b), (b, c), (c, a)].map(|(p, q)| (p.min(q), p.max(q))).to_vec(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let mut by_edge: BTreeMap<_, Vec<u32>> = BTreeMap::new();
|
||||
for t in m.triangles_of(material) {
|
||||
if let Some(v) = m.tri(t) {
|
||||
for i in v {
|
||||
by_vertex.entry(i).or_default().push(t as u32);
|
||||
}
|
||||
for e in edges(t) {
|
||||
by_edge.entry(e).or_default().push(t as u32);
|
||||
}
|
||||
}
|
||||
let mut seen = BTreeSet::new();
|
||||
@@ -498,12 +536,10 @@ impl Session {
|
||||
if !seen.insert(t) {
|
||||
continue;
|
||||
}
|
||||
if let Some(v) = m.tri(t as usize) {
|
||||
for i in v {
|
||||
for n in by_vertex.get(&i).map(Vec::as_slice).unwrap_or(&[]) {
|
||||
if !seen.contains(n) {
|
||||
stack.push(*n);
|
||||
}
|
||||
for e in edges(t as usize) {
|
||||
for n in by_edge.get(&e).map(Vec::as_slice).unwrap_or(&[]) {
|
||||
if !seen.contains(n) {
|
||||
stack.push(*n);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -573,3 +609,34 @@ fn with_commit_source<R>(
|
||||
let carried = st.canvas.pickup.as_ref().map(|p| &p.values);
|
||||
f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_geom::mesh::Mesh;
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
use crate::session::{FillMode, Session};
|
||||
|
||||
#[test]
|
||||
fn uv_island_fill_follows_uvs_across_split_vertices() {
|
||||
// Two copies of a plane, each triangle with its own three vertices (as hard edges or
|
||||
// per-face imports leave a mesh), the second copy apart in UV space.
|
||||
let plane = primitives::plane(2.0, 4);
|
||||
let (mut positions, mut uvs) = (Vec::<Vec3>::new(), Vec::<Vec2>::new());
|
||||
for shift in [0.0, 0.5] {
|
||||
for i in plane.indices.iter().map(|i| *i as usize) {
|
||||
positions.push(plane.positions[i] + Vec3::Y * shift);
|
||||
uvs.push(plane.uvs[i] * 0.5 + shift);
|
||||
}
|
||||
}
|
||||
let indices = (0..positions.len() as u32).collect();
|
||||
let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap();
|
||||
let n = plane.triangle_count();
|
||||
assert_eq!(mesh.vertex_count(), 6 * n, "no vertex is shared");
|
||||
let mut s = Session::new_project("t", mesh, "test", None, 128).unwrap();
|
||||
s.tool.fill_mode = FillMode::UvIsland;
|
||||
assert_eq!(s.fill_set(0, 0).len(), n, "the whole first island");
|
||||
assert_eq!(s.fill_set(n as u32, 0).len(), n, "only the second island");
|
||||
}
|
||||
}
|
||||
@@ -333,7 +333,7 @@ pub struct Session {
|
||||
/// Viewport size (pixels) used by scripted strokes.
|
||||
pub viewport: Vec2,
|
||||
pub(crate) stroke: Option<ActiveStroke>,
|
||||
/// Layer clipboard: a document snapshot and the copied layer.
|
||||
/// Layer clipboard: a document snapshot and the copied layer (or effect).
|
||||
pub clipboard: Option<(Document, LayerId)>,
|
||||
/// Decoded image resources (rebuilt from `doc.resources` by `Session::sync_images`).
|
||||
pub images: texturecraft_compose::ImageStore,
|
||||
@@ -601,6 +601,10 @@ impl Session {
|
||||
pub fn redo_label(&self) -> Option<&str> {
|
||||
self.redo.last().map(|(l, _)| l.as_str())
|
||||
}
|
||||
/// The undone steps, the next one to redo first.
|
||||
pub fn redo_labels(&self) -> Vec<String> {
|
||||
self.redo.iter().rev().map(|(l, _)| l.clone()).collect()
|
||||
}
|
||||
pub fn history_labels(&self) -> Vec<String> {
|
||||
self.undo.iter().map(|(l, _)| l.clone()).collect()
|
||||
}
|
||||
@@ -629,6 +633,14 @@ impl Session {
|
||||
self.modified = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.invalidate_changed(other);
|
||||
// An undone add or duplicate takes the selected effect away: select the stack it was in.
|
||||
if let StackTarget::Effect(e) = self.target
|
||||
&& self.doc.project.effect(e).is_none()
|
||||
{
|
||||
let p = &other.project;
|
||||
let content = p.effect(e).and_then(|(owner, _)| p.layers.get(&owner)).is_some_and(|l| l.content_effects.iter().any(|x| x.id == e));
|
||||
self.target = if content { StackTarget::Content } else { StackTarget::Mask };
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------------------
|
||||
@@ -773,12 +785,12 @@ impl Session {
|
||||
self.caches.get_mut(ts).map(|c| std::mem::take(&mut c.upload).into_iter().collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Grayscale RGBA8 of layer `id`'s mask at `size²` for the mask view (None without a mask).
|
||||
pub fn mask_view_rgba(&self, id: LayerId, size: u32) -> Option<Vec<u8>> {
|
||||
let (ts, _, _) = self.doc.project.locate(id)?;
|
||||
/// `f` on the compositor inputs of texture set `ts` (without a live stroke; None for a set
|
||||
/// not ready).
|
||||
pub(crate) fn with_inputs<R>(&self, ts: usize, f: impl FnOnce(&texturecraft_compose::Inputs) -> Option<R>) -> Option<R> {
|
||||
let cache = self.caches.get(ts)?;
|
||||
let empty = BakedMaps::default();
|
||||
let inputs = texturecraft_compose::Inputs {
|
||||
f(&texturecraft_compose::Inputs {
|
||||
project: &self.doc.project,
|
||||
ts,
|
||||
mesh: &self.mesh,
|
||||
@@ -788,11 +800,24 @@ impl Session {
|
||||
preview: None,
|
||||
images: &self.images,
|
||||
bounds: self.mesh.bounds(),
|
||||
};
|
||||
let gray = texturecraft_compose::mask_image(&inputs, id, size)?;
|
||||
})
|
||||
}
|
||||
|
||||
/// Grayscale RGBA8 of layer `id`'s mask at `size²` for the mask view (None without a mask).
|
||||
pub fn mask_view_rgba(&self, id: LayerId, size: u32) -> Option<Vec<u8>> {
|
||||
let (ts, _, _) = self.doc.project.locate(id)?;
|
||||
let gray = self.with_inputs(ts, |inp| texturecraft_compose::mask_image(inp, id, size))?;
|
||||
Some(gray.iter().flat_map(|g| [*g, *g, *g, 255]).collect())
|
||||
}
|
||||
|
||||
/// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's
|
||||
/// mask, or for a content effect the layer's `channel` (None for an unknown effect).
|
||||
pub fn effect_histogram(&self, effect: LayerId, channel: Channel, bins: usize) -> Option<Vec<u32>> {
|
||||
let (owner, _) = self.doc.project.effect(effect)?;
|
||||
let (ts, _, _) = self.doc.project.locate(owner)?;
|
||||
self.with_inputs(ts, |inp| texturecraft_compose::effect_histogram(inp, effect, channel, bins))
|
||||
}
|
||||
|
||||
pub fn baked(&self, ts: usize) -> Option<&BakedMaps> {
|
||||
self.doc.baked.get(&ts)
|
||||
}
|
||||
|
||||
@@ -28,6 +28,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("textureSet.channel.add", "Add channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, true)),
|
||||
cmd!("textureSet.channel.remove", "Remove channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, false)),
|
||||
cmd!("textureSet.visible", "Toggle texture set visibility", [], None, "{ts?, visible?}", always, visible),
|
||||
cmd!(
|
||||
"textureSet.visibility",
|
||||
"Show or hide texture sets",
|
||||
[],
|
||||
None,
|
||||
"{mode: showAll|hideAll|invert|solo, ts?} → {visible: [bool per set]}; solo shows only `ts` (the active set), or every set again when it already was the only one",
|
||||
always,
|
||||
visibility
|
||||
),
|
||||
cmd!("textureSet.rename", "Rename texture set", [], None, "{ts?, name}", always, rename),
|
||||
cmd!("textureSet.settings", "Texture set settings", [], None, "{ts?, description?, heightStrength?, normalFormat?: openGl|directX}", always, settings),
|
||||
cmd!(
|
||||
@@ -214,6 +223,25 @@ fn visible(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "visible": v }))
|
||||
}
|
||||
|
||||
fn visibility(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "textureSet.visibility";
|
||||
let ts = ts_param(s, p, cmd)?;
|
||||
let mode = strp(p, "mode").filter(|m| ["showAll", "hideAll", "invert", "solo"].contains(m));
|
||||
let mode = mode.ok_or_else(|| bad(cmd, "`mode` must be showAll, hideAll, invert or solo"))?;
|
||||
let sets = &mut s.doc.project.texture_sets;
|
||||
let solo = sets.iter().enumerate().all(|(i, t)| t.visible == (i == ts));
|
||||
for (i, t) in sets.iter_mut().enumerate() {
|
||||
t.visible = match mode {
|
||||
"showAll" => true,
|
||||
"hideAll" => false,
|
||||
"invert" => !t.visible,
|
||||
_ => solo || i == ts,
|
||||
};
|
||||
}
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(json!({ "visible": s.doc.project.texture_sets.iter().map(|t| t.visible).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ts = ts_param(s, p, "textureSet.rename")?;
|
||||
let name = strp(p, "name")
|
||||
@@ -251,3 +279,22 @@ fn settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn visibility_shows_hides_inverts_and_solos() {
|
||||
// The material ball has two texture sets.
|
||||
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
let mut run = |p: Value| crate::execute(&mut s, "textureSet.visibility", &p).map(|r| r["visible"].clone());
|
||||
assert_eq!(run(json!({"mode": "hideAll"})).unwrap(), json!([false, false]));
|
||||
assert_eq!(run(json!({"mode": "solo", "ts": 1})).unwrap(), json!([false, true]));
|
||||
assert_eq!(run(json!({"mode": "solo", "ts": 1})).unwrap(), json!([true, true]), "solo again shows every set");
|
||||
assert_eq!(run(json!({"mode": "solo", "ts": 0})).unwrap(), json!([true, false]));
|
||||
assert_eq!(run(json!({"mode": "invert"})).unwrap(), json!([false, true]));
|
||||
assert_eq!(run(json!({"mode": "showAll"})).unwrap(), json!([true, true]));
|
||||
assert!(run(json!({"mode": "sideways"})).is_err() && run(json!({"mode": "solo", "ts": 9})).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
//! Text: an image resource drawn from text in an installed font (or a built-in one), to stamp
|
||||
//! with the brush as its alpha or to place as a decal.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_paint::text::render_text;
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, color_param, f32p, strp};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("text.fonts", "List fonts", [], None, "{} — the installed font families with their styles, and the built-in ones", always, |_, _| Ok(fonts())),
|
||||
cmd!(
|
||||
"resource.text",
|
||||
"Add text",
|
||||
[],
|
||||
None,
|
||||
"{text (lines split at \\n), font?: family (text.fonts; default a common sans-serif), style?: e.g. Bold (default Regular), size?: 8..1024 texels per em (default 256), color?: [r,g,b] linear or \"#rrggbb\" (default white), name?} — draws the text as an image resource with an alpha (white for tool.brush {alpha: {image}}, colored for layer.add.decal)",
|
||||
always,
|
||||
add_text
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Fonts bundled with the app (egui's), used when nothing is installed or in the browser.
|
||||
const BUILT_IN: [(&str, &[u8]); 2] = [("Ubuntu Light", epaint_default_fonts::UBUNTU_LIGHT), ("Hack", epaint_default_fonts::HACK_REGULAR)];
|
||||
/// Families tried, in order, when no font is asked for.
|
||||
const DEFAULT_FAMILIES: [&str; 6] = ["Arial", "Segoe UI", "Helvetica", "Liberation Sans", "DejaVu Sans", "Noto Sans"];
|
||||
/// Largest font file read.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_FONT_BYTES: u64 = 128 << 20;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn installed() -> &'static [texturecraft_formats::fonts::FontFace] {
|
||||
static FONTS: std::sync::OnceLock<Vec<texturecraft_formats::fonts::FontFace>> = std::sync::OnceLock::new();
|
||||
FONTS.get_or_init(texturecraft_formats::fonts::system_fonts)
|
||||
}
|
||||
|
||||
fn fonts() -> Value {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let families = {
|
||||
let mut out: Vec<(String, Vec<String>)> = Vec::new();
|
||||
for f in installed() {
|
||||
match out.last_mut() {
|
||||
Some((family, styles)) if *family == f.family => styles.push(f.style.clone()),
|
||||
_ => out.push((f.family.clone(), vec![f.style.clone()])),
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let families: Vec<(String, Vec<String>)> = Vec::new();
|
||||
json!({
|
||||
"installed": families.into_iter().map(|(family, styles)| json!({"family": family, "styles": styles})).collect::<Vec<_>>(),
|
||||
"builtIn": BUILT_IN.map(|(name, _)| name),
|
||||
})
|
||||
}
|
||||
|
||||
/// The bytes and face index of `family` in `style` (a regular face when the style is missing),
|
||||
/// or the first default family installed, else the built-in font.
|
||||
fn font_bytes(family: Option<&str>, style: Option<&str>) -> Result<(std::borrow::Cow<'static, [u8]>, u32)> {
|
||||
let is = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
|
||||
if let Some((_, bytes)) = BUILT_IN.iter().find(|(name, _)| family.is_some_and(|f| is(f, name))) {
|
||||
return Ok((std::borrow::Cow::Borrowed(bytes), 0));
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let faces = installed();
|
||||
let pick = |family: &str| {
|
||||
let of: Vec<_> = faces.iter().filter(|f| is(&f.family, family)).collect();
|
||||
let regular = ["Regular", "Normal", "Book", "Roman"];
|
||||
let found = style.and_then(|s| of.iter().find(|f| is(&f.style, s)));
|
||||
found.or_else(|| of.iter().find(|f| regular.iter().any(|r| is(&f.style, r)))).or(of.first()).copied()
|
||||
};
|
||||
let face = match family {
|
||||
Some(f) => Some(pick(f).ok_or_else(|| bad("resource.text", format!("no font family `{f}` (see text.fonts)")))?),
|
||||
None => DEFAULT_FAMILIES.iter().find_map(|f| pick(f)),
|
||||
};
|
||||
if let Some(face) = face {
|
||||
let size = std::fs::metadata(&face.path).map(|m| m.len()).unwrap_or(u64::MAX);
|
||||
if size > MAX_FONT_BYTES {
|
||||
return Err(bad("resource.text", format!("{} is too large", face.path.display())));
|
||||
}
|
||||
let bytes = std::fs::read(&face.path).map_err(|e| bad("resource.text", format!("cannot read {}: {e}", face.path.display())))?;
|
||||
return Ok((std::borrow::Cow::Owned(bytes), face.index));
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = style;
|
||||
match family {
|
||||
Some(f) => Err(bad("resource.text", format!("no font family `{f}` (see text.fonts)"))),
|
||||
None => Ok((std::borrow::Cow::Borrowed(BUILT_IN[0].1), 0)),
|
||||
}
|
||||
}
|
||||
|
||||
fn add_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "resource.text";
|
||||
let text = strp(p, "text").ok_or_else(|| bad(cmd, "`text` is required"))?;
|
||||
let (font, index) = font_bytes(strp(p, "font"), strp(p, "style"))?;
|
||||
let size = f32p(p, "size").unwrap_or(256.0).clamp(8.0, 1024.0);
|
||||
let img = render_text(&font, index, text, size).map_err(|e| bad(cmd, e))?;
|
||||
let rgb = color_param(p, "color").unwrap_or([1.0; 3]).map(|c| (texturecraft_texel::linear_to_srgb(c.clamp(0.0, 1.0)) * 255.0).round() as u8);
|
||||
let png = texturecraft_formats::coverage_png(img.width, img.height, &img.coverage, rgb).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
// The resource is named after the text (its first line, shortened) unless a name is given.
|
||||
let label: String = strp(p, "name").unwrap_or_else(|| text.lines().next().unwrap_or_default()).chars().take(32).collect();
|
||||
let name = s.import_resource_bytes(&format!("Text {}.png", label.trim()), png)?;
|
||||
Ok(json!({ "name": name, "width": img.width, "height": img.height }))
|
||||
}
|
||||
@@ -42,7 +42,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"procedural": BrushAlpha::ALL.map(BrushAlpha::label),
|
||||
"library": alphas::library().iter().map(|a| json!({"id": a.id, "label": a.label, "category": a.category})).collect::<Vec<_>>(),
|
||||
}))),
|
||||
cmd!("tool.material", "Tool material", [], None, "{channel, color?|value?, enabled?} or {maskValue?: 0..1}", always, material),
|
||||
cmd!(
|
||||
"tool.material",
|
||||
"Tool material",
|
||||
[],
|
||||
None,
|
||||
"{channel, color?|value?, enabled?, solo?: true (paint this channel only)} or {maskValue?: 0..1}",
|
||||
always,
|
||||
material
|
||||
),
|
||||
cmd!(
|
||||
"tool.stencil",
|
||||
"Projection stencil",
|
||||
@@ -232,6 +240,9 @@ fn material(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if boolp(p, "solo") == Some(true) {
|
||||
s.tool.enabled = std::iter::once(c).collect();
|
||||
}
|
||||
}
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(json!({
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! Edit, viewport and display commands.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::project::ENVIRONMENTS;
|
||||
use texturecraft_core::{BakedMap, Channel, ToneMapping};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp};
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p};
|
||||
use crate::session::ViewMode;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
@@ -34,14 +35,51 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
pub(crate) fn edit_specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("edit.undo", "Undo", ["Edit"], Some("Ctrl+Z"), "{}", can_undo, |s, _| Ok(json!({ "undone": s.undo()? }))),
|
||||
cmd!("edit.redo", "Redo", ["Edit"], Some("Ctrl+Y"), "{}", can_redo, |s, _| Ok(json!({ "redone": s.redo()? }))),
|
||||
cmd!("edit.history", "History", [], None, "{}", always, |s, _| Ok(
|
||||
json!({ "undo": s.history_labels(), "redo": s.redo.iter().rev().map(|(l, _)| l.clone()).collect::<Vec<_>>() })
|
||||
cmd!(
|
||||
"edit.undo",
|
||||
"Undo",
|
||||
["Edit"],
|
||||
Some("Ctrl+Z"),
|
||||
"{steps?: 1 (as many as there are)} → {undone: the last step undone, steps}",
|
||||
can_undo,
|
||||
|s, p| {
|
||||
let (last, n) = repeat(s, p, Session::undo)?;
|
||||
Ok(json!({ "undone": last, "steps": n }))
|
||||
}
|
||||
),
|
||||
cmd!(
|
||||
"edit.redo",
|
||||
"Redo",
|
||||
["Edit"],
|
||||
Some("Ctrl+Y"),
|
||||
"{steps?: 1 (as many as there are)} → {redone: the last step redone, steps}",
|
||||
can_redo,
|
||||
|s, p| {
|
||||
let (last, n) = repeat(s, p, Session::redo)?;
|
||||
Ok(json!({ "redone": last, "steps": n }))
|
||||
}
|
||||
),
|
||||
cmd!("edit.history", "History", [], None, "{} → {undo: steps, oldest first, redo: undone steps, next first}", always, |s, _| Ok(
|
||||
json!({ "undo": s.history_labels(), "redo": s.redo_labels() })
|
||||
)),
|
||||
]
|
||||
}
|
||||
|
||||
/// Run `step` (undo or redo) `steps` times (default 1) or until the history runs out: the last
|
||||
/// step's label and how many ran (the History panel jumps to a step this way).
|
||||
fn repeat(s: &mut Session, p: &Value, step: fn(&mut Session) -> Result<String>) -> Result<(String, u64)> {
|
||||
let steps = u64p(p, "steps").unwrap_or(1).max(1);
|
||||
let mut last = step(s)?;
|
||||
let mut n = 1;
|
||||
while n < steps
|
||||
&& let Ok(l) = step(s)
|
||||
{
|
||||
last = l;
|
||||
n += 1;
|
||||
}
|
||||
Ok((last, n))
|
||||
}
|
||||
|
||||
fn frame(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let (lo, hi) = s.mesh.bounds();
|
||||
s.camera.frame(lo, hi);
|
||||
@@ -164,6 +202,9 @@ fn display(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return Err(bad("display.set", format!("no image resource `{name}` (import it with resource.import)")));
|
||||
}
|
||||
if let Some(e) = env.as_deref().filter(|e| !e.starts_with(texturecraft_core::project::ENV_RESOURCE_PREFIX) && !ENVIRONMENTS.contains(e)) {
|
||||
return Err(bad("display.set", format!("unknown environment `{e}`: one of {}, or resource:<image>", ENVIRONMENTS.join(", "))));
|
||||
}
|
||||
let d = &mut s.doc.project.display;
|
||||
if let Some(e) = env {
|
||||
d.environment = e;
|
||||
@@ -234,6 +275,10 @@ mod tests {
|
||||
fn hdr_resources_become_the_environment() {
|
||||
let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap();
|
||||
assert!(execute(&mut s, "display.set", &json!({"environment": "resource:sky.hdr"})).is_err(), "unknown resources are rejected");
|
||||
let e = execute(&mut s, "display.set", &json!({"environment": "nonexistent"})).unwrap_err().to_string();
|
||||
assert!(e.contains("Studio Soft"), "unknown environments are rejected with the valid names: {e}");
|
||||
assert_eq!(s.doc.project.display.environment, "Studio Soft");
|
||||
execute(&mut s, "display.set", &json!({"environment": "Night"})).unwrap();
|
||||
let img = image::Rgb32FImage::from_fn(64, 32, |_, y| image::Rgb([if y < 8 { 40.0 } else { 0.5 }; 3]));
|
||||
let mut hdr = Vec::new();
|
||||
image::DynamicImage::ImageRgb32F(img).write_to(&mut std::io::Cursor::new(&mut hdr), image::ImageFormat::Hdr).unwrap();
|
||||
|
||||
@@ -143,7 +143,7 @@ fn per_map_ray_settings_round_trip() {
|
||||
let b = s.doc.project.texture_sets[0].bake.clone();
|
||||
assert_eq!(b.ao, RaySettings { rays: 48, max_distance: 0.5, spread: 90.0, distribution: RayDistribution::Uniform });
|
||||
assert!(b.ao_ignore_backface && b.ao_self_occlusion == SelfOcclusion::SameMeshName);
|
||||
assert_eq!((b.thickness.rays, b.thickness.spread, b.thickness.max_distance), (12, 45.0, 0.25));
|
||||
assert_eq!((b.thickness.rays, b.thickness.spread, b.thickness.max_distance), (12, 45.0, 0.1));
|
||||
assert_eq!((b.bent_normal.rays, b.bent_normal.max_distance, b.bent_normal.spread), (6, 0.1, 180.0));
|
||||
assert_eq!((b.curvature_radius, b.position_mode, b.direction_mode), (3, PositionMode::BoundingSphere, DirectionMode::Positive));
|
||||
assert_eq!(r[0]["settings"]["ao"]["selfOcclusion"], "sameMeshName");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Content effects, HSL and anchor points through engine commands.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{Channel, LayerId};
|
||||
use texturecraft_engine::core::{Channel, EffectKind, LayerId};
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, StackTarget, execute};
|
||||
|
||||
@@ -111,3 +111,137 @@ fn painting_into_a_content_paint_effect() {
|
||||
assert!(s.doc.pixels.layer(LayerId(e), Channel::Roughness).is_none());
|
||||
assert!(center(&mut s, Channel::Roughness)[0] > 0.85);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effects_move_within_their_stack_and_duplicate_with_their_pixels() {
|
||||
let mut s = session();
|
||||
let layer = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3})).unwrap(), "layer");
|
||||
let paint = id(execute(&mut s, "effect.add.paint", &json!({"target": "content"})).unwrap(), "effect");
|
||||
execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.9})).unwrap();
|
||||
execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap();
|
||||
execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap();
|
||||
let fill = id(execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.2})).unwrap(), "effect");
|
||||
let order = |s: &Session| s.doc.project.layer(LayerId(layer)).unwrap().content_effects.iter().map(|e| e.id.0).collect::<Vec<_>>();
|
||||
assert!(close(center(&mut s, Channel::Roughness), [0.2; 3]), "the fill covers the paint");
|
||||
// To the bottom, the paint shows again; an index past the end means the top.
|
||||
execute(&mut s, "effect.move", &json!({"effect": fill, "index": 0})).unwrap();
|
||||
assert_eq!(order(&s), [fill, paint]);
|
||||
assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "{:?}", center(&mut s, Channel::Roughness));
|
||||
execute(&mut s, "effect.move", &json!({"effect": fill, "index": 99})).unwrap();
|
||||
assert_eq!(order(&s), [paint, fill]);
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
assert_eq!(order(&s), [fill, paint]);
|
||||
assert!(execute(&mut s, "effect.move", &json!({"effect": fill})).is_err(), "index is required");
|
||||
assert!(execute(&mut s, "effect.move", &json!({"effect": 999_999, "index": 0})).is_err());
|
||||
// A duplicate sits just above its original with the painted pixels, and takes the selection.
|
||||
execute(&mut s, "layer.select", &json!({"layer": layer, "target": paint})).unwrap();
|
||||
let copy = id(execute(&mut s, "effect.duplicate", &json!({"effect": paint})).unwrap(), "effect");
|
||||
assert_eq!(order(&s), [fill, paint, copy]);
|
||||
assert_eq!(s.target, StackTarget::Effect(LayerId(copy)));
|
||||
assert!(s.doc.project.effect(LayerId(copy)).unwrap().1.name.ends_with(" copy"));
|
||||
// Undoing it leaves no missing effect selected, but the stack it was in.
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
assert_eq!(s.target, StackTarget::Content);
|
||||
execute(&mut s, "edit.redo", &Value::Null).unwrap();
|
||||
execute(&mut s, "effect.remove", &json!({"effect": paint})).unwrap();
|
||||
assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "the copy keeps the strokes");
|
||||
assert!(execute(&mut s, "effect.duplicate", &json!({"effect": 999_999})).is_err());
|
||||
// Mask effects move within the mask.
|
||||
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
|
||||
let a = id(execute(&mut s, "effect.add.fill", &json!({"target": "mask", "value": 0.3})).unwrap(), "effect");
|
||||
let b = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect");
|
||||
execute(&mut s, "effect.move", &json!({"effect": b, "index": 0})).unwrap();
|
||||
let mask: Vec<u64> = s.doc.project.layer(LayerId(layer)).unwrap().mask.as_ref().unwrap().effects.iter().map(|e| e.id.0).collect();
|
||||
assert_eq!(mask, [b, a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effects_copy_and_paste_between_layers_and_stacks() {
|
||||
let mut s = session();
|
||||
let low = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3})).unwrap(), "layer");
|
||||
let paint = id(execute(&mut s, "effect.add.paint", &json!({"target": "content"})).unwrap(), "effect");
|
||||
execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.9})).unwrap();
|
||||
execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap();
|
||||
execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap();
|
||||
assert_eq!(execute(&mut s, "effect.copy", &Value::Null).unwrap(), json!({"copied": paint}), "the selected effect");
|
||||
assert!(execute(&mut s, "layer.paste", &Value::Null).is_err(), "the clipboard holds an effect, not a layer");
|
||||
// Onto the content of a fill above that covers the first: its strokes come along.
|
||||
let high = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3})).unwrap(), "layer");
|
||||
let pasted = id(execute(&mut s, "effect.paste", &Value::Null).unwrap(), "effect");
|
||||
assert_eq!(s.target, StackTarget::Effect(LayerId(pasted)));
|
||||
assert!(s.doc.pixels.layer(LayerId(pasted), Channel::Roughness).is_some());
|
||||
execute(&mut s, "effect.remove", &json!({"effect": paint})).unwrap();
|
||||
assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "{:?}", center(&mut s, Channel::Roughness));
|
||||
// Above the selected effect.
|
||||
let inv = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect");
|
||||
execute(&mut s, "effect.copy", &json!({"effect": inv})).unwrap();
|
||||
execute(&mut s, "layer.select", &json!({"layer": high, "target": pasted})).unwrap();
|
||||
let again = id(execute(&mut s, "effect.paste", &Value::Null).unwrap(), "effect");
|
||||
let order: Vec<u64> = s.doc.project.layer(LayerId(high)).unwrap().content_effects.iter().map(|e| e.id.0).collect();
|
||||
assert_eq!(order, [pasted, again, inv]);
|
||||
// A generator goes on a mask (made for it) even with the content selected; asking for the
|
||||
// content is an error. Cut removes the original.
|
||||
execute(&mut s, "layer.select", &json!({"layer": high})).unwrap();
|
||||
let generator = id(execute(&mut s, "effect.add.generator", &Value::Null).unwrap(), "effect");
|
||||
execute(&mut s, "effect.cut", &json!({"effect": generator})).unwrap();
|
||||
assert!(s.doc.project.effect(LayerId(generator)).is_none());
|
||||
execute(&mut s, "layer.select", &json!({"layer": low})).unwrap();
|
||||
assert!(execute(&mut s, "effect.paste", &json!({"target": "content"})).is_err());
|
||||
execute(&mut s, "effect.paste", &Value::Null).unwrap();
|
||||
let mask = &s.doc.project.layer(LayerId(low)).unwrap().mask;
|
||||
assert!(mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| matches!(e.kind, EffectKind::Generator(_)))));
|
||||
// A fill reading an anchor point needs one below its new layer.
|
||||
execute(&mut s, "layer.select", &json!({"layer": low})).unwrap();
|
||||
let anchor = id(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap(), "effect");
|
||||
execute(&mut s, "layer.select", &json!({"layer": high})).unwrap();
|
||||
let reader = id(execute(&mut s, "effect.add.fill", &json!({"target": "mask", "anchor": anchor})).unwrap(), "effect");
|
||||
execute(&mut s, "effect.copy", &json!({"effect": reader})).unwrap();
|
||||
execute(&mut s, "layer.select", &json!({"layer": low})).unwrap();
|
||||
assert!(execute(&mut s, "effect.paste", &Value::Null).is_err(), "the anchor is on the layer itself");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn histogram_counts_what_an_effect_reads() {
|
||||
let mut s = session();
|
||||
let hist = |s: &mut Session, p: Value| {
|
||||
let r = execute(s, "effect.histogram", &p).unwrap();
|
||||
let bins: Vec<u64> = r["bins"].as_array().unwrap().iter().map(|b| b.as_u64().unwrap()).collect();
|
||||
(r["target"].as_str().unwrap().to_string(), bins)
|
||||
};
|
||||
// Only the bucket holding the value is filled.
|
||||
let one = |bins: &[u64], k: usize| bins.iter().enumerate().all(|(i, b)| (*b > 0) == (i == k));
|
||||
execute(&mut s, "layer.add.fill", &json!({"color": [0.25, 0.25, 0.25], "roughness": 0.75})).unwrap();
|
||||
let lv = id(execute(&mut s, "effect.add.levels", &json!({"target": "content", "inLow": 0.5})).unwrap(), "effect");
|
||||
execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap();
|
||||
let (target, bins) = hist(&mut s, json!({"effect": lv, "channel": "roughness", "bins": 4}));
|
||||
assert_eq!(target, "content");
|
||||
assert!(one(&bins, 3), "roughness 0.75: {bins:?}");
|
||||
// The effect itself and those above it are left out; the default channel is the first.
|
||||
let (_, bins) = hist(&mut s, json!({"effect": lv, "bins": 4}));
|
||||
assert!(one(&bins, 1), "base color 0.25, components pooled: {bins:?}");
|
||||
assert_eq!(bins.iter().sum::<u64>() % 3, 0);
|
||||
// A mask's levels reads the mask below it.
|
||||
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
|
||||
execute(&mut s, "effect.add.fill", &json!({"target": "mask", "value": 0.3})).unwrap();
|
||||
let ml = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect");
|
||||
let (target, bins) = hist(&mut s, json!({"effect": ml, "bins": 4}));
|
||||
assert_eq!(target, "mask");
|
||||
assert!(one(&bins, 1), "mask 0.3: {bins:?}");
|
||||
assert_eq!(hist(&mut s, json!({"effect": ml})).1.len(), 64);
|
||||
// Below a blur, every tile builds its own neighbourhood field; the texels counted stay the same.
|
||||
let texels: u64 = bins.iter().sum();
|
||||
execute(&mut s, "effect.remove", &json!({"effect": ml})).unwrap();
|
||||
execute(&mut s, "effect.add.filter", &json!({"target": "mask", "filter": "blur", "radius": 4})).unwrap();
|
||||
let ml = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect");
|
||||
let (_, blurred) = hist(&mut s, json!({"effect": ml, "bins": 4}));
|
||||
assert_eq!(blurred.iter().sum::<u64>(), texels);
|
||||
assert_eq!(blurred.iter().enumerate().max_by_key(|(_, b)| **b).map(|(i, _)| i), Some(1), "{blurred:?}");
|
||||
// A paint layer with nothing painted yet still has its mask.
|
||||
execute(&mut s, "layer.add.paint", &Value::Null).unwrap();
|
||||
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
|
||||
execute(&mut s, "effect.add.fill", &json!({"target": "mask", "value": 0.6})).unwrap();
|
||||
let pl = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect");
|
||||
assert!(one(&hist(&mut s, json!({"effect": pl, "bins": 4})).1, 2), "an empty paint layer's mask");
|
||||
assert!(execute(&mut s, "effect.histogram", &json!({"effect": 999_999})).is_err());
|
||||
assert!(execute(&mut s, "effect.histogram", &json!({"effect": lv, "channel": "nope"})).is_err());
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//! `file.exportTextures` / `export.plan` with `colorSpace`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::texel::ColorSpace;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new_project("t", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap();
|
||||
execute(&mut s, "layer.add.fill", &json!({ "color": [0.8, 0.2, 0.1] })).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn export(s: &mut Session, tag: &str, extra: Value) -> (Value, std::path::PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("tc_export_cs_{tag}_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let mut p = json!({ "dir": dir.display().to_string(), "preset": "glTF PBR Metal Roughness", "format": "exr", "bitDepth": 32, "padding": "infinite" });
|
||||
for (k, v) in extra.as_object().unwrap() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
(execute(s, "file.exportTextures", &p).unwrap(), dir)
|
||||
}
|
||||
|
||||
fn first_pixel(path: &std::path::Path) -> [f32; 3] {
|
||||
let img = image::open(path).unwrap().to_rgb32f();
|
||||
// The plane's UV layout covers the whole image; read its middle.
|
||||
let px = img.get_pixel(img.width() / 2, img.height() / 2);
|
||||
[px[0], px[1], px[2]]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_maps_are_written_in_the_chosen_space() {
|
||||
let mut s = session();
|
||||
let (plain, dir_plain) = export(&mut s, "plain", json!({}));
|
||||
let (aces, dir_aces) = export(&mut s, "aces", json!({ "colorSpace": "ACEScg" }));
|
||||
let base =
|
||||
|r: &Value| std::path::PathBuf::from(r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).find(|f| f.contains("BaseColor")).unwrap());
|
||||
let (a, b) = (first_pixel(&base(&plain)), first_pixel(&base(&aces)));
|
||||
let want = ColorSpace::AcesCg.from_linear_rec709(a);
|
||||
assert!((0..3).all(|k| (b[k] - want[k]).abs() < 1e-3), "{b:?} vs {want:?}");
|
||||
assert!((0..3).any(|k| (a[k] - b[k]).abs() > 0.01), "the colour actually changed: {a:?} vs {b:?}");
|
||||
for d in [dir_plain, dir_aces] {
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_plan_reports_the_space_and_clamping_and_bad_names_are_errors() {
|
||||
let mut s = session();
|
||||
let plan = execute(&mut s, "export.plan", &json!({ "preset": "glTF PBR Metal Roughness", "colorSpace": "ACEScg" })).unwrap();
|
||||
assert!(plan.as_array().unwrap().iter().any(|f| f["warnings"].as_array().is_some_and(|w| !w.is_empty())), "8-bit ACEScg warns: {plan}");
|
||||
let float = execute(&mut s, "export.plan", &json!({ "preset": "glTF PBR Metal Roughness", "colorSpace": "ACEScg", "format": "exr" })).unwrap();
|
||||
assert!(float.as_array().unwrap().iter().all(|f| f["warnings"].as_array().is_some_and(Vec::is_empty)), "{float}");
|
||||
for bad in ["Display P3", "", "Rec.2020"] {
|
||||
assert!(execute(&mut s, "export.plan", &json!({ "preset": "glTF PBR Metal Roughness", "colorSpace": bad })).is_err(), "{bad:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
//! Painting while a filter is selected (it is selected right after the shelf adds it): the
|
||||
//! stroke paints what lies beneath the filter, so the new paint goes through it.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{Channel, EffectKind, LayerId};
|
||||
use texturecraft_engine::geom::glam::Vec2;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, StackTarget, execute};
|
||||
|
||||
const RES: f32 = 256.0;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap();
|
||||
s.viewport = Vec2::new(400.0, 400.0);
|
||||
s.camera.yaw = 0.0;
|
||||
s.camera.pitch = 0.0;
|
||||
s.update();
|
||||
s
|
||||
}
|
||||
|
||||
/// Base color of the composite under a viewport point.
|
||||
fn color_at(s: &mut Session, x: f32, y: f32) -> [f32; 3] {
|
||||
s.update();
|
||||
let hit = s.pick(Vec2::new(x, y), s.viewport).unwrap();
|
||||
s.caches[0].composite.value(Channel::BaseColor, (hit.uv.x * RES) as u32, (hit.uv.y * RES) as u32)
|
||||
}
|
||||
|
||||
fn brush(s: &mut Session, color: [f32; 3]) {
|
||||
execute(s, "tool.paint", &Value::Null).unwrap();
|
||||
execute(s, "tool.material", &json!({"channel": "baseColor", "color": color})).unwrap();
|
||||
execute(s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap();
|
||||
}
|
||||
|
||||
fn dab(s: &mut Session) -> Result<Value, String> {
|
||||
execute(s, "tool.stroke", &json!({"points": [[200, 200]]})).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn add_filter(s: &mut Session, filter: &str, target: &str) -> LayerId {
|
||||
execute(s, "effect.add.filter", &json!({"filter": filter, "target": target})).unwrap();
|
||||
let StackTarget::Effect(e) = s.target else { panic!("adding a filter selects it: {:?}", s.target) };
|
||||
e
|
||||
}
|
||||
|
||||
fn kinds(effects: &[texturecraft_engine::core::Effect]) -> Vec<&'static str> {
|
||||
effects.iter().map(|e| if matches!(e.kind, EffectKind::Paint) { "paint" } else { "other" }).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_content_filter_paints_its_paint_layer_through_it() {
|
||||
let mut s = session();
|
||||
let layer = s.selected_layer().unwrap();
|
||||
add_filter(&mut s, "invert", "content");
|
||||
brush(&mut s, [1.0, 0.0, 0.0]);
|
||||
dab(&mut s).expect("painting with the filter selected works");
|
||||
let v = color_at(&mut s, 200.0, 200.0);
|
||||
assert!(v[0] < 0.15 && v[1] > 0.85 && v[2] > 0.85, "red paint shows inverted (cyan): {v:?}");
|
||||
assert!(s.doc.pixels.layers.keys().any(|(id, _)| *id == layer), "the paint landed in the layer's own pixels");
|
||||
// One undo step removes the stroke and leaves the filter.
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
assert!(!s.doc.pixels.layers.iter().any(|((id, _), img)| *id == layer && img.allocated_count() > 0));
|
||||
assert_eq!(s.doc.project.layer(layer).unwrap().content_effects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_content_filter_paints_the_paint_effect_below_it() {
|
||||
let mut s = session();
|
||||
let layer = s.selected_layer().unwrap();
|
||||
execute(&mut s, "effect.add.paint", &json!({"target": "content"})).unwrap();
|
||||
let StackTarget::Effect(paint) = s.target else { panic!("{:?}", s.target) };
|
||||
add_filter(&mut s, "invert", "content");
|
||||
brush(&mut s, [1.0, 0.0, 0.0]);
|
||||
dab(&mut s).unwrap();
|
||||
assert!(s.doc.pixels.layers.iter().any(|((id, _), img)| *id == paint && img.allocated_count() > 0), "painted into the paint effect");
|
||||
assert!(!s.doc.pixels.layers.iter().any(|((id, _), img)| *id == layer && img.allocated_count() > 0), "not into the layer below it");
|
||||
let v = color_at(&mut s, 200.0, 200.0);
|
||||
assert!(v[0] < 0.15 && v[1] > 0.85, "through the filter: {v:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_filter_on_a_fill_layer_explains_why_it_cannot_paint() {
|
||||
let mut s = session();
|
||||
execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.4, 0.8]})).unwrap();
|
||||
add_filter(&mut s, "invert", "content");
|
||||
brush(&mut s, [1.0, 0.0, 0.0]);
|
||||
let e = dab(&mut s).unwrap_err();
|
||||
assert!(e.contains("fill layer"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_mask_filter_paints_a_mask_paint_effect_below_it() {
|
||||
let mut s = session();
|
||||
execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap();
|
||||
let layer = s.selected_layer().unwrap();
|
||||
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
|
||||
add_filter(&mut s, "invert", "mask");
|
||||
let mask = |s: &Session| s.doc.project.layer(layer).unwrap().mask.clone().unwrap().effects;
|
||||
assert_eq!(kinds(&mask(&s)), ["other"]);
|
||||
// Black mask, inverted: the red fill shows everywhere.
|
||||
assert!(color_at(&mut s, 200.0, 200.0)[0] > 0.85);
|
||||
brush(&mut s, [1.0, 1.0, 1.0]);
|
||||
s.tool.mask_value = 1.0;
|
||||
dab(&mut s).expect("painting the mask with its filter selected works");
|
||||
assert_eq!(kinds(&mask(&s)), ["paint", "other"], "a paint effect was inserted below the filter");
|
||||
// White paint goes through the invert: the fill disappears where it was painted only.
|
||||
let painted = color_at(&mut s, 200.0, 200.0);
|
||||
let elsewhere = color_at(&mut s, 120.0, 200.0);
|
||||
assert!(painted[0] < 0.6 && elsewhere[0] > 0.85, "painted {painted:?}, elsewhere {elsewhere:?}");
|
||||
// The next stroke reuses that paint effect.
|
||||
dab(&mut s).unwrap();
|
||||
assert_eq!(kinds(&mask(&s)), ["paint", "other"]);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! `file.exportTextures` with `materialX: true`: a `.mtlx` OpenPBR material next to the textures.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
const OPENPBR: &str = "OpenPBR (separate maps)";
|
||||
|
||||
/// A scratch folder that is removed when it goes out of scope, so a failing test leaves nothing behind.
|
||||
struct Scratch(std::path::PathBuf);
|
||||
|
||||
impl std::ops::Deref for Scratch {
|
||||
type Target = std::path::Path;
|
||||
fn deref(&self) -> &std::path::Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn temp(tag: &str) -> Scratch {
|
||||
let dir = std::env::temp_dir().join(format!("tc_mtlx_{tag}_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
Scratch(dir)
|
||||
}
|
||||
|
||||
fn export(s: &mut Session, dir: &std::path::Path, preset: &str, mtlx: bool) -> Value {
|
||||
execute(s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": preset, "materialX": mtlx})).unwrap()
|
||||
}
|
||||
|
||||
fn files(r: &Value) -> Vec<String> {
|
||||
r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_a_material_that_names_the_exported_textures() {
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
let dir = temp("ball");
|
||||
let r = export(&mut s, &dir, OPENPBR, true);
|
||||
let all = files(&r);
|
||||
let mtlx: Vec<&String> = all.iter().filter(|f| f.ends_with(".mtlx")).collect();
|
||||
assert_eq!(mtlx.len(), s.set_count(), "one material per texture set: {all:?}");
|
||||
for path in mtlx {
|
||||
let set = path.rsplit(['/', '\\']).next().unwrap().trim_end_matches(".mtlx").to_string();
|
||||
let text = std::fs::read_to_string(path).unwrap();
|
||||
assert!(text.contains("<open_pbr_surface") && text.contains("<surfacematerial"), "{text}");
|
||||
// Every texture the document points at was written beside it, and belongs to its set.
|
||||
let mut refs = 0;
|
||||
for part in text.split("name=\"file\" type=\"filename\" value=\"").skip(1) {
|
||||
let file = part.split('"').next().unwrap();
|
||||
assert!(dir.join(file).is_file(), "{file} is not in {all:?}");
|
||||
assert!(file.starts_with(&set), "{file} is not a texture of {set}");
|
||||
refs += 1;
|
||||
}
|
||||
assert!(refs >= 3, "base colour, roughness and normal at least: {text}");
|
||||
assert!(text.contains("name=\"base_color\"") && text.contains("name=\"geometry_normal\""), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_by_default_and_warns_without_openpbr_maps() {
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
let dir = temp("off");
|
||||
assert!(!files(&export(&mut s, &dir, OPENPBR, false)).iter().any(|f| f.ends_with(".mtlx")));
|
||||
let dir = temp("other");
|
||||
let r = export(&mut s, &dir, "Document channels + Normal + AO", true);
|
||||
assert!(!files(&r).iter().any(|f| f.ends_with(".mtlx")));
|
||||
assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("OpenPBR")), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_colour_maps_are_tagged_linear() {
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
let dir = temp("exr");
|
||||
let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": OPENPBR, "format": "exr", "materialX": true})).unwrap();
|
||||
let mtlx = files(&r).into_iter().find(|f| f.ends_with(".mtlx")).unwrap();
|
||||
let text = std::fs::read_to_string(mtlx).unwrap();
|
||||
assert!(text.contains("_base_color.exr\" colorspace=\"lin_rec709\"") && !text.contains("srgb_texture"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_maps_are_tagged_with_the_export_colour_space() {
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
for (space, tag, warns) in [("ACEScg", "acescg", false), ("ACES2065-1", "lin_ap0_scene", true), ("sRGB", "srgb_texture", false)] {
|
||||
let dir = temp(tag);
|
||||
let r = execute(
|
||||
&mut s,
|
||||
"file.exportTextures",
|
||||
&json!({"dir": dir.display().to_string(), "preset": OPENPBR, "format": "exr", "colorSpace": space, "materialX": true}),
|
||||
)
|
||||
.unwrap();
|
||||
let mtlx = files(&r).into_iter().find(|f| f.ends_with(".mtlx")).unwrap();
|
||||
let text = std::fs::read_to_string(mtlx).unwrap();
|
||||
assert!(text.contains(&format!("_base_color.exr\" colorspace=\"{tag}\"")), "{space}: {text}");
|
||||
let warned = r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("ACES2065-1"));
|
||||
assert_eq!(warned, warns, "{space}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sets_with_the_same_file_name_warn_instead_of_overwriting() {
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
assert!(s.set_count() >= 2);
|
||||
execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "a b"})).unwrap();
|
||||
execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "A_B"})).unwrap();
|
||||
let dir = temp("clash");
|
||||
let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": OPENPBR, "ts": "all", "materialX": true})).unwrap();
|
||||
assert_eq!(files(&r).iter().filter(|f| f.ends_with(".mtlx")).count(), s.set_count() - 1, "{r}");
|
||||
assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("\"A_B\"")), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn udim_sets_use_the_udim_token() {
|
||||
let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
|
||||
let dir = temp("udim");
|
||||
let r = export(&mut s, &dir, OPENPBR, true);
|
||||
let all = files(&r);
|
||||
let mtlx = all.iter().find(|f| f.ends_with(".mtlx")).unwrap_or_else(|| panic!("no .mtlx in {all:?}"));
|
||||
let text = std::fs::read_to_string(mtlx).unwrap();
|
||||
assert!(text.contains(".<UDIM>.png"), "{text}");
|
||||
assert!(!text.contains(".1001.") && !text.contains(".1002."), "{text}");
|
||||
assert!(all.iter().any(|f| f.ends_with(".1001.png")) && all.iter().any(|f| f.ends_with(".1002.png")));
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The filter library, geometry decals, cloning from the selected layer, placing saved smart
|
||||
//! materials, anchors inside a content stack and instances across texture set resolutions,
|
||||
//! through engine commands.
|
||||
//! materials, anchors inside a content stack, instances across texture set resolutions and mesh
|
||||
//! maps from images, through engine commands.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{Channel, EffectKind, Filter, LayerId, LayerKind, Projection};
|
||||
@@ -152,6 +152,19 @@ fn geometry_masks_limit_layers_to_mesh_parts() {
|
||||
assert!(texel(&mut s, 0.1, 0.9) && texel(&mut s, 0.6, 0.4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn solo_keeps_one_material_channel() {
|
||||
let mut s = session();
|
||||
let r = execute(&mut s, "tool.material", &json!({"channel": "roughness", "solo": true})).unwrap();
|
||||
assert_eq!(r["enabled"], json!(["roughness"]), "the brush paints roughness only");
|
||||
let fill = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer");
|
||||
assert!(s.doc.project.layer(fill).unwrap().channels.len() > 1);
|
||||
execute(&mut s, "layer.fill.set", &json!({"channel": "metallic", "solo": true})).unwrap();
|
||||
assert_eq!(s.doc.project.layer(fill).unwrap().channels.keys().copied().collect::<Vec<_>>(), [Channel::Metallic]);
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
assert!(s.doc.project.layer(fill).unwrap().channels.len() > 1, "one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decals_project_an_image_from_a_frame_placed_on_the_surface() {
|
||||
let mut s = session();
|
||||
@@ -188,6 +201,26 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() {
|
||||
assert!(!red(at(&mut s, Channel::BaseColor, 170.0, 180.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_decal_takes_its_up_from_the_params_or_a_rule_that_never_degenerates() {
|
||||
let mut s = session();
|
||||
let name = s.import_resource_bytes("logo.png", png(8, 4, |x, _| if x < 4 { [255, 0, 0, 255] } else { [0, 0, 255, 255] })).unwrap();
|
||||
let top = json!({"image": name, "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0]});
|
||||
let up = |r: &Value| [0, 1, 2].map(|i| r["decal"]["up"][i].as_f64().unwrap() as f32);
|
||||
let mut with_up = top.clone();
|
||||
with_up["up"] = json!([0.0, 0.0, -1.0]);
|
||||
assert_eq!(up(&execute(&mut s, "layer.add.decal", &with_up).unwrap()), [0.0, 0.0, -1.0]);
|
||||
with_up["up"] = json!([0.0, 2.0, 0.0]);
|
||||
assert!(execute(&mut s, "layer.add.decal", &with_up).is_err(), "an up along the normal is refused");
|
||||
// A level camera's up is the top face's normal: the decal's up is where the camera looks.
|
||||
execute(&mut s, "camera.set", &json!({"yaw": 90.0, "pitch": 0.0})).unwrap();
|
||||
let forward = s.camera.view().inverse().transform_vector3(texturecraft_engine::geom::glam::Vec3::NEG_Z);
|
||||
let u = up(&execute(&mut s, "layer.add.decal", &top).unwrap());
|
||||
assert!((texturecraft_engine::geom::glam::Vec3::from(u) - forward).length() < 1e-4, "{u:?} vs {forward}");
|
||||
let r = execute(&mut s, "layer.decal.set", &json!({"up": [1.0, 0.0, 0.0]})).unwrap();
|
||||
assert_eq!(up(&r), [1.0, 0.0, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clone_copies_the_selected_layer_alone_when_asked() {
|
||||
let mut s = session();
|
||||
@@ -342,3 +375,37 @@ fn geometry_mask_tool_toggles_the_clicked_part() {
|
||||
assert_eq!(s.doc.project.layer(layer).unwrap().geometry_mask, Some(vec!["Lid".to_string()]));
|
||||
assert!(execute(&mut s, "tool.click", &json!({"x": 1, "y": 1})).is_err(), "nothing under the point");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn images_fill_mesh_map_slots() {
|
||||
use texturecraft_engine::core::BakedMap;
|
||||
let mut s = session();
|
||||
// Dark on the left, light on the right.
|
||||
let ao = s.import_resource_bytes("ao.png", png(8, 8, |x, _| if x < 4 { [64, 64, 64, 255] } else { [192, 192, 192, 255] })).unwrap();
|
||||
let r = execute(&mut s, "textureSet.meshMap.set", &json!({"map": "ambient_occlusion", "image": ao})).unwrap();
|
||||
let res = s.doc.project.texture_sets[0].bake.resolution;
|
||||
assert_eq!(r, json!({"map": "ambient_occlusion", "resolution": res}));
|
||||
assert!(s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion));
|
||||
let sample = |s: &Session, m: BakedMap, x: u32| s.baked(0).unwrap().sample(m, x, 50, 100).unwrap();
|
||||
assert!((sample(&s, BakedMap::AmbientOcclusion, 10)[0] - 64.0 / 255.0).abs() < 1e-3, "raw file values, not linearized");
|
||||
assert!((sample(&s, BakedMap::AmbientOcclusion, 90)[0] - 192.0 / 255.0).abs() < 1e-3);
|
||||
// A normal map is read in the project's normal format (DirectX: green flipped).
|
||||
execute(&mut s, "textureSet.settings", &json!({"normalFormat": "directX"})).unwrap();
|
||||
let n = s.import_resource_bytes("n.png", png(2, 2, |_, _| [128, 64, 255, 255])).unwrap();
|
||||
execute(&mut s, "textureSet.meshMap.set", &json!({"map": "normal", "image": n})).unwrap();
|
||||
let v = sample(&s, BakedMap::Normal, 50);
|
||||
assert!((v[1] - (1.0 - 64.0 / 255.0)).abs() < 1e-3 && (v[2] - 1.0).abs() < 1e-3, "{v:?}");
|
||||
// Clearing empties the slot (one undo step); bad params are errors.
|
||||
execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambient_occlusion"})).unwrap();
|
||||
assert!(s.baked(0).unwrap().sample(BakedMap::AmbientOcclusion, 0, 0, 100).is_none());
|
||||
assert!(!s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion));
|
||||
assert!(execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambient_occlusion"})).is_err(), "already empty");
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
assert!(s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion));
|
||||
assert!(execute(&mut s, "textureSet.meshMap.set", &json!({"map": "nope", "image": ao})).is_err());
|
||||
assert!(execute(&mut s, "textureSet.meshMap.set", &json!({"map": "curvature", "image": "missing.png"})).is_err());
|
||||
assert!(execute(&mut s, "textureSet.meshMap.set", &json!({"map": "curvature"})).is_err());
|
||||
// The maps are saved with the project.
|
||||
let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
|
||||
assert_eq!(back.doc.baked, s.doc.baked);
|
||||
}
|
||||
@@ -69,6 +69,30 @@ fn layer_rename_and_undo() {
|
||||
assert_eq!(s.doc.project.layer(layer_id).unwrap().name, "Custom Paint");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_and_redo_jump_several_steps() {
|
||||
let mut s = session();
|
||||
let layer = s.selected_layer().unwrap();
|
||||
let name = |s: &Session| s.doc.project.layer(layer).unwrap().name.clone();
|
||||
let first = name(&s);
|
||||
for n in ["A", "B", "C"] {
|
||||
execute(&mut s, "layer.rename", &json!({"name": n})).unwrap();
|
||||
}
|
||||
let base = s.history_labels().len() - 3;
|
||||
// Two back to "A": the undone steps wait to be redone, next first.
|
||||
assert_eq!(execute(&mut s, "edit.undo", &json!({"steps": 2})).unwrap(), json!({"undone": "Rename layer", "steps": 2}));
|
||||
assert_eq!(name(&s), "A");
|
||||
assert_eq!(s.redo_labels().len(), 2);
|
||||
assert_eq!(execute(&mut s, "edit.history", &Value::Null).unwrap()["redo"].as_array().unwrap().len(), 2);
|
||||
// Forward past the end stops at "C"; back past the start stops at the first state.
|
||||
assert_eq!(execute(&mut s, "edit.redo", &json!({"steps": 99})).unwrap()["steps"], 2);
|
||||
assert_eq!(name(&s), "C");
|
||||
let r = execute(&mut s, "edit.undo", &json!({"steps": 1_000_000})).unwrap();
|
||||
assert_eq!(r["steps"].as_u64().unwrap() as usize, base + 3);
|
||||
assert_eq!(name(&s), first);
|
||||
assert!(execute(&mut s, "edit.undo", &json!({"steps": 2})).is_err(), "nothing left to undo");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polygon_fill_and_color_picker() {
|
||||
let mut s = session();
|
||||
@@ -165,6 +189,55 @@ fn image_resources_fill_layers_and_round_trip() {
|
||||
assert!(s.import_resource_bytes("bad.png", vec![1, 2, 3]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brush_presets_apply_save_and_load() {
|
||||
let mut s = session();
|
||||
let list = execute(&mut s, "brush.preset.list", &Value::Null).unwrap();
|
||||
assert!(list.as_array().unwrap().len() >= 12);
|
||||
execute(&mut s, "tool.brush", &json!({"size": 30})).unwrap();
|
||||
let b = execute(&mut s, "brush.preset.apply", &json!({"preset": "Scratches"})).unwrap();
|
||||
assert_eq!((b["alpha"]["library"].as_str(), b["followPath"].as_bool()), (Some("scratches"), Some(true)));
|
||||
assert!((b["size"].as_f64().unwrap() - 30.0).abs() < 1e-3, "presets keep the size");
|
||||
assert!(execute(&mut s, "tool.stroke", &json!({"points": [[160, 200], [240, 200]]})).unwrap()["stamps"].as_u64().unwrap() > 0);
|
||||
// Saved and loaded back onto another brush, the stroke returns and the size stays.
|
||||
let path = std::env::temp_dir().join(format!("tc-brush-{}.tcbrush", std::process::id()));
|
||||
let path = path.to_str().unwrap();
|
||||
execute(&mut s, "brush.preset.save", &json!({"path": path})).unwrap();
|
||||
execute(&mut s, "brush.preset.apply", &json!({"preset": "basic_soft"})).unwrap();
|
||||
execute(&mut s, "tool.brush", &json!({"size": 10})).unwrap();
|
||||
let b = execute(&mut s, "brush.preset.load", &json!({"path": path})).unwrap();
|
||||
assert_eq!(b["alpha"]["library"], "scratches");
|
||||
assert!((b["size"].as_f64().unwrap() - 10.0).abs() < 1e-3);
|
||||
std::fs::write(path, b"{}").unwrap();
|
||||
assert!(execute(&mut s, "brush.preset.load", &json!({"path": path})).is_err());
|
||||
let _ = std::fs::remove_file(path);
|
||||
for bad in [json!({}), json!({"preset": "nope"})] {
|
||||
assert!(execute(&mut s, "brush.preset.apply", &bad).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_becomes_a_brush_alpha_and_a_decal() {
|
||||
let mut s = session();
|
||||
let fonts = execute(&mut s, "text.fonts", &Value::Null).unwrap();
|
||||
assert_eq!(fonts["builtIn"][0], "Ubuntu Light");
|
||||
let r = execute(&mut s, "resource.text", &json!({"text": "TEXT\nCRAFT", "font": "ubuntu light", "size": 64})).unwrap();
|
||||
let name = r["name"].as_str().unwrap().to_string();
|
||||
assert_eq!(name, "Text_TEXT.png");
|
||||
assert!(r["width"].as_u64().unwrap() > r["height"].as_u64().unwrap() / 2, "two short lines");
|
||||
// White with the glyphs in alpha.
|
||||
let img = s.images[&name].clone();
|
||||
assert!(img.rgba.iter().any(|t| t[3] > 0.99) && img.rgba.iter().any(|t| t[3] == 0.0) && img.rgba.iter().all(|t| t[0] == 1.0));
|
||||
// As the brush alpha it paints (keeping its proportions), and it places as a decal.
|
||||
execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap();
|
||||
execute(&mut s, "tool.brush", &json!({"size": 40, "alpha": {"image": name}})).unwrap();
|
||||
assert!(execute(&mut s, "tool.click", &json!({"x": 200, "y": 200})).is_ok());
|
||||
assert!(execute(&mut s, "layer.add.decal", &json!({"image": name})).unwrap()["layer"].as_u64().is_some());
|
||||
for bad in [json!({}), json!({"text": " "}), json!({"text": "x", "font": "No Such Font"})] {
|
||||
assert!(execute(&mut s, "resource.text", &bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projection_tool_paints_the_stencil_colors() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -20,7 +20,7 @@ use serde::{Deserialize, Serialize};
|
||||
use texturecraft_compose::{BakedMaps, Composite};
|
||||
use texturecraft_core::{AoMixing, BakedMap, Channel, ChannelKind, NormalFormat, NormalMixing, Project, TextureSet};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_texel::{DilationMap, linear_to_srgb};
|
||||
use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb};
|
||||
|
||||
use crate::{FormatError, MAX_IMAGE_SIZE, Result};
|
||||
|
||||
@@ -41,7 +41,7 @@ pub const FILE_TOKENS: [(&str, &str); 6] = [
|
||||
("$textureSet", "Texture set name"),
|
||||
("$project", "Project name"),
|
||||
("$channel", "Channel or map id"),
|
||||
("$colorSpace", "sRGB or linear"),
|
||||
("$colorSpace", "Colour maps: sRGB, linear, ACEScg or ACES2065-1; data maps: linear"),
|
||||
("$udim", "UV tile number (1001 for sets without UV tiles)"),
|
||||
];
|
||||
|
||||
@@ -323,11 +323,31 @@ pub struct ExportOptions {
|
||||
/// UV-tiled sets: one image of the whole tile atlas per map instead of a file per tile
|
||||
/// (for formats without UDIM support, with the mesh's UVs in atlas space).
|
||||
pub atlas: bool,
|
||||
/// The colour space of the colour maps (data maps are never converted); None writes sRGB
|
||||
/// into 8/16-bit files and linear Rec.709 into float files (EXR, HDR).
|
||||
#[serde(skip)]
|
||||
pub color_space: Option<ColorSpace>,
|
||||
}
|
||||
|
||||
impl ExportOptions {
|
||||
/// The colour space colour maps are written in when `format` is used.
|
||||
pub fn space_for(&self, format: FileFormat) -> ColorSpace {
|
||||
self.color_space.unwrap_or(if format.is_float() { ColorSpace::LinearRec709 } else { ColorSpace::Srgb })
|
||||
}
|
||||
}
|
||||
|
||||
impl ExportOptions {
|
||||
pub fn new(preset: ExportPreset) -> ExportOptions {
|
||||
ExportOptions { preset, format_override: None, bit_depth_override: None, padding: Padding::Infinite, size: None, normal_format: None, atlas: false }
|
||||
ExportOptions {
|
||||
preset,
|
||||
format_override: None,
|
||||
bit_depth_override: None,
|
||||
padding: Padding::Infinite,
|
||||
size: None,
|
||||
normal_format: None,
|
||||
atlas: false,
|
||||
color_space: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -462,7 +482,14 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
|
||||
}
|
||||
let format = opts.format_override.unwrap_or(map.format);
|
||||
let bit_depth = format.depth(opts.bit_depth_override.unwrap_or(map.bit_depth));
|
||||
let color_space = if is_color(map) && !format.is_float() { "sRGB" } else { "linear" };
|
||||
let space = opts.space_for(format);
|
||||
let color_space = match (is_color(map), space) {
|
||||
(false, _) | (true, ColorSpace::LinearRec709) => "linear",
|
||||
(true, ColorSpace::Srgb) => "sRGB",
|
||||
(true, other) => other.name(),
|
||||
};
|
||||
// Integer files clamp to 0-1, which wide-gamut linear colour can leave.
|
||||
let clamps = is_color(map) && !format.is_float() && matches!(space, ColorSpace::AcesCg | ColorSpace::Aces2065);
|
||||
// One file per UV tile: names without `$udim` get it appended.
|
||||
let template = if tiles.iter().any(Option::is_some) && !map.file.contains("$udim") { format!("{}.$udim", map.file) } else { map.file.clone() };
|
||||
for &tile in &tiles {
|
||||
@@ -477,6 +504,13 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
|
||||
let ext = format.extension();
|
||||
let mut name = format!("{stem}.{ext}");
|
||||
let mut warnings = Vec::new();
|
||||
if clamps {
|
||||
warnings.push(format!(
|
||||
"{} colours outside 0-1 are clamped in {} files; use EXR or HDR to keep them",
|
||||
space.name(),
|
||||
format.extension().to_uppercase()
|
||||
));
|
||||
}
|
||||
// Case-insensitive: Windows and macOS file systems are.
|
||||
let mut k = 2;
|
||||
while used.contains(&name.to_ascii_lowercase()) {
|
||||
@@ -697,8 +731,23 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result<Vec<Expo
|
||||
let scale = |v: u32| (u64::from(v) * u64::from(opts.size.unwrap_or(tile_res)) / u64::from(tile_res)) as u32;
|
||||
let size = (scale(w), scale(h));
|
||||
let data = resize(data, (w, h), n, size);
|
||||
let srgb: Vec<bool> = lay.iter().map(|(d, _)| *d != Dest::A && is_color(map) && !p.format.is_float()).collect();
|
||||
// Colour maps leave linear Rec.709 for the chosen space. sRGB in integer files is
|
||||
// encoded by `encode`; every other case is converted here (float sRGB included).
|
||||
let space = opts.space_for(p.format);
|
||||
let rgb = lay.len() >= 3 && lay.iter().take(3).map(|(d, _)| *d).eq([Dest::R, Dest::G, Dest::B]);
|
||||
let mut data = data;
|
||||
let mut warnings = p.warnings;
|
||||
let convert = is_color(map) && (space != ColorSpace::Srgb || p.format.is_float()) && space != ColorSpace::LinearRec709;
|
||||
if convert && rgb {
|
||||
data.par_chunks_mut(n).for_each(|px| {
|
||||
if let [r, g, b, ..] = px {
|
||||
[*r, *g, *b] = space.from_linear_rec709([*r, *g, *b]);
|
||||
}
|
||||
});
|
||||
} else if convert {
|
||||
warnings.push(format!("\"{}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", p.name, space.name()));
|
||||
}
|
||||
let srgb: Vec<bool> = lay.iter().map(|(d, _)| *d != Dest::A && is_color(map) && !p.format.is_float() && space == ColorSpace::Srgb).collect();
|
||||
let bytes = encode(p.format, p.bit_depth, size, n, &data, &srgb, &mut warnings)?;
|
||||
Ok(ExportedFile { name: p.name, bytes, width: size.0, height: size.1, warnings })
|
||||
})
|
||||
|
||||
@@ -509,3 +509,91 @@ fn lobe_channels_export_as_document_maps_and_gltf_extension_maps() {
|
||||
let plain = Fx::new(&default_channels()).render_preset("glTF PBR Metal Roughness");
|
||||
assert!(!plain.iter().any(|f| f.name.contains("Clearcoat") || f.name.contains("Sheen")), "sets without the lobes export no extension maps");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_space_converts_colour_maps_only() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let preset = builtin_preset("glTF PBR Metal Roughness").unwrap();
|
||||
let want_at = |space: ColorSpace, x, y| space.from_linear_rec709(fx.comp.value(Channel::BaseColor, x, y));
|
||||
// ACEScg in a float EXR: the base colour is the converted triple, above-1 values aside.
|
||||
let mut exr = ExportOptions::new(preset.clone());
|
||||
exr.format_override = Some(FileFormat::Exr);
|
||||
exr.bit_depth_override = Some(32);
|
||||
exr.color_space = Some(ColorSpace::AcesCg);
|
||||
let files = fx.render(&exr);
|
||||
let img = decode(find(&files, "_BaseColor.exr")).to_rgb32f();
|
||||
for (x, y) in [(0, 0), (10, 40), (63, 63)] {
|
||||
let (px, want) = (img.get_pixel(x, y), want_at(ColorSpace::AcesCg, x, y));
|
||||
assert!((0..3).all(|k| (px[k] - want[k]).abs() < 1e-4), "({x},{y}) {px:?} vs {want:?}");
|
||||
}
|
||||
// Data maps are never converted: roughness and metalness (packed in the ORM map) are as before.
|
||||
let default_files =
|
||||
fx.render(&ExportOptions { format_override: Some(FileFormat::Exr), bit_depth_override: Some(32), ..ExportOptions::new(preset.clone()) });
|
||||
assert_eq!(find(&files, "OcclusionRoughnessMetallic").bytes, find(&default_files, "OcclusionRoughnessMetallic").bytes);
|
||||
assert_eq!(find(&files, "_Normal").bytes, find(&default_files, "_Normal").bytes);
|
||||
assert_ne!(find(&files, "_BaseColor").bytes, find(&default_files, "_BaseColor").bytes);
|
||||
|
||||
// Linear Rec.709 in an 8-bit PNG: the values are written without the sRGB curve.
|
||||
let mut lin = ExportOptions::new(preset.clone());
|
||||
lin.color_space = Some(ColorSpace::LinearRec709);
|
||||
let png = decode(find(&fx.render(&lin), "_BaseColor.png"));
|
||||
let v = fx.comp.value(Channel::BaseColor, 10, 40);
|
||||
for k in 0..3 {
|
||||
assert!((png.get_pixel(10, 40)[k] as f32 - v[k] * 255.0).abs() <= 1.0, "[{k}]");
|
||||
}
|
||||
// The default is unchanged: sRGB for integer files (None and explicit sRGB agree).
|
||||
let default_png = fx.render(&ExportOptions::new(preset.clone()));
|
||||
let mut srgb = ExportOptions::new(preset.clone());
|
||||
srgb.color_space = Some(ColorSpace::Srgb);
|
||||
assert_eq!(find(&default_png, "_BaseColor.png").bytes, find(&fx.render(&srgb), "_BaseColor.png").bytes);
|
||||
// An explicit sRGB in a float file is encoded once, not twice.
|
||||
let mut float_srgb = ExportOptions::new(preset);
|
||||
float_srgb.format_override = Some(FileFormat::Exr);
|
||||
float_srgb.bit_depth_override = Some(32);
|
||||
float_srgb.color_space = Some(ColorSpace::Srgb);
|
||||
let px = *decode(find(&fx.render(&float_srgb), "_BaseColor.exr")).to_rgb32f().get_pixel(10, 40);
|
||||
assert!((px[0] - linear_to_srgb(v[0])).abs() < 1e-4, "{px:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_space_names_the_files_and_warns_when_integer_files_clamp() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let named = ExportPreset {
|
||||
name: "named".into(),
|
||||
maps: vec![MapSpec {
|
||||
file: "$textureSet_$channel_$colorSpace".into(),
|
||||
format: FileFormat::Png,
|
||||
bit_depth: 8,
|
||||
channels: vec![
|
||||
(Dest::R, SourceRef::Channel { channel: Channel::BaseColor, component: 0 }),
|
||||
(Dest::G, SourceRef::Channel { channel: Channel::BaseColor, component: 1 }),
|
||||
(Dest::B, SourceRef::Channel { channel: Channel::BaseColor, component: 2 }),
|
||||
],
|
||||
}],
|
||||
};
|
||||
let plan = |space: Option<ColorSpace>, format: Option<FileFormat>| {
|
||||
let opts = ExportOptions { color_space: space, format_override: format, ..ExportOptions::new(named.clone()) };
|
||||
list_outputs(&fx.project, 0, "sphere", &opts).unwrap().remove(0)
|
||||
};
|
||||
assert!(plan(None, None).name.ends_with("_sRGB.png") && plan(None, Some(FileFormat::Exr)).name.ends_with("_linear.exr"), "defaults keep their names");
|
||||
assert!(plan(Some(ColorSpace::LinearRec709), None).name.ends_with("_linear.png"));
|
||||
let aces = plan(Some(ColorSpace::AcesCg), None);
|
||||
assert!(aces.name.ends_with("_ACEScg.png"), "{}", aces.name);
|
||||
assert!(aces.warnings.iter().any(|w| w.contains("clamped")), "{:?}", aces.warnings);
|
||||
assert!(plan(Some(ColorSpace::AcesCg), Some(FileFormat::Exr)).warnings.is_empty(), "float files keep the values");
|
||||
assert!(plan(None, None).warnings.is_empty() && plan(Some(ColorSpace::LinearRec709), None).warnings.is_empty());
|
||||
// The planned names are the rendered names.
|
||||
let opts = ExportOptions { color_space: Some(ColorSpace::Aces2065), ..ExportOptions::new(named) };
|
||||
let names: Vec<String> = fx.render(&opts).into_iter().map(|f| f.name).collect();
|
||||
assert_eq!(names, list_outputs(&fx.project, 0, "sphere", &opts).unwrap().into_iter().map(|p| p.name).collect::<Vec<_>>());
|
||||
assert!(names[0].ends_with("_ACES2065-1.png"), "{names:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_packed_into_one_channel_warns_instead_of_converting_silently() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let preset = ExportPreset { name: "l".into(), maps: vec![gray_map("$textureSet_red", SourceRef::Channel { channel: Channel::BaseColor, component: 0 })] };
|
||||
let opts = |space| ExportOptions { color_space: space, format_override: Some(FileFormat::Exr), ..ExportOptions::new(preset.clone()) };
|
||||
assert!(fx.render(&opts(Some(ColorSpace::AcesCg)))[0].warnings.iter().any(|w| w.contains("ACEScg")));
|
||||
assert!(fx.render(&opts(None))[0].warnings.is_empty(), "linear Rec.709 needs no conversion");
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
//! Installed fonts, for text alphas: the faces (family and style) of every TrueType or OpenType
|
||||
//! file (and collection) in the system's font folders, read from each file's `name` table only,
|
||||
//! so listing hundreds of fonts stays quick. Native only; the browser has no font folders.
|
||||
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// One face of an installed font file.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct FontFace {
|
||||
pub family: String,
|
||||
pub style: String,
|
||||
pub path: PathBuf,
|
||||
/// Face index in a collection (`.ttc`), else 0.
|
||||
pub index: u32,
|
||||
}
|
||||
|
||||
/// Files and faces visited at most (a font folder is never this large, a wrong one may be).
|
||||
const MAX_FILES: usize = 20_000;
|
||||
const MAX_FACES_PER_FILE: u32 = 64;
|
||||
const MAX_NAME_TABLE: u32 = 1 << 20;
|
||||
|
||||
/// The installed fonts' faces, sorted by family then style.
|
||||
pub fn system_fonts() -> Vec<FontFace> {
|
||||
let mut files = Vec::new();
|
||||
for dir in font_dirs() {
|
||||
collect(&dir, 0, &mut files);
|
||||
}
|
||||
let mut faces: Vec<FontFace> = files.iter().flat_map(|p| faces_of(p).unwrap_or_default()).collect();
|
||||
faces.sort();
|
||||
faces.dedup_by(|a, b| a.family == b.family && a.style == b.style);
|
||||
faces
|
||||
}
|
||||
|
||||
fn font_dirs() -> Vec<PathBuf> {
|
||||
let home = std::env::var_os("HOME").map(PathBuf::from);
|
||||
if cfg!(windows) {
|
||||
let mut v = vec![PathBuf::from(std::env::var_os("WINDIR").unwrap_or_else(|| "C:\\Windows".into())).join("Fonts")];
|
||||
v.extend(std::env::var_os("LOCALAPPDATA").map(|d| PathBuf::from(d).join("Microsoft\\Windows\\Fonts")));
|
||||
v
|
||||
} else if cfg!(target_os = "macos") {
|
||||
let mut v = vec![PathBuf::from("/System/Library/Fonts"), PathBuf::from("/Library/Fonts")];
|
||||
v.extend(home.map(|h| h.join("Library/Fonts")));
|
||||
v
|
||||
} else {
|
||||
let mut v = vec![PathBuf::from("/usr/share/fonts"), PathBuf::from("/usr/local/share/fonts")];
|
||||
v.extend(home.iter().flat_map(|h| [h.join(".local/share/fonts"), h.join(".fonts")]));
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
/// Font files under `dir` (a few levels deep).
|
||||
fn collect(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
for e in entries.flatten() {
|
||||
if out.len() >= MAX_FILES {
|
||||
return;
|
||||
}
|
||||
let path = e.path();
|
||||
match e.file_type() {
|
||||
Ok(t) if t.is_dir() && depth < 4 => collect(&path, depth + 1, out),
|
||||
Ok(t) if t.is_file() => {
|
||||
let ext = path.extension().and_then(|x| x.to_str()).unwrap_or_default().to_ascii_lowercase();
|
||||
if matches!(ext.as_str(), "ttf" | "otf" | "ttc" | "otc") {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The faces of the font file at `path` (each face of a collection).
|
||||
pub fn faces_of(path: &Path) -> std::io::Result<Vec<FontFace>> {
|
||||
let mut f = std::fs::File::open(path)?;
|
||||
let mut at = |offset: u64, len: usize| -> std::io::Result<Vec<u8>> {
|
||||
f.seek(SeekFrom::Start(offset))?;
|
||||
let mut buf = vec![0; len];
|
||||
f.read_exact(&mut buf)?;
|
||||
Ok(buf)
|
||||
};
|
||||
let head = at(0, 12)?;
|
||||
let offsets: Vec<u64> = if head.get(..4) == Some(b"ttcf") {
|
||||
let n = u32_at(&head, 8).unwrap_or(0).min(MAX_FACES_PER_FILE);
|
||||
let table = at(12, 4 * n as usize)?;
|
||||
(0..n as usize).filter_map(|i| u32_at(&table, 4 * i)).map(u64::from).collect()
|
||||
} else {
|
||||
vec![0]
|
||||
};
|
||||
let mut faces = Vec::new();
|
||||
for (index, offset) in offsets.into_iter().enumerate() {
|
||||
let dir = at(offset, 12)?;
|
||||
let tables = at(offset + 12, 16 * usize::from(u16_at(&dir, 4).unwrap_or(0)))?;
|
||||
let Some(rec) = tables.chunks_exact(16).find(|r| r.get(..4) == Some(b"name")) else { continue };
|
||||
let (Some(off), Some(len)) = (u32_at(rec, 8), u32_at(rec, 12)) else { continue };
|
||||
let names = at(u64::from(off), len.min(MAX_NAME_TABLE) as usize)?;
|
||||
let name = |ids: [u16; 2]| ids.iter().find_map(|id| name_string(&names, *id));
|
||||
if let Some(family) = name([16, 1]) {
|
||||
let style = name([17, 2]).unwrap_or_else(|| "Regular".into());
|
||||
faces.push(FontFace { family, style, path: path.to_path_buf(), index: index as u32 });
|
||||
}
|
||||
}
|
||||
Ok(faces)
|
||||
}
|
||||
|
||||
fn u16_at(b: &[u8], o: usize) -> Option<u16> {
|
||||
Some(u16::from_be_bytes(b.get(o..o.checked_add(2)?)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
fn u32_at(b: &[u8], o: usize) -> Option<u32> {
|
||||
Some(u32::from_be_bytes(b.get(o..o.checked_add(4)?)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
/// Name `id` of a `name` table, in English when it has several languages: Windows and Unicode
|
||||
/// records are UTF-16BE, Macintosh ones single-byte (read as Latin-1).
|
||||
fn name_string(t: &[u8], id: u16) -> Option<String> {
|
||||
let (count, base) = (usize::from(u16_at(t, 2)?), usize::from(u16_at(t, 4)?));
|
||||
let mut best: Option<(u8, String)> = None;
|
||||
for r in (0..count).filter_map(|i| t.get(6 + 12 * i..18 + 12 * i)) {
|
||||
let (platform, language, name_id) = (u16_at(r, 0)?, u16_at(r, 4)?, u16_at(r, 6)?);
|
||||
let (len, off) = (usize::from(u16_at(r, 8)?), usize::from(u16_at(r, 10)?));
|
||||
let Some(bytes) = t.get(base + off..base + off + len) else { continue };
|
||||
if name_id != id {
|
||||
continue;
|
||||
}
|
||||
let (rank, s) = match platform {
|
||||
3 | 0 => {
|
||||
let s = String::from_utf16_lossy(&bytes.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect::<Vec<_>>());
|
||||
(if language == 0x409 { 0 } else { 1 }, s)
|
||||
}
|
||||
1 => (if language == 0 { 2 } else { 3 }, bytes.iter().map(|b| char::from(*b)).collect()),
|
||||
_ => continue,
|
||||
};
|
||||
let s = s.trim().to_string();
|
||||
if !s.is_empty() && best.as_ref().is_none_or(|(r, _)| rank < *r) {
|
||||
best = Some((rank, s));
|
||||
}
|
||||
}
|
||||
best.map(|(_, s)| s)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A `name` table with the given (platform, language, name id, bytes) records.
|
||||
fn name_table(records: &[(u16, u16, u16, Vec<u8>)]) -> Vec<u8> {
|
||||
let base = 6 + 12 * records.len();
|
||||
let mut t: Vec<u8> = [0u16, records.len() as u16, base as u16].iter().flat_map(|v| v.to_be_bytes()).collect();
|
||||
let mut strings: Vec<u8> = Vec::new();
|
||||
for (platform, language, id, bytes) in records {
|
||||
for v in [*platform, 1, *language, *id, bytes.len() as u16, strings.len() as u16] {
|
||||
t.extend(v.to_be_bytes());
|
||||
}
|
||||
strings.extend(bytes);
|
||||
}
|
||||
t.extend(strings);
|
||||
t
|
||||
}
|
||||
|
||||
fn utf16(s: &str) -> Vec<u8> {
|
||||
s.encode_utf16().flat_map(u16::to_be_bytes).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_prefer_english_windows_records() {
|
||||
let t =
|
||||
name_table(&[(1, 0, 1, b"Mac Name".to_vec()), (3, 0x407, 1, utf16("Deutsch")), (3, 0x409, 1, utf16("Plain Sans")), (3, 0x409, 2, utf16("Bold"))]);
|
||||
assert_eq!(name_string(&t, 1).as_deref(), Some("Plain Sans"));
|
||||
assert_eq!(name_string(&t, 2).as_deref(), Some("Bold"));
|
||||
assert_eq!(name_string(&t, 16), None);
|
||||
// Truncated or hostile tables give nothing rather than panicking.
|
||||
for n in 0..t.len() {
|
||||
let _ = name_string(&t[..n], 1);
|
||||
}
|
||||
assert_eq!(name_string(&[0xff; 64], 1), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn faces_of_a_file_and_garbage() {
|
||||
let dir = std::env::temp_dir().join(format!("tc-fonts-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("font.ttf");
|
||||
// A font file with only a name table: offset table, one table record, the table.
|
||||
let names = name_table(&[(3, 0x409, 1, utf16("Plain Sans")), (3, 0x409, 2, utf16("Italic"))]);
|
||||
let mut file: Vec<u8> = [0x0001_0000u32.to_be_bytes().to_vec(), 1u16.to_be_bytes().to_vec(), vec![0; 6]].concat();
|
||||
file.extend(b"name");
|
||||
file.extend([0u32, 28, names.len() as u32].iter().flat_map(|v| v.to_be_bytes()));
|
||||
file.extend(&names);
|
||||
std::fs::write(&path, &file).unwrap();
|
||||
let faces = faces_of(&path).unwrap();
|
||||
assert_eq!((faces[0].family.as_str(), faces[0].style.as_str(), faces[0].index), ("Plain Sans", "Italic", 0));
|
||||
std::fs::write(&path, b"garbage").unwrap();
|
||||
assert!(faces_of(&path).is_err() || faces_of(&path).unwrap().is_empty());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,17 @@ pub fn decode_image(bytes: &[u8]) -> Result<DecodedImage> {
|
||||
Ok(DecodedImage { width, height, rgba, srgb })
|
||||
}
|
||||
|
||||
/// PNG bytes of an `rgb` (sRGB) image whose alpha is `coverage` (`width × height`, top row first):
|
||||
/// drawn text as an image resource.
|
||||
pub fn coverage_png(width: u32, height: u32, coverage: &[u8], rgb: [u8; 3]) -> Result<Vec<u8>> {
|
||||
let rgba: Vec<u8> = coverage.iter().flat_map(|a| [rgb[0], rgb[1], rgb[2], *a]).collect();
|
||||
let img = image::RgbaImage::from_raw(width, height, rgba)
|
||||
.ok_or_else(|| FormatError::Invalid(format!("{} coverage values for {width}x{height}", coverage.len())))?;
|
||||
let mut png = Vec::new();
|
||||
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| FormatError::Invalid(e.to_string()))?;
|
||||
Ok(png)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -44,5 +55,8 @@ mod tests {
|
||||
assert!((d.rgba[1][0] - 60.0 / 255.0).abs() < 1e-3);
|
||||
assert!(decode_image(b"not an image").is_err());
|
||||
assert!(decode_image(&png[..png.len() / 2]).is_err());
|
||||
let text = decode_image(&coverage_png(2, 1, &[0, 255], [255; 3]).unwrap()).unwrap();
|
||||
assert_eq!(text.rgba, vec![[1.0, 1.0, 1.0, 0.0], [1.0; 4]]);
|
||||
assert!(coverage_png(2, 2, &[0], [255; 3]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -12,9 +12,11 @@
|
||||
//! - [`export`]: texture export from a texture set's composite through [`ExportPreset`]s (file
|
||||
//! name templates, channel packing, virtual maps such as the final normal, padding, resizing)
|
||||
//! to PNG, JPEG, TGA, TIFF, BMP, WebP, EXR and HDR bytes.
|
||||
//! - [`materialx`]: a MaterialX (`.mtlx`) OpenPBR document for an exported texture set.
|
||||
//! - [`presets`]: the built-in export presets and JSON (de)serialization of user presets.
|
||||
//! - [`project_file`]: the `.tcraft` project zip (project JSON, sparse lossless pixel tiles,
|
||||
//! baked maps, the original mesh and a thumbnail).
|
||||
//! - `fonts`: the installed fonts' families and styles (native only), for text alphas.
|
||||
//!
|
||||
//! Every reader takes untrusted bytes and returns an error, never panics. Byte-based functions
|
||||
//! work everywhere (including the web build); path-based ones are native only.
|
||||
@@ -22,7 +24,10 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod export;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod fonts;
|
||||
pub mod image_res;
|
||||
pub mod materialx;
|
||||
pub mod mesh_export;
|
||||
pub mod mesh_import;
|
||||
pub mod presets;
|
||||
@@ -31,7 +36,7 @@ pub mod project_file;
|
||||
pub use export::{
|
||||
Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapSpec, Padding, PlannedFile, SourceRef, VirtualMap, list_outputs, render_maps,
|
||||
};
|
||||
pub use image_res::{DecodedImage, decode_image};
|
||||
pub use image_res::{DecodedImage, coverage_png, decode_image};
|
||||
pub use mesh_export::{GlbTextures, UsdExport, UsdFormat, glb_bytes, glb_export_options, obj_bytes, usd_bytes, usd_export_options};
|
||||
pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_high_poly_bytes, import_mesh_bytes, mesh_report, self_contained_mesh};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
//! MaterialX documents for exported texture sets, written from the ASWF MaterialX specification
|
||||
//! (version 1.39) and the OpenPBR Surface specification. Pure Rust: no MaterialX library is
|
||||
//! linked, and nothing is read from any other application.
|
||||
//!
|
||||
//! [`write`] takes a material's name and the texture files an export produced, each tagged with
|
||||
//! the OpenPBR input it feeds, and gives the text of a `.mtlx` file: an `open_pbr_surface` shader
|
||||
//! whose inputs read `tiledimage` nodes, wrapped in a `surfacematerial`. The inputs are the ones
|
||||
//! the built-in "OpenPBR (separate maps)" export preset writes ([`INPUTS`]); `height` becomes a
|
||||
//! `displacement` shader on the material and `geometry_normal` goes through a `normalmap` node
|
||||
//! (OpenGL, +Y up, which is what that node expects).
|
||||
//!
|
||||
//! Colour textures (base, fuzz and emission colour) are tagged with the colour space they were
|
||||
//! exported in ([`colorspace_name`]); every data map is left untagged (linear). UDIM sets write the `<UDIM>` filename token MaterialX defines.
|
||||
//! Texture file names are relative to the document.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use texturecraft_texel::ColorSpace;
|
||||
|
||||
/// How an OpenPBR input is typed in the document.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
/// `color3` from an sRGB texture.
|
||||
Color,
|
||||
/// `float` from a linear texture.
|
||||
Float,
|
||||
/// `vector3` through a `normalmap` node.
|
||||
Normal,
|
||||
/// `float` driving a `displacement` shader.
|
||||
Height,
|
||||
}
|
||||
|
||||
/// The OpenPBR inputs the export writes, in document order. Names are the file-name suffixes of
|
||||
/// the built-in OpenPBR preset's maps (`$mesh_$textureSet_<input>`).
|
||||
pub const INPUTS: &[(&str, Kind)] = &[
|
||||
("base_color", Kind::Color),
|
||||
("base_metalness", Kind::Float),
|
||||
("specular_roughness", Kind::Float),
|
||||
("specular_roughness_anisotropy", Kind::Float),
|
||||
("coat_weight", Kind::Float),
|
||||
("coat_roughness", Kind::Float),
|
||||
("fuzz_weight", Kind::Float),
|
||||
("fuzz_color", Kind::Color),
|
||||
("fuzz_roughness", Kind::Float),
|
||||
("transmission_weight", Kind::Float),
|
||||
("subsurface_weight", Kind::Float),
|
||||
("emission_color", Kind::Color),
|
||||
("geometry_opacity", Kind::Float),
|
||||
("geometry_normal", Kind::Normal),
|
||||
("height", Kind::Height),
|
||||
];
|
||||
|
||||
/// The file-name prefix of the built-in OpenPBR preset's maps.
|
||||
const PREFIX: &str = "$mesh_$textureSet_";
|
||||
|
||||
/// One exported texture: the OpenPBR input it feeds and the file (relative to the `.mtlx`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Texture {
|
||||
pub input: String,
|
||||
pub file: String,
|
||||
/// The MaterialX colour space of the file's values (`srgb_texture`, `lin_rec709`, ...);
|
||||
/// used for colour inputs only, data maps are always linear.
|
||||
pub colorspace: &'static str,
|
||||
}
|
||||
|
||||
/// The MaterialX colour space of colour maps written in `space`. MaterialX 1.39 defines no
|
||||
/// ACES2065-1 (AP0) space: it gets `lin_ap0_scene`, its name in later versions of the
|
||||
/// specification, which 1.39 readers may not know.
|
||||
pub fn colorspace_name(space: ColorSpace) -> &'static str {
|
||||
match space {
|
||||
ColorSpace::Srgb => "srgb_texture",
|
||||
ColorSpace::LinearRec709 => "lin_rec709",
|
||||
ColorSpace::AcesCg => "acescg",
|
||||
ColorSpace::Aces2065 => "lin_ap0_scene",
|
||||
}
|
||||
}
|
||||
|
||||
/// The OpenPBR input a preset map's file template feeds (`$mesh_$textureSet_base_color` →
|
||||
/// `base_color`), or None for templates this module has no place for.
|
||||
pub fn input_of_template(template: &str) -> Option<&'static str> {
|
||||
let suffix = template.strip_prefix(PREFIX)?;
|
||||
INPUTS.iter().find(|(n, _)| *n == suffix).map(|(n, _)| *n)
|
||||
}
|
||||
|
||||
fn kind_of(input: &str) -> Option<Kind> {
|
||||
INPUTS.iter().find(|(n, _)| *n == input).map(|(_, k)| *k)
|
||||
}
|
||||
|
||||
/// A MaterialX name: letters, digits and underscores, not starting with a digit.
|
||||
pub fn node_name(s: &str) -> String {
|
||||
let mut out: String = s.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect();
|
||||
if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) {
|
||||
out.insert(0, '_');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn esc(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
c if c.is_control() => out.push(' '),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn image_name(input: &str) -> String {
|
||||
format!("image_{}", node_name(input))
|
||||
}
|
||||
|
||||
/// The text of a MaterialX document for `name` with the given textures. `physical_size_cm` goes
|
||||
/// into the material's `doc` attribute. Inputs this module has no place for are skipped, and so
|
||||
/// are repeats of one input (the first wins).
|
||||
pub fn write(name: &str, textures: &[Texture], physical_size_cm: Option<[f32; 2]>) -> String {
|
||||
let base = node_name(name);
|
||||
let mut seen = HashSet::new();
|
||||
let tex: Vec<(&Texture, Kind)> = textures.iter().filter_map(|t| kind_of(&t.input).map(|k| (t, k))).filter(|(t, _)| seen.insert(t.input.as_str())).collect();
|
||||
let has = |i: &str| tex.iter().any(|(t, _)| t.input == i);
|
||||
let mut x = String::new();
|
||||
let _ = writeln!(x, "<?xml version=\"1.0\"?>");
|
||||
let _ = writeln!(x, "<materialx version=\"1.39\" colorspace=\"lin_rec709\">");
|
||||
|
||||
let shader = format!("OPBR_{base}");
|
||||
let _ = writeln!(x, " <open_pbr_surface name=\"{}\" type=\"surfaceshader\">", esc(&shader));
|
||||
for (t, kind) in &tex {
|
||||
let (ty, node) = match kind {
|
||||
Kind::Color => ("color3", image_name(&t.input)),
|
||||
Kind::Float => ("float", image_name(&t.input)),
|
||||
Kind::Normal => ("vector3", "normalmap".to_owned()),
|
||||
Kind::Height => continue,
|
||||
};
|
||||
let _ = writeln!(x, " <input name=\"{}\" type=\"{ty}\" nodename=\"{node}\" />", t.input);
|
||||
}
|
||||
if has("emission_color") {
|
||||
let _ = writeln!(x, " <input name=\"emission_luminance\" type=\"float\" value=\"1\" />");
|
||||
}
|
||||
let _ = writeln!(x, " </open_pbr_surface>");
|
||||
|
||||
for (t, kind) in &tex {
|
||||
let (ty, space) = match kind {
|
||||
Kind::Color => ("color3", Some(t.colorspace)),
|
||||
Kind::Normal => ("vector3", None),
|
||||
Kind::Float | Kind::Height => ("float", None),
|
||||
};
|
||||
let node = image_name(&t.input);
|
||||
let _ = writeln!(x, " <tiledimage name=\"{node}\" type=\"{ty}\">");
|
||||
match space {
|
||||
Some(space) => {
|
||||
let _ = writeln!(x, " <input name=\"file\" type=\"filename\" value=\"{}\" colorspace=\"{space}\" />", esc(&t.file));
|
||||
}
|
||||
None => {
|
||||
let _ = writeln!(x, " <input name=\"file\" type=\"filename\" value=\"{}\" />", esc(&t.file));
|
||||
}
|
||||
}
|
||||
let _ = writeln!(x, " </tiledimage>");
|
||||
}
|
||||
if has("geometry_normal") {
|
||||
let _ = writeln!(x, " <normalmap name=\"normalmap\" type=\"vector3\">");
|
||||
let _ = writeln!(x, " <input name=\"in\" type=\"vector3\" nodename=\"{}\" />", image_name("geometry_normal"));
|
||||
let _ = writeln!(x, " </normalmap>");
|
||||
}
|
||||
if has("height") {
|
||||
let _ = writeln!(x, " <displacement name=\"DISP_{base}\" type=\"displacementshader\">");
|
||||
let _ = writeln!(x, " <input name=\"displacement\" type=\"float\" nodename=\"{}\" />", image_name("height"));
|
||||
let _ = writeln!(x, " <input name=\"scale\" type=\"float\" value=\"1\" />");
|
||||
let _ = writeln!(x, " </displacement>");
|
||||
}
|
||||
|
||||
let doc = match physical_size_cm {
|
||||
Some([w, h]) if w.is_finite() && h.is_finite() => format!(" doc=\"Tiles every {w} x {h} cm\""),
|
||||
_ => String::new(),
|
||||
};
|
||||
let _ = writeln!(x, " <surfacematerial name=\"{}\" type=\"material\"{doc}>", esc(&base));
|
||||
let _ = writeln!(x, " <input name=\"surfaceshader\" type=\"surfaceshader\" nodename=\"{}\" />", esc(&shader));
|
||||
if has("height") {
|
||||
let _ = writeln!(x, " <input name=\"displacementshader\" type=\"displacementshader\" nodename=\"DISP_{base}\" />");
|
||||
}
|
||||
let _ = writeln!(x, " </surfacematerial>");
|
||||
let _ = writeln!(x, "</materialx>");
|
||||
x
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tex(input: &str, file: &str) -> Texture {
|
||||
Texture { input: input.into(), file: file.into(), colorspace: "srgb_texture" }
|
||||
}
|
||||
|
||||
/// Every start tag is closed or self-closed, in order: enough to catch a malformed writer.
|
||||
fn balanced(xml: &str) -> bool {
|
||||
let mut stack: Vec<String> = Vec::new();
|
||||
let mut rest = xml;
|
||||
while let Some(i) = rest.find('<') {
|
||||
let Some(j) = rest.get(i..).and_then(|r| r.find('>')) else { return false };
|
||||
let Some(tag) = rest.get(i + 1..i + j) else { return false };
|
||||
rest = rest.get(i + j + 1..).unwrap_or("");
|
||||
if tag.starts_with('?') || tag.starts_with('!') {
|
||||
continue;
|
||||
}
|
||||
if let Some(name) = tag.strip_prefix('/') {
|
||||
if stack.pop().as_deref() != Some(name.trim()) {
|
||||
return false;
|
||||
}
|
||||
} else if !tag.ends_with('/') {
|
||||
stack.push(tag.split_whitespace().next().unwrap_or("").to_owned());
|
||||
}
|
||||
}
|
||||
stack.is_empty()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_material_maps_every_input() {
|
||||
let t: Vec<Texture> = INPUTS.iter().map(|(n, _)| tex(n, &format!("stone_{n}.png"))).collect();
|
||||
let x = write("Stone", &t, Some([100.0, 50.0]));
|
||||
assert!(balanced(&x), "{x}");
|
||||
for want in [
|
||||
"<materialx version=\"1.39\"",
|
||||
"<open_pbr_surface name=\"OPBR_Stone\" type=\"surfaceshader\">",
|
||||
"name=\"base_color\" type=\"color3\" nodename=\"image_base_color\"",
|
||||
"name=\"base_metalness\" type=\"float\" nodename=\"image_base_metalness\"",
|
||||
"name=\"specular_roughness\" type=\"float\" nodename=\"image_specular_roughness\"",
|
||||
"name=\"coat_weight\" type=\"float\" nodename=\"image_coat_weight\"",
|
||||
"name=\"fuzz_color\" type=\"color3\" nodename=\"image_fuzz_color\"",
|
||||
"name=\"transmission_weight\" type=\"float\"",
|
||||
"name=\"subsurface_weight\" type=\"float\"",
|
||||
"name=\"geometry_opacity\" type=\"float\" nodename=\"image_geometry_opacity\"",
|
||||
"name=\"geometry_normal\" type=\"vector3\" nodename=\"normalmap\"",
|
||||
"name=\"emission_color\" type=\"color3\" nodename=\"image_emission_color\"",
|
||||
"name=\"emission_luminance\" type=\"float\" value=\"1\"",
|
||||
"value=\"stone_base_color.png\" colorspace=\"srgb_texture\"",
|
||||
"value=\"stone_emission_color.png\" colorspace=\"srgb_texture\"",
|
||||
"<normalmap name=\"normalmap\" type=\"vector3\">",
|
||||
"<displacement name=\"DISP_Stone\" type=\"displacementshader\">",
|
||||
"name=\"displacementshader\"",
|
||||
"<surfacematerial name=\"Stone\" type=\"material\" doc=\"Tiles every 100 x 50 cm\">",
|
||||
] {
|
||||
assert!(x.contains(want), "missing {want}\n{x}");
|
||||
}
|
||||
// Data textures carry no colour space, and height is not an OpenPBR input.
|
||||
assert!(x.contains("value=\"stone_specular_roughness.png\" />"));
|
||||
assert!(!x.contains("name=\"height\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_what_is_there_is_written() {
|
||||
let x = write("m", &[tex("specular_roughness", "r.png")], None);
|
||||
assert!(balanced(&x));
|
||||
assert!(!x.contains("base_color") && !x.contains("normalmap") && !x.contains("displacement") && !x.contains("emission_luminance"));
|
||||
assert!(x.contains("<surfacematerial name=\"m\" type=\"material\">"));
|
||||
let none = write("m", &[], None);
|
||||
assert!(balanced(&none) && none.contains("<open_pbr_surface") && !none.contains("tiledimage"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_inputs_carry_their_files_space_and_data_inputs_none() {
|
||||
let lin = |input: &str, file: &str| Texture { colorspace: "lin_rec709", ..tex(input, file) };
|
||||
let x = write("m", &[lin("base_color", "c.exr"), lin("specular_roughness", "r.exr")], None);
|
||||
assert!(x.contains("value=\"c.exr\" colorspace=\"lin_rec709\"") && x.contains("value=\"r.exr\" />"), "{x}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_and_repeated_inputs_are_skipped() {
|
||||
let x = write("m", &[tex("ambient_occlusion", "ao.png"), tex("base_color", "a.png"), tex("base_color", "b.png")], None);
|
||||
assert!(!x.contains("ao.png") && x.contains("a.png") && !x.contains("b.png"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn templates_map_to_inputs() {
|
||||
assert_eq!(input_of_template("$mesh_$textureSet_base_color"), Some("base_color"));
|
||||
assert_eq!(input_of_template("$mesh_$textureSet_height"), Some("height"));
|
||||
assert_eq!(input_of_template("$mesh_$textureSet_orm"), None);
|
||||
assert_eq!(input_of_template("base_color"), None);
|
||||
for (n, _) in INPUTS {
|
||||
assert_eq!(input_of_template(&format!("{PREFIX}{n}")), Some(*n));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn udim_tokens_and_hostile_names_are_escaped() {
|
||||
assert_eq!(node_name("Rough Stone #2"), "Rough_Stone__2");
|
||||
assert_eq!(node_name("9lives"), "_9lives");
|
||||
assert_eq!(node_name(""), "_");
|
||||
let x = write("a<b>&\"c", &[tex("base_color", "x\"&<'>.<UDIM>.png")], Some([f32::NAN, 1.0]));
|
||||
assert!(balanced(&x.replace("<UDIM>", "UDIM")), "{x}");
|
||||
assert!(x.contains("value=\"x"&<'>.<UDIM>.png\""));
|
||||
assert!(!x.contains("doc="), "a non-finite size is left out");
|
||||
assert!(x.contains("OPBR_a_b___c"));
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,7 @@ pub fn usd_export_options() -> ExportOptions {
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) enum UsdValue {
|
||||
Token(String),
|
||||
Str(String),
|
||||
Int(i32),
|
||||
Double(f64),
|
||||
Asset(String),
|
||||
@@ -277,7 +278,8 @@ fn material(path: &str, id: &str, files: &[(usize, String)]) -> UsdPrim {
|
||||
let mut st = UsdPrim::new("st", "Shader");
|
||||
st.attrs = vec![
|
||||
UsdAttr::new("info:id", "token", Some(UsdValue::Token("UsdPrimvarReader_float2".into()))).uniform(),
|
||||
UsdAttr::new("inputs:varname", "token", Some(UsdValue::Token("st".into()))),
|
||||
// A string, not a token: usdchecker's ARKit profile refuses a token here.
|
||||
UsdAttr::new("inputs:varname", "string", Some(UsdValue::Str("st".into()))),
|
||||
UsdAttr::new("outputs:result", "float2", None),
|
||||
];
|
||||
mat.children.push(st);
|
||||
@@ -355,7 +357,7 @@ fn usda_value(s: &mut String, v: &UsdValue) {
|
||||
s.push(']');
|
||||
};
|
||||
match v {
|
||||
UsdValue::Token(t) => {
|
||||
UsdValue::Token(t) | UsdValue::Str(t) => {
|
||||
let _ = write!(s, "\"{t}\"");
|
||||
}
|
||||
UsdValue::Int(i) => {
|
||||
|
||||
@@ -57,6 +57,18 @@ impl Writer {
|
||||
i
|
||||
}
|
||||
|
||||
/// Index of `s` in the string table (which holds token indices).
|
||||
fn string(&mut self, s: &str) -> u32 {
|
||||
let t = self.token(s);
|
||||
match self.strings.iter().position(|x| *x == t) {
|
||||
Some(i) => i as u32,
|
||||
None => {
|
||||
self.strings.push(t);
|
||||
(self.strings.len() - 1) as u32
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn add_path(&mut self, parent: usize, parent_text: &str, name: &str, prop: bool) -> (usize, String) {
|
||||
let text = match (prop, parent_text) {
|
||||
(true, _) => format!("{parent_text}.{name}"),
|
||||
@@ -127,6 +139,7 @@ impl Writer {
|
||||
Ok(match v {
|
||||
UsdValue::Token(t) => rep(ty::TOKEN, codec::IS_INLINED, u64::from(self.token(t))),
|
||||
UsdValue::Asset(a) => rep(ty::ASSET_PATH, codec::IS_INLINED, u64::from(self.token(a))),
|
||||
UsdValue::Str(s) => rep(ty::STRING, codec::IS_INLINED, u64::from(self.string(s))),
|
||||
UsdValue::Int(i) => rep(ty::INT, codec::IS_INLINED, u64::from(*i as u32)),
|
||||
UsdValue::Double(d) => {
|
||||
let at = self.offset();
|
||||
|
||||
@@ -344,7 +344,15 @@ fn usda_usdc_and_usdz_round_trip_with_textures() {
|
||||
&& !text.contains("Red_Clearcoat"),
|
||||
"a coat exports with its roughness; no coat (black) drops both"
|
||||
);
|
||||
round_trip(&m, UsdFormat::Usdc, "usdc", &textures);
|
||||
// The primvar reader's varname is a string (usdchecker --arkit refuses a token), in both encodings.
|
||||
assert!(text.contains("string inputs:varname = \"st\""), "{text}");
|
||||
let usdc = round_trip(&m, UsdFormat::Usdc, "usdc", &textures);
|
||||
let layer = super::usdc::read(&usdc, &mut super::Budget::new()).unwrap();
|
||||
let varnames: Vec<&super::Prop> = layer.prims.iter().filter_map(|p| p.props.get("inputs:varname")).collect();
|
||||
assert!(!varnames.is_empty());
|
||||
for v in varnames {
|
||||
assert_eq!((v.type_name.as_str(), v.value.clone()), ("string", Some(super::Val::Tok(vec!["st".into()]))));
|
||||
}
|
||||
let usdz = round_trip(&m, UsdFormat::Usdz, "usdz", &textures);
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&usdz)).unwrap();
|
||||
let names: Vec<String> = zip.file_names().map(|n| n.unwrap().into_owned()).collect();
|
||||
|
||||
@@ -14,4 +14,9 @@ texturecraft-texel = { workspace = true }
|
||||
texturecraft-geom = { workspace = true }
|
||||
texturecraft-compose = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
harfrust = { workspace = true }
|
||||
skrifa = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
epaint_default_fonts = { workspace = true }
|
||||
@@ -112,12 +112,15 @@ impl Shape<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// An image as a brush alpha: luminance × alpha over the stamp square (−1..1, y up), 0 outside.
|
||||
/// An image as a brush alpha: luminance × alpha, its longer side across the stamp square (−1..1,
|
||||
/// y up) so it keeps its proportions (a line of text stays a line), 0 outside.
|
||||
pub fn image_alpha(img: &ImageRes, lx: f32, ly: f32) -> f32 {
|
||||
if !(lx.abs() <= 1.0 && ly.abs() <= 1.0) {
|
||||
let aspect = img.width as f32 / img.height.max(1) as f32;
|
||||
let (x, y) = if aspect >= 1.0 { (lx, ly * aspect) } else { (lx / aspect.max(1e-6), ly) };
|
||||
if !(x.abs() <= 1.0 && y.abs() <= 1.0) {
|
||||
return 0.0;
|
||||
}
|
||||
let [r, g, b, a] = img.sample(lx * 0.5 + 0.5, 0.5 - ly * 0.5);
|
||||
let [r, g, b, a] = img.sample(x * 0.5 + 0.5, 0.5 - y * 0.5);
|
||||
((0.2126 * r + 0.7152 * g + 0.0722 * b) * a).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
//! see ([`EyeDepth`]); [`commit`] blends the finished stroke into layer pixels. Clone and smudge
|
||||
//! strokes carry channel values ([`pickup`]) instead of painting the tool's material.
|
||||
//! [`path`] samples the Path tool's curves and lasso coverage; [`particles`] runs the particle
|
||||
//! brush; [`alphas`] is the built-in library of procedural brush alphas.
|
||||
//! brush; [`alphas`] is the built-in library of procedural brush alphas and [`presets`] the built-in
|
||||
//! brush presets; [`text`] draws text for text alphas and decals.
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
@@ -16,8 +17,10 @@ pub mod commit;
|
||||
pub mod particles;
|
||||
pub mod path;
|
||||
pub mod pickup;
|
||||
pub mod presets;
|
||||
pub mod raster;
|
||||
pub mod stroke;
|
||||
pub mod text;
|
||||
pub mod visibility;
|
||||
|
||||
pub use brush::{Alignment, BrushAlpha, BrushSettings, Particles, Shape, Symmetry, image_alpha};
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
//! Built-in brush presets: how a brush strokes (shape, spacing, flow, hardness, jitters, path
|
||||
//! following, particles). Applying one keeps the brush's size, alignment, culling, symmetry and
|
||||
//! lazy mouse, so a preset changes the stroke, not the setup.
|
||||
|
||||
use crate::brush::{BrushAlpha, BrushSettings};
|
||||
|
||||
/// A named stroke recipe on top of the default stroke.
|
||||
pub struct BrushPreset {
|
||||
pub id: &'static str,
|
||||
pub label: &'static str,
|
||||
pub category: &'static str,
|
||||
recipe: fn(&mut BrushSettings),
|
||||
}
|
||||
|
||||
impl BrushPreset {
|
||||
/// `brush` with this preset's stroke.
|
||||
pub fn applied(&self, brush: &BrushSettings) -> BrushSettings {
|
||||
let mut b = with_stroke_of(brush, &BrushSettings::default());
|
||||
(self.recipe)(&mut b);
|
||||
b.sanitized()
|
||||
}
|
||||
}
|
||||
|
||||
/// `brush` with the stroke of `from` (shape, flow, opacity, spacing, hardness, angle, path
|
||||
/// following, jitters and particles): what a preset sets.
|
||||
pub fn with_stroke_of(brush: &BrushSettings, from: &BrushSettings) -> BrushSettings {
|
||||
BrushSettings {
|
||||
flow: from.flow,
|
||||
opacity: from.opacity,
|
||||
spacing: from.spacing,
|
||||
hardness: from.hardness,
|
||||
angle: from.angle,
|
||||
follow_path: from.follow_path,
|
||||
jitter_size: from.jitter_size,
|
||||
jitter_angle: from.jitter_angle,
|
||||
jitter_flow: from.jitter_flow,
|
||||
jitter_position: from.jitter_position,
|
||||
alpha: from.alpha,
|
||||
alpha_image: from.alpha_image.clone(),
|
||||
alpha_library: from.alpha_library.clone(),
|
||||
particles: from.particles,
|
||||
..brush.clone()
|
||||
}
|
||||
.sanitized()
|
||||
}
|
||||
|
||||
/// A preset by id or label (case, spaces, `_` and `-` ignored).
|
||||
pub fn find_preset(name: &str) -> Option<&'static BrushPreset> {
|
||||
let n = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-'], "");
|
||||
PRESETS.iter().find(|p| n(p.id) == n(name) || n(p.label) == n(name))
|
||||
}
|
||||
|
||||
const BASIC: &str = "Basic";
|
||||
const GRUNGE: &str = "Wear and grunge";
|
||||
const DETAIL: &str = "Details";
|
||||
|
||||
fn library(b: &mut BrushSettings, id: &str) {
|
||||
b.alpha_library = Some(id.to_string());
|
||||
}
|
||||
|
||||
/// Every built-in preset, in shelf order.
|
||||
pub const PRESETS: [BrushPreset; 18] = [
|
||||
BrushPreset { id: "basic_hard", label: "Basic hard", category: BASIC, recipe: |b| b.hardness = 0.95 },
|
||||
BrushPreset { id: "basic_soft", label: "Basic soft", category: BASIC, recipe: |b| (b.hardness, b.flow) = (0.0, 0.6) },
|
||||
BrushPreset { id: "airbrush", label: "Airbrush", category: BASIC, recipe: |b| (b.hardness, b.flow, b.spacing) = (0.0, 0.12, 0.04) },
|
||||
BrushPreset { id: "square", label: "Square", category: BASIC, recipe: |b| (b.alpha, b.hardness, b.follow_path) = (BrushAlpha::Square, 0.9, true) },
|
||||
BrushPreset { id: "dots", label: "Dots", category: BASIC, recipe: |b| (b.hardness, b.spacing) = (0.9, 1.6) },
|
||||
BrushPreset {
|
||||
id: "dry_brush",
|
||||
label: "Dry brush",
|
||||
category: GRUNGE,
|
||||
recipe: |b| (b.alpha, b.follow_path, b.spacing, b.flow) = (BrushAlpha::Streaks, true, 0.04, 0.5),
|
||||
},
|
||||
BrushPreset {
|
||||
id: "chalk",
|
||||
label: "Chalk",
|
||||
category: GRUNGE,
|
||||
recipe: |b| {
|
||||
library(b, "sponge");
|
||||
(b.jitter_angle, b.spacing, b.flow) = (1.0, 0.15, 0.7);
|
||||
},
|
||||
},
|
||||
BrushPreset {
|
||||
id: "spray",
|
||||
label: "Spray",
|
||||
category: GRUNGE,
|
||||
recipe: |b| (b.alpha, b.jitter_angle, b.jitter_size, b.spacing) = (BrushAlpha::Spray, 1.0, 0.3, 0.3),
|
||||
},
|
||||
BrushPreset {
|
||||
id: "grunge",
|
||||
label: "Grunge",
|
||||
category: GRUNGE,
|
||||
recipe: |b| (b.alpha, b.jitter_angle, b.jitter_size, b.spacing) = (BrushAlpha::Grunge, 1.0, 0.4, 0.4),
|
||||
},
|
||||
BrushPreset {
|
||||
id: "splatter",
|
||||
label: "Splatter",
|
||||
category: GRUNGE,
|
||||
recipe: |b| {
|
||||
library(b, "splatter");
|
||||
(b.jitter_angle, b.jitter_size, b.jitter_position, b.spacing) = (1.0, 0.5, 1.5, 1.2);
|
||||
},
|
||||
},
|
||||
BrushPreset {
|
||||
id: "scratches",
|
||||
label: "Scratches",
|
||||
category: GRUNGE,
|
||||
recipe: |b| {
|
||||
library(b, "scratches");
|
||||
(b.follow_path, b.jitter_angle, b.spacing) = (true, 0.1, 0.5);
|
||||
},
|
||||
},
|
||||
BrushPreset {
|
||||
id: "chips",
|
||||
label: "Chips",
|
||||
category: GRUNGE,
|
||||
recipe: |b| {
|
||||
library(b, "chips");
|
||||
(b.jitter_angle, b.jitter_size, b.jitter_position, b.spacing) = (1.0, 0.5, 1.0, 0.8);
|
||||
},
|
||||
},
|
||||
BrushPreset {
|
||||
id: "cracks",
|
||||
label: "Cracks",
|
||||
category: GRUNGE,
|
||||
recipe: |b| {
|
||||
library(b, "cracks");
|
||||
(b.jitter_angle, b.spacing) = (1.0, 0.9);
|
||||
},
|
||||
},
|
||||
BrushPreset {
|
||||
id: "drips",
|
||||
label: "Drips",
|
||||
category: GRUNGE,
|
||||
recipe: |b| {
|
||||
(b.hardness, b.flow) = (0.7, 0.6);
|
||||
b.particles.enabled = true;
|
||||
},
|
||||
},
|
||||
BrushPreset {
|
||||
id: "stars",
|
||||
label: "Stars",
|
||||
category: DETAIL,
|
||||
recipe: |b| {
|
||||
library(b, "star_5");
|
||||
(b.jitter_size, b.jitter_angle, b.jitter_position, b.spacing) = (0.6, 1.0, 2.0, 1.5);
|
||||
},
|
||||
},
|
||||
BrushPreset {
|
||||
id: "stitches",
|
||||
label: "Stitches",
|
||||
category: DETAIL,
|
||||
recipe: |b| {
|
||||
library(b, "stitches");
|
||||
(b.follow_path, b.spacing) = (true, 0.9);
|
||||
},
|
||||
},
|
||||
BrushPreset {
|
||||
id: "rivets",
|
||||
label: "Rivets",
|
||||
category: DETAIL,
|
||||
recipe: |b| {
|
||||
library(b, "rivet");
|
||||
b.spacing = 2.0;
|
||||
},
|
||||
},
|
||||
BrushPreset {
|
||||
id: "fur",
|
||||
label: "Fur",
|
||||
category: DETAIL,
|
||||
recipe: |b| {
|
||||
library(b, "fur");
|
||||
(b.follow_path, b.jitter_angle, b.spacing) = (true, 0.15, 0.3);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn presets_are_unique_valid_and_keep_the_setup() {
|
||||
let mut ids: Vec<&str> = PRESETS.iter().map(|p| p.id).collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
assert_eq!(ids.len(), PRESETS.len());
|
||||
let mine =
|
||||
BrushSettings { size: 0.1, lazy: 12.0, backface_culling: false, jitter_size: 1.0, alpha_image: Some("x.png".into()), ..BrushSettings::default() };
|
||||
for p in &PRESETS {
|
||||
let b = p.applied(&mine);
|
||||
assert_eq!(b, b.sanitized(), "{}", p.id);
|
||||
assert_eq!((b.size, b.lazy, b.backface_culling, b.alpha_image.as_deref()), (0.1, 12.0, false, None), "{}", p.id);
|
||||
if let Some(id) = &b.alpha_library {
|
||||
assert!(crate::alphas::find(id).is_some(), "{}: library alpha {id}", p.id);
|
||||
}
|
||||
assert_eq!(find_preset(p.label).map(|f| f.id), Some(p.id));
|
||||
}
|
||||
assert_eq!(find_preset("basic hard").map(|p| p.id), Some("basic_hard"));
|
||||
assert!(find_preset("nope").is_none());
|
||||
assert_eq!(PRESETS[0].applied(&mine).jitter_size, 0.0, "jitters reset");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
//! Text as a coverage image, for brush alphas and decals: each line shaped with harfrust
|
||||
//! (kerning, ligatures, joined scripts), drawn from the font's outlines (skrifa) and filled with
|
||||
//! a non-zero scanline rasterizer, lines centered.
|
||||
|
||||
use harfrust::{FontRef, ShapeOptions, ShaperData, UnicodeBuffer};
|
||||
use skrifa::MetadataProvider;
|
||||
use skrifa::instance::{LocationRef, Size};
|
||||
use skrifa::outline::{DrawSettings, OutlinePen};
|
||||
|
||||
/// Longest text drawn (characters).
|
||||
pub const MAX_TEXT_CHARS: usize = 1000;
|
||||
/// Largest side of a text image (texels); bigger layouts are drawn smaller to fit.
|
||||
pub const MAX_TEXT_SIDE: u32 = 4096;
|
||||
/// Vertical samples per texel row.
|
||||
const SUBROWS: usize = 4;
|
||||
|
||||
/// A shaped glyph: its id and pen position (font units).
|
||||
type Placed = (u32, f32, f32);
|
||||
|
||||
/// Coverage 0..=255 per texel, rows top to bottom.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TextImage {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub coverage: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Draw `text` (one or more lines) with face `index` of `font` at `px` texels per em, cropped to
|
||||
/// the ink with a margin of a tenth of an em.
|
||||
pub fn render_text(font: &[u8], index: u32, text: &str, px: f32) -> Result<TextImage, String> {
|
||||
let text = text.trim_end();
|
||||
if text.trim().is_empty() {
|
||||
return Err("the text is empty".into());
|
||||
}
|
||||
if text.chars().count() > MAX_TEXT_CHARS {
|
||||
return Err(format!("the text is longer than {MAX_TEXT_CHARS} characters"));
|
||||
}
|
||||
let font = FontRef::from_index(font, index).map_err(|e| format!("not a usable font: {e}"))?;
|
||||
// Layout in font units; `scale` turns them into texels.
|
||||
let m = font.metrics(Size::unscaled(), LocationRef::default());
|
||||
let upem = f32::from(m.units_per_em.max(1));
|
||||
let line = (m.ascent - m.descent + m.leading).max(upem * 0.5);
|
||||
let data = ShaperData::new(&font);
|
||||
let shaper = data.shaper(&font).build();
|
||||
let mut lines: Vec<(f32, Vec<Placed>)> = Vec::new();
|
||||
for t in text.lines() {
|
||||
let mut buffer = UnicodeBuffer::new();
|
||||
buffer.push_str(t);
|
||||
buffer.guess_segment_properties();
|
||||
let shaped = shaper.shape(buffer, ShapeOptions::new());
|
||||
let mut x = 0.0;
|
||||
let mut glyphs = Vec::new();
|
||||
for (info, pos) in shaped.glyph_infos().iter().zip(shaped.glyph_positions()) {
|
||||
glyphs.push((info.glyph_id, x + pos.x_offset as f32, pos.y_offset as f32));
|
||||
x += pos.x_advance as f32;
|
||||
}
|
||||
lines.push((x, glyphs));
|
||||
}
|
||||
let widest = lines.iter().map(|(w, _)| *w).fold(0.0, f32::max);
|
||||
let px = px.clamp(4.0, 1024.0);
|
||||
// Outlines in texels (y down) at the shaped positions, lines centered on the widest.
|
||||
let outlines = font.outline_glyphs();
|
||||
let mut pen = Edges { scale: px / upem, ..Edges::default() };
|
||||
for (row, (line_width, glyphs)) in lines.iter().enumerate() {
|
||||
let left = (widest - line_width) * 0.5;
|
||||
for &(id, x, y) in glyphs {
|
||||
let Some(glyph) = outlines.get(skrifa::GlyphId::new(id)) else { continue };
|
||||
pen.origin = ((left + x) * pen.scale, (line * row as f32 - y) * pen.scale);
|
||||
// A glyph that can't be drawn is left out rather than failing the text.
|
||||
let _ = glyph.draw(DrawSettings::unhinted(Size::unscaled(), LocationRef::default()), &mut pen);
|
||||
pen.close();
|
||||
}
|
||||
}
|
||||
// The image is the ink's bounds plus the margin (accents and descenders never clip), scaled
|
||||
// down when that is too large.
|
||||
let points = || pen.edges.iter().flat_map(|e| [(e[0], e[1]), (e[2], e[3])]);
|
||||
let lo = points().fold((f32::MAX, f32::MAX), |a, p| (a.0.min(p.0), a.1.min(p.1)));
|
||||
let hi = points().fold((f32::MIN, f32::MIN), |a, p| (a.0.max(p.0), a.1.max(p.1)));
|
||||
if pen.edges.is_empty() || !(lo.0.is_finite() && hi.0.is_finite() && lo.1.is_finite() && hi.1.is_finite()) {
|
||||
return Err("the font draws nothing for this text".into());
|
||||
}
|
||||
let margin = px * 0.1;
|
||||
let (w, h) = (hi.0 - lo.0 + 2.0 * margin, hi.1 - lo.1 + 2.0 * margin);
|
||||
let fit = (MAX_TEXT_SIDE as f32 / w.max(h)).min(1.0);
|
||||
let edges: Vec<[f32; 4]> = pen
|
||||
.edges
|
||||
.iter()
|
||||
.map(|e| [(e[0] - lo.0 + margin) * fit, (e[1] - lo.1 + margin) * fit, (e[2] - lo.0 + margin) * fit, (e[3] - lo.1 + margin) * fit])
|
||||
.collect();
|
||||
let (width, height) = ((w * fit).ceil().max(1.0) as u32, (h * fit).ceil().max(1.0) as u32);
|
||||
Ok(TextImage { width, height, coverage: fill(&edges, width as usize, height as usize) })
|
||||
}
|
||||
|
||||
/// Line segments (texel space, y down) collected from glyph outlines: font units times `scale`
|
||||
/// from `origin`, curves flattened.
|
||||
#[derive(Default)]
|
||||
struct Edges {
|
||||
scale: f32,
|
||||
origin: (f32, f32),
|
||||
start: (f32, f32),
|
||||
at: (f32, f32),
|
||||
edges: Vec<[f32; 4]>,
|
||||
}
|
||||
|
||||
impl Edges {
|
||||
fn map(&self, x: f32, y: f32) -> (f32, f32) {
|
||||
(self.origin.0 + x * self.scale, self.origin.1 - y * self.scale)
|
||||
}
|
||||
|
||||
fn segment(&mut self, to: (f32, f32)) {
|
||||
if to != self.at {
|
||||
self.edges.push([self.at.0, self.at.1, to.0, to.1]);
|
||||
}
|
||||
self.at = to;
|
||||
}
|
||||
|
||||
/// Flatten a curve given as a point function of t in 0..1, finer for longer curves.
|
||||
fn curve(&mut self, control_length: f32, point: impl Fn(f32) -> (f32, f32)) {
|
||||
let steps = (control_length.sqrt() * 2.0).clamp(2.0, 64.0) as usize;
|
||||
for i in 1..=steps {
|
||||
self.segment(point(i as f32 / steps as f32));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dist(a: (f32, f32), b: (f32, f32)) -> f32 {
|
||||
(a.0 - b.0).hypot(a.1 - b.1)
|
||||
}
|
||||
|
||||
impl OutlinePen for Edges {
|
||||
fn move_to(&mut self, x: f32, y: f32) {
|
||||
self.close();
|
||||
self.start = self.map(x, y);
|
||||
self.at = self.start;
|
||||
}
|
||||
|
||||
fn line_to(&mut self, x: f32, y: f32) {
|
||||
let p = self.map(x, y);
|
||||
self.segment(p);
|
||||
}
|
||||
|
||||
fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
|
||||
let (p0, c, p) = (self.at, self.map(cx0, cy0), self.map(x, y));
|
||||
self.curve(dist(p0, c) + dist(c, p), |t| {
|
||||
let s = 1.0 - t;
|
||||
(s * s * p0.0 + 2.0 * s * t * c.0 + t * t * p.0, s * s * p0.1 + 2.0 * s * t * c.1 + t * t * p.1)
|
||||
});
|
||||
}
|
||||
|
||||
fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
|
||||
let (p0, c0, c1, p) = (self.at, self.map(cx0, cy0), self.map(cx1, cy1), self.map(x, y));
|
||||
self.curve(dist(p0, c0) + dist(c0, c1) + dist(c1, p), |t| {
|
||||
let s = 1.0 - t;
|
||||
let (a, b, c, d) = (s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t);
|
||||
(a * p0.0 + b * c0.0 + c * c1.0 + d * p.0, a * p0.1 + b * c0.1 + c * c1.1 + d * p.1)
|
||||
});
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.segment(self.start);
|
||||
}
|
||||
}
|
||||
|
||||
/// Non-zero winding coverage of closed `edges` over a `w × h` grid: [`SUBROWS`] scanlines per
|
||||
/// row, each span's ends spread over the texels they cross.
|
||||
fn fill(edges: &[[f32; 4]], w: usize, h: usize) -> Vec<u8> {
|
||||
let mut acc = vec![0f32; w * h];
|
||||
// Edges by their top, and the ones the current scanline may cross.
|
||||
let mut sorted: Vec<[f32; 4]> = edges.iter().copied().filter(|e| e[1] != e[3]).collect();
|
||||
sorted.sort_by(|a, b| a[1].min(a[3]).total_cmp(&b[1].min(b[3])));
|
||||
let (mut next, mut active) = (0, Vec::new());
|
||||
let mut crossings: Vec<(f32, i32)> = Vec::new();
|
||||
for row in 0..h {
|
||||
for sub in 0..SUBROWS {
|
||||
let y = row as f32 + (sub as f32 + 0.5) / SUBROWS as f32;
|
||||
while let Some(e) = sorted.get(next).filter(|e| e[1].min(e[3]) <= y) {
|
||||
active.push(*e);
|
||||
next += 1;
|
||||
}
|
||||
active.retain(|e| e[1].max(e[3]) > y);
|
||||
crossings.clear();
|
||||
for &[x0, y0, x1, y1] in &active {
|
||||
if (y0 <= y) != (y1 <= y) {
|
||||
crossings.push((x0 + (y - y0) / (y1 - y0) * (x1 - x0), if y1 > y0 { 1 } else { -1 }));
|
||||
}
|
||||
}
|
||||
crossings.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let mut winding = 0;
|
||||
for pair in crossings.windows(2) {
|
||||
winding += pair[0].1;
|
||||
if winding != 0 {
|
||||
span(&mut acc[row * w..(row + 1) * w], pair[0].0, pair[1].0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
acc.iter().map(|c| (c / SUBROWS as f32 * 255.0).round().clamp(0.0, 255.0) as u8).collect()
|
||||
}
|
||||
|
||||
/// Add the covered length of `x0..x1` to each texel of `row`.
|
||||
fn span(row: &mut [f32], x0: f32, x1: f32) {
|
||||
let (x0, x1) = (x0.clamp(0.0, row.len() as f32), x1.clamp(0.0, row.len() as f32));
|
||||
if x1 <= x0 {
|
||||
return;
|
||||
}
|
||||
for (i, c) in row.iter_mut().enumerate().take(x1.ceil() as usize).skip(x0.floor() as usize) {
|
||||
*c += (x1.min(i as f32 + 1.0) - x0.max(i as f32)).max(0.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn spans_spread_partial_texels() {
|
||||
let mut row = [0.0; 4];
|
||||
span(&mut row, 0.5, 2.25);
|
||||
assert_eq!(row, [0.5, 1.0, 0.25, 0.0]);
|
||||
// A square drawn either way round fills the same texels.
|
||||
let square = |cw: bool| {
|
||||
let p = [(1.0, 1.0), (3.0, 1.0), (3.0, 3.0), (1.0, 3.0)];
|
||||
let p: Vec<_> = if cw { p.to_vec() } else { p.iter().rev().copied().collect() };
|
||||
(0..4).map(|i| [p[i].0, p[i].1, p[(i + 1) % 4].0, p[(i + 1) % 4].1]).collect::<Vec<_>>()
|
||||
};
|
||||
let a = fill(&square(true), 4, 4);
|
||||
assert_eq!(a, fill(&square(false), 4, 4));
|
||||
assert_eq!((a[5], a[0], a[3 * 4 + 3]), (255, 0, 0), "inside full, outside empty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_is_laid_out_and_filled() {
|
||||
let font = epaint_default_fonts::UBUNTU_LIGHT;
|
||||
let one = render_text(font, 0, "H", 64.0).unwrap();
|
||||
let two = render_text(font, 0, "HH", 64.0).unwrap();
|
||||
let lines = render_text(font, 0, "H\nH", 64.0).unwrap();
|
||||
assert!(two.width > one.width && two.height == one.height);
|
||||
assert!(lines.height > one.height && lines.width == one.width, "lines stack");
|
||||
let ink = |t: &TextImage| t.coverage.iter().map(|c| u32::from(*c)).sum::<u32>();
|
||||
assert!(ink(&two) > ink(&one) * 19 / 10 && ink(&two) < ink(&one) * 21 / 10, "two H, twice the ink");
|
||||
assert!(one.coverage.contains(&255) && one.coverage.contains(&0));
|
||||
// The margin stays clear; huge sizes are drawn to fit.
|
||||
assert!(one.coverage[..one.width as usize].iter().all(|c| *c == 0));
|
||||
let big = render_text(font, 0, &"W".repeat(400), 1024.0).unwrap();
|
||||
assert!(big.width <= MAX_TEXT_SIDE && big.height >= 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_input_is_an_error() {
|
||||
assert!(render_text(b"not a font", 0, "Hi", 64.0).is_err());
|
||||
assert!(render_text(b"", 0, " ", 64.0).is_err());
|
||||
assert!(render_text(b"", 0, &"x".repeat(MAX_TEXT_CHARS + 1), 64.0).is_err());
|
||||
}
|
||||
}
|
||||
@@ -17,10 +17,15 @@ texturecraft-bake = { workspace = true }
|
||||
wgpu = { workspace = true }
|
||||
bytemuck = { workspace = true }
|
||||
half = { workspace = true }
|
||||
log = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
pollster = "0.4"
|
||||
|
||||
# The browser's WebGPU resolves error scopes later: their results are awaited on the page.
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
wasm-bindgen-futures = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
image = { workspace = true }
|
||||
@@ -140,6 +140,54 @@ pub(crate) fn scoped<T>(device: &wgpu::Device, what: &str, f: impl FnOnce() -> T
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`checked`] knows right after the call.
|
||||
pub(crate) enum Checked<T> {
|
||||
/// wgpu answered at once (native backends, WebGL): the value, or what went wrong.
|
||||
Done(Result<T, String>),
|
||||
/// The browser's WebGPU answers later: the value, possibly invalid, and where the answer
|
||||
/// arrives (`None` for success). Don't use the value until it arrives. (Native backends
|
||||
/// never answer late; the renderer's tests build this variant by hand.)
|
||||
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
|
||||
Later(T, std::sync::mpsc::Receiver<Option<String>>),
|
||||
}
|
||||
|
||||
/// [`scoped`] for work whose errors may arrive later: never takes an unanswered scope as success.
|
||||
pub(crate) fn checked<T>(device: &wgpu::Device, what: &str, f: impl FnOnce() -> T) -> Checked<T> {
|
||||
let oom = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
||||
let invalid = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
let out = f();
|
||||
let (invalid, oom) = (invalid.pop(), oom.pop());
|
||||
let what = what.to_string();
|
||||
let mut answer = Box::pin(async move {
|
||||
let invalid = invalid.await;
|
||||
let oom = oom.await;
|
||||
// An allocation that ran out of memory also makes later calls on it invalid: the
|
||||
// out-of-memory error is the cause.
|
||||
oom.or(invalid).map(|e| format!("{what}: {e}"))
|
||||
});
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
Checked::Done(match pollster::block_on(answer.as_mut()) {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(out),
|
||||
})
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
match answer.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
|
||||
Poll::Ready(Some(e)) => Checked::Done(Err(e)),
|
||||
Poll::Ready(None) => Checked::Done(Ok(out)),
|
||||
Poll::Pending => {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let _ = tx.send(answer.await);
|
||||
});
|
||||
Checked::Later(out, rx)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn entry(binding: u32, ty: wgpu::BindingType) -> wgpu::BindGroupLayoutEntry {
|
||||
wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty, count: None }
|
||||
}
|
||||
@@ -439,7 +487,8 @@ impl GpuTracer {
|
||||
let mut info: Vec<[f32; 3]> = sets
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let dims = s.first().map_or((1, 1), |t| (t.width(), t.height()));
|
||||
// The set's size is its largest texture's; any kind may still be a 1×1 placeholder.
|
||||
let dims = s.iter().fold((1, 1), |(w, h), t| (t.width().max(w), t.height().max(h)));
|
||||
let small = s.iter().enumerate().filter(|(_, t)| (t.width(), t.height()) != dims).fold(0u32, |m, (k, _)| m | 1 << k);
|
||||
[dims.0 as f32, dims.1 as f32, small as f32]
|
||||
})
|
||||
@@ -821,6 +870,43 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_reads_full_size_channels_beside_placeholders() {
|
||||
// Base color stays at its default (a 1×1 placeholder texture) while roughness varies
|
||||
// across the surface (a full-size texture): the tracer must still read every texel of it.
|
||||
use Channel::*;
|
||||
let Some((mut h, mut t)) = gpu() else { return };
|
||||
let mut composite = Composite::new(&[Roughness, Metallic], 64);
|
||||
for y in 0..64 {
|
||||
for x in 0..64 {
|
||||
let rough = if x < 32 { 0.05 } else { 0.9 };
|
||||
composite.channels.get_mut(&Roughness).unwrap().set(x, y, &[texturecraft_texel::to_u16(rough)]);
|
||||
composite.channels.get_mut(&Metallic).unwrap().set(x, y, &[texturecraft_texel::to_u16(1.0)]);
|
||||
}
|
||||
}
|
||||
h.renderer.set_texture_sets(&h.device, &h.queue, &[((64, 64), 0)], 1);
|
||||
for (tx, ty) in all_tiles(64, 64) {
|
||||
for k in DisplayKind::ALL {
|
||||
h.renderer.upload_tile(&h.device, &h.queue, 0, k, tx, ty, &tile_bytes(&composite, &BakedMaps::default(), k, tx, ty));
|
||||
}
|
||||
}
|
||||
let sizes: Vec<u32> = h.renderer.display_textures()[0].iter().map(|t| t.width()).collect();
|
||||
assert_eq!(sizes[0], 1, "base color stays a placeholder");
|
||||
assert_eq!(sizes[1], 64, "roughness and metallic are full size");
|
||||
let mesh = Arc::new(primitives::sphere(1.0, 32, 16));
|
||||
let bvh = Arc::new(Bvh::new(&mesh));
|
||||
let env = crate::ibl::environment("Studio Contrast", 256);
|
||||
let scene = TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0 }], Arc::new(env), 0.0);
|
||||
let d = TraceDisplay { exposure: 1.0, aces: true, env_opacity: 0.5, denoise: false };
|
||||
let settings = TraceSettings { bounces: 4 };
|
||||
let (_, _, gpu) = t.render(&h.device, &h.queue, &h.renderer, &scene, &camera(), &settings, &d, [48, 36], 1024).unwrap();
|
||||
let mut cpu = Tracer::new(48, 36);
|
||||
for _ in 0..1024 {
|
||||
cpu.pass(&scene, &camera(), &settings);
|
||||
}
|
||||
assert_region_means_match("varying roughness, default base color", &gpu, &cpu.rgba8(&d), 48, 36, 3.0);
|
||||
}
|
||||
|
||||
/// Mean luminance of each 6×6 block of two RGBA8 renders agrees within `tol` 8-bit levels.
|
||||
fn assert_region_means_match(name: &str, a: &[u8], b: &[u8], w: usize, h: usize, tol: f32) {
|
||||
let lum = |img: &[u8], x: usize, y: usize| {
|
||||
|
||||
@@ -18,8 +18,7 @@ pub struct EnvImage {
|
||||
pub data: Vec<[f32; 3]>,
|
||||
}
|
||||
|
||||
/// Built-in environments, in menu order.
|
||||
pub const ENVIRONMENTS: [&str; 6] = ["Studio Soft", "Studio Contrast", "Overcast", "Sunset", "Warehouse", "Night"];
|
||||
pub use texturecraft_core::project::ENVIRONMENTS;
|
||||
|
||||
pub fn dir_of(u: f32, v: f32) -> Vec3 {
|
||||
let (theta, phi) = (v * PI, u * TAU);
|
||||
|
||||
+235
-32
@@ -30,6 +30,7 @@ use texturecraft_geom::glam::{Mat4, Vec3};
|
||||
use texturecraft_geom::{Mesh, OrbitCamera};
|
||||
use texturecraft_texel::TILE;
|
||||
|
||||
use crate::gpu_trace::{Checked, checked};
|
||||
use crate::ibl;
|
||||
use crate::subdivide::{self, Vertex};
|
||||
|
||||
@@ -327,10 +328,67 @@ struct SetGpu {
|
||||
/// Display textures hold the set at `size >> shift`: halved until they fit the device.
|
||||
shift: u32,
|
||||
/// The display textures in [`DisplayKind::ALL`] order, then the aux (mesh map) texture.
|
||||
/// [`lazy`] kinds stay 1×1 until a tile with a non-default value arrives.
|
||||
/// Each starts as a 1×1 neutral placeholder and gets its full size with the first tile (or
|
||||
/// aux image) that holds something else, so a mesh with many materials costs no GPU memory
|
||||
/// until its sets are painted.
|
||||
tex: Vec<Tex>,
|
||||
bind_group: wgpu::BindGroup,
|
||||
mips_dirty: Vec<bool>,
|
||||
/// Textures whose full-size allocation failed (out of GPU memory): they keep their
|
||||
/// placeholder until the set is re-created, instead of retrying on every tile.
|
||||
failed: Vec<bool>,
|
||||
/// Full-size textures the browser's WebGPU has not yet confirmed: tiles go into them while
|
||||
/// the placeholder stays bound (see [`Renderer::resolve_pending`]).
|
||||
pending: Vec<Option<PendingTex>>,
|
||||
}
|
||||
|
||||
/// A full-size texture waiting for WebGPU's verdict on its allocation.
|
||||
struct PendingTex {
|
||||
tex: Tex,
|
||||
/// `None` for success, else what went wrong. (A mutex: the renderer is shared with the
|
||||
/// paint callback, so it must be `Sync`.)
|
||||
answer: std::sync::Mutex<std::sync::mpsc::Receiver<Option<String>>>,
|
||||
}
|
||||
|
||||
/// Swap `tex` in for slot `slot` of `set` (bound at once; its mips are rebuilt).
|
||||
fn install(set: &mut SetGpu, slot: usize, tex: Tex, device: &wgpu::Device, layout: &wgpu::BindGroupLayout, sampler: &wgpu::Sampler) {
|
||||
if let Some(s) = set.tex.get_mut(slot) {
|
||||
*s = tex;
|
||||
}
|
||||
set.bind_group = set_bind_group(device, layout, sampler, &set.tex);
|
||||
if let Some(d) = set.mips_dirty.get_mut(slot) {
|
||||
*d = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Give slot `slot` of `set` (texture set `ts`) the full-size texture `checked` allocated:
|
||||
/// installed when wgpu accepted it, kept pending while WebGPU has not answered, or (out of GPU
|
||||
/// memory) left as the placeholder with the failure recorded. False when there is nothing to
|
||||
/// write into.
|
||||
fn grow(
|
||||
set: &mut SetGpu,
|
||||
ts: usize,
|
||||
slot: usize,
|
||||
checked: Checked<Tex>,
|
||||
ctx: (&wgpu::Device, &wgpu::BindGroupLayout, &wgpu::Sampler),
|
||||
failures: &mut Vec<usize>,
|
||||
) -> bool {
|
||||
match checked {
|
||||
Checked::Done(Ok(full)) => install(set, slot, full, ctx.0, ctx.1, ctx.2),
|
||||
Checked::Done(Err(e)) => {
|
||||
if let Some(f) = set.failed.get_mut(slot) {
|
||||
*f = true;
|
||||
}
|
||||
memory_failed(failures, ts, &e);
|
||||
return false;
|
||||
}
|
||||
Checked::Later(tex, answer) => {
|
||||
if let Some(p) = set.pending.get_mut(slot) {
|
||||
*p = Some(PendingTex { tex, answer: std::sync::Mutex::new(answer) });
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Vertex and index buffers with their draws (first index, count, material).
|
||||
@@ -477,6 +535,9 @@ pub struct Renderer {
|
||||
black: wgpu::TextureView,
|
||||
/// [`DisplayKind::default_texel`] in [`DisplayKind::ALL`] order.
|
||||
default_texels: Vec<Vec<u8>>,
|
||||
/// Texture sets whose display textures could not be allocated (out of GPU memory) since
|
||||
/// [`Renderer::take_memory_failures`].
|
||||
memory_failures: Vec<usize>,
|
||||
accum_pipeline: wgpu::RenderPipeline,
|
||||
env: Tex,
|
||||
env_name: String,
|
||||
@@ -530,11 +591,8 @@ pub(crate) fn display_format(k: DisplayKind) -> wgpu::TextureFormat {
|
||||
}
|
||||
}
|
||||
|
||||
/// Textures of the optional lobe channels: most sets never use them, so they cost no memory or
|
||||
/// bandwidth (a 1×1 neutral texture) until painted.
|
||||
fn lazy(k: DisplayKind) -> bool {
|
||||
matches!(k, DisplayKind::Lobes | DisplayKind::Sheen | DisplayKind::Extra)
|
||||
}
|
||||
/// Texel of the aux texture before a mesh map or mask is shown.
|
||||
const AUX_NEUTRAL: [u8; 4] = [128, 128, 128, 255];
|
||||
|
||||
/// A `w × h` texture filled with `texel`.
|
||||
fn neutral_tex(device: &wgpu::Device, queue: &wgpu::Queue, (w, h): (u32, u32), format: wgpu::TextureFormat, mips: u32, texel: &[u8]) -> Tex {
|
||||
@@ -557,6 +615,14 @@ fn neutral_tex(device: &wgpu::Device, queue: &wgpu::Queue, (w, h): (u32, u32), f
|
||||
t
|
||||
}
|
||||
|
||||
/// Record that texture set `ts` could not get a display texture (`error` says which).
|
||||
fn memory_failed(failures: &mut Vec<usize>, ts: usize, error: &str) {
|
||||
log::warn!("cannot allocate the display texture of {error}");
|
||||
if !failures.contains(&ts) {
|
||||
failures.push(ts);
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes per write when filling a texture with one texel.
|
||||
const NEUTRAL_BAND_BYTES: usize = 8 << 20;
|
||||
|
||||
@@ -946,6 +1012,7 @@ impl Renderer {
|
||||
shadow,
|
||||
black,
|
||||
default_texels: DisplayKind::ALL.map(DisplayKind::default_texel).to_vec(),
|
||||
memory_failures: Vec::new(),
|
||||
env,
|
||||
env_name: String::new(),
|
||||
sh: [[0.0; 4]; 9],
|
||||
@@ -1068,20 +1135,13 @@ impl Renderer {
|
||||
if self.sets.get(i).is_some_and(|s| s.size == size && s.shift == shift) {
|
||||
continue;
|
||||
}
|
||||
let dims = display_dims(size, shift);
|
||||
let mut tex: Vec<Tex> = DisplayKind::ALL
|
||||
.iter()
|
||||
.zip(&self.default_texels)
|
||||
.map(|(k, texel)| {
|
||||
let (d, mips) = if lazy(*k) { ((1, 1), 1) } else { (dims, mip_count(dims.0.max(dims.1))) };
|
||||
neutral_tex(device, queue, d, display_format(*k), mips, texel)
|
||||
})
|
||||
.collect();
|
||||
let aux = aux_size(size);
|
||||
tex.push(neutral_tex(device, queue, (aux, aux), wgpu::TextureFormat::Rgba8Unorm, mip_count(aux), &[128, 128, 128, 255]));
|
||||
// Placeholders only: full-size textures come with the first non-neutral upload.
|
||||
let mut tex: Vec<Tex> =
|
||||
DisplayKind::ALL.iter().zip(&self.default_texels).map(|(k, texel)| neutral_tex(device, queue, (1, 1), display_format(*k), 1, texel)).collect();
|
||||
tex.push(neutral_tex(device, queue, (1, 1), wgpu::TextureFormat::Rgba8Unorm, 1, &AUX_NEUTRAL));
|
||||
let bind_group = set_bind_group(device, &self.set_bgl, &self.sampler, &tex);
|
||||
let n = tex.len();
|
||||
let gpu = SetGpu { size, shift, tex, bind_group, mips_dirty: vec![true; n] };
|
||||
let gpu = SetGpu { size, shift, tex, bind_group, mips_dirty: vec![true; n], failed: vec![false; n], pending: (0..n).map(|_| None).collect() };
|
||||
if i < self.sets.len() {
|
||||
self.sets[i] = gpu;
|
||||
} else {
|
||||
@@ -1110,18 +1170,24 @@ impl Renderer {
|
||||
return;
|
||||
}
|
||||
let dims = display_dims(set.size, set.shift);
|
||||
if t.texture.width() < dims.0 {
|
||||
// A lazy placeholder: neutral tiles change nothing, the first real one allocates it.
|
||||
if bytes.chunks_exact(texel.len()).all(|px| px == texel.as_slice()) {
|
||||
let awaiting = set.pending.get(ki).is_some_and(Option::is_some);
|
||||
if !awaiting && (t.texture.width() < dims.0 || t.texture.height() < dims.1) {
|
||||
// A placeholder: neutral tiles change nothing, the first real one allocates it.
|
||||
if set.failed.get(ki).copied().unwrap_or(true) || bytes.chunks_exact(texel.len()).all(|px| px == texel.as_slice()) {
|
||||
return;
|
||||
}
|
||||
let full = neutral_tex(device, queue, dims, display_format(kind), mip_count(dims.0.max(dims.1)), texel);
|
||||
if let Some(slot) = set.tex.get_mut(ki) {
|
||||
*slot = full;
|
||||
let what = format!("texture set {} ({kind:?}, {}×{})", ts + 1, dims.0, dims.1);
|
||||
let full = checked(device, &what, || neutral_tex(device, queue, dims, display_format(kind), mip_count(dims.0.max(dims.1)), texel));
|
||||
if !grow(set, ts, ki, full, (device, &self.set_bgl, &self.sampler), &mut self.memory_failures) {
|
||||
return;
|
||||
}
|
||||
set.bind_group = set_bind_group(device, &self.set_bgl, &self.sampler, &set.tex);
|
||||
}
|
||||
let Some(t) = set.tex.get(ki) else { return };
|
||||
// While WebGPU has not confirmed the full-size texture, tiles go into it (its errors, if
|
||||
// it is invalid, are dropped with these scopes) and the placeholder stays bound.
|
||||
let pending = set.pending.get(ki).and_then(Option::as_ref).map(|p| &p.tex);
|
||||
let Some(t) = pending.or(set.tex.get(ki)) else { return };
|
||||
let oom = pending.is_some().then(|| device.push_error_scope(wgpu::ErrorFilter::OutOfMemory));
|
||||
let invalid = pending.is_some().then(|| device.push_error_scope(wgpu::ErrorFilter::Validation));
|
||||
// Downscaled sets take every `step`-th texel of the tile.
|
||||
let (step, n) = (1usize << set.shift.min(6), TILE >> set.shift.min(6));
|
||||
let small: Vec<u8>;
|
||||
@@ -1143,33 +1209,96 @@ impl Renderer {
|
||||
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(n * bpt), rows_per_image: Some(n) },
|
||||
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
);
|
||||
// Innermost scope first.
|
||||
drop(invalid);
|
||||
drop(oom);
|
||||
self.content_rev += 1;
|
||||
if let Some(d) = set.mips_dirty.get_mut(ki) {
|
||||
*d = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Upload the aux (mesh map / debug) texture of a set: RGBA8, `size × size`.
|
||||
pub fn upload_aux(&mut self, queue: &wgpu::Queue, ts: usize, size: u32, rgba: &[u8]) {
|
||||
/// Upload the aux (mesh map / debug) texture of a set: RGBA8, `size × size` with `size` from
|
||||
/// [`aux_size`]. The first upload allocates it.
|
||||
pub fn upload_aux(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, ts: usize, size: u32, rgba: &[u8]) {
|
||||
let Some(set) = self.sets.get_mut(ts) else { return };
|
||||
let want = aux_size(set.size);
|
||||
let ai = set.tex.len().saturating_sub(1);
|
||||
let Some(t) = set.tex.last() else { return };
|
||||
let (w, h) = (t.texture.width(), t.texture.height());
|
||||
if size != w || rgba.len() < (w * h * 4) as usize {
|
||||
if size != want || rgba.len() < (size as usize) * (size as usize) * 4 {
|
||||
return;
|
||||
}
|
||||
let awaiting = set.pending.get(ai).is_some_and(Option::is_some);
|
||||
if !awaiting && t.texture.width() != size {
|
||||
if set.failed.get(ai).copied().unwrap_or(true) {
|
||||
return;
|
||||
}
|
||||
let what = format!("texture set {} (mesh map view, {size}×{size})", ts + 1);
|
||||
let full = checked(device, &what, || neutral_tex(device, queue, (size, size), wgpu::TextureFormat::Rgba8Unorm, mip_count(size), &AUX_NEUTRAL));
|
||||
if !grow(set, ts, ai, full, (device, &self.set_bgl, &self.sampler), &mut self.memory_failures) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let pending = set.pending.get(ai).and_then(Option::as_ref).map(|p| &p.tex);
|
||||
let Some(t) = pending.or(set.tex.last()) else { return };
|
||||
let (w, h) = (t.texture.width(), t.texture.height());
|
||||
let oom = pending.is_some().then(|| device.push_error_scope(wgpu::ErrorFilter::OutOfMemory));
|
||||
let invalid = pending.is_some().then(|| device.push_error_scope(wgpu::ErrorFilter::Validation));
|
||||
queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo { texture: &t.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
rgba,
|
||||
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 4), rows_per_image: Some(h) },
|
||||
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
);
|
||||
drop(invalid);
|
||||
drop(oom);
|
||||
self.content_rev += 1;
|
||||
if let Some(d) = set.mips_dirty.last_mut() {
|
||||
*d = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Size of the aux texture of a set.
|
||||
/// Texture sets whose display textures could not be allocated since the last call (out of
|
||||
/// GPU memory: they show neutral values where they could not be allocated).
|
||||
pub fn take_memory_failures(&mut self) -> Vec<usize> {
|
||||
std::mem::take(&mut self.memory_failures)
|
||||
}
|
||||
|
||||
/// Whether a full-size texture still waits for WebGPU's verdict: keep drawing frames, since
|
||||
/// [`Renderer::prepare`] installs it (or reports the failure) once the answer is in.
|
||||
pub fn awaiting_gpu(&self) -> bool {
|
||||
self.sets.iter().any(|s| s.pending.iter().any(Option::is_some))
|
||||
}
|
||||
|
||||
/// Install the pending full-size textures WebGPU accepted; drop the ones it rejected (their
|
||||
/// placeholder stays and the failure is reported).
|
||||
fn resolve_pending(&mut self, device: &wgpu::Device) {
|
||||
for (ts, set) in self.sets.iter_mut().enumerate() {
|
||||
for slot in 0..set.pending.len() {
|
||||
let poll = |p: &PendingTex| p.answer.lock().unwrap_or_else(std::sync::PoisonError::into_inner).try_recv();
|
||||
let verdict = match set.pending.get(slot).and_then(Option::as_ref).map(poll) {
|
||||
None | Some(Err(std::sync::mpsc::TryRecvError::Empty)) => continue,
|
||||
Some(Ok(v)) => v,
|
||||
Some(Err(std::sync::mpsc::TryRecvError::Disconnected)) => Some(format!("texture set {}: the GPU never answered", ts + 1)),
|
||||
};
|
||||
let Some(p) = set.pending.get_mut(slot).and_then(Option::take) else { continue };
|
||||
match verdict {
|
||||
None => {
|
||||
install(set, slot, p.tex, device, &self.set_bgl, &self.sampler);
|
||||
self.content_rev += 1;
|
||||
}
|
||||
Some(e) => {
|
||||
if let Some(f) = set.failed.get_mut(slot) {
|
||||
*f = true;
|
||||
}
|
||||
memory_failed(&mut self.memory_failures, ts, &e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Size of the aux texture of a set (1 until a mesh map or mask was shown).
|
||||
pub fn aux_size(&self, ts: usize) -> Option<u32> {
|
||||
self.sets.get(ts).and_then(|s| s.tex.last()).map(|t| t.texture.width())
|
||||
}
|
||||
@@ -1490,6 +1619,7 @@ impl Renderer {
|
||||
/// `shade.taa` that repeats the previous one adds a jittered sample to the average instead,
|
||||
/// and renders nothing once [`TAA_SAMPLES`] are in.
|
||||
pub fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, frame: &Frame) {
|
||||
self.resolve_pending(device);
|
||||
self.generate_mips(device, encoder);
|
||||
let rev = self.content_rev;
|
||||
let sample = match self.views.get(&frame.view_id) {
|
||||
@@ -1584,7 +1714,7 @@ impl Renderer {
|
||||
b: [fx(s.vignette), fx(s.sharpen), fx(s.grain), BLOOM_THRESHOLD],
|
||||
c: dof_c,
|
||||
d: sss_d,
|
||||
e: [flag(cam.ortho), 0.0, 0.0, 0.0],
|
||||
e: [flag(cam.ortho), sample as f32, 0.0, 0.0],
|
||||
};
|
||||
let Some(v) = self.targets(device, frame.view_id, frame.size, bloom, fx_on, refraction) else { return };
|
||||
queue.write_buffer(&v.globals, 0, bytemuck::bytes_of(&raw));
|
||||
@@ -1832,3 +1962,76 @@ impl Renderer {
|
||||
self.views.remove(&id);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::headless::Headless;
|
||||
|
||||
/// A headless renderer with one 256² texture set, and the base color slot's full-size
|
||||
/// texture handed over as WebGPU would: allocated, with its verdict still to come.
|
||||
fn awaiting() -> Option<(Headless, std::sync::mpsc::Sender<Option<String>>)> {
|
||||
let Ok(mut h) = Headless::new() else {
|
||||
eprintln!("skipping: no GPU adapter");
|
||||
return None;
|
||||
};
|
||||
h.renderer.set_texture_sets(&h.device, &h.queue, &[((256, 256), 0)], 1);
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let full = neutral_tex(&h.device, &h.queue, (256, 256), display_format(DisplayKind::BaseColor), mip_count(256), &[0, 0, 0, 255]);
|
||||
let r = &mut h.renderer;
|
||||
let set = r.sets.get_mut(0).unwrap();
|
||||
assert!(grow(set, 0, 0, Checked::Later(full, rx), (&h.device, &r.set_bgl, &r.sampler), &mut r.memory_failures));
|
||||
Some((h, tx))
|
||||
}
|
||||
|
||||
fn base_width(h: &Headless) -> u32 {
|
||||
h.renderer.display_textures()[0][0].width()
|
||||
}
|
||||
|
||||
fn prepare(h: &mut Headless) {
|
||||
let mut enc = h.device.create_command_encoder(&Default::default());
|
||||
h.renderer.resolve_pending(&h.device);
|
||||
h.renderer.generate_mips(&h.device, &mut enc);
|
||||
h.queue.submit([enc.finish()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_late_texture_stays_unbound_until_accepted() {
|
||||
let Some((mut h, tx)) = awaiting() else { return };
|
||||
assert!(h.renderer.awaiting_gpu());
|
||||
// Tiles go into the pending texture; the placeholder stays bound and nothing is retried.
|
||||
h.renderer.upload_tile(&h.device, &h.queue, 0, DisplayKind::BaseColor, 0, 0, &[200, 30, 30, 255].repeat(64 * 64));
|
||||
prepare(&mut h);
|
||||
assert_eq!(base_width(&h), 1, "no verdict yet: the placeholder stays bound");
|
||||
assert!(h.renderer.awaiting_gpu());
|
||||
tx.send(None).unwrap();
|
||||
prepare(&mut h);
|
||||
assert_eq!(base_width(&h), 256, "accepted: installed");
|
||||
assert!(!h.renderer.awaiting_gpu());
|
||||
assert!(h.renderer.take_memory_failures().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_late_rejection_keeps_the_placeholder_and_is_reported() {
|
||||
let Some((mut h, tx)) = awaiting() else { return };
|
||||
tx.send(Some("texture set 1 (BaseColor, 256×256): Out of Memory".into())).unwrap();
|
||||
prepare(&mut h);
|
||||
assert_eq!(base_width(&h), 1);
|
||||
assert!(!h.renderer.awaiting_gpu());
|
||||
assert_eq!(h.renderer.take_memory_failures(), vec![0]);
|
||||
// The failed kind is not allocated again by later tiles.
|
||||
h.renderer.upload_tile(&h.device, &h.queue, 0, DisplayKind::BaseColor, 1, 0, &[200, 30, 30, 255].repeat(64 * 64));
|
||||
prepare(&mut h);
|
||||
assert_eq!(base_width(&h), 1);
|
||||
assert!(!h.renderer.awaiting_gpu());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_verdict_that_never_comes_counts_as_a_failure() {
|
||||
let Some((mut h, tx)) = awaiting() else { return };
|
||||
drop(tx);
|
||||
prepare(&mut h);
|
||||
assert_eq!(base_width(&h), 1);
|
||||
assert_eq!(h.renderer.take_memory_failures(), vec![0]);
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,8 @@ fn texel_at(t: texture_2d<f32>, p: vec2<f32>) -> vec4<f32> {
|
||||
|
||||
// ---- Subsurface scattering: a separable bilateral blur (Jimenez et al., "Separable Subsurface
|
||||
// Scattering", 2015) of the scattering diffuse light, a Gaussian per color channel as wide as
|
||||
// its mean free path, cut off across depth discontinuities.
|
||||
// its mean free path. A tap across a depth discontinuity (or off the mesh) takes the centre's
|
||||
// light instead, so no tap drops out of the sum as it crosses a silhouette.
|
||||
|
||||
const SSS_TAPS: i32 = 8;
|
||||
|
||||
@@ -41,17 +42,22 @@ fn sss_blur(p: vec2<f32>, dir: vec2<f32>) -> vec4<f32> {
|
||||
let stride = dir * (smax * 3.0 / f32(SSS_TAPS));
|
||||
let depth_range = 3.0 * max(post.d.x, max(post.d.y, post.d.z));
|
||||
let inv = 1.0 / (2.0 * sigma * sigma + vec3<f32>(1e-4));
|
||||
// Wide blurs space their taps pixels apart: shifting them per pixel (interleaved gradient
|
||||
// noise) and per accumulated frame turns what would show as copies of edges into fine grain.
|
||||
let ign = fract(52.9829189 * fract(dot(p, vec2<f32>(0.06711056, 0.00583715))));
|
||||
let jitter = fract(ign + post.e.y * 0.618034) - 0.5;
|
||||
var sum = c.rgb;
|
||||
var wsum = vec3<f32>(1.0);
|
||||
for (var k = -SSS_TAPS; k <= SSS_TAPS; k++) {
|
||||
if (k == 0) {
|
||||
continue;
|
||||
}
|
||||
let t = texel_at(src, p + stride * f32(k));
|
||||
let x = f32(k) * smax * 3.0 / f32(SSS_TAPS);
|
||||
let o = f32(k) + jitter;
|
||||
let t = texel_at(src, p + stride * o);
|
||||
let x = o * smax * 3.0 / f32(SSS_TAPS);
|
||||
let wd = select(0.0, max(1.0 - abs(t.a - c.a) / depth_range, 0.0), t.a > 0.0);
|
||||
let w = exp(-x * x * inv) * wd;
|
||||
sum += t.rgb * w;
|
||||
let w = exp(-x * x * inv);
|
||||
sum += mix(c.rgb, t.rgb, wd) * w;
|
||||
wsum += w;
|
||||
}
|
||||
return vec4<f32>(sum / wsum, c.a);
|
||||
|
||||
@@ -7,7 +7,7 @@ struct Post {
|
||||
b: vec4<f32>, // x vignette, y sharpen, z grain, w bloom threshold
|
||||
c: vec4<f32>, // depth of field (fx.wgsl): x circle of confusion at infinity (pixels), y focus depth, z largest circle radius (pixels), w accumulation sample
|
||||
d: vec4<f32>, // subsurface blur (fx.wgsl): xyz mean free path per channel (world units), w pixels per world unit at depth 1
|
||||
e: vec4<f32>, // x orthographic camera (1: pixels per world unit don't fall off with depth), yzw -
|
||||
e: vec4<f32>, // x orthographic camera (1: pixels per world unit don't fall off with depth), y accumulation sample, zw -
|
||||
};
|
||||
|
||||
@group(0) @binding(3) var<uniform> post: Post;
|
||||
|
||||
@@ -734,3 +734,47 @@ fn refraction_shows_the_scene_behind_transmissive_surfaces() {
|
||||
let frosted = render(&mut h, &refr, "refr_frosted_checker");
|
||||
assert!(detail(&frosted, &ball) < detail(&clear, &ball), "frosted glass blurs the scene behind");
|
||||
}
|
||||
|
||||
/// Kinds in [`DisplayKind::ALL`] order with each set's display texture widths, then the aux width.
|
||||
fn widths(h: &Headless) -> Vec<Vec<u32>> {
|
||||
h.renderer.display_textures().iter().map(|s| s.iter().map(|t| t.width()).collect()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn texture_sets_take_no_gpu_memory_until_painted() {
|
||||
// A mesh with many materials (one texture set each) must not reserve full-size textures
|
||||
// for every set up front: that ran a 4 GB GPU out of memory, and wgpu's handler aborted.
|
||||
let Some((mut h, _)) = setup() else { return };
|
||||
let sets: Vec<((u32, u32), usize)> = (0..40).map(|m| ((2048, 2048), m)).collect();
|
||||
h.renderer.set_texture_sets(&h.device, &h.queue, &sets, 40);
|
||||
assert!(widths(&h).iter().flatten().all(|w| *w == 1), "every display texture starts as a 1×1 placeholder");
|
||||
assert!((0..40).all(|ts| h.renderer.aux_size(ts) == Some(1)), "so does every aux texture");
|
||||
// A neutral tile changes nothing; the first painted one allocates that kind alone.
|
||||
let kind = DisplayKind::BaseColor;
|
||||
let neutral = kind.default_texel().repeat(64 * 64);
|
||||
h.renderer.upload_tile(&h.device, &h.queue, 3, kind, 0, 0, &neutral);
|
||||
assert_eq!(widths(&h)[3][0], 1);
|
||||
h.renderer.upload_tile(&h.device, &h.queue, 3, kind, 0, 0, &[200, 30, 30, 255].repeat(64 * 64));
|
||||
let w = widths(&h);
|
||||
assert_eq!(w[3][0], 2048, "the painted kind is full size");
|
||||
assert!(w[3][1..].iter().all(|w| *w == 1) && w[2].iter().all(|w| *w == 1), "nothing else was allocated");
|
||||
// The aux texture is allocated by its first upload, at the set's aux size only.
|
||||
h.renderer.upload_aux(&h.device, &h.queue, 3, 512, &[0; 512 * 512 * 4]);
|
||||
assert_eq!(h.renderer.aux_size(3), Some(1), "a wrong aux size is ignored");
|
||||
h.renderer.upload_aux(&h.device, &h.queue, 3, 2048, &[90; 2048 * 2048 * 4]);
|
||||
assert_eq!(h.renderer.aux_size(3), Some(2048));
|
||||
assert!(h.renderer.take_memory_failures().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn painted_placeholders_render_like_full_textures() {
|
||||
// A set painted in one kind renders that paint whether the other kinds are placeholders.
|
||||
let Some((mut h, frame)) = setup() else { return };
|
||||
let before = render(&mut h, &frame, "placeholders");
|
||||
fill(&mut h, &[0, 1], DisplayKind::BaseColor, &[220, 40, 40, 255]);
|
||||
let red = render(&mut h, &frame, "painted_base_color");
|
||||
let (w, hgt) = (frame.size[0], frame.size[1]);
|
||||
let [r0, g0, _] = before.at(w / 2, hgt / 2);
|
||||
let [r1, g1, _] = red.at(w / 2, hgt / 2);
|
||||
assert!(r1 > r0 && g1 < g0, "the painted base color shows: {:?} → {:?}", before.at(w / 2, hgt / 2), red.at(w / 2, hgt / 2));
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
//! Built-in colour spaces as plain maths: sRGB, linear Rec.709, ACEScg and ACES2065-1.
|
||||
//!
|
||||
//! The conversion matrices are derived at first use from the published primaries and white points
|
||||
//! (ITU-R BT.709, ACES S-2014-004 for AP1, SMPTE ST 2065-1 for AP0) with Bradford chromatic
|
||||
//! adaptation, so nothing is copied from a colour-management library. TextureCraft's colour
|
||||
//! channels are linear Rec.709 internally; this module converts them for export.
|
||||
//!
|
||||
//! Only colour is converted. Data (normal, height, roughness...) has no colour space and never
|
||||
//! goes through here.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use crate::linear_to_srgb;
|
||||
|
||||
/// The colour space of exported colour images.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum ColorSpace {
|
||||
/// sRGB-encoded (display-referred, 0–1), Rec.709 primaries.
|
||||
#[default]
|
||||
Srgb,
|
||||
/// Scene-linear Rec.709 / sRGB primaries, D65.
|
||||
LinearRec709,
|
||||
/// Scene-linear ACES AP1 primaries.
|
||||
AcesCg,
|
||||
/// Scene-linear ACES AP0 primaries (the archival interchange space).
|
||||
Aces2065,
|
||||
}
|
||||
|
||||
impl ColorSpace {
|
||||
pub const ALL: [ColorSpace; 4] = [ColorSpace::Srgb, ColorSpace::LinearRec709, ColorSpace::AcesCg, ColorSpace::Aces2065];
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
ColorSpace::Srgb => "sRGB",
|
||||
ColorSpace::LinearRec709 => "Linear Rec.709",
|
||||
ColorSpace::AcesCg => "ACEScg",
|
||||
ColorSpace::Aces2065 => "ACES2065-1",
|
||||
}
|
||||
}
|
||||
|
||||
/// A space by name, ignoring case, spaces and punctuation ("linear rec709", "ap1", "srgb_texture").
|
||||
pub fn from_name(name: &str) -> Option<ColorSpace> {
|
||||
let key: String = name.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();
|
||||
Some(match key.as_str() {
|
||||
"srgb" | "srgbtexture" => ColorSpace::Srgb,
|
||||
"linearrec709" | "linearsrgb" | "linear" | "rec709" => ColorSpace::LinearRec709,
|
||||
"acescg" | "ap1" => ColorSpace::AcesCg,
|
||||
"aces20651" | "aces2065" | "ap0" | "aces" => ColorSpace::Aces2065,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether values are scene-linear light.
|
||||
pub fn is_linear(self) -> bool {
|
||||
self != ColorSpace::Srgb
|
||||
}
|
||||
|
||||
fn primaries(self) -> Primaries {
|
||||
match self {
|
||||
ColorSpace::Srgb | ColorSpace::LinearRec709 => REC709,
|
||||
ColorSpace::AcesCg => AP1,
|
||||
ColorSpace::Aces2065 => AP0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Linear Rec.709 `rgb` as values in this space: the primaries are converted, and sRGB
|
||||
/// also gets its transfer curve (clamped to 0–1). Linear spaces keep values outside 0–1.
|
||||
/// Non-finite input becomes 0.
|
||||
pub fn from_linear_rec709(self, rgb: [f32; 3]) -> [f32; 3] {
|
||||
let rgb = rgb.map(|v| if v.is_finite() { v } else { 0.0 });
|
||||
let out = match matrix_to(self) {
|
||||
Some(m) => [0, 1, 2].map(|i| m[i][0] * rgb[0] + m[i][1] * rgb[1] + m[i][2] * rgb[2]),
|
||||
None => rgb,
|
||||
};
|
||||
if self == ColorSpace::Srgb { out.map(linear_to_srgb) } else { out }
|
||||
}
|
||||
}
|
||||
|
||||
type M3 = [[f64; 3]; 3];
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Primaries {
|
||||
r: [f64; 2],
|
||||
g: [f64; 2],
|
||||
b: [f64; 2],
|
||||
white: [f64; 2],
|
||||
}
|
||||
|
||||
const D65: [f64; 2] = [0.3127, 0.3290];
|
||||
const D60_ACES: [f64; 2] = [0.32168, 0.33767];
|
||||
const REC709: Primaries = Primaries { r: [0.640, 0.330], g: [0.300, 0.600], b: [0.150, 0.060], white: D65 };
|
||||
const AP1: Primaries = Primaries { r: [0.713, 0.293], g: [0.165, 0.830], b: [0.128, 0.044], white: D60_ACES };
|
||||
const AP0: Primaries = Primaries { r: [0.7347, 0.2653], g: [0.0, 1.0], b: [0.0001, -0.0770], white: D60_ACES };
|
||||
|
||||
const BRADFORD: M3 = [[0.8951, 0.2664, -0.1614], [-0.7502, 1.7135, 0.0367], [0.0389, -0.0685, 1.0296]];
|
||||
|
||||
fn mul(a: &M3, b: &M3) -> M3 {
|
||||
let mut o = [[0.0; 3]; 3];
|
||||
for (i, row) in o.iter_mut().enumerate() {
|
||||
for (j, v) in row.iter_mut().enumerate() {
|
||||
*v = (0..3).map(|k| a[i][k] * b[k][j]).sum();
|
||||
}
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
fn apply(m: &M3, v: [f64; 3]) -> [f64; 3] {
|
||||
[0, 1, 2].map(|i| m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2])
|
||||
}
|
||||
|
||||
fn inverse(m: &M3) -> Option<M3> {
|
||||
let c = |r: usize, c: usize| {
|
||||
let (r1, r2) = ((r + 1) % 3, (r + 2) % 3);
|
||||
let (c1, c2) = ((c + 1) % 3, (c + 2) % 3);
|
||||
m[r1][c1] * m[r2][c2] - m[r1][c2] * m[r2][c1]
|
||||
};
|
||||
let det = m[0][0] * c(0, 0) + m[0][1] * c(0, 1) + m[0][2] * c(0, 2);
|
||||
if det.abs() < 1e-12 || !det.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let mut o = [[0.0; 3]; 3];
|
||||
for (i, row) in o.iter_mut().enumerate() {
|
||||
for (j, v) in row.iter_mut().enumerate() {
|
||||
*v = c(j, i) / det;
|
||||
}
|
||||
}
|
||||
Some(o)
|
||||
}
|
||||
|
||||
fn xy_to_xyz(xy: [f64; 2]) -> [f64; 3] {
|
||||
[xy[0] / xy[1], 1.0, (1.0 - xy[0] - xy[1]) / xy[1]]
|
||||
}
|
||||
|
||||
/// RGB (linear) to XYZ for a set of primaries, scaled so white maps to the white point.
|
||||
fn rgb_to_xyz(p: &Primaries) -> Option<M3> {
|
||||
let (r, g, b) = (xy_to_xyz(p.r), xy_to_xyz(p.g), xy_to_xyz(p.b));
|
||||
let cols = [[r[0], g[0], b[0]], [r[1], g[1], b[1]], [r[2], g[2], b[2]]];
|
||||
let s = apply(&inverse(&cols)?, xy_to_xyz(p.white));
|
||||
Some([[r[0] * s[0], g[0] * s[1], b[0] * s[2]], [r[1] * s[0], g[1] * s[1], b[1] * s[2]], [r[2] * s[0], g[2] * s[1], b[2] * s[2]]])
|
||||
}
|
||||
|
||||
/// Bradford chromatic adaptation from one white point to another.
|
||||
fn adapt(from: [f64; 2], to: [f64; 2]) -> Option<M3> {
|
||||
let (cs, cd) = (apply(&BRADFORD, xy_to_xyz(from)), apply(&BRADFORD, xy_to_xyz(to)));
|
||||
let scale = [[cd[0] / cs[0], 0.0, 0.0], [0.0, cd[1] / cs[1], 0.0], [0.0, 0.0, cd[2] / cs[2]]];
|
||||
Some(mul(&inverse(&BRADFORD)?, &mul(&scale, &BRADFORD)))
|
||||
}
|
||||
|
||||
/// The matrix from linear Rec.709 to the linear primaries of `to` (cached).
|
||||
fn matrix_to(to: ColorSpace) -> Option<[[f32; 3]; 3]> {
|
||||
static CACHE: OnceLock<[Option<[[f32; 3]; 3]>; 4]> = OnceLock::new();
|
||||
let table = CACHE.get_or_init(|| {
|
||||
ColorSpace::ALL.map(|s| {
|
||||
let (from, to) = (REC709, s.primaries());
|
||||
let m = mul(&inverse(&rgb_to_xyz(&to)?)?, &mul(&adapt(from.white, to.white)?, &rgb_to_xyz(&from)?));
|
||||
Some(m.map(|r| r.map(|v| v as f32)))
|
||||
})
|
||||
});
|
||||
let i = ColorSpace::ALL.iter().position(|s| *s == to)?;
|
||||
table.get(i).copied().flatten()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::srgb_to_linear;
|
||||
|
||||
fn close(a: [f32; 3], b: [f32; 3], tol: f32) -> bool {
|
||||
a.iter().zip(b).all(|(x, y)| (x - y).abs() <= tol)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn white_stays_white_in_every_linear_space() {
|
||||
for s in [ColorSpace::LinearRec709, ColorSpace::AcesCg, ColorSpace::Aces2065] {
|
||||
assert!(close(s.from_linear_rec709([1.0; 3]), [1.0; 3], 1e-4), "{s:?}");
|
||||
}
|
||||
assert!(close(ColorSpace::Srgb.from_linear_rec709([1.0; 3]), [1.0; 3], 1e-5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rec709_primaries_in_acescg_match_published_values() {
|
||||
// Rec.709 red in ACEScg (AP1, D60): the widely published 0.6131 0.0702 0.0206.
|
||||
assert!(close(ColorSpace::AcesCg.from_linear_rec709([1.0, 0.0, 0.0]), [0.6131, 0.0702, 0.0206], 2e-3));
|
||||
// And in ACES2065-1 (AP0): 0.4397 0.0897 0.0175.
|
||||
assert!(close(ColorSpace::Aces2065.from_linear_rec709([1.0, 0.0, 0.0]), [0.4397, 0.0897, 0.0175], 2e-3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grey_stays_neutral_and_srgb_is_the_transfer_curve() {
|
||||
for s in ColorSpace::ALL {
|
||||
let o = s.from_linear_rec709([0.18; 3]);
|
||||
assert!(close(o, [o[0]; 3], 1e-4), "{s:?} {o:?}");
|
||||
}
|
||||
assert!(close(ColorSpace::Srgb.from_linear_rec709([0.5; 3]), [linear_to_srgb(0.5); 3], 1e-6));
|
||||
assert!((srgb_to_linear(ColorSpace::Srgb.from_linear_rec709([0.25; 3])[0]) - 0.25).abs() < 1e-5);
|
||||
assert_eq!(ColorSpace::LinearRec709.from_linear_rec709([0.3, 2.0, -1.0]), [0.3, 2.0, -1.0], "linear Rec.709 is the identity, values above 1 kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_values_stay_finite() {
|
||||
for s in ColorSpace::ALL {
|
||||
assert!(s.from_linear_rec709([f32::NAN, f32::INFINITY, f32::NEG_INFINITY]).iter().all(|v| v.is_finite()), "{s:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_round_trip_and_aliases_work() {
|
||||
for s in ColorSpace::ALL {
|
||||
assert_eq!(ColorSpace::from_name(s.name()), Some(s));
|
||||
}
|
||||
assert_eq!(ColorSpace::from_name("srgb_texture"), Some(ColorSpace::Srgb));
|
||||
assert_eq!(ColorSpace::from_name("AP1"), Some(ColorSpace::AcesCg));
|
||||
assert_eq!(ColorSpace::from_name("linear"), Some(ColorSpace::LinearRec709));
|
||||
assert_eq!(ColorSpace::from_name("nope"), None);
|
||||
assert!(!ColorSpace::Srgb.is_linear() && ColorSpace::AcesCg.is_linear());
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,12 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod colorspace;
|
||||
pub mod dilate;
|
||||
pub mod noise;
|
||||
pub mod tile;
|
||||
|
||||
pub use colorspace::ColorSpace;
|
||||
pub use dilate::DilationMap;
|
||||
pub use tile::{TILE, TILE_AREA, TileData, TileImage, from_u16, from_u16_signed, to_u16, to_u16_signed};
|
||||
|
||||
|
||||
+229
-40
@@ -5,7 +5,7 @@ use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2};
|
||||
use egui_phosphor::regular as ic;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{
|
||||
BakedMap, BlendMode, Channel, Decal, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, ProceduralKind, Source,
|
||||
BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, ProceduralKind, Source,
|
||||
};
|
||||
use texturecraft_engine::filter_lib::{FILTERS, scalar_params};
|
||||
use texturecraft_engine::paint::{BrushAlpha, alphas};
|
||||
@@ -16,7 +16,7 @@ use crate::i18n::{n_, tr, trf};
|
||||
use crate::shelf::{Asset, ShelfDrag};
|
||||
use crate::state::PropsTab;
|
||||
use crate::theme::{Tokens, caption};
|
||||
use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, section, slider};
|
||||
use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, slider, slider_edit};
|
||||
|
||||
const TAG_COLORS: [Color32; 8] = [
|
||||
Color32::from_rgb(0xc0, 0x40, 0x40),
|
||||
@@ -47,6 +47,23 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
})
|
||||
.collect();
|
||||
let active = app.session.ts();
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
ui.menu_button(RichText::new(ic::EYE).size(14.0), |ui| {
|
||||
for (label, mode) in [(tr("Show all"), "showAll"), (tr("Hide all"), "hideAll"), (tr("Invert show/hide"), "invert")] {
|
||||
if ui.button(label).clicked() {
|
||||
app.run("textureSet.visibility", json!({ "mode": mode }));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
.on_hover_text(tr("Show or hide texture sets"));
|
||||
let solo = sets.iter().enumerate().all(|(i, s)| s.2 == (i == active));
|
||||
if icon_button(ui, ic::FRAME_CORNERS, tr("Focus: show only the active texture set"), solo && sets.len() > 1, 22.0).clicked() {
|
||||
app.run("textureSet.visibility", json!({ "mode": "solo" }));
|
||||
}
|
||||
});
|
||||
egui::ScrollArea::vertical().id_salt("ts_scroll").show(ui, |ui| {
|
||||
for (i, (name, size, visible)) in sets.into_iter().enumerate() {
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
|
||||
@@ -238,11 +255,11 @@ fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize)
|
||||
let Some(layer) = app.session.doc.project.layers.get(&id).cloned() else { return };
|
||||
layer_row(app, ui, &layer, depth);
|
||||
for e in layer.content_effects.iter().rev() {
|
||||
effect_row(app, ui, &layer, e.id, &e.name, e.visible, depth + 1, ic::SPHERE);
|
||||
effect_row(app, ui, &layer, &layer.content_effects, e, depth + 1, ic::SPHERE);
|
||||
}
|
||||
if let Some(m) = &layer.mask {
|
||||
for e in m.effects.iter().rev() {
|
||||
effect_row(app, ui, &layer, e.id, &e.name, e.visible, depth + 1, ic::MAGIC_WAND);
|
||||
effect_row(app, ui, &layer, &m.effects, e, depth + 1, ic::MAGIC_WAND);
|
||||
}
|
||||
}
|
||||
if let LayerKind::Group { children, collapsed } = &layer.kind
|
||||
@@ -260,6 +277,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
|
||||
let selected = app.session.selected_layer() == Some(layer.id);
|
||||
let h = 38.0;
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag());
|
||||
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &layer.name));
|
||||
let p = ui.painter().clone();
|
||||
let bg = if selected && app.session.target == StackTarget::Content {
|
||||
tk.row_selected
|
||||
@@ -504,12 +522,16 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
|
||||
resp.context_menu(|ui| layer_context_menu(app, ui, layer));
|
||||
}
|
||||
|
||||
/// One effect of a layer's content (`glyph` sphere) or mask (`glyph` wand) stack.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId, name: &str, visible: bool, depth: usize, glyph: &str) {
|
||||
/// The drag-and-drop payload of an effect row (the effect id).
|
||||
struct EffectDrag(u64);
|
||||
|
||||
/// Effect `e` of `stack`, a layer's content (`glyph` sphere) or mask (`glyph` wand) effects.
|
||||
fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, depth: usize, glyph: &str) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let (eid, visible) = (e.id, e.visible);
|
||||
let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(eid);
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag());
|
||||
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &e.name));
|
||||
let p = ui.painter().clone();
|
||||
p.rect_filled(
|
||||
rect.shrink2(vec2(0.0, 1.0)),
|
||||
@@ -530,16 +552,55 @@ fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerI
|
||||
let er = ui.interact(eye, ui.scope_id().with(("eff_eye", eid.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect"));
|
||||
p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(12.0), tk.text_dim);
|
||||
p.text(pos2(x0 + 22.0, rect.center().y), egui::Align2::LEFT_CENTER, glyph, egui::FontId::proportional(11.0), tk.text_dim);
|
||||
p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(11.5), tk.text);
|
||||
p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, &e.name, egui::FontId::proportional(11.5), tk.text);
|
||||
if er.clicked() {
|
||||
app.run("effect.set", json!({"effect": eid.0, "visible": !visible}));
|
||||
} else if resp.clicked() {
|
||||
app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0}));
|
||||
}
|
||||
// Drag to reorder within the stack: a drop lands above this row, or below it from its lower half.
|
||||
if resp.drag_started() {
|
||||
resp.dnd_set_drag_payload(EffectDrag(eid.0));
|
||||
}
|
||||
let pos = |id: u64| stack.iter().position(|x| x.id.0 == id);
|
||||
let below = ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| p.y > rect.center().y);
|
||||
if resp.dnd_hover_payload::<EffectDrag>().is_some_and(|src| src.0 != eid.0 && pos(src.0).is_some()) {
|
||||
let y = if below { rect.bottom() } else { rect.top() };
|
||||
p.line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(2.0, tk.accent));
|
||||
}
|
||||
if let Some(src) = dnd_release::<EffectDrag>(&resp)
|
||||
&& let (Some(from), Some(to)) = (pos(src.0), pos(eid.0))
|
||||
&& from != to
|
||||
{
|
||||
// Rows list the stack top first, so above this row is the next index up.
|
||||
let index = match (from < to, below) {
|
||||
(true, false) | (false, true) => to,
|
||||
(true, true) => to - 1,
|
||||
(false, false) => to + 1,
|
||||
};
|
||||
app.run("effect.move", json!({"effect": src.0, "index": index}));
|
||||
}
|
||||
resp.context_menu(|ui| {
|
||||
if ui.button(tr("Remove effect")).clicked() {
|
||||
app.run("effect.remove", json!({"effect": eid.0}));
|
||||
ui.close();
|
||||
let keymap = app.ui.keymap.clone();
|
||||
let paste = crate::menus::enabled(app, "effect.paste");
|
||||
// The clipboard items show the layer clipboard's shortcuts, which act on a selected effect.
|
||||
for (label, id, keys, enabled) in [
|
||||
(tr("Copy effect"), "effect.copy", Some("layer.copy"), true),
|
||||
(tr("Cut effect"), "effect.cut", Some("layer.cut"), true),
|
||||
(tr("Paste effect"), "effect.paste", Some("layer.paste"), paste),
|
||||
(tr("Duplicate effect"), "effect.duplicate", None, true),
|
||||
(tr("Remove effect"), "effect.remove", None, true),
|
||||
] {
|
||||
let mut b = egui::Button::new(label);
|
||||
if let Some(sc) = keys.and_then(|k| crate::keymap::shortcut_of(&keymap, k)) {
|
||||
b = b.shortcut_text(sc);
|
||||
}
|
||||
if ui.add_enabled(enabled, b).clicked() {
|
||||
// Selected first: a paste lands above it, a duplicate takes the selection.
|
||||
app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0}));
|
||||
app.run(id, json!({"effect": eid.0}));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -632,7 +693,9 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) {
|
||||
ui.separator();
|
||||
run(app, ui, tr("Cut layer(s)"), "layer.cut", json!({"layer": lid}), true);
|
||||
run(app, ui, tr("Copy layer(s)"), "layer.copy", json!({"layer": lid}), true);
|
||||
run(app, ui, tr("Paste layer(s)"), "layer.paste", json!({}), app.session.clipboard.is_some());
|
||||
let (paste_layer, paste_effect) = (crate::menus::enabled(app, "layer.paste"), crate::menus::enabled(app, "effect.paste"));
|
||||
run(app, ui, tr("Paste layer(s)"), "layer.paste", json!({}), paste_layer);
|
||||
run(app, ui, tr("Paste effect"), "effect.paste", json!({}), paste_effect);
|
||||
let paste_instance = crate::menus::enabled(app, "layer.pasteInstance");
|
||||
run(app, ui, tr("Paste as instance"), "layer.pasteInstance", json!({}), paste_instance);
|
||||
run(app, ui, tr("Duplicate layer(s)"), "layer.duplicate", json!({"layer": lid}), true);
|
||||
@@ -744,10 +807,10 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
});
|
||||
});
|
||||
let baked = app.session.doc.baked.get(&ts);
|
||||
let images: Vec<String> = app.session.doc.resources.keys().cloned().collect();
|
||||
for m in BakedMap::ALL {
|
||||
let present = baked.is_some_and(|b| b.maps.contains_key(&m));
|
||||
ui.horizontal(|ui| {
|
||||
let present = app.session.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&m));
|
||||
let row = ui.horizontal(|ui| {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(26.0, 26.0), Sense::hover());
|
||||
ui.painter().rect_filled(r, 2.0, if present { mesh_map_color(m) } else { tk.button });
|
||||
ui.vertical(|ui| {
|
||||
@@ -758,7 +821,36 @@ 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.
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.menu_button(RichText::new(ic::DOTS_THREE).size(13.0), |ui| {
|
||||
ui.label(caption(tr("Images")));
|
||||
for name in &images {
|
||||
if ui.button(name).clicked() {
|
||||
app.run("textureSet.meshMap.set", json!({"ts": ts, "map": m.id(), "image": name}));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
if ui.button(tr("Import...")).clicked() {
|
||||
crate::menus::invoke(app, ui.ctx(), "resource.import");
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if ui.add_enabled(present, egui::Button::new(tr("Clear"))).clicked() {
|
||||
app.run("textureSet.meshMap.clear", json!({"ts": ts, "map": m.id()}));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
// 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 resp.dnd_hover_payload::<ShelfDrag>().is_some_and(|d| matches!(d.asset, Asset::Texture(_))) {
|
||||
ui.painter().rect_stroke(resp.rect.shrink(1.0), 3.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside);
|
||||
}
|
||||
if let Some(Asset::Texture(name)) = dnd_release::<ShelfDrag>(&resp).map(|d| d.asset.clone()) {
|
||||
app.run("textureSet.meshMap.set", json!({"ts": ts, "map": m.id(), "image": name}));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -852,10 +944,10 @@ fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) {
|
||||
}
|
||||
ui.add_enabled_ui(hm.enabled, |ui| {
|
||||
let (mut contrast, mut offset) = (hm.contrast, hm.offset);
|
||||
if slider(ui, tr("Contrast"), &mut contrast, 0.0..=16.0, 2).drag_stopped() {
|
||||
if slider_edit(ui, tr("Contrast"), &mut contrast, 0.0..=16.0, 2) {
|
||||
app.run("layer.set", json!({"layer": id, "heightMask": {"contrast": contrast}}));
|
||||
}
|
||||
if slider(ui, tr("Height offset"), &mut offset, -1.0..=1.0, 2).drag_stopped() {
|
||||
if slider_edit(ui, tr("Height offset"), &mut offset, -1.0..=1.0, 2) {
|
||||
app.run("layer.set", json!({"layer": id, "heightMask": {"offset": offset}}));
|
||||
}
|
||||
});
|
||||
@@ -1009,6 +1101,8 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let b = &mut app.session.tool.brush;
|
||||
ui.label(caption(tr("Brush")));
|
||||
let hint = tr("Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.");
|
||||
ui.label(RichText::new(hint).size(10.5).color(Tokens::get(ui.ctx()).text_dim));
|
||||
section(ui, "sec_size", tr("Size"), true, |ui| {
|
||||
let mut size = b.size / 0.25 * 100.0;
|
||||
if slider(ui, tr("Size"), &mut size, 0.05..=100.0, 1).changed() {
|
||||
@@ -1114,7 +1208,8 @@ fn alpha_tile(ui: &mut Ui, on: bool, label: &str, paint: impl FnOnce(&egui::Pain
|
||||
p.rect_stroke(rect, 3.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside);
|
||||
}
|
||||
paint(p, Rect::from_center_size(rect.center() - vec2(0.0, 7.0), vec2(40.0, 40.0)));
|
||||
p.text(rect.center_bottom() - vec2(0.0, 6.0), egui::Align2::CENTER_CENTER, label, egui::FontId::proportional(9.5), tk.viewport_text);
|
||||
let name = elided(p, label, 9.5, tk.viewport_text, rect.width() - 4.0);
|
||||
p.galley(rect.center_bottom() - vec2(name.size().x * 0.5, 6.0 + name.size().y * 0.5), name, tk.viewport_text);
|
||||
resp.on_hover_text(label)
|
||||
}
|
||||
|
||||
@@ -1163,8 +1258,67 @@ fn alpha_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
ui.label(RichText::new(tr("More in Assets > Alphas: click one, or drag it here")).size(10.0).color(tk.text_dim));
|
||||
crate::shelf::drop_target(app, ui, &zone.response, crate::shelf::DropZone::Brush);
|
||||
section(ui, "sec_text", tr("Text"), true, |ui| text_section(app, ui));
|
||||
}
|
||||
|
||||
/// Text drawn in a font, as the brush alpha or a decal (`resource.text`).
|
||||
fn text_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
if app.ui.text.fonts.is_empty()
|
||||
&& let Some(f) = app.run("text.fonts", Value::Null)
|
||||
{
|
||||
let installed = f["installed"].as_array().into_iter().flatten().map(|v| {
|
||||
let styles = v["styles"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();
|
||||
(v["family"].as_str().unwrap_or_default().to_string(), styles)
|
||||
});
|
||||
let built_in = f["builtIn"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|n| (n.to_string(), Vec::new()));
|
||||
app.ui.text.fonts = installed.chain(built_in).collect();
|
||||
}
|
||||
// A decal shows the text in the tool's base color; an alpha must stay white.
|
||||
let color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([1.0; 3]);
|
||||
let t = &mut app.ui.text;
|
||||
ui.add(egui::TextEdit::multiline(&mut t.text).desired_rows(2).desired_width(f32::INFINITY).hint_text(tr("Text")));
|
||||
let shown = if t.font.is_empty() { tr("Default").to_string() } else { t.font.clone() };
|
||||
combo(ui, tr("Font"), shown, |ui| {
|
||||
if ui.selectable_label(t.font.is_empty(), tr("Default")).clicked() {
|
||||
(t.font, t.style) = (String::new(), String::new());
|
||||
}
|
||||
for (family, _) in &t.fonts {
|
||||
if ui.selectable_label(t.font == *family, family).clicked() {
|
||||
(t.font, t.style) = (family.clone(), String::new());
|
||||
}
|
||||
}
|
||||
});
|
||||
let styles = t.fonts.iter().find(|(f, _)| *f == t.font).map(|(_, s)| s.clone()).unwrap_or_default();
|
||||
if styles.len() > 1 {
|
||||
let shown = if t.style.is_empty() { tr("Default").to_string() } else { t.style.clone() };
|
||||
combo(ui, tr("Style"), shown, |ui| {
|
||||
for s in styles {
|
||||
ui.selectable_value(&mut t.style, s.clone(), s);
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut params = json!({"text": t.text, "font": (!t.font.is_empty()).then_some(&t.font), "style": (!t.style.is_empty()).then_some(&t.style)});
|
||||
let ready = !t.text.trim().is_empty();
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let alpha = ui.add_enabled(ready, egui::Button::new(tr("Use as brush alpha"))).clicked();
|
||||
let decal = ui.add_enabled(ready, egui::Button::new(tr("Place as decal"))).clicked();
|
||||
if decal {
|
||||
params["color"] = json!(color);
|
||||
}
|
||||
if (alpha || decal)
|
||||
&& let Some(name) = app.run("resource.text", params).and_then(|r| r["name"].as_str().map(str::to_string))
|
||||
{
|
||||
match alpha {
|
||||
true => app.run("tool.brush", json!({"alpha": {"image": name}})),
|
||||
false => app.run("layer.add.decal", json!({"image": name})),
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Tooltip of the material channel chips.
|
||||
pub(crate) const SOLO_HINT: &str = "Click: turn this channel on or off. Alt+click: this channel only";
|
||||
|
||||
fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.label(caption(tr("Material")));
|
||||
@@ -1172,8 +1326,9 @@ fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for c in &chans {
|
||||
let on = app.session.tool.enabled.contains(c);
|
||||
if chip(ui, tr(c.short()), on).clicked() {
|
||||
app.run("tool.material", json!({"channel": c.id(), "enabled": !on}));
|
||||
if chip(ui, tr(c.short()), on).on_hover_text(tr(SOLO_HINT)).clicked() {
|
||||
let solo = ui.input(|i| i.modifiers.alt);
|
||||
app.run("tool.material", json!({"channel": c.id(), "enabled": solo || !on, "solo": solo}));
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1271,8 +1426,9 @@ fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for c in &chans {
|
||||
let enabled = on.contains(c);
|
||||
if chip(ui, tr(c.short()), enabled).clicked() {
|
||||
app.run("layer.fill.set", with(base, json!({"channel": c.id(), "enabled": !enabled})));
|
||||
if chip(ui, tr(c.short()), enabled).on_hover_text(tr(SOLO_HINT)).clicked() {
|
||||
let solo = ui.input(|i| i.modifiers.alt);
|
||||
app.run("layer.fill.set", with(base, json!({"channel": c.id(), "enabled": solo || !enabled, "solo": solo})));
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1311,7 +1467,7 @@ fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base:
|
||||
Projection::Cylindrical { scale, .. } => (*scale, "cylindrical"),
|
||||
Projection::Decal(_) => return,
|
||||
};
|
||||
if slider(ui, tr("Scale / tiling"), &mut scale, 0.01..=20.0, 2).drag_stopped() {
|
||||
if slider_edit(ui, tr("Scale / tiling"), &mut scale, 0.01..=20.0, 2) {
|
||||
app.run("layer.fill.projection", with(base, json!({"projection": proj_id, "scale": scale})));
|
||||
}
|
||||
}
|
||||
@@ -1338,7 +1494,7 @@ fn decal_editor(app: &mut TextureCraftApp, ui: &mut Ui, d: &Decal, layer: LayerI
|
||||
];
|
||||
let mut done = false;
|
||||
for ((label, range), x) in rows.into_iter().zip(v.iter_mut()) {
|
||||
done |= slider(ui, label, x, range, 3).drag_stopped();
|
||||
done |= slider_edit(ui, label, x, range, 3);
|
||||
}
|
||||
if done {
|
||||
app.run("layer.decal.set", json!({"layer": layer.0, "size": [v[0], v[1]], "rotation": v[2], "offset": [v[3], v[4]], "depth": v[5]}));
|
||||
@@ -1415,11 +1571,11 @@ fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Valu
|
||||
);
|
||||
let mut s = pattern.scale;
|
||||
let mut con = pattern.contrast;
|
||||
let r1 = slider(ui, tr("Pattern scale"), &mut s, 0.1..=100.0, 1);
|
||||
let r2 = slider(ui, tr("Contrast"), &mut con, 0.0..=8.0, 2);
|
||||
let r1 = slider_edit(ui, tr("Pattern scale"), &mut s, 0.1..=100.0, 1);
|
||||
let r2 = slider_edit(ui, tr("Contrast"), &mut con, 0.0..=8.0, 2);
|
||||
let mut seed = pattern.seed as f32;
|
||||
let r3 = slider(ui, tr("Seed"), &mut seed, 0.0..=999.0, 0);
|
||||
if r1.drag_stopped() || r2.drag_stopped() || r3.drag_stopped() {
|
||||
let r3 = slider_edit(ui, tr("Seed"), &mut seed, 0.0..=999.0, 0);
|
||||
if r1 || r2 || r3 {
|
||||
app.run(
|
||||
"layer.fill.set",
|
||||
set(json!({"procedural": pattern.kind.label(), "scale": s, "contrast": con, "seed": seed as u64, "low": low, "high": high})),
|
||||
@@ -1468,7 +1624,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid:
|
||||
});
|
||||
});
|
||||
let mut op = e.opacity;
|
||||
if slider(ui, tr("Opacity"), &mut op, 0.0..=1.0, 2).drag_stopped() {
|
||||
if slider_edit(ui, tr("Opacity"), &mut op, 0.0..=1.0, 2) {
|
||||
app.run("effect.set", json!({"effect": id, "opacity": op}));
|
||||
}
|
||||
ui.separator();
|
||||
@@ -1485,13 +1641,13 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid:
|
||||
}
|
||||
});
|
||||
let (mut level, mut soft, mut noise, mut ns) = (g.level, g.softness, g.noise_amount, g.noise_scale);
|
||||
let r1 = slider(ui, tr("Level"), &mut level, 0.0..=1.0, 2);
|
||||
let r2 = slider(ui, tr("Softness"), &mut soft, 0.0..=1.0, 2);
|
||||
let r3 = slider(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2);
|
||||
let r4 = slider(ui, tr("Noise scale"), &mut ns, 0.1..=64.0, 1);
|
||||
let r1 = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2);
|
||||
let r2 = slider_edit(ui, tr("Softness"), &mut soft, 0.0..=1.0, 2);
|
||||
let r3 = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2);
|
||||
let r4 = slider_edit(ui, tr("Noise scale"), &mut ns, 0.1..=64.0, 1);
|
||||
let mut inv = g.invert;
|
||||
let r5 = ui.checkbox(&mut inv, tr("Invert"));
|
||||
if r1.drag_stopped() || r2.drag_stopped() || r3.drag_stopped() || r4.drag_stopped() || r5.changed() {
|
||||
if r1 || r2 || r3 || r4 || r5.changed() {
|
||||
app.run("effect.set", json!({"effect": id, "level": level, "softness": soft, "noise": noise, "noiseScale": ns, "invert": inv}));
|
||||
}
|
||||
if !app.session.doc.baked.contains_key(&app.session.ts()) {
|
||||
@@ -1502,12 +1658,13 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid:
|
||||
}
|
||||
EffectKind::Levels(l) => {
|
||||
ui.label(caption(tr("Levels")));
|
||||
levels_histogram(app, ui, layer, eid, (l.in_low, l.in_high));
|
||||
let mut v = [l.in_low, l.in_high, l.gamma, l.out_low, l.out_high];
|
||||
let labels = [tr("Input low"), tr("Input high"), tr("Gamma"), tr("Output low"), tr("Output high")];
|
||||
let mut done = false;
|
||||
for (i, label) in labels.iter().enumerate() {
|
||||
let range = if i == 2 { 0.1..=5.0 } else { 0.0..=1.0 };
|
||||
done |= slider(ui, label, &mut v[i], range, 2).drag_stopped();
|
||||
done |= slider_edit(ui, label, &mut v[i], range, 2);
|
||||
}
|
||||
if done {
|
||||
app.run("effect.set", json!({"effect": id, "inLow": v[0], "inHigh": v[1], "gamma": v[2], "outLow": v[3], "outHigh": v[4]}));
|
||||
@@ -1535,7 +1692,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid:
|
||||
match source {
|
||||
Source::Uniform(v) => {
|
||||
let mut x = v[0];
|
||||
if slider(ui, tr("Value"), &mut x, 0.0..=1.0, 2).drag_stopped() {
|
||||
if slider_edit(ui, tr("Value"), &mut x, 0.0..=1.0, 2) {
|
||||
app.run("effect.set", json!({"effect": id, "value": x}));
|
||||
}
|
||||
}
|
||||
@@ -1584,6 +1741,38 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid:
|
||||
}
|
||||
}
|
||||
|
||||
/// The histogram of what levels effect `eid` of `layer` remaps (its mask, or a content channel
|
||||
/// picked here), with the input range marked. Recomputed after a document change once no
|
||||
/// pointer button is held, so dragging a slider keeps the last one.
|
||||
fn levels_histogram(app: &TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId, range: (f32, f32)) {
|
||||
let mut channel = layer.channels.keys().next().copied().unwrap_or(Channel::BaseColor);
|
||||
if layer.content_effects.iter().any(|e| e.id == eid) {
|
||||
let pick = egui::Id::unique(("levels_channel", eid.0));
|
||||
let chans: Vec<Channel> = layer.channels.keys().copied().filter(|c| c.kind() != texturecraft_engine::core::ChannelKind::NormalMap).collect();
|
||||
channel = ui.data(|d| d.get_temp(pick)).filter(|c| chans.contains(c)).or(chans.first().copied()).unwrap_or(channel);
|
||||
combo(ui, tr("Channel"), tr(channel.label()), |ui| {
|
||||
for c in chans {
|
||||
if ui.selectable_label(c == channel, tr(c.label())).clicked() {
|
||||
ui.data_mut(|d| d.insert_temp(pick, c));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let key = egui::Id::unique(("levels_histogram", eid.0, channel));
|
||||
let rev = app.session.revision;
|
||||
let counts = match ui.data(|d| d.get_temp::<(u64, std::sync::Arc<Vec<u32>>)>(key)) {
|
||||
Some((r, h)) if r == rev || ui.input(|i| i.pointer.any_down()) => Some(h),
|
||||
_ => app.session.effect_histogram(eid, channel, 64).map(|h| {
|
||||
let h = std::sync::Arc::new(h);
|
||||
ui.data_mut(|d| d.insert_temp(key, (rev, h.clone())));
|
||||
h
|
||||
}),
|
||||
};
|
||||
if let Some(counts) = counts {
|
||||
histogram(ui, &counts, range);
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameters of filter effect `id`.
|
||||
fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
@@ -1595,7 +1784,7 @@ fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter
|
||||
ui.label(caption(tr(f.label())));
|
||||
if let Filter::Hsl { hue, .. } = f {
|
||||
let mut h = hue * 360.0;
|
||||
if slider(ui, tr("Hue shift (degrees)"), &mut h, -180.0..=180.0, 0).drag_stopped() {
|
||||
if slider_edit(ui, tr("Hue shift (degrees)"), &mut h, -180.0..=180.0, 0) {
|
||||
set(app, "hue", json!(h / 360.0));
|
||||
}
|
||||
}
|
||||
@@ -1607,7 +1796,7 @@ fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter
|
||||
} else {
|
||||
2
|
||||
};
|
||||
if slider(ui, tr(label), &mut v, lo..=hi, decimals).drag_stopped() {
|
||||
if slider_edit(ui, tr(label), &mut v, lo..=hi, decimals) {
|
||||
set(app, key, json!(v));
|
||||
}
|
||||
}
|
||||
@@ -1619,7 +1808,7 @@ fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter
|
||||
let mut v = *rgb;
|
||||
let mut done = false;
|
||||
for (x, name) in v.iter_mut().zip([tr("Cyan / red"), tr("Magenta / green"), tr("Yellow / blue")]) {
|
||||
done |= slider(ui, name, x, -1.0..=1.0, 2).drag_stopped();
|
||||
done |= slider_edit(ui, name, x, -1.0..=1.0, 2);
|
||||
}
|
||||
if done {
|
||||
set(app, key, json!(v));
|
||||
|
||||
@@ -43,11 +43,27 @@ pub struct GpuState {
|
||||
pub renderer: Renderer,
|
||||
/// Raised when texture-set textures were recreated: the UI must upload every tile again.
|
||||
pub reset: Arc<AtomicBool>,
|
||||
pub reports: Arc<Mutex<GpuReports>>,
|
||||
/// Wakes the UI when the GPU side has something to report.
|
||||
pub ctx: egui::Context,
|
||||
}
|
||||
|
||||
/// Problems the GPU side hands to the UI, which shows them as toasts.
|
||||
#[derive(Default)]
|
||||
pub struct GpuReports {
|
||||
/// Texture sets whose display textures could not be allocated (out of GPU memory).
|
||||
pub memory: Vec<usize>,
|
||||
/// wgpu errors no error scope caught (logged instead of wgpu's default panic).
|
||||
pub errors: Vec<String>,
|
||||
}
|
||||
|
||||
/// Most distinct uncaptured GPU errors kept until the UI shows them.
|
||||
const MAX_GPU_ERRORS: usize = 8;
|
||||
|
||||
/// UI-side bookkeeping of what the GPU already has.
|
||||
pub struct GpuLink {
|
||||
pub reset: Arc<AtomicBool>,
|
||||
pub reports: Arc<Mutex<GpuReports>>,
|
||||
/// Raised when a view callback was dropped before the GPU applied its scene sync (the
|
||||
/// frame was never painted, e.g. a WebGPU surface not ready yet): send everything again.
|
||||
pub lost: Arc<AtomicBool>,
|
||||
@@ -78,13 +94,28 @@ const UPLOAD_CHUNK: usize = 64;
|
||||
/// display kind, measured at ~5.5 µs on a desktop GPU), counted against the frame budget.
|
||||
const UPLOAD_MS_PER_TILE: f64 = 0.006;
|
||||
|
||||
pub fn init(rs: &egui_wgpu::RenderState) -> GpuLink {
|
||||
pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink {
|
||||
let reset = Arc::new(AtomicBool::new(false));
|
||||
let reports = Arc::new(Mutex::new(GpuReports::default()));
|
||||
// wgpu's default handler panics on any error no scope caught (an out-of-memory texture, a
|
||||
// driver hiccup): report it instead, so the user keeps the session.
|
||||
let (sink, wake) = (reports.clone(), ctx.clone());
|
||||
rs.device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| {
|
||||
log::error!("GPU error: {e}");
|
||||
let mut r = sink.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let text = e.to_string();
|
||||
if r.errors.len() < MAX_GPU_ERRORS && !r.errors.contains(&text) {
|
||||
r.errors.push(text);
|
||||
}
|
||||
// The UI may be idle: draw a frame to show it.
|
||||
wake.request_repaint();
|
||||
}));
|
||||
let renderer = Renderer::new(&rs.device, &rs.queue, rs.target_format);
|
||||
rs.renderer.write().callback_resources.insert(GpuState { renderer, reset: reset.clone() });
|
||||
rs.renderer.write().callback_resources.insert(GpuState { renderer, reset: reset.clone(), reports: reports.clone(), ctx: ctx.clone() });
|
||||
let info = rs.adapter.get_info();
|
||||
GpuLink {
|
||||
reset,
|
||||
reports,
|
||||
lost: Arc::new(AtomicBool::new(false)),
|
||||
mesh_id: 0,
|
||||
sets: Vec::new(),
|
||||
@@ -97,6 +128,11 @@ pub fn init(rs: &egui_wgpu::RenderState) -> GpuLink {
|
||||
}
|
||||
|
||||
impl GpuLink {
|
||||
/// What the GPU side reported since the last call (see [`GpuReports`]).
|
||||
pub fn take_reports(&self) -> GpuReports {
|
||||
std::mem::take(&mut *self.reports.lock().unwrap_or_else(PoisonError::into_inner))
|
||||
}
|
||||
|
||||
/// Collect everything the GPU needs this frame (runs the compositor first).
|
||||
/// Compositing progress (0..1) while tiles wait to be composited.
|
||||
pub fn composite_progress(&self, s: &Session) -> Option<f32> {
|
||||
@@ -264,10 +300,25 @@ impl CallbackTrait for ViewCallback {
|
||||
gpu.renderer.upload_tile(device, queue, *ts, *k, *tx, *ty, bytes);
|
||||
}
|
||||
for (ts, size, bytes) in &sync.aux {
|
||||
gpu.renderer.upload_aux(queue, *ts, *size, bytes);
|
||||
gpu.renderer.upload_aux(device, queue, *ts, *size, bytes);
|
||||
}
|
||||
}
|
||||
// Also installs (or rejects) full-size textures WebGPU answered for since last frame.
|
||||
gpu.renderer.prepare(device, queue, encoder, &self.frame);
|
||||
let failed = gpu.renderer.take_memory_failures();
|
||||
if !failed.is_empty() {
|
||||
let mut r = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
for ts in failed {
|
||||
if !r.memory.contains(&ts) {
|
||||
r.memory.push(ts);
|
||||
}
|
||||
}
|
||||
// This frame's report drain already ran: the next frame shows the toast.
|
||||
gpu.ctx.request_repaint();
|
||||
}
|
||||
if gpu.renderer.awaiting_gpu() {
|
||||
gpu.ctx.request_repaint();
|
||||
}
|
||||
let ppp = screen.pixels_per_point;
|
||||
let r = self.rect;
|
||||
gpu.renderer.set_blit_rect(queue, self.frame.view_id, [r.min.x * ppp, r.min.y * ppp, r.width() * ppp, r.height() * ppp], screen.size_in_pixels);
|
||||
|
||||
@@ -184,6 +184,7 @@ mod tests {
|
||||
"Anchor point",
|
||||
"Layer mask",
|
||||
texturecraft_engine::camera_cmds::DEFAULT_CAMERA,
|
||||
crate::dock::SOLO_HINT,
|
||||
]);
|
||||
k.retain(|s| !s.is_empty() && !UNTRANSLATED.contains(s));
|
||||
k
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Arabic UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "لا يوجد رسم على \"{layer}\" بعد: يغيّر المرشح ما ترسمه عليها."),
|
||||
("0 turns autosave off. Copies go to {folder}", "0 يعطل الحفظ التلقائي. تُحفظ النُسخ في {folder}"),
|
||||
("2D view only", "عرض ثنائي الأبعاد فقط"),
|
||||
("32 bits (float)", "32 بت (فاصلة عائمة)"),
|
||||
@@ -186,6 +187,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Contrast", "التباين"),
|
||||
("Contrast/Luminosity", "التباين / الإضاءة"),
|
||||
("Converted maps", "الخرائط المحوّلة"),
|
||||
("Copy RGB values", "نسخ قيم RGB"),
|
||||
("Copy effect", "نسخ التأثير"),
|
||||
("Copy from", "نسخ من"),
|
||||
("Copy layer(s)", "نسخ الطبقة (الطبقات)"),
|
||||
("Copy the selected layer alone (its empty parts copy nothing)", "نسخ الطبقة المحددة وحدها (الأجزاء الفارغة لا تنسخ شيئاً)"),
|
||||
@@ -205,9 +208,14 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Crate", "صندوق"),
|
||||
("Create", "إنشاء"),
|
||||
("Create smart material", "إنشاء مادة ذكية"),
|
||||
(
|
||||
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
|
||||
"Ctrl+السحب بالزر الأيمن في عرض يضبط الحجم والصلابة، وCtrl+السحب بالزر الأيسر يضبط التدفق والزاوية.",
|
||||
),
|
||||
("Cube", "مكعب"),
|
||||
("Current layer", "الطبقة الحالية"),
|
||||
("Curvature", "الانحناء"),
|
||||
("Cut effect", "قص التأثير"),
|
||||
("Cut layer(s)", "قص الطبقة (الطبقات)"),
|
||||
("Cyan / red", "سماوي / أحمر"),
|
||||
("Cylinder", "أسطوانة"),
|
||||
@@ -262,7 +270,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Drag the frame to move the decal, a corner to scale it, the round handle to turn it",
|
||||
"اسحب الإطار لتحريك الملصق، أو الزاوية لتغيير حجمه، أو المقبض الدائري لتدويره",
|
||||
),
|
||||
("Drop an image from the Assets panel here to use it as this mesh map", "أفلت صورة من لوحة الأصول هنا لاستخدامها كخريطة المجسم هذه"),
|
||||
("Dry streaks", "خطوط جافة"),
|
||||
("Duplicate effect", "تكرار التأثير"),
|
||||
("Duplicate layer(s)", "تكرار الطبقة (الطبقات)"),
|
||||
("Duplicate the selected template", "تكرار القالب المحدد"),
|
||||
("Edge Detect", "اكتشاف الحواف"),
|
||||
@@ -329,6 +339,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("From template", "من قالب"),
|
||||
("From template / project", "من قالب / مشروع"),
|
||||
("Full", "كامل"),
|
||||
("GPU error: {error}", "خطأ في GPU: {error}"),
|
||||
("Geometry mask", "قناع هندسي"),
|
||||
(
|
||||
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
|
||||
@@ -372,6 +383,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High poly mesh suffix", "لاحقة المجسم عالي الدقة"),
|
||||
("High poly: {name}", "عالي الدقة: {name}"),
|
||||
("Highlights", "المناطق المضيئة"),
|
||||
("Histogram Range", "نطاق المدرج التكراري"),
|
||||
("Histogram Scan", "مسح المدرج التكراري"),
|
||||
("Histogram Shift", "إزاحة المدرج التكراري"),
|
||||
("History", "السجل"),
|
||||
(
|
||||
"Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.",
|
||||
@@ -521,12 +535,22 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Normal from height", "ناظم من الارتفاع"),
|
||||
("Normal map combine", "دمج خرائط النواظم"),
|
||||
("Normal map detail", "تفاصيل خريطة النواظم"),
|
||||
("Color space", "فضاء الألوان"),
|
||||
("Normal map format", "صيغة خريطة النواظم"),
|
||||
("Normal map inverse detail", "عكس تفاصيل خريطة النواظم"),
|
||||
("Normal: painting uses the flat normal", "عادي: يستخدم الرسم الناظم المسطح"),
|
||||
(
|
||||
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"لا توجد ذاكرة GPU كافية لعرض مجموعة الخامات \"{name}\" كاملة: خفّض دقة الخامة لمنفذ العرض في الإعدادات. لا يتأثر الرسم والتصدير.",
|
||||
),
|
||||
(
|
||||
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"لا توجد ذاكرة GPU كافية لعرض {count} من مجموعات الخامات كاملة ({names}): خفّض دقة الخامة لمنفذ العرض في الإعدادات. لا يتأثر الرسم والتصدير.",
|
||||
),
|
||||
("Not exported: no source in this texture set", "لم يتم التصدير: لا يوجد مصدر في مجموعة الخامات هذه"),
|
||||
("Not saved: {error}", "لم يتم الحفظ: {error}"),
|
||||
("Off", "معطل"),
|
||||
("Offset", "إزاحة"),
|
||||
("Offset right", "إزاحة لليمين"),
|
||||
("Offset up", "إزاحة لأعلى"),
|
||||
("Offsets the textures by the height channel, at the height to normal strength", "يزيح الخامات وفق قناة الارتفاع، بقوة تحويل الارتفاع إلى ناظم"),
|
||||
@@ -575,6 +599,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Particles", "جسيمات"),
|
||||
("Passthrough", "تمرير مباشر (Passthrough)"),
|
||||
("Paste as instance", "لصق كنسخة مرتبطة (Instance)"),
|
||||
("Paste effect", "لصق التأثير"),
|
||||
("Paste layer(s)", "لصق الطبقة (الطبقات)"),
|
||||
("Path", "مسار"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "تتبع المسار على المعالج بدلاً من بطاقة الرسوميات (أبطأ)"),
|
||||
@@ -609,6 +634,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Radial copies", "نُسخ دائرية"),
|
||||
("Radius (texels at 2K)", "نصف القطر (تكسل بدقة 2K)"),
|
||||
("RENDERING", "التصيير"),
|
||||
("Range", "النطاق"),
|
||||
("Rebind any menu item, tool or command", "إعادة ربط أي عنصر قائمة، أو أداة أو أمر"),
|
||||
("Recent projects", "المشاريع الأخيرة"),
|
||||
(
|
||||
@@ -650,6 +676,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Resizing", "تغيير الحجم"),
|
||||
("Restore every default shortcut", "استعادة كل الاختصارات الافتراضية"),
|
||||
("Return to painting mode", "العودة إلى نمط الرسم"),
|
||||
("Return to this step", "العودة إلى هذه الخطوة"),
|
||||
("Right-click a layer > Create smart material", "انقر بزر الفأرة الأيمن على طبقة > إنشاء مادة ذكية"),
|
||||
("Rotation", "التدوير"),
|
||||
("Rotation (degrees)", "التدوير (بالدرجات)"),
|
||||
@@ -924,4 +951,29 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"استخدام إطار وأزرار نافذة نظام التشغيل بدلاً من شريط عنوان TextureCraft الخاص",
|
||||
),
|
||||
("Brushes", "الفرش"),
|
||||
("My brushes", "فرشي"),
|
||||
("Use this brush (keeps its size)", "استخدام هذه الفرشاة (مع الحفاظ على حجمها)"),
|
||||
("Brush name", "اسم الفرشاة"),
|
||||
("Save current brush", "حفظ الفرشاة الحالية"),
|
||||
("Start window", "نافذة البدء"),
|
||||
("Show at startup", "إظهار عند بدء التشغيل"),
|
||||
("Continue with the sample project", "المتابعة مع المشروع النموذجي"),
|
||||
("No recent projects yet", "لا توجد مشاريع حديثة بعد"),
|
||||
("Text", "نص"),
|
||||
("Font", "الخط"),
|
||||
("Style", "النمط"),
|
||||
("Use as brush alpha", "استخدام كألفا للفرشاة"),
|
||||
("Place as decal", "وضع كملصق"),
|
||||
("Click: turn this channel on or off. Alt+click: this channel only", "انقر: تشغيل هذه القناة أو إيقافها. Alt+نقر: هذه القناة فقط"),
|
||||
("Show all", "إظهار الكل"),
|
||||
("Hide all", "إخفاء الكل"),
|
||||
("Invert show/hide", "عكس الإظهار/الإخفاء"),
|
||||
("Show or hide texture sets", "إظهار مجموعات الخامات أو إخفاؤها"),
|
||||
("Focus: show only the active texture set", "تركيز: إظهار مجموعة الخامات النشطة فقط"),
|
||||
("Unsaved changes", "تغييرات غير محفوظة"),
|
||||
("Don't save", "عدم الحفظ"),
|
||||
("Save the changes to {name} before closing?", "هل تريد حفظ التغييرات في {name} قبل الإغلاق؟"),
|
||||
("Twill weave", "نسيج مائل"),
|
||||
("Save the changes to {name} first?", "هل تريد حفظ التغييرات في {name} أولًا؟"),
|
||||
];
|
||||
@@ -1,6 +1,7 @@
|
||||
//! German UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ist noch nicht bemalt: Der Filter verändert, was du darauf malst."),
|
||||
("0 turns autosave off. Copies go to {folder}", "0 deaktiviert die automatische Speicherung. Kopien werden in {folder} abgelegt"),
|
||||
("2D view only", "Nur 2D-Ansicht"),
|
||||
("32 bits (float)", "32 Bit (Float)"),
|
||||
@@ -198,6 +199,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Contrast", "Kontrast"),
|
||||
("Contrast/Luminosity", "Kontrast/Luminanz"),
|
||||
("Converted maps", "Konvertierte Maps"),
|
||||
("Copy RGB values", "RGB-Werte kopieren"),
|
||||
("Copy effect", "Effekt kopieren"),
|
||||
("Copy from", "Kopieren aus"),
|
||||
("Copy layer(s)", "Ebene(n) kopieren"),
|
||||
("Copy the selected layer alone (its empty parts copy nothing)", "Nur die ausgewählte Ebene kopieren (ihre leeren Bereiche kopieren nichts)"),
|
||||
@@ -217,9 +220,14 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Crate", "Kiste"),
|
||||
("Create", "Erstellen"),
|
||||
("Create smart material", "Smart-Material erstellen"),
|
||||
(
|
||||
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
|
||||
"Strg+Ziehen mit RMT in einer Ansicht stellt Größe und Härte ein, Strg+Ziehen mit LMT Fluss und Winkel.",
|
||||
),
|
||||
("Cube", "Würfel"),
|
||||
("Current layer", "Aktuelle Ebene"),
|
||||
("Curvature", "Krümmung"),
|
||||
("Cut effect", "Effekt ausschneiden"),
|
||||
("Cut layer(s)", "Ebene(n) ausschneiden"),
|
||||
("Cyan / red", "Cyan / Rot"),
|
||||
("Cylinder", "Zylinder"),
|
||||
@@ -280,7 +288,12 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Drag the frame to move the decal, a corner to scale it, the round handle to turn it",
|
||||
"Rahmen ziehen, um das Decal zu verschieben, eine Ecke zum Skalieren, den runden Griff zum Drehen",
|
||||
),
|
||||
(
|
||||
"Drop an image from the Assets panel here to use it as this mesh map",
|
||||
"Ein Bild aus dem Assets-Panel hier ablegen, um es als diese Mesh-Map zu verwenden",
|
||||
),
|
||||
("Dry streaks", "Trockene Schlieren"),
|
||||
("Duplicate effect", "Effekt duplizieren"),
|
||||
("Duplicate layer(s)", "Ebene(n) duplizieren"),
|
||||
("Duplicate the selected template", "Ausgewählte Vorlage duplizieren"),
|
||||
("Edge Detect", "Kantenerkennung"),
|
||||
@@ -350,6 +363,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("From template", "Aus Vorlage"),
|
||||
("From template / project", "Aus Vorlage / Projekt"),
|
||||
("Full", "Voll"),
|
||||
("GPU error: {error}", "GPU-Fehler: {error}"),
|
||||
("Geometry mask", "Geometriemaske"),
|
||||
(
|
||||
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
|
||||
@@ -393,6 +407,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High poly mesh suffix", "Suffix für High-Poly-Mesh"),
|
||||
("High poly: {name}", "High-Poly: {name}"),
|
||||
("Highlights", "Lichter"),
|
||||
("Histogram Range", "Histogrammbereich"),
|
||||
("Histogram Scan", "Histogramm-Scan"),
|
||||
("Histogram Shift", "Histogramm-Verschiebung"),
|
||||
("History", "Verlauf"),
|
||||
(
|
||||
"Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.",
|
||||
@@ -548,12 +565,22 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Normal from height", "Normale aus Höhe"),
|
||||
("Normal map combine", "Normal-Map kombinieren"),
|
||||
("Normal map detail", "Normal-Map-Detail"),
|
||||
("Color space", "Farbraum"),
|
||||
("Normal map format", "Normal-Map-Format"),
|
||||
("Normal map inverse detail", "Normal-Map-Detail invertiert"),
|
||||
("Normal: painting uses the flat normal", "Normale: Malen verwendet die flache Normale"),
|
||||
(
|
||||
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"Nicht genug GPU-Speicher, um das Texturset \"{name}\" vollständig anzuzeigen: Verringere in den Einstellungen die Texturauflösung des Ansichtsfensters. Malen und Export sind nicht betroffen.",
|
||||
),
|
||||
(
|
||||
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"Nicht genug GPU-Speicher, um {count} Texturesets vollständig anzuzeigen ({names}): Verringere in den Einstellungen die Texturauflösung des Ansichtsfensters. Malen und Export sind nicht betroffen.",
|
||||
),
|
||||
("Not exported: no source in this texture set", "Nicht exportiert: keine Quelle in diesem Texturset"),
|
||||
("Not saved: {error}", "Nicht gespeichert: {error}"),
|
||||
("Off", "Aus"),
|
||||
("Offset", "Versatz"),
|
||||
("Offset right", "Versatz rechts"),
|
||||
("Offset up", "Versatz oben"),
|
||||
(
|
||||
@@ -608,6 +635,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Particles", "Partikel"),
|
||||
("Passthrough", "Hindurchwirken"),
|
||||
("Paste as instance", "Als Instanz einfügen"),
|
||||
("Paste effect", "Effekt einfügen"),
|
||||
("Paste layer(s)", "Ebene(n) einfügen"),
|
||||
("Path", "Pfad"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "Path Tracing auf dem Prozessor statt auf der Grafikkarte (langsamer)"),
|
||||
@@ -645,6 +673,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Radial copies", "Radiale Kopien"),
|
||||
("Radius (texels at 2K)", "Radius (Texel bei 2K)"),
|
||||
("RENDERING", "RENDERING"),
|
||||
("Range", "Bereich"),
|
||||
("Rebind any menu item, tool or command", "Beliebige Menüeinträge, Werkzeuge oder Befehle neu belegen"),
|
||||
("Recent projects", "Letzte Projekte"),
|
||||
(
|
||||
@@ -689,6 +718,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Resizing", "Größe wird geändert"),
|
||||
("Restore every default shortcut", "Alle Standard-Tastenkürzel wiederherstellen"),
|
||||
("Return to painting mode", "Zurück zum Malmodus"),
|
||||
("Return to this step", "Zu diesem Schritt zurückkehren"),
|
||||
("Right-click a layer > Create smart material", "Rechtsklick auf eine Ebene > Smart-Material erstellen"),
|
||||
("Rotation", "Drehung"),
|
||||
("Rotation (degrees)", "Drehung (Grad)"),
|
||||
@@ -979,4 +1009,29 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"Fensterrahmen und Fenstertasten des Betriebssystems statt der eigenen Titelleiste von TextureCraft verwenden",
|
||||
),
|
||||
("Brushes", "Pinsel"),
|
||||
("My brushes", "Meine Pinsel"),
|
||||
("Use this brush (keeps its size)", "Diesen Pinsel verwenden (Größe bleibt)"),
|
||||
("Brush name", "Pinselname"),
|
||||
("Save current brush", "Aktuellen Pinsel speichern"),
|
||||
("Start window", "Startfenster"),
|
||||
("Show at startup", "Beim Start anzeigen"),
|
||||
("Continue with the sample project", "Mit dem Beispielprojekt fortfahren"),
|
||||
("No recent projects yet", "Noch keine zuletzt geöffneten Projekte"),
|
||||
("Text", "Text"),
|
||||
("Font", "Schrift"),
|
||||
("Style", "Schnitt"),
|
||||
("Use as brush alpha", "Als Pinsel-Alpha verwenden"),
|
||||
("Place as decal", "Als Decal platzieren"),
|
||||
("Click: turn this channel on or off. Alt+click: this channel only", "Klick: diesen Kanal ein- oder ausschalten. Alt+Klick: nur diesen Kanal"),
|
||||
("Show all", "Alle einblenden"),
|
||||
("Hide all", "Alle ausblenden"),
|
||||
("Invert show/hide", "Ein-/Ausblenden umkehren"),
|
||||
("Show or hide texture sets", "Texturesets ein- oder ausblenden"),
|
||||
("Focus: show only the active texture set", "Fokus: nur das aktive Textureset zeigen"),
|
||||
("Unsaved changes", "Ungespeicherte Änderungen"),
|
||||
("Don't save", "Nicht speichern"),
|
||||
("Save the changes to {name} before closing?", "Änderungen an {name} vor dem Schließen speichern?"),
|
||||
("Twill weave", "Köperbindung"),
|
||||
("Save the changes to {name} first?", "Änderungen an {name} zuerst speichern?"),
|
||||
];
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Spanish UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" aún no tiene pintura: el filtro cambia lo que pintes en ella."),
|
||||
("0 turns autosave off. Copies go to {folder}", "0 desactiva el autoguardado. Las copias se guardan en {folder}"),
|
||||
("2D view only", "Solo vista 2D"),
|
||||
("32 bits (float)", "32 bits (float)"),
|
||||
@@ -195,6 +196,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Contrast", "Contraste"),
|
||||
("Contrast/Luminosity", "Contraste/Luminosidad"),
|
||||
("Converted maps", "Mapas convertidos"),
|
||||
("Copy RGB values", "Copiar los valores RGB"),
|
||||
("Copy effect", "Copiar efecto"),
|
||||
("Copy from", "Copiar de"),
|
||||
("Copy layer(s)", "Copiar capa(s)"),
|
||||
("Copy the selected layer alone (its empty parts copy nothing)", "Copiar solo la capa seleccionada (sus partes vacías no copian nada)"),
|
||||
@@ -214,9 +217,14 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Crate", "Caja"),
|
||||
("Create", "Crear"),
|
||||
("Create smart material", "Crear material inteligente"),
|
||||
(
|
||||
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
|
||||
"Ctrl+arrastrar con botón der. en una vista ajusta el tamaño y la dureza; Ctrl+arrastrar con botón izq., el flujo y el ángulo.",
|
||||
),
|
||||
("Cube", "Cubo"),
|
||||
("Current layer", "Capa actual"),
|
||||
("Curvature", "Curvatura"),
|
||||
("Cut effect", "Cortar efecto"),
|
||||
("Cut layer(s)", "Cortar capa(s)"),
|
||||
("Cyan / red", "Cian / rojo"),
|
||||
("Cylinder", "Cilindro"),
|
||||
@@ -277,7 +285,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Drag the frame to move the decal, a corner to scale it, the round handle to turn it",
|
||||
"Arrastra el marco para mover la calcomanía, una esquina para escalarla y el tirador redondo para girarla",
|
||||
),
|
||||
("Drop an image from the Assets panel here to use it as this mesh map", "Suelta aquí una imagen del panel Recursos para usarla como este mapa de malla"),
|
||||
("Dry streaks", "Trazos secos"),
|
||||
("Duplicate effect", "Duplicar efecto"),
|
||||
("Duplicate layer(s)", "Duplicar capa(s)"),
|
||||
("Duplicate the selected template", "Duplicar la plantilla seleccionada"),
|
||||
("Edge Detect", "Detección de bordes"),
|
||||
@@ -344,6 +354,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("From template", "Desde la plantilla"),
|
||||
("From template / project", "Desde la plantilla / el proyecto"),
|
||||
("Full", "Completa"),
|
||||
("GPU error: {error}", "Error de GPU: {error}"),
|
||||
("Geometry mask", "Máscara de geometría"),
|
||||
(
|
||||
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
|
||||
@@ -387,6 +398,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High poly mesh suffix", "Sufijo de malla high poly"),
|
||||
("High poly: {name}", "High poly: {name}"),
|
||||
("Highlights", "Iluminaciones"),
|
||||
("Histogram Range", "Rango de histograma"),
|
||||
("Histogram Scan", "Barrido de histograma"),
|
||||
("Histogram Shift", "Desplazamiento de histograma"),
|
||||
("History", "Historial"),
|
||||
(
|
||||
"Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.",
|
||||
@@ -542,12 +556,22 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Normal from height", "Normal desde altura"),
|
||||
("Normal map combine", "Combinar mapa de normales"),
|
||||
("Normal map detail", "Detalle de mapa de normales"),
|
||||
("Color space", "Espacio de color"),
|
||||
("Normal map format", "Formato del mapa de normales"),
|
||||
("Normal map inverse detail", "Detalle inverso de mapa de normales"),
|
||||
("Normal: painting uses the flat normal", "Normal: la pintura usa la normal plana"),
|
||||
(
|
||||
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"No hay suficiente memoria de GPU para mostrar el conjunto de texturas \"{name}\" por completo: reduce en Ajustes la resolución de texturas de la ventana gráfica. La pintura y la exportación no se ven afectadas.",
|
||||
),
|
||||
(
|
||||
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"No hay suficiente memoria de GPU para mostrar por completo {count} conjuntos de texturas ({names}): reduce en Ajustes la resolución de texturas de la ventana gráfica. La pintura y la exportación no se ven afectadas.",
|
||||
),
|
||||
("Not exported: no source in this texture set", "No exportado: no hay origen en este conjunto de texturas"),
|
||||
("Not saved: {error}", "No guardado: {error}"),
|
||||
("Off", "Desactivado"),
|
||||
("Offset", "Desplazamiento"),
|
||||
("Offset right", "Desplazamiento a la derecha"),
|
||||
("Offset up", "Desplazamiento hacia arriba"),
|
||||
(
|
||||
@@ -602,6 +626,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Particles", "Partículas"),
|
||||
("Passthrough", "Paso directo"),
|
||||
("Paste as instance", "Pegar como instancia"),
|
||||
("Paste effect", "Pegar efecto"),
|
||||
("Paste layer(s)", "Pegar capa(s)"),
|
||||
("Path", "Trazado"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "Trazar trayectorias en el procesador en lugar de la tarjeta gráfica (más lento)"),
|
||||
@@ -636,6 +661,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Radial copies", "Copias radiales"),
|
||||
("Radius (texels at 2K)", "Radio (téxeles a 2K)"),
|
||||
("RENDERING", "RENDERIZADO"),
|
||||
("Range", "Rango"),
|
||||
("Rebind any menu item, tool or command", "Reasignar cualquier elemento de menú, herramienta o comando"),
|
||||
("Recent projects", "Proyectos recientes"),
|
||||
(
|
||||
@@ -680,6 +706,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Resizing", "Redimensionando"),
|
||||
("Restore every default shortcut", "Restaurar todos los atajos predeterminados"),
|
||||
("Return to painting mode", "Volver al modo de pintura"),
|
||||
("Return to this step", "Volver a este paso"),
|
||||
("Right-click a layer > Create smart material", "Clic derecho en una capa > Crear material inteligente"),
|
||||
("Rotation", "Rotación"),
|
||||
("Rotation (degrees)", "Rotación (grados)"),
|
||||
@@ -964,4 +991,29 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"Usar el marco y los botones de ventana del sistema operativo en lugar de la barra de título propia de TextureCraft",
|
||||
),
|
||||
("Brushes", "Pinceles"),
|
||||
("My brushes", "Mis pinceles"),
|
||||
("Use this brush (keeps its size)", "Usar este pincel (conserva su tamaño)"),
|
||||
("Brush name", "Nombre del pincel"),
|
||||
("Save current brush", "Guardar el pincel actual"),
|
||||
("Start window", "Ventana de inicio"),
|
||||
("Show at startup", "Mostrar al iniciar"),
|
||||
("Continue with the sample project", "Continuar con el proyecto de ejemplo"),
|
||||
("No recent projects yet", "Aún no hay proyectos recientes"),
|
||||
("Text", "Texto"),
|
||||
("Font", "Fuente"),
|
||||
("Style", "Estilo"),
|
||||
("Use as brush alpha", "Usar como alfa del pincel"),
|
||||
("Place as decal", "Colocar como calcomanía"),
|
||||
("Click: turn this channel on or off. Alt+click: this channel only", "Clic: activa o desactiva este canal. Alt+clic: solo este canal"),
|
||||
("Show all", "Mostrar todo"),
|
||||
("Hide all", "Ocultar todo"),
|
||||
("Invert show/hide", "Invertir mostrar/ocultar"),
|
||||
("Show or hide texture sets", "Mostrar u ocultar conjuntos de texturas"),
|
||||
("Focus: show only the active texture set", "Enfoque: mostrar solo el conjunto de texturas activo"),
|
||||
("Unsaved changes", "Cambios sin guardar"),
|
||||
("Don't save", "No guardar"),
|
||||
("Save the changes to {name} before closing?", "¿Guardar los cambios de {name} antes de cerrar?"),
|
||||
("Twill weave", "Tejido de sarga"),
|
||||
("Save the changes to {name} first?", "¿Guardar primero los cambios de {name}?"),
|
||||
];
|
||||
@@ -1,6 +1,10 @@
|
||||
//! French UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
(
|
||||
"\"{layer}\" has no paint yet: the filter changes what you paint on it.",
|
||||
"\"{layer}\" n'a pas encore de peinture : le filtre modifie ce que vous y peignez.",
|
||||
),
|
||||
("0 turns autosave off. Copies go to {folder}", "0 désactive la sauvegarde automatique. Les copies vont dans {folder}"),
|
||||
("2D view only", "Vue 2D seule"),
|
||||
("32 bits (float)", "32 bits (flottant)"),
|
||||
@@ -198,6 +202,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Contrast", "Contraste"),
|
||||
("Contrast/Luminosity", "Contraste/Luminosité"),
|
||||
("Converted maps", "Cartes converties"),
|
||||
("Copy RGB values", "Copier les valeurs RVB"),
|
||||
("Copy effect", "Copier l'effet"),
|
||||
("Copy from", "Copier depuis"),
|
||||
("Copy layer(s)", "Copier le(s) calque(s)"),
|
||||
("Copy the selected layer alone (its empty parts copy nothing)", "Copier uniquement le calque sélectionné (ses parties vides ne copient rien)"),
|
||||
@@ -217,9 +223,14 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Crate", "Caisse"),
|
||||
("Create", "Créer"),
|
||||
("Create smart material", "Créer un matériau intelligent"),
|
||||
(
|
||||
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
|
||||
"Ctrl+glisser (clic droit) dans une vue règle la taille et la dureté, Ctrl+glisser (clic gauche) le flux et l'angle.",
|
||||
),
|
||||
("Cube", "Cube"),
|
||||
("Current layer", "Calque actuel"),
|
||||
("Curvature", "Courbure"),
|
||||
("Cut effect", "Couper l'effet"),
|
||||
("Cut layer(s)", "Couper le(s) calque(s)"),
|
||||
("Cyan / red", "Cyan / rouge"),
|
||||
("Cylinder", "Cylindre"),
|
||||
@@ -280,7 +291,12 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Drag the frame to move the decal, a corner to scale it, the round handle to turn it",
|
||||
"Faites glisser le cadre pour déplacer le décalque, un coin pour le mettre à l'échelle, la poignée ronde pour le faire pivoter",
|
||||
),
|
||||
(
|
||||
"Drop an image from the Assets panel here to use it as this mesh map",
|
||||
"Déposez ici une image du panneau Ressources pour l'utiliser comme cette carte de maillage",
|
||||
),
|
||||
("Dry streaks", "Traînées sèches"),
|
||||
("Duplicate effect", "Dupliquer l'effet"),
|
||||
("Duplicate layer(s)", "Dupliquer le(s) calque(s)"),
|
||||
("Duplicate the selected template", "Dupliquer le modèle sélectionné"),
|
||||
("Edge Detect", "Détection des contours"),
|
||||
@@ -350,6 +366,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("From template", "Selon le modèle"),
|
||||
("From template / project", "Selon le modèle / projet"),
|
||||
("Full", "Pleine"),
|
||||
("GPU error: {error}", "Erreur GPU : {error}"),
|
||||
("Geometry mask", "Masque de géométrie"),
|
||||
(
|
||||
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
|
||||
@@ -393,6 +410,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High poly mesh suffix", "Suffixe du maillage high poly"),
|
||||
("High poly: {name}", "High poly : {name}"),
|
||||
("Highlights", "Tons clairs"),
|
||||
("Histogram Range", "Plage d'histogramme"),
|
||||
("Histogram Scan", "Balayage d'histogramme"),
|
||||
("Histogram Shift", "Décalage d'histogramme"),
|
||||
("History", "Historique"),
|
||||
(
|
||||
"Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.",
|
||||
@@ -551,12 +571,22 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Normal from height", "Normale depuis la hauteur"),
|
||||
("Normal map combine", "Normales : combinaison"),
|
||||
("Normal map detail", "Normales : détail"),
|
||||
("Color space", "Espace colorimétrique"),
|
||||
("Normal map format", "Format de carte de normales"),
|
||||
("Normal map inverse detail", "Normales : détail inverse"),
|
||||
("Normal: painting uses the flat normal", "Normal : la peinture utilise la normale plate"),
|
||||
(
|
||||
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"Mémoire GPU insuffisante pour afficher entièrement l'ensemble de textures \"{name}\" : réduisez la résolution des textures de l'affichage dans les Paramètres. La peinture et l'export ne sont pas affectés.",
|
||||
),
|
||||
(
|
||||
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"Mémoire GPU insuffisante pour afficher entièrement {count} ensembles de textures ({names}) : réduisez la résolution des textures de l'affichage dans les Paramètres. La peinture et l'export ne sont pas affectés.",
|
||||
),
|
||||
("Not exported: no source in this texture set", "Non exporté : aucune source dans cet ensemble de textures"),
|
||||
("Not saved: {error}", "Non enregistré : {error}"),
|
||||
("Off", "Désactivé"),
|
||||
("Offset", "Décalage"),
|
||||
("Offset right", "Décalage vers la droite"),
|
||||
("Offset up", "Décalage vers le haut"),
|
||||
(
|
||||
@@ -611,6 +641,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Particles", "Particules"),
|
||||
("Passthrough", "Transfert"),
|
||||
("Paste as instance", "Coller comme instance"),
|
||||
("Paste effect", "Coller l'effet"),
|
||||
("Paste layer(s)", "Coller le(s) calque(s)"),
|
||||
("Path", "Tracé"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "Tracé de chemins sur le processeur au lieu de la carte graphique (plus lent)"),
|
||||
@@ -645,6 +676,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Radial copies", "Copies radiales"),
|
||||
("Radius (texels at 2K)", "Rayon (texels en 2K)"),
|
||||
("RENDERING", "RENDU"),
|
||||
("Range", "Plage"),
|
||||
("Rebind any menu item, tool or command", "Réattribuer n'importe quel élément de menu, outil ou commande"),
|
||||
("Recent projects", "Projets récents"),
|
||||
(
|
||||
@@ -689,6 +721,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Resizing", "Redimensionnement"),
|
||||
("Restore every default shortcut", "Restaurer tous les raccourcis par défaut"),
|
||||
("Return to painting mode", "Revenir au mode peinture"),
|
||||
("Return to this step", "Revenir à cette étape"),
|
||||
("Right-click a layer > Create smart material", "Clic droit sur un calque > Créer un matériau intelligent"),
|
||||
("Rotation", "Rotation"),
|
||||
("Rotation (degrees)", "Rotation (degrés)"),
|
||||
@@ -979,4 +1012,29 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"Utiliser le cadre et les boutons de fenêtre du système d'exploitation au lieu de la barre de titre de TextureCraft",
|
||||
),
|
||||
("Brushes", "Pinceaux"),
|
||||
("My brushes", "Mes pinceaux"),
|
||||
("Use this brush (keeps its size)", "Utiliser ce pinceau (garde sa taille)"),
|
||||
("Brush name", "Nom du pinceau"),
|
||||
("Save current brush", "Enregistrer le pinceau actuel"),
|
||||
("Start window", "Fenêtre de démarrage"),
|
||||
("Show at startup", "Afficher au démarrage"),
|
||||
("Continue with the sample project", "Continuer avec le projet d'exemple"),
|
||||
("No recent projects yet", "Aucun projet récent pour l'instant"),
|
||||
("Text", "Texte"),
|
||||
("Font", "Police"),
|
||||
("Style", "Style"),
|
||||
("Use as brush alpha", "Utiliser comme alpha du pinceau"),
|
||||
("Place as decal", "Placer en décalque"),
|
||||
("Click: turn this channel on or off. Alt+click: this channel only", "Clic : active ou désactive ce canal. Alt+clic : ce canal uniquement"),
|
||||
("Show all", "Tout afficher"),
|
||||
("Hide all", "Tout masquer"),
|
||||
("Invert show/hide", "Inverser afficher/masquer"),
|
||||
("Show or hide texture sets", "Afficher ou masquer les ensembles de textures"),
|
||||
("Focus: show only the active texture set", "Focus : n'afficher que l'ensemble de textures actif"),
|
||||
("Unsaved changes", "Modifications non enregistrées"),
|
||||
("Don't save", "Ne pas enregistrer"),
|
||||
("Save the changes to {name} before closing?", "Enregistrer les modifications de {name} avant de fermer ?"),
|
||||
("Twill weave", "Armure sergé"),
|
||||
("Save the changes to {name} first?", "Enregistrer d'abord les modifications de {name} ?"),
|
||||
];
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Italian UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" non è ancora dipinto: il filtro modifica ciò che vi dipingi."),
|
||||
("0 turns autosave off. Copies go to {folder}", "0 disattiva il salvataggio automatico. Le copie vengono salvate in {folder}"),
|
||||
("2D view only", "Solo vista 2D"),
|
||||
("32 bits (float)", "32 bit (float)"),
|
||||
@@ -201,6 +202,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Contrast", "Contrasto"),
|
||||
("Contrast/Luminosity", "Contrasto/Luminosità"),
|
||||
("Converted maps", "Mappe convertite"),
|
||||
("Copy RGB values", "Copia i valori RGB"),
|
||||
("Copy effect", "Copia effetto"),
|
||||
("Copy from", "Copia da"),
|
||||
("Copy layer(s)", "Copia livello/i"),
|
||||
("Copy the selected layer alone (its empty parts copy nothing)", "Copia solo il livello selezionato (le sue parti vuote non copiano nulla)"),
|
||||
@@ -220,9 +223,14 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Crate", "Cassa"),
|
||||
("Create", "Crea"),
|
||||
("Create smart material", "Crea materiale intelligente"),
|
||||
(
|
||||
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
|
||||
"Ctrl+trascina con il tasto destro in una vista per regolare dimensione e durezza, con il sinistro flusso e angolo.",
|
||||
),
|
||||
("Cube", "Cubo"),
|
||||
("Current layer", "Livello corrente"),
|
||||
("Curvature", "Curvatura"),
|
||||
("Cut effect", "Taglia effetto"),
|
||||
("Cut layer(s)", "Taglia livello/i"),
|
||||
("Cyan / red", "Ciano / rosso"),
|
||||
("Cylinder", "Cilindro"),
|
||||
@@ -283,7 +291,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Drag the frame to move the decal, a corner to scale it, the round handle to turn it",
|
||||
"Trascina il riquadro per spostare la decal, un angolo per scalarla, la maniglia rotonda per ruotarla",
|
||||
),
|
||||
("Drop an image from the Assets panel here to use it as this mesh map", "Rilascia qui un'immagine dal pannello Risorse per usarla come questa mappa mesh"),
|
||||
("Dry streaks", "Striature secche"),
|
||||
("Duplicate effect", "Duplica effetto"),
|
||||
("Duplicate layer(s)", "Duplica livello/i"),
|
||||
("Duplicate the selected template", "Duplica il modello selezionato"),
|
||||
("Edge Detect", "Rilevamento bordi"),
|
||||
@@ -350,6 +360,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("From template", "Da modello"),
|
||||
("From template / project", "Da modello / progetto"),
|
||||
("Full", "Piena"),
|
||||
("GPU error: {error}", "Errore GPU: {error}"),
|
||||
("Geometry mask", "Maschera geometria"),
|
||||
(
|
||||
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
|
||||
@@ -393,6 +404,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High poly mesh suffix", "Suffisso mesh high poly"),
|
||||
("High poly: {name}", "High poly: {name}"),
|
||||
("Highlights", "Luci"),
|
||||
("Histogram Range", "Intervallo istogramma"),
|
||||
("Histogram Scan", "Scansione istogramma"),
|
||||
("Histogram Shift", "Spostamento istogramma"),
|
||||
("History", "Cronologia"),
|
||||
(
|
||||
"Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.",
|
||||
@@ -548,12 +562,22 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Normal from height", "Normale da altezza"),
|
||||
("Normal map combine", "Combina mappa normali"),
|
||||
("Normal map detail", "Dettaglio mappa normali"),
|
||||
("Color space", "Spazio colore"),
|
||||
("Normal map format", "Formato mappa normali"),
|
||||
("Normal map inverse detail", "Dettaglio inverso mappa normali"),
|
||||
("Normal: painting uses the flat normal", "Normale: la pittura usa la normale piatta"),
|
||||
(
|
||||
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"Memoria GPU insufficiente per mostrare per intero il set di texture \"{name}\": riduci nelle Impostazioni la risoluzione texture della viewport. Pittura ed esportazione non sono interessate.",
|
||||
),
|
||||
(
|
||||
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"Memoria GPU insufficiente per mostrare per intero {count} set di texture ({names}): riduci nelle Impostazioni la risoluzione texture della viewport. Pittura ed esportazione non sono interessate.",
|
||||
),
|
||||
("Not exported: no source in this texture set", "Non esportato: nessuna sorgente in questo set di texture"),
|
||||
("Not saved: {error}", "Non salvato: {error}"),
|
||||
("Off", "Disattivato"),
|
||||
("Offset", "Scostamento"),
|
||||
("Offset right", "Offset a destra"),
|
||||
("Offset up", "Offset in alto"),
|
||||
(
|
||||
@@ -608,6 +632,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Particles", "Particelle"),
|
||||
("Passthrough", "Pass-through"),
|
||||
("Paste as instance", "Incolla come istanza"),
|
||||
("Paste effect", "Incolla effetto"),
|
||||
("Paste layer(s)", "Incolla livello/i"),
|
||||
("Path", "Tracciato"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "Esegui il path tracing sul processore anziché sulla scheda grafica (più lento)"),
|
||||
@@ -645,6 +670,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Radial copies", "Copie radiali"),
|
||||
("Radius (texels at 2K)", "Raggio (texel a 2K)"),
|
||||
("RENDERING", "RENDERING"),
|
||||
("Range", "Intervallo"),
|
||||
("Rebind any menu item, tool or command", "Riassegna qualsiasi voce di menu, strumento o comando"),
|
||||
("Recent projects", "Progetti recenti"),
|
||||
(
|
||||
@@ -689,6 +715,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Resizing", "Ridimensionamento"),
|
||||
("Restore every default shortcut", "Ripristina tutte le scorciatoie predefinite"),
|
||||
("Return to painting mode", "Torna alla modalità pittura"),
|
||||
("Return to this step", "Torna a questo passaggio"),
|
||||
("Right-click a layer > Create smart material", "Clic destro su un livello > Crea materiale intelligente"),
|
||||
("Rotation", "Rotazione"),
|
||||
("Rotation (degrees)", "Rotazione (gradi)"),
|
||||
@@ -973,4 +1000,29 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"Usa la cornice e i pulsanti della finestra del sistema operativo invece della barra del titolo di TextureCraft",
|
||||
),
|
||||
("Brushes", "Pennelli"),
|
||||
("My brushes", "I miei pennelli"),
|
||||
("Use this brush (keeps its size)", "Usa questo pennello (mantiene la dimensione)"),
|
||||
("Brush name", "Nome del pennello"),
|
||||
("Save current brush", "Salva il pennello attuale"),
|
||||
("Start window", "Finestra iniziale"),
|
||||
("Show at startup", "Mostra all'avvio"),
|
||||
("Continue with the sample project", "Continua con il progetto di esempio"),
|
||||
("No recent projects yet", "Ancora nessun progetto recente"),
|
||||
("Text", "Testo"),
|
||||
("Font", "Carattere"),
|
||||
("Style", "Stile"),
|
||||
("Use as brush alpha", "Usa come alpha del pennello"),
|
||||
("Place as decal", "Posiziona come decal"),
|
||||
("Click: turn this channel on or off. Alt+click: this channel only", "Clic: attiva o disattiva questo canale. Alt+clic: solo questo canale"),
|
||||
("Show all", "Mostra tutto"),
|
||||
("Hide all", "Nascondi tutto"),
|
||||
("Invert show/hide", "Inverti mostra/nascondi"),
|
||||
("Show or hide texture sets", "Mostra o nascondi i set di texture"),
|
||||
("Focus: show only the active texture set", "Focus: mostra solo il set di texture attivo"),
|
||||
("Unsaved changes", "Modifiche non salvate"),
|
||||
("Don't save", "Non salvare"),
|
||||
("Save the changes to {name} before closing?", "Salvare le modifiche a {name} prima di chiudere?"),
|
||||
("Twill weave", "Tessuto a saia"),
|
||||
("Save the changes to {name} first?", "Salvare prima le modifiche a {name}?"),
|
||||
];
|
||||
@@ -1,6 +1,10 @@
|
||||
//! Japanese UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
(
|
||||
"\"{layer}\" has no paint yet: the filter changes what you paint on it.",
|
||||
"「{layer}」にはまだペイントがありません:フィルターはこのレイヤーにペイントした内容を変化させます。",
|
||||
),
|
||||
("0 turns autosave off. Copies go to {folder}", "0で自動保存をオフにします。コピーの保存先: {folder}"),
|
||||
("2D view only", "2Dビューのみ"),
|
||||
("32 bits (float)", "32ビット (浮動小数点)"),
|
||||
@@ -198,6 +202,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Contrast", "コントラスト"),
|
||||
("Contrast/Luminosity", "コントラスト/輝度"),
|
||||
("Converted maps", "変換マップ"),
|
||||
("Copy RGB values", "RGB 値をコピー"),
|
||||
("Copy effect", "エフェクトをコピー"),
|
||||
("Copy from", "コピー元"),
|
||||
("Copy layer(s)", "レイヤーをコピー"),
|
||||
("Copy the selected layer alone (its empty parts copy nothing)", "選択中のレイヤーのみをコピー (空の部分は何もコピーしない)"),
|
||||
@@ -217,9 +223,14 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Crate", "木箱"),
|
||||
("Create", "作成"),
|
||||
("Create smart material", "スマートマテリアルを作成"),
|
||||
(
|
||||
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
|
||||
"ビューでCtrl+右ドラッグでサイズと硬さ、Ctrl+左ドラッグでフローと角度を設定します。",
|
||||
),
|
||||
("Cube", "立方体"),
|
||||
("Current layer", "現在のレイヤー"),
|
||||
("Curvature", "曲率"),
|
||||
("Cut effect", "エフェクトを切り取り"),
|
||||
("Cut layer(s)", "レイヤーを切り取り"),
|
||||
("Cyan / red", "シアン / レッド"),
|
||||
("Cylinder", "円柱"),
|
||||
@@ -271,7 +282,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Draws {name} of texture set \"{set}\". Edits to the source show in every instance.",
|
||||
"テクスチャセット「{set}」の {name} を描画します。ソースへの編集はすべてのインスタンスに反映されます。",
|
||||
),
|
||||
("Drop an image from the Assets panel here to use it as this mesh map", "アセットパネルから画像をここにドロップすると、このメッシュマップとして使用します"),
|
||||
("Dry streaks", "かすれ"),
|
||||
("Duplicate effect", "エフェクトを複製"),
|
||||
("Duplicate layer(s)", "レイヤーを複製"),
|
||||
("Duplicate the selected template", "選択中のテンプレートを複製"),
|
||||
("Edge Detect", "エッジ検出"),
|
||||
@@ -338,6 +351,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("From template", "テンプレートから"),
|
||||
("From template / project", "テンプレート / プロジェクトから"),
|
||||
("Full", "フル"),
|
||||
("GPU error: {error}", "GPU エラー: {error}"),
|
||||
("Geometry mask", "ジオメトリマスク"),
|
||||
(
|
||||
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
|
||||
@@ -378,6 +392,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High poly mesh suffix", "ハイポリメッシュの接尾辞"),
|
||||
("High poly: {name}", "ハイポリ: {name}"),
|
||||
("Highlights", "ハイライト"),
|
||||
("Histogram Range", "ヒストグラム範囲"),
|
||||
("Histogram Scan", "ヒストグラムスキャン"),
|
||||
("Histogram Shift", "ヒストグラムシフト"),
|
||||
("History", "履歴"),
|
||||
(
|
||||
"Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.",
|
||||
@@ -533,12 +550,22 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Normal from height", "ハイトからノーマル"),
|
||||
("Normal map combine", "ノーマルマップ合成"),
|
||||
("Normal map detail", "ノーマルマップ ディテール"),
|
||||
("Color space", "カラースペース"),
|
||||
("Normal map format", "ノーマルマップ形式"),
|
||||
("Normal map inverse detail", "ノーマルマップ 逆ディテール"),
|
||||
("Normal: painting uses the flat normal", "ノーマル: ペイントにはフラットな法線を使用"),
|
||||
(
|
||||
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"GPU メモリが不足しているため、テクスチャセット「{name}」を完全には表示できません:設定でビューポートのテクスチャ解像度を下げてください。ペイントと書き出しには影響しません。",
|
||||
),
|
||||
(
|
||||
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"GPU メモリが不足しているため、{count} 個のテクスチャセット({names})を完全には表示できません:設定でビューポートのテクスチャ解像度を下げてください。ペイントと書き出しには影響しません。",
|
||||
),
|
||||
("Not exported: no source in this texture set", "エクスポートされません: このテクスチャセットにソースがありません"),
|
||||
("Not saved: {error}", "保存されていません: {error}"),
|
||||
("Off", "オフ"),
|
||||
("Offset", "オフセット"),
|
||||
("Offset right", "右オフセット"),
|
||||
("Offset up", "上オフセット"),
|
||||
(
|
||||
@@ -590,6 +617,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Particles", "パーティクル"),
|
||||
("Passthrough", "通過"),
|
||||
("Paste as instance", "インスタンスとして貼り付け"),
|
||||
("Paste effect", "エフェクトを貼り付け"),
|
||||
("Paste layer(s)", "レイヤーを貼り付け"),
|
||||
("Path", "パス"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "グラフィックカードではなくプロセッサーでパストレース (低速)"),
|
||||
@@ -624,6 +652,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Radial copies", "放射状コピー"),
|
||||
("Radius (texels at 2K)", "半径 (2K時のテクセル)"),
|
||||
("RENDERING", "レンダリング"),
|
||||
("Range", "範囲"),
|
||||
("Rebind any menu item, tool or command", "メニュー項目、ツール、コマンドのショートカットを再割り当て"),
|
||||
("Recent projects", "最近使ったプロジェクト"),
|
||||
(
|
||||
@@ -668,6 +697,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Resizing", "サイズ変更中"),
|
||||
("Restore every default shortcut", "すべてのショートカットをデフォルトに戻す"),
|
||||
("Return to painting mode", "ペイントモードに戻る"),
|
||||
("Return to this step", "このステップに戻る"),
|
||||
("Right-click a layer > Create smart material", "レイヤーを右クリック > スマートマテリアルを作成"),
|
||||
("Rotation", "回転"),
|
||||
("Rotation (degrees)", "回転 (度)"),
|
||||
@@ -946,4 +976,29 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"TextureCraft 独自のタイトルバーの代わりに、OS のウィンドウ枠とボタンを使います",
|
||||
),
|
||||
("Brushes", "ブラシ一覧"),
|
||||
("My brushes", "マイブラシ"),
|
||||
("Use this brush (keeps its size)", "このブラシを使用(サイズはそのまま)"),
|
||||
("Brush name", "ブラシ名"),
|
||||
("Save current brush", "現在のブラシを保存"),
|
||||
("Start window", "スタートウィンドウ"),
|
||||
("Show at startup", "起動時に表示"),
|
||||
("Continue with the sample project", "サンプルプロジェクトで続ける"),
|
||||
("No recent projects yet", "最近のプロジェクトはまだありません"),
|
||||
("Text", "テキスト"),
|
||||
("Font", "フォント"),
|
||||
("Style", "スタイル"),
|
||||
("Use as brush alpha", "ブラシのアルファとして使用"),
|
||||
("Place as decal", "デカールとして配置"),
|
||||
("Click: turn this channel on or off. Alt+click: this channel only", "クリック: このチャンネルのオン/オフ。Alt+クリック: このチャンネルのみ"),
|
||||
("Show all", "すべて表示"),
|
||||
("Hide all", "すべて非表示"),
|
||||
("Invert show/hide", "表示/非表示を反転"),
|
||||
("Show or hide texture sets", "テクスチャセットの表示/非表示"),
|
||||
("Focus: show only the active texture set", "フォーカス: アクティブなテクスチャセットのみ表示"),
|
||||
("Unsaved changes", "未保存の変更"),
|
||||
("Don't save", "保存しない"),
|
||||
("Save the changes to {name} before closing?", "閉じる前に {name} の変更を保存しますか?"),
|
||||
("Twill weave", "綾織り"),
|
||||
("Save the changes to {name} first?", "先に {name} の変更を保存しますか?"),
|
||||
];
|
||||
@@ -1,6 +1,10 @@
|
||||
//! Korean UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
(
|
||||
"\"{layer}\" has no paint yet: the filter changes what you paint on it.",
|
||||
"\"{layer}\"에 아직 페인트가 없습니다: 필터는 이 레이어에 칠하는 내용을 바꿉니다.",
|
||||
),
|
||||
("0 turns autosave off. Copies go to {folder}", "0으로 설정하면 자동 저장이 꺼집니다. 사본 저장 위치: {folder}"),
|
||||
("2D view only", "2D 뷰만"),
|
||||
("32 bits (float)", "32비트 (float)"),
|
||||
@@ -189,6 +193,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Contrast", "대비"),
|
||||
("Contrast/Luminosity", "대비/광도"),
|
||||
("Converted maps", "변환된 맵"),
|
||||
("Copy RGB values", "RGB 값 복사"),
|
||||
("Copy effect", "이펙트 복사"),
|
||||
("Copy from", "복사 원본"),
|
||||
("Copy layer(s)", "레이어 복사"),
|
||||
("Copy the selected layer alone (its empty parts copy nothing)", "선택한 레이어만 복사합니다 (빈 부분은 복사되지 않음)"),
|
||||
@@ -208,9 +214,14 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Crate", "상자"),
|
||||
("Create", "만들기"),
|
||||
("Create smart material", "스마트 머티리얼 만들기"),
|
||||
(
|
||||
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
|
||||
"뷰에서 Ctrl+오른쪽 드래그로 크기와 경도를, Ctrl+왼쪽 드래그로 흐름과 각도를 설정합니다.",
|
||||
),
|
||||
("Cube", "큐브"),
|
||||
("Current layer", "현재 레이어"),
|
||||
("Curvature", "곡률"),
|
||||
("Cut effect", "이펙트 잘라내기"),
|
||||
("Cut layer(s)", "레이어 잘라내기"),
|
||||
("Cyan / red", "녹청 / 빨강"),
|
||||
("Cylinder", "실린더"),
|
||||
@@ -268,7 +279,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Draws {name} of texture set \"{set}\". Edits to the source show in every instance.",
|
||||
"텍스처 세트 \"{set}\"의 {name}을(를) 그립니다. 원본을 편집하면 모든 인스턴스에 반영됩니다.",
|
||||
),
|
||||
("Drop an image from the Assets panel here to use it as this mesh map", "에셋 패널의 이미지를 여기에 놓으면 이 메시 맵으로 사용합니다"),
|
||||
("Dry streaks", "마른 붓자국"),
|
||||
("Duplicate effect", "이펙트 복제"),
|
||||
("Duplicate layer(s)", "레이어 복제"),
|
||||
("Duplicate the selected template", "선택한 템플릿을 복제합니다"),
|
||||
("Edge Detect", "가장자리 검출"),
|
||||
@@ -332,6 +345,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("From template", "템플릿 기준"),
|
||||
("From template / project", "템플릿 / 프로젝트 기준"),
|
||||
("Full", "전체"),
|
||||
("GPU error: {error}", "GPU 오류: {error}"),
|
||||
("Geometry mask", "지오메트리 마스크"),
|
||||
(
|
||||
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
|
||||
@@ -375,6 +389,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High poly mesh suffix", "하이 폴리 메시 접미사"),
|
||||
("High poly: {name}", "하이 폴리: {name}"),
|
||||
("Highlights", "밝은 영역"),
|
||||
("Histogram Range", "히스토그램 범위"),
|
||||
("Histogram Scan", "히스토그램 스캔"),
|
||||
("Histogram Shift", "히스토그램 이동"),
|
||||
("History", "히스토리"),
|
||||
(
|
||||
"Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.",
|
||||
@@ -527,12 +544,22 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Normal from height", "높이에서 노멀"),
|
||||
("Normal map combine", "노멀 맵 결합"),
|
||||
("Normal map detail", "노멀 맵 디테일"),
|
||||
("Color space", "색 공간"),
|
||||
("Normal map format", "노멀 맵 형식"),
|
||||
("Normal map inverse detail", "노멀 맵 역 디테일"),
|
||||
("Normal: painting uses the flat normal", "노멀: 평면 노멀로 페인팅합니다"),
|
||||
(
|
||||
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"GPU 메모리가 부족하여 텍스처 세트 \"{name}\"을(를) 모두 표시할 수 없습니다: 설정에서 뷰포트의 텍스처 해상도를 낮추세요. 페인팅과 내보내기에는 영향이 없습니다.",
|
||||
),
|
||||
(
|
||||
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"GPU 메모리가 부족하여 텍스처 세트 {count}개({names})를 모두 표시할 수 없습니다: 설정에서 뷰포트의 텍스처 해상도를 낮추세요. 페인팅과 내보내기에는 영향이 없습니다.",
|
||||
),
|
||||
("Not exported: no source in this texture set", "내보내지 않음: 이 텍스처 세트에 소스가 없습니다"),
|
||||
("Not saved: {error}", "저장되지 않음: {error}"),
|
||||
("Off", "끄기"),
|
||||
("Offset", "오프셋"),
|
||||
("Offset right", "오른쪽 오프셋"),
|
||||
("Offset up", "위쪽 오프셋"),
|
||||
("Offsets the textures by the height channel, at the height to normal strength", "높이-노멀 변환 강도로 높이 채널에 따라 텍스처를 오프셋합니다"),
|
||||
@@ -581,6 +608,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Particles", "파티클"),
|
||||
("Passthrough", "통과"),
|
||||
("Paste as instance", "인스턴스로 붙여넣기"),
|
||||
("Paste effect", "이펙트 붙여넣기"),
|
||||
("Paste layer(s)", "레이어 붙여넣기"),
|
||||
("Path", "패스"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "그래픽 카드 대신 프로세서에서 패스 트레이싱합니다 (더 느림)"),
|
||||
@@ -615,6 +643,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Radial copies", "방사형 복사본"),
|
||||
("Radius (texels at 2K)", "반경 (2K 기준 텍셀)"),
|
||||
("RENDERING", "렌더링"),
|
||||
("Range", "범위"),
|
||||
("Rebind any menu item, tool or command", "메뉴 항목, 도구 또는 명령의 단축키를 다시 지정합니다"),
|
||||
("Recent projects", "최근 프로젝트"),
|
||||
(
|
||||
@@ -659,6 +688,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Resizing", "크기 조정 중"),
|
||||
("Restore every default shortcut", "모든 기본 단축키를 복원합니다"),
|
||||
("Return to painting mode", "페인팅 모드로 돌아가기"),
|
||||
("Return to this step", "이 단계로 돌아가기"),
|
||||
("Right-click a layer > Create smart material", "레이어 마우스 오른쪽 클릭 > 스마트 머티리얼 만들기"),
|
||||
("Rotation", "회전"),
|
||||
("Rotation (degrees)", "회전 (도)"),
|
||||
@@ -931,4 +961,29 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"TextureCraft 자체 제목 표시줄 대신 운영 체제의 창 테두리와 버튼을 사용합니다",
|
||||
),
|
||||
("Brushes", "브러시 목록"),
|
||||
("My brushes", "내 브러시"),
|
||||
("Use this brush (keeps its size)", "이 브러시 사용 (크기 유지)"),
|
||||
("Brush name", "브러시 이름"),
|
||||
("Save current brush", "현재 브러시 저장"),
|
||||
("Start window", "시작 창"),
|
||||
("Show at startup", "시작 시 표시"),
|
||||
("Continue with the sample project", "샘플 프로젝트로 계속"),
|
||||
("No recent projects yet", "아직 최근 프로젝트가 없습니다"),
|
||||
("Text", "텍스트"),
|
||||
("Font", "글꼴"),
|
||||
("Style", "스타일"),
|
||||
("Use as brush alpha", "브러시 알파로 사용"),
|
||||
("Place as decal", "데칼로 배치"),
|
||||
("Click: turn this channel on or off. Alt+click: this channel only", "클릭: 이 채널 켜기/끄기. Alt+클릭: 이 채널만"),
|
||||
("Show all", "모두 표시"),
|
||||
("Hide all", "모두 숨기기"),
|
||||
("Invert show/hide", "표시/숨기기 반전"),
|
||||
("Show or hide texture sets", "텍스처 세트 표시 또는 숨기기"),
|
||||
("Focus: show only the active texture set", "포커스: 활성 텍스처 세트만 표시"),
|
||||
("Unsaved changes", "저장되지 않은 변경 사항"),
|
||||
("Don't save", "저장 안 함"),
|
||||
("Save the changes to {name} before closing?", "닫기 전에 {name}의 변경 사항을 저장할까요?"),
|
||||
("Twill weave", "능직"),
|
||||
("Save the changes to {name} first?", "먼저 {name}의 변경 사항을 저장할까요?"),
|
||||
];
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Brazilian Portuguese UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ainda não tem pintura: o filtro altera o que você pintar nela."),
|
||||
("0 turns autosave off. Copies go to {folder}", "0 desativa o salvamento automático. As cópias vão para {folder}"),
|
||||
("2D view only", "Apenas vista 2D"),
|
||||
("32 bits (float)", "32 bits (float)"),
|
||||
@@ -195,6 +196,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Contrast", "Contraste"),
|
||||
("Contrast/Luminosity", "Contraste/Luminosidade"),
|
||||
("Converted maps", "Mapas convertidos"),
|
||||
("Copy RGB values", "Copiar os valores RGB"),
|
||||
("Copy effect", "Copiar efeito"),
|
||||
("Copy from", "Copiar de"),
|
||||
("Copy layer(s)", "Copiar camada(s)"),
|
||||
("Copy the selected layer alone (its empty parts copy nothing)", "Copiar apenas a camada selecionada (suas partes vazias não copiam nada)"),
|
||||
@@ -214,9 +217,14 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Crate", "Caixote"),
|
||||
("Create", "Criar"),
|
||||
("Create smart material", "Criar material inteligente"),
|
||||
(
|
||||
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
|
||||
"Ctrl+arrastar com botão direito em uma vista ajusta o tamanho e a dureza; Ctrl+arrastar com botão esquerdo, o fluxo e o ângulo.",
|
||||
),
|
||||
("Cube", "Cubo"),
|
||||
("Current layer", "Camada atual"),
|
||||
("Curvature", "Curvatura"),
|
||||
("Cut effect", "Recortar efeito"),
|
||||
("Cut layer(s)", "Recortar camada(s)"),
|
||||
("Cyan / red", "Ciano / vermelho"),
|
||||
("Cylinder", "Cilindro"),
|
||||
@@ -277,7 +285,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Drag the frame to move the decal, a corner to scale it, the round handle to turn it",
|
||||
"Arraste o quadro para mover o decalque, um canto para redimensioná-lo e a alça redonda para girá-lo",
|
||||
),
|
||||
("Drop an image from the Assets panel here to use it as this mesh map", "Solte aqui uma imagem do painel Recursos para usá-la como este mapa de malha"),
|
||||
("Dry streaks", "Estrias secas"),
|
||||
("Duplicate effect", "Duplicar efeito"),
|
||||
("Duplicate layer(s)", "Duplicar camada(s)"),
|
||||
("Duplicate the selected template", "Duplicar o modelo selecionado"),
|
||||
("Edge Detect", "Detecção de bordas"),
|
||||
@@ -344,6 +354,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("From template", "Do modelo"),
|
||||
("From template / project", "Do modelo / projeto"),
|
||||
("Full", "Completa"),
|
||||
("GPU error: {error}", "Erro de GPU: {error}"),
|
||||
("Geometry mask", "Máscara de geometria"),
|
||||
(
|
||||
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
|
||||
@@ -387,6 +398,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High poly mesh suffix", "Sufixo da malha high poly"),
|
||||
("High poly: {name}", "High poly: {name}"),
|
||||
("Highlights", "Realces"),
|
||||
("Histogram Range", "Intervalo do histograma"),
|
||||
("Histogram Scan", "Varredura do histograma"),
|
||||
("Histogram Shift", "Deslocamento do histograma"),
|
||||
("History", "Histórico"),
|
||||
(
|
||||
"Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.",
|
||||
@@ -539,12 +553,22 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Normal from height", "Normal a partir da altura"),
|
||||
("Normal map combine", "Combinação de mapa normal"),
|
||||
("Normal map detail", "Detalhe de mapa normal"),
|
||||
("Color space", "Espaço de cor"),
|
||||
("Normal map format", "Formato do mapa normal"),
|
||||
("Normal map inverse detail", "Detalhe inverso de mapa normal"),
|
||||
("Normal: painting uses the flat normal", "Normal: a pintura usa a normal plana"),
|
||||
(
|
||||
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"Memória de GPU insuficiente para mostrar o conjunto de texturas \"{name}\" por completo: reduza nas Configurações a resolução das texturas da viewport. A pintura e a exportação não são afetadas.",
|
||||
),
|
||||
(
|
||||
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"Memória de GPU insuficiente para mostrar por completo {count} conjuntos de texturas ({names}): reduza nas Configurações a resolução das texturas da viewport. A pintura e a exportação não são afetadas.",
|
||||
),
|
||||
("Not exported: no source in this texture set", "Não exportado: sem origem neste conjunto de texturas"),
|
||||
("Not saved: {error}", "Não salvo: {error}"),
|
||||
("Off", "Desligado"),
|
||||
("Offset", "Deslocamento"),
|
||||
("Offset right", "Deslocamento à direita"),
|
||||
("Offset up", "Deslocamento para cima"),
|
||||
(
|
||||
@@ -599,6 +623,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Particles", "Partículas"),
|
||||
("Passthrough", "Passagem"),
|
||||
("Paste as instance", "Colar como instância"),
|
||||
("Paste effect", "Colar efeito"),
|
||||
("Paste layer(s)", "Colar camada(s)"),
|
||||
("Path", "Caminho"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "Fazer path tracing no processador em vez da placa de vídeo (mais lento)"),
|
||||
@@ -633,6 +658,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Radial copies", "Cópias radiais"),
|
||||
("Radius (texels at 2K)", "Raio (texels em 2K)"),
|
||||
("RENDERING", "RENDERIZAÇÃO"),
|
||||
("Range", "Intervalo"),
|
||||
("Rebind any menu item, tool or command", "Reatribuir qualquer item de menu, ferramenta ou comando"),
|
||||
("Recent projects", "Projetos recentes"),
|
||||
(
|
||||
@@ -677,6 +703,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Resizing", "Redimensionando"),
|
||||
("Restore every default shortcut", "Restaurar todos os atalhos padrão"),
|
||||
("Return to painting mode", "Voltar ao modo de pintura"),
|
||||
("Return to this step", "Voltar a esta etapa"),
|
||||
("Right-click a layer > Create smart material", "Clique com o botão direito em uma camada > Criar material inteligente"),
|
||||
("Rotation", "Rotação"),
|
||||
("Rotation (degrees)", "Rotação (graus)"),
|
||||
@@ -961,4 +988,29 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"Usar a moldura e os botões de janela do sistema operacional em vez da barra de título própria do TextureCraft",
|
||||
),
|
||||
("Brushes", "Pincéis"),
|
||||
("My brushes", "Meus pincéis"),
|
||||
("Use this brush (keeps its size)", "Usar este pincel (mantém o tamanho)"),
|
||||
("Brush name", "Nome do pincel"),
|
||||
("Save current brush", "Salvar o pincel atual"),
|
||||
("Start window", "Janela inicial"),
|
||||
("Show at startup", "Mostrar ao iniciar"),
|
||||
("Continue with the sample project", "Continuar com o projeto de exemplo"),
|
||||
("No recent projects yet", "Nenhum projeto recente ainda"),
|
||||
("Text", "Texto"),
|
||||
("Font", "Fonte"),
|
||||
("Style", "Estilo"),
|
||||
("Use as brush alpha", "Usar como alpha do pincel"),
|
||||
("Place as decal", "Colocar como decalque"),
|
||||
("Click: turn this channel on or off. Alt+click: this channel only", "Clique: liga ou desliga este canal. Alt+clique: só este canal"),
|
||||
("Show all", "Mostrar tudo"),
|
||||
("Hide all", "Ocultar tudo"),
|
||||
("Invert show/hide", "Inverter mostrar/ocultar"),
|
||||
("Show or hide texture sets", "Mostrar ou ocultar conjuntos de texturas"),
|
||||
("Focus: show only the active texture set", "Foco: mostrar só o conjunto de texturas ativo"),
|
||||
("Unsaved changes", "Alterações não salvas"),
|
||||
("Don't save", "Não salvar"),
|
||||
("Save the changes to {name} before closing?", "Salvar as alterações em {name} antes de fechar?"),
|
||||
("Twill weave", "Tecido sarja"),
|
||||
("Save the changes to {name} first?", "Salvar primeiro as alterações em {name}?"),
|
||||
];
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Simplified Chinese UI text: (English key, translation). Keys are the English strings passed to `tr`.
|
||||
|
||||
pub const TABLE: &[(&str, &str)] = &[
|
||||
("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "“{layer}”尚未绘制:滤镜会改变你在其上绘制的内容。"),
|
||||
("0 turns autosave off. Copies go to {folder}", "设为 0 可关闭自动保存。副本保存到 {folder}"),
|
||||
("2D view only", "仅 2D 视图"),
|
||||
("32 bits (float)", "32 位(浮点)"),
|
||||
@@ -168,6 +169,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Contrast", "对比度"),
|
||||
("Contrast/Luminosity", "对比度/亮度"),
|
||||
("Converted maps", "转换贴图"),
|
||||
("Copy RGB values", "复制 RGB 值"),
|
||||
("Copy effect", "复制效果"),
|
||||
("Copy from", "复制自"),
|
||||
("Copy layer(s)", "复制图层"),
|
||||
("Copy the selected layer alone (its empty parts copy nothing)", "仅复制所选图层(其空白部分不复制任何内容)"),
|
||||
@@ -187,9 +190,14 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Crate", "箱子"),
|
||||
("Create", "创建"),
|
||||
("Create smart material", "创建智能材质"),
|
||||
(
|
||||
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
|
||||
"在视图中按住 Ctrl 右键拖动可调整大小和硬度,Ctrl 左键拖动可调整流量和角度。",
|
||||
),
|
||||
("Cube", "立方体"),
|
||||
("Current layer", "当前图层"),
|
||||
("Curvature", "曲率"),
|
||||
("Cut effect", "剪切效果"),
|
||||
("Cut layer(s)", "剪切图层"),
|
||||
("Cyan / red", "青色 / 红色"),
|
||||
("Cylinder", "圆柱体"),
|
||||
@@ -238,7 +246,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "拖动边框移动贴花,拖动角缩放,拖动圆形手柄旋转"),
|
||||
("Drags the layer stack's values along the stroke into the selected layer.", "沿笔画将图层堆栈的值拖入所选图层。"),
|
||||
("Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", "绘制纹理集“{set}”的 {name}。对源的编辑会显示在每个实例中。"),
|
||||
("Drop an image from the Assets panel here to use it as this mesh map", "将资产面板中的图像拖放到此处,用作此网格贴图"),
|
||||
("Dry streaks", "干笔条纹"),
|
||||
("Duplicate effect", "创建效果副本"),
|
||||
("Duplicate layer(s)", "创建图层副本"),
|
||||
("Duplicate the selected template", "创建所选模板的副本"),
|
||||
("Edge Detect", "边缘检测"),
|
||||
@@ -299,6 +309,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("From template", "基于模板"),
|
||||
("From template / project", "基于模板 / 项目"),
|
||||
("Full", "完整"),
|
||||
("GPU error: {error}", "GPU 错误:{error}"),
|
||||
("Geometry mask", "几何遮罩"),
|
||||
(
|
||||
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
|
||||
@@ -339,6 +350,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High poly mesh suffix", "高模网格后缀"),
|
||||
("High poly: {name}", "高模:{name}"),
|
||||
("Highlights", "高光"),
|
||||
("Histogram Range", "直方图范围"),
|
||||
("Histogram Scan", "直方图扫描"),
|
||||
("Histogram Shift", "直方图偏移"),
|
||||
("History", "历史记录"),
|
||||
("Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", "按住 S:左键拖动旋转,右键拖动缩放,中键拖动移动模板。"),
|
||||
("Hold V and click the mesh to set the clone source", "按住 V 并单击网格以设置仿制源"),
|
||||
@@ -482,12 +496,22 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Normal from height", "由高度生成法线"),
|
||||
("Normal map combine", "法线贴图合并"),
|
||||
("Normal map detail", "法线贴图细节"),
|
||||
("Color space", "色彩空间"),
|
||||
("Normal map format", "法线贴图格式"),
|
||||
("Normal map inverse detail", "法线贴图反向细节"),
|
||||
("Normal: painting uses the flat normal", "法线:绘画使用平坦法线"),
|
||||
(
|
||||
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"GPU 内存不足,无法完整显示纹理集“{name}”:请在设置中降低视口的纹理分辨率。绘制和导出不受影响。",
|
||||
),
|
||||
(
|
||||
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
"GPU 内存不足,无法完整显示 {count} 个纹理集({names}):请在设置中降低视口的纹理分辨率。绘制和导出不受影响。",
|
||||
),
|
||||
("Not exported: no source in this texture set", "未导出:此纹理集中没有来源"),
|
||||
("Not saved: {error}", "未保存:{error}"),
|
||||
("Off", "关"),
|
||||
("Offset", "偏移"),
|
||||
("Offset right", "向右偏移"),
|
||||
("Offset up", "向上偏移"),
|
||||
("Offsets the textures by the height channel, at the height to normal strength", "按高度通道偏移纹理,偏移量取决于高度转法线强度"),
|
||||
@@ -533,6 +557,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Particles", "粒子"),
|
||||
("Passthrough", "穿透"),
|
||||
("Paste as instance", "粘贴为实例"),
|
||||
("Paste effect", "粘贴效果"),
|
||||
("Paste layer(s)", "粘贴图层"),
|
||||
("Path", "路径"),
|
||||
("Path trace on the processor instead of the graphics card (slower)", "在处理器而非显卡上进行路径追踪(较慢)"),
|
||||
@@ -567,6 +592,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Radial copies", "径向副本"),
|
||||
("Radius (texels at 2K)", "半径(2K 下的纹素数)"),
|
||||
("RENDERING", "渲染"),
|
||||
("Range", "范围"),
|
||||
("Rebind any menu item, tool or command", "重新绑定任意菜单项、工具或命令"),
|
||||
("Recent projects", "最近的项目"),
|
||||
(
|
||||
@@ -608,6 +634,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Resizing", "正在调整大小"),
|
||||
("Restore every default shortcut", "恢复所有默认快捷键"),
|
||||
("Return to painting mode", "返回绘画模式"),
|
||||
("Return to this step", "返回到此步骤"),
|
||||
("Right-click a layer > Create smart material", "右键单击图层 > 创建智能材质"),
|
||||
("Rotation", "旋转"),
|
||||
("Rotation (degrees)", "旋转(度)"),
|
||||
@@ -877,4 +904,29 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"使用操作系统的窗口边框和按钮,而不是 TextureCraft 自己的标题栏",
|
||||
),
|
||||
("Brushes", "笔刷库"),
|
||||
("My brushes", "我的笔刷"),
|
||||
("Use this brush (keeps its size)", "使用此笔刷(保留大小)"),
|
||||
("Brush name", "笔刷名称"),
|
||||
("Save current brush", "保存当前笔刷"),
|
||||
("Start window", "启动窗口"),
|
||||
("Show at startup", "启动时显示"),
|
||||
("Continue with the sample project", "继续使用示例项目"),
|
||||
("No recent projects yet", "暂无最近的项目"),
|
||||
("Text", "文字"),
|
||||
("Font", "字体"),
|
||||
("Style", "样式"),
|
||||
("Use as brush alpha", "用作笔刷 Alpha"),
|
||||
("Place as decal", "作为贴花放置"),
|
||||
("Click: turn this channel on or off. Alt+click: this channel only", "单击:打开或关闭此通道。Alt+单击:仅此通道"),
|
||||
("Show all", "全部显示"),
|
||||
("Hide all", "全部隐藏"),
|
||||
("Invert show/hide", "反转显示/隐藏"),
|
||||
("Show or hide texture sets", "显示或隐藏纹理集"),
|
||||
("Focus: show only the active texture set", "聚焦:仅显示当前纹理集"),
|
||||
("Unsaved changes", "未保存的更改"),
|
||||
("Don't save", "不保存"),
|
||||
("Save the changes to {name} before closing?", "关闭前是否保存对 {name} 的更改?"),
|
||||
("Twill weave", "斜纹织物"),
|
||||
("Save the changes to {name} first?", "是否先保存对 {name} 的更改?"),
|
||||
];
|
||||
@@ -70,6 +70,8 @@ pub struct TextureCraftApp {
|
||||
pub gpu: Option<gpu::GpuLink>,
|
||||
pub control: Option<std::sync::mpsc::Receiver<ControlRequest>>,
|
||||
pub toasts: Vec<Toast>,
|
||||
/// Texture sets the GPU could not hold, and the text of the one sticky toast naming them.
|
||||
pub(crate) gpu_memory: (Vec<String>, Option<String>),
|
||||
pub bake: Option<BakeJob>,
|
||||
pub resize: Option<ResizeJob>,
|
||||
pub thumbs: thumbs::Thumbs,
|
||||
@@ -78,6 +80,8 @@ pub struct TextureCraftApp {
|
||||
pub fps: f32,
|
||||
/// User smart materials found in the library folder (refreshed on demand).
|
||||
pub library: Option<Vec<std::path::PathBuf>>,
|
||||
/// User brush presets found in the brushes folder (refreshed on demand).
|
||||
pub brushes: Option<Vec<std::path::PathBuf>>,
|
||||
/// Rendering mode's path tracer.
|
||||
pub render: render_mode::RenderView,
|
||||
/// Smoothed CPU time spent building the UI per frame (ms).
|
||||
@@ -110,7 +114,7 @@ impl TextureCraftApp {
|
||||
// Bakes cast their rays on a GPU device of their own (created on the first bake).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
texturecraft_engine::bake_cmds::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new()));
|
||||
let gpu = cc.wgpu_render_state.as_ref().map(gpu::init);
|
||||
let gpu = cc.wgpu_render_state.as_ref().map(|rs| gpu::init(rs, &cc.egui_ctx));
|
||||
// The first run speaks the OS (or browser) language.
|
||||
let ui = cc.storage.and_then(|s| eframe::get_value::<UiState>(s, "ui")).unwrap_or_else(|| {
|
||||
let mut ui = UiState::default();
|
||||
@@ -124,6 +128,7 @@ impl TextureCraftApp {
|
||||
gpu,
|
||||
control: None,
|
||||
toasts: Vec::new(),
|
||||
gpu_memory: (Vec::new(), None),
|
||||
bake: None,
|
||||
resize: None,
|
||||
thumbs: thumbs::Thumbs::default(),
|
||||
@@ -132,6 +137,7 @@ impl TextureCraftApp {
|
||||
ui_ms: 0.0,
|
||||
profiler: profile::Profiler::default(),
|
||||
library: None,
|
||||
brushes: None,
|
||||
render: render_mode::RenderView::default(),
|
||||
last_paint_point: None,
|
||||
placing_decal: None,
|
||||
@@ -170,6 +176,12 @@ impl TextureCraftApp {
|
||||
self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 } });
|
||||
}
|
||||
|
||||
/// An error toast that stays until the user dismisses it (for a problem that persists and
|
||||
/// is reported once, like a texture set the GPU could not hold).
|
||||
pub fn toast_sticky(&mut self, text: impl Into<String>) {
|
||||
self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY });
|
||||
}
|
||||
|
||||
/// Start baking texture sets in the background (one after another).
|
||||
pub fn start_bake(&mut self, sets: Vec<usize>) {
|
||||
if self.bake.is_some() || sets.is_empty() {
|
||||
@@ -378,7 +390,10 @@ impl eframe::App for TextureCraftApp {
|
||||
self.autosave(now);
|
||||
i18n::set_language(&self.ui.prefs.language);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
keymap::sync_captured(&self.ui.keymap);
|
||||
{
|
||||
keymap::sync_captured(&self.ui.keymap);
|
||||
web_files::sync_unsaved(self);
|
||||
}
|
||||
self.fonts.update(ctx, i18n::current().code, self.ui.windows.settings);
|
||||
menus::shortcuts(self, ctx);
|
||||
profile::drive(self, ctx);
|
||||
@@ -465,10 +480,19 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
if app.toasts.is_empty() {
|
||||
return;
|
||||
}
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(250));
|
||||
// Expiring toasts need frames to disappear on time; sticky ones wait for a click.
|
||||
if app.toasts.iter().any(|t| t.until.is_finite()) {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(250));
|
||||
}
|
||||
let tk = theme::Tokens::get(ctx);
|
||||
let mut dismissed = None;
|
||||
// Toasts fit the window: at most 360 points wide and, for their text, a part of its height
|
||||
// (longer text scrolls), so a sticky toast's dismiss button always stays on screen.
|
||||
let screen = ctx.content_rect().size();
|
||||
let max_width = (screen.x - 52.0).clamp(120.0, 360.0);
|
||||
let max_text_height = (screen.y * 0.35).clamp(48.0, 220.0);
|
||||
egui::Area::new(egui::Id::unique("toasts")).anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-16.0, -36.0)).show(ctx, |ui| {
|
||||
for t in &app.toasts {
|
||||
for (i, t) in app.toasts.iter().enumerate() {
|
||||
egui::Frame::NONE
|
||||
.fill(tk.panel)
|
||||
.stroke(egui::Stroke::new(1.0, if t.error { tk.danger } else { tk.accent }))
|
||||
@@ -476,10 +500,26 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
.shadow(ui.visuals().popup_shadow)
|
||||
.inner_margin(egui::Margin::symmetric(10, 6))
|
||||
.show(ui, |ui| {
|
||||
ui.set_max_width(360.0);
|
||||
ui.label(egui::RichText::new(&t.text).color(tk.text_strong));
|
||||
ui.set_max_width(max_width);
|
||||
let sticky = t.until.is_infinite();
|
||||
ui.horizontal_top(|ui| {
|
||||
// The text wraps in the width the dismiss button leaves.
|
||||
let width = if sticky { max_width - 28.0 } else { max_width };
|
||||
ui.allocate_ui_with_layout(egui::vec2(width, 0.0), egui::Layout::top_down(egui::Align::Min), |ui| {
|
||||
egui::ScrollArea::vertical().id_salt(("toast", i)).max_height(max_text_height).show(ui, |ui| {
|
||||
ui.set_max_width(width);
|
||||
ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap());
|
||||
});
|
||||
});
|
||||
if sticky && widgets::icon_button(ui, egui_phosphor::regular::X, i18n::tr("Dismiss"), false, 18.0).clicked() {
|
||||
dismissed = Some(i);
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
}
|
||||
});
|
||||
if let Some(i) = dismissed.filter(|i| *i < app.toasts.len()) {
|
||||
app.toasts.remove(i);
|
||||
}
|
||||
}
|
||||
@@ -117,6 +117,11 @@ pub fn implemented(id: &str) -> bool {
|
||||
|
||||
/// Invoke a menu item (menus, shortcuts, palette, control channel `ui.menu.invoke`).
|
||||
pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) {
|
||||
if matches!(id, "ui.newProject" | "file.open" | "file.close" | "project.sample")
|
||||
&& crate::windows::ask_to_save(app, crate::state::Unsaved::Command(id.into()))
|
||||
{
|
||||
return;
|
||||
}
|
||||
if let Some(panel) = crate::docking::view_panel(id) {
|
||||
app.ui.dock.toggle(panel);
|
||||
return;
|
||||
@@ -255,15 +260,30 @@ fn menu_item(app: &mut TextureCraftApp, ctx: &egui::Context, ui: &mut egui::Ui,
|
||||
/// plus the fixed brush keys.
|
||||
/// Keys pressed in a floating panel's own OS window run the shortcuts the main window's keys do.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn forwarded_shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context, events: Vec<egui::Event>, _modifiers: Modifiers) {
|
||||
pub fn forwarded_shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context, events: Vec<egui::Event>, held: Modifiers) {
|
||||
if crate::keymap::capturing(ctx) {
|
||||
return;
|
||||
}
|
||||
let active = crate::keymap::active(&app.ui.keymap);
|
||||
for event in events {
|
||||
let event = clipboard_key(&event, held).unwrap_or(event);
|
||||
let egui::Event::Key { key, pressed: true, repeat: false, modifiers, .. } = event else { continue };
|
||||
let Some((id, _)) = active.iter().find(|(_, sc)| sc.logical_key == key && modifiers.matches_logically(sc.modifiers)) else { continue };
|
||||
invoke(app, ctx, id);
|
||||
invoke(app, ctx, effect_command(app, id));
|
||||
}
|
||||
}
|
||||
|
||||
/// Layer shortcuts act on the selected effect instead of its layer (copy, cut, duplicate,
|
||||
/// remove), and paste a copied effect onto the selection.
|
||||
fn effect_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str {
|
||||
let effect = matches!(app.session.target, texturecraft_engine::StackTarget::Effect(_));
|
||||
match id {
|
||||
"layer.copy" if effect => "effect.copy",
|
||||
"layer.cut" if effect => "effect.cut",
|
||||
"layer.duplicate" if effect => "effect.duplicate",
|
||||
"layer.remove" if effect => "effect.remove",
|
||||
"layer.paste" if enabled(app, "effect.paste") => "effect.paste",
|
||||
_ => id,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -271,6 +291,10 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
if crate::keymap::capturing(ctx) || (ctx.memory(|m| m.focused().is_some()) && ctx.egui_wants_keyboard_input()) {
|
||||
return;
|
||||
}
|
||||
ctx.input_mut(|i| {
|
||||
let keys: Vec<_> = i.events.iter().filter_map(|e| clipboard_key(e, i.modifiers)).collect();
|
||||
i.events.extend(keys);
|
||||
});
|
||||
if !ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. }))) {
|
||||
return;
|
||||
}
|
||||
@@ -295,6 +319,25 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
});
|
||||
for id in fire {
|
||||
invoke(app, ctx, id);
|
||||
if matches!(id, "layer.copy" | "layer.cut")
|
||||
&& let Some(layer) = app.session.selected_layer().and_then(|l| app.session.doc.project.layers.get(&l))
|
||||
{
|
||||
// Ctrl+V reaches the app only while the system clipboard holds text or an image.
|
||||
ctx.copy_text(layer.name.clone());
|
||||
}
|
||||
invoke(app, ctx, effect_command(app, id));
|
||||
}
|
||||
}
|
||||
|
||||
/// The desktop and web shells turn Ctrl+C, Ctrl+X and Ctrl+V (and Ctrl+Insert, Shift+Delete,
|
||||
/// Shift+Insert) into clipboard events instead of key presses. Outside a text field they are the
|
||||
/// shortcuts bound to Ctrl+C, Ctrl+X and Ctrl+V (copy, cut and paste a layer by default).
|
||||
fn clipboard_key(event: &egui::Event, held: Modifiers) -> Option<egui::Event> {
|
||||
let key = match event {
|
||||
egui::Event::Copy => Key::C,
|
||||
egui::Event::Cut => Key::X,
|
||||
egui::Event::Paste(_) | egui::Event::PasteImage(_) => Key::V,
|
||||
_ => return None,
|
||||
};
|
||||
Some(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: held | Modifiers::COMMAND })
|
||||
}
|
||||
+107
-3
@@ -11,11 +11,12 @@ use texturecraft_engine::core::ProceduralKind;
|
||||
use texturecraft_engine::filter_lib::FILTERS;
|
||||
use texturecraft_engine::materials::MATERIALS;
|
||||
use texturecraft_engine::paint::alphas;
|
||||
use texturecraft_engine::paint::presets::{BrushPreset, PRESETS};
|
||||
use texturecraft_engine::smart_masks::SMART_MASKS;
|
||||
use texturecraft_render::ibl::ENVIRONMENTS;
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::i18n::{tr, trf};
|
||||
use crate::theme::Tokens;
|
||||
use crate::widgets::{dnd_release, icon_button};
|
||||
|
||||
@@ -25,6 +26,7 @@ pub(crate) enum Tab {
|
||||
Smart,
|
||||
Masks,
|
||||
Filters,
|
||||
Brushes,
|
||||
Alphas,
|
||||
Procedurals,
|
||||
Environments,
|
||||
@@ -32,11 +34,12 @@ pub(crate) enum Tab {
|
||||
}
|
||||
|
||||
/// The shelf tabs: icon and (English, translated where shown) name.
|
||||
pub(crate) const TABS: [(Tab, &str, &str); 8] = [
|
||||
pub(crate) const TABS: [(Tab, &str, &str); 9] = [
|
||||
(Tab::Materials, ic::SPHERE, "Materials"),
|
||||
(Tab::Smart, ic::STACK, "Smart materials"),
|
||||
(Tab::Masks, ic::CIRCLE_HALF, "Smart masks"),
|
||||
(Tab::Filters, ic::FUNNEL, "Filters"),
|
||||
(Tab::Brushes, ic::PAINT_BRUSH_BROAD, "Brushes"),
|
||||
(Tab::Alphas, ic::SHAPES, "Alphas"),
|
||||
(Tab::Procedurals, ic::CHECKERBOARD, "Procedurals"),
|
||||
(Tab::Environments, ic::SUN_HORIZON, "Environments"),
|
||||
@@ -75,7 +78,17 @@ pub fn apply(app: &mut TextureCraftApp, asset: &Asset) {
|
||||
let (cmd, params) = match asset {
|
||||
Asset::Material(id) => ("material.apply", json!({"material": id})),
|
||||
Asset::SmartMask(id) => ("mask.smart.apply", json!({"name": id})),
|
||||
Asset::Filter(id) => ("effect.add.filter", json!({"filter": id, "target": if crate::dock::targets_content(app) { "content" } else { "mask" }})),
|
||||
Asset::Filter(id) => {
|
||||
let content = crate::dock::targets_content(app);
|
||||
if app.run("effect.add.filter", json!({"filter": id, "target": if content { "content" } else { "mask" }})).is_some()
|
||||
&& content
|
||||
&& let Some(name) = unpainted_paint_layer(app)
|
||||
{
|
||||
// Otherwise the filter seems to do nothing: it has nothing to change yet.
|
||||
app.toast(trf("\"{layer}\" has no paint yet: the filter changes what you paint on it.", &[("layer", &name)]), false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
Asset::Alpha(id) => ("tool.brush", json!({"alpha": {"library": id}})),
|
||||
Asset::Library(path) => ("material.load", json!({"path": path})),
|
||||
Asset::Texture(name) => ("layer.add.image", json!({"name": name})),
|
||||
@@ -83,6 +96,20 @@ pub fn apply(app: &mut TextureCraftApp, asset: &Asset) {
|
||||
app.run(cmd, params);
|
||||
}
|
||||
|
||||
/// The selected layer's name when it is a paint layer with nothing painted (in itself or in its
|
||||
/// content paint effects).
|
||||
fn unpainted_paint_layer(app: &TextureCraftApp) -> Option<String> {
|
||||
use texturecraft_engine::core::{EffectKind, LayerKind};
|
||||
let s = &app.session;
|
||||
let layer = s.selected_layer().and_then(|id| s.doc.project.content_layer(id))?;
|
||||
if !matches!(layer.kind, LayerKind::Paint) {
|
||||
return None;
|
||||
}
|
||||
let ids: Vec<_> = std::iter::once(layer.id).chain(layer.content_effects.iter().filter(|e| matches!(e.kind, EffectKind::Paint)).map(|e| e.id)).collect();
|
||||
let painted = s.doc.pixels.layers.iter().any(|((id, _), img)| ids.contains(id) && img.allocated_count() > 0);
|
||||
(!painted).then(|| layer.name.clone())
|
||||
}
|
||||
|
||||
/// What a view accepts from the shelf.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DropZone {
|
||||
@@ -158,6 +185,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
Tab::Masks => smart_masks(app, ui, &ctx, &filter, title),
|
||||
Tab::Filters => filters(app, ui, &ctx, &filter, title),
|
||||
Tab::Brushes => brushes(app, ui, &ctx, &filter, title),
|
||||
Tab::Alphas => alpha_library(app, ui, &ctx, &filter, title),
|
||||
Tab::Procedurals => procedurals(app, ui, &ctx, &filter, title),
|
||||
Tab::Environments => environments(app, ui, &filter, title),
|
||||
@@ -332,6 +360,82 @@ fn filters(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter:
|
||||
}
|
||||
}
|
||||
|
||||
/// Brush presets, grouped by category, then the user's own: a click sets the brush's stroke
|
||||
/// (alpha, spacing, flow, jitters…) and keeps its size.
|
||||
fn brushes(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) {
|
||||
let shown: Vec<&BrushPreset> = PRESETS.iter().filter(|p| matches(filter, &[p.label, p.category, p.id])).collect();
|
||||
if !shown.is_empty() {
|
||||
title(ui, name);
|
||||
for cat in categories(&shown, |p| p.category) {
|
||||
header(ui, cat);
|
||||
tiles(ui, |ui| {
|
||||
for p in shown.iter().filter(|p| p.category == cat) {
|
||||
let tex = app.thumbs.brush_preset(ctx, p);
|
||||
if tile(ui, tex.as_ref(), p.label, tr("Use this brush (keeps its size)"), None).clicked() {
|
||||
app.run("brush.preset.apply", json!({"preset": p.id}));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
my_brushes(app, ui, filter);
|
||||
}
|
||||
|
||||
/// The user's saved brush presets (desktop brushes folder) and saving the current brush there.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn my_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) {
|
||||
use texturecraft_engine::brush_preset_cmds::BRUSH_EXT;
|
||||
let dir = crate::user_dir("brushes");
|
||||
if app.brushes.is_none() {
|
||||
let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(&dir)
|
||||
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == BRUSH_EXT)).collect())
|
||||
.unwrap_or_default();
|
||||
files.sort();
|
||||
app.brushes = Some(files);
|
||||
}
|
||||
let files = app.brushes.clone().unwrap_or_default();
|
||||
let name = |f: &std::path::PathBuf| f.file_stem().and_then(|s| s.to_str()).unwrap_or("brush").to_string();
|
||||
let shown: Vec<_> = files.iter().filter(|f| matches(filter, &[&name(f)])).collect();
|
||||
if !filter.is_empty() && shown.is_empty() {
|
||||
return;
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
header(ui, tr("My brushes"));
|
||||
if ui.small_button(ic::ARROW_CLOCKWISE).on_hover_text(tr("Rescan the library folder")).clicked() {
|
||||
app.brushes = None;
|
||||
}
|
||||
});
|
||||
for f in shown {
|
||||
if ui
|
||||
.add(egui::Button::selectable(false, format!("{} {}", ic::PAINT_BRUSH_BROAD, name(f))))
|
||||
.on_hover_text(tr("Use this brush (keeps its size)"))
|
||||
.clicked()
|
||||
{
|
||||
app.run("brush.preset.load", json!({"path": f.display().to_string()}));
|
||||
}
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
let id = ui.make_persistent_id("brush_preset_name");
|
||||
let mut new_name: String = ui.data_mut(|d| d.get_temp(id)).unwrap_or_default();
|
||||
ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(110.0));
|
||||
let file = texturecraft_engine::formats::export::sanitize_file_stem(new_name.trim());
|
||||
if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() {
|
||||
let path = dir.join(format!("{file}.{BRUSH_EXT}"));
|
||||
// A folder that can't be made fails the save, which reports it.
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_some() {
|
||||
new_name.clear();
|
||||
app.brushes = None;
|
||||
}
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(id, new_name));
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn my_brushes(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {}
|
||||
|
||||
/// The built-in alpha library, grouped by category; the brush's alpha is outlined.
|
||||
fn alpha_library(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) {
|
||||
let tk = Tokens::get(ctx);
|
||||
|
||||
@@ -15,6 +15,18 @@ pub enum Mode {
|
||||
Rendering,
|
||||
}
|
||||
|
||||
/// The Alpha tab's text: what to draw and in which font (empty: the default font).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct TextUi {
|
||||
pub text: String,
|
||||
pub font: String,
|
||||
pub style: String,
|
||||
/// Installed and built-in families with their styles (`text.fonts`), read when first shown.
|
||||
#[serde(skip)]
|
||||
pub fonts: Vec<(String, Vec<String>)>,
|
||||
}
|
||||
|
||||
/// Rendering mode settings.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
@@ -61,6 +73,25 @@ pub struct Windows {
|
||||
/// Browser File › Export Mesh: the download format choice.
|
||||
#[serde(default)]
|
||||
pub export_mesh: bool,
|
||||
/// The start window: new, open, recent projects (the app opens it at launch).
|
||||
#[serde(skip)]
|
||||
pub start: bool,
|
||||
/// What waits on the unsaved-changes dialog: save, don't save or cancel.
|
||||
#[serde(skip)]
|
||||
pub unsaved: Option<Unsaved>,
|
||||
}
|
||||
|
||||
/// An action that replaces or ends the project, held while the project has unsaved changes.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Unsaved {
|
||||
Quit,
|
||||
/// A menu command (New project, Open, Close, Open sample project).
|
||||
Command(String),
|
||||
/// Open this project or mesh file.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Open(String),
|
||||
/// Open a project or mesh file's bytes (picked or dropped in the browser): its name and bytes.
|
||||
Load(String, std::sync::Arc<Vec<u8>>),
|
||||
}
|
||||
|
||||
/// Edit › Settings.
|
||||
@@ -82,6 +113,8 @@ pub struct Prefs {
|
||||
pub accent: crate::theme::Accent,
|
||||
/// The system draws the window's title bar instead of TextureCraft (desktop; read at startup).
|
||||
pub system_title_bar: bool,
|
||||
/// Show the start window at launch.
|
||||
pub start_window: bool,
|
||||
}
|
||||
|
||||
impl Default for Prefs {
|
||||
@@ -94,6 +127,7 @@ impl Default for Prefs {
|
||||
brightness: crate::theme::Brightness::default(),
|
||||
accent: crate::theme::Accent::default(),
|
||||
system_title_bar: false,
|
||||
start_window: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -149,6 +183,9 @@ pub struct ExportUi {
|
||||
pub size: u32,
|
||||
/// "" (project), openGl or directX.
|
||||
pub normal_format: String,
|
||||
/// "" (by file format: sRGB, or linear for float files), or a colour space name.
|
||||
#[serde(default)]
|
||||
pub color_space: String,
|
||||
/// Texture sets excluded from export.
|
||||
pub skip: Vec<usize>,
|
||||
pub tab: u8,
|
||||
@@ -171,6 +208,7 @@ impl Default for ExportUi {
|
||||
dilation: 16,
|
||||
size: 0,
|
||||
normal_format: String::new(),
|
||||
color_space: String::new(),
|
||||
skip: Vec::new(),
|
||||
tab: 0,
|
||||
draft: None,
|
||||
@@ -209,6 +247,8 @@ pub struct UiState {
|
||||
#[serde(default)]
|
||||
pub shelf_tab: usize,
|
||||
pub props_tab: PropsTab,
|
||||
#[serde(default)]
|
||||
pub text: TextUi,
|
||||
/// Layer being renamed and the edit buffer.
|
||||
pub rename: Option<(u64, String)>,
|
||||
pub new_project: NewProject,
|
||||
@@ -263,6 +303,7 @@ impl Default for UiState {
|
||||
shelf_filter: String::new(),
|
||||
shelf_tab: 0,
|
||||
props_tab: PropsTab::Brush,
|
||||
text: TextUi::default(),
|
||||
rename: None,
|
||||
new_project: NewProject::default(),
|
||||
uv_wireframe: true,
|
||||
|
||||
@@ -6,7 +6,8 @@ use std::collections::HashMap;
|
||||
|
||||
use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions};
|
||||
use texturecraft_engine::core::ProceduralKind;
|
||||
use texturecraft_engine::paint::{BrushAlpha, alphas};
|
||||
use texturecraft_engine::paint::presets::BrushPreset;
|
||||
use texturecraft_engine::paint::{BrushAlpha, BrushSettings, Shape, alphas};
|
||||
use texturecraft_engine::preview::{self, Sample};
|
||||
use texturecraft_engine::texel::linear_to_srgb;
|
||||
|
||||
@@ -17,7 +18,8 @@ const SPHERE_PX: usize = 72;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Thumbs {
|
||||
/// Shelf thumbnails by key (`mat:<id>`, `mask:<id>`, `filter:<id>`, `proc:<kind>`, `alpha:<id>`).
|
||||
/// Shelf thumbnails by key (`mat:<id>`, `mask:<id>`, `filter:<id>`, `proc:<kind>`, `alpha:<id>`,
|
||||
/// `brush:<id>`).
|
||||
shelf: HashMap<String, TextureHandle>,
|
||||
images: HashMap<String, TextureHandle>,
|
||||
/// (frame, thumbnails rendered in it).
|
||||
@@ -114,11 +116,18 @@ impl Thumbs {
|
||||
return t.clone();
|
||||
}
|
||||
let n = 64usize;
|
||||
// Letterboxed to keep its proportions, over black where it is transparent.
|
||||
let aspect = img.width as f32 / img.height.max(1) as f32;
|
||||
let (sx, sy) = if aspect >= 1.0 { (1.0, aspect) } else { (1.0 / aspect.max(1e-6), 1.0) };
|
||||
let mut ci = ColorImage::filled([n, n], Color32::BLACK);
|
||||
for y in 0..n {
|
||||
for x in 0..n {
|
||||
let s = img.sample((x as f32 + 0.5) / n as f32, (y as f32 + 0.5) / n as f32);
|
||||
let enc = |v: f32| if img.srgb { (v.clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(v) * 255.0) as u8 };
|
||||
let (u, v) = (((x as f32 + 0.5) / n as f32 - 0.5) * sx + 0.5, ((y as f32 + 0.5) / n as f32 - 0.5) * sy + 0.5);
|
||||
if !((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v)) {
|
||||
continue;
|
||||
}
|
||||
let s = img.sample(u, v);
|
||||
let enc = |c: f32| if img.srgb { (c.clamp(0.0, 1.0) * s[3].clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(c * s[3]) * 255.0) as u8 };
|
||||
ci.pixels[y * n + x] = Color32::from_rgb(enc(s[0]), enc(s[1]), enc(s[2]));
|
||||
}
|
||||
}
|
||||
@@ -192,6 +201,54 @@ impl Thumbs {
|
||||
ColorImage::new([n, n], a.render(n, 2).into_iter().map(|v| Color32::from_gray((v * 255.0 + 0.5) as u8)).collect())
|
||||
})
|
||||
}
|
||||
|
||||
/// A brush preset's stroke along an S curve.
|
||||
pub fn brush_preset(&mut self, ctx: &egui::Context, p: &BrushPreset) -> Option<TextureHandle> {
|
||||
self.shelf(ctx, format!("brush:{}", p.id), || stroke_preview(&p.applied(&BrushSettings::default()), 64))
|
||||
}
|
||||
}
|
||||
|
||||
/// `b`'s stamps (shape, spacing, flow, angle, path following, jitters) along an S curve across
|
||||
/// an `n`-pixel square, white on black.
|
||||
fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage {
|
||||
let library = b.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image);
|
||||
let radius = n as f32 * 0.11;
|
||||
let shape = Shape { alpha: b.alpha, image: None, library, level: 0 }.at_radius(radius);
|
||||
let curve = |t: f32| (n as f32 * (0.15 + 0.7 * t), n as f32 * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin()));
|
||||
let mut cover = vec![0f32; n * n];
|
||||
// Deterministic jitter per stamp.
|
||||
let rnd = |i: u32, k: u32| (i.wrapping_mul(0x9E37_79B9) ^ k.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32;
|
||||
let step = (b.spacing * 2.0 * radius).max(0.5);
|
||||
let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32);
|
||||
let mut last = curve(0.0);
|
||||
while t <= 1.0 && i < 2000 {
|
||||
let p = curve(t);
|
||||
travelled += (p.0 - last.0).hypot(p.1 - last.1);
|
||||
last = p;
|
||||
t += 0.002;
|
||||
if travelled < step {
|
||||
continue;
|
||||
}
|
||||
travelled = 0.0;
|
||||
i += 1;
|
||||
let r = radius * (1.0 - b.jitter_size * rnd(i, 1));
|
||||
let tangent = if b.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 };
|
||||
let angle = b.angle.to_radians() + tangent + b.jitter_angle * std::f32::consts::TAU * rnd(i, 2);
|
||||
let (cx, cy) = (p.0 + b.jitter_position * radius * (rnd(i, 3) * 2.0 - 1.0), p.1 + b.jitter_position * radius * (rnd(i, 4) * 2.0 - 1.0));
|
||||
let flow = b.flow * (1.0 - b.jitter_flow * rnd(i, 5));
|
||||
let (sin, cos) = angle.sin_cos();
|
||||
let (x0, x1) = ((cx - r).floor().max(0.0) as usize, ((cx + r).ceil() as usize).min(n));
|
||||
let (y0, y1) = ((cy - r).floor().max(0.0) as usize, ((cy + r).ceil() as usize).min(n));
|
||||
for y in y0..y1 {
|
||||
for x in x0..x1 {
|
||||
let (dx, dy) = ((x as f32 + 0.5 - cx) / r, (cy - y as f32 - 0.5) / r);
|
||||
let a = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, b.hardness, i) * flow;
|
||||
let c = &mut cover[y * n + x];
|
||||
*c = 1.0 - (1.0 - *c) * (1.0 - a.clamp(0.0, 1.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
ColorImage::new([n, n], cover.into_iter().map(|v| Color32::from_gray((v * b.opacity * 255.0 + 0.5) as u8)).collect())
|
||||
}
|
||||
|
||||
/// A small shaded sphere drawn with a vertex-colored mesh (layer thumbnails, previews).
|
||||
|
||||
@@ -95,6 +95,59 @@ fn shade(app: &TextureCraftApp) -> Shade {
|
||||
}
|
||||
}
|
||||
|
||||
/// Show what the GPU side reported (each message once while its toast is up).
|
||||
fn gpu_report_toasts(app: &mut TextureCraftApp, reports: crate::gpu::GpuReports) {
|
||||
let names: Vec<String> = reports.memory.iter().filter_map(|ts| app.session.doc.project.texture_sets.get(*ts).map(|t| t.name.clone())).collect();
|
||||
if !names.is_empty() {
|
||||
// One sticky notice for every set the GPU could not hold (they are not retried, so the
|
||||
// notice stays until dismissed); after a dismissal, a new one names only the new sets.
|
||||
let (sets, shown) = &mut app.gpu_memory;
|
||||
let current = shown.take().filter(|text| app.toasts.iter().any(|t| &t.text == text));
|
||||
match ¤t {
|
||||
Some(text) => app.toasts.retain(|t| &t.text != text),
|
||||
None => sets.clear(),
|
||||
}
|
||||
for n in names {
|
||||
if !sets.contains(&n) {
|
||||
sets.push(n);
|
||||
}
|
||||
}
|
||||
let text = match sets.as_slice() {
|
||||
[one] => trf(
|
||||
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
&[("name", one)],
|
||||
),
|
||||
many => {
|
||||
let short = |n: &String| match n.char_indices().nth(MAX_NAME_CHARS) {
|
||||
Some((cut, _)) => format!("\"{}...\"", &n[..cut]),
|
||||
None => format!("\"{n}\""),
|
||||
};
|
||||
let mut list = many.iter().take(MAX_NAMED_SETS).map(short).collect::<Vec<_>>().join(", ");
|
||||
if many.len() > MAX_NAMED_SETS {
|
||||
list.push_str(", ...");
|
||||
}
|
||||
trf(
|
||||
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
|
||||
&[("count", &many.len()), ("names", &list)],
|
||||
)
|
||||
}
|
||||
};
|
||||
app.gpu_memory.1 = Some(text.clone());
|
||||
app.toast_sticky(text);
|
||||
}
|
||||
for e in &reports.errors {
|
||||
let text = trf("GPU error: {error}", &[("error", e)]);
|
||||
if !app.toasts.iter().any(|t| t.text == text) {
|
||||
app.toast(text, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Texture sets a GPU memory notice names before "...".
|
||||
const MAX_NAMED_SETS: usize = 5;
|
||||
/// Characters of a set name in that notice (long names are cut, with "...").
|
||||
const MAX_NAME_CHARS: usize = 32;
|
||||
|
||||
/// This frame's scene sync (compositing and GPU uploads), run by the first view drawn, after
|
||||
/// that view handled its input: a stroke shows in the frame it is painted, not the next.
|
||||
pub struct PendingSync(Option<Option<crate::gpu::AuxView>>);
|
||||
@@ -105,7 +158,9 @@ fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, frame: Frame, sy
|
||||
(Some(aux), Some(g)) => {
|
||||
let t0 = crate::now_ms();
|
||||
let scene = g.sync(&mut app.session, aux, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms));
|
||||
let reports = g.take_reports();
|
||||
app.profiler.sync_ms += (crate::now_ms() - t0) as f32;
|
||||
gpu_report_toasts(app, reports);
|
||||
// Display tiles left for later frames (the frame budget ran out).
|
||||
if app.session.caches.iter().any(|c| !c.upload.is_empty()) {
|
||||
ui.ctx().request_repaint();
|
||||
@@ -199,14 +254,16 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
app.session.viewport = Vec2::new(size.x.max(16.0), size.y.max(16.0));
|
||||
let (alt, shift) = ui.input(|i| (i.modifiers.alt, i.modifiers.shift));
|
||||
let local = |p: egui::Pos2| Vec2::new(p.x - rect.left(), p.y - rect.top());
|
||||
let navigating = alt || ui.input(|i| i.pointer.middle_down() || i.pointer.secondary_down());
|
||||
let adjusting = brush_drag(app, ui, &resp);
|
||||
let navigating = !adjusting && (alt || ui.input(|i| i.pointer.middle_down() || i.pointer.secondary_down()));
|
||||
|
||||
// Navigation (S + drag manipulates the projection stencil instead, below).
|
||||
let delta = ui.input(|i| i.pointer.delta());
|
||||
let s_held = ui.input(|i| i.key_down(egui::Key::S)) && !ui.ctx().egui_wants_keyboard_input();
|
||||
let stencil_drag = s_held && app.session.tool.stencil.is_some();
|
||||
if stencil_drag {
|
||||
// The stencil moves, turns and scales instead of the camera (handled below).
|
||||
if stencil_drag || adjusting {
|
||||
// The stencil moves, turns and scales instead of the camera (handled below), or the
|
||||
// brush changes.
|
||||
} else if resp.dragged_by(PointerButton::Middle) {
|
||||
app.session.camera.pan(delta.x / size.y, delta.y / size.y);
|
||||
} else if alt && resp.dragged_by(PointerButton::Primary) {
|
||||
@@ -302,8 +359,15 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
// The selected decal's frame and handles: drag to move, scale or turn it.
|
||||
let decal_drag = !alt && !s_held && !v_held && !focus_pick && placing.is_none() && touch.is_none() && decal_input(app, ui, &resp, rect);
|
||||
// Painting.
|
||||
let painting =
|
||||
app.ui.mode == crate::state::Mode::Painting && !alt && !s_held && !v_held && !focus_pick && placing.is_none() && touch.is_none() && !decal_drag;
|
||||
let painting = app.ui.mode == crate::state::Mode::Painting
|
||||
&& !alt
|
||||
&& !adjusting
|
||||
&& !s_held
|
||||
&& !v_held
|
||||
&& !focus_pick
|
||||
&& placing.is_none()
|
||||
&& touch.is_none()
|
||||
&& !decal_drag;
|
||||
let path_tool = app.session.tool.tool == Tool::Path;
|
||||
let vp = app.session.viewport;
|
||||
let show = |app: &TextureCraftApp, p: Vec3| project(app, rect, p);
|
||||
@@ -368,8 +432,9 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
if app.ui.mode == crate::state::Mode::Painting
|
||||
&& !navigating
|
||||
&& resp.hovered()
|
||||
&& matches!(app.session.tool.tool, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path)
|
||||
&& let Some(hp) = resp.hover_pos()
|
||||
&& brush_tool(app.session.tool.tool)
|
||||
// While a Ctrl+drag changes the brush, its cursor stays where the drag began.
|
||||
&& let Some(hp) = if adjusting { ui.input(|i| i.pointer.press_origin()) } else { resp.hover_pos() }
|
||||
&& let Some(hit) = app.session.pick(local(hp), app.session.viewport)
|
||||
{
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::None);
|
||||
@@ -392,6 +457,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
}
|
||||
stencil_overlay(app, ui, rect);
|
||||
decal_overlay(app, ui, rect);
|
||||
brush_readout(app, ui, &resp, adjusting);
|
||||
if app.session.quick_mask.editing {
|
||||
ui.painter_at(rect).text(
|
||||
rect.left_top() + vec2(12.0, 40.0),
|
||||
@@ -754,6 +820,62 @@ fn clone_marker(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tools that paint with the brush (and show its cursor).
|
||||
fn brush_tool(t: Tool) -> bool {
|
||||
matches!(t, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path)
|
||||
}
|
||||
|
||||
/// Ctrl (Cmd on macOS) + drag in a view changes the brush instead of painting or navigating: a
|
||||
/// right drag its size (left/right) and hardness (up/down), a left drag its flow and angle. True
|
||||
/// while Ctrl is held with a brush tool and no stroke is under way.
|
||||
fn brush_drag(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response) -> bool {
|
||||
let held =
|
||||
app.ui.mode == crate::state::Mode::Painting && brush_tool(app.session.tool.tool) && !app.session.stroke_active() && ui.input(|i| i.modifiers.command);
|
||||
if held && let Some(right) = brush_drag_button(resp) {
|
||||
adjust_brush(&mut app.session.tool.brush, right, ui.input(|i| i.pointer.delta()));
|
||||
}
|
||||
held
|
||||
}
|
||||
|
||||
/// The button of a drag on `resp`: Some(true) right, Some(false) left.
|
||||
fn brush_drag_button(resp: &egui::Response) -> Option<bool> {
|
||||
let right = resp.dragged_by(PointerButton::Secondary);
|
||||
(right || resp.dragged_by(PointerButton::Primary)).then_some(right)
|
||||
}
|
||||
|
||||
/// While a Ctrl+drag changes the brush, its values beside where the drag began (drawn over the
|
||||
/// view; the tool bar and Properties show them too).
|
||||
fn brush_readout(app: &TextureCraftApp, ui: &Ui, resp: &egui::Response, adjusting: bool) {
|
||||
let Some(right) = brush_drag_button(resp).filter(|_| adjusting) else { return };
|
||||
let Some(at) = ui.input(|i| i.pointer.press_origin()) else { return };
|
||||
// The pointer would cover the values; the brush cursor stays where the drag began.
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::None);
|
||||
let b = &app.session.tool.brush;
|
||||
let text = if right {
|
||||
format!("{} {:.1} {} {:.0}", tr("Size"), b.size / 0.25 * 100.0, tr("Hardness"), b.hardness * 100.0)
|
||||
} else {
|
||||
format!("{} {:.0} {} {:.0}°", tr("Flow"), b.flow * 100.0, tr("Angle"), b.angle)
|
||||
};
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let p = ui.painter_at(resp.rect);
|
||||
let g = p.layout_no_wrap(text, egui::FontId::proportional(12.0), tk.text_strong);
|
||||
let r = Rect::from_min_size(at + vec2(18.0, -30.0), g.size()).expand2(vec2(6.0, 3.0));
|
||||
p.rect_filled(r, 3.0, tk.panel);
|
||||
p.galley(r.min + vec2(6.0, 3.0), g, tk.text_strong);
|
||||
}
|
||||
|
||||
/// Brush change for a Ctrl+drag by `d` points: `right` sets the size (x) and hardness (y), else
|
||||
/// the flow (x) and angle (y); dragging up raises hardness and angle.
|
||||
fn adjust_brush(b: &mut texturecraft_engine::paint::BrushSettings, right: bool, d: egui::Vec2) {
|
||||
if right {
|
||||
b.size = (b.size * (1.0 + d.x * 0.005)).clamp(0.0005, 0.25);
|
||||
b.hardness = (b.hardness - d.y * 0.005).clamp(0.0, 0.999);
|
||||
} else {
|
||||
b.flow = (b.flow + d.x * 0.005).clamp(0.0, 1.0);
|
||||
b.angle = (b.angle - d.y * 0.5 + 180.0).rem_euclid(360.0) - 180.0;
|
||||
}
|
||||
}
|
||||
|
||||
fn brush_cursor(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3, nrm: Vec3) {
|
||||
let (lo, hi) = app.session.mesh.bounds();
|
||||
let r = app.session.tool.brush.size * (hi - lo).length();
|
||||
@@ -791,6 +913,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
let resp = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag());
|
||||
let size = rect.size();
|
||||
let alt = ui.input(|i| i.modifiers.alt);
|
||||
let adjusting = brush_drag(app, ui, &resp);
|
||||
let delta = ui.input(|i| i.pointer.delta());
|
||||
if resp.dragged_by(PointerButton::Middle) || (alt && resp.dragged_by(PointerButton::Primary)) {
|
||||
app.ui.uv_pan[0] += delta.x / size.x * 2.0;
|
||||
@@ -836,7 +959,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
let uv = to_uv(p);
|
||||
app.run("tool.cloneSource", json!({"uv": [uv.x, uv.y]}));
|
||||
}
|
||||
let painting = app.ui.mode == crate::state::Mode::Painting && !alt && !v_held;
|
||||
let painting = app.ui.mode == crate::state::Mode::Painting && !alt && !adjusting && !v_held;
|
||||
if painting && path_tool {
|
||||
path_input(app, ui, &resp, true, |_, p| Some(to_uv(p).extend(0.0)), show);
|
||||
} else if painting {
|
||||
@@ -898,6 +1021,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
if app.ui.mode == crate::state::Mode::Painting && path_tool {
|
||||
path_overlay(app, ui, rect, &resp, true, show);
|
||||
}
|
||||
brush_readout(app, ui, &resp, adjusting);
|
||||
view_header(app, ui, rect, "v2d");
|
||||
axis_gizmo(ui, rect, app, true);
|
||||
let name = app.session.doc.project.texture_sets.get(ts).map(|t| t.name.clone()).unwrap_or_default();
|
||||
|
||||
@@ -53,7 +53,7 @@ pub fn poll(app: &mut TextureCraftApp) {
|
||||
for (name, bytes, pick) in picked {
|
||||
let done = match pick {
|
||||
Pick::Open => {
|
||||
load(app, &name, &bytes);
|
||||
load(app, &name, bytes);
|
||||
continue;
|
||||
}
|
||||
Pick::Environment => app.session.import_resource_bytes(&name, bytes).map(|res| use_environment(app, &res)),
|
||||
@@ -106,12 +106,12 @@ fn use_environment(app: &mut TextureCraftApp, name: &str) {
|
||||
}
|
||||
|
||||
/// Import an image as a project resource, or replace the session with a `.tcraft` project or a
|
||||
/// mesh file's bytes (errors become toasts).
|
||||
pub fn load(app: &mut TextureCraftApp, name: &str, bytes: &[u8]) {
|
||||
/// mesh file's bytes, after asking to save unsaved changes (errors become toasts).
|
||||
pub fn load(app: &mut TextureCraftApp, name: &str, bytes: Vec<u8>) {
|
||||
let path = std::path::Path::new(name);
|
||||
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
|
||||
if IMAGE_EXTS.contains(&ext.as_str()) {
|
||||
match app.session.import_resource_bytes(name, bytes.to_vec()) {
|
||||
match app.session.import_resource_bytes(name, bytes) {
|
||||
Ok(res) => {
|
||||
app.ui.dock.focus(crate::docking::Panel::Assets);
|
||||
app.toast(trf("Imported {name}", &[("name", &res)]), false);
|
||||
@@ -120,8 +120,12 @@ pub fn load(app: &mut TextureCraftApp, name: &str, bytes: &[u8]) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
let bytes = std::sync::Arc::new(bytes);
|
||||
if crate::windows::ask_to_save(app, crate::state::Unsaved::Load(name.into(), bytes.clone())) {
|
||||
return;
|
||||
}
|
||||
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("Untitled");
|
||||
let next = if ext == PROJECT_EXT { Session::from_project_bytes(bytes) } else { Session::from_mesh_bytes(name, bytes, MESH_RESOLUTION, stem) };
|
||||
let next = if ext == PROJECT_EXT { Session::from_project_bytes(&bytes) } else { Session::from_mesh_bytes(name, &bytes, MESH_RESOLUTION, stem) };
|
||||
match next {
|
||||
Ok(next) => {
|
||||
app.session.switch_to(next);
|
||||
@@ -183,7 +187,9 @@ fn zip_files(files: &[ExportedFile]) -> Result<Vec<u8>, String> {
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub use web::{download, export_mesh, export_textures, import_bake_mesh, import_environment, import_images, import_preset, open, save_project};
|
||||
pub use web::{
|
||||
download, export_mesh, export_textures, import_bake_mesh, import_environment, import_images, import_preset, open, save_project, sync_unsaved, unsaved,
|
||||
};
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod web {
|
||||
@@ -191,6 +197,19 @@ mod web {
|
||||
use serde_json::Value;
|
||||
use wasm_bindgen::JsCast as _;
|
||||
|
||||
/// Whether the project has unsaved changes, for the page's `beforeunload` listener.
|
||||
static UNSAVED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
/// Refresh [`unsaved`] (once per frame).
|
||||
pub fn sync_unsaved(app: &TextureCraftApp) {
|
||||
UNSAVED.store(app.session.modified, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Whether closing or reloading the page would lose unsaved changes.
|
||||
pub fn unsaved() -> bool {
|
||||
UNSAVED.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// File › Open: the browser's file picker; the file loads on a later frame (see [`poll`]).
|
||||
pub fn open(ctx: &egui::Context) {
|
||||
pick(ctx, tr("Projects and meshes"), OPEN_EXTS, false, Pick::Open);
|
||||
|
||||
@@ -14,11 +14,23 @@ pub fn dnd_release<T: std::any::Any + Send + Sync>(resp: &Response) -> Option<st
|
||||
}
|
||||
|
||||
/// A labelled slider in two rows: "Label ........ value" over a slim track with a round knob.
|
||||
/// Returns the response of the track (`.changed()` when dragged, `.drag_stopped()` at the end).
|
||||
/// Returns the response of the track (`.changed()` while dragged); for a value that is applied
|
||||
/// once the edit is done, use [`slider_edit`].
|
||||
pub fn slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive<f32>, decimals: usize) -> Response {
|
||||
slider_inner(ui, label, value, range, decimals).0
|
||||
}
|
||||
|
||||
/// [`slider`] for a value re-read from the document every frame: true on the frame an edit is
|
||||
/// done (a drag released, a click on the track, a typed value), with `value` holding the result.
|
||||
pub fn slider_edit(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive<f32>, decimals: usize) -> bool {
|
||||
slider_inner(ui, label, value, range, decimals).1
|
||||
}
|
||||
|
||||
fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive<f32>, decimals: usize) -> (Response, bool) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let (lo, hi) = (*range.start(), *range.end());
|
||||
let w = ui.available_width();
|
||||
let mut done = false;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(label).color(tk.text));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
@@ -29,6 +41,7 @@ pub fn slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeI
|
||||
&& v.is_finite()
|
||||
{
|
||||
*value = v.clamp(lo, hi);
|
||||
done = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -38,14 +51,22 @@ pub fn slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeI
|
||||
{
|
||||
let t = ((p.x - rect.left() - 5.0) / (rect.width() - 10.0).max(1.0)).clamp(0.0, 1.0);
|
||||
let v = lo + (hi - lo) * t;
|
||||
// Remembered for the release frame, where the pointer no longer drags.
|
||||
ui.data_mut(|d| d.insert_temp(resp.id, v));
|
||||
if (v - *value).abs() > f32::EPSILON {
|
||||
*value = v;
|
||||
resp.mark_changed();
|
||||
}
|
||||
}
|
||||
if resp.drag_stopped() || resp.clicked() {
|
||||
if let Some(v) = ui.data_mut(|d| d.remove_temp::<f32>(resp.id)) {
|
||||
*value = v;
|
||||
}
|
||||
done = true;
|
||||
}
|
||||
let t = if hi > lo { ((*value - lo) / (hi - lo)).clamp(0.0, 1.0) } else { 0.0 };
|
||||
track(ui, &resp, rect.left() + 5.0..=rect.right() - 5.0, rect.center().y, t, 2.0, 4.5);
|
||||
resp
|
||||
(resp, done)
|
||||
}
|
||||
|
||||
/// A small inline slider for the top tool bar: "Label value" above a short track.
|
||||
@@ -84,6 +105,31 @@ fn track(ui: &Ui, resp: &Response, x: std::ops::RangeInclusive<f32>, y: f32, t:
|
||||
p.circle(egui::pos2(xk, y), knob, tk.panel, Stroke::new(1.5, ring));
|
||||
}
|
||||
|
||||
/// A histogram of `counts` (buckets over 0..1, scaled to the fullest) in a field-colored well
|
||||
/// the width of the panel, the part of 0..1 outside `range` dimmed.
|
||||
pub fn histogram(ui: &mut Ui, counts: &[u32], range: (f32, f32)) -> Response {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 56.0), Sense::hover());
|
||||
let p = ui.painter_at(rect);
|
||||
p.rect(rect, CornerRadius::same(tk.radius), tk.field, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside);
|
||||
let inner = rect.shrink(3.0);
|
||||
let max = counts.iter().copied().max().unwrap_or(0).max(1) as f32;
|
||||
let w = inner.width() / counts.len().max(1) as f32;
|
||||
for (i, c) in counts.iter().enumerate() {
|
||||
let h = inner.height() * *c as f32 / max;
|
||||
let x = inner.left() + i as f32 * w;
|
||||
p.rect_filled(egui::Rect::from_min_max(egui::pos2(x, inner.bottom() - h), egui::pos2(x + w, inner.bottom())), 0.0, tk.text_dim);
|
||||
}
|
||||
let x = |t: f32| inner.left() + inner.width() * t.clamp(0.0, 1.0);
|
||||
let shade = tk.field.gamma_multiply(0.7);
|
||||
p.rect_filled(egui::Rect::from_x_y_ranges(inner.left()..=x(range.0), inner.y_range()), 0.0, shade);
|
||||
p.rect_filled(egui::Rect::from_x_y_ranges(x(range.1)..=inner.right(), inner.y_range()), 0.0, shade);
|
||||
for t in [range.0, range.1] {
|
||||
p.line_segment([egui::pos2(x(t), inner.top()), egui::pos2(x(t), inner.bottom())], Stroke::new(1.0, tk.accent));
|
||||
}
|
||||
resp
|
||||
}
|
||||
|
||||
/// One line of `text` cut with "…" to fit `max_width`, for list rows that shrink with their panel.
|
||||
pub fn elided(painter: &egui::Painter, text: impl Into<String>, size: f32, color: Color32, max_width: f32) -> std::sync::Arc<egui::Galley> {
|
||||
let mut job = egui::text::LayoutJob::simple_singleline(text.into(), egui::FontId::proportional(size), color);
|
||||
@@ -187,7 +233,8 @@ pub fn color_swatch(ui: &mut Ui, id: &str, linear: &mut [f32; 3], width: f32) ->
|
||||
let mut changed = false;
|
||||
// Open state lives in memory (`toggle_id` above); `from_response` alone shows it always.
|
||||
egui::Popup::from_response(&resp).id(popup).open_memory(None).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
|
||||
if egui::color_picker::color_picker_color32(ui, &mut c, egui::color_picker::Alpha::Opaque) {
|
||||
// Wider than the R, G, B row at any value, so the popup keeps one size and place.
|
||||
if color_picker(ui, popup.with("picker"), &mut c, 275.0) {
|
||||
let lin = [c.r(), c.g(), c.b()].map(|v| texturecraft_engine::texel::srgb_to_linear(v as f32 / 255.0));
|
||||
*linear = lin;
|
||||
changed = true;
|
||||
@@ -196,6 +243,80 @@ pub fn color_swatch(ui: &mut Ui, id: &str, linear: &mut [f32; 3], width: f32) ->
|
||||
changed
|
||||
}
|
||||
|
||||
/// A color picker `width` wide: R, G, B (sRGB 0–255) with a copy button, a saturation/value
|
||||
/// square and a hue strip. Returns true when the color changed.
|
||||
fn color_picker(ui: &mut Ui, id: egui::Id, c: &mut Color32, width: f32) -> bool {
|
||||
use egui::ecolor::{hsv_from_rgb, rgb_from_hsv};
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let mut srgb = [c.r(), c.g(), c.b()];
|
||||
let hsv_of = |srgb: [u8; 3]| hsv_from_rgb(srgb.map(|v| v as f32 / 255.0));
|
||||
// Remembered with the color it was for, so hue and saturation survive black, white and grays.
|
||||
let (mut h, mut s, mut v) = ui.data(|d| d.get_temp::<(Color32, (f32, f32, f32))>(id)).filter(|(k, _)| k == c).map_or_else(|| hsv_of(srgb), |(_, hsv)| hsv);
|
||||
let mut typed = false;
|
||||
let mut dragged = false;
|
||||
ui.horizontal(|ui| {
|
||||
for (x, prefix) in srgb.iter_mut().zip(["R ", "G ", "B "]) {
|
||||
typed |= ui.add(egui::DragValue::new(x).speed(0.5).prefix(prefix)).changed();
|
||||
}
|
||||
if icon_button(ui, egui_phosphor::regular::COPY, crate::i18n::tr("Copy RGB values"), false, 20.0).clicked() {
|
||||
ui.copy_text(format!("{}, {}, {}", srgb[0], srgb[1], srgb[2]));
|
||||
}
|
||||
});
|
||||
if typed {
|
||||
(h, s, v) = hsv_of(srgb);
|
||||
}
|
||||
let border = Stroke::new(1.0, tk.field_border);
|
||||
// Saturation across, value up.
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(width, width), Sense::click_and_drag());
|
||||
if let Some(p) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.clicked()) {
|
||||
(s, v) = (((p.x - rect.left()) / rect.width()).clamp(0.0, 1.0), 1.0 - ((p.y - rect.top()) / rect.height()).clamp(0.0, 1.0));
|
||||
dragged = true;
|
||||
}
|
||||
gradient(ui.painter(), rect, |x, y| rgb_from_hsv((h, x, 1.0 - y)));
|
||||
ui.painter().rect_stroke(rect, 0.0, border, egui::StrokeKind::Inside);
|
||||
let at = rect.lerp_inside(vec2(s, 1.0 - v));
|
||||
ui.painter().circle_stroke(at, 5.0, Stroke::new(2.0, Color32::WHITE));
|
||||
ui.painter().circle_stroke(at, 6.5, Stroke::new(1.0, Color32::BLACK));
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(width, 16.0), Sense::click_and_drag());
|
||||
if let Some(p) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.clicked()) {
|
||||
h = ((p.x - rect.left()) / rect.width()).clamp(0.0, 1.0);
|
||||
dragged = true;
|
||||
}
|
||||
gradient(ui.painter(), rect, |x, _| rgb_from_hsv((x, 1.0, 1.0)));
|
||||
ui.painter().rect_stroke(rect, 0.0, border, egui::StrokeKind::Inside);
|
||||
let x = rect.left() + rect.width() * h;
|
||||
ui.painter().rect_stroke(egui::Rect::from_x_y_ranges(x - 2.0..=x + 2.0, rect.y_range()), 1.0, Stroke::new(1.5, Color32::WHITE), egui::StrokeKind::Middle);
|
||||
if dragged {
|
||||
srgb = rgb_from_hsv((h, s, v)).map(|x| (x * 255.0 + 0.5) as u8);
|
||||
}
|
||||
let next = Color32::from_rgb(srgb[0], srgb[1], srgb[2]);
|
||||
ui.data_mut(|d| d.insert_temp(id, (next, (h, s, v))));
|
||||
let changed = next != *c;
|
||||
*c = next;
|
||||
changed
|
||||
}
|
||||
|
||||
/// Fill `rect` with `rgb(x, y)` (sRGB 0..1 over 0..1 across and down), as a shaded mesh.
|
||||
fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> [f32; 3]) {
|
||||
const N: u32 = 24;
|
||||
let mut mesh = egui::Mesh::default();
|
||||
for j in 0..=N {
|
||||
for i in 0..=N {
|
||||
let (x, y) = (i as f32 / N as f32, j as f32 / N as f32);
|
||||
let [r, g, b] = rgb(x, y).map(|c| (c.clamp(0.0, 1.0) * 255.0 + 0.5) as u8);
|
||||
mesh.colored_vertex(rect.lerp_inside(vec2(x, y)), Color32::from_rgb(r, g, b));
|
||||
}
|
||||
}
|
||||
for j in 0..N {
|
||||
for i in 0..N {
|
||||
let k = j * (N + 1) + i;
|
||||
mesh.add_triangle(k, k + 1, k + N + 1);
|
||||
mesh.add_triangle(k + 1, k + N + 2, k + N + 1);
|
||||
}
|
||||
}
|
||||
painter.add(mesh);
|
||||
}
|
||||
|
||||
/// Panel title row with optional trailing content.
|
||||
pub fn panel_header(ui: &mut Ui, title: &str, trailing: impl FnOnce(&mut Ui)) {
|
||||
ui.horizontal(|ui| {
|
||||
|
||||
@@ -15,9 +15,10 @@ use crate::i18n::LANGUAGES;
|
||||
use crate::i18n::{tr, trf};
|
||||
use crate::state::Mode;
|
||||
use crate::theme::{Accent, Brightness, Tokens, caption};
|
||||
use crate::widgets::{color_swatch, combo, icon_button, primary_button, slider};
|
||||
use crate::widgets::{color_swatch, combo, icon_button, primary_button, slider, slider_edit};
|
||||
|
||||
pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
start(app, ctx);
|
||||
new_project(app, ctx);
|
||||
about(app, ctx);
|
||||
settings(app, ctx);
|
||||
@@ -28,6 +29,70 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
if app.ui.mode == Mode::Baking {
|
||||
bake_bar(app, ctx);
|
||||
}
|
||||
unsaved(app, ctx);
|
||||
}
|
||||
|
||||
/// Hold `then` (quitting, opening or closing a project) behind the unsaved-changes dialog when
|
||||
/// the project has unsaved changes; false when it can go ahead now.
|
||||
pub(crate) fn ask_to_save(app: &mut TextureCraftApp, then: crate::state::Unsaved) -> bool {
|
||||
if app.session.modified {
|
||||
app.ui.windows.unsaved = Some(then);
|
||||
}
|
||||
app.session.modified
|
||||
}
|
||||
|
||||
/// Quitting, opening or closing a project with unsaved changes asks whether to save them first
|
||||
/// (in the browser, Save downloads the project).
|
||||
fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
use crate::state::Unsaved;
|
||||
if ctx.input(|i| i.viewport().close_requested()) && ask_to_save(app, Unsaved::Quit) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
}
|
||||
let Some(then) = app.ui.windows.unsaved.clone() else { return };
|
||||
let mut open = true;
|
||||
let mut save = None;
|
||||
let mut cancel = false;
|
||||
let name: [(&str, &dyn std::fmt::Display); 1] = [("name", &app.session.doc.project.name)];
|
||||
let question =
|
||||
if then == Unsaved::Quit { trf("Save the changes to {name} before closing?", &name) } else { trf("Save the changes to {name} first?", &name) };
|
||||
dialog("unsaved", tr("Unsaved changes"), &mut open).show(ctx, |ui| {
|
||||
ui.label(question);
|
||||
ui.add_space(8.0);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.add(primary_button(ui, tr("Save"))).clicked() {
|
||||
save = Some(true);
|
||||
}
|
||||
if ui.button(tr("Don't save")).clicked() {
|
||||
save = Some(false);
|
||||
}
|
||||
if ui.button(tr("Cancel")).clicked() {
|
||||
cancel = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
if !open || cancel {
|
||||
app.ui.windows.unsaved = None;
|
||||
}
|
||||
match save {
|
||||
Some(true) => {
|
||||
file_action(app, ctx, "file.save");
|
||||
}
|
||||
// Going ahead anyway: the changes are let go.
|
||||
Some(false) => app.session.modified = false,
|
||||
None => return,
|
||||
}
|
||||
// A cancelled or failed save keeps the project and this dialog open.
|
||||
if app.session.modified {
|
||||
return;
|
||||
}
|
||||
app.ui.windows.unsaved = None;
|
||||
match then {
|
||||
Unsaved::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
|
||||
Unsaved::Command(id) => crate::menus::invoke(app, ctx, &id),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Unsaved::Open(path) => open_path(app, &path),
|
||||
Unsaved::Load(name, bytes) => crate::web_files::load(app, &name, std::sync::Arc::unwrap_or_clone(bytes)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A titled tool window; `id` keeps its place across UI languages.
|
||||
@@ -203,7 +268,7 @@ pub(crate) fn shader(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let ts = app.session.ts();
|
||||
if let Some(set) = app.session.doc.project.texture_sets.get(ts) {
|
||||
let mut hs = set.height_strength;
|
||||
if slider(ui, tr("Height to normal strength"), &mut hs, 0.0..=10.0, 2).drag_stopped() {
|
||||
if slider_edit(ui, tr("Height to normal strength"), &mut hs, 0.0..=10.0, 2) {
|
||||
app.run("textureSet.settings", json!({"ts": ts, "heightStrength": hs}));
|
||||
}
|
||||
}
|
||||
@@ -216,16 +281,27 @@ pub(crate) fn shader(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
/// The History panel body (a dock tab).
|
||||
pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let labels = app.session.history_labels();
|
||||
let (done, undone) = (app.session.history_labels(), app.session.redo_labels());
|
||||
// A click on a step goes back (or forward) to it: steps to undo, or to redo when negative.
|
||||
let mut jump = 0i64;
|
||||
egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {
|
||||
ui.label(RichText::new(tr("Project opened")).color(tk.text_dim));
|
||||
for l in &labels {
|
||||
ui.label(l);
|
||||
}
|
||||
if let Some(r) = app.session.redo_label() {
|
||||
ui.label(RichText::new(trf("{action} (undone)", &[("action", &r)])).color(tk.text_dim));
|
||||
let n = done.len() as i64;
|
||||
let rows = std::iter::once(RichText::new(tr("Project opened")).color(tk.text_dim))
|
||||
.chain(done.iter().map(RichText::new))
|
||||
.chain(undone.iter().map(|l| RichText::new(trf("{action} (undone)", &[("action", l)])).color(tk.text_dim)));
|
||||
for (i, text) in rows.enumerate() {
|
||||
// Row i is the state after i steps.
|
||||
let steps = n - i as i64;
|
||||
if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() {
|
||||
jump = steps;
|
||||
}
|
||||
}
|
||||
});
|
||||
if jump > 0 {
|
||||
app.run("edit.undo", json!({ "steps": jump }));
|
||||
} else if jump < 0 {
|
||||
app.run("edit.redo", json!({ "steps": -jump }));
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
if ui.add_enabled(app.session.can_undo(), egui::Button::new(format!("{} {}", ic::ARROW_COUNTER_CLOCKWISE, tr("Undo")))).clicked() {
|
||||
app.run("edit.undo", json!({}));
|
||||
@@ -236,6 +312,72 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
});
|
||||
}
|
||||
|
||||
/// What the start window was asked for.
|
||||
enum Start {
|
||||
Menu(&'static str),
|
||||
Recent(String),
|
||||
Close,
|
||||
}
|
||||
|
||||
/// The start window: a new project, a project file or a recent one, or the sample that is open.
|
||||
fn start(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
if !app.ui.windows.start {
|
||||
return;
|
||||
}
|
||||
let tk = Tokens::get(ctx);
|
||||
let mut open = true;
|
||||
let mut action = None;
|
||||
dialog("start", "TextureCraft", &mut open).min_width(380.0).show(ctx, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
if ui.add(primary_button(ui, tr("New project..."))).clicked() {
|
||||
action = Some(Start::Menu("ui.newProject"));
|
||||
}
|
||||
if ui.button(tr("Open...")).clicked() {
|
||||
action = Some(Start::Menu("file.open"));
|
||||
}
|
||||
});
|
||||
if file_dialogs_available() {
|
||||
ui.add_space(8.0);
|
||||
ui.label(caption(tr("Recent projects")));
|
||||
if app.ui.recent.is_empty() {
|
||||
ui.label(RichText::new(tr("No recent projects yet")).color(tk.text_dim));
|
||||
}
|
||||
for path in &app.ui.recent {
|
||||
let name = std::path::Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or(path);
|
||||
if ui
|
||||
.add(egui::Button::selectable(false, format!("{} {name}", ic::FILE)).min_size(vec2(ui.available_width(), 0.0)))
|
||||
.on_hover_text(path)
|
||||
.clicked()
|
||||
{
|
||||
action = Some(Start::Recent(path.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
ui.checkbox(&mut app.ui.prefs.start_window, tr("Show at startup"));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button(tr("Continue with the sample project")).clicked() {
|
||||
action = Some(Start::Close);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
if let Some(a) = action {
|
||||
app.ui.windows.start = false;
|
||||
match a {
|
||||
Start::Menu(id) => crate::menus::invoke(app, ctx, id),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Start::Recent(path) => open_path(app, &path),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !open {
|
||||
app.ui.windows.start = false;
|
||||
}
|
||||
}
|
||||
|
||||
fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
if !app.ui.windows.new_project {
|
||||
return;
|
||||
@@ -408,6 +550,9 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
.on_hover_text(tr("Use the operating system's window frame and buttons instead of TextureCraft's own title bar"));
|
||||
ui.end_row();
|
||||
}
|
||||
ui.label(tr("Start window"));
|
||||
ui.checkbox(&mut p.start_window, tr("Show at startup"));
|
||||
ui.end_row();
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
ui.label(caption(tr("Viewport")));
|
||||
@@ -929,6 +1074,10 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) ->
|
||||
/// Open a project or mesh by path (menus, Recent projects, drag and drop).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn open_path(app: &mut TextureCraftApp, path: &str) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if ask_to_save(app, crate::state::Unsaved::Open(path.into())) {
|
||||
return;
|
||||
}
|
||||
if app.run("file.open", json!({"path": path})).is_some() {
|
||||
remember(app, path);
|
||||
app.ui.mode = Mode::Painting;
|
||||
@@ -993,6 +1142,9 @@ pub(crate) fn export_params(app: &TextureCraftApp) -> serde_json::Value {
|
||||
if !e.normal_format.is_empty() {
|
||||
p["normalFormat"] = json!(e.normal_format);
|
||||
}
|
||||
if !e.color_space.is_empty() {
|
||||
p["colorSpace"] = json!(e.color_space);
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
@@ -1092,6 +1244,15 @@ fn export_settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, presets: &[textur
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("Color space"));
|
||||
let shown = if app.ui.export.color_space.is_empty() { tr("Default") } else { app.ui.export.color_space.as_str() };
|
||||
egui::ComboBox::from_id_salt("exp_cs").selected_text(shown).show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut app.ui.export.color_space, String::new(), tr("Default"));
|
||||
for name in ["sRGB", "Linear Rec.709", "ACEScg", "ACES2065-1"] {
|
||||
ui.selectable_value(&mut app.ui.export.color_space, name.to_string(), name);
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
//! Ctrl+drag in the 3D view changes the brush instead of painting or orbiting.
|
||||
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
|
||||
/// Drag with `button` from `from` by `by` in a few moves.
|
||||
fn drag(h: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: Pos2, by: egui::Vec2, modifiers: Modifiers) {
|
||||
h.event(Event::ModifiersChanged(modifiers));
|
||||
h.hover_at(from);
|
||||
h.event(Event::PointerButton { pos: from, button, pressed: true, modifiers });
|
||||
h.run_steps(2);
|
||||
for k in 1..=4 {
|
||||
h.hover_at(from + by * (k as f32 / 4.0));
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.event(Event::PointerButton { pos: from + by, button, pressed: false, modifiers });
|
||||
h.event(Event::ModifiersChanged(Modifiers::NONE));
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_drag_changes_the_brush_instead_of_painting_or_orbiting() {
|
||||
let session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.run_steps(4);
|
||||
let c = h.state().viewport_rect.center();
|
||||
let (brush, yaw, history) = {
|
||||
let s = &h.state().session;
|
||||
(s.tool.brush.clone(), s.camera.yaw, s.history_labels().len())
|
||||
};
|
||||
// Right drag to the right and up: a bigger, harder brush; the camera stays.
|
||||
drag(&mut h, PointerButton::Secondary, c, vec2(80.0, -40.0), Modifiers::COMMAND);
|
||||
let b = h.state().session.tool.brush.clone();
|
||||
assert!(b.size > brush.size && b.hardness > brush.hardness, "{} {} → {} {}", brush.size, brush.hardness, b.size, b.hardness);
|
||||
assert_eq!(h.state().session.camera.yaw, yaw, "no orbit");
|
||||
// Left drag to the left and up: less flow, a turned brush, and no stroke.
|
||||
drag(&mut h, PointerButton::Primary, c, vec2(-80.0, -40.0), Modifiers::COMMAND);
|
||||
let b2 = h.state().session.tool.brush.clone();
|
||||
assert!(b2.flow < b.flow && b2.angle != b.angle, "{} {} → {} {}", b.flow, b.angle, b2.flow, b2.angle);
|
||||
assert_eq!(h.state().session.history_labels().len(), history, "nothing painted");
|
||||
// Without Ctrl, a right drag orbits again and the brush keeps its values.
|
||||
drag(&mut h, PointerButton::Secondary, c, vec2(80.0, -40.0), Modifiers::NONE);
|
||||
assert_ne!(h.state().session.camera.yaw, yaw);
|
||||
assert_eq!(h.state().session.tool.brush, b2);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Closing the app, or opening or closing a project, with unsaved changes asks whether to save
|
||||
//! them first.
|
||||
|
||||
use egui::{ViewportCommand, ViewportEvent, ViewportId};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
use texturecraft_ui_egui::state::Unsaved;
|
||||
|
||||
fn harness(modified: bool) -> Harness<'static, TextureCraftApp> {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
session.modified = modified;
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
/// The window's close button, for one frame.
|
||||
fn request_close(h: &mut Harness<'_, TextureCraftApp>) {
|
||||
h.input_mut().viewports.entry(ViewportId::ROOT).or_default().events.push(ViewportEvent::Close);
|
||||
h.step();
|
||||
h.input_mut().viewports.entry(ViewportId::ROOT).or_default().events.clear();
|
||||
}
|
||||
|
||||
/// The viewport commands of the last frame.
|
||||
fn sent(h: &Harness<'_, TextureCraftApp>, cmd: &ViewportCommand) -> bool {
|
||||
h.output().viewport_output.get(&ViewportId::ROOT).is_some_and(|v| v.commands.contains(cmd))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_with_changes_asks_and_dont_save_closes() {
|
||||
let mut h = harness(true);
|
||||
request_close(&mut h);
|
||||
assert!(sent(&h, &ViewportCommand::CancelClose), "the close waits for an answer");
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the dialog is open");
|
||||
h.get_by_label("Don't save").click();
|
||||
h.step();
|
||||
assert!(sent(&h, &ViewportCommand::Close), "Don't save closes the app");
|
||||
assert!(h.state().ui.windows.unsaved.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_keeps_the_app_open() {
|
||||
let mut h = harness(true);
|
||||
request_close(&mut h);
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Cancel").click();
|
||||
h.step();
|
||||
assert!(!sent(&h, &ViewportCommand::Close));
|
||||
assert!(h.state().ui.windows.unsaved.is_none(), "Cancel closes the dialog");
|
||||
assert!(h.state().session.modified, "and keeps the changes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_without_changes_does_not_ask() {
|
||||
let mut h = harness(false);
|
||||
request_close(&mut h);
|
||||
assert!(!sent(&h, &ViewportCommand::CancelClose));
|
||||
assert!(h.state().ui.windows.unsaved.is_none());
|
||||
}
|
||||
|
||||
/// A project picked or dropped in the browser arrives as bytes; it waits on the same dialog.
|
||||
#[test]
|
||||
fn a_dropped_project_waits_on_the_dialog() {
|
||||
let mut h = harness(true);
|
||||
let dropped = texturecraft_engine::Session::new_project("Dropped", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
|
||||
texturecraft_ui_egui::web_files::load(h.state_mut(), "dropped.tcraft", dropped.to_project_bytes().unwrap());
|
||||
h.run_steps(4);
|
||||
assert!(matches!(h.state().ui.windows.unsaved, Some(Unsaved::Load(ref name, _)) if name == "dropped.tcraft"), "the dialog is open");
|
||||
assert_ne!(h.state().session.doc.project.name, "Dropped", "the project stays until answered");
|
||||
h.get_by_label("Don't save").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().session.doc.project.name, "Dropped", "Don't save opens it");
|
||||
assert!(h.state().ui.windows.unsaved.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_the_project_with_changes_asks_first() {
|
||||
let mut h = harness(true);
|
||||
h.state_mut().session.doc.project.name = "Edited".into();
|
||||
let name = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.name.clone();
|
||||
let ctx = h.ctx.clone();
|
||||
texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "file.close");
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Command("file.close".into())), "the dialog is open");
|
||||
assert_eq!(name(&h), "Edited", "the project stays until answered");
|
||||
h.get_by_label("Don't save").click();
|
||||
h.run_steps(2);
|
||||
assert_ne!(name(&h), "Edited", "Don't save closes the project");
|
||||
assert!(h.state().ui.windows.unsaved.is_none() && !h.state().session.modified);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! The color picker popup keeps its place while the color changes, picks from its square and hue
|
||||
//! strip, and copies its values.
|
||||
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use texturecraft_ui_egui::{theme, widgets};
|
||||
|
||||
/// A swatch at the right edge of the window, like the Properties panel's, with its picker open.
|
||||
fn open_picker(color: [f32; 3]) -> Harness<'static, [f32; 3]> {
|
||||
let mut h = Harness::builder().with_size(egui::vec2(800.0, 600.0)).build_ui_state(
|
||||
|ui, color: &mut [f32; 3]| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
|
||||
widgets::color_swatch(ui, "color", color, 120.0);
|
||||
});
|
||||
},
|
||||
color,
|
||||
);
|
||||
h.ctx.set_fonts(theme::font_definitions());
|
||||
theme::apply(&h.ctx, theme::Brightness::default(), theme::Accent::default());
|
||||
h.run_steps(2);
|
||||
let swatch = egui::pos2(800.0 - 60.0, 9.0);
|
||||
h.drag_at(swatch);
|
||||
h.drop_at(swatch);
|
||||
h.run_steps(3);
|
||||
h
|
||||
}
|
||||
|
||||
/// The picker's R value.
|
||||
fn r_value(h: &Harness<'_, [f32; 3]>) -> egui::Rect {
|
||||
h.get_all_by_role(Role::SpinButton).next().unwrap().rect()
|
||||
}
|
||||
|
||||
/// Click at `p` and let the picker apply it.
|
||||
fn click(h: &mut Harness<'_, [f32; 3]>, p: egui::Pos2) {
|
||||
h.drag_at(p);
|
||||
h.drop_at(p);
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_popup_stays_put_while_the_color_changes() {
|
||||
let mut h = open_picker([1.0; 3]);
|
||||
let bright = r_value(&h).left();
|
||||
*h.state_mut() = [0.001; 3];
|
||||
h.run_steps(3);
|
||||
assert_eq!(r_value(&h).left(), bright, "the picker does not move when R, G and B lose digits");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_square_and_the_hue_strip_pick_the_color() {
|
||||
let mut h = open_picker([1.0; 3]);
|
||||
// The square starts a row below the values; its bottom-left corner is black.
|
||||
let r = r_value(&h);
|
||||
let square = egui::Rect::from_min_size(egui::pos2(r.left() + 1.0, r.bottom() + 8.0), egui::vec2(273.0, 273.0));
|
||||
click(&mut h, square.left_bottom() + egui::vec2(2.0, -6.0));
|
||||
assert!(h.state().iter().all(|c| *c < 0.01), "black: {:?}", h.state());
|
||||
// Full saturation and value, then a hue a third of the way along: green.
|
||||
click(&mut h, square.right_top() + egui::vec2(-1.0, 1.0));
|
||||
let strip = square.bottom() + 14.0;
|
||||
click(&mut h, egui::pos2(square.left() + 275.0 / 3.0, strip));
|
||||
let [r, g, b] = *h.state();
|
||||
assert!(g > 0.9 && r < 0.05 && b < 0.05, "green: {:?}", h.state());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_copy_button_copies_the_rgb_values() {
|
||||
let mut h = open_picker([1.0, 0.0, 0.0]);
|
||||
h.get_by_label("Copy RGB values").click();
|
||||
h.step();
|
||||
let copied = h.output().platform_output.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(t) if t == "255, 0, 0"));
|
||||
assert!(copied, "{:?}", h.output().platform_output.commands);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//! Effect rows in the layer stack: dragging one reorders its stack.
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::LayerId;
|
||||
use texturecraft_engine::execute;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
|
||||
fn id(v: Value, key: &str) -> u64 {
|
||||
v[key].as_u64().unwrap()
|
||||
}
|
||||
|
||||
/// Drag the row labelled `from` onto the upper (`below` false) or lower half of the row `to`.
|
||||
fn drag(h: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) {
|
||||
let start = h.get_by_label(from).rect().center();
|
||||
let r = h.get_by_label(to).rect();
|
||||
let end = egui::pos2(r.center().x, if below { r.bottom() - 4.0 } else { r.top() + 4.0 });
|
||||
h.drag_at(start);
|
||||
h.run_steps(2);
|
||||
h.hover_at(end);
|
||||
h.run_steps(2);
|
||||
h.drop_at(end);
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_an_effect_row_reorders_its_stack() {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"));
|
||||
let mut add =
|
||||
|name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect");
|
||||
let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C"));
|
||||
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.run_steps(4);
|
||||
let order = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::<Vec<_>>();
|
||||
assert_eq!(order(&h), [a, b, c]);
|
||||
// The rows list the top first: C, B, A. A dropped on C's upper half goes to the top.
|
||||
drag(&mut h, "Effect A", "Effect C", false);
|
||||
assert_eq!(order(&h), [b, c, a]);
|
||||
// A dropped on B's lower half goes back to the bottom.
|
||||
drag(&mut h, "Effect A", "Effect B", true);
|
||||
assert_eq!(order(&h), [a, b, c]);
|
||||
// C dropped on A's upper half lands between A and B.
|
||||
drag(&mut h, "Effect C", "Effect A", false);
|
||||
assert_eq!(order(&h), [a, c, b]);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//! The sliders of a selected effect (opacity, generator, levels…) apply what they were dragged
|
||||
//! or clicked to.
|
||||
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{Queryable, by};
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::core::{EffectKind, LayerId};
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
|
||||
/// The sample session with its first generator effect selected, and that effect's id.
|
||||
fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let (layer, effect) = session
|
||||
.doc
|
||||
.project
|
||||
.layers
|
||||
.values()
|
||||
.find_map(|l| {
|
||||
let mask = l.mask.iter().flat_map(|m| m.effects.iter());
|
||||
l.content_effects.iter().chain(mask).find(|e| matches!(e.kind, EffectKind::Generator(_))).map(|e| (l.id, e.id))
|
||||
})
|
||||
.unwrap();
|
||||
texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.run_steps(4);
|
||||
(h, effect)
|
||||
}
|
||||
|
||||
fn opacity(h: &Harness<'_, TextureCraftApp>, effect: LayerId) -> f32 {
|
||||
h.state().session.doc.project.effect(effect).unwrap().1.opacity
|
||||
}
|
||||
|
||||
/// The track under the slider labelled `label` (the row below the label).
|
||||
fn track(h: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect {
|
||||
let l = h.get_by_label(label).rect();
|
||||
egui::Rect::from_min_max(egui::pos2(l.left() + 6.0, l.bottom() + 6.0), egui::pos2(l.left() + 200.0, l.bottom() + 14.0))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_the_effect_opacity_applies_it() {
|
||||
let (mut h, effect) = harness();
|
||||
assert_eq!(opacity(&h, effect), 1.0);
|
||||
let t = track(&h, "Opacity");
|
||||
h.drag_at(egui::pos2(t.right(), t.center().y));
|
||||
h.run_steps(2);
|
||||
h.hover_at(egui::pos2(t.left() + 20.0, t.center().y));
|
||||
h.run_steps(2);
|
||||
h.drop_at(egui::pos2(t.left() + 20.0, t.center().y));
|
||||
h.run_steps(3);
|
||||
assert!(opacity(&h, effect) < 0.5, "the dragged opacity applies: {}", opacity(&h, effect));
|
||||
}
|
||||
|
||||
/// The combo box in the row of the "Channel" label.
|
||||
fn channel_picker<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> {
|
||||
let row = h.get_by_label("Channel").rect().center().y;
|
||||
h.get_all(by().role(Role::ComboBox)).find(|n| (n.rect().center().y - row).abs() < 4.0).unwrap()
|
||||
}
|
||||
|
||||
/// A content levels effect offers a channel for its histogram; picking one keeps it selected.
|
||||
#[test]
|
||||
fn content_levels_pick_the_histogram_channel() {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"color": [0.5, 0.2, 0.1], "roughness": 0.6})).unwrap();
|
||||
texturecraft_engine::execute(&mut session, "effect.add.levels", &json!({"target": "content"})).unwrap();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.run_steps(4);
|
||||
assert_eq!(channel_picker(&h).value().as_deref(), Some("Base color"), "the layer's first channel");
|
||||
channel_picker(&h).click();
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Roughness").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(channel_picker(&h).value().as_deref(), Some("Roughness"), "the picked channel stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_the_effect_opacity_applies_it() {
|
||||
let (mut h, effect) = harness();
|
||||
let t = track(&h, "Opacity");
|
||||
let at = egui::pos2(t.left() + 20.0, t.center().y);
|
||||
h.drag_at(at);
|
||||
h.drop_at(at);
|
||||
h.run_steps(3);
|
||||
assert!(opacity(&h, effect) < 0.5, "a click on the track applies: {}", opacity(&h, effect));
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! A click on a step of the History panel goes back or forward to it.
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use serde_json::json;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
use texturecraft_ui_egui::docking::Panel;
|
||||
|
||||
#[test]
|
||||
fn clicking_a_history_step_returns_to_it() {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let layer = session.selected_layer().unwrap();
|
||||
for name in ["Step A", "Step B", "Step C"] {
|
||||
texturecraft_engine::execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": name})).unwrap();
|
||||
}
|
||||
let done = session.history_labels().len();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.state_mut().ui.dock.focus(Panel::History);
|
||||
h.run_steps(4);
|
||||
let name = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].name.clone();
|
||||
// The first state: everything undone, and listed as undone.
|
||||
h.get_by_label("Project opened").click();
|
||||
h.run_steps(3);
|
||||
assert!(!h.state().session.can_undo());
|
||||
assert_eq!(h.state().session.redo_labels().len(), done);
|
||||
// The first undone row is the next step: one redo.
|
||||
h.get_all_by_label("Rename layer (undone)").next().unwrap().click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().session.history_labels().len(), 1);
|
||||
assert_eq!(h.state().session.redo_labels().len(), done - 1);
|
||||
// The last undone row: all the way forward again.
|
||||
h.get_all_by_label("Rename layer (undone)").last().unwrap().click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(name(&h), "Step C");
|
||||
assert!(!h.state().session.can_redo());
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
//! Ctrl+C, Ctrl+X and Ctrl+V on a layer clicked in the stack. The desktop and web shells deliver
|
||||
//! these keys as clipboard events, not key presses, so the tests send those events.
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use texturecraft_engine::core::LayerId;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
|
||||
/// The sample session with its selected layer clicked in the stack, and that layer.
|
||||
fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) {
|
||||
let session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.run_steps(4);
|
||||
let layer = h.state().session.selected_layer().unwrap();
|
||||
let name = h.state().session.doc.project.layers[&layer].name.clone();
|
||||
h.get_by_label(&name).click();
|
||||
h.run_steps(3);
|
||||
(h, layer)
|
||||
}
|
||||
|
||||
fn count(h: &Harness<'_, TextureCraftApp>) -> usize {
|
||||
h.state().session.doc.project.layers.len()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_x_cuts_the_clicked_layer() {
|
||||
let (mut h, layer) = harness();
|
||||
h.event(egui::Event::Cut);
|
||||
h.run_steps(3);
|
||||
assert!(!h.state().session.doc.project.layers.contains_key(&layer), "Ctrl+X removes the layer");
|
||||
assert!(h.state().session.clipboard.is_some(), "and keeps it on the layer clipboard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_c_then_ctrl_v_pastes_a_copy() {
|
||||
let (mut h, _) = harness();
|
||||
let before = count(&h);
|
||||
h.event(egui::Event::Copy);
|
||||
h.run_steps(3);
|
||||
assert!(h.state().session.clipboard.is_some(), "Ctrl+C copies the layer");
|
||||
// The shell sends the system clipboard's text with the paste; Ctrl+C put the layer name there.
|
||||
h.event(egui::Event::Paste("Layer".into()));
|
||||
h.run_steps(3);
|
||||
assert!(count(&h) > before, "Ctrl+V pastes the layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_shortcuts_act_on_a_selected_effect() {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let id = |v: serde_json::Value, key: &str| LayerId(v[key].as_u64().unwrap());
|
||||
let layer = id(texturecraft_engine::execute(&mut session, "layer.add.fill", &serde_json::Value::Null).unwrap(), "layer");
|
||||
let p = serde_json::json!({"target": "content", "filter": "invert"});
|
||||
let effect = id(texturecraft_engine::execute(&mut session, "effect.add.filter", &p).unwrap(), "effect");
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.run_steps(4);
|
||||
let effects = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers.get(&layer).map(|l| l.content_effects.len());
|
||||
h.event(egui::Event::Copy);
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().session.clipboard.as_ref().map(|(_, id)| *id), Some(effect), "Ctrl+C copies the selected effect");
|
||||
h.event(egui::Event::Paste("Fill".into()));
|
||||
h.run_steps(3);
|
||||
assert_eq!(effects(&h), Some(2), "Ctrl+V pastes it above");
|
||||
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::D);
|
||||
h.run_steps(3);
|
||||
assert_eq!(effects(&h), Some(3), "Ctrl+D duplicates the effect");
|
||||
h.key_press(egui::Key::Delete);
|
||||
h.run_steps(3);
|
||||
assert_eq!(effects(&h), Some(2), "Delete removes the effect, not its layer");
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//! The start window: New project opens its dialog, Continue keeps the open project, and the
|
||||
//! startup choice is a setting.
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
|
||||
fn harness() -> Harness<'static, TextureCraftApp> {
|
||||
let session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.state_mut().ui.windows.start = true;
|
||||
h.run_steps(3);
|
||||
h
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_window_choices() {
|
||||
let mut h = harness();
|
||||
h.get_by_label("New project...").click();
|
||||
h.run_steps(3);
|
||||
assert!(!h.state().ui.windows.start && h.state().ui.windows.new_project, "New project opens its dialog");
|
||||
|
||||
let mut h = harness();
|
||||
h.get_by_label("Show at startup").click();
|
||||
h.get_by_label("Continue with the sample project").click();
|
||||
h.run_steps(3);
|
||||
assert!(!h.state().ui.windows.start && !h.state().ui.windows.new_project);
|
||||
assert!(!h.state().ui.prefs.start_window, "unticked: not shown next time");
|
||||
assert_eq!(h.state().session.doc.project.texture_sets.len(), 2, "the sample stays open");
|
||||
}
|
||||
@@ -61,4 +61,33 @@ fn window_snapshots() {
|
||||
h.state_mut().ui.windows.export = false;
|
||||
h.state_mut().ui.windows.settings = true;
|
||||
save(&mut h, &dir, "window-settings");
|
||||
h.state_mut().ui.windows.settings = false;
|
||||
// The mesh map slots, each with its menu of images (a tall window shows them all).
|
||||
h.state_mut().ui.dock.focus(Panel::TextureSetSettings);
|
||||
h.set_size(egui::vec2(1600.0, 1800.0));
|
||||
save(&mut h, &dir, "panel-texture-set-settings");
|
||||
h.set_size(egui::vec2(1600.0, 960.0));
|
||||
// A mask's levels effect over clouds: the histogram in Properties.
|
||||
let s = &mut h.state_mut().session;
|
||||
for (id, p) in [
|
||||
("layer.add.fill", serde_json::json!({"color": [0.8, 0.3, 0.1]})),
|
||||
("mask.add.black", serde_json::Value::Null),
|
||||
("effect.add.fill", serde_json::json!({"target": "mask", "procedural": "clouds"})),
|
||||
("effect.add.levels", serde_json::json!({"target": "mask", "inLow": 0.3, "inHigh": 0.8})),
|
||||
] {
|
||||
texturecraft_engine::execute(s, id, &p).unwrap();
|
||||
}
|
||||
save(&mut h, &dir, "properties-levels");
|
||||
// Ctrl+right drag in the 3D view: the brush cursor where it began and the readout.
|
||||
let c = h.state().viewport_rect.center();
|
||||
let (m, button) = (egui::Modifiers::COMMAND, egui::PointerButton::Secondary);
|
||||
h.event(egui::Event::ModifiersChanged(m));
|
||||
h.event(egui::Event::PointerButton { pos: c, button, pressed: true, modifiers: m });
|
||||
for k in 1..=4 {
|
||||
h.hover_at(c + egui::vec2(15.0 * k as f32, -8.0 * k as f32));
|
||||
h.run_steps(1);
|
||||
}
|
||||
save(&mut h, &dir, "brush-ctrl-drag");
|
||||
h.event(egui::Event::PointerButton { pos: c, button, pressed: false, modifiers: m });
|
||||
h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
|
||||
}
|
||||
@@ -13,6 +13,14 @@ Everything TextureCraft does is an engine command with a stable id (`layer.add.f
|
||||
Programmatic calls never open dialogs: a command runs with its defaults. Only `ui.menu.invoke`
|
||||
behaves like a menu click. `session.inspect` shows every layer, mask, effect, fill source and
|
||||
painted tile count, so an agent can verify its work without a screenshot.
|
||||
`effect.histogram {effect, channel?, bins?}` counts the values an effect reads (a levels
|
||||
effect's input), so an agent can pick its input range from the data. `effect.move {effect,
|
||||
index}` reorders an effect within its stack (0 = bottom) and `effect.duplicate {effect}` copies
|
||||
one just above itself. `effect.copy {effect?}` and `effect.cut {effect?}` put an effect on the
|
||||
layer clipboard, and `effect.paste {layer?, target?}` adds it to another layer's content or mask.
|
||||
|
||||
`edit.undo {steps?}` and `edit.redo {steps?}` go back or forward several steps at once (as far
|
||||
as the history reaches); `edit.history` lists the steps done and the undone ones, next first.
|
||||
|
||||
## Control channel (desktop app)
|
||||
|
||||
@@ -100,16 +108,19 @@ print(call("command.run", {"id": "layer.add.fill", "params": {"color": [0.8, 0.1
|
||||
- **Headless** (default): an in-process session that starts on the material ball (1024).
|
||||
Files are reachable only below the roots given at launch, as forward-slash paths relative to
|
||||
them: `--read-root <dir>` for `project_open` / `mesh_import` / `mesh_reimport` / `bake_mesh_add`,
|
||||
`--write-root <dir>` for `project_save` / `material_save` / `textures_export` / `mesh_export`. Without roots there is no file access. `..`, absolute
|
||||
`--write-root <dir>` for `project_save` / `material_save` / `textures_export` / `mesh_export`
|
||||
(`--automation-read-root` / `--automation-write-root`, as in the other crafting apps, are the
|
||||
same flags). Without roots there is no file access. `..`, absolute
|
||||
paths, drive letters, device names and symlink or junction escapes are refused.
|
||||
- **Bridge**: `--bridge <port>` forwards to a running `texturecraft --control <port>` (token from
|
||||
`--token`, `TEXTURECRAFT_CONTROL_TOKEN` or the app's token file). The app reads and writes its
|
||||
own files, so the path tools are unavailable there; `project_save` without a path invokes
|
||||
File › Save.
|
||||
|
||||
Through `command_run`, every `file.*` command but `file.close` (and `file.reimportMesh` without
|
||||
a `path`) is refused, and so is any command given a `path` or `dir` (`resource.import`,
|
||||
`material.save`, `material.load`, …), in both modes: use the workspace tools below.
|
||||
Through `command_run`, every `file.*` command but `file.close` and `file.removeUnused` (and
|
||||
`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir` (`resource.import`,
|
||||
`material.save`, `material.load`, …), in both modes: use the workspace tools below. `resource.text`
|
||||
takes a font family, not a path: it reads only the system's font folders.
|
||||
|
||||
| Tool | Params | Notes |
|
||||
|---|---|---|
|
||||
@@ -124,7 +135,7 @@ a `path`) is refused, and so is any command given a `path` or `dir` (`resource.i
|
||||
| `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter |
|
||||
| `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (usda / usdc textures next to it) → `{path, textures?}` |
|
||||
| `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` |
|
||||
| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil` |
|
||||
| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot) |
|
||||
| `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root |
|
||||
| `material_load` | `{path}` | Add a `.tcmat` smart material above the selection |
|
||||
| `textures_export` | `{dir, preset?, ts?, format?, padding?, size?}` | Writes files below the write root |
|
||||
@@ -217,7 +228,7 @@ texturecraft-cli --version # TextureCraft 0.1.
|
||||
texturecraft-cli info model.glb # triangles, materials, UV report
|
||||
texturecraft-cli info project.tcraft # texture sets, layers, baked maps
|
||||
texturecraft-cli commands --filter mask
|
||||
texturecraft-cli new builtin:material_ball ball.tcraft --resolution 1024 --sample
|
||||
texturecraft-cli new builtin:material_ball ball.tcraft --resolution 1024 --sample # mesh maps baked at ≤ 1024 px
|
||||
texturecraft-cli new model.glb model.tcraft --resolution 2048
|
||||
texturecraft-cli run ball.tcraft layer.add.fill '{"color":"#c08040","metallic":1}' -o ball.tcraft
|
||||
texturecraft-cli batch script.json
|
||||
|
||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user