diff --git a/README.md b/README.md
index 3283e4d3..6b44b4a9 100644
--- a/README.md
+++ b/README.md
@@ -142,7 +142,8 @@
rotation, blur, ACES or linear tone mapping, key-light shadows, bloom, vignette, sharpen and
grain, parallax occlusion, and temporal anti-aliasing that refines the image while you look.
- **Rendering mode** (F10): a progressive, path-traced view of your textures with multi-bounce
- light, environment importance sampling and one-click PNG save.
+ light, environment importance sampling and one-click PNG save, traced on the GPU (compute
+ shaders, desktop and WebGPU) or on the CPU.
diff --git a/ROADMAP.md b/ROADMAP.md
index de74c43b..9b317ecc 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -13,16 +13,16 @@ end to end today (engine + UI + automation + tests), not what is planned.
|---|---:|---:|---|---|
| Project and files | 8 | 85% | New project from glTF/GLB, FBX (binary and ASCII 7.x), COLLADA, **USD (usda, usdc, usdz)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing), `.tcraft` open/save/save as/save a copy, autosave, recent files, drag and drop, reimport mesh, image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | Alembic import; FBX 6; project templates; preserving strokes on reimport |
| Texture sets | 6 | 80% | One set per material, **UDIM / UV tiles** (auto-detected, one texture per tile, `$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 | Per-tile resolution, converting a set to UV tiles after creation |
-| Layer stack | 16 | 82% | 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 | Anchor position inside a content stack; instances across texture sets of different resolutions |
-| Painting tools | 14 | 78% | 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 symmetry, pen pressure, procedural and image alphas, **particle brush** | Pen tilt (not exposed by the windowing layer), geometry decals, clone from the current layer only |
-| Materials and assets | 8 | 70% | 48 procedural materials (incl. car paint, velvet, brushed steel, skin, wax), 17 smart materials, 10 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 | Filter library; dragging saved smart materials |
+| Layer stack | 16 | 92% | 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 | Layer effects beyond the filter library (Painter's full effect catalog) |
+| Painting tools | 14 | 85% | 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 symmetry, pen pressure, procedural and image alphas, **particle brush** | Pen tilt (not exposed by the windowing layer) |
+| Materials and assets | 8 | 80% | 48 procedural materials (incl. car paint, velvet, brushed steel, skin, wax), 17 smart materials, 10 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 | More filters (Painter ships dozens) |
| Baking | 10 | 82% | 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 | Per-map ray settings, GPU ray-traced baking, high-poly material textures for the color map |
-| Viewport and display | 12 | 75% | 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, **path-traced Rendering mode** (F10) with environment importance sampling and an edge-aware **denoiser** | Subsurface scattering, depth of field, multiple cameras, GPU path tracing |
-| Shader | 6 | 75% | 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 | Transmission/IOR, coat normal, screen-space subsurface blur |
+| Viewport and display | 12 | 88% | 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, **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Subsurface scattering, depth of field, multiple cameras |
+| Shader | 6 | 88% | 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 | Transmission/IOR, coat normal, screen-space subsurface blur |
| Export | 8 | 85% | 8 presets 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 mesh export, zip download in the browser | USD export of the new shader lobes |
| UI and UX | 8 | 78% | 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), saved UI layouts, **shortcut editor** with conflict detection, tooltips with shortcuts; all menu items live ([docs/parity.md](docs/parity.md)); progressive compositing keeps 4K and 8K sets responsive | Translations (the lookup is in place), remembering where a closed panel was |
| Platforms | 4 | 60% | 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** | **≈ 78%** | | |
+| **Total** | **100** | **≈ 84%** | | |
Beyond Painter: every command is available to agents through MCP, the CLI and the app's
control channel, and the whole engine runs headless.
@@ -34,19 +34,19 @@ parallel on separate crates:
| Milestone | Scope | Estimate |
|---|---|---:|
-| M1 Layer stack depth | Anchor position in content stacks, cross-resolution instances | 1 h |
-| M2 Tools | Geometry decals, clone from layer, pen tilt when the platform exposes it | 3 h |
-| M3 Assets | Filter library, dragging saved smart materials | 2 h |
+| M1 Layer stack depth | Done | 0 h |
+| M2 Tools | Pen tilt once the windowing layer reports it, decal drag handles | 1 h |
+| M3 Assets | Done | 0 h |
| M4 Baking | Per-map ray settings, GPU ray-traced baking, high-poly material transfer | 3 h |
-| M5 Viewport | SSS, depth of field, cameras, GPU path tracing | 6 h |
-| M6 Shader | Transmission/IOR, coat normal, tessellated displacement | 2 h |
+| M5 Viewport | Refraction of other geometry, hardware ray tracing | 2 h |
+| M6 Shader | Tessellated displacement | 1 h |
| M7 Formats | Alembic import, per-tile UDIM resolution | 3 h |
| M8 UX | Translations, panel placement memory, more 8K tuning | 3 h |
| M9 Release | First signed release on every platform, web deployment, README screenshots refresh | 4 h |
-| **Total** | | **≈ 27 h** |
+| **Total** | | **≈ 17 h** |
## Current focus
-1. Viewport (M5): depth of field, multiple cameras, GPU path tracing.
+1. Viewport (M5): depth of field, multiple cameras.
2. Baking (M4): per-map ray settings, GPU ray-traced baking.
3. Release (M9): signing secrets on the repository, then the first release run.
diff --git a/apps/texturecraft-cli/src/main.rs b/apps/texturecraft-cli/src/main.rs
index 5daede0a..48f431d9 100644
--- a/apps/texturecraft-cli/src/main.rs
+++ b/apps/texturecraft-cli/src/main.rs
@@ -30,9 +30,10 @@ USAGE:
texturecraft-cli export
[--preset ] [--format ] [--padding ] [--size ]
Export textures (default preset: Document channels + Normal + AO).
texturecraft-cli render [--size x] [--view 3d|2d] [--yaw ] [--pitch ]
- [--samples ] [--bounces ]
- Render the viewport to PNG (needs a GPU or software adapter); --samples path traces it on
- the CPU instead (Rendering mode).
+ [--samples ] [--bounces ] [--cpu]
+ Render the viewport to PNG (needs a GPU or software adapter); --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 > [--resolution ] [--sample]
New project; --sample bakes and applies a smart material to every texture set.
texturecraft-cli mcp [--bridge ] [--token ] [--read-root ] [--write-root ]
@@ -54,7 +55,7 @@ const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[
("batch", &[], &[]),
("bake", &["-o", "--resolution", "--maps"], &[]),
("export", &["--preset", "--format", "--padding", "--size"], &[]),
- ("render", &["--size", "--view", "--yaw", "--pitch", "--samples", "--bounces"], &[]),
+ ("render", &["--size", "--view", "--yaw", "--pitch", "--samples", "--bounces"], &["--cpu"]),
("new", &["--resolution"], &["--sample"]),
("mcp", &["--bridge", "--token", "--read-root", "--write-root"], &[]),
("serve", &["--port", "--read-root", "--write-root"], &[]),
@@ -333,12 +334,14 @@ fn render(a: &Args) -> R {
pitch: a.num("--pitch")?,
samples: a.num("--samples")?,
bounces: a.num("--bounces")?,
+ cpu: a.has("--cpu"),
};
let mut h = open(input, None)?;
- let (w, ht, png) = h.render_png(&o).map_err(s)?;
- std::fs::write(out, png).map_err(|e| format!("cannot write {out}: {e}"))?;
- let by = if o.samples.is_some() { "path traced" } else { h.adapter().unwrap_or("GPU") };
- eprintln!("wrote {out} ({w}x{ht}, {by})");
+ let t0 = std::time::Instant::now();
+ let r = h.render_png(&o).map_err(s)?;
+ let secs = t0.elapsed().as_secs_f64();
+ std::fs::write(out, &r.png).map_err(|e| format!("cannot write {out}: {e}"))?;
+ eprintln!("wrote {out} ({}x{}, {}, {secs:.2} s)", r.width, r.height, r.by);
Ok(())
}
diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs
index 31d4b8c7..2a0b3dce 100644
--- a/apps/texturecraft-cli/tests/cli.rs
+++ b/apps/texturecraft-cli/tests/cli.rs
@@ -117,12 +117,17 @@ fn render_writes_a_png() {
fn path_traced_render_needs_no_gpu() {
let d = tmp("trace");
let out = d.join("ball.png");
- ok(&["render", "builtin:material_ball", p(&out), "--size", "96x64", "--samples", "4"]);
- let img = image::open(&out).unwrap().to_rgb8();
- assert_eq!(img.dimensions(), (96, 64));
- // The lit ball in the middle is brighter than the dark backdrop corner.
- let lum = |x, y| img.get_pixel(x, y).0.iter().map(|v| *v as u32).sum::();
- assert!(lum(48, 28) > lum(1, 1) + 60);
+ // On the GPU where it has compute shaders, then forced onto the CPU.
+ for extra in [None, Some("--cpu")] {
+ let mut args = vec!["render", "builtin:material_ball", p(&out), "--size", "96x64", "--samples", "4"];
+ args.extend(extra);
+ ok(&args);
+ let img = image::open(&out).unwrap().to_rgb8();
+ assert_eq!(img.dimensions(), (96, 64));
+ // The lit ball in the middle is brighter than the dark backdrop corner.
+ let lum = |x, y| img.get_pixel(x, y).0.iter().map(|v| *v as u32).sum::();
+ assert!(lum(48, 28) > lum(1, 1) + 60);
+ }
assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "0"]).status.code(), Some(1));
assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "4", "--view", "2d"]).status.code(), Some(1));
let _ = std::fs::remove_dir_all(&d);
diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs
index 961a2255..3beedb8b 100644
--- a/crates/automation/src/headless.rs
+++ b/crates/automation/src/headless.rs
@@ -39,6 +39,16 @@ pub struct RenderOptions {
pub samples: Option,
/// Light bounces for path tracing (default 6).
pub bounces: Option,
+ /// Path trace on the CPU even when a GPU with compute shaders exists.
+ pub cpu: bool,
+}
+
+/// A PNG render and what drew it (the GPU adapter, or the CPU path tracer).
+pub struct Rendered {
+ pub width: u32,
+ pub height: u32,
+ pub png: Vec,
+ pub by: String,
}
/// Most samples per pixel a path-traced render may take.
@@ -233,8 +243,9 @@ impl Headless {
Ok(json!({ "files": written, "warnings": warnings }))
}
- /// Render the session to PNG: `(width, height, png)`. Errors without a GPU adapter.
- pub fn render_png(&mut self, o: &RenderOptions) -> Result<(u32, u32, Vec), AutomationError> {
+ /// Render the session to PNG. The viewport needs a GPU adapter; path tracing (`samples`)
+ /// runs on the GPU when it has compute shaders and falls back to the CPU.
+ pub fn render_png(&mut self, o: &RenderOptions) -> Result {
let s = &self.session;
let kind = match o.view.as_deref().unwrap_or("3d") {
"3d" => ViewKind::Scene,
@@ -261,12 +272,34 @@ impl Headless {
return Err(bad(format!("path tracing renders the 3D view with 1 to {MAX_TRACE_SAMPLES} samples")));
}
let settings = texturecraft_render::trace::TraceSettings { bounces: o.bounces.unwrap_or(6).clamp(1, 32) };
- let (w, h, rgba) = crate::render::path_trace(&mut self.session, size, camera, samples, &settings);
+ let mut traced = None;
+ let mut by = "CPU path tracer".to_string();
+ if !o.cpu
+ && let Ok(gpu) = self.gpu.get_or_insert_with(Gpu::new)
+ {
+ // Last-resort guard, as for viewport renders below.
+ let session = &mut self.session;
+ match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| gpu.path_trace(session, size, camera, samples, &settings))) {
+ Ok(Ok(px)) => {
+ by = format!("{} (GPU path tracer)", gpu.adapter());
+ traced = Some(px);
+ }
+ Ok(Err(e)) => by = format!("CPU path tracer ({e})"),
+ Err(_) => {
+ by = "CPU path tracer (the GPU path tracer failed)".into();
+ self.gpu = None;
+ }
+ }
+ }
+ let (w, h, rgba) = match traced {
+ Some(px) => px,
+ None => crate::render::path_trace(&mut self.session, size, camera, samples, &settings),
+ };
let png = encode_png(w, h, rgba)?;
if !self.trusted() {
check_png(png.len())?;
}
- return Ok((w, h, png));
+ return Ok(Rendered { width: w, height: h, png, by });
}
let gpu = match self.gpu.get_or_insert_with(Gpu::new) {
Ok(g) => g,
@@ -287,7 +320,7 @@ impl Headless {
if !self.trusted() {
check_png(png.len())?;
}
- Ok((w, h, png))
+ Ok(Rendered { width: w, height: h, png, by: self.adapter().unwrap_or("GPU").to_string() })
}
/// The GPU adapter used for renders, if one was created.
diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs
index 696d5c17..cbc834f5 100644
--- a/crates/automation/src/render.rs
+++ b/crates/automation/src/render.rs
@@ -4,6 +4,7 @@
use rayon::prelude::*;
use texturecraft_engine::compose::{DisplayKind, all_tiles, tile_bytes};
use texturecraft_engine::{Session, ViewMode};
+use texturecraft_render::gpu_trace::GpuTracer;
use texturecraft_render::trace::{TraceDisplay, TraceScene, TraceSet, TraceSettings, Tracer};
use texturecraft_render::{Frame, Shade, ViewKind};
@@ -13,12 +14,14 @@ pub struct Gpu {
mesh_id: u64,
sets: Vec<((u32, u32), usize)>,
env: String,
+ /// The GPU path tracer, created by the first [`Gpu::path_trace`].
+ tracer: Option,
}
impl Gpu {
/// Errors when there is no GPU (or software) adapter.
pub fn new() -> Result {
- Ok(Gpu { h: texturecraft_render::headless::Headless::new()?, mesh_id: 0, sets: Vec::new(), env: String::new() })
+ Ok(Gpu { h: texturecraft_render::headless::Headless::new()?, mesh_id: 0, sets: Vec::new(), env: String::new(), tracer: None })
}
pub fn adapter(&self) -> &str {
@@ -84,11 +87,30 @@ impl Gpu {
let frame = Frame { view_id: 1, size, kind, camera, shade: shade(s), visible: s.doc.project.texture_sets.iter().map(|t| t.visible).collect() };
self.h.render(&frame)
}
+
+ /// [`path_trace`] on the GPU (compute shaders); errors when the adapter or the scene does
+ /// not allow it.
+ pub fn path_trace(
+ &mut self,
+ s: &mut Session,
+ size: [u32; 2],
+ camera: texturecraft_engine::geom::OrbitCamera,
+ samples: u32,
+ settings: &TraceSettings,
+ ) -> Result<(u32, u32, Vec), String> {
+ self.sync(s);
+ let (scene, display) = trace_inputs(s);
+ let h = &self.h;
+ let tracer = match &mut self.tracer {
+ Some(t) => t,
+ None => self.tracer.insert(GpuTracer::new(&h.device)?),
+ };
+ tracer.render(&h.device, &h.queue, &h.renderer, &scene, &camera, settings, &display, size, samples)
+ }
}
-/// A progressive CPU path trace of the session's 3D view (the app's Rendering mode), finished
-/// after `samples` passes and denoised; RGBA8 (sRGB) pixels.
-pub fn path_trace(s: &mut Session, size: [u32; 2], camera: texturecraft_engine::geom::OrbitCamera, samples: u32, settings: &TraceSettings) -> (u32, u32, Vec) {
+/// The session's 3D view as the path tracers see it, and how Rendering mode shows it (denoised).
+fn trace_inputs(s: &mut Session) -> (TraceScene, TraceDisplay) {
s.update();
let sets = s
.doc
@@ -101,11 +123,24 @@ pub fn path_trace(s: &mut Session, size: [u32; 2], camera: texturecraft_engine::
let d = &s.doc.project.display;
let env_image = d.environment_resource().and_then(|n| s.images.get(n));
let scene = TraceScene::for_display(s.mesh.clone(), s.bvh.clone(), sets, d, env_image.map(|i| i.as_ref()));
+ (scene, TraceDisplay { denoise: true, ..TraceDisplay::from_display(d) })
+}
+
+/// A progressive CPU path trace of the session's 3D view (the app's Rendering mode), finished
+/// after `samples` passes and denoised; RGBA8 (sRGB) pixels.
+pub fn path_trace(
+ s: &mut Session,
+ size: [u32; 2],
+ camera: texturecraft_engine::geom::OrbitCamera,
+ samples: u32,
+ settings: &TraceSettings,
+) -> (u32, u32, Vec) {
+ let (scene, display) = trace_inputs(s);
let mut tracer = Tracer::new(size[0], size[1]);
for _ in 0..samples {
tracer.pass(&scene, &camera, settings);
}
- (tracer.width, tracer.height, tracer.rgba8(&TraceDisplay { denoise: true, ..TraceDisplay::from_display(d) }))
+ (tracer.width, tracer.height, tracer.rgba8(&display))
}
/// How the viewport shades the session (the app's `viewport::shade`).
@@ -122,7 +157,7 @@ pub fn shade(s: &Session) -> Shade {
channel,
// The app's default (only the 2D view draws it).
wireframe: true,
- ..Shade::from_display(&s.doc.project.display)
+ ..Shade::from_project(&s.doc.project)
}
}
@@ -166,6 +201,35 @@ mod tests {
assert!(warm(&lit) > warm(&base), "the orange sky warms the image");
}
+ #[test]
+ fn gpu_path_trace_matches_the_cpu_on_the_material_ball() {
+ let mesh = texturecraft_engine::geom::primitives::material_ball();
+ let mut s = Session::new_project("t", mesh, "builtin:material_ball", None, 256).unwrap();
+ execute(&mut s, "layer.add.fill", &json!({"color": [0.75, 0.42, 0.23], "roughness": 0.3, "metallic": 0.4})).unwrap();
+ let Ok(mut gpu) = Gpu::new() else {
+ eprintln!("skipping: no GPU adapter");
+ return;
+ };
+ let (cam, settings, size) = (s.camera, TraceSettings { bounces: 4 }, [64, 48]);
+ let g = match gpu.path_trace(&mut s, size, cam, 384, &settings) {
+ Ok((_, _, px)) => px,
+ Err(e) => {
+ eprintln!("skipping: {e}");
+ return;
+ }
+ };
+ let (_, _, c) = path_trace(&mut s, size, cam, 384, &settings);
+ // Mean luminance per 8×8 block (8-bit levels) agrees.
+ let lum = |img: &[u8], x: usize, y: usize| {
+ let p = &img[(y * 64 + x) * 4..(y * 64 + x) * 4 + 3];
+ 0.2126 * p[0] as f32 + 0.7152 * p[1] as f32 + 0.0722 * p[2] as f32
+ };
+ let block = |img: &[u8], bx: usize, by: usize| (0..64).map(|i| lum(img, bx * 8 + i % 8, by * 8 + i / 8)).sum::() / 64.0;
+ let worst = (0..6).flat_map(|by| (0..8).map(move |bx| (bx, by))).map(|(bx, by)| (block(&g, bx, by) - block(&c, bx, by)).abs()).fold(0.0, f32::max);
+ assert!(worst < 4.0, "worst block differs by {worst} levels");
+ assert!(g.chunks(4).any(|p| p[0] > p[2] + 40), "the orange fill shows");
+ }
+
#[test]
fn uv_tile_atlas_renders_tiles_side_by_side() {
let mesh = texturecraft_engine::geom::primitives::udim_plane();
diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs
index d8e50d38..b575391f 100644
--- a/crates/automation/src/rpc.rs
+++ b/crates/automation/src/rpc.rs
@@ -93,9 +93,13 @@ impl Headless {
pitch: f32_of(p, "pitch")?,
samples: u32_of(p, "samples")?,
bounces: u32_of(p, "bounces")?,
+ cpu: match p.get("cpu") {
+ None | Some(Value::Null) => false,
+ Some(v) => v.as_bool().ok_or_else(|| bad("`cpu` must be true or false"))?,
+ },
};
- let (w, h, png) = self.render_png(&o)?;
- Ok(json!({ "width": w, "height": h, "png": base64::engine::general_purpose::STANDARD.encode(png) }))
+ let r = self.render_png(&o)?;
+ Ok(json!({ "width": r.width, "height": r.height, "by": r.by, "png": base64::engine::general_purpose::STANDARD.encode(r.png) }))
}
m if m.starts_with("ui.") || m == "viewport.screenshot" => {
Err(bad(format!("`{m}` needs the running app (texturecraft --control ); headless renders use `render`")))
diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs
index 7a366358..dfc0e442 100644
--- a/crates/automation/src/server.rs
+++ b/crates/automation/src/server.rs
@@ -182,12 +182,16 @@ pub struct RenderParams {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pitch: Option,
/// Path trace the 3D view with this many samples per pixel (1..4096) instead of the
- /// real-time viewport: slower, physically based light transport, no GPU needed.
+ /// real-time viewport: slower, physically based light transport; on the GPU when it has
+ /// compute shaders, otherwise on the CPU (no GPU needed).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub samples: Option,
/// Light bounces when path tracing (default 6).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bounces: Option,
+ /// Path trace on the CPU even when a GPU is available.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cpu: Option,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs
index 6d6bab28..fce718c2 100644
--- a/crates/compose/src/display.rs
+++ b/crates/compose/src/display.rs
@@ -11,6 +11,10 @@
//! | Emissive | sRGB8 | emissive | | | scattering weight |
//! | Lobes | RGBA8 | coat weight | coat roughness | anisotropy level | anisotropy angle |
//! | Sheen | sRGB8 | sheen color | | | sheen weight |
+//! | Extra | RGBA8 | coat normal x | coat normal y | transmission | |
+//!
+//! Extra packs the coat normal's x and y as `128 + 127 × n` (the default normal is exactly 0;
+//! z is rebuilt in the shader).
//!
//! Alpha of sRGB formats is linear. Channels a set lacks pack their default values, which switch
//! the extra lobes off, so the renderer can keep Lobes and Sheen as 1×1 placeholders until a
@@ -40,11 +44,21 @@ pub enum DisplayKind {
Lobes,
/// sRGB8: sheen color, alpha = sheen weight.
Sheen,
+ /// RGBA8 linear: coat normal x and y, transmission.
+ Extra,
}
impl DisplayKind {
- pub const ALL: [DisplayKind; 7] =
- [DisplayKind::BaseColor, DisplayKind::Orm, DisplayKind::Normal, DisplayKind::Height, DisplayKind::Emissive, DisplayKind::Lobes, DisplayKind::Sheen];
+ pub const ALL: [DisplayKind; 8] = [
+ DisplayKind::BaseColor,
+ DisplayKind::Orm,
+ DisplayKind::Normal,
+ DisplayKind::Height,
+ DisplayKind::Emissive,
+ DisplayKind::Lobes,
+ DisplayKind::Sheen,
+ DisplayKind::Extra,
+ ];
/// Bytes per texel of the upload format.
pub fn bytes_per_texel(self) -> usize {
@@ -60,6 +74,7 @@ impl DisplayKind {
Channel::Emissive | Channel::ScatterWeight => DisplayKind::Emissive,
Channel::CoatWeight | Channel::CoatRoughness | Channel::AnisotropyLevel | Channel::AnisotropyAngle => DisplayKind::Lobes,
Channel::SheenColor | Channel::SheenWeight => DisplayKind::Sheen,
+ Channel::CoatNormal | Channel::Transmission => DisplayKind::Extra,
_ => DisplayKind::Orm,
}
}
@@ -120,6 +135,18 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3
}
}
}
+ DisplayKind::Extra => {
+ let (n, transmission) = (get(Channel::CoatNormal), scalar8(Channel::Transmission));
+ // Signed 8-bit around 128 so the flat normal packs exactly.
+ let snorm = |v: u16| (128.0 + 127.0 * (v as f32 / 65535.0 * 2.0 - 1.0)).round().clamp(0.0, 255.0) as u8;
+ for (i, px) in out.chunks_exact_mut(4).enumerate() {
+ for (k, d) in px.iter_mut().take(2).enumerate() {
+ *d = n.and_then(|t| t.get(i * 3 + k)).map_or(128, |v| snorm(*v));
+ }
+ px[2] = transmission(i);
+ px[3] = 0;
+ }
+ }
DisplayKind::Orm => {
let (ao, m, s) = (get(Channel::AmbientOcclusion), get(Channel::Metallic), get(Channel::SpecularLevel));
// Specular/glossiness sets: the viewport shades roughness = 1 − glossiness.
@@ -194,6 +221,7 @@ mod tests {
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Emissive, 0, 0)[..4], &[0, 0, 0, 0]);
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Lobes, 0, 0)[..4], &[0, 25, 0, 0], "lobes off, coat roughness 0.1");
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Sheen, 0, 0)[..4], &[255, 255, 255, 0]);
+ assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Extra, 0, 0)[..4], &[128, 128, 0, 0], "flat coat normal, no transmission");
for k in DisplayKind::ALL {
assert_eq!(k.default_texel(), tile_bytes(&comp, &BakedMaps::default(), k, 3, 5)[..k.bytes_per_texel()]);
}
@@ -229,11 +257,14 @@ mod tests {
set(Channel::SheenWeight, &[to_u16(0.8)]);
set(Channel::SheenRoughness, &[to_u16(0.3)]);
set(Channel::ScatterWeight, &[to_u16(0.4)]);
+ set(Channel::Transmission, &[to_u16(0.6)]);
+ set(Channel::CoatNormal, &[to_u16(1.0), to_u16(0.5), to_u16(1.0)]);
let px = |k: DisplayKind| tile_bytes(&comp, &BakedMaps::default(), k, 0, 0)[4..8].to_vec();
let near = |a: &[u8], b: &[u8]| a.iter().zip(b).all(|(x, y)| x.abs_diff(*y) <= 1);
assert!(near(&px(DisplayKind::Lobes), &[255, 51, 153, 64]), "{:?}", px(DisplayKind::Lobes));
assert!(near(&px(DisplayKind::Sheen), &[255, 0, 188, 204]), "{:?}", px(DisplayKind::Sheen));
assert!(near(&px(DisplayKind::Normal)[3..], &[77]) && near(&px(DisplayKind::Emissive)[3..], &[102]));
+ assert!(near(&px(DisplayKind::Extra), &[255, 128, 153, 0]), "{:?}", px(DisplayKind::Extra));
for c in Channel::LOBES {
assert_ne!(DisplayKind::of_channel(c), DisplayKind::Orm, "{c:?}");
}
diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs
index 84688e9b..06ceaa37 100644
--- a/crates/compose/src/eval.rs
+++ b/crates/compose/src/eval.rs
@@ -2,19 +2,20 @@
//! tile by tile in parallel. This is the reference implementation (the oracle) for the viewport
//! and for export.
+use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use rayon::prelude::*;
use texturecraft_core::{
BakedMap, BlendMode, Channel, ChannelKind, CompareOp, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind,
- Mask, MaskBackground, Project, Projection, Source, TextureSet, TileGrid, blend1, blend3, hsl_adjust, lum, mix3,
+ Mask, MaskBackground, Project, Projection, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit,
};
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer};
-use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, to_u16, to_u16_signed};
+use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed};
use crate::below::{Band, BelowCache, Level};
-use crate::pattern::{Coords, image_samples, procedural, world_noise};
+use crate::pattern::{Coords, decal_uv, image_samples, procedural, world_noise};
use crate::store::{BakedMaps, ImageStore, PixelStore, decode};
const NCH: usize = Channel::ALL.len();
@@ -173,7 +174,7 @@ struct ChanPlan<'a> {
comps: usize,
blend: BlendMode,
opacity: f32,
- data: Option<&'a [u16]>,
+ data: Option>,
/// Visible content effects, holding this channel's tile for paint effects (empty, and
/// allocation free, for layers without content effects).
effects: Vec>,
@@ -192,7 +193,7 @@ struct EffectPlan<'a> {
kind: &'a EffectKind,
blend: BlendMode,
opacity: f32,
- data: Option<&'a [u16]>,
+ data: Option>,
preview: bool,
}
@@ -233,21 +234,128 @@ pub enum FieldKey {
pub type Fields = HashMap;
+/// How a neighbourhood filter reads around a texel.
+#[derive(Clone, Copy)]
+enum Op {
+ /// Box blurs (≈ Gaussian), sharpening by the amount when given.
+ Blur(Option),
+ /// Average along a direction (unit vector in texels).
+ Line([f32; 2]),
+ /// Read at an offset given by a noise vector field.
+ Warp { scale: f32, seed: u32 },
+ /// Average downhill along a noise height field.
+ Slope { scale: f32, seed: u32 },
+}
+
/// Index (among visible effects) of the last neighbourhood filter of an effect stack, its
-/// radius in texels and its sharpen amount.
-fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Option)> {
+/// radius in texels (`res` texels per UV tile across) and what it does.
+fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> {
+ let texels = |v: f32| (v * res as f32 / 2048.0).max(0.5);
effects
.iter()
.filter(|e| e.visible)
.enumerate()
.filter_map(|(i, e)| match &e.kind {
- EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((i, (radius * res as f32 / 2048.0).max(0.5), None)),
- EffectKind::Filter(Filter::Sharpen { amount }) => Some((i, (1.5 * res as f32 / 2048.0).max(0.75), Some(*amount))),
+ EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((i, texels(*radius), Op::Blur(None))),
+ EffectKind::Filter(Filter::Sharpen { amount }) => Some((i, (1.5 * res as f32 / 2048.0).max(0.75), Op::Blur(Some(*amount)))),
+ EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => {
+ let (sn, cs) = angle.to_radians().sin_cos();
+ // Texel rows run down: positive angles turn counterclockwise on screen.
+ Some((i, texels(*radius), Op::Line([cs, -sn])))
+ }
+ EffectKind::Filter(Filter::Warp { intensity, scale, seed }) if *intensity > 0.0 => {
+ Some((i, texels(*intensity), Op::Warp { scale: *scale, seed: *seed }))
+ }
+ EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => {
+ Some((i, texels(*radius), Op::Slope { scale: *scale, seed: *seed }))
+ }
_ => None,
})
.last()
}
+/// Samples along a directional or slope blur at most (beyond, samples spread out).
+const LINE_SAMPLES: i32 = 24;
+
+/// Fractal noise over texel position `(x, y)` (`res` texels per UV unit, `scale` features per
+/// UV unit), shifted by `d` in noise space.
+fn texel_noise(x: f32, y: f32, d: [f32; 2], res: u32, scale: f32, seed: u32) -> f32 {
+ let k = if scale.is_finite() { scale.clamp(0.01, 1000.0) } else { 1.0 } / res.max(1) as f32;
+ noise::fbm([x * k + d[0], y * k + d[1], 0.0], 3, seed, noise::perlin)
+}
+
+/// The neighbourhood filters that gather samples (directional and slope blur, warp) over a
+/// field region `(x0, y0, w, h)` of premultiplied `orig` texels (`comps` each) and their
+/// `cover`: bilinear samples weighted by coverage, so uncovered texels don't bleed in.
+/// Positions are absolute texel coordinates, so a texel's result does not depend on the region.
+#[allow(clippy::too_many_arguments)]
+fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u32, u32, u32, u32), r: f32, res: u32, opacity: f32) -> Vec {
+ let mut data = orig.to_vec();
+ let (wu, hu) = (w as usize, h as usize);
+ // Bilinear sample at absolute texel position (fx, fy) into `acc` (components, then weight).
+ let sample = |fx: f32, fy: f32, acc: &mut [f32; 5]| {
+ if !(fx.is_finite() && fy.is_finite()) {
+ return;
+ }
+ let (bx, by) = (fx.floor(), fy.floor());
+ let (tx, ty) = (fx - bx, fy - by);
+ for (dx, dy, k) in [(0, 0, (1.0 - tx) * (1.0 - ty)), (1, 0, tx * (1.0 - ty)), (0, 1, (1.0 - tx) * ty), (1, 1, tx * ty)] {
+ let (cx, cy) = (bx as i64 + dx - i64::from(x0), by as i64 + dy - i64::from(y0));
+ if k <= 0.0 || cx < 0 || cy < 0 || cx >= wu as i64 || cy >= hu as i64 {
+ continue;
+ }
+ let i = cy as usize * wu + cx as usize;
+ let (Some(c), Some(px)) = (cover.get(i), orig.get(i * comps..(i + 1) * comps)) else { continue };
+ for (a, v) in acc.iter_mut().zip(px) {
+ *a += v * k;
+ }
+ acc[4] += c * k;
+ }
+ };
+ data.par_chunks_mut((comps * wu).max(1)).enumerate().for_each(|(row, line)| {
+ for col in 0..wu {
+ if cover.get(row * wu + col).is_none_or(|c| *c <= 0.0) {
+ continue;
+ }
+ let (x, y) = ((x0 as usize + col) as f32, (y0 as usize + row) as f32);
+ let mut acc = [0.0f32; 5];
+ let n = (r.ceil() as i32).clamp(1, LINE_SAMPLES);
+ let step = r / n as f32;
+ match op {
+ Op::Line(d) => {
+ for s in -n..=n {
+ let t = s as f32 * step;
+ sample(x + d[0] * t, y + d[1] * t, &mut acc);
+ }
+ }
+ Op::Warp { scale, seed } => {
+ let off = |salt: u32| ((texel_noise(x, y, [0.0; 2], res, scale, seed ^ salt) - 0.5) * 3.0).clamp(-1.0, 1.0) * r;
+ sample(x + off(0), y + off(0x5BD1_E995), &mut acc);
+ }
+ Op::Slope { scale, seed } => {
+ let e = 0.01;
+ let hgt = |dx: f32, dy: f32| texel_noise(x, y, [dx, dy], res, scale, seed);
+ // Downhill; a flat spot keeps its value.
+ let d = Vec2::new(hgt(-e, 0.0) - hgt(e, 0.0), hgt(0.0, -e) - hgt(0.0, e)).try_normalize().unwrap_or(Vec2::ZERO);
+ for s in 0..=n {
+ let t = s as f32 * step;
+ sample(x + d.x * t, y + d.y * t, &mut acc);
+ }
+ }
+ Op::Blur(_) => {}
+ }
+ if acc[4] > 1e-6
+ && let Some(px) = line.get_mut(col * comps..(col + 1) * comps)
+ {
+ for (slot, a) in px.iter_mut().zip(acc) {
+ *slot += (a / acc[4] - *slot) * opacity;
+ }
+ }
+ }
+ });
+ data
+}
+
/// Fixed-point scale of the blur. Integer running sums make a texel's result independent of
/// the region it is computed in, so tiles composited in any grouping agree exactly.
const FIX: f64 = (1u64 << 24) as f64;
@@ -367,12 +475,13 @@ fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: J
Job::Mask(m) => &m.effects,
Job::Content(_) => &inp.project.content_layer(id)?.content_effects,
};
- let (k, radius, sharpen) = neighbourhood(effects, inp.tile_res())?;
+ let (k, radius, op) = neighbourhood(effects, inp.tile_res())?;
let opacity = effects.iter().filter(|e| e.visible).nth(k).map(|e| e.opacity.clamp(0.0, 1.0)).unwrap_or(1.0);
// Clamped: a hostile radius must not overflow the halo and window arithmetic.
let r = radius.round().clamp(1.0, gw.max(gh) as f32) as u32;
- // Three box passes reach 3r texels.
- let halo = (3 * r).div_ceil(TILE);
+ // Three box passes reach 3r texels, the other filters r (and a texel for bilinear samples).
+ let reach = if let Op::Blur(_) = op { 3 * r } else { r + 1 };
+ let halo = reach.div_ceil(TILE);
let (tx0, ty0) = tiles.iter().fold((u32::MAX, u32::MAX), |(a, b), t| (a.min(t.0), b.min(t.1)));
let (tx1, ty1) = tiles.iter().fold((0, 0), |(a, b), t| (a.max(t.0), b.max(t.1)));
let (rx0, ry0) = (tx0.saturating_sub(halo) * TILE, ty0.saturating_sub(halo) * TILE);
@@ -442,6 +551,14 @@ fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: J
}
}
});
+ let sharpen = match op {
+ Op::Blur(sharpen) => sharpen,
+ _ => {
+ let mut data = gather(op, &orig, &cover, comps, (rx0, ry0, w, h), r as f32, inp.tile_res(), opacity);
+ unpremultiply(&mut data, comps);
+ return Some(Field { x0: rx0, y0: ry0, w, h, comps, data });
+ }
+ };
// Weighted so uncovered texels don't bleed in.
let (wu, hu, ru) = (w as usize, h as usize, r as usize);
let mut weights = cover;
@@ -463,6 +580,12 @@ fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: J
}
});
}
+ unpremultiply(&mut data, comps);
+ Some(Field { x0: rx0, y0: ry0, w, h, comps, data })
+}
+
+/// Clamp filtered masks to 0..1, and turn filtered content back into straight values.
+fn unpremultiply(data: &mut [f32], comps: usize) {
data.par_chunks_mut(comps).for_each(|px| match px {
[v] => *v = v.clamp(0.0, 1.0),
[r, g, b, cov] => {
@@ -474,7 +597,6 @@ fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: J
}
_ => {}
});
- Some(Field { x0: rx0, y0: ry0, w, h, comps, data })
}
/// Precompute the neighbourhood-filtered masks and content channels of every layer that needs
@@ -518,8 +640,9 @@ struct Node<'a> {
content: Content<'a>,
chans: Vec>,
mask: Option>,
- /// Visible anchor points of the layer (recorded after it is applied).
- anchors: Vec,
+ /// Visible anchor points of the layer: recorded after it is applied, or (`Some(k)`, an
+ /// anchor with visible effects above it) with its content cut after `k` visible effects.
+ anchors: Vec<(LayerId, Option)>,
/// The node or one of its children records an anchor.
has_anchor: bool,
height_mask: HeightMask,
@@ -540,13 +663,36 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, c
kind: &e.kind,
blend: e.blend,
opacity: e.opacity,
- data: matches!(e.kind, EffectKind::Paint).then(|| img.filter(|i| i.width() == inp.gbuf.width).and_then(|i| i.tile(tx, ty))).flatten(),
- preview: inp.preview.is_some_and(|p| p.target == target),
+ data: if matches!(e.kind, EffectKind::Paint) { tile_of(inp, img, tx, ty, channel) } else { None },
+ preview: previews(inp, target),
}
})
.collect()
}
+/// Whether the live stroke paints `target` in this composite (a stroke on a layer instanced in a
+/// set of another size does not show there).
+fn previews(inp: &Inputs, target: PaintTarget) -> bool {
+ inp.preview.is_some_and(|p| p.target == target && (p.alpha.width(), p.alpha.height()) == (inp.gbuf.width, inp.gbuf.height))
+}
+
+/// Tile (tx, ty) of painted pixels `img` (of `channel`, or a mask when None) at the size of the
+/// set being composited: as stored, or resampled (bilinear, premultiplied) when the pixels
+/// belong to a layer instanced from a set of another resolution.
+fn tile_of<'a>(inp: &Inputs, img: Option<&'a TileImage>, tx: u32, ty: u32, channel: Option) -> Option> {
+ let img = img?;
+ let (w, h) = (inp.gbuf.width, inp.gbuf.height);
+ if (img.width(), img.height()) == (w, h) {
+ return img.tile(tx, ty).map(Cow::Borrowed);
+ }
+ // Empty texels of signed channels hold a signed zero.
+ let empty: Vec = match channel {
+ Some(c) if c.kind() == ChannelKind::Signed => [vec![to_u16_signed(0.0); c.components()], vec![0]].concat(),
+ _ => Vec::new(),
+ };
+ img.resampled_tile(w, h, tx, ty, &empty).map(Cow::Owned)
+}
+
fn mask_plan<'a>(inp: &Inputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32, fields: Option<&'a Fields>) -> Option> {
if !mask.enabled {
return None;
@@ -567,7 +713,16 @@ fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, t
/// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are
/// planned when `kids`.
#[allow(clippy::too_many_arguments)]
-fn plan_node<'a>(inp: &Inputs<'a>, id: LayerId, channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>, kids: bool) -> Option> {
+fn plan_node<'a>(
+ inp: &Inputs<'a>,
+ id: LayerId,
+ channels: &[Channel],
+ tx: u32,
+ ty: u32,
+ depth: usize,
+ fields: Option<&'a Fields>,
+ kids: bool,
+) -> Option> {
let own: &'a Layer = inp.project.layers.get(&id)?;
// Instances draw their source's content (a missing source draws nothing).
let layer: &'a Layer = inp.project.content_layer(id)?;
@@ -584,16 +739,14 @@ fn plan_node<'a>(inp: &Inputs<'a>, id: LayerId, channels: &[Channel], tx: u32, t
if b.mode == BlendMode::Disable || b.opacity <= 0.0 {
return None;
}
- // shortcut: an instance in a set of another resolution draws no painted pixels;
- // resample the source's pixels if instances across sizes become common.
- let data = if paint { inp.pixels.layer(layer.id, *c).filter(|img| img.width() == inp.gbuf.width).and_then(|img| img.tile(tx, ty)) } else { None };
+ let data = if paint { tile_of(inp, inp.pixels.layer(layer.id, *c), tx, ty, Some(*c)) } else { None };
let effects = if fx { effect_plans(inp, &layer.content_effects, tx, ty, Some(*c)) } else { Vec::new() };
let start = fx_start.zip(fields.and_then(|f| f.get(&FieldKey::Content(id, *c))));
Some(ChanPlan { ch: c.index(), kind: c.kind(), comps: c.components(), blend: b.mode, opacity: b.opacity.clamp(0.0, 1.0), data, effects, start })
})
.collect::>();
let content = match &layer.kind {
- LayerKind::Paint => Content::Paint { preview: inp.preview.is_some_and(|p| p.target == PaintTarget::Layer(layer.id)) },
+ LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) },
LayerKind::Fill(f) => Content::Fill(f),
LayerKind::Group { children, .. } => Content::Group(if kids { plan(inp, children, channels, tx, ty, depth + 1, fields) } else { Vec::new() }),
// `content_layer` already followed instance links.
@@ -610,12 +763,20 @@ fn plan_node<'a>(inp: &Inputs<'a>, id: LayerId, channels: &[Channel], tx: u32, t
return None;
}
let mask = layer_mask(inp.project, id).and_then(|m| mask_plan(inp, id, m, tx, ty, fields));
- let anchors: Vec =
- if fx { layer.content_effects.iter().filter(|e| e.visible && matches!(e.kind, EffectKind::Anchor)).map(|e| e.id).collect() } else { Vec::new() };
+ let anchors = if fx { anchor_cuts(&layer.content_effects) } else { Vec::new() };
let has_anchor = !anchors.is_empty() || matches!(&content, Content::Group(nodes) if nodes.iter().any(|n| n.has_anchor));
Some(Node { id, content, chans, mask, anchors, has_anchor, height_mask: layer.height_mask })
}
+/// The visible anchor points of a content stack with where they cut it: after their index among
+/// the visible effects, or None for anchors with only anchors above them (they record the
+/// layer's full result).
+fn anchor_cuts(effects: &[Effect]) -> Vec<(LayerId, Option)> {
+ let visible: Vec<&Effect> = effects.iter().filter(|e| e.visible).collect();
+ let last = visible.iter().rposition(|e| !matches!(e.kind, EffectKind::Anchor));
+ visible.iter().enumerate().filter(|(_, e)| matches!(e.kind, EffectKind::Anchor)).map(|(i, e)| (e.id, last.filter(|l| *l > i).map(|_| i))).collect()
+}
+
/// One level of the path to the hot layer (see [`Level`]) planned for a tile.
struct LevelPlan<'a> {
below: Vec>,
@@ -639,16 +800,6 @@ fn plan_levels<'a>(inp: &Inputs<'a>, levels: &[Level], channels: &[Channel], tx:
.collect()
}
-/// Apply a 0..1 function to each component of a channel value: signed values map through
-/// 0..1, normals are left alone.
-fn per_unit(kind: ChannelKind, v: [f32; 3], f: impl Fn(f32) -> f32) -> [f32; 3] {
- match kind {
- ChannelKind::NormalMap => v,
- ChannelKind::Signed => v.map(|x| f(x * 0.5 + 0.5) * 2.0 - 1.0),
- ChannelKind::Color | ChannelKind::Scalar => v.map(f),
- }
-}
-
#[inline]
fn blend_chan(c: &ChanPlan, mode: BlendMode, a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
if c.comps == 3 { blend3(mode, a, b) } else { [blend1(mode, a[0], b[0]); 3] }
@@ -664,6 +815,9 @@ fn over(c: &ChanPlan, mode: BlendMode, v: [f32; 3], cov: f32, p: [f32; 3], a: f3
(mix3(v, b, a / nc.max(1e-5)), nc)
}
+/// The plain UV projection a decal's frame coordinates are sampled through.
+const DECAL_UV: Projection = Projection::Uv { scale: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] };
+
/// Per-texel context.
struct Texel<'a, 'b> {
inp: &'b Inputs<'a>,
@@ -791,17 +945,44 @@ impl<'a, 'b> Texel<'a, 'b> {
self.inp.baked.scalar(m, self.x, self.y, self.res)
}
+ /// Where projection `proj` samples this texel: the texel's coordinates, or for a decal its
+ /// position in the decal's frame (then sampled as UVs) and the decal's coverage.
+ fn projected<'p>(&mut self, proj: &'p Projection) -> (Coords, &'p Projection, f32) {
+ let c = self.coords();
+ match proj {
+ Projection::Decal(d) => match self.world().and_then(|p| decal_uv(d, p, c.nrm)) {
+ Some((uv, w)) => (Coords { uv, ..c }, &DECAL_UV, w),
+ None => (c, &DECAL_UV, 0.0),
+ },
+ _ => (c, proj, 1.0),
+ }
+ }
+
+ /// How much a fill projected by `proj` covers this texel: 1, or for a decal its frame
+ /// coverage times the alpha of its first image source.
+ fn cover<'s>(&mut self, mut sources: impl Iterator, proj: &Projection) -> f32 {
+ if !matches!(proj, Projection::Decal(_)) {
+ return 1.0;
+ }
+ let (c, _, w) = self.projected(proj);
+ let image = sources.find_map(|s| match s {
+ Source::Image { name } => self.inp.images.get(name),
+ _ => None,
+ });
+ w * image.map_or(1.0, |img| img.sample(c.uv.x, c.uv.y)[3].clamp(0.0, 1.0))
+ }
+
fn source(&mut self, s: &Source, proj: &Projection, kind: ChannelKind) -> [f32; 3] {
match s {
Source::Uniform(v) => *v,
Source::Procedural { pattern, low, high } => {
- let c = self.coords();
+ let (c, proj, _) = self.projected(proj);
let t = procedural(pattern, proj, &c);
mix3(*low, *high, t)
}
Source::Image { name } => {
let Some(img) = self.inp.images.get(name) else { return [0.5; 3] };
- let c = self.coords();
+ let (c, proj, _) = self.projected(proj);
let mut acc = [0.0f32; 4];
for (uv, w) in image_samples(proj, &c).into_iter().filter(|(_, w)| *w > 0.0) {
let s = img.sample(uv.x, uv.y);
@@ -858,7 +1039,7 @@ impl<'a, 'b> Texel<'a, 'b> {
let o = e.opacity.clamp(0.0, 1.0);
match e.kind {
EffectKind::Paint => {
- let (mut pv, mut cov) = match e.data {
+ let (mut pv, mut cov) = match e.data.as_deref() {
Some(d) => (from_u16(d.get(self.o * 2).copied().unwrap_or(0)), from_u16(d.get(self.o * 2 + 1).copied().unwrap_or(0))),
None => (0.0, 0.0),
};
@@ -881,7 +1062,7 @@ impl<'a, 'b> Texel<'a, 'b> {
}
EffectKind::Fill { source, projection } => {
let val = self.source(source, projection, ChannelKind::Scalar)[0];
- v += (blend1(e.blend, v, val) - v) * o;
+ v += (blend1(e.blend, v, val) - v) * o * self.cover(std::iter::once(source), projection);
}
EffectKind::Generator(g) => {
let val = self.generator(g);
@@ -889,20 +1070,9 @@ impl<'a, 'b> Texel<'a, 'b> {
}
EffectKind::Levels(l) => v += (l.apply(v) - v) * o,
EffectKind::Filter(f) => {
- let val = match f {
- Filter::Invert => 1.0 - v,
- Filter::Threshold { level } => {
- if v >= *level {
- 1.0
- } else {
- 0.0
- }
- }
- // A mask is gray: only its lightness changes.
- Filter::Hsl { lightness, .. } => hsl_adjust([v; 3], 0.0, 0.0, *lightness)[0],
- // Neighbourhood filters come precomputed through `MaskPlan::start`.
- Filter::Blur { .. } | Filter::Sharpen { .. } => v,
- };
+ // A mask is gray (HSL only changes its lightness); neighbourhood filters come
+ // precomputed through `MaskPlan::start`.
+ let val = f.point(ChannelKind::Scalar, [v; 3]).map_or(v, |x| x[0]);
v += (val - v) * o;
}
EffectKind::ColorSelection { colors, tolerance } => {
@@ -948,15 +1118,32 @@ impl<'a, 'b> Texel<'a, 'b> {
}
}
Content::Fill(_) | Content::Paint { .. } if m > 0.0 => {
+ let before = if n.anchors.iter().any(|a| a.1.is_some()) { Some(*acc) } else { None };
for c in &n.chans {
if let Some((v, cov)) = self.tape_content(&n.content, c) {
apply(acc, c, v, cov, m);
}
}
+ // Anchors inside the content stack: the stack with the content cut there.
+ for (a, cut) in &n.anchors {
+ let rec = match (cut, before) {
+ (Some(k), Some(mut b)) => {
+ for c in &n.chans {
+ if let Some((v, cov)) = self.content_to(&n.content, c, *k) {
+ apply(&mut b, c, v, cov, m);
+ }
+ }
+ b
+ }
+ _ => *acc,
+ };
+ self.anchors.push((*a, rec));
+ }
+ continue;
}
_ => {}
}
- for a in &n.anchors {
+ for (a, _) in &n.anchors {
self.anchors.push((*a, *acc));
}
}
@@ -1049,7 +1236,13 @@ impl<'a, 'b> Texel<'a, 'b> {
/// Straight value and coverage of one channel of a paint or fill layer at this texel
/// (content effects and live stroke preview included). None where the layer is empty.
fn content(&mut self, content: &Content, c: &ChanPlan) -> Option<([f32; 3], f32)> {
- let (mut v, mut cov, skip) = match c.start.and_then(|(k, f)| f.get(self.x, self.y).map(|d| (k, d))) {
+ self.content_to(content, c, usize::MAX)
+ }
+
+ /// [`Texel::content`] with only the first `end` visible content effects.
+ fn content_to(&mut self, content: &Content, c: &ChanPlan, end: usize) -> Option<([f32; 3], f32)> {
+ let start = c.start.filter(|(k, _)| *k < end);
+ let (mut v, mut cov, skip) = match start.and_then(|(k, f)| f.get(self.x, self.y).map(|d| (k, d))) {
Some((k, d)) => {
let px = |i: usize| d.get(i).copied().unwrap_or(0.0);
([px(0), px(1), px(2)], px(3), k + 1)
@@ -1063,15 +1256,15 @@ impl<'a, 'b> Texel<'a, 'b> {
Some(s) => self.source(s, &f.projection, ch.kind()),
None => ch.default_value(),
};
- (v, 1.0)
+ (v, self.cover(f.sources.values(), &f.projection))
}
- Content::Paint { preview } => self.painted(c.data, c, *preview),
+ Content::Paint { preview } => self.painted(c.data.as_deref(), c, *preview),
Content::Group(_) => return None,
};
(v, cov, 0)
}
};
- for e in c.effects.iter().skip(skip) {
+ for e in c.effects.iter().take(end).skip(skip) {
(v, cov) = self.content_effect(e, c, v, cov);
}
(cov > 0.0).then_some((v, cov.min(1.0)))
@@ -1138,32 +1331,24 @@ impl<'a, 'b> Texel<'a, 'b> {
let o = e.opacity.clamp(0.0, 1.0);
match e.kind {
EffectKind::Paint => {
- let (p, pc) = self.painted(e.data, c, e.preview);
+ let (p, pc) = self.painted(e.data.as_deref(), c, e.preview);
over(c, e.blend, v, cov, p, pc * o)
}
EffectKind::Material(f) => match Channel::ALL.get(c.ch).and_then(|ch| f.sources.get(ch).map(|s| (*ch, s))) {
Some((ch, s)) => {
let p = self.source(s, &f.projection, ch.kind());
- over(c, e.blend, v, cov, p, o)
+ let w = o * self.cover(f.sources.values(), &f.projection);
+ over(c, e.blend, v, cov, p, w)
}
None => (v, cov),
},
EffectKind::Levels(l) => (mix3(v, per_unit(c.kind, v, |x| l.apply(x)), o), cov),
- EffectKind::Filter(f) => {
- let out = match f {
- Filter::Invert => per_unit(c.kind, v, |x| 1.0 - x),
- Filter::Threshold { level } => per_unit(c.kind, v, |x| if x >= *level { 1.0 } else { 0.0 }),
- Filter::Hsl { hue, saturation, lightness } => match c.kind {
- ChannelKind::Color => hsl_adjust(v, *hue, *saturation, *lightness),
- _ => per_unit(c.kind, v, |x| hsl_adjust([x; 3], 0.0, 0.0, *lightness)[0]),
- },
- // Neighbourhood filters come precomputed through `ChanPlan::start`.
- Filter::Blur { .. } | Filter::Sharpen { .. } => v,
- };
- (mix3(v, out, o), cov)
- }
+ // Neighbourhood filters come precomputed through `ChanPlan::start`.
+ EffectKind::Filter(f) => (f.point(c.kind, v).map_or(v, |out| mix3(v, out, o)), cov),
// Anchors are recorded by `eval`; mask-only effects leave content as it is.
- EffectKind::Anchor | EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection { .. } | EffectKind::Compare { .. } => (v, cov),
+ EffectKind::Anchor | EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection { .. } | EffectKind::Compare { .. } => {
+ (v, cov)
+ }
}
}
}
@@ -1587,11 +1772,8 @@ pub fn flatten_layer(inp: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option<
let nodes = plan(&solo_inp, &[id], &channels, tx, ty, 0, Some(&fields));
let Some(n) = nodes.first() else { return Vec::new() };
let full = anchor_plan(&solo_inp, id, &channels, tx, ty, Some(&fields));
- let mut bufs: Vec<(Channel, Vec, bool)> = n
- .chans
- .iter()
- .filter_map(|c| Channel::ALL.get(c.ch).map(|ch| (*ch, vec![0u16; TILE_AREA * (c.comps + 1)], false)))
- .collect();
+ let mut bufs: Vec<(Channel, Vec, bool)> =
+ n.chans.iter().filter_map(|c| Channel::ALL.get(c.ch).map(|ch| (*ch, vec![0u16; TILE_AREA * (c.comps + 1)], false))).collect();
for (ch, buf, _) in &mut bufs {
if ch.kind() == ChannelKind::Signed {
for px in buf.chunks_exact_mut(2) {
@@ -1652,7 +1834,17 @@ mod tests {
fn run(f: &Fixture, preview: Option<&StrokePreview>) -> Composite {
let images = Default::default();
- let inp = Inputs { project: &f.project, ts: 0, mesh: &f.mesh, gbuf: &f.gbuf, pixels: &f.pixels, baked: &f.baked, preview, images: &images, bounds: f.mesh.bounds() };
+ let inp = Inputs {
+ project: &f.project,
+ ts: 0,
+ mesh: &f.mesh,
+ gbuf: &f.gbuf,
+ pixels: &f.pixels,
+ baked: &f.baked,
+ preview,
+ images: &images,
+ bounds: f.mesh.bounds(),
+ };
let mut out = Composite::new(&f.project.texture_sets[0].channel_list(), 64);
composite_tiles(&inp, &mut out, &all_tiles(64, 64));
out
@@ -1753,7 +1945,10 @@ mod tests {
let mut mask = Mask::new(MaskBackground::Black);
let pattern = Procedural::new(ProceduralKind::Checker);
let (e1, e2) = (f.project.alloc_id(), f.project.alloc_id());
- mask.effects.push(Effect::new(e1, EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() }));
+ mask.effects.push(Effect::new(
+ e1,
+ EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() },
+ ));
f.project.layer_mut(id).unwrap().mask = Some(mask.clone());
let hard: Vec = (0..64).map(|x| run(&f, None).value(Channel::BaseColor, x, 20)[0]).collect();
mask.effects.push(Effect::new(e2, EffectKind::Filter(Filter::Blur { radius: 64.0 })));
@@ -1761,8 +1956,11 @@ mod tests {
let soft_img = run(&f, None);
let soft: Vec = (0..64).map(|x| soft_img.value(Channel::BaseColor, x, 20)[0]).collect();
let mids = |v: &[f32]| v.iter().filter(|x| **x > 0.55 && **x < 0.95).count();
- assert!(mids(&soft) > mids(&hard) + 4, "hard {hard:?}
-soft {soft:?}");
+ assert!(
+ mids(&soft) > mids(&hard) + 4,
+ "hard {hard:?}
+soft {soft:?}"
+ );
}
#[test]
@@ -1866,7 +2064,17 @@ soft {soft:?}");
assert!(close(out.value(Channel::BaseColor, 3, 3), [0.5; 3]), "channels without a source stay untouched");
// Flattening bakes the content effects in.
let images = Default::default();
- let inp = Inputs { project: &f.project, ts: 0, mesh: &f.mesh, gbuf: &f.gbuf, pixels: &f.pixels, baked: &f.baked, preview: None, images: &images, bounds: f.mesh.bounds() };
+ let inp = Inputs {
+ project: &f.project,
+ ts: 0,
+ mesh: &f.mesh,
+ gbuf: &f.gbuf,
+ pixels: &f.pixels,
+ baked: &f.baked,
+ preview: None,
+ images: &images,
+ bounds: f.mesh.bounds(),
+ };
let flat = flatten_layer(&inp, id, &all_tiles(64, 64)).unwrap();
assert!(flat.iter().all(|(c, _, _)| *c == Channel::Roughness));
let (_, _, data) = flat.iter().find(|(_, t, _)| *t == (0, 0)).unwrap();
@@ -1897,6 +2105,48 @@ soft {soft:?}");
assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.5; 3]));
}
+ #[test]
+ fn decal_fills_cover_only_their_frame_and_image_alpha() {
+ let mut f = fixture();
+ let s = f.gbuf.surface(&f.mesh, 32 * 64 + 32).unwrap();
+ let d = texturecraft_core::Decal {
+ center: s.pos.to_array(),
+ normal: s.nrm.to_array(),
+ up: s.nrm.any_orthonormal_vector().to_array(),
+ size: [1.0, 1.0],
+ rotation: 0.0,
+ offset: [0.0; 2],
+ depth: 0.5,
+ };
+ let id = f.project.alloc_id();
+ let mut fill = Fill { projection: Projection::Decal(d), ..Fill::default() };
+ fill.sources.insert(Channel::BaseColor, Source::Image { name: "decal".into() });
+ f.project.insert_layer(0, Layer::new(id, "Decal", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap();
+ let composite = |alpha: f32| {
+ let img = crate::store::ImageRes { width: 2, height: 2, rgba: vec![[1.0, 0.0, 0.0, alpha]; 4], srgb: false };
+ let images: ImageStore = [("decal".to_string(), std::sync::Arc::new(img))].into_iter().collect();
+ let inp = Inputs {
+ project: &f.project,
+ ts: 0,
+ mesh: &f.mesh,
+ gbuf: &f.gbuf,
+ pixels: &f.pixels,
+ baked: &f.baked,
+ preview: None,
+ images: &images,
+ bounds: f.mesh.bounds(),
+ };
+ let mut out = Composite::new(&f.project.texture_sets[0].channel_list(), 64);
+ composite_tiles(&inp, &mut out, &all_tiles(64, 64));
+ out
+ };
+ let out = composite(1.0);
+ assert!(close(out.value(Channel::BaseColor, 32, 32), [1.0, 0.0, 0.0]), "{:?}", out.value(Channel::BaseColor, 32, 32));
+ assert!(close(out.value(Channel::BaseColor, 2, 2), [0.5; 3]), "outside the frame");
+ let half = composite(0.5);
+ assert!(close(half.value(Channel::BaseColor, 32, 32), [0.75, 0.25, 0.25]), "the image alpha shapes the decal");
+ }
+
#[test]
fn anchors_read_colors_as_gray_in_fill_layers() {
let mut f = fixture();
diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs
index 74f80102..e03685b7 100644
--- a/crates/compose/src/pattern.rs
+++ b/crates/compose/src/pattern.rs
@@ -1,6 +1,6 @@
//! Procedural patterns and projections.
-use texturecraft_core::{Procedural, ProceduralKind, Projection};
+use texturecraft_core::{Decal, Procedural, ProceduralKind, Projection};
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_texel::noise;
@@ -199,6 +199,8 @@ pub fn procedural(pr: &Procedural, proj: &Projection, c: &Coords) -> f32 {
let u = b.atan2(a) / std::f32::consts::TAU + 0.5;
raw(pr.kind, Vec3::new(u * 4.0, h, 0.0) * *scale * s, pr.seed)
}
+ // `c.uv` is already in the decal's frame (see [`decal_uv`]).
+ Projection::Decal(_) => raw(pr.kind, (c.uv * s).extend(0.0), pr.seed),
};
shape(pr, v)
}
@@ -244,9 +246,48 @@ pub fn image_samples(proj: &Projection, c: &Coords) -> [(Vec2, f32); 3] {
let u = b.atan2(a) / std::f32::consts::TAU + 0.5;
one(Vec2::new(u, 0.5 - h * 0.5) * *scale)
}
+ Projection::Decal(_) => one(c.uv),
}
}
+/// A decal's frame: origin (center plus offset), unit right, up and normal (None when degenerate).
+pub fn decal_axes(d: &Decal) -> Option<(Vec3, Vec3, Vec3, Vec3)> {
+ if !d.size.iter().all(|v| v.is_finite() && *v > 0.0) {
+ return None;
+ }
+ let n = Vec3::from(d.normal).try_normalize()?;
+ let up0 = (Vec3::from(d.up) - n * n.dot(Vec3::from(d.up))).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector());
+ let right0 = up0.cross(n);
+ let origin = Vec3::from(d.center) + right0 * d.offset[0] + up0 * d.offset[1];
+ let (sn, cs) = d.rotation.to_radians().sin_cos();
+ let right = right0 * cs + up0 * sn;
+ let up = up0 * cs - right0 * sn;
+ origin.is_finite().then_some((origin, right, up, n))
+}
+
+/// The decal's corners in world space (top left, top right, bottom right, bottom left).
+pub fn decal_corners(d: &Decal) -> Option<[Vec3; 4]> {
+ let (o, r, u, _) = decal_axes(d)?;
+ let (hw, hh) = (d.size[0] * 0.5, d.size[1] * 0.5);
+ Some([o - r * hw + u * hh, o + r * hw + u * hh, o + r * hw - u * hh, o - r * hw - u * hh])
+}
+
+/// Where world point `p` with surface normal `nrm` falls in the decal: texture coordinates
+/// (v down) and how much the decal covers it, None outside the frame, behind it, beyond its
+/// depth or on faces turned away. Coverage fades on grazing faces and near the depth limit.
+pub fn decal_uv(d: &Decal, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> {
+ let (o, r, u, n) = decal_axes(d)?;
+ let facing = nrm.dot(n);
+ let q = p - o;
+ let (lx, ly, lz) = (q.dot(r) / d.size[0].max(1e-6), q.dot(u) / d.size[1].max(1e-6), q.dot(n).abs());
+ let depth = d.depth.max(1e-6);
+ if facing <= 0.0 || lx.abs() > 0.5 || ly.abs() > 0.5 || lz > depth || !(lx.is_finite() && ly.is_finite()) {
+ return None;
+ }
+ let w = smoothstep(0.0, 0.3, facing) * (1.0 - smoothstep(0.75 * depth, depth, lz));
+ Some((Vec2::new(lx + 0.5, 0.5 - ly), w))
+}
+
/// World-space noise used by generators (seamless across UV islands).
pub fn world_noise(pos: Vec3, scale: f32, seed: u32) -> f32 {
noise::fbm((pos * scale.max(1e-3)).to_array(), 4, seed, noise::perlin)
@@ -264,6 +305,15 @@ mod tests {
Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3] },
Projection::Spherical { scale: 1.0 },
Projection::Cylindrical { scale: 1.0, axis: 1 },
+ Projection::Decal(Decal {
+ center: [0.0; 3],
+ normal: [0.0, 0.0, 1.0],
+ up: [0.0, 1.0, 0.0],
+ size: [1.0; 2],
+ rotation: 0.0,
+ offset: [0.0; 2],
+ depth: 1.0,
+ }),
];
for k in ProceduralKind::ALL {
let pr = Procedural::new(k);
@@ -282,6 +332,25 @@ mod tests {
}
}
+ #[test]
+ fn decals_cover_their_frame_facing_them() {
+ let d = Decal { center: [0.0; 3], normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], size: [2.0, 1.0], rotation: 0.0, offset: [0.0; 2], depth: 0.5 };
+ let z = Vec3::Z;
+ let (uv, w) = decal_uv(&d, Vec3::new(0.5, 0.25, 0.0), z).unwrap();
+ assert!((uv - Vec2::new(0.75, 0.25)).length() < 1e-5 && (w - 1.0).abs() < 1e-5, "{uv} {w}");
+ assert!(decal_uv(&d, Vec3::new(1.1, 0.0, 0.0), z).is_none(), "outside the frame");
+ assert!(decal_uv(&d, Vec3::ZERO, -z).is_none(), "back faces");
+ assert!(decal_uv(&d, Vec3::new(0.0, 0.0, 0.6), z).is_none(), "beyond the depth");
+ // Rotated a quarter turn and shifted: the frame turns with it.
+ let r = Decal { rotation: 90.0, offset: [1.0, 0.0], ..d };
+ let (uv, _) = decal_uv(&r, Vec3::new(1.0, 0.9, 0.0), z).unwrap();
+ assert!((uv.x - 0.95).abs() < 1e-4 && (uv.y - 0.5).abs() < 1e-4, "{uv}");
+ let c = decal_corners(&d).unwrap();
+ assert!((c[0] - Vec3::new(-1.0, 0.5, 0.0)).length() < 1e-5 && (c[2] - Vec3::new(1.0, -0.5, 0.0)).length() < 1e-5);
+ assert!(decal_axes(&Decal { normal: [0.0; 3], ..d }).is_none());
+ assert!(decal_uv(&Decal { size: [f32::NAN; 2], ..d }, Vec3::ZERO, z).is_none());
+ }
+
#[test]
fn every_pattern_varies() {
for k in ProceduralKind::ALL {
diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs
index 44ef17c2..020a9de0 100644
--- a/crates/compose/tests/cache_and_instances.rs
+++ b/crates/compose/tests/cache_and_instances.rs
@@ -275,7 +275,8 @@ fn nested_stack(f: &mut Fixture) -> Nested {
);
let mask = generator_mask(f, GeneratorKind::Position, None);
let g1 = group(f, None, BlendMode::Normal, 0.8, Some(mask));
- let inner = put(f, 0, Some(g1), fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0)), (Channel::Metallic, Source::Uniform([0.3; 3]))]), None);
+ let inner =
+ put(f, 0, Some(g1), fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0)), (Channel::Metallic, Source::Uniform([0.3; 3]))]), None);
let mut checker = Mask::new(MaskBackground::Black);
checker.effects.push(effect(f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.2, 1.0), projection: Projection::default() }));
let g2 = group(f, Some(g1), BlendMode::Passthrough, 1.0, Some(checker));
@@ -439,3 +440,125 @@ fn edits_off_the_hot_layer_invalidate_and_edits_to_it_do_not() {
paint_rect(&mut f, n.top, (0, 0), (30, 30), 0.9);
assert!(emptied(&f), "pixels above");
}
+
+/// Paint a half-covered rectangle (base color and roughness `v`) into a paint layer stored at
+/// `size` texels.
+fn paint_rect_at(f: &mut Fixture, id: LayerId, size: u32, (x0, y0): (u32, u32), (w, h): (u32, u32), v: f32) {
+ for (ch, px) in [(Channel::BaseColor, vec![to_u16(v * 0.5), to_u16(0.1), 0, to_u16(0.5)]), (Channel::Roughness, vec![to_u16(v * 0.5), to_u16(0.5)])] {
+ let img = f.pixels.layer_mut(id, ch, (size, size));
+ for y in y0..y0 + h {
+ for x in x0..x0 + w {
+ img.set(x, y, &px);
+ }
+ }
+ }
+}
+
+#[test]
+fn instances_resample_sources_painted_at_another_resolution() {
+ let mut f = fixture();
+ let half = RES / 2;
+ f.project.texture_sets[1].resolution = half;
+ // The source lives in set B at half resolution, masked by half-resolution mask pixels.
+ let src = add(&mut f, 1, LayerKind::Paint, None);
+ paint_rect_at(&mut f, src, half, (20, 30), (60, 50), 0.9);
+ let paint = effect(&mut f, EffectKind::Paint);
+ let mask_id = paint.id;
+ f.project.layer_mut(src).unwrap().mask = Some(Mask { effects: vec![paint], ..Mask::new(MaskBackground::Black) });
+ let m = f.pixels.mask_mut(mask_id, (half, half));
+ for y in 0..half {
+ for x in 0..50 {
+ m.set(x, y, &[to_u16(1.0), to_u16(1.0)]);
+ }
+ }
+ add(&mut f, 0, fill(&[(Channel::Metallic, procedural(ProceduralKind::Clouds, 0.0, 1.0))]), None);
+ let inst = add(&mut f, 0, LayerKind::Instance { source: src }, None);
+ let top = add(&mut f, 0, LayerKind::Paint, None);
+ paint_rect(&mut f, top, (0, 0), (40, 40), 0.2);
+ let out = reference(&f, 0);
+ let rough = |x, y| out.value(Channel::Roughness, x, y)[0];
+ // Painted roughness 0.9 at half coverage over the default 0.5, where the mask lets it through.
+ assert!((rough(70, 120) - 0.7).abs() < 2e-3, "inside: {}", rough(70, 120));
+ assert!((rough(180, 120) - 0.5).abs() < 2e-3, "masked out: {}", rough(180, 120));
+ assert!((rough(70, 200) - 0.5).abs() < 2e-3, "not painted: {}", rough(70, 200));
+ for hot in [top, inst] {
+ check_cached(&f, 0, hot);
+ }
+ assert!(!check_cached(&f, 0, top).is_empty());
+}
+
+#[test]
+fn anchors_inside_a_content_stack_record_the_content_up_to_them() {
+ let mut f = fixture();
+ let low = add(&mut f, 0, fill(&[(Channel::Height, Source::Uniform([0.4; 3]))]), None);
+ f.project.layer_mut(low).unwrap().channels.retain(|c, _| *c == Channel::Height);
+ blend(&mut f, low, BlendMode::Normal, 0.5);
+ let (mid, end) = (effect(&mut f, EffectKind::Anchor), effect(&mut f, EffectKind::Anchor));
+ let (mid_id, end_id) = (mid.id, end.id);
+ let mut raise = Fill::default();
+ raise.sources.insert(Channel::Height, Source::Uniform([0.8; 3]));
+ let raise = effect(&mut f, EffectKind::Material(raise));
+ f.project.layer_mut(low).unwrap().content_effects.extend([mid, raise, end]);
+ let top = add(&mut f, 0, LayerKind::Paint, None);
+ paint_rect(&mut f, top, (0, 0), (60, 60), 0.3);
+ // Without readers the stack is cached (anchors are still recorded) and exact.
+ assert!(!check_cached(&f, 0, top).is_empty());
+ // Readers: roughness reads the anchor inside the stack, metallic the one at its end.
+ for (c, anchor) in [(Channel::Roughness, mid_id), (Channel::Metallic, end_id)] {
+ let reader = add(&mut f, 0, fill(&[(c, Source::Anchor { anchor, channel: Channel::Height })]), None);
+ f.project.layer_mut(reader).unwrap().channels.retain(|x, _| *x == c);
+ }
+ let out = reference(&f, 0);
+ let at = |c| out.value(c, 128, 128)[0];
+ // Half opacity over the default height 0: 0.4 before the raise, 0.8 after it.
+ assert!((at(Channel::Roughness) - 0.2).abs() < 2e-3, "inside the stack: {}", at(Channel::Roughness));
+ assert!((at(Channel::Metallic) - 0.4).abs() < 2e-3, "at the end: {}", at(Channel::Metallic));
+ assert!((at(Channel::Height) - 0.4).abs() < 2e-3);
+ assert!(check_cached(&f, 0, top).is_empty(), "anchor readers evaluate everything");
+ // Behind a blur the cut reads the filtered field; before it, the unfiltered content.
+ let blur = effect(&mut f, EffectKind::Filter(Filter::Blur { radius: 30.0 }));
+ f.project.layer_mut(low).unwrap().content_effects.insert(0, blur);
+ let blurred = reference(&f, 0);
+ assert!((blurred.value(Channel::Roughness, 128, 128)[0] - 0.2).abs() < 2e-3, "a flat height stays flat");
+ let mut one_by_one = Composite::new(&f.project.texture_sets[0].channel_list(), RES);
+ let (images, baked) = (Default::default(), Default::default());
+ for t in all_tiles(RES, RES) {
+ composite_tiles(&inputs(&f, 0, &images, &baked), &mut one_by_one, &[t]);
+ }
+ assert!(one_by_one == blurred);
+}
+
+#[test]
+fn gathering_filters_composite_identically_in_any_grouping_and_cached() {
+ let mut f = fixture();
+ let base = add(
+ &mut f,
+ 0,
+ fill(&[(Channel::BaseColor, procedural(ProceduralKind::Clouds, 0.1, 0.9)), (Channel::Roughness, procedural(ProceduralKind::Checker, 0.0, 1.0))]),
+ None,
+ );
+ let mut slope = Mask::new(MaskBackground::Black);
+ slope.effects.push(effect(&mut f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() }));
+ slope.effects.push(effect(&mut f, EffectKind::Filter(Filter::SlopeBlur { radius: 24.0, scale: 3.0, seed: 1 })));
+ let streaks = add(&mut f, 0, fill(&[(Channel::Metallic, procedural(ProceduralKind::Stripes, 0.0, 1.0))]), Some(slope));
+ let top = add(&mut f, 0, LayerKind::Paint, None);
+ paint_rect(&mut f, top, (30, 40), (150, 100), 0.4);
+ let plain = reference(&f, 0);
+ let warp = effect(&mut f, EffectKind::Filter(Filter::Warp { intensity: 30.0, scale: 4.0, seed: 3 }));
+ f.project.layer_mut(base).unwrap().content_effects.push(warp);
+ let line = effect(&mut f, EffectKind::Filter(Filter::DirectionalBlur { radius: 40.0, angle: 30.0 }));
+ f.project.layer_mut(streaks).unwrap().content_effects.push(line);
+ let want = reference(&f, 0);
+ for c in [Channel::BaseColor, Channel::Roughness, Channel::Metallic] {
+ assert!(want.channels[&c] != plain.channels[&c], "{c:?} changed by its filter");
+ }
+ let mut one_by_one = Composite::new(&f.project.texture_sets[0].channel_list(), RES);
+ let (images, baked) = (Default::default(), Default::default());
+ for t in all_tiles(RES, RES) {
+ composite_tiles(&inputs(&f, 0, &images, &baked), &mut one_by_one, &[t]);
+ }
+ assert!(one_by_one == want, "per-tile composites differ from one pass");
+ for hot in [top, streaks] {
+ assert!(!check_cached(&f, 0, hot).is_empty());
+ }
+}
diff --git a/crates/core/src/channel.rs b/crates/core/src/channel.rs
index 972c8e15..eb7b3918 100644
--- a/crates/core/src/channel.rs
+++ b/crates/core/src/channel.rs
@@ -34,6 +34,11 @@ pub enum Channel {
AnisotropyAngle,
/// Subsurface scattering weight (scatter color and radius are project shader settings).
ScatterWeight,
+ /// Transmission: how much of the dielectric base lets light through (refraction at the
+ /// project's IOR, tinted by the base color) instead of reflecting it diffusely.
+ Transmission,
+ /// Tangent-space normal of the clear coat (relative to the mesh normal).
+ CoatNormal,
}
/// How a channel's values are stored and interpreted.
@@ -50,7 +55,7 @@ pub enum ChannelKind {
}
impl Channel {
- pub const ALL: [Channel; 19] = [
+ pub const ALL: [Channel; 21] = [
Channel::BaseColor,
Channel::Metallic,
Channel::Roughness,
@@ -70,11 +75,14 @@ impl Channel {
Channel::AnisotropyLevel,
Channel::AnisotropyAngle,
Channel::ScatterWeight,
+ Channel::Transmission,
+ Channel::CoatNormal,
];
- /// The extra shading lobes (clear coat, sheen, anisotropy, subsurface scattering). Their
- /// defaults switch the lobes off, so a set without them shades exactly as before.
- pub const LOBES: [Channel; 8] = [
+ /// The extra shading lobes (clear coat, sheen, anisotropy, subsurface scattering,
+ /// transmission). Their defaults switch the lobes off, so a set without them shades exactly
+ /// as before.
+ pub const LOBES: [Channel; 10] = [
Channel::CoatWeight,
Channel::CoatRoughness,
Channel::SheenWeight,
@@ -83,6 +91,8 @@ impl Channel {
Channel::AnisotropyLevel,
Channel::AnisotropyAngle,
Channel::ScatterWeight,
+ Channel::Transmission,
+ Channel::CoatNormal,
];
/// The channels of the default "PBR - Metallic Roughness" template.
@@ -91,7 +101,7 @@ impl Channel {
pub fn kind(self) -> ChannelKind {
match self {
Channel::BaseColor | Channel::Emissive | Channel::Specular | Channel::SheenColor => ChannelKind::Color,
- Channel::Normal => ChannelKind::NormalMap,
+ Channel::Normal | Channel::CoatNormal => ChannelKind::NormalMap,
Channel::Height => ChannelKind::Signed,
_ => ChannelKind::Scalar,
}
@@ -110,12 +120,17 @@ impl Channel {
match self {
Channel::BaseColor => [0.5, 0.5, 0.5],
Channel::Metallic | Channel::Height | Channel::Emissive => [0.0; 3],
- Channel::CoatWeight | Channel::SheenWeight | Channel::AnisotropyLevel | Channel::AnisotropyAngle | Channel::ScatterWeight => [0.0; 3],
+ Channel::CoatWeight
+ | Channel::SheenWeight
+ | Channel::AnisotropyLevel
+ | Channel::AnisotropyAngle
+ | Channel::ScatterWeight
+ | Channel::Transmission => [0.0; 3],
Channel::CoatRoughness => [0.1; 3],
Channel::SheenColor => [1.0; 3],
Channel::SheenRoughness => [0.5; 3],
Channel::Roughness => [0.5; 3],
- Channel::Normal => [0.5, 0.5, 1.0],
+ Channel::Normal | Channel::CoatNormal => [0.5, 0.5, 1.0],
Channel::Opacity | Channel::AmbientOcclusion => [1.0; 3],
Channel::SpecularLevel | Channel::Glossiness => [0.5; 3],
// F0 of a common dielectric (4 %).
@@ -144,6 +159,8 @@ impl Channel {
Channel::AnisotropyLevel => "Anisotropy level",
Channel::AnisotropyAngle => "Anisotropy angle",
Channel::ScatterWeight => "Scattering weight",
+ Channel::Transmission => "Transmission",
+ Channel::CoatNormal => "Coat normal",
}
}
@@ -169,6 +186,8 @@ impl Channel {
Channel::AnisotropyLevel => "aniso",
Channel::AnisotropyAngle => "aniso angle",
Channel::ScatterWeight => "scatter",
+ Channel::Transmission => "transm",
+ Channel::CoatNormal => "coat nrm",
}
}
@@ -194,6 +213,8 @@ impl Channel {
Channel::AnisotropyLevel => "anisotropyLevel",
Channel::AnisotropyAngle => "anisotropyAngle",
Channel::ScatterWeight => "scatterWeight",
+ Channel::Transmission => "transmission",
+ Channel::CoatNormal => "coatNormal",
}
}
@@ -274,7 +295,9 @@ mod tests {
}
for c in Channel::LOBES {
assert!(Channel::ALL.contains(&c));
- let off = matches!(c, Channel::CoatRoughness | Channel::SheenColor | Channel::SheenRoughness) || c.default_value() == [0.0; 3];
+ // Tints, roughnesses and the flat coat normal only matter once their lobe has weight.
+ let off =
+ matches!(c, Channel::CoatRoughness | Channel::SheenColor | Channel::SheenRoughness | Channel::CoatNormal) || c.default_value() == [0.0; 3];
assert!(off, "{c:?} must default to an inactive lobe");
}
assert_eq!(Channel::parse("sheen color"), Some(Channel::SheenColor));
diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs
index 916b7cd7..04afca9e 100644
--- a/crates/core/src/layer.rs
+++ b/crates/core/src/layer.rs
@@ -4,7 +4,7 @@ use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
-use crate::{BlendMode, Channel};
+use crate::{BlendMode, Channel, ChannelKind, lum};
/// Id of a layer or effect (one id space per project).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
@@ -152,6 +152,28 @@ pub enum Projection {
Spherical { scale: f32 },
/// Cylindrical projection around an axis.
Cylindrical { scale: f32, axis: u8 },
+ /// A geometry decal: the image projected from a frame placed on the surface (outside the
+ /// frame, behind it or beyond its depth the fill does not cover).
+ Decal(Decal),
+}
+
+/// The frame a decal projects from (world space).
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Decal {
+ /// The surface point the decal was placed on.
+ pub center: [f32; 3],
+ /// The surface normal there: the decal projects along it.
+ pub normal: [f32; 3],
+ /// Up direction of the unrotated frame.
+ pub up: [f32; 3],
+ /// Width and height (world units).
+ pub size: [f32; 2],
+ /// Rotation around the normal (degrees).
+ pub rotation: f32,
+ /// Shift of the frame from `center` along the unrotated right and up directions (world units).
+ pub offset: [f32; 2],
+ /// How far in front of and behind the frame the decal reaches (world units).
+ pub depth: f32,
}
impl Default for Projection {
@@ -168,6 +190,7 @@ impl Projection {
Projection::Planar { .. } => "Planar projection",
Projection::Spherical { .. } => "Spherical projection",
Projection::Cylindrical { .. } => "Cylindrical projection",
+ Projection::Decal(_) => "Decal projection",
}
}
}
@@ -480,6 +503,49 @@ pub enum Filter {
saturation: f32,
lightness: f32,
},
+ /// Contrast around mid gray and a luminosity shift, both −1..1 (0 = unchanged).
+ ContrastLuminosity {
+ contrast: f32,
+ luminosity: f32,
+ },
+ /// Color offsets (−1..1 per component) weighted towards the shadows, midtones and highlights.
+ ColorBalance {
+ shadows: [f32; 3],
+ midtones: [f32; 3],
+ highlights: [f32; 3],
+ },
+ /// Luminance mapped through evenly spaced colors (linear RGB; scalars read their gray).
+ GradientMap {
+ colors: Vec<[f32; 3]>,
+ },
+ /// Quantize to `levels` steps (2..64).
+ Posterize {
+ levels: f32,
+ },
+ /// Keep values within `min..max`.
+ Clamp {
+ min: f32,
+ max: f32,
+ },
+ /// Shift each texel's lookup along a noise vector field: `intensity` in texels at 2K,
+ /// `scale` noise features per UV unit.
+ Warp {
+ intensity: f32,
+ scale: f32,
+ seed: u32,
+ },
+ /// Blur along one direction: `radius` in texels at 2K, `angle` in degrees.
+ DirectionalBlur {
+ radius: f32,
+ angle: f32,
+ },
+ /// Smear values downhill along a noise height field ("slope blur"): `radius` in texels at
+ /// 2K, `scale` noise features per UV unit.
+ SlopeBlur {
+ radius: f32,
+ scale: f32,
+ seed: u32,
+ },
}
/// Push `x` (0..1) towards 1 (`amount` > 0) or 0 (`amount` < 0); `amount` in −1..1.
@@ -530,7 +596,83 @@ pub fn hsl_adjust(rgb: [f32; 3], hue: f32, saturation: f32, lightness: f32) -> [
[hue_to_rgb(p, q, h + 1.0 / 3.0), hue_to_rgb(p, q, h), hue_to_rgb(p, q, h - 1.0 / 3.0)]
}
+/// Apply a 0..1 function to each component of a channel value: signed values map through
+/// 0..1, normals are left alone.
+pub fn per_unit(kind: ChannelKind, v: [f32; 3], f: impl Fn(f32) -> f32) -> [f32; 3] {
+ match kind {
+ ChannelKind::NormalMap => v,
+ // One-component channels hold their value in the first slot (read as gray).
+ ChannelKind::Signed => [f(v[0] * 0.5 + 0.5) * 2.0 - 1.0; 3],
+ ChannelKind::Scalar => [f(v[0]); 3],
+ ChannelKind::Color => v.map(f),
+ }
+}
+
+/// The color at `t` (0..1) of a gradient through evenly spaced `colors` (None when empty).
+pub fn gradient(colors: &[[f32; 3]], t: f32) -> Option<[f32; 3]> {
+ let last = colors.len().checked_sub(1)?;
+ let pos = if t.is_finite() { t.clamp(0.0, 1.0) * last as f32 } else { 0.0 };
+ let i = (pos.floor() as usize).min(last);
+ let (a, b) = (colors.get(i)?, colors.get((i + 1).min(last))?);
+ let f = pos - i as f32;
+ Some(std::array::from_fn(|k| a[k] + (b[k] - a[k]) * f))
+}
+
impl Filter {
+ /// Whether the filter reads neighbouring texels (the compositor runs it over a region).
+ pub fn is_neighbourhood(&self) -> bool {
+ matches!(self, Filter::Blur { .. } | Filter::Sharpen { .. } | Filter::Warp { .. } | Filter::DirectionalBlur { .. } | Filter::SlopeBlur { .. })
+ }
+
+ /// The filter applied to one value of a channel of `kind` (masks are scalars). None for
+ /// neighbourhood filters and where it changes nothing (an empty gradient).
+ pub fn point(&self, kind: ChannelKind, v: [f32; 3]) -> Option<[f32; 3]> {
+ let unit = |x: f32| if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 };
+ Some(match self {
+ Filter::Invert => per_unit(kind, v, |x| 1.0 - x),
+ Filter::Threshold { level } => per_unit(kind, v, |x| if x >= *level { 1.0 } else { 0.0 }),
+ Filter::Hsl { hue, saturation, lightness } => match kind {
+ ChannelKind::Color => hsl_adjust(v, *hue, *saturation, *lightness),
+ _ => per_unit(kind, v, |x| hsl_adjust([x; 3], 0.0, 0.0, *lightness)[0]),
+ },
+ Filter::ContrastLuminosity { contrast, luminosity } => {
+ let k = 1.0 + contrast.clamp(-1.0, 1.0);
+ per_unit(kind, v, |x| unit((x - 0.5) * k + 0.5 + luminosity))
+ }
+ Filter::ColorBalance { shadows, midtones, highlights } => {
+ // Smooth weights summing to 1: shadows fade out and highlights in with lightness.
+ let weights = |l: f32| {
+ let l = unit(l);
+ ((1.0 - l) * (1.0 - l), 2.0 * l * (1.0 - l), l * l)
+ };
+ let shift = |k: usize, l: f32| {
+ let (s, m, h) = weights(l);
+ shadows.get(k).copied().unwrap_or(0.0) * s + midtones.get(k).copied().unwrap_or(0.0) * m + highlights.get(k).copied().unwrap_or(0.0) * h
+ };
+ match kind {
+ ChannelKind::Color => {
+ let l = lum(v);
+ std::array::from_fn(|k| unit(v[k] + shift(k, l)))
+ }
+ _ => per_unit(kind, v, |x| unit(x + (shift(0, x) + shift(1, x) + shift(2, x)) / 3.0)),
+ }
+ }
+ Filter::GradientMap { colors } => match kind {
+ ChannelKind::Color => gradient(colors, lum(v))?,
+ _ => per_unit(kind, v, |x| gradient(colors, x).map_or(x, lum)),
+ },
+ Filter::Posterize { levels } => {
+ let steps = (levels.clamp(2.0, 64.0).round() - 1.0).max(1.0);
+ per_unit(kind, v, |x| (unit(x) * steps).round() / steps)
+ }
+ Filter::Clamp { min, max } => {
+ let (lo, hi) = (min.min(*max), min.max(*max));
+ per_unit(kind, v, |x| x.max(lo).min(hi))
+ }
+ Filter::Blur { .. } | Filter::Sharpen { .. } | Filter::Warp { .. } | Filter::DirectionalBlur { .. } | Filter::SlopeBlur { .. } => return None,
+ })
+ }
+
pub fn label(&self) -> &'static str {
match self {
Filter::Blur { .. } => "Blur",
@@ -538,6 +680,14 @@ impl Filter {
Filter::Invert => "Invert",
Filter::Threshold { .. } => "Threshold",
Filter::Hsl { .. } => "HSL Perceptive",
+ Filter::ContrastLuminosity { .. } => "Contrast/Luminosity",
+ Filter::ColorBalance { .. } => "Color Balance",
+ Filter::GradientMap { .. } => "Gradient Map",
+ Filter::Posterize { .. } => "Posterize",
+ Filter::Clamp { .. } => "Clamp",
+ Filter::Warp { .. } => "Warp",
+ Filter::DirectionalBlur { .. } => "Blur Directional",
+ Filter::SlopeBlur { .. } => "Slope Blur",
}
}
}
@@ -675,6 +825,30 @@ mod tests {
assert!(hsl_adjust([f32::NAN, 2.0, -1.0], f32::NAN, 5.0, -5.0).iter().all(|v| v.is_finite()));
}
+ #[test]
+ fn point_filters_map_values_and_skip_neighbourhood_filters() {
+ let c = ChannelKind::Color;
+ let close = |a: [f32; 3], b: [f32; 3]| (0..3).all(|i| (a[i] - b[i]).abs() < 1e-4);
+ let cl = Filter::ContrastLuminosity { contrast: 1.0, luminosity: 0.0 };
+ assert!(close(cl.point(c, [0.25, 0.5, 0.75]).unwrap(), [0.0, 0.5, 1.0]));
+ assert!(close(Filter::ContrastLuminosity { contrast: 0.0, luminosity: 0.2 }.point(ChannelKind::Scalar, [0.5; 3]).unwrap(), [0.7; 3]));
+ let gm = Filter::GradientMap { colors: vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]] };
+ assert!(close(gm.point(c, [0.0; 3]).unwrap(), [1.0, 0.0, 0.0]));
+ assert!(close(gm.point(c, [1.0; 3]).unwrap(), [0.0, 0.0, 1.0]));
+ 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 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]));
+ assert_eq!(Filter::Invert.point(ChannelKind::NormalMap, [0.5, 0.5, 1.0]), Some([0.5, 0.5, 1.0]));
+ for f in [Filter::Blur { radius: 1.0 }, Filter::Warp { intensity: 1.0, scale: 1.0, seed: 0 }, Filter::DirectionalBlur { radius: 1.0, angle: 0.0 }] {
+ assert!(f.is_neighbourhood() && f.point(c, [0.5; 3]).is_none());
+ }
+ let nan = Filter::ContrastLuminosity { contrast: f32::NAN, luminosity: f32::NAN };
+ assert!(nan.point(c, [0.5; 3]).unwrap().iter().all(|v| v.is_finite()));
+ }
+
#[test]
fn effect_targets_and_anchor_reads() {
assert_eq!(EffectKind::Anchor.content_only(), Some(true));
@@ -683,7 +857,10 @@ mod tests {
let mut l = Layer::new(LayerId(1), "l", LayerKind::Paint, &[Channel::BaseColor]);
assert!(!l.reads_anchor());
let source = Source::Anchor { anchor: LayerId(9), channel: Channel::Height };
- l.mask = Some(Mask { effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default() })], ..Mask::new(MaskBackground::Black) });
+ l.mask = Some(Mask {
+ effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default() })],
+ ..Mask::new(MaskBackground::Black)
+ });
assert!(l.reads_anchor());
}
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index 04d09dd4..506a4650 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -15,10 +15,10 @@ pub mod project;
pub use blend::{BlendMode, blend1, blend3, lum, mix3};
pub use channel::{Channel, ChannelFormat, ChannelKind};
pub use layer::{
- ChannelBlend, CompareOp, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, Mask, MaskBackground, Procedural,
- ProceduralKind, Projection, Source, hsl_adjust,
+ ChannelBlend, CompareOp, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, Mask, MaskBackground,
+ Procedural, ProceduralKind, Projection, Source, gradient, hsl_adjust, per_unit,
};
-pub use project::{AoMixing, BakeMatch, BakeSettings, BakedMap, DisplaySettings, FORMAT_VERSION, NormalFormat, NormalMixing, Project, TextureSet, TileGrid, ToneMapping, UDIM_RANGE};
+pub use project::{AoMixing, BakeMatch, BakeSettings, BakedMap, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, NormalFormat, NormalMixing, Project, TextureSet, TileGrid, ToneMapping, UDIM_RANGE};
#[derive(Debug, thiserror::Error, Clone, PartialEq)]
pub enum CoreError {
diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs
index 63dc6b42..5ead726b 100644
--- a/crates/core/src/project.rs
+++ b/crates/core/src/project.rs
@@ -379,6 +379,52 @@ pub struct DisplaySettings {
pub scatter_color: [f32; 3],
/// Subsurface scattering mean free path as a fraction of the mesh's bounding radius.
pub scatter_radius: f32,
+ /// Index of refraction of transmissive surfaces (where the Transmission channel is painted).
+ pub ior: f32,
+ /// Depth of field of the viewport and the path tracer (thin lens).
+ pub dof: DepthOfField,
+}
+
+/// A thin-lens camera's depth of field (Painter's Display settings: focus distance and aperture).
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct DepthOfField {
+ pub enabled: bool,
+ /// Distance of the plane in focus along the view axis (world units); 0 focuses on the
+ /// camera's orbit target.
+ pub focus_distance: f32,
+ /// Lens radius as a fraction of the mesh's bounding radius: how fast the blur grows away
+ /// from the focus plane.
+ pub aperture: f32,
+}
+
+impl Default for DepthOfField {
+ fn default() -> Self {
+ DepthOfField { enabled: false, focus_distance: 0.0, aperture: 0.05 }
+ }
+}
+
+/// A saved viewpoint of the camera list (the default camera's orbit parameters, as in
+/// `geom::OrbitCamera`): saved views and cameras imported with the mesh.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct Camera {
+ pub name: String,
+ pub target: [f32; 3],
+ /// Radians around +Y.
+ pub yaw: f32,
+ /// Radians above the horizon.
+ pub pitch: f32,
+ pub distance: f32,
+ /// Vertical field of view, degrees (orthographic: the view height at `distance`).
+ pub fov: f32,
+ pub ortho: bool,
+}
+
+impl Default for Camera {
+ fn default() -> Self {
+ Camera { name: "Camera".into(), target: [0.0; 3], yaw: 0.0, pitch: 0.0, distance: 5.0, fov: 40.0, ortho: false }
+ }
}
/// Prefix of [`DisplaySettings::environment`] naming an image resource.
@@ -413,6 +459,8 @@ impl Default for DisplaySettings {
parallax: false,
scatter_color: [1.0, 0.4, 0.25],
scatter_radius: 0.1,
+ ior: 1.5,
+ dof: DepthOfField::default(),
}
}
}
@@ -428,6 +476,9 @@ pub struct Project {
pub layers: BTreeMap,
pub next_id: u64,
pub display: DisplaySettings,
+ /// Saved and imported cameras (the viewport's default camera is not in the list).
+ #[serde(default)]
+ pub cameras: Vec,
}
impl Project {
@@ -441,6 +492,7 @@ impl Project {
layers: BTreeMap::new(),
next_id: 1,
display: DisplaySettings::default(),
+ cameras: Vec::new(),
}
}
diff --git a/crates/engine/src/camera_cmds.rs b/crates/engine/src/camera_cmds.rs
new file mode 100644
index 00000000..ebedab77
--- /dev/null
+++ b/crates/engine/src/camera_cmds.rs
@@ -0,0 +1,235 @@
+//! The camera list (Painter's viewport camera menu: the default camera plus saved and imported
+//! cameras, saved with the project) and the depth of field focus pick.
+
+use serde_json::{Value, json};
+use texturecraft_core::Camera;
+use texturecraft_geom::OrbitCamera;
+use texturecraft_geom::glam::{Vec2, Vec3};
+
+use crate::commands::{CommandSpec, always, bad, f32p, strp, u64p};
+use crate::tool_cmds::viewport_of;
+use crate::{Result, Session, cmd};
+
+/// Name of the viewport's own camera in the camera menu (it is not in the list).
+pub const DEFAULT_CAMERA: &str = "Default camera";
+
+pub fn specs() -> Vec {
+ vec![
+ cmd!("camera.list", "Cameras", [], None, "{}", always, |s, _| Ok(list(s))),
+ cmd!("camera.add", "Save view as camera", [], None, "{name?}", always, add),
+ cmd!(
+ "camera.select",
+ "Select camera",
+ [],
+ None,
+ "{index? | name?} (neither, or name \"Default camera\": the default camera framing the mesh)",
+ always,
+ select
+ ),
+ cmd!("camera.remove", "Remove camera", [], None, "{index? | name?}", has_cameras, remove),
+ cmd!("camera.rename", "Rename camera", [], None, "{index? | name?, to}", has_cameras, rename),
+ cmd!("viewport.focusAt", "Focus depth of field here", [], None, "{x, y (viewport pixels), viewport?: [w, h]}", always, focus_at),
+ ]
+}
+
+fn has_cameras(s: &Session) -> std::result::Result<(), String> {
+ if s.doc.project.cameras.is_empty() { Err("the project has no saved cameras".into()) } else { Ok(()) }
+}
+
+/// The view as a saved camera.
+fn saved(c: &OrbitCamera, name: String) -> Camera {
+ Camera { name, target: c.target.to_array(), yaw: c.yaw, pitch: c.pitch, distance: c.distance, fov: c.fov, ortho: c.ortho }
+}
+
+/// Move the view to saved camera `c` (values from project files are checked and clamped).
+fn apply(view: &mut OrbitCamera, c: &Camera) {
+ let target = Vec3::from(c.target);
+ if target.is_finite() {
+ view.target = target;
+ }
+ let r = view.scene_radius.max(1e-3);
+ let ok = |v: f32| v.is_finite().then_some(v);
+ view.yaw = ok(c.yaw).unwrap_or(view.yaw);
+ view.pitch = ok(c.pitch).map_or(view.pitch, |p| p.clamp(-89f32.to_radians(), 89f32.to_radians()));
+ view.distance = ok(c.distance).map_or(view.distance, |d| d.clamp(r * 0.05, r * 200.0));
+ view.fov = ok(c.fov).map_or(view.fov, |f| f.clamp(5.0, 150.0));
+ view.ortho = c.ortho;
+}
+
+/// The saved camera the view is at, if any.
+pub fn current(s: &Session) -> Option {
+ let mut view = s.camera;
+ s.doc.project.cameras.iter().position(|c| {
+ apply(&mut view, c);
+ let close = |a: f32, b: f32| (a - b).abs() <= 1e-4 * (1.0 + a.abs());
+ (view.target - s.camera.target).length() <= 1e-4 * (1.0 + view.distance)
+ && close(view.yaw, s.camera.yaw)
+ && close(view.pitch, s.camera.pitch)
+ && close(view.distance, s.camera.distance)
+ && close(view.fov, s.camera.fov)
+ && view.ortho == s.camera.ortho
+ })
+}
+
+fn list(s: &Session) -> Value {
+ let cams: Vec = s
+ .doc
+ .project
+ .cameras
+ .iter()
+ .enumerate()
+ .map(|(i, c)| {
+ json!({
+ "index": i, "name": c.name, "fov": c.fov, "ortho": c.ortho, "distance": c.distance,
+ "yaw": c.yaw.to_degrees(), "pitch": c.pitch.to_degrees(), "target": c.target,
+ })
+ })
+ .collect();
+ json!({ "cameras": cams, "current": current(s) })
+}
+
+/// The camera `index` or `name` of params `p` points at.
+fn which(s: &Session, cmd: &str, p: &Value) -> Result {
+ let cams = &s.doc.project.cameras;
+ let found = match (u64p(p, "index"), strp(p, "name")) {
+ (Some(i), _) => usize::try_from(i).ok().filter(|i| *i < cams.len()),
+ (None, Some(n)) => cams.iter().position(|c| c.name == n),
+ (None, None) => return Err(bad(cmd, "give `index` or `name`")),
+ };
+ found.ok_or_else(|| bad(cmd, "no such camera (see camera.list)"))
+}
+
+fn unique_name(s: &Session, base: &str) -> String {
+ let taken = |n: &str| n == DEFAULT_CAMERA || s.doc.project.cameras.iter().any(|c| c.name == n);
+ if !taken(base) {
+ return base.to_string();
+ }
+ (2..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_default()
+}
+
+fn add(s: &mut Session, p: &Value) -> Result {
+ let base = strp(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Camera");
+ let name = unique_name(s, base);
+ let cam = saved(&s.camera, name.clone());
+ s.edit("Save camera", |s| {
+ s.doc.project.cameras.push(cam);
+ Ok(json!({ "index": s.doc.project.cameras.len() - 1, "name": name }))
+ })
+}
+
+fn select(s: &mut Session, p: &Value) -> Result {
+ if u64p(p, "index").is_none() && strp(p, "name").is_none_or(|n| n == DEFAULT_CAMERA) {
+ // The default camera: fov and projection from the display settings, framing the mesh.
+ s.camera.fov = s.doc.project.display.fov;
+ s.camera.ortho = false;
+ return crate::execute(s, "viewport.frame", &Value::Null);
+ }
+ let i = which(s, "camera.select", p)?;
+ if let Some(c) = s.doc.project.cameras.get(i).cloned() {
+ apply(&mut s.camera, &c);
+ }
+ s.revision = s.revision.wrapping_add(1);
+ Ok(crate::view_cmds::camera_json(s))
+}
+
+fn remove(s: &mut Session, p: &Value) -> Result {
+ let i = which(s, "camera.remove", p)?;
+ s.edit("Remove camera", |s| {
+ let c = s.doc.project.cameras.remove(i);
+ Ok(json!({ "removed": c.name }))
+ })
+}
+
+fn rename(s: &mut Session, p: &Value) -> Result {
+ let i = which(s, "camera.rename", p)?;
+ let to = strp(p, "to").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("camera.rename", "`to` (the new name) is required"))?;
+ if s.doc.project.cameras.get(i).is_some_and(|c| c.name == to) {
+ return Ok(json!({ "index": i, "name": to }));
+ }
+ let name = unique_name(s, to);
+ s.edit("Rename camera", |s| {
+ if let Some(c) = s.doc.project.cameras.get_mut(i) {
+ c.name = name.clone();
+ }
+ Ok(json!({ "index": i, "name": name }))
+ })
+}
+
+/// Focus the depth of field on the mesh under viewport pixel (x, y).
+fn focus_at(s: &mut Session, p: &Value) -> Result {
+ let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("viewport.focusAt", "`x` and `y` (viewport pixels) are required")) };
+ let vp = viewport_of(s, p);
+ let hit = s.pick(Vec2::new(x, y), vp).ok_or_else(|| bad("viewport.focusAt", "no mesh under that point"))?;
+ let depth = (hit.pos - s.camera.eye()).dot(s.camera.forward()).max(1e-4);
+ s.doc.project.display.dof.focus_distance = depth;
+ s.revision = s.revision.wrapping_add(1);
+ Ok(json!({ "focusDistance": depth }))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::execute;
+
+ fn session() -> Session {
+ Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:sphere", None, 128).unwrap()
+ }
+
+ #[test]
+ fn cameras_add_select_rename_remove_and_undo() {
+ let mut s = session();
+ let home = s.camera;
+ assert_eq!(execute(&mut s, "camera.list", &Value::Null).unwrap()["current"], Value::Null);
+ execute(&mut s, "camera.set", &json!({"yaw": 30, "pitch": 10, "fov": 25, "ortho": true})).unwrap();
+ let side = s.camera;
+ assert_eq!(execute(&mut s, "camera.add", &json!({"name": "Side"})).unwrap()["index"], 0);
+ assert_eq!(execute(&mut s, "camera.add", &json!({"name": "Side"})).unwrap()["name"], "Side 2", "names stay unique");
+ assert_eq!(execute(&mut s, "camera.list", &Value::Null).unwrap()["current"], 0);
+ execute(&mut s, "camera.select", &json!({})).unwrap();
+ assert!(!s.camera.ortho && s.camera.fov == s.doc.project.display.fov, "the default camera");
+ assert_eq!((s.camera.yaw, s.camera.target), (side.yaw, home.target), "framing the mesh, keeping the angles");
+ execute(&mut s, "camera.orbit", &json!({"dx": 40})).unwrap();
+ execute(&mut s, "camera.select", &json!({"name": "Side"})).unwrap();
+ assert_eq!(s.camera, side, "selecting brings back the saved view, fov and projection");
+ execute(&mut s, "camera.rename", &json!({"index": 1, "to": "Top"})).unwrap();
+ execute(&mut s, "camera.remove", &json!({"name": "Side"})).unwrap();
+ let list = execute(&mut s, "camera.list", &Value::Null).unwrap();
+ assert_eq!(list["cameras"].as_array().unwrap().len(), 1);
+ assert_eq!(list["cameras"][0]["name"], "Top");
+ assert!(execute(&mut s, "camera.select", &json!({"index": 5})).is_err());
+ assert!(execute(&mut s, "camera.rename", &json!({"index": 0})).is_err(), "`to` is required");
+ execute(&mut s, "edit.undo", &Value::Null).unwrap();
+ assert_eq!(s.doc.project.cameras.len(), 2, "removing is undoable");
+ }
+
+ #[test]
+ fn cameras_round_trip_through_the_project_file() {
+ let mut s = session();
+ execute(&mut s, "camera.set", &json!({"yaw": -20, "fov": 60})).unwrap();
+ execute(&mut s, "camera.add", &json!({"name": "Hero"})).unwrap();
+ execute(&mut s, "display.set", &json!({"dof": {"enabled": true, "focusDistance": 3.5, "aperture": 0.2}, "ior": 1.33})).unwrap();
+ let bytes = texturecraft_formats::save_project_bytes(&s.project_file()).unwrap();
+ let back = Session::from_project_bytes(&bytes).unwrap();
+ assert_eq!(back.doc.project.cameras, s.doc.project.cameras);
+ assert_eq!(back.doc.project.display.dof, s.doc.project.display.dof);
+ assert_eq!(back.doc.project.display.ior, 1.33);
+ // Projects saved before cameras and depth of field existed load with the defaults.
+ let mut v = serde_json::to_value(&s.doc.project).unwrap();
+ v.as_object_mut().unwrap().remove("cameras");
+ v["display"].as_object_mut().unwrap().remove("dof");
+ let old: texturecraft_core::Project = serde_json::from_value(v).unwrap();
+ assert!(old.cameras.is_empty() && !old.display.dof.enabled);
+ }
+
+ #[test]
+ fn focus_at_picks_the_depth_under_the_cursor() {
+ let mut s = session();
+ let vp = s.viewport;
+ let r = execute(&mut s, "viewport.focusAt", &json!({"x": vp.x / 2.0, "y": vp.y / 2.0})).unwrap();
+ let d = r["focusDistance"].as_f64().unwrap() as f32;
+ // The front of the unit sphere, one radius before the orbit target.
+ assert!((d - (s.camera.distance - 1.0)).abs() < 0.05, "{d} vs {}", s.camera.distance);
+ assert_eq!(s.doc.project.display.dof.focus_distance, d);
+ assert!(execute(&mut s, "viewport.focusAt", &json!({"x": 1, "y": 1})).is_err(), "nothing under the corner");
+ }
+}
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 17901b22..f2a330d3 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -59,6 +59,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::tool_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::project_cmds::specs());
@@ -68,6 +69,8 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::resource_cmds::specs());
v.extend(crate::material_lib::specs());
v.extend(crate::smart_masks::specs());
+ v.extend(crate::filter_lib::specs());
+ v.extend(crate::decal_cmds::specs());
v
})
}
@@ -159,7 +162,12 @@ pub(crate) fn blend_param(cmd: &str, p: &Value, key: &str) -> Result