Auto: Integrate main and fix project creation and resource imports

Preserve main's empty startup and project-bound dialog behavior. Check for unsaved edits at Create, reject stale mesh picks, and release closed forms' mesh buffers. Transfer the desktop mesh input into the new session after validation.

Retain failed import rows for retry, keep duplicate names within the archive limit, and preserve the active brush alpha during unused-resource cleanup. Remove repeated row scans and idle UV-tooltip formatting, and keep baked-map filenames visible on separate rows.
This commit is contained in:
chasse20 committed 2026-11-18 17:12:29 +00:00
commit 9feb78523a
234 files changed
+21099 -2050

No files matched your search

Generated
+4 -3
View File
@@ -851,10 +851,11 @@ dependencies = [
[[package]]
name = "craft-mesh"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52#b952ca0231867c8ad6749ac44cab5fc903c3ad52"
source = "git+https://github.com/storytold/craft-libs?rev=70e562aa88436b6b79a997215b4fa4f6a6b1838a#70e562aa88436b6b79a997215b4fa4f6a6b1838a"
dependencies = [
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52)",
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=70e562aa88436b6b79a997215b4fa4f6a6b1838a)",
"miniz_oxide 0.9.1",
"serde_json",
]
[[package]]
@@ -970,7 +971,7 @@ dependencies = [
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52#b952ca0231867c8ad6749ac44cab5fc903c3ad52"
source = "git+https://github.com/storytold/craft-libs?rev=70e562aa88436b6b79a997215b4fa4f6a6b1838a#70e562aa88436b6b79a997215b4fa4f6a6b1838a"
dependencies = [
"flate2",
"thiserror 2.0.21",
+1 -1
View File
@@ -73,7 +73,7 @@ craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "c376774
# Isolated aligned writer; existing archive readers retain their pin and behavior.
craft-zip-usdz = { package = "craft-zip", git = "https://github.com/storytold/craft-libs", rev = "5631e99fe126cffb74c673eb458db04299f2bb9b" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" }
craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "b952ca0231867c8ad6749ac44cab5fc903c3ad52", default-features = false, features = ["stl", "ply", "fbx", "obj"] }
craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "70e562aa88436b6b79a997215b4fa4f6a6b1838a", default-features = false, features = ["stl", "ply", "fbx", "obj", "gltf"] }
craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" }
# Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs).
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] }
+3 -3
View File
@@ -146,7 +146,7 @@ The full list of what's in it is in [`docs/features.md`](docs/features.md).
git clone https://github.com/storytold/texturecraft
cd texturecraft
cargo run --release -p texturecraft # desktop app (opens a sample project)
cargo run --release -p texturecraft # desktop app (starts with no project)
cargo run --release -p texturecraft -- model.glb # a new project from a mesh
cargo run --release -p texturecraft -- --control 7878 # + JSON control channel
cargo run --release -p texturecraft-cli -- mcp # MCP server (stdio)
@@ -157,8 +157,8 @@ cd apps/texturecraft-web && trunk serve # web build
cargo xtask ci # fmt, clippy, tests, layering, wasm
```
You need Rust 1.95 or newer. The app opens with a baked sample project and a start window (new project, open, recent projects); **File ▸ New project** starts
from your own mesh file and a project template (UVs are generated if it has none).
You need Rust 1.95 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one, and **File ▸ Close** returns to the empty state).
**File ▸ New project** starts from your own mesh file and a project template. TextureCraft generates UVs if the mesh has none.
Japanese, Chinese, Korean and Arabic interface text uses the fonts of
[storytold/craft-fonts](https://github.com/storytold/craft-fonts) where it has them, an optional
+6 -16
View File
@@ -40,9 +40,11 @@ pub fn start() {
}
async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> {
// The WebAssembly has downloaded and compiled when this runs.
step(0.5, "Preparing the sample project…").await;
let session = initial_session()?;
// The WebAssembly has downloaded and compiled when this runs
step(0.5, "Preparing the app…").await;
// The app starts with no project, like File > Close
let session = Session::closed().map_err(|e| e.to_string())?;
step(0.8, "Starting the renderer…").await;
let mut options = eframe::WebOptions::default();
if query().contains("webgl")
@@ -50,13 +52,13 @@ async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> {
{
create.instance_descriptor.backends = eframe::wgpu::Backends::GL;
}
eframe::WebRunner::new()
.start(
canvas,
options,
Box::new(|cc| {
let mut app = TextureCraftApp::new(cc, session);
app.ui.windows.start = app.ui.prefs.start_window;
if let Some(rs) = &cc.wgpu_render_state {
let backend = rs.adapter.get_info().backend;
log::info!("TextureCraft: wgpu backend {backend:?}");
@@ -137,18 +139,6 @@ fn guard_unsaved_changes() {
on_unload.forget();
}
/// The baked sample project, or an empty material ball if that fails. Texture and bake sizes are
/// kept small: the web build composites and bakes on one thread (bake 256 took ~12 s to start on a
/// fast desktop CPU, 128 ~7.5 s).
fn initial_session() -> Result<Session, String> {
texturecraft_engine::sample_session(1024, 128)
.or_else(|e| {
log::warn!("sample project failed: {e}");
Session::new_project("Untitled", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 1024)
})
.map_err(|e| e.to_string())
}
fn query() -> String {
web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default()
}
+35 -21
View File
@@ -38,6 +38,7 @@ fn version() -> String {
struct Args {
file: Option<String>,
control: Option<u16>,
/// With `--control`: start with an empty material ball instead of the sample project
empty: bool,
gpu: Option<String>,
power_pref: Option<eframe::wgpu::PowerPreference>,
@@ -84,21 +85,34 @@ fn parse_args_from<I: IntoIterator<Item = String>>(it: I) -> Result<Option<Args>
}
fn initial_session(args: &Args) -> Session {
if let Some(f) = &args.file {
match texturecraft_engine::file_cmds::open_path(f) {
Ok(s) => return s,
Err(e) => eprintln!("texturecraft: could not open {f}: {e}"),
if let Some(path) = &args.file {
match texturecraft_engine::file_cmds::open_path(path) {
Ok(session) => return session,
Err(error) => eprintln!("texturecraft: could not open {path}: {error}"),
}
}
if !args.empty
&& let Ok(s) = texturecraft_engine::sample_session(2048, 512)
{
return s;
// Control runs retain their sample project; interactive runs start empty
if args.control.is_some() {
if !args.empty
&& let Ok(session) = texturecraft_engine::sample_session(2048, 512)
{
return session;
}
return match Session::new_project("Untitled", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 2048) {
Ok(session) => session,
Err(error) => {
eprintln!("texturecraft: {error}");
std::process::exit(1);
}
};
}
match Session::new_project("Untitled", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 2048) {
Ok(s) => s,
Err(e) => {
eprintln!("texturecraft: {e}");
match Session::closed() {
Ok(session) => session,
Err(error) => {
eprintln!("texturecraft: {error}");
std::process::exit(1);
}
}
@@ -176,7 +190,7 @@ fn checks_for_updates_at_start(control: Option<u16>) -> bool {
}
fn main() {
// Windows: the update helper is a copy of this program started with `--finish-update`.
// Windows: the update helper is a copy of this program started with `--finish-update`
#[cfg(windows)]
if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
std::process::exit(i32::from(result.is_err()));
@@ -189,14 +203,16 @@ fn main() {
std::process::exit(2);
}
};
// Errors before the window opens speak the system's language; the app then applies the saved one
texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language());
let prev = std::panic::take_hook();
let previous_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
// A message box needs the main thread on macOS; other threads' panics are only logged
fatal(&format!("internal error: {info}"), std::thread::current().name() == Some("main"));
prev(info);
previous_hook(info);
}));
// Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS to keep the user's saved settings untouched: state goes to throwaway files
let persistence_path =
std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id())));
@@ -220,9 +236,7 @@ fn main() {
std::process::exit(2);
}
let control = args.control;
// The start window offers new, open and recent projects, unless a file was given or a script drives the app
let start = args.file.is_none() && control.is_none();
let r = eframe::run_native(
let result = eframe::run_native(
APP_NAME,
options,
Box::new(move |cc| {
@@ -230,7 +244,8 @@ fn main() {
if let Some(w) = cc.winit_window() {
set_taskbar_icon(w);
}
// winit's Quit ends the process without asking; this menu's asks like the close button.
// winit's Quit ends the process without asking; this menu's asks like the close button
#[cfg(target_os = "macos")]
if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, APP_NAME) {
log::warn!("the app menu could not be installed: {e}");
@@ -238,7 +253,6 @@ fn main() {
let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_)));
let mut app = TextureCraftApp::new(cc, session);
app.title_bar = title_bar;
app.ui.windows.start = start && app.ui.prefs.start_window;
app.set_startup_update_check(checks_for_updates_at_start(control));
if let Some(port) = control {
app.control = Some(control_server::start(port, cc.egui_ctx.clone()));
@@ -251,7 +265,7 @@ fn main() {
}))
}),
);
if let Err(e) = r {
if let Err(e) = result {
fatal(&e.to_string(), true);
std::process::exit(1);
}
+56 -17
View File
@@ -101,6 +101,11 @@ impl Headless {
matches!(self.fs, Filesystem::TrustedLocal)
}
/// Commands that act on the project refuse after `file.close`, as in the app
fn require_project(&self) -> Result<(), AutomationError> {
if self.session.project_open { Ok(()) } else { Err(bad("no project is open")) }
}
fn read(&self, path: &str) -> Result<Vec<u8>, AutomationError> {
match &self.fs {
Filesystem::Denied => Err(bad("file access is not granted: start the server with --read-root <dir>")),
@@ -205,12 +210,15 @@ impl Headless {
/// Add a high-definition mesh for baking from `path` (or, with `cage`, set the bake cage).
pub fn add_bake_mesh(&mut self, path: &str, cage: bool) -> Result<Value, AutomationError> {
self.require_project()?;
let f = self.read_mesh(path)?;
Ok(self.session.add_bake_mesh(f, cage)?)
}
/// Reimport the mesh from `path`, or from the project's own copy, keeping the project.
pub fn reimport_mesh(&mut self, path: Option<&str>, preserve_strokes: bool) -> Result<Value, AutomationError> {
self.require_project()?;
let file = path.map(|p| self.read_mesh(p)).transpose()?;
Ok(self.session.reimport_mesh(file, preserve_strokes)?)
}
@@ -218,6 +226,7 @@ impl Headless {
/// Export the working mesh to `path` (obj, glb, usda, usdc or usdz, from `format` or the
/// extension); obj writes its .mtl and textures, usda and usdc their textures, next to it.
pub fn export_mesh(&mut self, path: &str, format: Option<&str>) -> Result<Value, AutomationError> {
self.require_project()?;
let out = self.session.mesh_export(path, format)?;
let dir = Path::new(&out.path).parent().and_then(|d| d.to_str()).filter(|d| !d.is_empty()).unwrap_or(".");
self.create_dir_all(dir)?;
@@ -233,12 +242,14 @@ impl Headless {
/// Import an image file as a project resource (for `layer.add.image`, `tool.stencil`).
pub fn import_resource(&mut self, path: &str) -> Result<Value, AutomationError> {
self.require_project()?;
let bytes = self.read(path)?;
Ok(json!({ "name": self.session.import_resource_bytes(path, bytes)? }))
}
/// Save a layer (default: the selected one) as a smart material file (`.tcmat`).
pub fn material_save(&mut self, p: &Value) -> Result<Value, AutomationError> {
self.require_project()?;
let path = p.get("path").and_then(Value::as_str).ok_or_else(|| bad("`path` is required"))?;
let s = &self.session;
let id = match p.get("layer").and_then(Value::as_u64) {
@@ -258,12 +269,14 @@ impl Headless {
/// Add a smart material from a `.tcmat` file above the selection.
pub fn material_load(&mut self, path: &str) -> Result<Value, AutomationError> {
self.require_project()?;
let bytes = self.read(path)?;
Ok(json!({ "layer": self.session.add_smart_material_bytes(&bytes)?.0 }))
}
/// Save as `.tcraft` to `path`, or to the project's own file.
pub fn save(&mut self, path: Option<&str>) -> Result<Value, AutomationError> {
self.require_project()?;
let target = match path.or(self.session.path.as_deref()) {
Some(p) if ext_of(p) == PROJECT_EXT => p.to_string(),
Some(p) => format!("{p}.{PROJECT_EXT}"),
@@ -277,6 +290,7 @@ impl Headless {
/// Export textures to `dir` (`file.exportTextures` params: preset, ts, format, padding, size…).
pub fn export(&mut self, p: &Value) -> Result<Value, AutomationError> {
self.require_project()?;
let dir = p.get("dir").and_then(Value::as_str).filter(|d| !d.is_empty()).ok_or_else(|| bad("`dir` is required"))?;
let opts = file_cmds::export_options(&self.session, p, "textures.export")?;
let n = self.session.set_count();
@@ -299,39 +313,43 @@ impl Headless {
/// 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<Rendered, AutomationError> {
let s = &self.session;
let kind = match o.view.as_deref().unwrap_or("3d") {
pub fn render_png(&mut self, options: &RenderOptions) -> Result<Rendered, AutomationError> {
self.require_project()?;
let session = &self.session;
let kind = match options.view.as_deref().unwrap_or("3d") {
"3d" => ViewKind::Scene,
"2d" | "uv" => ViewKind::Uv { ts: s.ts(), zoom: 1.0, pan: [0.0, 0.0] },
"2d" | "uv" => ViewKind::Uv { ts: session.ts(), zoom: 1.0, pan: [0.0, 0.0] },
other => return Err(bad(format!("unknown view `{other}` (3d, 2d or uv)"))),
};
let max = if self.trusted() { MAX_LOCAL_RENDER_SIDE } else { MAX_PNG_SIDE };
let side = |v: Option<u32>, d: f32| {
let max_side = if self.trusted() { MAX_LOCAL_RENDER_SIDE } else { MAX_PNG_SIDE };
let checked_side = |v: Option<u32>, d: f32| {
let v = v.unwrap_or(d.round() as u32);
if (16..=max).contains(&v) { Ok(v) } else { Err(bad(format!("render size {v} must be 16 to {max} pixels"))) }
if (16..=max_side).contains(&v) { Ok(v) } else { Err(bad(format!("render size {v} must be 16 to {max_side} pixels"))) }
};
let size = [side(o.width, s.viewport.x)?, side(o.height, s.viewport.y)?];
let mut camera = s.camera;
for (v, slot, lim) in [(o.yaw, &mut camera.yaw, 1e6), (o.pitch, &mut camera.pitch, 89.0)] {
let size = [checked_side(options.width, session.viewport.x)?, checked_side(options.height, session.viewport.y)?];
let mut camera = session.camera;
for (v, slot, max_degrees) in [(options.yaw, &mut camera.yaw, 1e6), (options.pitch, &mut camera.pitch, 89.0)] {
if let Some(v) = v {
if !v.is_finite() {
return Err(bad("camera angles must be finite"));
}
*slot = v.clamp(-lim, lim).to_radians();
*slot = v.clamp(-max_degrees, max_degrees).to_radians();
}
}
if let Some(samples) = o.samples {
if !(1..=MAX_TRACE_SAMPLES).contains(&samples) || o.view.as_deref().is_some_and(|v| v != "3d") {
if let Some(samples) = options.samples {
if !(1..=MAX_TRACE_SAMPLES).contains(&samples) || options.view.as_deref().is_some_and(|v| v != "3d") {
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 settings = texturecraft_render::trace::TraceSettings { bounces: options.bounces.unwrap_or(6).clamp(1, 32) };
let mut traced = None;
let mut by = "CPU path tracer".to_string();
if !o.cpu
if !options.cpu
&& let Ok(gpu) = self.gpu.get_or_insert_with(Gpu::new)
{
// Last-resort guard, as for viewport renders below.
// 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)) => {
@@ -355,11 +373,13 @@ impl Headless {
}
return Ok(Rendered { width: w, height: h, png, by });
}
let gpu = match self.gpu.get_or_insert_with(Gpu::new) {
Ok(g) => g,
Err(e) => return Err(AutomationError::Other(format!("cannot render: {e}"))),
};
// Last-resort guard: wgpu panics on device errors; drop the device and report instead.
// Last-resort guard: wgpu panics on device errors; drop the device and report instead
let session = &mut self.session;
let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| gpu.render(session, kind, size, camera)));
let (w, h, rgba) = match out {
@@ -396,6 +416,25 @@ pub fn batch_reply(results: Vec<Value>, failed: Option<(usize, &str, String)>) -
mod tests {
use super::*;
#[test]
fn closed_session_rejects_bake_mesh_before_reading_it() {
let mut client = Headless::new(Session::closed().unwrap(), Filesystem::Denied);
let error = client.add_bake_mesh("missing.obj", false).unwrap_err();
assert!(error.to_string().contains("no project is open"), "{error}");
}
#[test]
fn closed_session_rejects_render_before_view_validation() {
let mut client = Headless::new(Session::closed().unwrap(), Filesystem::Denied);
let options = RenderOptions { view: Some("unknown".into()), ..RenderOptions::default() };
let error = client.render_png(&options).err().unwrap();
assert!(error.to_string().contains("no project is open"), "{error}");
}
#[test]
fn fresh_headless_session_loads_saved_brushes() {
let brush_dir = std::env::temp_dir().join(format!("tc-headless-brush-{}", std::process::id()));
+1 -1
View File
@@ -238,7 +238,7 @@ mod tests {
for id in ["file.open", "file.new", "file.save", "file.saveAs", "file.saveCopy", "file.exportTextures"] {
assert!(authorize_command(id, &json!({})).is_err(), "{id}");
}
for id in ["resource.import", "material.save", "material.load", "anything.new"] {
for id in ["resource.import", "material.save", "material.load", "mask.smart.create", "mask.smart.apply", "anything.new"] {
assert!(authorize_command(id, &json!({"path": "/etc/x"})).is_err(), "{id}");
assert!(authorize_command(id, &json!({"dir": "/etc"})).is_err(), "{id}");
}
+4 -2
View File
@@ -430,13 +430,15 @@ async fn mesh_files_export_bake_and_reimport_in_the_workspace() {
assert!(!textures.is_empty() && textures.iter().all(|t| base.join(t.as_str().unwrap()).is_file()), "{usda}");
assert_eq!(tool(&c, "mesh_export", json!({"path": "out/cube.glb"})).await["path"], "out/cube.glb");
assert!(base.join("out/cube.usda").is_file() && base.join("out/cube.glb").is_file());
// The loose usda arrives packaged with its textures.
// The loose usda arrives packaged with its textures
let high = tool(&c, "bake_mesh_add", json!({"path": "out/cube.usda"})).await;
assert_eq!(high["name"], "cube.usdz", "{high}");
let cage = tool(&c, "bake_mesh_add", json!({"path": "out/cube.glb", "cage": true})).await;
assert_eq!(cage["meshes"]["cage"]["name"], "cube.glb", "{cage}");
assert_eq!(inspect(&c).await["bakeMeshes"]["highPoly"][0]["name"], "cube.usdz");
// A built-in mesh has no file to re-read; a file does.
// A built-in mesh has no file to re-read; a file does
assert!(tool_err(&c, "mesh_reimport", json!({})).await.contains("built-in"));
tool(&c, "mesh_reimport", json!({"path": "out/cube.glb", "preserveStrokes": true})).await;
assert_eq!(inspect(&c).await["mesh"]["source"], "mesh.glb");
+1 -5
View File
@@ -143,11 +143,7 @@ impl StackKey {
let mut referenced_images = BTreeSet::new();
if !images.is_empty() {
let mut record_image_reference = |source: &Source| {
if let Source::Image { name, .. } = source
&& let Some((name, _)) = images.get_key_value(name)
{
referenced_images.insert(name);
}
referenced_images.extend(source.images().into_iter().filter_map(|name| images.get_key_value(name)).map(|(name, _)| name));
};
for layer in render_tree.iter().filter_map(|id| project.layers.get(id)) {
if let LayerKind::Fill(fill) = &layer.kind {
File diff suppressed because it is too large. Load diff
+8 -2
View File
@@ -16,14 +16,20 @@ pub mod eval;
mod held_fields;
mod image_identity;
pub mod pattern;
mod pattern_context;
pub mod solo;
pub mod store;
pub mod thumb;
mod tile_pattern;
mod tile_random_stream;
pub use below::{BelowCache, StackKey};
pub use display::{DisplayKind, kinds_for, tile_bytes};
pub use eval::{
BLOCK, Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram,
flatten_layer, mask_at, mask_image, pad_tiles, stack_reads_neighbours,
BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles,
effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours,
};
pub use pattern_context::PatternContext;
pub use solo::solo_project;
pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore};
pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget};
+160 -24
View File
@@ -1,9 +1,14 @@
//! Procedural patterns and projections.
use texturecraft_core::{Decal, Procedural, ProceduralKind, Projection};
use texturecraft_core::{Decal, DecalFlip, Procedural, ProceduralKind, Projection};
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_texel::noise;
use crate::pattern_context::PatternContext;
/// Smaller pattern scales are read as this: a pattern stretched over ten thousand repeats of its projection
const MIN_PATTERN_SCALE: f32 = 1e-4;
/// Where a texel is, for pattern evaluation.
#[derive(Clone, Copy, Debug)]
pub struct Coords {
@@ -26,7 +31,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 {
((n - 0.45) * 4.0 + 0.5).clamp(0.0, 1.0)
}
ProceduralKind::Scratches => {
// Long thin streaks: noise stretched along one axis, sharpened to lines.
// Stretch noise along one axis to make thin streaks
let q = Vec3::new(p.x * 0.15, p.y * 6.0, p.z * 6.0);
let n = noise::perlin(q.to_array(), seed);
let line = 1.0 - ((n - 0.5).abs() * 40.0).min(1.0);
@@ -43,8 +48,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 {
}
ProceduralKind::Gradient => p.x.rem_euclid(1.0),
ProceduralKind::Wood => {
// Rings across Y (warped by low-frequency noise), latewood darkening sharply before
// each ring boundary; fine fibers stretched along X.
// Warp ring boundaries and add fine fibers along X
let warp = noise::fbm([p.x * 0.18, p.y * 0.6, p.z], 3, seed, noise::perlin);
let t = ((p.y + (warp - 0.5) * 0.9) * 5.0).rem_euclid(1.0);
let ring = 1.0 - smoothstep(0.45, 1.0, t);
@@ -53,8 +57,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 {
(ring * 0.6 + fiber * 0.25 + tone * 0.15).clamp(0.0, 1.0)
}
ProceduralKind::Bricks => {
// Bricks 1 × 0.5 in running bond; per-brick tone in the top 15 % so low/high map to
// mortar/brick colors without washing the bricks out.
// Keep per-brick tone near its high value so mortar stays distinct
let row = (p.y * 2.0).floor();
let x = p.x + if (row as i32).rem_euclid(2) == 1 { 0.5 } else { 0.0 };
let (col, fx, fy) = (x.floor(), x.rem_euclid(1.0), (p.y * 2.0).rem_euclid(1.0));
@@ -68,10 +71,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 {
smoothstep(0.015, 0.035, d) * (0.9 + 0.1 * noise::cell_hash(c.x as i32, c.y as i32, 0, seed))
}
ProceduralKind::Weave | ProceduralKind::Twill => {
// Warp along X, weft along Y: in each cell the thread on top shows its round
// cross-section, bulging mid-span. A plain weave alternates every cell; a 2/2 twill
// floats over two cells and steps one cell per row, so the floats line up in diagonal
// ribs, the weft darker than the warp.
// Alternate top threads for plain weave or step them into twill ribs
let c = (p * 2.0).floor();
let f = p * 2.0 - c;
let pi = std::f32::consts::PI;
@@ -112,8 +112,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 {
}
ProceduralKind::Voronoi => noise::cellular(a, seed).2,
ProceduralKind::Streaks => {
// Drips: thin columns along Y, each segment starting at a random height and fading
// as it runs down (Y is up), over two offset column grids.
// Offset column grids make sparse drips that fade downwards
let drip = |x: f32, salt: u32| {
let cx = x * 6.0;
let col = cx.floor() as i32;
@@ -129,7 +128,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 {
(drip(p.x, 0).max(drip(p.x + 0.37, 1) * 0.8) * (0.6 + 0.4 * fine)).clamp(0.0, 1.0)
}
ProceduralKind::Smudges => {
// Sparse elliptical prints with concentric ridges, over soft greasy smudges.
// Blend ridged elliptical prints with soft smudges
let w = noise::perlin((p * 1.3).to_array(), seed ^ 0x61) - 0.5;
let q = Vec3::new(p.x * 1.15 + w * 0.3, p.y * 0.85 + w * 0.3, p.z);
let (f1, _, id) = noise::cellular(q.to_array(), seed);
@@ -143,6 +142,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 {
let (g1, _, _) = noise::cellular((p * 2.7 + Vec3::splat(13.0)).to_array(), seed ^ 0x6B);
smoothstep(0.08, 0.16, f1).min(smoothstep(0.06, 0.12, g1))
}
ProceduralKind::TileGenerator => crate::tile_pattern::value(&crate::tile_pattern::DEFAULT, p.truncate(), seed, None),
ProceduralKind::Chips => {
let (f1, _, _) = noise::cellular((p * 2.0).to_array(), seed ^ 0x45);
let n = noise::fbm(a, 5, seed, noise::perlin) + (f1 - 0.5) * 0.25;
@@ -200,16 +200,22 @@ fn shape(pr: &Procedural, v: f32) -> f32 {
if pr.invert { 1.0 - v } else { v }
}
/// Evaluate a procedural through a projection.
/// Evaluate a procedural through a projection, at full resolution and without images
pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords) -> f32 {
let pattern_scale = pattern.scale.max(1e-4);
procedural_in(pattern, projection, coords, &PatternContext::default())
}
/// Evaluate a procedural through a projection with what `context` gives it: its resolution and the images it reads
pub fn procedural_in(pattern: &Procedural, projection: &Projection, coords: &Coords, context: &PatternContext) -> f32 {
let pattern_scale = pattern.scale.max(MIN_PATTERN_SCALE);
let sample = |point: Vec3| plane_value(pattern, point, context);
let value = match projection {
Projection::Uv { scale, rotation, offset } => {
let (sn, cs) = rotation.to_radians().sin_cos();
let uv = Vec2::new(coords.uv.x * cs - coords.uv.y * sn, coords.uv.x * sn + coords.uv.y * cs) * Vec2::from(*scale) + Vec2::from(*offset);
// Evaluate two-dimensional patterns on a slice of the volume
raw(pattern.kind, (uv * pattern_scale).extend(0.0), pattern.seed)
sample((uv * pattern_scale).extend(0.0))
}
Projection::Triplanar { scale, sharpness, offset } => {
let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset);
@@ -217,7 +223,7 @@ pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords
// Shape scales the blend by the contrast
let w = triplanar_weights(coords.nrm, *sharpness, pattern.contrast);
let planes = [(w.x, Vec3::new(p.z, p.y, 0.0)), (w.y, Vec3::new(p.x, p.z, 0.0)), (w.z, Vec3::new(p.x, p.y, 0.0))];
planes.into_iter().filter(|(w, _)| *w > 0.0).map(|(w, q)| raw(pattern.kind, q, pattern.seed) * w).sum()
planes.into_iter().filter(|(w, _)| *w > 0.0).map(|(w, q)| sample(q) * w).sum()
}
Projection::Planar { scale, axis, offset } => {
let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset);
@@ -226,13 +232,13 @@ pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords
1 => Vec3::new(p.x, p.z, 0.0),
_ => Vec3::new(p.x, p.y, 0.0),
};
raw(pattern.kind, q, pattern.seed)
sample(q)
}
Projection::Spherical { scale } => {
let d = coords.pos.try_normalize().unwrap_or(Vec3::Y);
let u = d.z.atan2(d.x) / std::f32::consts::TAU + 0.5;
let v = d.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI;
raw(pattern.kind, Vec3::new(u * 4.0, v * 2.0, 0.0) * *scale * pattern_scale, pattern.seed)
sample(Vec3::new(u * 4.0, v * 2.0, 0.0) * *scale * pattern_scale)
}
Projection::Cylindrical { scale, axis } => {
let p = coords.pos;
@@ -242,15 +248,50 @@ pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords
_ => (p.x, p.y, p.z),
};
let u = b.atan2(a) / std::f32::consts::TAU + 0.5;
raw(pattern.kind, Vec3::new(u * 4.0, h, 0.0) * *scale * pattern_scale, pattern.seed)
sample(Vec3::new(u * 4.0, h, 0.0) * *scale * pattern_scale)
}
// The decal already supplied coordinates in its local frame
Projection::Decal(_) => raw(pattern.kind, (coords.uv * pattern_scale).extend(0.0), pattern.seed),
Projection::Decal(_) => sample((coords.uv * pattern_scale).extend(0.0)),
};
shape(pattern, value)
}
/// The texels per side `pattern`'s resolution draws it at for a UV tile of `uv_tile` texels per side in a texture set of `texture_set`, when that is coarser than the UV tile (a finer image changes nothing: patterns are evaluated per texel)
pub fn pattern_pixels(pattern: &Procedural, uv_tile: u32, texture_set: u32) -> Option<u32> {
if !pattern.resolution.can_reduce() {
return None;
}
let size = pattern.resolution.output_size(uv_tile, texture_set);
(size < uv_tile).then_some(size)
}
/// The pattern at `point` of its plane, read from an image of `context.pixels` texels per repeat (bilinear) when given
fn plane_value(pattern: &Procedural, point: Vec3, context: &PatternContext) -> f32 {
let cells = context.pixels.map(|pixels| pixels as f32 / pattern.scale.max(MIN_PATTERN_SCALE)).filter(|cells| cells.is_finite() && *cells > 0.0);
let Some(cells) = cells else { return pattern_value(pattern, point, context) };
let grid = point.truncate() * cells - 0.5;
let base = grid.floor();
let fraction = grid - base;
let at = |dx: f32, dy: f32| pattern_value(pattern, ((base + Vec2::new(dx, dy) + 0.5) / cells).extend(point.z), context);
let top_left = at(0.0, 0.0);
let bottom_left = at(0.0, 1.0);
let top = top_left + (at(1.0, 0.0) - top_left) * fraction.x;
let bottom = bottom_left + (at(1.0, 1.0) - bottom_left) * fraction.x;
top + (bottom - top) * fraction.y
}
/// The pattern at `point` of its plane, exactly
fn pattern_value(pattern: &Procedural, point: Vec3, context: &PatternContext) -> f32 {
match (&pattern.tile, pattern.kind) {
(Some(tile), ProceduralKind::TileGenerator) => crate::tile_pattern::value(tile, point.truncate(), pattern.seed, context.images),
_ => raw(pattern.kind, point, pattern.seed),
}
}
/// Texture coordinates (and blend weights) at which an image is sampled for a projection
/// (unused slots weigh 0; no allocation per texel).
pub fn image_samples(projection: &Projection, coords: &Coords) -> [(Vec2, f32); 3] {
@@ -332,8 +373,38 @@ pub fn decal_uv(d: &Decal, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> {
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))
Some((flip_uv(Vec2::new(lx + 0.5, 0.5 - ly), d.flip), w))
}
/// `uv` with the image mirrored left to right (`flip[0]`) and/or top to bottom (`flip[1]`) inside the frame.
fn flip_uv(uv: Vec2, flip: [bool; 2]) -> Vec2 {
Vec2::new(if flip[0] { 1.0 - uv.x } else { uv.x }, if flip[1] { 1.0 - uv.y } else { uv.y })
}
/// [`decal_uv`] for a decal with a mirrored copy: whichever of the decal and its copy covers the
/// point more. The copy is the decal reflected through the plane across `center` (the mesh
/// center), so a point is looked up as its reflection (the plane is `offset` away from the center) and the image flipped as asked.
pub fn decal_uv_symmetric(d: &Decal, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> {
let direct = decal_uv(d, p, nrm);
let Some(symmetry) = d.symmetry else { return direct };
let axis = usize::from(symmetry.axis.min(2));
let (mut mirrored_position, mut mirrored_normal) = (p, nrm);
mirrored_position[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis];
mirrored_normal[axis] = -nrm[axis];
let mirrored = decal_uv(d, mirrored_position, mirrored_normal).map(|(uv, w)| {
let uv = match symmetry.flip {
DecalFlip::None => uv,
DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y),
DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y),
};
(uv, w)
});
match (direct, mirrored) {
(Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }),
(a, b) => a.or(b),
}
}
/// World-space noise used by generators (seamless across UV islands).
@@ -344,6 +415,32 @@ pub fn world_noise(pos: Vec3, scale: f32, seed: u32) -> f32 {
#[cfg(test)]
mod tests {
use super::*;
use texturecraft_core::{OutputResolution, ResolutionMode};
#[test]
fn a_pattern_is_drawn_coarser_only_below_the_uv_tiles_resolution() {
let with = |resolution: OutputResolution| pattern_pixels(&Procedural { resolution, ..Procedural::new(ProceduralKind::Clouds) }, 1024, 2048);
assert_eq!(with(OutputResolution::default()), None, "by default a pattern is evaluated per texel");
assert_eq!(with(OutputResolution { factor: -1, ..OutputResolution::default() }), Some(512));
assert_eq!(with(OutputResolution { mode: ResolutionMode::Custom, custom: 256, factor: 0 }), Some(256));
assert_eq!(with(OutputResolution { mode: ResolutionMode::Custom, custom: 2048, factor: 0 }), None, "a finer image than the UV tile changes nothing");
}
#[test]
fn a_coarser_pattern_reads_its_cells_bilinearly() {
let pattern = Procedural { scale: 1.0, ..Procedural::new(ProceduralKind::Clouds) };
let coarse = PatternContext { pixels: Some(4), ..PatternContext::default() };
let at = |x: f32, context: &PatternContext| {
procedural_in(&pattern, &Projection::default(), &Coords { uv: Vec2::new(x, 0.375), pos: Vec3::ZERO, nrm: Vec3::Y }, context)
};
let exact = PatternContext::default();
// Coarse reads are exact at cell centers and blend between them
assert!((at(0.375, &coarse) - at(0.375, &exact)).abs() < 1e-5);
let blended = (at(0.125, &exact) + at(0.375, &exact)) * 0.5;
assert!((at(0.25, &coarse) - blended).abs() < 1e-5, "{} vs {blended}", at(0.25, &coarse));
assert!((at(0.25, &exact) - blended).abs() > 1e-3, "the exact pattern is not the blend, so the coarse read shows");
}
#[test]
fn every_pattern_and_projection_stays_in_range() {
@@ -361,6 +458,8 @@ mod tests {
rotation: 0.0,
offset: [0.0; 2],
depth: 1.0,
symmetry: None,
flip: [false; 2],
}),
];
for k in ProceduralKind::ALL {
@@ -461,14 +560,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 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,
symmetry: None,
flip: [false; 2],
};
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.
// 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}");
@@ -478,6 +588,32 @@ mod tests {
assert!(decal_uv(&Decal { size: [f32::NAN; 2], ..d }, Vec3::ZERO, z).is_none());
}
#[test]
fn decals_mirror_their_image_inside_the_frame() {
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,
symmetry: None,
flip: [false; 2],
};
let (left, top) = (Vec3::new(-0.5, 0.25, 0.0), Vec3::Z);
let uv = |flip: [bool; 2]| decal_uv(&Decal { flip, ..d }, left, top).unwrap().0;
assert!((uv([false, false]) - Vec2::new(0.25, 0.25)).length() < 1e-5);
assert!((uv([true, false]) - Vec2::new(0.75, 0.25)).length() < 1e-5, "Flip U mirrors left to right only");
assert!((uv([false, true]) - Vec2::new(0.25, 0.75)).length() < 1e-5, "Flip V mirrors top to bottom only");
assert!((uv([true, true]) - Vec2::new(0.75, 0.75)).length() < 1e-5);
// The frame itself does not move: coverage is the same flipped or not
let covered = |flip: [bool; 2], p: Vec3| decal_uv(&Decal { flip, ..d }, p, top).map(|(_, w)| w);
assert_eq!(covered([true, true], left), covered([false, false], left));
assert_eq!(covered([true, true], Vec3::new(1.1, 0.0, 0.0)), None);
}
#[test]
fn twill_floats_run_in_diagonal_ribs() {
// The value at the centre of cell (x, y); cells are half a unit.
+12
View File
@@ -0,0 +1,12 @@
//! What evaluating a pattern needs besides the texel: the resolution it is drawn at and the images it reads
use crate::store::ImageStore;
/// What a pattern reads beyond the texel's coordinates (fields can be added; build it with `..PatternContext::default()`)
#[derive(Clone, Copy, Default)]
pub struct PatternContext<'a> {
/// Texels per side of the image the pattern is drawn as over one repeat of the projection (see [`crate::pattern::pattern_pixels`]); None draws it exactly
pub pixels: Option<u32>,
/// The image resources a pattern's inputs name; None reads them as empty
pub images: Option<&'a ImageStore>,
}
+169
View File
@@ -0,0 +1,169 @@
//! The view-only "solo" of one layer: the project as the viewport shows it while a layer is
//! isolated. The document itself is never changed; the compositor reads this copy instead.
use std::collections::BTreeSet;
use texturecraft_core::project::MAX_DEPTH;
use texturecraft_core::{LayerId, Mask, MaskBackground, Project};
/// `project` as shown while `layer` is soloed: every other layer of its texture set hidden, the
/// layer and the folders around it shown (even if their eyes are off), and with `ignore_mask`
/// the layer and its folders drawn at full coverage. Other texture sets stay as they are.
/// None when `layer` is in no stack.
pub fn solo_project(project: &Project, layer: LayerId, ignore_mask: bool) -> Option<Project> {
let (ts, mut parent, _) = project.locate(layer)?;
let set = project.texture_sets.get(ts)?;
// The layer and the folders holding it
let mut shown = vec![layer];
for _ in 0..=MAX_DEPTH {
let Some(folder) = parent else { break };
shown.push(folder);
parent = project.locate(folder).and_then(|located| located.1);
}
// What stays drawn: those, and a soloed folder's contents
let mut kept: BTreeSet<LayerId> = shown.iter().copied().collect();
contents(project, &[layer], &mut kept, 0);
// A soloed instance draws its source's contents, which must stay visible too
kept.extend(project.render_tree(&[layer]));
let mut every = BTreeSet::new();
contents(project, &set.stack, &mut every, 0);
let mut view = project.clone();
for id in every.difference(&kept) {
if let Some(hidden) = view.layers.get_mut(id) {
hidden.visible = false;
}
}
for id in &shown {
let Some(drawn) = view.layers.get_mut(id) else { continue };
drawn.visible = true;
if !ignore_mask {
continue;
}
let instance = drawn.instance_source().is_some();
match drawn.mask.as_mut() {
Some(mask) => mask.enabled = false,
// An instance without its own mask draws its source's: an own, disabled one overrides it
None if instance => drawn.mask = Some(Mask { enabled: false, ..Mask::new(MaskBackground::White) }),
None => {}
}
}
Some(view)
}
/// `roots` and everything in the folders among them (instances' sources are not followed:
/// they may belong to another texture set).
fn contents(project: &Project, roots: &[LayerId], out: &mut BTreeSet<LayerId>, depth: usize) {
if depth > MAX_DEPTH {
return;
}
for id in roots {
out.insert(*id);
if let Some(layer) = project.layers.get(id) {
contents(project, layer.children(), out, depth + 1);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use texturecraft_core::{Channel, Layer, LayerKind, TextureSet};
const CHANNELS: [Channel; 1] = [Channel::BaseColor];
fn project() -> Project {
let mut p = Project::new("t", "");
p.texture_sets.push(TextureSet::new("a", 0, 64));
p.texture_sets.push(TextureSet::new("b", 0, 64));
p
}
fn add(p: &mut Project, ts: usize, kind: LayerKind, above: Option<LayerId>, inside: bool) -> LayerId {
let id = p.alloc_id();
p.insert_layer(ts, Layer::new(id, "layer", kind, &CHANNELS), above, inside).unwrap();
id
}
fn masked(p: &mut Project, id: LayerId) {
p.layer_mut(id).unwrap().mask = Some(Mask::new(MaskBackground::Black));
}
#[test]
fn solo_hides_the_others_and_leaves_the_original_alone() {
let mut p = project();
let (below, rust, other_set) =
(add(&mut p, 0, LayerKind::Paint, None, false), add(&mut p, 0, LayerKind::Paint, None, false), add(&mut p, 1, LayerKind::Paint, None, false));
p.layer_mut(rust).unwrap().visible = false;
let before = p.clone();
let view = solo_project(&p, rust, false).unwrap();
assert!(view.layers[&rust].visible, "the soloed layer shows even with its eye off");
assert!(!view.layers[&below].visible, "the others are hidden");
assert!(view.layers[&other_set].visible, "another texture set keeps its layers");
assert_eq!(p, before, "the project itself is untouched");
}
#[test]
fn solo_keeps_the_folders_around_a_layer_and_everything_inside_a_soloed_folder() {
let mut p = project();
let outside = add(&mut p, 0, LayerKind::Paint, None, false);
let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false);
let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true);
let sibling = add(&mut p, 0, LayerKind::Paint, Some(inner), false);
let view = solo_project(&p, inner, false).unwrap();
assert!(view.layers[&folder].visible && view.layers[&inner].visible);
assert!(!view.layers[&sibling].visible && !view.layers[&outside].visible);
let whole = solo_project(&p, folder, false).unwrap();
assert!(whole.layers[&inner].visible && whole.layers[&sibling].visible, "a soloed folder shows its contents");
assert!(!whole.layers[&outside].visible);
}
#[test]
fn ignoring_the_mask_disables_it_on_the_layer_and_its_folders_only() {
let mut p = project();
let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false);
let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true);
let other = add(&mut p, 0, LayerKind::Paint, None, false);
for id in [folder, inner, other] {
masked(&mut p, id);
}
let kept = solo_project(&p, inner, false).unwrap();
assert!(kept.layers[&inner].mask.as_ref().unwrap().enabled, "without the flag the mask stays");
let view = solo_project(&p, inner, true).unwrap();
assert!(!view.layers[&inner].mask.as_ref().unwrap().enabled && !view.layers[&folder].mask.as_ref().unwrap().enabled);
assert!(view.layers[&other].mask.as_ref().unwrap().enabled, "a hidden layer's mask is not touched");
assert!(p.layers[&inner].mask.as_ref().unwrap().enabled, "the project keeps its mask");
}
#[test]
fn an_instance_gets_its_own_disabled_mask_instead_of_changing_its_source() {
let mut p = project();
let source = add(&mut p, 0, LayerKind::Paint, None, false);
masked(&mut p, source);
let instance = add(&mut p, 1, LayerKind::Instance { source }, None, false);
let view = solo_project(&p, instance, true).unwrap();
assert!(!view.layers[&instance].mask.as_ref().unwrap().enabled);
assert!(view.layers[&source].mask.as_ref().unwrap().enabled, "the source keeps its mask");
}
#[test]
fn a_soloed_instance_of_a_folder_keeps_the_folders_contents_drawn() {
let mut p = project();
let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false);
let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true);
let instance = add(&mut p, 0, LayerKind::Instance { source: folder }, None, false);
let view = solo_project(&p, instance, false).unwrap();
assert!(view.layers[&instance].visible && view.layers[&folder].visible && view.layers[&inner].visible);
}
#[test]
fn a_layer_in_no_stack_gives_nothing() {
assert!(solo_project(&project(), LayerId(99), true).is_none());
}
}
+658
View File
@@ -0,0 +1,658 @@
//! The Tile Generator pattern: shapes in a grid of tiles over one repeating unit, x right and y down as a texture's rows
use std::sync::LazyLock;
use texturecraft_core::{TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry};
use texturecraft_geom::glam::Vec2;
use crate::store::{ImageRes, ImageStore};
use crate::tile_random_stream::TileRandomStream;
/// The settings a Tile Generator pattern saved without its own reads
pub(crate) static DEFAULT: LazyLock<TileGenerator> = LazyLock::new(TileGenerator::default);
/// The output size the pixel size mode measures shapes against
const PIXEL_REFERENCE: f32 = 2048.0;
/// Position random moves a tile up to this many cells times its amount, either way
const POSITION_RANDOM_CELLS: f32 = 1.0;
/// Capsule shape: the radius of its round ends
const CAPSULE_RADIUS: f32 = 0.2225;
/// Half bell shape: the width of its squashed half at a specific of 0
const HALF_BELL_WIDTH: f32 = 1.24;
/// Gaussian shape: the falloff exponent, 2^(−k·r²)
const GAUSSIAN_FALLOFF: f32 = 16.0;
/// Crescent shape: scales its ring r²(1 − r²)² to a peak of 1
const CRESCENT_GAIN: f32 = 6.75;
/// Waves shape: cycles across the tile at a specific of 0, and the cycles a specific of 1 adds
const WAVES_BASE_CYCLES: f32 = 1.5;
const WAVES_SPECIFIC_CYCLES: f32 = 6.0;
/// Narrower than this, a size or a bevel is none
const EPSILON: f32 = 1e-6;
/// Valid tile settings reach at most three neighboring copies along an axis
const MAX_PERIODIC_COPY: f32 = 3.0;
fn smoothstep(t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
fn bell(r: f32) -> f32 {
(1.0 - r * r).clamp(0.0, 1.0).powi(4)
}
/// The shape's value at (u, v) of its square (−1..1 both ways; 0 outside it). `specific` changes some shapes
fn shape(kind: TileShape, u: f32, v: f32, specific: f32) -> f32 {
if u.abs() > 1.0 || v.abs() > 1.0 {
return 0.0;
}
let r = u.hypot(v);
match kind {
TileShape::Square => 1.0,
TileShape::Disc => f32::from(u8::from(r <= 1.0)),
TileShape::Paraboloid => (1.0 - r * r).clamp(0.0, 1.0),
TileShape::Bell => bell(r),
TileShape::Gaussian => (-GAUSSIAN_FALLOFF * r * r).exp2(),
TileShape::Thorn => (1.0 - r).clamp(0.0, 1.0).powi(4),
TileShape::Pyramid => (1.0 - u.abs().max(v.abs())).clamp(0.0, 1.0),
TileShape::Cone => (1.0 - r).clamp(0.0, 1.0),
TileShape::Brick if specific <= EPSILON => 1.0,
TileShape::Brick => smoothstep((1.0 - u.abs()) / specific) * smoothstep((1.0 - v.abs()) / specific),
TileShape::Gradation => (u + 1.0) * 0.5 * (1.0 - specific),
TileShape::Waves => {
let cycles = WAVES_BASE_CYCLES + WAVES_SPECIFIC_CYCLES * specific;
(1.0 - r * r).clamp(0.0, 1.0) * (0.5 + 0.5 * (std::f32::consts::TAU * cycles * u).cos())
}
TileShape::HalfBell => {
let width = HALF_BELL_WIDTH * (1.0 - specific);
let cut = match (u > 0.0, width > EPSILON) {
(false, _) => 1.0,
(true, true) => bell(u / width),
(true, false) => 0.0,
};
bell(r) * cut
}
TileShape::RidgedBell => bell(r) * (1.0 - u.abs()).powi(2),
TileShape::Crescent if specific >= 1.0 => 0.0,
TileShape::Crescent => {
let shifted = (u + 1.0) / (1.0 - specific) - 1.0;
let ring = (1.0 - r * r).clamp(0.0, 1.0);
CRESCENT_GAIN * r * r * ring * ring * smoothstep((1.0 - shifted) * 0.5)
}
TileShape::Capsule => {
let half_length = specific * (1.0 - CAPSULE_RADIUS);
let distance = (u.abs() - half_length).max(0.0).hypot(v);
(1.0 - (distance / CAPSULE_RADIUS).powi(2)).clamp(0.0, 1.0)
}
// The image shape draws an input image instead (see `pattern`): without one it is empty
TileShape::Image => 0.0,
}
}
/// `point` turned clockwise on screen by `turns` undone (y runs down)
fn unrotate(point: Vec2, turns: f32) -> Vec2 {
if turns == 0.0 {
return point;
}
let (sin, cos) = (turns * std::f32::consts::TAU).sin_cos();
Vec2::new(cos * point.x + sin * point.y, -sin * point.x + cos * point.y)
}
/// The pattern section: tile-local (u, v) through the shape's tiling, angle, scale, size and 45° turn, then the shape (`input` for the image shape)
fn pattern(tile: &TileGenerator, mut local: Vec2, input: Option<&ImageRes>) -> f32 {
if local.x.abs() > 1.0 || local.y.abs() > 1.0 {
return 0.0;
}
if tile.shape_tiling > 1 {
// Tiling shows the copy just above and left of center
let count = tile.shape_tiling as f32;
let shown = (tile.shape_tiling.div_ceil(2) - 1) as f32;
let cell = (local + 1.0) * 0.5 * count;
if cell.x.floor() != shown || cell.y.floor() != shown {
return 0.0;
}
local = (cell - shown) * 2.0 - 1.0;
}
local = unrotate(local, tile.shape_angle / 360.0);
let size = Vec2::from(tile.shape_size) * tile.shape_scale;
if size.x <= EPSILON || size.y <= EPSILON {
return 0.0;
}
local /= size;
if tile.shape_diagonal {
local = unrotate(local, 0.125) * std::f32::consts::SQRT_2;
}
if tile.shape == TileShape::Image {
return input.map_or(0.0, |image| image_shape(image, local));
}
let samples = Vec2::new(tile.shape_resolution[0] as f32, tile.shape_resolution[1] as f32);
sampled_shape(tile, local, samples)
}
/// An input image over the shape's square, as gray (the average of its color)
fn image_shape(image: &ImageRes, local: Vec2) -> f32 {
if local.x.abs() > 1.0 || local.y.abs() > 1.0 {
return 0.0;
}
let at = (local + 1.0) * 0.5;
gray(image.sample(at.x, at.y))
}
/// The gray of an image texel: the average of its color
fn gray([red, green, blue, _]: [f32; 4]) -> f32 {
((red + green + blue) / 3.0).clamp(0.0, 1.0)
}
/// The shape read from an image of `samples` texels over its square, bilinearly, as the shape is drawn at its own resolution
fn sampled_shape(tile: &TileGenerator, local: Vec2, samples: Vec2) -> f32 {
let grid = (local + 1.0) * 0.5 * samples - 0.5;
let base = grid.floor();
let fraction = grid - base;
let at = |dx: f32, dy: f32| {
let texel = (base + Vec2::new(dx, dy) + 0.5) / samples * 2.0 - 1.0;
shape(tile.shape, texel.x, texel.y, tile.specific)
};
let top_left = at(0.0, 0.0);
let bottom_left = at(0.0, 1.0);
let top = top_left + (at(1.0, 0.0) - top_left) * fraction.x;
let bottom = bottom_left + (at(1.0, 1.0) - bottom_left) * fraction.x;
top + (bottom - top) * fraction.y
}
/// The start and width, in cells, of cell `index` along an axis whose middle size is `middle` (cells pair up)
fn cell_span(index: i32, middle: f32) -> (f32, f32) {
let pair = index.div_euclid(2) as f32 * 2.0;
if index.rem_euclid(2) == 0 { (pair, 2.0 * middle) } else { (pair + 2.0 * middle, 2.0 * (1.0 - middle)) }
}
/// `delta` wrapped into −span/2..span/2 (the pattern repeats every `span`)
fn wrap(delta: f32, span: f32) -> f32 {
delta - (delta / span).round() * span
}
/// What one tile gives a texel (its shape times its luminance), or None when hidden or out of reach; `inputs` are its input images
fn tile_value(
tile: &TileGenerator,
seed: u32,
(column, row): (i32, i32),
(columns, rows): (i32, i32),
(point, inputs): (Vec2, &[Option<&ImageRes>]),
) -> Option<f32> {
let total = columns * rows;
let number = column * rows + row;
let index = (if tile.reverse_order { total - 1 - number } else { number }) as u32;
if hidden(tile, seed, (column, row), index) {
return None;
}
let (start_x, width) = cell_span(column, tile.middle_size[0]);
let (start_y, height) = cell_span(row, tile.middle_size[1]);
let mut center = Vec2::new(start_x + width * 0.5, start_y + height * 0.5);
if tile.vertical_offset {
center.y += line_shift(tile, column);
} else {
center.x += line_shift(tile, row);
}
center.x += (TileRandomStream::PositionX.draw(seed, index) - 0.5) * 2.0 * POSITION_RANDOM_CELLS * tile.position_random[0];
center.y += (TileRandomStream::PositionY.draw(seed, index) - 0.5) * 2.0 * POSITION_RANDOM_CELLS * tile.position_random[1];
let counts = Vec2::new(columns as f32, rows as f32);
let center = center / counts + Vec2::from(tile.global_offset);
let scale_factor = 1.0 - tile.scale_random * TileRandomStream::Scale.draw(tile.scale_random_seed, index);
let size = tile_size(tile, seed, index, Vec2::new(width, height) / counts) * tile.scale * scale_factor;
if size.x <= EPSILON || size.y <= EPSILON {
return None;
}
let delta = Vec2::new(wrap(point.x - center.x, 1.0), wrap(point.y - center.y, 1.0));
let turns = (tile.rotation + tile.rotation_random * TileRandomStream::Rotation.draw(seed, index) * 360.0) / 360.0;
let (sin, cos) = (turns * std::f32::consts::TAU).sin_cos();
let radius = Vec2::new(cos.abs() * size.x + sin.abs() * size.y, sin.abs() * size.x + cos.abs() * size.y) * 0.5;
let first = (-radius - delta).ceil().max(Vec2::splat(-MAX_PERIODIC_COPY));
let last = (radius - delta).floor().min(Vec2::splat(MAX_PERIODIC_COPY));
let quarter_turns = quarter_turns(tile, seed, (column, row), index);
let mirrors = tile.symmetry_random * 0.5;
let mirror_x = tile.symmetry != TileSymmetry::Vertical && TileRandomStream::MirrorX.draw(seed, index) < mirrors;
let mirror_y = tile.symmetry != TileSymmetry::Horizontal && TileRandomStream::MirrorY.draw(seed, index) < mirrors;
let input = match tile.input_distribution {
_ if inputs.is_empty() => None,
TileInputDistribution::Random => inputs.get((TileRandomStream::Input.draw(seed, index) * inputs.len() as f32) as usize).copied().flatten(),
TileInputDistribution::ByNumber => inputs.get(number as usize % inputs.len()).copied().flatten(),
};
let mut value = 0.0f32;
// A rotated shape may cross a repeat boundary even when the nearest copy misses it
for copy_y in first.y as i32..=last.y as i32 {
let y = delta.y + copy_y as f32;
if y.abs() > radius.y {
continue;
}
for copy_x in first.x as i32..=last.x as i32 {
let x = delta.x + copy_x as f32;
if x.abs() > radius.x {
continue;
}
let mut local = Vec2::new(cos * x + sin * y, -sin * x + cos * y) * 2.0 / size;
for _ in 0..quarter_turns {
local = Vec2::new(local.y, -local.x);
}
if mirror_x {
local.x = -local.x;
}
if mirror_y {
local.y = -local.y;
}
value = value.max(pattern(tile, local, input));
}
}
if value <= 0.0 {
return None;
}
let mut luminance = 1.0 - tile.luminance_random * TileRandomStream::Luminance.draw(seed, index);
if tile.luminance_by_number {
luminance *= (number + 1) as f32 / total as f32;
}
if tile.luminance_by_scale {
luminance *= scale_factor;
}
Some(value * luminance)
}
/// Whether the masks hide tile (column, row), whose randoms are at `index`
fn hidden(tile: &TileGenerator, seed: u32, (column, row): (i32, i32), index: u32) -> bool {
let masked = (tile.checker_mask && (column + row).rem_euclid(2) == 1)
|| (tile.horizontal_mask && row.rem_euclid(2) == 1)
|| (tile.vertical_mask && column.rem_euclid(2) == 0)
|| (tile.random_mask > 0.0 && TileRandomStream::Mask.draw(seed, index) < tile.random_mask);
masked != tile.invert_mask
}
/// The tile's width and height on the plane before its scale, for a cell `cell` wide and high
fn tile_size(tile: &TileGenerator, seed: u32, index: u32, cell: Vec2) -> Vec2 {
match tile.size_mode {
TileSizeMode::NormalInterstice => {
let gap_x = tile.interstice[0] * (1.0 - tile.interstice_random[0] * TileRandomStream::IntersticeX.draw(seed, index));
let gap_y = tile.interstice[1] * (1.0 - tile.interstice_random[1] * TileRandomStream::IntersticeY.draw(seed, index));
cell * Vec2::new(1.0 - gap_x, 1.0 - gap_y)
}
TileSizeMode::NormalSize => cell * Vec2::from(tile.size),
TileSizeMode::KeepRatio => Vec2::splat(cell.x.min(cell.y)),
TileSizeMode::Absolute | TileSizeMode::Pixel => {
let size = if tile.size_mode == TileSizeMode::Absolute { Vec2::from(tile.size_absolute) } else { Vec2::from(tile.size_pixel) / PIXEL_REFERENCE };
let random_x = 1.0 - tile.size_random[0] * TileRandomStream::SizeX.draw(seed, index);
let random_y = 1.0 - tile.size_random[1] * TileRandomStream::SizeY.draw(seed, index);
size * Vec2::new(random_x, random_y)
}
}
}
/// The quarter turns clockwise of tile (column, row): the set ones, the quincunx pinwheel and the random ones
fn quarter_turns(tile: &TileGenerator, seed: u32, (column, row): (i32, i32), index: u32) -> u32 {
let mut turns = u32::from(tile.quarter_turns);
if tile.quincunx_flip {
turns += match (column.rem_euclid(2), row.rem_euclid(2)) {
(0, 0) => 0,
(1, 0) => 3,
(0, _) => 1,
_ => 2,
};
}
if tile.quarter_turn_random > 0.0 && TileRandomStream::QuarterTurnApplies.draw(seed, index) < tile.quarter_turn_random {
turns += (TileRandomStream::QuarterTurn.draw(seed, index) * 4.0) as u32;
}
turns % 4
}
/// How far, in cells along each axis, a tile's center can be from a texel its shape reaches: half its largest size turned, plus its random move and the shift of its center by the middle size
fn reach(tile: &TileGenerator, counts: Vec2) -> Vec2 {
let widest = Vec2::new(tile.middle_size[0].max(1.0 - tile.middle_size[0]), tile.middle_size[1].max(1.0 - tile.middle_size[1])) * 2.0;
let largest = match tile.size_mode {
TileSizeMode::NormalInterstice | TileSizeMode::KeepRatio => widest / counts,
TileSizeMode::NormalSize => widest / counts * Vec2::from(tile.size),
TileSizeMode::Absolute => Vec2::from(tile.size_absolute),
TileSizeMode::Pixel => Vec2::from(tile.size_pixel) / PIXEL_REFERENCE,
} * tile.scale;
let radius = largest.length() * 0.5 * counts;
let moved = Vec2::from(tile.position_random) * POSITION_RANDOM_CELLS;
let middle = Vec2::new((tile.middle_size[0] - 0.5).abs(), (tile.middle_size[1] - 0.5).abs());
radius + moved + middle
}
/// The cells along an axis of `count` whose centers can be within `reach` of `position` (in cells): each once, at most `count`
fn near(position: f32, reach: f32, count: i32) -> impl Iterator<Item = i32> {
let first = (position - reach - 0.5).floor();
let last = (position + reach - 0.5).ceil();
// A reach past the whole grid visits each cell once; float math keeps a hostile reach from overflowing
let span = (last - first + 1.0).min(count as f32).max(1.0) as i32;
let first = first as i32;
(first..first.saturating_add(span)).map(move |index| index.rem_euclid(count))
}
/// The shift along its line of line `line` (a row, or a column with a vertical offset), in cells
fn line_shift(tile: &TileGenerator, line: i32) -> f32 {
tile.offset * line as f32 + tile.offset_random * TileRandomStream::Offset.draw(tile.offset_random_seed, line as u32)
}
/// The pattern's value at `point` of its plane (one unit = the whole grid, repeating); `images` holds the images its inputs name
pub(crate) fn value(tile: &TileGenerator, point: Vec2, seed: u32, images: Option<&ImageStore>) -> f32 {
let image = |name: &str| images.and_then(|images| images.get(name)).map(|image| &**image);
let mut slots: [Option<&ImageRes>; TileGenerator::MAX_INPUTS] = [None; TileGenerator::MAX_INPUTS];
let count = tile.inputs.len().min(TileGenerator::MAX_INPUTS);
if tile.shape == TileShape::Image {
for (slot, name) in slots.iter_mut().zip(&tile.inputs) {
*slot = image(name);
}
}
let inputs = &slots[..count];
let background = tile.background_image.as_deref().and_then(image);
// Commands and saved projects keep the settings in range; the counts are guarded as they size the loops
let (columns, rows) = (tile.amount[0].clamp(1, *TileGenerator::AMOUNT.end()) as i32, tile.amount[1].clamp(1, *TileGenerator::AMOUNT.end()) as i32);
let counts = Vec2::new(columns as f32, rows as f32);
let point = Vec2::new(point.x.rem_euclid(1.0), point.y.rem_euclid(1.0));
let cell = (point - Vec2::from(tile.global_offset)) * counts;
let reach = reach(tile, counts);
let mut sum = 0.0f32;
let mut colored = 0.0f32;
let mut add = |value: f32| match tile.blending {
TileBlending::Max => {
sum = sum.max(value);
colored = colored.max(value * tile.color);
}
TileBlending::Add => {
sum += value;
colored += value * tile.color;
}
TileBlending::AddSub => {
sum += value;
colored += value * (2.0 * tile.color - 1.0);
}
};
// Each shifted line needs its own nearby tile search
if tile.vertical_offset {
for column in near(cell.x, reach.x, columns) {
for row in near(cell.y - line_shift(tile, column), reach.y, rows) {
if let Some(value) = tile_value(tile, seed, (column, row), (columns, rows), (point, inputs)) {
add(value);
}
}
}
} else {
for row in near(cell.y, reach.y, rows) {
for column in near(cell.x - line_shift(tile, row), reach.x, columns) {
if let Some(value) = tile_value(tile, seed, (column, row), (columns, rows), (point, inputs)) {
add(value);
}
}
}
}
let background = background.map_or(tile.background, |image| gray(image.sample(point.x, point.y)));
finish(tile, sum, colored, background)
}
/// The combined tiles over `background`, through the pattern's opacity and its position/contrast window
fn finish(tile: &TileGenerator, sum: f32, colored: f32, background: f32) -> f32 {
let alpha = sum.clamp(0.0, 1.0) * tile.opacity;
let color = colored.clamp(0.0, 1.0) * tile.opacity;
let value = (background * (1.0 - alpha) + color).clamp(0.0, 1.0);
let windowed = window(value, tile.position, tile.contrast);
// Out-of-range settings drawn as they are must not leave a non-number in the texture
if windowed.is_finite() { windowed } else { 0.0 }
}
/// The position/contrast window: position picks the input range stretched to 0..1 (0.5 keeps it), contrast narrows it around its middle
fn window(value: f32, position: f32, contrast: f32) -> f32 {
let low = (1.0 - 2.0 * position).clamp(0.0, 1.0);
let high = (2.0 - 2.0 * position).clamp(0.0, 1.0);
let middle = (low + high) * 0.5;
let half = (high - low) * 0.5 * (1.0 - contrast);
if half <= EPSILON {
return f32::from(u8::from(value >= middle));
}
((value - (middle - half)) / (2.0 * half)).clamp(0.0, 1.0)
}
#[cfg(test)]
mod tests {
use super::*;
fn at(tile: &TileGenerator, x: f32, y: f32) -> f32 {
value(tile, Vec2::new(x, y), 1, None)
}
#[test]
fn rotated_tiles_cover_the_repeat_boundary_once() {
let tile = TileGenerator {
shape: TileShape::Square,
amount: [1, 1],
size_mode: TileSizeMode::NormalSize,
size: [1.0, 0.1],
scale: 2.0,
rotation: 45.0,
blending: TileBlending::Add,
..TileGenerator::default()
};
assert!(at(&tile, 0.99, 0.01) > 0.99);
assert!(at(&tile, 0.99, 0.01) <= 1.0);
}
#[test]
fn overlapping_periodic_copies_contribute_one_tile_value() {
let tile = TileGenerator {
shape: TileShape::Square,
amount: [1, 1],
size_mode: TileSizeMode::NormalSize,
size: [1.0, 1.0],
scale: 2.0,
color: 0.4,
blending: TileBlending::Add,
..TileGenerator::default()
};
assert!((at(&tile, 0.5, 0.5) - 0.4).abs() < EPSILON);
}
/// Bell shapes peak only at their tile's center, so the brightest texel of a cell shows where its tile is
fn bells(amount: [u32; 2]) -> TileGenerator {
TileGenerator { shape: TileShape::Bell, amount, ..TileGenerator::default() }
}
#[test]
fn tile_centers_follow_the_amounts() {
let tile = bells([4, 2]);
// Cell (i, j) of a 4 × 2 grid is centered at ((i + 0.5) / 4, (j + 0.5) / 2)
for (x, y) in [(0.125, 0.25), (0.375, 0.75), (0.875, 0.25)] {
assert!(at(&tile, x, y) > 0.99, "a tile center at ({x}, {y})");
}
assert!(at(&tile, 0.25, 0.25) < 0.01, "the bells meet at zero between cells");
}
#[test]
fn the_offset_shifts_each_row_along_by_its_share_of_a_cell() {
let tile = TileGenerator { offset: 0.5, ..bells([4, 4]) };
// Row 0 stays; row 1 (y 0.375) moves half a cell (0.125) to the right
assert!(at(&tile, 0.125, 0.125) > 0.99);
assert!(at(&tile, 0.25, 0.375) > 0.99, "row 1's first tile is centered at x 0.25");
assert!(at(&tile, 0.125, 0.375) < 0.5);
let columns = TileGenerator { vertical_offset: true, ..tile };
assert!(at(&columns, 0.375, 0.25) > 0.99, "a vertical offset moves column 1 down instead");
}
#[test]
fn a_free_rotation_turns_the_shape_clockwise() {
// The half bell's bright side is to the left (−x); turned a quarter clockwise it is at the top
let tile = TileGenerator { shape: TileShape::HalfBell, specific: 1.0, amount: [1, 1], ..TileGenerator::default() };
assert!(at(&tile, 0.3, 0.5) > at(&tile, 0.7, 0.5));
let turned = TileGenerator { rotation: 90.0, ..tile };
assert!(at(&turned, 0.5, 0.3) > at(&turned, 0.5, 0.7), "the bright side moved from the left to the top");
}
/// Whether a disc of a 2 × 1 grid's first tile, centered at (0.25, 0.5), covers the point `right` and `down` of its center
fn first_disc_covers(tile: &TileGenerator, right: f32, down: f32) -> bool {
at(tile, 0.25 + right, 0.5 + down) > 0.5
}
#[test]
fn each_size_mode_sizes_the_shape_its_own_way() {
let discs = TileGenerator { shape: TileShape::Disc, amount: [2, 1], ..TileGenerator::default() };
assert!(first_disc_covers(&discs, 0.2, 0.0) && first_disc_covers(&discs, 0.0, 0.4), "without a gap the disc fills its 0.5 × 1 cell");
// Half the cell: 0.25 wide and 0.5 high, so the disc ends 0.125 right and 0.25 below its center
let halved = TileGenerator { size_mode: TileSizeMode::NormalSize, size: [0.5, 0.5], ..discs.clone() };
assert!(first_disc_covers(&halved, 0.1, 0.0) && !first_disc_covers(&halved, 0.15, 0.0));
assert!(first_disc_covers(&halved, 0.0, 0.2) && !first_disc_covers(&halved, 0.0, 0.3));
// The largest square of the cell is 0.5 wide and high, whatever the size is set to
let square = TileGenerator { size_mode: TileSizeMode::KeepRatio, ..halved.clone() };
assert!(first_disc_covers(&square, 0.2, 0.0) && first_disc_covers(&square, 0.0, 0.2) && !first_disc_covers(&square, 0.0, 0.3));
// A fifth of the pattern has the same extent in absolute and reference pixels
let absolute = TileGenerator { size_mode: TileSizeMode::Absolute, size_absolute: [0.2, 0.2], ..discs.clone() };
let pixel = TileGenerator { size_mode: TileSizeMode::Pixel, size_pixel: [0.2 * PIXEL_REFERENCE; 2], ..discs.clone() };
for sized in [&absolute, &pixel] {
assert!(first_disc_covers(sized, 0.08, 0.0) && !first_disc_covers(sized, 0.12, 0.0), "{:?}", sized.size_mode);
assert!(first_disc_covers(sized, 0.0, 0.08) && !first_disc_covers(sized, 0.0, 0.12), "{:?}", sized.size_mode);
}
}
#[test]
fn size_randomness_shrinks_shapes_sized_absolutely_or_in_pixels_only() {
// Sixteen texels across each of the 4 × 4 cells: enough for the covered count to move when the discs shrink
const SAMPLES_PER_SIDE: usize = 64;
let center = |sample: usize| (sample as f32 + 0.5) / SAMPLES_PER_SIDE as f32;
let covered = |tile: &TileGenerator| {
(0..SAMPLES_PER_SIDE).flat_map(|y| (0..SAMPLES_PER_SIDE).map(move |x| (x, y))).filter(|(x, y)| at(tile, center(*x), center(*y)) > 0.5).count()
};
let fifth = [0.2, 0.2];
let discs = TileGenerator {
shape: TileShape::Disc,
amount: [4, 4],
size: [0.8, 0.8],
size_absolute: fifth,
size_pixel: fifth.map(|share| share * PIXEL_REFERENCE),
..TileGenerator::default()
};
let random = TileGenerator { size_random: [1.0, 1.0], ..discs.clone() };
for mode in [TileSizeMode::NormalInterstice, TileSizeMode::NormalSize, TileSizeMode::KeepRatio] {
let (plain, random) = (TileGenerator { size_mode: mode, ..discs.clone() }, TileGenerator { size_mode: mode, ..random.clone() });
assert_eq!(covered(&plain), covered(&random), "{mode:?} ignores the size randomness");
}
for mode in [TileSizeMode::Absolute, TileSizeMode::Pixel] {
let (plain, random) = (TileGenerator { size_mode: mode, ..discs.clone() }, TileGenerator { size_mode: mode, ..random.clone() });
assert!(covered(&random) < covered(&plain), "{mode:?}: random sizes shrink the discs");
}
}
#[test]
fn masks_hide_their_rows_columns_and_checkers() {
let checker = TileGenerator { checker_mask: true, ..bells([2, 2]) };
assert!(at(&checker, 0.25, 0.25) > 0.99 && at(&checker, 0.75, 0.25) < 0.01, "odd (i + j) is hidden");
let rows = TileGenerator { horizontal_mask: true, ..bells([2, 2]) };
assert!(at(&rows, 0.25, 0.25) > 0.99 && at(&rows, 0.25, 0.75) < 0.01, "the horizontal mask hides odd rows");
let columns = TileGenerator { vertical_mask: true, ..bells([2, 2]) };
assert!(at(&columns, 0.25, 0.25) < 0.01 && at(&columns, 0.75, 0.25) > 0.99, "the vertical mask hides even columns");
let inverted = TileGenerator { invert_mask: true, ..columns };
assert!(at(&inverted, 0.25, 0.25) > 0.99, "invert mask shows what the masks hid");
}
#[test]
fn the_position_window_stretches_a_range_and_contrast_makes_a_step() {
assert_eq!(window(0.3, 0.5, 0.0), 0.3, "the middle position leaves the value");
assert_eq!(window(0.75, 0.25, 0.0), 0.5, "position 0.25 stretches 0.5..1 to 0..1");
assert_eq!(window(0.49, 0.5, 1.0), 0.0);
assert_eq!(window(0.51, 0.5, 1.0), 1.0, "full contrast cuts at the middle of the range");
}
#[test]
fn every_shape_stays_in_range_and_outside_its_square_is_empty() {
for shape_kind in TileShape::ALL {
for specific in [0.0, 0.5, 1.0] {
for step in 0..41 {
let u = step as f32 / 20.0 - 1.0;
let value = shape(shape_kind, u, u * 0.7, specific);
assert!((0.0..=1.0 + 1e-5).contains(&value), "{shape_kind:?} at {u}: {value}");
}
assert_eq!(shape(shape_kind, 1.2, 0.0, specific), 0.0);
}
}
}
/// An image `size` texels wide whose left half is `left` and right half `right`
fn halves(left: f32, right: f32) -> std::sync::Arc<ImageRes> {
let size = 8;
let rgba = (0..size * size).map(|texel| if texel % size < size / 2 { [left, left, left, 1.0] } else { [right, right, right, 1.0] }).collect();
std::sync::Arc::new(ImageRes { width: size as u32, height: size as u32, rgba, srgb: false })
}
#[test]
fn the_image_shape_draws_its_inputs_in_turn_by_pattern_number() {
let images: ImageStore = [("dark".to_string(), halves(0.2, 0.2)), ("bright".to_string(), halves(0.9, 0.9))].into();
let tile = TileGenerator {
shape: TileShape::Image,
amount: [2, 1],
inputs: vec!["dark".into(), "bright".into()],
input_distribution: TileInputDistribution::ByNumber,
..TileGenerator::default()
};
// Tile 0 (left) draws the first input, tile 1 the second
let left = value(&tile, Vec2::new(0.25, 0.5), 1, Some(&images));
let right = value(&tile, Vec2::new(0.75, 0.5), 1, Some(&images));
assert!((left - 0.2).abs() < 0.01 && (right - 0.9).abs() < 0.01, "{left} {right}");
assert_eq!(value(&tile, Vec2::new(0.25, 0.5), 1, None), 0.0, "missing images draw nothing");
}
#[test]
fn an_image_input_keeps_its_orientation_in_the_tile() {
let images: ImageStore = [("halves".to_string(), halves(0.0, 1.0))].into();
let tile = TileGenerator { shape: TileShape::Image, amount: [1, 1], inputs: vec!["halves".into()], ..TileGenerator::default() };
assert!(value(&tile, Vec2::new(0.3, 0.5), 1, Some(&images)) < 0.05, "the image's left half is on the tile's left");
assert!(value(&tile, Vec2::new(0.7, 0.5), 1, Some(&images)) > 0.95);
}
#[test]
fn the_background_image_shows_between_the_shapes() {
let images: ImageStore = [("ground".to_string(), halves(0.4, 0.4))].into();
let tile = TileGenerator { background_image: Some("ground".into()), interstice: [0.5, 0.5], ..bells([2, 2]) };
// Between the bells only the background is left
assert!((value(&tile, Vec2::new(0.0, 0.0), 1, Some(&images)) - 0.4).abs() < 0.01);
assert_eq!(value(&tile, Vec2::new(0.0, 0.0), 1, None), 0.0, "without the image the background value stays");
}
#[test]
fn hostile_settings_neither_crash_nor_leave_the_range() {
let hostile = TileGenerator {
amount: [0, u32::MAX],
scale: f32::INFINITY,
size_mode: TileSizeMode::Pixel,
size_pixel: [f32::NAN, 1e30],
position_random: [1.0, 1.0],
offset: f32::NAN,
middle_size: [0.0, 1.0],
..TileGenerator::default()
};
for step in 0..20 {
let value = at(&hostile, step as f32 * 0.37, -(step as f32) * 1.3);
assert!((0.0..=1.0).contains(&value));
}
}
}
+85
View File
@@ -0,0 +1,85 @@
//! The random streams of a Tile Generator
/// The random streams of a Tile Generator, so the randoms of one tile are independent of each other
#[derive(Clone, Copy)]
pub(crate) enum TileRandomStream {
Luminance = 0,
Scale,
Offset,
PositionX,
PositionY,
Rotation,
QuarterTurn,
QuarterTurnApplies,
MirrorX,
MirrorY,
Mask,
SizeX,
SizeY,
IntersticeX,
IntersticeY,
Input,
}
/// Odd multipliers spreading the seed, the stream and the index over the hash, and its start (the golden ratio's and xxHash32's primes)
const SEED_MIX: u32 = 0x9E37_79B1;
const STREAM_MIX: u32 = 0x85EB_CA77;
const INDEX_MIX: u32 = 0xC2B2_AE3D;
const HASH_START: u32 = 0x27D4_EB2F;
/// The finalizer's multipliers ("lowbias32", an integer hash whose output bits all depend on every input bit) and its rounds
const FINALIZER_MIX_A: u32 = 0x7FEB_352D;
const FINALIZER_MIX_B: u32 = 0x846C_A68B;
const FINALIZER_ROUNDS: usize = 3;
/// The bits a draw keeps: an f32's precision, so every value is exact and below 1
const DRAW_BITS: u32 = 24;
impl TileRandomStream {
/// A uniform value in 0..1 per (seed, stream, index): an integer hash, so a tile's randoms do not depend on evaluation order
pub(crate) fn draw(self, seed: u32, index: u32) -> f32 {
let mut hash = seed
.wrapping_mul(SEED_MIX)
.wrapping_add((self as u32).wrapping_mul(STREAM_MIX))
.wrapping_add(index.wrapping_mul(INDEX_MIX))
.wrapping_add(HASH_START);
for _ in 0..FINALIZER_ROUNDS {
hash ^= hash >> 16;
hash = hash.wrapping_mul(FINALIZER_MIX_A);
hash ^= hash >> 15;
hash = hash.wrapping_mul(FINALIZER_MIX_B);
hash ^= hash >> 16;
}
(hash >> (u32::BITS - DRAW_BITS)) as f32 / (1u32 << DRAW_BITS) as f32
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A draw keeps 24 bits, so `bits / 2^24` is the value exactly
fn exact(bits: u32) -> f32 {
bits as f32 / (1u32 << DRAW_BITS) as f32
}
/// Saved projects keep only the seed and the settings, so a changed draw would move the tiles of existing textures
#[test]
fn draws_stay_the_values_saved_projects_were_made_with() {
assert_eq!(TileRandomStream::Luminance.draw(0, 0), exact(6_969_297));
assert_eq!(TileRandomStream::Rotation.draw(1, 7), exact(11_123_133));
assert_eq!(TileRandomStream::Input.draw(u32::MAX, u32::MAX), exact(6_943_220));
}
#[test]
fn draws_are_below_one_and_differ_by_seed_stream_and_index() {
let first = TileRandomStream::Scale.draw(3, 5);
assert_eq!(first, TileRandomStream::Scale.draw(3, 5), "the same seed, stream and index draw the same value");
assert_ne!(first, TileRandomStream::Scale.draw(4, 5));
assert_ne!(first, TileRandomStream::Offset.draw(3, 5));
assert_ne!(first, TileRandomStream::Scale.draw(3, 6));
for index in 0..1000 {
let value = TileRandomStream::Mask.draw(index, index);
assert!((0.0..1.0).contains(&value), "draw {index} is {value}");
}
}
}
+59 -12
View File
@@ -31,7 +31,7 @@ fn fixture() -> Fixture {
}
fn procedural(kind: ProceduralKind, low: f32, high: f32) -> Source {
Source::Procedural { pattern: Procedural::new(kind), low: [low; 3], high: [high; 3] }
Source::Procedural { pattern: Procedural::new(kind), low: [low; 3], high: [high; 3], ramp: Vec::new() }
}
fn add(f: &mut Fixture, ts: usize, kind: LayerKind, mask: Option<Mask>) -> LayerId {
@@ -196,11 +196,11 @@ fn instances_draw_their_source_across_texture_sets() {
#[test]
fn mask_with_height_follows_the_layer_height() {
let mut f = fixture();
// A white layer over the default gray, half masked, its height falling from 0.25 (left) to
// -0.25 (right).
// Half masking makes the height fall from 0.25 at left to -0.25 at right
let mut ramp = Procedural::new(ProceduralKind::Gradient);
ramp.scale = 1.0;
let height = Source::Procedural { pattern: ramp, low: [0.25; 3], high: [-0.25; 3] };
let height = Source::Procedural { pattern: ramp, low: [0.25; 3], high: [-0.25; 3], ramp: Vec::new() };
let id = add(&mut f, 0, fill(&[(Channel::BaseColor, Source::Uniform([1.0; 3])), (Channel::Height, height)]), None);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(effect(&mut f, EffectKind::Fill { source: Source::Uniform([0.5; 3]), projection: Projection::default() }));
@@ -214,7 +214,8 @@ fn mask_with_height_follows_the_layer_height() {
assert!((v(&plain, left) - 0.75).abs() < 0.01 && (v(&plain, right) - 0.75).abs() < 0.01, "plain mask: 50 % white over gray");
assert!(v(&hm, left) > 0.84, "high parts show first: {}", v(&hm, left));
assert!(v(&hm, right) < 0.66, "low parts later: {}", v(&hm, right));
// Without a mask there is nothing to combine.
// Without a mask there is nothing to combine
f.project.layer_mut(id).unwrap().mask.as_mut().unwrap().enabled = false;
assert!((v(&reference(&f, 0), left) - 1.0).abs() < 1e-3);
}
@@ -332,6 +333,7 @@ fn stroke(target: LayerId) -> StrokePreview {
mask_value: 1.0,
stencil: None,
carried: BTreeMap::new(),
carried_mask: None,
}
}
@@ -406,9 +408,10 @@ fn anchor_readers_fall_back_to_full_evaluation() {
let mut f = fixture();
let n = nested_stack(&mut f);
let anchor = effect(&mut f, EffectKind::Anchor);
let source = Source::Anchor { anchor: anchor.id, channel: Channel::Height };
let source = Source::Anchor { anchor: anchor.id, channel: Channel::Height, ramp: Vec::new() };
f.project.layer_mut(n.base).unwrap().content_effects.push(anchor);
// A mask above the hot layer reads the stack below it.
// A mask above the hot layer reads the stack below it
let reader = effect(&mut f, EffectKind::Fill { source, projection: Projection::default() });
f.project.layer_mut(n.g2_above).unwrap().mask.as_mut().unwrap().effects.push(reader);
for hot in [n.deep, n.top] {
@@ -512,21 +515,25 @@ fn anchors_inside_a_content_stack_record_the_content_up_to_them() {
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.
// 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.
// 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);
let reader = add(&mut f, 0, fill(&[(c, Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() })]), 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.
// 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.
// 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);
@@ -742,6 +749,46 @@ fn a_live_stroke_releases_the_fields_kept_before_it_started() {
assert!(live == run_with(&fixture, 0, &all, None, Some(&preview)), "a stroke that starts during a sliced pass differs");
}
#[test]
fn cached_stack_tracks_the_images_a_tile_generator_reads() {
use std::sync::Arc;
use texturecraft_compose::{ImageRes, ImageStore};
let mut fixture = fixture();
let hot_layer = heavy_stack(&mut fixture);
let bottom_layer = fixture.project.texture_sets[0].stack[0];
let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(bottom_layer).unwrap().kind else { panic!("expected fill") };
let mut pattern = Procedural::new(ProceduralKind::TileGenerator);
pattern.tile.get_or_insert_with(Box::default).background_image = Some("plate".into());
fill.sources.insert(Channel::Roughness, Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() });
let image_with_value = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false });
let mut images = ImageStore::default();
let baked = Default::default();
let tiles = all_tiles(RES, RES);
let mut cache = BelowCache::default();
cache.set_hot(Some(hot_layer));
let mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
for (stage, background) in [("cold", None), ("added", Some(1.0)), ("replaced", Some(0.4))] {
if let Some(value) = background {
images.insert("plate".into(), image_with_value(value));
}
fixture.pixels.layer_mut(hot_layer, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]);
let input = inputs(&fixture, 0, &images, &baked);
composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache));
assert!(!cache.is_empty(), "{stage}: first tile should be cached");
let retained = cache.len() - 1;
composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache));
assert_eq!(retained, 0, "{stage}: the layers below are drawn again with the new image");
let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
composite_tiles(&input, &mut expected, &tiles);
assert!(output == expected, "{stage}");
}
}
#[test]
fn cached_stack_tracks_referenced_images_only() {
use std::sync::Arc;
+196 -14
View File
@@ -8,17 +8,33 @@ use crate::{BakedMap, BlendMode, Channel, ChannelKind, lum};
mod curvature_detail;
mod curvature_mode;
mod decal_flip;
mod decal_symmetry;
mod generator_global;
mod micro_detail;
mod output_resolution;
mod resolution_mode;
mod tile_blending;
mod tile_generator;
mod tile_input_distribution;
mod tile_shape;
mod tile_size_mode;
mod tile_symmetry;
pub use curvature_detail::CurvatureDetail;
pub use curvature_mode::CurvatureMode;
pub use decal_flip::DecalFlip;
pub use decal_symmetry::DecalSymmetry;
pub use generator_global::GeneratorGlobal;
pub use micro_detail::MicroDetail;
pub use output_resolution::OutputResolution;
pub use resolution_mode::ResolutionMode;
pub use tile_blending::TileBlending;
pub use tile_generator::TileGenerator;
pub use tile_input_distribution::TileInputDistribution;
pub use tile_shape::TileShape;
pub use tile_size_mode::TileSizeMode;
pub use tile_symmetry::TileSymmetry;
/// Id of a layer or effect (one id space per project).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
@@ -192,6 +208,18 @@ pub struct Decal {
pub offset: [f32; 2],
/// How far in front of and behind the frame the decal reaches (world units).
pub depth: f32,
/// A mirrored copy of the decal on the other side of the mesh (None: no copy). The copy
/// follows this frame, so moving, scaling or turning the decal moves it too.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub symmetry: Option<DecalSymmetry>,
/// Mirror the image inside the frame: left to right (`[0]`), top to bottom (`[1]`). Old projects have neither.
#[serde(default, skip_serializing_if = "not_flipped")]
pub flip: [bool; 2],
}
/// Serde helper: a decal that mirrors nothing saves without the field
fn not_flipped(flip: &[bool; 2]) -> bool {
!flip[0] && !flip[1]
}
impl Default for Projection {
@@ -262,10 +290,12 @@ pub enum ProceduralKind {
Pores,
/// Sharp-edged paint chips.
Chips,
/// Shapes laid out in a grid of tiles, with the settings in [`Procedural::tile`]
TileGenerator,
}
impl ProceduralKind {
pub const ALL: [ProceduralKind; 23] = [
pub const ALL: [ProceduralKind; 24] = [
ProceduralKind::Clouds,
ProceduralKind::Perlin,
ProceduralKind::Noise,
@@ -289,6 +319,7 @@ impl ProceduralKind {
ProceduralKind::Smudges,
ProceduralKind::Pores,
ProceduralKind::Chips,
ProceduralKind::TileGenerator,
];
pub fn label(self) -> &'static str {
match self {
@@ -315,6 +346,7 @@ impl ProceduralKind {
ProceduralKind::Smudges => "Fingerprints",
ProceduralKind::Pores => "Pores",
ProceduralKind::Chips => "Paint chips",
ProceduralKind::TileGenerator => "Tile Generator",
}
}
pub fn parse(s: &str) -> Option<ProceduralKind> {
@@ -335,11 +367,34 @@ pub struct Procedural {
/// Shifts the pattern brighter (+) or darker (−).
pub balance: f32,
pub invert: bool,
/// The Tile Generator's settings; `None` for other kinds (and reads as the defaults); loaded in range, as drawing trusts them
#[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "tile_in_range")]
pub tile: Option<Box<TileGenerator>>,
/// The resolution the pattern is computed at before it is sampled onto the texture set
#[serde(default, skip_serializing_if = "OutputResolution::is_default")]
pub resolution: OutputResolution,
}
/// Saved Tile Generator settings brought into range (a saved project is hostile input)
fn tile_in_range<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<Box<TileGenerator>>, D::Error> {
let saved: Option<Box<TileGenerator>> = Deserialize::deserialize(deserializer)?;
Ok(saved.map(|tile| Box::new(tile.clamped())))
}
impl Procedural {
/// The scales a command accepts (repeats per projection unit)
pub const MIN_SCALE: f32 = 0.001;
pub const MAX_SCALE: f32 = 1000.0;
/// The strongest contrast a command accepts, and the furthest balance either way
pub const MAX_CONTRAST: f32 = 20.0;
pub const MAX_BALANCE: f32 = 1.0;
pub fn new(kind: ProceduralKind) -> Procedural {
Procedural { kind, scale: 4.0, seed: 1, contrast: 1.0, balance: 0.0, invert: false }
let tile = (kind == ProceduralKind::TileGenerator).then(Box::default);
// The Tile Generator lays its whole grid over one projection unit, as its tile counts set its frequency
let scale = if tile.is_some() { 1.0 } else { 4.0 };
Procedural { kind, scale, seed: 1, contrast: 1.0, balance: 0.0, invert: false, tile, resolution: OutputResolution::default() }
}
}
@@ -348,8 +403,15 @@ impl Procedural {
pub enum Source {
/// A constant value (linear RGB for colors; `[v, v, v]` for scalars).
Uniform([f32; 3]),
/// A procedural pattern mixing two values.
Procedural { pattern: Procedural, low: [f32; 3], high: [f32; 3] },
/// A procedural pattern mixing two values, or on a color channel colored by `ramp` when it
/// has stops (a gradient map: dark to light through evenly spaced linear RGB colors).
Procedural {
pattern: Procedural,
low: [f32; 3],
high: [f32; 3],
#[serde(default, skip_serializing_if = "Vec::is_empty")]
ramp: Vec<[f32; 3]>,
},
/// An imported image resource, by name. `normal_format` is the convention of a normal map
/// image (DirectX images have their green flipped where a normal channel samples them).
Image {
@@ -358,8 +420,14 @@ pub enum Source {
normal_format: crate::NormalFormat,
},
/// The stack value recorded by an anchor point effect (`anchor` is the effect id) for
/// `channel`; colors read as gray where a scalar is needed.
Anchor { anchor: LayerId, channel: Channel },
/// `channel`; colors read as gray where a scalar is needed. On a color channel a `ramp` with
/// stops recolors the value by its lightness (a gradient map).
Anchor {
anchor: LayerId,
channel: Channel,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
ramp: Vec<[f32; 3]>,
},
}
impl Source {
@@ -372,6 +440,23 @@ impl Source {
Source::Image { name: name.into(), normal_format: crate::NormalFormat::OpenGl }
}
/// The image resources this source reads: its image, or the images of a Tile Generator pattern
pub fn images(&self) -> Vec<&str> {
match self {
Source::Image { name, .. } => vec![name.as_str()],
Source::Procedural { pattern, .. } => pattern.tile.iter().flat_map(|tile| tile.images()).collect(),
Source::Uniform(_) | Source::Anchor { .. } => Vec::new(),
}
}
/// The gradient map stops of a procedural or anchor source (empty: none).
pub fn ramp(&self) -> &[[f32; 3]] {
match self {
Source::Procedural { ramp, .. } | Source::Anchor { ramp, .. } => ramp,
_ => &[],
}
}
/// The anchor point this source reads, if any.
pub fn anchor(&self) -> Option<LayerId> {
match self {
@@ -1045,6 +1130,10 @@ pub enum EffectKind {
pub struct PathShape {
/// Surface positions (3D view) or texture coordinates with z = 0 (2D view).
pub points: Vec<[f32; 3]>,
/// Per point: the curve turns sharply there instead of passing smoothly through. Empty (and absent from old
/// projects) when every point is smooth; a missing entry is smooth too.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub corners: Vec<bool>,
pub uv: bool,
pub closed: bool,
/// A closed path fills its interior instead of stroking the curve.
@@ -1114,7 +1203,7 @@ impl EffectKind {
let mut anchors: Vec<_> = sources
.into_iter()
.filter_map(|source| match source {
Source::Anchor { anchor, channel } => Some((*anchor, *channel)),
Source::Anchor { anchor, channel, .. } => Some((*anchor, *channel)),
_ => None,
})
.collect();
@@ -1126,7 +1215,7 @@ impl EffectKind {
anchors
}
/// The image resources this effect's sources read (a fill, material or generator input).
/// The image resources this effect's sources read (a fill, its patterns, a material or a generator input)
pub fn images_read(&self) -> impl Iterator<Item = &str> {
let sources: Vec<&Source> = match self {
EffectKind::Fill { source, .. } => vec![source],
@@ -1134,10 +1223,7 @@ impl EffectKind {
EffectKind::Generator(generator) => generator.inputs.values().collect(),
_ => Vec::new(),
};
sources.into_iter().filter_map(|source| match source {
Source::Image { name, .. } => Some(name.as_str()),
_ => None,
})
sources.into_iter().flat_map(Source::images)
}
}
@@ -1164,7 +1250,7 @@ pub struct Effect {
impl Effect {
pub fn new(id: LayerId, kind: EffectKind) -> Effect {
// Generators and fills that build a mask usually add on top of the background.
// Generators and fills that build a mask usually add on top of the background
Effect { id, name: kind.name().to_string(), visible: true, kind, blend: BlendMode::Normal, opacity: 1.0 }
}
}
@@ -1173,6 +1259,27 @@ impl Effect {
mod tests {
use super::*;
#[test]
fn a_decal_saved_without_symmetry_loads_unchanged_and_saves_without_it() {
let old = r#"{"center":[0.0,0.0,1.0],"normal":[0.0,0.0,1.0],"up":[0.0,1.0,0.0],"size":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0],"depth":0.5}"#;
let decal: Decal = serde_json::from_str(old).unwrap();
assert_eq!(decal.symmetry, None);
assert_eq!(serde_json::to_string(&decal).unwrap(), old.replace(' ', ""), "nothing new is written for a decal without a copy");
let mirrored = Decal { symmetry: Some(DecalSymmetry { axis: 2, flip: DecalFlip::V, offset: 0.0 }), ..decal };
let json = serde_json::to_string(&mirrored).unwrap();
assert!(json.contains(r#""symmetry":{"axis":2,"flip":"v"}"#), "{json}");
assert_eq!(serde_json::from_str::<Decal>(&json).unwrap(), mirrored);
let without_flip = json.replace(r#","flip":"v""#, "");
assert_eq!(serde_json::from_str::<Decal>(&without_flip).unwrap().symmetry, Some(DecalSymmetry { axis: 2, flip: DecalFlip::None, offset: 0.0 }));
// The plane's offset is written only when it is not zero
let moved = Decal { symmetry: Some(DecalSymmetry { axis: 1, flip: DecalFlip::None, offset: -0.25 }), ..decal };
let json = serde_json::to_string(&moved).unwrap();
assert!(json.contains(r#""offset":-0.25}"#), "{json}");
assert_eq!(serde_json::from_str::<Decal>(&json).unwrap(), moved);
}
#[test]
fn material_effect_images_are_reported_as_used() {
let mut fill = Fill::default();
@@ -1206,6 +1313,42 @@ mod tests {
}
}
#[test]
fn patterns_saved_before_tile_settings_keep_their_form() {
let saved = serde_json::json!({"kind": "Clouds", "scale": 4.0, "seed": 1, "contrast": 1.0, "balance": 0.0, "invert": false});
let loaded: Procedural = serde_json::from_value(saved.clone()).unwrap();
assert_eq!(loaded, Procedural::new(ProceduralKind::Clouds));
assert_eq!(serde_json::to_value(&loaded).unwrap(), saved, "a pattern at its defaults saves as before");
let tile = serde_json::to_value(Procedural::new(ProceduralKind::TileGenerator)).unwrap();
assert!(
tile.get("tile").is_some() && tile.get("resolution").is_none(),
"only the Tile Generator carries tile settings, and a default resolution is not saved"
);
}
#[test]
fn tile_settings_saved_with_missing_or_hostile_values_load_in_range() {
let tile = serde_json::json!({"amount": [0, 4000], "specific": 7.0, "quarter_turns": 6, "inputs": ["a", "b", "c", "d", "e", "f", "g"]});
let saved = serde_json::json!({"kind": "TileGenerator", "scale": 1.0, "seed": 1, "contrast": 1.0, "balance": 0.0, "invert": false, "tile": tile});
let loaded: Procedural = serde_json::from_value(saved).unwrap();
let tile = loaded.tile.unwrap();
assert_eq!(tile.amount, [1, 64]);
assert_eq!(tile.specific, 1.0);
assert_eq!(tile.quarter_turns, 2);
assert_eq!(tile.inputs.len(), TileGenerator::MAX_INPUTS);
assert_eq!(tile.middle_size, TileGenerator::default().middle_size, "a missing setting reads its default");
let not_finite = TileGenerator { scale: f32::NAN, rotation: f32::INFINITY, ..TileGenerator::default() }.clamped();
assert_eq!((not_finite.scale, not_finite.rotation), (1.0, 0.0));
}
#[test]
fn curvature_generators_saved_before_detail_sizes_load_without_them() {
let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap();
@@ -1296,6 +1439,29 @@ mod tests {
assert!(nan.point(c, [0.5; 3]).unwrap().iter().all(|v| v.is_finite()));
}
#[test]
fn gradient_map_stops_round_trip_and_sources_without_them_save_as_before() {
let ramp = vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]];
let procedural = |ramp: Vec<[f32; 3]>| Source::Procedural { pattern: Procedural::new(ProceduralKind::Clouds), low: [0.25; 3], high: [0.75; 3], ramp };
let anchor = |ramp: Vec<[f32; 3]>| Source::Anchor { anchor: LayerId(7), channel: Channel::BaseColor, ramp };
for source in [procedural(ramp.clone()), anchor(ramp.clone())] {
let json = serde_json::to_value(&source).unwrap();
assert!(json.to_string().contains("\"ramp\""), "{json}");
assert_eq!(serde_json::from_value::<Source>(json).unwrap(), source);
assert_eq!(source.ramp(), ramp.as_slice());
}
// Empty ramps preserve older projects' JSON shape
let old_procedural = serde_json::json!({"Procedural": {"pattern": serde_json::to_value(Procedural::new(ProceduralKind::Clouds)).unwrap(), "low": [0.25, 0.25, 0.25], "high": [0.75, 0.75, 0.75]}});
let old_anchor = serde_json::json!({"Anchor": {"anchor": 7, "channel": "BaseColor"}});
for (old, source) in [(old_procedural, procedural(Vec::new())), (old_anchor, anchor(Vec::new()))] {
assert_eq!(serde_json::to_value(&source).unwrap(), old);
assert_eq!(serde_json::from_value::<Source>(old).unwrap(), source);
assert!(source.ramp().is_empty());
}
assert!(Source::Uniform([0.5; 3]).ramp().is_empty());
}
#[test]
fn effect_targets_and_anchor_reads() {
assert_eq!(EffectKind::Anchor.content_only(), None, "anchors go on content and masks");
@@ -1303,7 +1469,7 @@ mod tests {
assert_eq!(EffectKind::Filter(Filter::Invert).content_only(), None);
let mut fill_layer = Layer::new(LayerId(1), "l", LayerKind::Paint, &[Channel::BaseColor]);
assert!(!fill_layer.reads_anchor());
let source = Source::Anchor { anchor: LayerId(9), channel: Channel::Height };
let source = Source::Anchor { anchor: LayerId(9), channel: Channel::Height, ramp: Vec::new() };
fill_layer.mask = Some(Mask {
effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default() })],
..Mask::new(MaskBackground::Black)
@@ -1336,6 +1502,22 @@ mod tests {
assert_eq!(hm.apply(0.5, f32::NAN), 0.5);
}
#[test]
fn old_decals_load_unflipped_and_save_unchanged() {
let old = r#"{"center":[0.0,0.0,0.0],"normal":[0.0,0.0,1.0],"up":[0.0,1.0,0.0],"size":[1.0,2.0],"rotation":0.0,"offset":[0.0,0.0],"depth":0.5}"#;
let decal: Decal = serde_json::from_str(old).unwrap();
assert_eq!(decal.flip, [false, false]);
assert_eq!(
serde_json::from_str::<serde_json::Value>(&serde_json::to_string(&decal).unwrap()).unwrap(),
serde_json::from_str::<serde_json::Value>(old).unwrap()
);
let flipped = Decal { flip: [true, false], ..decal };
let saved = serde_json::to_string(&flipped).unwrap();
assert!(saved.contains(r#""flip":[true,false]"#), "{saved}");
assert_eq!(serde_json::from_str::<Decal>(&saved).unwrap(), flipped);
}
#[test]
fn generator_kinds_parse() {
for k in GeneratorKind::ALL {
+14
View File
@@ -0,0 +1,14 @@
use serde::{Deserialize, Serialize};
/// How the mirrored decal's image is turned over
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DecalFlip {
/// Only the reflection: the copy is the decal's mirror image
#[default]
None,
/// The image's left and right swapped
U,
/// The image's top and bottom swapped
V,
}
+26
View File
@@ -0,0 +1,26 @@
use serde::{Deserialize, Deserializer, Serialize};
use super::DecalFlip;
/// The mirrored copy of a decal: reflected through the plane perpendicular to `axis`, across the mesh center (moved by `offset`)
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct DecalSymmetry {
/// Axis the mirror plane is perpendicular to (0 = X, 1 = Y, 2 = Z)
#[serde(deserialize_with = "deserialize_axis")]
pub axis: u8,
/// Extra flip of the image on the mirrored copy, on top of the reflection itself
#[serde(default)]
pub flip: DecalFlip,
/// Where the mirror plane sits, relative to the mesh center along `axis` (world units, as the brush symmetry's offset)
#[serde(default, skip_serializing_if = "is_zero")]
pub offset: f32,
}
fn deserialize_axis<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u8, D::Error> {
// Recover malformed projects with the same Z plane used by the renderer
Ok(u8::deserialize(deserializer)?.min(2))
}
fn is_zero(value: &f32) -> bool {
*value == 0.0
}
+23
View File
@@ -0,0 +1,23 @@
use serde::{Deserialize, Serialize};
/// How a Tile Generator combines shapes that overlap
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TileBlending {
#[default]
Add,
Max,
/// Adds bright shapes and subtracts dark ones
AddSub,
}
impl TileBlending {
pub const ALL: [TileBlending; 3] = [TileBlending::Add, TileBlending::Max, TileBlending::AddSub];
pub fn label(self) -> &'static str {
match self {
TileBlending::Add => "Add",
TileBlending::Max => "Max",
TileBlending::AddSub => "Add sub",
}
}
}
+265
View File
@@ -0,0 +1,265 @@
use serde::{Deserialize, Serialize};
use super::tile_blending::TileBlending;
use super::tile_input_distribution::TileInputDistribution;
use super::tile_shape::TileShape;
use super::tile_size_mode::TileSizeMode;
use super::tile_symmetry::TileSymmetry;
/// The settings of a Tile Generator pattern: shapes laid out in a grid of tiles, in the reference app's sections (pattern, size, position, rotation, color); pairs are `[horizontal, vertical]`; angles are in degrees; the seeds of the random settings are separate from the pattern's seed, as in the reference app
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct TileGenerator {
/// The level the output is cut at (0.5 leaves it unchanged)
pub position: f32,
/// How sharply the output is cut at [`TileGenerator::position`] (0 unchanged, 1 a hard step)
pub contrast: f32,
/// Tiles across and down
pub amount: [u32; 2],
/// The reference app's Non Square Expansion, kept with the settings: its outputs match with it on and off, so drawing ignores it
pub non_square_expansion: bool,
pub shape: TileShape,
/// Texels per side the shape is drawn at before it is laid out
pub shape_resolution: [u32; 2],
/// Changes the shape in its own way (roundness, falloff, ripple count…)
pub specific: f32,
pub shape_angle: f32,
pub shape_scale: f32,
pub shape_size: [f32; 2],
/// Repeats of the shape inside each tile
pub shape_tiling: u32,
/// Turns the shape 45 degrees
pub shape_diagonal: bool,
/// As [`TileGenerator::non_square_expansion`], for the shape itself
pub shape_non_square_expansion: bool,
/// Input images, read when [`TileGenerator::shape`] is [`TileShape::Image`]
pub inputs: Vec<String>,
pub input_distribution: TileInputDistribution,
/// Quarter turns of every shape (0 to 3)
pub quarter_turns: u8,
/// The share of shapes turned by a random number of quarter turns
pub quarter_turn_random: f32,
/// Turns every other shape a quarter turn
pub quincunx_flip: bool,
/// The share of shapes mirrored
pub symmetry_random: f32,
pub symmetry: TileSymmetry,
pub size_mode: TileSizeMode,
/// Where the boundary between alternating columns (rows) falls; 0.5 makes them equal
pub middle_size: [f32; 2],
/// The gap between shapes, in [`TileSizeMode::NormalInterstice`]
pub interstice: [f32; 2],
pub interstice_random: [f32; 2],
/// The shape's size as a share of its cell, in [`TileSizeMode::NormalSize`]
pub size: [f32; 2],
/// The shape's size as a share of the pattern, in [`TileSizeMode::Absolute`]
pub size_absolute: [f32; 2],
/// The shape's size in pixels, in [`TileSizeMode::Pixel`]
pub size_pixel: [f32; 2],
/// How much each shape's size shrinks at random, in [`TileSizeMode::Absolute`] and [`TileSizeMode::Pixel`]
pub size_random: [f32; 2],
pub scale: f32,
pub scale_random: f32,
pub scale_random_seed: u32,
/// Shift of each row (column) from the one before, as a share of a tile
pub offset: f32,
pub offset_random: f32,
pub offset_random_seed: u32,
/// Shifts columns instead of rows
pub vertical_offset: bool,
pub position_random: [f32; 2],
pub global_offset: [f32; 2],
pub rotation: f32,
pub rotation_random: f32,
/// The shapes' brightness
pub color: f32,
pub luminance_random: f32,
/// Brightness rises tile after tile
pub luminance_by_number: bool,
/// Bigger shapes are brighter
pub luminance_by_scale: bool,
/// Hides every other tile
pub checker_mask: bool,
/// Hides the odd rows
pub horizontal_mask: bool,
/// Hides the even columns
pub vertical_mask: bool,
/// The share of tiles hidden at random
pub random_mask: f32,
/// Shows the hidden tiles instead
pub invert_mask: bool,
pub blending: TileBlending,
pub background: f32,
/// An image under the shapes instead of [`TileGenerator::background`]
pub background_image: Option<String>,
pub opacity: f32,
/// Gives tile n the randoms of the last tile but n (the reference app's Reverse Rendering Order: its blendings don't depend on order)
pub reverse_order: bool,
}
impl TileGenerator {
/// Tiles per side: the reference app's slider range
pub const AMOUNT: std::ops::RangeInclusive<u32> = 1..=64;
/// Shape resolutions offered (the reference app's 256 to 4096)
pub const SHAPE_RESOLUTIONS: [u32; 5] = [256, 512, 1024, 2048, 4096];
pub const SHAPE_TILING: std::ops::RangeInclusive<u32> = 1..=16;
pub const MAX_SCALE: f32 = 2.0;
pub const MAX_RANDOM_SEED: u32 = 1000;
/// The largest shape in the pixel size mode: the largest shape resolution
pub const MAX_SIZE_PIXELS: f32 = 4096.0;
/// Input images a pattern reads
pub const MAX_INPUTS: usize = 6;
pub fn is_default(&self) -> bool {
*self == TileGenerator::default()
}
/// The settings inside their ranges, with non-finite numbers at their defaults (saved projects and commands are hostile input)
pub fn clamped(&self) -> TileGenerator {
TileGenerator {
inputs: self.inputs.iter().take(TileGenerator::MAX_INPUTS).cloned().collect(),
background_image: self.background_image.clone(),
..self.clamped_numbers()
}
}
/// [`TileGenerator::clamped`] without the input images
fn clamped_numbers(&self) -> TileGenerator {
let default = TileGenerator::default();
let unit = |value: f32, fallback: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { fallback };
let unit_pair = |pair: [f32; 2], fallback: [f32; 2]| [unit(pair[0], fallback[0]), unit(pair[1], fallback[1])];
let angle = |value: f32| if value.is_finite() { value.rem_euclid(360.0) } else { 0.0 };
let amount = |count: u32| count.clamp(*TileGenerator::AMOUNT.start(), *TileGenerator::AMOUNT.end());
let resolution = |size: u32| {
let largest = TileGenerator::SHAPE_RESOLUTIONS[TileGenerator::SHAPE_RESOLUTIONS.len() - 1];
size.clamp(TileGenerator::SHAPE_RESOLUTIONS[0], largest).next_power_of_two().min(largest)
};
TileGenerator {
position: unit(self.position, default.position),
contrast: unit(self.contrast, default.contrast),
amount: self.amount.map(amount),
shape_resolution: self.shape_resolution.map(resolution),
specific: unit(self.specific, default.specific),
shape_angle: angle(self.shape_angle),
shape_scale: unit(self.shape_scale, default.shape_scale),
shape_size: unit_pair(self.shape_size, default.shape_size),
shape_tiling: self.shape_tiling.clamp(*TileGenerator::SHAPE_TILING.start(), *TileGenerator::SHAPE_TILING.end()),
inputs: Vec::new(),
quarter_turns: self.quarter_turns % 4,
quarter_turn_random: unit(self.quarter_turn_random, 0.0),
symmetry_random: unit(self.symmetry_random, 0.0),
middle_size: unit_pair(self.middle_size, default.middle_size),
interstice: unit_pair(self.interstice, default.interstice),
interstice_random: unit_pair(self.interstice_random, default.interstice_random),
size: unit_pair(self.size, default.size),
size_absolute: unit_pair(self.size_absolute, default.size_absolute),
size_pixel: self
.size_pixel
.map(|pixels| if pixels.is_finite() { pixels.clamp(0.0, TileGenerator::MAX_SIZE_PIXELS) } else { default.size_pixel[0] }),
size_random: unit_pair(self.size_random, default.size_random),
scale: if self.scale.is_finite() { self.scale.clamp(0.0, TileGenerator::MAX_SCALE) } else { default.scale },
scale_random: unit(self.scale_random, 0.0),
scale_random_seed: self.scale_random_seed.min(TileGenerator::MAX_RANDOM_SEED),
offset: unit(self.offset, 0.0),
offset_random: unit(self.offset_random, 0.0),
offset_random_seed: self.offset_random_seed.min(TileGenerator::MAX_RANDOM_SEED),
position_random: unit_pair(self.position_random, default.position_random),
global_offset: unit_pair(self.global_offset, default.global_offset),
rotation: angle(self.rotation),
rotation_random: unit(self.rotation_random, 0.0),
color: unit(self.color, default.color),
luminance_random: unit(self.luminance_random, 0.0),
random_mask: unit(self.random_mask, 0.0),
background: unit(self.background, default.background),
opacity: unit(self.opacity, default.opacity),
background_image: None,
non_square_expansion: self.non_square_expansion,
shape: self.shape,
shape_diagonal: self.shape_diagonal,
shape_non_square_expansion: self.shape_non_square_expansion,
input_distribution: self.input_distribution,
quincunx_flip: self.quincunx_flip,
symmetry: self.symmetry,
size_mode: self.size_mode,
vertical_offset: self.vertical_offset,
luminance_by_number: self.luminance_by_number,
luminance_by_scale: self.luminance_by_scale,
checker_mask: self.checker_mask,
horizontal_mask: self.horizontal_mask,
vertical_mask: self.vertical_mask,
invert_mask: self.invert_mask,
blending: self.blending,
reverse_order: self.reverse_order,
}
}
/// Every image the pattern reads
pub fn images(&self) -> impl Iterator<Item = &str> {
self.inputs.iter().chain(&self.background_image).map(String::as_str)
}
}
impl Default for TileGenerator {
fn default() -> Self {
TileGenerator {
position: 0.5,
contrast: 0.0,
amount: [10, 10],
non_square_expansion: true,
shape: TileShape::default(),
shape_resolution: [256, 256],
specific: 0.5,
shape_angle: 0.0,
shape_scale: 1.0,
shape_size: [1.0, 1.0],
shape_tiling: 1,
shape_diagonal: false,
shape_non_square_expansion: true,
inputs: Vec::new(),
input_distribution: TileInputDistribution::default(),
quarter_turns: 0,
quarter_turn_random: 0.0,
quincunx_flip: false,
symmetry_random: 0.0,
symmetry: TileSymmetry::default(),
size_mode: TileSizeMode::default(),
middle_size: [0.5, 0.5],
interstice: [0.0, 0.0],
interstice_random: [0.0, 0.0],
size: [1.0, 1.0],
size_absolute: [0.1, 0.1],
size_pixel: [1.0, 1.0],
size_random: [0.0, 0.0],
scale: 1.0,
scale_random: 0.0,
scale_random_seed: 0,
offset: 0.0,
offset_random: 0.0,
offset_random_seed: 0,
vertical_offset: false,
position_random: [0.0, 0.0],
global_offset: [0.0, 0.0],
rotation: 0.0,
rotation_random: 0.0,
color: 1.0,
luminance_random: 0.0,
luminance_by_number: false,
luminance_by_scale: false,
checker_mask: false,
horizontal_mask: false,
vertical_mask: false,
random_mask: 0.0,
invert_mask: false,
blending: TileBlending::default(),
background: 0.0,
background_image: None,
opacity: 1.0,
reverse_order: false,
}
}
}
@@ -0,0 +1,22 @@
use serde::{Deserialize, Serialize};
/// Which of a Tile Generator's input images each tile draws
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TileInputDistribution {
/// A random input per tile
#[default]
Random,
/// The inputs in turn, tile after tile
ByNumber,
}
impl TileInputDistribution {
pub const ALL: [TileInputDistribution; 2] = [TileInputDistribution::Random, TileInputDistribution::ByNumber];
pub fn label(self) -> &'static str {
match self {
TileInputDistribution::Random => "Random",
TileInputDistribution::ByNumber => "By pattern number",
}
}
}
+67
View File
@@ -0,0 +1,67 @@
use serde::{Deserialize, Serialize};
/// The shape a Tile Generator draws in each tile
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TileShape {
/// One of the pattern's input images
Image,
Square,
Disc,
Paraboloid,
Bell,
Gaussian,
Thorn,
Pyramid,
#[default]
Brick,
Gradation,
Waves,
HalfBell,
RidgedBell,
Crescent,
Capsule,
Cone,
}
impl TileShape {
/// In the reference app's menu order
pub const ALL: [TileShape; 16] = [
TileShape::Image,
TileShape::Square,
TileShape::Disc,
TileShape::Paraboloid,
TileShape::Bell,
TileShape::Gaussian,
TileShape::Thorn,
TileShape::Pyramid,
TileShape::Brick,
TileShape::Gradation,
TileShape::Waves,
TileShape::HalfBell,
TileShape::RidgedBell,
TileShape::Crescent,
TileShape::Capsule,
TileShape::Cone,
];
pub fn label(self) -> &'static str {
match self {
TileShape::Image => "Custom image input",
TileShape::Square => "Square",
TileShape::Disc => "Disc",
TileShape::Paraboloid => "Paraboloid",
TileShape::Bell => "Bell",
TileShape::Gaussian => "Gaussian",
TileShape::Thorn => "Thorn",
TileShape::Pyramid => "Pyramid",
TileShape::Brick => "Brick",
TileShape::Gradation => "Gradation",
TileShape::Waves => "Waves",
TileShape::HalfBell => "Half bell",
TileShape::RidgedBell => "Ridged bell",
TileShape::Crescent => "Crescent",
TileShape::Capsule => "Capsule",
TileShape::Cone => "Cone",
}
}
}
+32
View File
@@ -0,0 +1,32 @@
use serde::{Deserialize, Serialize};
/// How a Tile Generator sizes its shapes
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TileSizeMode {
/// Each shape fills its tile minus the interstice (the gap between shapes)
#[default]
NormalInterstice,
/// Each shape takes a size relative to its tile, whatever the gap
NormalSize,
/// Each shape is the largest square its tile holds; the size settings are not read
KeepRatio,
/// A size relative to the whole pattern, whatever the tile count
Absolute,
/// A size in pixels of a 2048 pixel output, whatever the output's resolution
Pixel,
}
impl TileSizeMode {
pub const ALL: [TileSizeMode; 5] =
[TileSizeMode::NormalInterstice, TileSizeMode::NormalSize, TileSizeMode::KeepRatio, TileSizeMode::Absolute, TileSizeMode::Pixel];
pub fn label(self) -> &'static str {
match self {
TileSizeMode::NormalInterstice => "Normal - interstice",
TileSizeMode::NormalSize => "Normal - size",
TileSizeMode::KeepRatio => "Keep ratio",
TileSizeMode::Absolute => "Absolute",
TileSizeMode::Pixel => "Pixel",
}
}
}
+22
View File
@@ -0,0 +1,22 @@
use serde::{Deserialize, Serialize};
/// The mirrors a Tile Generator's random symmetry picks from
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TileSymmetry {
#[default]
Both,
Horizontal,
Vertical,
}
impl TileSymmetry {
pub const ALL: [TileSymmetry; 3] = [TileSymmetry::Both, TileSymmetry::Horizontal, TileSymmetry::Vertical];
pub fn label(self) -> &'static str {
match self {
TileSymmetry::Both => "Horizontal + vertical",
TileSymmetry::Horizontal => "Horizontal",
TileSymmetry::Vertical => "Vertical",
}
}
}
+4 -3
View File
@@ -24,9 +24,10 @@ pub use bake::{
pub use blend::{BlendMode, blend1, blend3, lum, mix3};
pub use channel::{Channel, ChannelFormat, ChannelKind};
pub use layer::{
ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorGlobal, GeneratorKind, HeightMask,
Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, PathShape, Procedural,
ProceduralKind, Projection, ResolutionMode, Source, gradient, hsl_adjust, per_unit,
ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Generator, GeneratorGlobal,
GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution,
PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode,
TileSymmetry, gradient, hsl_adjust, per_unit,
};
pub use project::{
AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project,
+8 -2
View File
@@ -562,6 +562,11 @@ impl Project {
}
let (ts, parent, i) = self.locate(id).ok_or(CoreError::NoLayer(id))?;
if let Some(t) = target {
let (target_set, _, _) = self.locate(t).ok_or(CoreError::NoLayer(t))?;
if target_set != ts {
return Err(CoreError::Invalid("layer move target belongs to another texture set".into()));
}
let mut sub = Vec::new();
self.collect_subtree(id, 0, &mut sub);
if sub.contains(&t) {
@@ -791,7 +796,7 @@ mod tests {
];
let id = p.insert_layer(0, l, None, false).unwrap();
let mut top = paint(&mut p, "y");
let source = Source::Anchor { anchor, channel: Channel::Height };
let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() };
top.mask = Some(Mask {
effects: vec![Effect::new(p.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })],
..Mask::new(MaskBackground::Black)
@@ -801,7 +806,8 @@ mod tests {
let back: Project = serde_json::from_str(&json).unwrap();
assert_eq!(back, p);
assert_eq!(back.effect(anchor).map(|(owner, _)| owner), Some(id));
// Projects saved before content effects existed load with empty stacks.
// Projects saved before content effects existed load with empty stacks
let mut v: serde_json::Value = serde_json::from_str(&json).unwrap();
for l in v["layers"].as_object_mut().unwrap().values_mut() {
l.as_object_mut().unwrap().remove("content_effects");
+114 -1
View File
@@ -37,6 +37,23 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("camera.bookmark7", "Go to camera 7", ["Viewport"], Some("Ctrl+7"), "{}", always, |s, _| bookmark(s, 6)),
cmd!("camera.bookmark8", "Go to camera 8", ["Viewport"], Some("Ctrl+8"), "{}", always, |s, _| bookmark(s, 7)),
cmd!("camera.bookmark9", "Go to camera 9", ["Viewport"], Some("Ctrl+9"), "{}", always, |s, _| bookmark(s, 8)),
cmd!(
"camera.view",
"Fixed view",
[],
None,
"{view: front|back|left|right|top|bottom} → the camera (looks at the mesh from that side and frames it; the projection stays)",
always,
|s, p| fixed_view(s, strp(p, "view").ok_or_else(|| bad("camera.view", "`view` is required"))?)
),
cmd!("camera.view.front", "Front view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "front")),
cmd!("camera.view.back", "Back view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "back")),
cmd!("camera.view.left", "Left view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "left")),
cmd!("camera.view.right", "Right view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "right")),
cmd!("camera.view.top", "Top view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "top")),
cmd!("camera.view.bottom", "Bottom view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "bottom")),
cmd!("camera.perspective", "Perspective", ["Viewport"], Some("F5"), "{}", always, |s, _| projection(s, false)),
cmd!("camera.orthographic", "Orthographic", ["Viewport"], Some("F6"), "{}", always, |s, _| projection(s, true)),
cmd!("viewport.focusAt", "Focus depth of field here", [], None, "{x, y (viewport pixels), viewport?: [w, h]}", always, focus_at),
]
}
@@ -128,19 +145,48 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
fn select(s: &mut Session, p: &Value) -> Result<Value> {
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.
// 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() {
// A saved view is clamped against the whole mesh, not against a part framed with F
s.camera.scene_radius = s.mesh.radius();
apply(&mut s.camera, &c);
}
s.revision = s.revision.wrapping_add(1);
Ok(crate::view_cmds::camera_json(s))
}
/// The fixed views: name, yaw and pitch in degrees. Yaw 0 puts the eye on +Z (the front), yaw 90
/// on +X (the right side); top and bottom stop at the orbit's ±89° pitch limit.
pub const VIEWS: [(&str, f32, f32); 6] =
[("front", 0.0, 0.0), ("back", 180.0, 0.0), ("left", -90.0, 0.0), ("right", 90.0, 0.0), ("top", 0.0, 89.0), ("bottom", 0.0, -89.0)];
/// Look at the mesh from fixed view `name` and frame it, keeping the projection. The yaw is the
/// one nearest the current yaw, so the desktop UI's glide takes the short way round.
fn fixed_view(s: &mut Session, name: &str) -> Result<Value> {
let Some(&(_, yaw, pitch)) = VIEWS.iter().find(|(view, ..)| *view == name) else {
return Err(bad("camera.view", format!("unknown view `{name}`: one of front, back, left, right, top, bottom")));
};
let current = if s.camera.yaw.is_finite() { s.camera.yaw } else { 0.0 };
let turn = std::f32::consts::TAU;
s.camera.yaw = current + (yaw.to_radians() - current + turn * 0.5).rem_euclid(turn) - turn * 0.5;
s.camera.pitch = pitch.to_radians();
crate::execute(s, "viewport.frame", &Value::Null)
}
/// Switch to a perspective or orthographic projection; position and rotation stay.
fn projection(s: &mut Session, ortho: bool) -> Result<Value> {
s.camera.ortho = ortho;
s.revision = s.revision.wrapping_add(1);
Ok(crate::view_cmds::camera_json(s))
}
/// Shortcut slot `slot` (0-based): the n-th saved camera, in list order.
fn bookmark(s: &mut Session, slot: usize) -> Result<Value> {
if slot >= s.doc.project.cameras.len() {
@@ -238,6 +284,73 @@ mod tests {
assert!(ids.iter().all(|c| c.shortcut.is_some()));
}
#[test]
fn fixed_views_look_from_their_side_frame_the_mesh_and_keep_the_projection() {
let mut s = session();
execute(&mut s, "camera.set", &json!({"yaw": 37, "pitch": 21, "distance": 9, "target": [0.4, -0.3, 0.2]})).unwrap();
let (lo, hi) = s.mesh.bounds();
let mut framed = s.camera;
framed.frame(lo, hi);
let sides = [("front", Vec3::Z), ("back", Vec3::NEG_Z), ("left", Vec3::NEG_X), ("right", Vec3::X), ("top", Vec3::Y), ("bottom", Vec3::NEG_Y)];
for ortho in [false, true] {
execute(&mut s, "camera.set", &json!({"ortho": ortho})).unwrap();
for (view, side) in sides {
// Through the parameterized command and through the menu command alike
let menu_id = format!("camera.view.{view}");
for (id, params) in [("camera.view", json!({"view": view})), (menu_id.as_str(), Value::Null)] {
execute(&mut s, "camera.orbit", &json!({"dx": 123, "dy": 17})).unwrap();
let back = execute(&mut s, id, &params).unwrap();
let looking_from = (s.camera.eye() - s.camera.target).normalize();
assert!(looking_from.dot(side) > 0.999, "{id} {view}: the eye is on the {side} side, not at {looking_from}");
assert_eq!(s.camera.ortho, ortho, "{id} {view} keeps the projection");
assert!((s.camera.target - framed.target).length() < 1e-5, "{view} centres the mesh");
assert!((s.camera.distance - framed.distance).abs() < 1e-4, "{view} frames the mesh");
assert_eq!(back["ortho"], ortho);
}
}
}
// Orbit still works from a fixed view, and a view is not an undo step
let steps = s.history_labels().len();
execute(&mut s, "camera.view.top", &Value::Null).unwrap();
assert!((s.camera.pitch - 89f32.to_radians()).abs() < 1e-6, "top stops at the orbit limit");
execute(&mut s, "camera.orbit", &json!({"dx": 30, "dy": -40})).unwrap();
assert!((s.camera.pitch - 49f32.to_radians()).abs() < 1e-5 && s.camera.yaw.to_degrees().rem_euclid(360.0) > 1.0);
assert_eq!(s.history_labels().len(), steps);
}
#[test]
fn fixed_views_take_the_nearest_turn_and_reject_unknown_views() {
let mut s = session();
execute(&mut s, "camera.set", &json!({"yaw": 715})).unwrap();
execute(&mut s, "camera.view", &json!({"view": "front"})).unwrap();
assert!((s.camera.yaw - 720f32.to_radians()).abs() < 1e-4, "two whole turns, not a spin back to 0: {}", s.camera.yaw.to_degrees());
let before = s.camera;
assert!(execute(&mut s, "camera.view", &json!({"view": "sideways"})).is_err());
assert!(execute(&mut s, "camera.view", &json!({})).is_err(), "`view` is required");
assert!(execute(&mut s, "camera.view", &json!({"view": 3})).is_err());
assert_eq!(s.camera, before, "a rejected view leaves the camera");
let menu: Vec<_> = crate::command_specs().iter().filter(|c| c.id.starts_with("camera.view.")).collect();
assert_eq!(menu.len(), 6);
assert!(menu.iter().all(|c| c.shortcut.is_none() && c.menu == ["Viewport"]), "no default keys: users bind their own");
}
#[test]
fn perspective_and_orthographic_change_only_the_projection() {
let mut s = session();
execute(&mut s, "camera.set", &json!({"yaw": 30, "pitch": 10, "distance": 4})).unwrap();
let before = s.camera;
let r = execute(&mut s, "camera.orthographic", &Value::Null).unwrap();
assert!(s.camera.ortho && r["ortho"] == true);
assert_eq!(OrbitCamera { ortho: false, ..s.camera }, before, "position and rotation stay");
execute(&mut s, "camera.orthographic", &Value::Null).unwrap();
assert!(s.camera.ortho, "a second press keeps it orthographic: two actions, not a toggle");
execute(&mut s, "camera.perspective", &Value::Null).unwrap();
assert_eq!(s.camera, before);
let key = |id: &str| crate::find(id).and_then(|c| c.shortcut);
assert_eq!((key("camera.perspective"), key("camera.orthographic")), (Some("F5"), Some("F6")));
}
#[test]
fn cameras_round_trip_through_the_project_file() {
let mut s = session();
+173 -7
View File
@@ -24,6 +24,63 @@ pub struct CommandSpec {
pub run: Run,
}
impl CommandSpec {
/// Whether a keyboard shortcut can run this command: it acts with no parameters at all, or
/// every parameter in its first `params` form is optional (`name?`) and none of them is one
/// of several alternatives. Left out: commands that need a path, name or similar, commands
/// that only return data or do nothing without parameters, and the ones that replace the
/// open project (the menu asks to save first).
pub fn bindable(&self) -> bool {
const NOT_FROM_A_KEY: [&str; 13] = [
"project.inspect",
"project.templates",
"project.new",
"tool.state",
"text.fonts",
"export.presets",
"edit.history",
"camera.get",
"textureSet.parts",
"bake.settings",
"bake.preview",
"camera.set",
"textureSet.settings",
];
const NOTHING_WITHOUT_PARAMS: [&str; 4] = ["layer.blend", "tool.stencil", "tool.fillSelection", "tool.path"];
!(self.id.ends_with(".list") || NOT_FROM_A_KEY.contains(&self.id) || NOTHING_WITHOUT_PARAMS.contains(&self.id)) && params_all_optional(self.params)
}
}
/// Whether the first `{...}` group of a `params` text has only optional entries.
fn params_all_optional(params: &str) -> bool {
let Some(body) = params.trim_start().strip_prefix('{') else { return false };
let Some(end) = body.find('}') else { return false };
// `{a?} | {b}`: other forms exist, and the first one alone may not do anything
if body[end + 1..].trim_start().starts_with('|') {
return false;
}
let (mut depth, mut start) = (0i32, 0);
let mut entries = Vec::new();
for (i, c) in body[..end].char_indices() {
match c {
'(' | '[' => depth += 1,
')' | ']' => depth -= 1,
',' if depth == 0 => {
entries.push(&body[start..i]);
start = i + 1;
}
_ => {}
}
}
entries.push(&body[start..end]);
entries.iter().filter(|entry| !entry.trim().is_empty()).all(|entry| {
// `index? | name?` asks for one of the two, so it is not optional as a whole
!entry.contains(" | ") && entry.trim().split([':', ' ', '(']).next().is_some_and(|key| key.ends_with('?'))
})
}
pub(crate) fn always(_: &Session) -> std::result::Result<(), String> {
Ok(())
}
@@ -57,12 +114,14 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::layer_ops::specs());
v.extend(crate::instance_cmds::specs());
v.extend(crate::mask_cmds::specs());
v.extend(crate::mask_export::specs());
v.extend(crate::color_selection_cmds::specs());
v.extend(crate::effect_clipboard::specs());
v.extend(crate::tool_cmds::specs());
v.extend(crate::brush_preset_cmds::specs());
v.extend(crate::path_tool::specs());
v.extend(crate::view_cmds::specs());
v.extend(crate::solo::specs());
v.extend(crate::camera_cmds::specs());
v.extend(crate::quick_mask::specs());
v.extend(crate::set_cmds::specs());
@@ -88,6 +147,40 @@ pub fn command_specs() -> &'static [CommandSpec] {
})
}
/// Commands that run in the empty state (no project open): they open or create a project, or
/// only read the libraries and the user's presets, or only move the camera (`viewport.frame`, enabled on the reference app's blank screen).
fn works_without_project(id: &str) -> bool {
matches!(
id,
"file.open"
| "file.new"
| "project.new"
| "project.sample"
| "project.inspect"
| "viewport.frame"
| "project.templates"
| "export.presets"
| "export.preset.get"
| "export.preset.save"
| "export.preset.remove"
| "brush.preset.list"
| "alpha.list"
| "filter.list"
| "material.list"
| "mask.smart.list"
| "text.fonts"
)
}
/// Whether `spec` can run on `s`: no project open refuses everything but [`works_without_project`]
pub fn check_enabled(spec: &CommandSpec, s: &Session) -> std::result::Result<(), String> {
if !s.project_open && !works_without_project(spec.id) {
return Err("no project is open".into());
}
(spec.enabled)(s)
}
pub fn find(id: &str) -> Option<&'static CommandSpec> {
command_specs().iter().find(|c| c.id == id)
}
@@ -96,7 +189,7 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> {
/// `merge: true` its edits continue the previous undo step of the same label (drags).
pub fn execute(s: &mut Session, id: &str, params: &Value) -> Result<Value> {
let spec = find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
(spec.enabled)(s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?;
check_enabled(spec, s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?;
let outer = std::mem::replace(&mut s.merge_edits, boolp(params, "merge").unwrap_or(false));
let result = (spec.run)(s, params);
s.merge_edits = outer;
@@ -116,7 +209,7 @@ pub fn list(s: &Session, filter: Option<&str>) -> Value {
"menu": c.menu,
"shortcut": c.shortcut,
"params": c.params,
"enabled": (c.enabled)(s).is_ok(),
"enabled": check_enabled(c, s).is_ok(),
})
})
.collect();
@@ -199,7 +292,7 @@ pub(crate) fn blend_param(cmd: &str, p: &Value, key: &str) -> Result<Option<Blen
pub(crate) fn color_param(cmd: &str, p: &Value, key: &str) -> Result<Option<[f32; 3]>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => color_of(v).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a color ([r, g, b] linear or \"#rrggbb\")"))),
Some(v) => color_of(v).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"))),
}
}
@@ -234,6 +327,65 @@ pub(crate) fn color_of(v: &Value) -> Option<[f32; 3]> {
mod tests {
use super::*;
#[test]
fn only_commands_a_key_can_run_are_bindable() {
let bindable = |id: &str| find(id).unwrap_or_else(|| panic!("{id} is gone")).bindable();
for id in [
"layer.add.paint",
"layer.add.fill",
"layer.add.group",
"mask.invert",
"mask.clear",
"layer.visible",
"effect.add.paint",
"file.save",
"tool.paint",
"camera.add",
"effect.duplicate",
"effect.paste",
] {
assert!(bindable(id), "{id} needs no parameters");
}
for id in [
"file.saveCopy",
"textureSet.select",
"layer.rename",
"tool.select",
"layer.select",
"viewport.focusAt",
"tool.stroke",
"mask.smart.apply",
"bake.skew.set",
"textureSet.resolution",
"effect.move",
"camera.remove",
"bake.highPoly.remove",
] {
assert!(!bindable(id), "{id} needs a parameter");
}
for id in ["layer.move", "layer.list", "project.inspect", "edit.history", "export.presets", "tool.state", "project.new", "camera.set", "layer.blend"] {
assert!(!bindable(id), "{id} is a query or has several forms");
}
}
#[test]
fn params_texts_are_read_by_their_required_entries() {
for ok in ["{}", "{layer?}", "{enabled?: bool} \u{2014} toggles when omitted", "{effect?: the selected effect}"] {
assert!(params_all_optional(ok), "{ok}");
}
for no in [
"{path}",
"{layer?, name}",
"{x, y (viewport pixels), viewport?: [w, h]}",
"{a?} | {b}",
"{index? | name?}",
"{ts?, value?: 0..1 | path: image}",
"no braces",
] {
assert!(!params_all_optional(no), "{no}");
}
}
#[test]
fn color_param_accepts_valid_forms() {
let p = json!({
@@ -253,10 +405,10 @@ mod tests {
#[test]
fn color_param_rejects_invalid_forms() {
let bad_cases = [
("#fff", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"),
("red", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"),
("#12345", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"),
("#gggggg", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"),
("#fff", "`color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"),
("red", "`color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"),
("#12345", "`color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"),
("#gggggg", "`color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"),
];
for (input, expected_err) in bad_cases {
let p = json!({ "color": input });
@@ -284,4 +436,18 @@ mod tests {
assert_eq!(color_of(&json!("#GGGGGG")), None);
assert!(color_of(&json!("#ff8000")).is_some());
}
#[test]
fn no_bindable_command_asks_for_a_parameter() {
// Effect commands need a selected effect, which this session lacks
for spec in command_specs().iter().filter(|c| c.bindable() && c.shortcut.is_none() && !c.id.starts_with("effect.")) {
let mut session = crate::sample_session(256, 64).unwrap();
if (spec.enabled)(&session).is_ok()
&& let Err(err) = execute(&mut session, spec.id, &Value::Null)
{
let text = err.to_string();
assert!(!text.contains("required") && !text.contains("give "), "{} asks for a parameter: {text}", spec.id);
}
}
}
}
+106 -8
View File
@@ -2,10 +2,12 @@
//! (a decal fill with a planar projection), as a fill layer with a decal projection.
use serde_json::{Value, json};
use texturecraft_core::{Channel, Decal, Effect, EffectKind, Fill, Layer, LayerId, LayerKind, Mask, MaskBackground, Projection, Source};
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_core::{
Channel, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Layer, LayerId, LayerKind, Mask, MaskBackground, Projection, Source,
};
use texturecraft_geom::glam::{Quat, Vec2, Vec3};
use crate::commands::{CommandSpec, always, bad, channel_param, f32p, has_layer, layer_param, strp, u64p, vec3};
use crate::commands::{CommandSpec, always, bad, boolp, channel_param, f32p, layer_param, strp, u64p, vec3};
use crate::tool_cmds::viewport_of;
use crate::{Result, Session, StackTarget, cmd};
@@ -16,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add decal",
[],
None,
"{image: resource name, channel?: a channel id (default baseColor) | \"mask\" (a new fill layer masked by the image's gray), x?, y?: viewport pixels (default: the view center; a point on another texture set selects it), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z] (on the selected texture set), up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} → {layer, decal, maskEffect: the mask fill effect holding the image with channel \"mask\", else null} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round",
"{image: resource name, channel?: a channel id (default baseColor) | \"mask\" (a new fill layer masked by the image's gray), x?, y?: viewport pixels (default: the view center; a point on another texture set selects it), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z] (on the selected texture set), up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), keepProportions?: true makes the height follow the width by the image's aspect, flipU?, flipV?: mirror the image left to right / top to bottom inside the frame, rotation?: degrees, depth?, symmetry?: x|y|z|off (also place a mirrored copy across the mesh center, perpendicular to that axis; it follows this decal), symmetryFlip?: none|u|v (flip the copy's image on top of the reflection), symmetryOffset?: world units from the mesh center along the axis to the mirror plane (default 0, within the mesh), name?} → {layer, decal, maskEffect: the mask fill effect holding the image with channel \"mask\", else null} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round",
always,
add
),
@@ -25,8 +27,8 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit decal",
[],
None,
"{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer), x?, y?, viewport? | position?, normal? (re-place it on its own texture set), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags)}",
has_layer,
"{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer), x?, y?, viewport? | position?, normal? (re-place it on its own texture set), up?: [x,y,z] (default: the decal's up carried along when it moves onto a surface facing another way), size?: height | [w,h], keepProportions?: true keeps the image's aspect (the current ratio without an image): a height sets the width, a [w,h] pair or no size sets the height from the width, flipU?, flipV?: mirror the image left to right / top to bottom inside the frame, rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, symmetry?: x|y|z|off, symmetryFlip?: none|u|v, symmetryOffset? (the mirrored copy; the flip and offset alone keep the axis), image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags)}",
always,
set
),
]
@@ -91,6 +93,56 @@ fn decal_up(s: &Session, cmd: &str, p: &Value, normal: Vec3) -> Result<Vec3> {
Ok(if up.normalize_or_zero().cross(normal).length_squared() > 1e-4 { up } else { to_world.transform_vector3(Vec3::NEG_Z) })
}
/// The mirrored copy asked for by `symmetry` (x, y, z or off) and `symmetryFlip` (none, u or v),
/// starting from `current` for what the params leave out
fn symmetry_param(cmd: &str, p: &Value, current: Option<DecalSymmetry>, bounds: (Vec3, Vec3)) -> Result<Option<DecalSymmetry>> {
let axis = match strp(p, "symmetry").map(str::to_ascii_lowercase).as_deref() {
None => current.map(|symmetry| symmetry.axis.min(2)),
Some("off" | "none") => None,
Some("x") => Some(0),
Some("y") => Some(1),
Some("z") => Some(2),
Some(other) => return Err(bad(cmd, format!("unknown symmetry `{other}` (x, y, z or off)"))),
};
let flip = match strp(p, "symmetryFlip").map(str::to_ascii_lowercase).as_deref() {
None => current.map_or(DecalFlip::None, |symmetry| symmetry.flip),
Some("none" | "off") => DecalFlip::None,
Some("u") => DecalFlip::U,
Some("v") => DecalFlip::V,
Some(other) => return Err(bad(cmd, format!("unknown symmetryFlip `{other}` (none, u or v)"))),
};
// The plane stays within the mesh, as the brush symmetry's offset does
let (lo, hi) = bounds;
let half_extent = (hi - lo) * 0.5;
let offset = match (f32p(p, "symmetryOffset"), current) {
(Some(offset), _) if !offset.is_finite() => return Err(bad(cmd, "`symmetryOffset` must be a number")),
(Some(offset), _) => offset,
(None, Some(symmetry)) => symmetry.offset,
(None, None) => 0.0,
};
Ok(axis.map(|axis| {
let limit = half_extent[usize::from(axis)];
DecalSymmetry { axis, flip, offset: offset.clamp(-limit, limit) }
}))
}
/// The up of a decal moved from a surface facing `from.0` (up `from.1`) onto one facing `to`: the
/// old up turned by the smallest rotation that takes the old normal to the new one (parallel
/// transport), so it follows the surface smoothly and never degenerates. A surface turned
/// exactly away has no smallest rotation: the camera rule of a new decal decides there.
fn carried_up(s: &Session, from: (Vec3, Vec3), to: Vec3) -> Vec3 {
let (old_normal, old_up) = from;
let (Some(old_normal), Some(new_normal)) = (old_normal.try_normalize(), to.try_normalize()) else { return old_up };
if old_normal.dot(new_normal) < -0.9999 {
return decal_up(s, "", &Value::Null, new_normal).unwrap_or(old_up);
}
Quat::from_rotation_arc(old_normal, new_normal) * old_up
}
fn add(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "layer.add.decal";
let image = strp(p, "image").ok_or_else(|| bad(cmd, "`image` is required"))?.to_string();
@@ -112,7 +164,10 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
let mesh_diagonal = mesh_size(s);
let default_height = mesh_diagonal * DEFAULT_HEIGHT;
let size = size_param(p, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]);
let mut size = size_param(p, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]);
if boolp(p, "keepProportions") == Some(true) && p.get("size").is_some_and(Value::is_array) {
size[1] = (size[0] / aspect).clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE);
}
let decal = Decal {
center: center.to_array(),
normal: normal.to_array(),
@@ -120,8 +175,11 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
size,
rotation: f32p(p, "rotation").unwrap_or(0.0).rem_euclid(360.0),
offset: [0.0; 2],
flip: [boolp(p, "flipU").unwrap_or(false), boolp(p, "flipV").unwrap_or(false)],
// By default it reaches half its larger side into the surface
depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)),
symmetry: symmetry_param(cmd, p, None, s.mesh.bounds())?,
};
// A decal dropped on another texture set goes there and selects it, as a dropped material does
@@ -169,6 +227,27 @@ fn decal_of(s: &Session, cmd: &str, id: LayerId, effect: Option<LayerId>) -> Res
}
}
/// Width over height of the image the decal of fill layer `id` (or of mask fill effect `effect`) shows
/// (`new`: the image a call replaces it with, which then counts instead)
fn image_aspect(s: &Session, id: LayerId, effect: Option<LayerId>, new: Option<&str>) -> Option<f32> {
let name = match effect {
_ if new.is_some() => new?.to_string(),
Some(effect) => match &s.doc.project.effect(effect)?.1.kind {
EffectKind::Fill { source: Source::Image { name, .. }, .. } => name.clone(),
_ => return None,
},
None => match &s.doc.project.layer(id).ok()?.kind {
LayerKind::Fill(fill) => fill.sources.values().find_map(|source| match source {
Source::Image { name, .. } => Some(name.clone()),
_ => None,
})?,
_ => return None,
},
};
let image = s.images.get(&name)?;
Some(image.width as f32 / image.height.max(1) as f32)
}
fn set(session: &mut Session, params: &Value) -> Result<Value> {
let command = "layer.decal.set";
let effect = u64p(params, "effect").map(LayerId);
@@ -192,14 +271,32 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
return Err(bad(command, "that surface belongs to another texture set"));
}
// Carry up so a stale axis cannot lie in or flip on the new surface
let previous = (Vec3::from(decal.normal), Vec3::from(decal.up));
(decal.center, decal.normal, decal.offset) = (center.to_array(), normal.to_array(), [0.0; 2]);
if params.get("up").is_none() {
decal.up = carried_up(session, previous, normal).to_array();
}
}
if params.get("up").is_some() {
decal.up = decal_up(session, command, params, Vec3::from(decal.normal))?.to_array();
}
if let Some(size) = size_param(params, decal.size[0] / decal.size[1].max(1e-6), mesh_diagonal) {
let keep = boolp(params, "keepProportions") == Some(true);
let ratio = decal.size[0] / decal.size[1].max(1e-6);
let aspect = if keep { image_aspect(session, layer_id, effect, strp(params, "image")).unwrap_or(ratio) } else { ratio };
if let Some(mut size) = size_param(params, aspect, mesh_diagonal).or_else(|| keep.then_some(decal.size)) {
// A height sets the width through `aspect`; a pair or the current size sets the height from the width
if keep && params.get("size").is_none_or(Value::is_array) {
size[1] = (size[0] / aspect).clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE);
}
decal.size = size;
}
if let Some(flip) = boolp(params, "flipU") {
decal.flip[0] = flip;
}
if let Some(flip) = boolp(params, "flipV") {
decal.flip[1] = flip;
}
if let Some(rotation) = f32p(params, "rotation") {
decal.rotation = rotation.rem_euclid(360.0);
}
@@ -212,6 +309,7 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
if let Some(depth) = f32p(params, "depth") {
decal.depth = depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE);
}
decal.symmetry = symmetry_param(command, params, decal.symmetry, session.mesh.bounds())?;
let image = strp(params, "image").map(str::to_string);
if let Some(name) = &image
+1 -1
View File
@@ -127,7 +127,7 @@ fn paste(session: &mut Session, params: &Value) -> Result<Value> {
// The target belongs to the active set's selection: a paste into another set leaves it
if let Some((layer_set, _, _)) = session.doc.project.locate(layer) {
session.selected.insert(layer_set, layer);
session.select_one(layer_set, layer);
if layer_set == session.ts() {
session.target = StackTarget::Effect(pasted);
}
+88 -31
View File
@@ -1,6 +1,8 @@
//! Files: projects (`.tcraft`), mesh import, texture export. Byte-based functions work on the
//! web; path-based commands are native only.
use std::borrow::Cow;
use serde_json::{Value, json};
#[cfg(not(target_arch = "wasm32"))]
use texturecraft_core::{NormalFormat, PROJECT_EXT};
@@ -51,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export textures",
["File"],
None,
"{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP and HDR can't hold one and warn), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)}",
"{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP and HDR can't hold one and warn), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)}",
always,
export_textures
),
@@ -140,6 +142,7 @@ impl Session {
/// for UV-tiled sets, or nothing for them without `tiled`).
fn material_files(&mut self, opts: ExportOptions, tiled: bool, materials: usize) -> Result<Vec<Vec<ExportedFile>>> {
let opts = ExportOptions { atlas: true, ..opts };
(0..materials)
.map(|m| match self.texture_set_of_material(m) {
Some(ts) if tiled || self.doc.project.texture_sets.get(ts).is_some_and(|t| t.tile_grid().is_none()) => self.export_files(&[ts], &opts),
@@ -155,20 +158,31 @@ impl Session {
/// [`Session::from_mesh_bytes`] with a UV tile mode (see [`Session::new_project_tiled`]).
pub fn from_mesh_bytes_tiled(file_name: &str, bytes: &[u8], resolution: u32, name: &str, uv_tiles: Option<bool>) -> Result<Session> {
let imported = texturecraft_formats::import_mesh_bytes(file_name, bytes).map_err(fe)?;
let ext = ext_of(file_name);
let mut s = Session::new_project_tiled(name, imported.mesh, &format!("mesh.{ext}"), Some((ext, bytes.to_vec())), resolution, uv_tiles)?;
s.doc.project.mesh_file = leaf_of(file_name);
s.doc.project.cameras = imported.cameras;
s.log.extend(imported.report.warnings.iter().cloned());
s.log.push(format!(
Self::from_mesh_source(file_name, Cow::Borrowed(bytes), resolution, name, uv_tiles)
}
fn from_mesh_source(file_name: &str, bytes: Cow<'_, [u8]>, resolution: u32, name: &str, uv_tiles: Option<bool>) -> Result<Session> {
let imported = texturecraft_formats::import_mesh_bytes(file_name, &bytes).map_err(fe)?;
let extension = ext_of(file_name);
let mut session = Session::new_project_tiled(name, imported.mesh, &format!("mesh.{extension}"), None, resolution, uv_tiles)?;
// Packed mesh files can have spare capacity that the project would otherwise retain
let mut source = bytes.into_owned();
source.shrink_to_fit();
session.mesh_source = Some((extension, source));
session.doc.project.mesh_file = leaf_of(file_name);
session.doc.project.cameras = imported.cameras;
session.log.extend(imported.report.warnings);
session.log.push(format!(
"Imported {} ({} triangles, {} materials{})",
file_name,
imported.report.triangles,
imported.report.materials,
if imported.report.uvs_generated { ", UVs generated" } else { "" }
));
Ok(s)
Ok(session)
}
/// Open a `.tcraft` project from bytes.
@@ -236,17 +250,21 @@ impl Session {
/// Render every export file for texture sets `sets` (in memory; works on the web).
pub fn export_files(&mut self, sets: &[usize], opts: &ExportOptions) -> Result<Vec<ExportedFile>> {
self.update();
if self.solo.is_none() {
self.update();
}
let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:"));
let mut out = Vec::new();
let empty = Default::default();
for &ts in sets {
let cache = self.caches.get(ts).ok_or_else(|| EngineError::Other(format!("no texture set {ts}")))?;
let composite = self.document_composite(ts, &cache.covered_tiles).ok_or_else(|| EngineError::Other(format!("no texture set {ts}")))?;
let coverage = cache.gbuf.coverage_mask();
let input = ExportInput {
project: &self.doc.project,
ts,
composite: &cache.composite,
composite: &composite,
baked: self.doc.baked.get(&ts).unwrap_or(&empty),
coverage: &coverage,
mesh_name: &mesh_name,
@@ -275,6 +293,7 @@ pub fn export_options(s: &Session, p: &Value, cmd: &str) -> Result<ExportOptions
Some(v @ Value::Object(_)) => Some(crate::preset_cmds::preset_param(v, cmd)?),
Some(_) => return Err(bad(cmd, "`preset` must be a preset name or a preset object")),
};
let preset = preset.ok_or_else(|| bad(cmd, format!("unknown export preset {}", p.get("preset").unwrap_or(&Value::Null))))?;
let mut o = ExportOptions::new(preset);
if let Some(f) = strp(p, "format") {
@@ -305,7 +324,8 @@ pub fn export_options(s: &Session, p: &Value, cmd: &str) -> Result<ExportOptions
.ok_or_else(|| bad(cmd, format!("unknown colorSpace `{name}` (sRGB, Linear Rec.709, ACEScg or ACES2065-1)")))?,
);
}
// A value of the wrong type is an error, not the format's default space.
// A value of the wrong type is an error, not the format's default space
Some(other) => return Err(bad(cmd, format!("`colorSpace` is a name (sRGB, Linear Rec.709, ACEScg or ACES2065-1), not {other}"))),
}
Ok(o)
@@ -315,10 +335,24 @@ fn sets_param(s: &Session, p: &Value, cmd: &str) -> Result<Vec<usize>> {
match p.get("ts") {
None => Ok((0..s.set_count()).collect()),
Some(Value::String(a)) if a == "all" => Ok((0..s.set_count()).collect()),
Some(v) => Ok(vec![v.as_u64().map(|t| t as usize).filter(|t| *t < s.set_count()).ok_or_else(|| bad(cmd, "invalid `ts`"))?]),
// Several sets in one command, so a file name two of them share is found before anything is written
Some(Value::Array(a)) => {
let mut sets = a.iter().map(|v| set_index(s, v, cmd)).collect::<Result<Vec<_>>>()?;
// A set listed twice is written once
let mut seen = std::collections::HashSet::new();
sets.retain(|t| seen.insert(*t));
Ok(sets)
}
Some(v) => Ok(vec![set_index(s, v, cmd)?]),
}
}
fn set_index(s: &Session, v: &Value, cmd: &str) -> Result<usize> {
v.as_u64().and_then(|index| usize::try_from(index).ok()).filter(|index| *index < s.set_count()).ok_or_else(|| bad(cmd, "invalid `ts`"))
}
fn plan(s: &mut Session, p: &Value) -> Result<Value> {
let opts = export_options(s, p, "export.plan")?;
let mesh_name = stem_of(s.doc.project.mesh.trim_start_matches("builtin:"));
@@ -387,23 +421,29 @@ pub use native::{absolute, open_path, read_mesh};
/// `file.new {mesh, name?, resolution?, uvTiles?, template?, importCameras?}`: a new project from the
/// mesh file `mesh`, remembering its path for Reimport mesh.
#[cfg(not(target_arch = "wasm32"))]
fn new_from_mesh(s: &mut Session, p: &Value) -> Result<Value> {
let path = native::path_param(p, "mesh", "file.new")?;
let f = native::read_mesh("file.new", path)?;
let template = crate::template_cmds::template_param(s, p, "file.new")?;
let res = u64p(p, "resolution").or(template.as_ref().map(|t| u64::from(t.resolution))).unwrap_or(2048);
let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| stem_of(path));
let mut next = Session::from_mesh_bytes_tiled(&f.name, &f.bytes, u32::try_from(res).unwrap_or(0), &name, crate::commands::boolp(p, "uvTiles"))?;
fn new_from_mesh(session: &mut Session, params: &Value) -> Result<Value> {
const DEFAULT_RESOLUTION_PX: u64 = 2048;
let path = native::path_param(params, "mesh", "file.new")?;
let template = crate::template_cmds::template_param(session, params, "file.new")?;
let resolution = u64p(params, "resolution").or(template.as_ref().map(|template| u64::from(template.resolution))).unwrap_or(DEFAULT_RESOLUTION_PX);
let name = strp(params, "name").map(str::to_string).unwrap_or_else(|| stem_of(path));
let uv_tiles = crate::commands::boolp(params, "uvTiles");
let mesh_file = native::read_mesh("file.new", path)?;
let mut next = Session::from_mesh_source(&mesh_file.name, Cow::Owned(mesh_file.bytes), u32::try_from(resolution).unwrap_or(0), &name, uv_tiles)?;
next.doc.project.mesh_path = native::absolute(path);
next.log.extend(f.warnings);
if crate::commands::boolp(p, "importCameras") == Some(false) {
next.log.extend(mesh_file.warnings);
if crate::commands::boolp(params, "importCameras") == Some(false) {
next.doc.project.cameras.clear();
}
if let Some(t) = &template {
next.apply_template(t);
if let Some(template) = &template {
next.apply_template(template);
}
s.switch_to(next);
Ok(crate::inspect::session(s))
session.switch_to(next);
Ok(crate::inspect::session(session))
}
#[cfg(not(target_arch = "wasm32"))]
@@ -549,7 +589,8 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std:
let mut textures: Vec<Texture> = Vec::new();
for f in texturecraft_formats::list_outputs(&s.doc.project, ts, &mesh_name, opts).map_err(fe)? {
let Some(input) = opts.preset.maps.get(f.map).and_then(|m| materialx::input_of_template(&m.file)) else { continue };
// The first tile stands for all of them: its number is written as <UDIM>.
// The first tile stands for all of them: its number is written as <UDIM>
let file = f.udim_name.clone().unwrap_or_else(|| f.name.clone());
let colorspace = materialx::colorspace_name(opts.space_for(f.format));
if !textures.iter().any(|t| t.input == input) {
@@ -561,8 +602,10 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std:
warnings.push(format!("MaterialX: texture set \"{}\" has no OpenPBR maps; use the \"OpenPBR (separate maps)\" preset", set.name));
continue;
}
let stem = texturecraft_formats::export::sanitize_file_stem(&format!("{mesh_name}_{}", set.name));
// Case-insensitive: Windows and macOS file systems are.
// Case-insensitive: Windows and macOS file systems are
if !stems.insert(stem.to_ascii_lowercase()) {
warnings.push(format!(
"MaterialX: texture set \"{}\" exports as \"{stem}\" like an earlier set, so its .mtlx was not written; rename one of them",
@@ -574,7 +617,8 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std:
texturecraft_formats::write_atomic(&path, materialx::write(&format!("{mesh_name}_{}", set.name), &textures, None).as_bytes()).map_err(fe)?;
out.push(path);
}
// The normalmap node only exists in a material that has a normal map.
// The normalmap node only exists in a material that has a normal map
if normal_map_written && opts.normal_format == Some(NormalFormat::DirectX) {
warnings.push("MaterialX: the normalmap node reads OpenGL (+Y) normals; this export wrote DirectX normals, so flip the green channel".into());
}
@@ -663,8 +707,7 @@ use unsupported as export_textures;
use unsupported as export_mesh;
fn close(s: &mut Session, _: &Value) -> Result<Value> {
let next = Session::new_project("Untitled", primitives::material_ball(), "builtin:material_ball", None, 2048)?;
s.switch_to(next);
s.switch_to(Session::closed()?);
Ok(Value::Null)
}
@@ -951,3 +994,17 @@ f 1/1 2/2 3/3
assert_eq!(parts(&mut old), json!(["mesh"]));
}
}
#[cfg(all(test, target_pointer_width = "32"))]
mod index_tests {
use super::*;
#[test]
fn export_rejects_an_index_that_would_wrap_to_the_first_set() {
let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let wrapped_index = u64::from(u32::MAX) + 1;
assert!(crate::execute(&mut session, "export.plan", &json!({ "ts": wrapped_index })).is_err());
assert!(crate::execute(&mut session, "export.plan", &json!({ "ts": [wrapped_index] })).is_err());
}
}
+4 -3
View File
@@ -149,10 +149,11 @@ fn mat_finish(id: &str) -> Option<Fill> {
"matFinishHammered" => (ProceduralKind::Hammered, 6.0, [0.25, 0.45], 0.08),
_ => return None,
};
let pattern = Procedural { scale, ..Procedural::new(kind) };
let mut fill = Fill { projection: Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] }, ..Fill::default() };
fill.sources.insert(Channel::Roughness, Source::Procedural { pattern: pattern.clone(), low: [rough[0]; 3], high: [rough[1]; 3] });
fill.sources.insert(Channel::Height, Source::Procedural { pattern, low: [-height; 3], high: [height; 3] });
fill.sources.insert(Channel::Roughness, Source::Procedural { pattern: pattern.clone(), low: [rough[0]; 3], high: [rough[1]; 3], ramp: Vec::new() });
fill.sources.insert(Channel::Height, Source::Procedural { pattern, low: [-height; 3], high: [height; 3], ramp: Vec::new() });
Some(fill)
}
@@ -264,7 +265,7 @@ pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> {
let parsed: Option<Vec<[f32; 3]>> = list.as_array().and_then(|a| a.iter().map(|c| color_of(c).map(|v| v.map(|x| x.clamp(0.0, 1.0)))).collect());
match parsed {
Some(c) if (1..=16).contains(&c.len()) => *colors = c,
_ => return Err(bad(cmd, "`colors` must be 1 to 16 colors ([r, g, b] linear or \"#rrggbb\")")),
_ => return Err(bad(cmd, "`colors` must be 1 to 16 colors ([r, g, b] linear or \"#rrggbb\" sRGB)")),
}
}
}
+5
View File
@@ -0,0 +1,5 @@
#[derive(Clone, Copy)]
pub(crate) enum FrameTarget {
All,
Selection,
}
+50 -27
View File
@@ -7,18 +7,38 @@ use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, Laye
use crate::Session;
use crate::session::StackTarget;
fn source_json(s: &Source) -> Value {
match s {
Source::Uniform(v) => json!({ "uniform": v }),
Source::Procedural { pattern, low, high } => json!({
"procedural": pattern.kind.label(), "scale": pattern.scale, "seed": pattern.seed, "contrast": pattern.contrast, "low": low, "high": high
}),
fn source_json(source: &Source) -> Value {
match source {
Source::Uniform(value) => json!({ "uniform": value }),
Source::Procedural { pattern, low, high, ramp } => {
let mut report = json!({
"procedural": pattern.kind.label(), "scale": pattern.scale, "seed": pattern.seed, "contrast": pattern.contrast, "low": low, "high": high
});
if !pattern.resolution.is_default() {
report["resolution"] =
json!({ "mode": format!("{:?}", pattern.resolution.mode), "custom": pattern.resolution.custom, "factor": pattern.resolution.factor });
}
if let Some(tile) = &pattern.tile {
report["tile"] = crate::procedural_params::tile_report(tile);
}
with_ramp(report, ramp)
}
Source::Image { name, normal_format: NormalFormat::OpenGl } => json!({ "image": name }),
Source::Image { name, normal_format: NormalFormat::DirectX } => json!({ "image": name, "normalFormat": "directX" }),
Source::Anchor { anchor, channel } => json!({ "anchor": anchor.0, "channel": channel.id() }),
Source::Anchor { anchor, channel, ramp } => with_ramp(json!({ "anchor": anchor.0, "channel": channel.id() }), ramp),
}
}
/// `v` with the gradient map stops of its source as `colors`, when it has any.
fn with_ramp(mut v: Value, ramp: &[[f32; 3]]) -> Value {
if !ramp.is_empty() {
v["colors"] = json!(ramp);
}
v
}
fn fill_json(f: &Fill) -> Value {
let mut v = json!({
"projection": f.projection.label(),
@@ -182,26 +202,29 @@ pub fn texture_set(session: &Session, index: usize) -> Value {
}
/// The whole session.
pub fn session(s: &Session) -> Value {
let ts = s.ts();
pub fn session(session: &Session) -> Value {
let texture_set = session.ts();
json!({
"project": s.doc.project.name,
"mesh": { "source": s.doc.project.mesh, "triangles": s.mesh.triangle_count(), "vertices": s.mesh.vertex_count(), "materials": s.mesh.materials },
"path": s.path,
"modified": s.modified,
"textureSets": texture_sets(s),
"bakeMeshes": crate::bake::meshes_json(s),
"activeTextureSet": ts,
"selectedLayer": s.selected_layer().map(|l| l.0),
"target": match s.target { StackTarget::Content => json!("content"), StackTarget::Mask => json!("mask"), StackTarget::Effect(e) => json!(e.0) },
"layers": stack(s, ts),
"tool": { "tool": s.tool.tool.id(), "brush": crate::tool_cmds::brush_json(s) },
"view": s.view.label(),
"bakePreview": crate::bake_preview::preview_json(s),
"camera": crate::view_cmds::camera_json(s),
"display": s.doc.project.display,
"history": { "undo": s.undo_label(), "redo": s.redo_label(), "depth": s.history_labels().len() },
"memoryBytes": s.memory().total(),
"pendingTiles": s.pending_tiles(),
"projectOpen": session.project_open,
"project": session.doc.project.name,
"mesh": { "source": session.doc.project.mesh, "triangles": session.mesh.triangle_count(), "vertices": session.mesh.vertex_count(), "materials": session.mesh.materials },
"path": session.path,
"modified": session.modified,
"textureSets": texture_sets(session),
"bakeMeshes": crate::bake::meshes_json(session),
"activeTextureSet": texture_set,
"selectedLayer": session.selected_layer().map(|layer| layer.0),
"selectedLayers": crate::layer_selection::ids_json(&session.selected_layers()),
"target": match session.target { StackTarget::Content => json!("content"), StackTarget::Mask => json!("mask"), StackTarget::Effect(effect) => json!(effect.0) },
"layers": stack(session, texture_set),
"tool": { "tool": session.tool.tool.id(), "brush": crate::tool_cmds::brush_json(session) },
"view": session.view.label(),
"solo": session.solo.map(|solo| json!({ "layer": solo.layer.0, "ignoreMask": solo.ignore_mask })),
"bakePreview": crate::bake_preview::preview_json(session),
"camera": crate::view_cmds::camera_json(session),
"display": session.doc.project.display,
"history": { "undo": session.undo_label(), "redo": session.redo_label(), "depth": session.history_labels().len() },
"memoryBytes": session.memory().total(),
"pendingTiles": session.pending_tiles(),
})
}
+2 -2
View File
@@ -49,7 +49,7 @@ pub(crate) fn make_instance(s: &mut Session, source: LayerId, ts: usize) -> Resu
let sel = s.selected.get(&ts).copied().filter(|l| s.doc.project.locate(*l).is_some_and(|(t, _, _)| t == ts));
let inside = sel.and_then(|l| s.doc.project.layer(l).ok()).is_some_and(Layer::is_group);
s.doc.project.insert_layer(ts, Layer::new(id, name, LayerKind::Instance { source: src_id }, &[]), sel, inside)?;
s.selected.insert(ts, id);
s.select_one(ts, id);
if ts == s.ts() {
s.target = StackTarget::Content;
}
@@ -98,7 +98,7 @@ pub(crate) fn detach(s: &mut Session, src: &Document, inst: LayerId) -> Result<L
}
s.doc.project.remove_layer(inst)?;
if s.selected.get(&ts) == Some(&inst) {
s.selected.insert(ts, copy);
s.select_one(ts, copy);
}
Ok(copy)
}
+447 -116
View File
@@ -2,32 +2,101 @@
//! per-channel blending and fill sources.
use serde_json::{Value, json};
use texturecraft_core::{BlendMode, Channel, ChannelBlend, EffectKind, Fill, Layer, LayerId, LayerKind, Procedural, ProceduralKind, Projection, Source};
use texturecraft_core::{
BlendMode, Channel, ChannelBlend, ChannelKind, EffectKind, Fill, Layer, LayerId, LayerKind, NormalFormat, Procedural, ProceduralKind, Project, Projection,
Source,
};
use crate::commands::{
CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, content_param, f32p, has_layer, layer_param, normal_format_param, strp, u64p,
};
use crate::layer_selection::{batch_param, ids_json};
use crate::{EngineError, Result, Session, cmd, session::StackTarget};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("layer.add.paint", "Add paint layer", ["Layers"], None, "{name?}", always, add_paint),
cmd!("layer.add.fill", "Add fill layer", ["Layers"], None, "{name?, color?, roughness?, metallic?}", always, add_fill),
cmd!(
"layer.add.fill",
"Add fill layer",
["Layers"],
None,
"{name?, color?: [r,g,b] linear or \"#rrggbb\" sRGB, roughness?, metallic?}",
always,
add_fill
),
cmd!("layer.add.group", "Add folder", ["Layers"], None, "{name?}", always, add_group),
cmd!("layer.remove", "Remove layer(s)", ["Layers"], Some("Delete"), "{layer?}", has_layer, remove),
cmd!("layer.duplicate", "Duplicate layer(s)", ["Layers"], Some("Ctrl+D"), "{layer?}", has_layer, duplicate),
cmd!("layer.group", "Group layer(s)", ["Layers"], Some("Ctrl+G"), "{layer?}", has_layer, group),
cmd!("layer.select", "Select layer", [], None, "{layer, target?: content|mask|<effect id>}", always, select),
cmd!(
"layer.remove",
"Remove layer(s)",
["Layers"],
Some("Delete"),
"{layer?, layers?: [id] (wins over `layer`)} — default: every selected layer",
has_layer,
remove
),
cmd!(
"layer.duplicate",
"Duplicate layer(s)",
["Layers"],
Some("Ctrl+D"),
"{layer?, layers?: [id] (wins over `layer`)} — default: every selected layer",
has_layer,
duplicate
),
cmd!(
"layer.group",
"Group layer(s)",
["Layers"],
Some("Ctrl+G"),
"{layer?, layers?: [id] (wins over `layer`)} — default: every selected layer",
has_layer,
group
),
cmd!(
"layer.select",
"Select layer",
[],
None,
"{layer, target?: content|mask|<effect id>} | {layer, toggle: true} (Ctrl+click: add or take out one layer) | {layer, range: true} (Shift+click: the rows from the last clicked layer) | {all: true} (Ctrl+A: every shown row of the active texture set, folder rows and the layers of open folders included) | {layers: [id], layer?} (select several; `layer` is the active one)",
always,
select
),
cmd!("layer.rename", "Rename layer", [], None, "{layer?, name}", has_layer, rename),
cmd!("layer.visible", "Toggle layer visibility", [], None, "{layer?, visible?}", has_layer, visible),
cmd!("layer.move", "Move layer", [], None, "{layer?, index?} | {layer?, above?: id|null, inside?: bool} | {layer?, delta: ±n}", has_layer, move_layer),
cmd!(
"layer.visible",
"Toggle layer visibility",
[],
None,
"{layer?, layers?: [id], visible?} — default: every selected layer; with `layers`, `layer` is the one the others follow",
has_layer,
visible
),
cmd!(
"layer.move",
"Move layer",
[],
None,
"{layer? | layers?: [id], index?} | {layer? | layers?: [id], above?: id|null, inside?: bool} | {layer?, delta: ±n}",
has_layer,
move_layer
),
cmd!("layer.blend", "Set channel blending", [], None, "{layer?, channel?: id|all, mode?, opacity?: 0..1, enabled?}", has_layer, blend),
cmd!(
"layer.blending.set",
"Set blending of several channels",
[],
None,
"{layer?, channels: {<channel id>: {mode?, opacity?: 0..1}}} (only channels the layer has enabled; one undo step)",
has_layer,
blending_set
),
cmd!(
"layer.fill.set",
"Set fill source",
[],
None,
"{layer? | effect?: content fill effect id, channel, color?|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?|image?, normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, enabled?, solo?: true (this channel on, every other one off)}",
"{layer? | effect?: content fill effect id, channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?, normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}",
has_layer,
fill_set
),
@@ -51,7 +120,7 @@ pub(crate) fn insert_selected(s: &mut Session, layer: Layer) -> Result<LayerId>
let sel = s.selected_layer();
let inside = sel.and_then(|id| s.doc.project.layer(id).ok()).is_some_and(|l| l.is_group());
let id = s.doc.project.insert_layer(ts, layer, sel, inside)?;
s.selected.insert(ts, id);
s.select_one(ts, id);
s.target = StackTarget::Content;
Ok(id)
}
@@ -110,45 +179,66 @@ fn add_group(s: &mut Session, p: &Value) -> Result<Value> {
}
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.remove", p)?;
let ids = batch_param(s, "layer.remove", p, true)?;
let before = s.doc.clone();
let removed = s.edit("Remove layer", |s| {
let (ts, parent, i) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?;
let removed = s.doc.project.remove_layer(id)?;
// Instances of what was removed keep their look as independent layers.
let mut removed = Vec::new();
// Top row first, so the layer under the lowest removed one is never removed after it is chosen
for id in &ids {
let (ts, parent, i) = s.doc.project.locate(*id).ok_or(EngineError::Other("layer not in a stack".into()))?;
removed.extend(s.doc.project.remove_layer(*id)?);
// Select the layer below (or above) the removed one
let list = match parent {
Some(g) => s.doc.project.layer(g).map(|l| l.children().to_vec()).unwrap_or_default(),
None => s.doc.project.texture_set(ts).map(|t| t.stack.clone()).unwrap_or_default(),
};
let next = list.get(i.saturating_sub(1)).or(list.first()).copied().or(parent);
match next {
Some(n) => s.select_one(ts, n),
None => s.select_none(ts),
}
}
// Instances of what was removed keep their look as independent layers
crate::instance_cmds::detach_orphans(s, &before)?;
// Select the layer below (or above) the removed one.
let list = match parent {
Some(g) => s.doc.project.layer(g).map(|l| l.children().to_vec()).unwrap_or_default(),
None => s.doc.project.texture_set(ts).map(|t| t.stack.clone()).unwrap_or_default(),
};
let next = list.get(i.saturating_sub(1)).or(list.first()).copied().or(parent);
match next {
Some(n) => s.selected.insert(ts, n),
None => s.selected.remove(&ts),
};
Ok(removed)
})?;
Ok(json!({ "removed": removed.iter().map(|l| l.0).collect::<Vec<_>>() }))
}
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.duplicate", p)?;
let (ts, _, _) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?;
let ids = batch_param(s, "layer.duplicate", p, true)?;
let first = ids.first().copied().ok_or_else(|| bad("layer.duplicate", "no layer to duplicate"))?;
let (ts, _, _) = s.doc.project.locate(first).ok_or(EngineError::Other("layer not in a stack".into()))?;
let src = s.doc.clone();
let new = s.edit("Duplicate layer", |s| {
let new = crate::layer_ops::copy_tree(&src, id, &mut s.doc, ts, Some(id), false, 0)?;
let name = format!("{} copy", src.project.layer(id)?.name);
s.doc.project.layer_mut(new)?.name = name;
Ok(new)
let copies = s.edit("Duplicate layer", |s| {
// Insert copies in order above the topmost selected layer, at its folder level
let mut copies = Vec::new();
let mut above = first;
for id in ids.iter().rev() {
let new = crate::layer_ops::copy_tree(&src, *id, &mut s.doc, ts, Some(above), false, 0)?;
let name = format!("{} copy", src.project.layer(*id)?.name);
s.doc.project.layer_mut(new)?.name = name;
copies.insert(0, new);
above = new;
}
Ok(copies)
})?;
s.selected.insert(ts, new);
Ok(json!({ "layer": new.0 }))
// The copies are selected; the active layer's copy stays the active one
let active =
s.selected.get(&ts).and_then(|active| ids.iter().position(|id| id == active)).and_then(|i| copies.get(i)).or(copies.first()).copied().unwrap_or(first);
s.select_several(ts, active, active, copies.clone());
Ok(json!({ "layer": active.0, "layers": ids_json(&copies) }))
}
fn group(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.group", p)?;
let ids = batch_param(s, "layer.group", p, true)?;
let g = s.edit("Group layers", |s| {
// The folder takes the top layer's place and parent; the others follow it in, in stack order
let id = ids.first().copied().ok_or_else(|| bad("layer.group", "no layer to group"))?;
let (ts, _, _) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?;
let gid = s.doc.project.alloc_id();
let name = s.doc.project.next_layer_name(ts, "Folder");
@@ -158,29 +248,51 @@ fn group(s: &mut Session, p: &Value) -> Result<Value> {
b.mode = BlendMode::Passthrough;
}
s.doc.project.insert_layer(ts, gl, Some(id), false)?;
s.doc.project.move_above(id, Some(gid), true)?;
s.selected.insert(ts, gid);
move_stacked(&mut s.doc.project, &ids, Some(gid), true)?;
s.select_one(ts, gid);
Ok(gid)
})?;
Ok(json!({ "layer": g.0 }))
}
fn select(s: &mut Session, p: &Value) -> Result<Value> {
if boolp(p, "all") == Some(true) {
return crate::layer_selection::select_all(s);
}
if p.get("layers").is_some() {
return crate::layer_selection::select_list(s, p);
}
let id = layer_param(s, "layer.select", p)?;
let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| bad("layer.select", "layer not in a stack"))?;
// Paths paint into the active set
if ts != s.ts() {
s.finish_path()?;
// The clone source is a point of the set it was picked in
s.tool.clone_source = None;
}
// Shift+click and Ctrl/Cmd+click select several layers, each on its content
let range = boolp(p, "range") == Some(true);
if range || boolp(p, "toggle") == Some(true) {
s.active_set = ts;
let active = crate::layer_selection::extend(s, ts, id, range);
s.target = StackTarget::Content;
s.revision = s.revision.wrapping_add(1);
return Ok(json!({ "layer": active.map(|active| active.0), "textureSet": ts, "layers": ids_json(&s.selected_layers()) }));
}
s.active_set = ts;
s.selected.insert(ts, id);
s.select_one(ts, id);
s.target = match p.get("target") {
Some(Value::String(t)) if t == "mask" => {
if s.doc.project.layer(s.doc.project.mask_owner(id))?.mask.is_none() {
return Err(bad("layer.select", "the layer has no mask"));
}
StackTarget::Mask
}
Some(Value::String(t)) if t == "content" => StackTarget::Content,
@@ -192,7 +304,7 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
};
s.revision = s.revision.wrapping_add(1);
Ok(json!({ "layer": id.0, "textureSet": ts }))
Ok(json!({ "layer": id.0, "textureSet": ts, "layers": [id.0] }))
}
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
@@ -209,33 +321,105 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
}
fn visible(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.visible", p)?;
let ids = batch_param(s, "layer.visible", p, false)?;
// Use the clicked layer as lead, then the active or top layer if absent
let lead = u64p(p, "layer")
.map(LayerId)
.filter(|lead| ids.contains(lead))
.or(s.selected_layer().filter(|active| ids.contains(active)))
.or(ids.first().copied())
.ok_or_else(|| bad("layer.visible", "no layer given"))?;
let v = s.edit("Layer visibility", |s| {
let l = s.doc.project.layer_mut(id)?;
l.visible = boolp(p, "visible").unwrap_or(!l.visible);
Ok(l.visible)
let v = boolp(p, "visible").unwrap_or(!s.doc.project.layer(lead)?.visible);
for id in &ids {
s.doc.project.layer_mut(*id)?.visible = v;
}
Ok(v)
})?;
Ok(json!({ "visible": v }))
}
/// Move `ids` (top row first) above `target` (inside it when `inside`), keeping their order:
/// the lowest goes first and each next one above it.
fn move_stacked(project: &mut Project, ids: &[LayerId], target: Option<LayerId>, inside: bool) -> Result<()> {
let (mut target, mut inside) = (target, inside);
for id in ids.iter().rev() {
project.move_above(*id, target, inside)?;
(target, inside) = (Some(*id), false);
}
Ok(())
}
/// The positions of the moved layers determine whether a reorder needs an undo step.
fn apply_move(s: &mut Session, ids: &[LayerId], change: impl FnOnce(&mut Project) -> Result<()>) -> Result<Value> {
s.edit_if_changed("Move layer", s.merge_edits, |s| {
let project = &mut s.doc.project;
let previous: Vec<_> = ids.iter().map(|id| project.locate(*id)).collect();
change(project)?;
let changed = ids.iter().map(|id| project.locate(*id)).ne(previous);
Ok((Value::Null, changed))
})
}
/// `layer.move {layers, index | above}`: the listed layers move together, keeping their order.
fn move_layers(s: &mut Session, p: &Value) -> Result<Value> {
let ids = batch_param(s, "layer.move", p, true)?;
if let Some(i) = u64p(p, "index") {
// The lowest one goes to `index` of the texture set's stack, the others right above it in their order
let to = usize::try_from(i).unwrap_or(usize::MAX);
apply_move(s, &ids, |project| {
let mut below = None;
for id in ids.iter().rev() {
match below {
None => {
project.move_above(*id, None, false)?;
project.move_layer(*id, to)?;
}
Some(below) => project.move_above(*id, Some(below), false)?,
}
below = Some(*id);
}
Ok(())
})
} else if p.get("above").is_some() {
let above = u64p(p, "above").map(LayerId);
if above.is_some_and(|above| ids.contains(&above)) {
return Err(bad("layer.move", "`above` is one of the moved layers"));
}
let inside = boolp(p, "inside").unwrap_or(false);
apply_move(s, &ids, |project| move_stacked(project, &ids, above, inside))
} else {
Err(bad("layer.move", "give `index` or `above` with `layers`"))
}
}
fn move_layer(s: &mut Session, p: &Value) -> Result<Value> {
if p.get("layers").is_some() {
return move_layers(s, p);
}
let id = layer_param(s, "layer.move", p)?;
s.edit("Move layer", |s| {
apply_move(s, &[id], |project| {
if let Some(d) = p.get("delta").and_then(Value::as_i64) {
let (_, _, i) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?;
let to = (i as i64 + d).max(0) as usize;
s.doc.project.move_layer(id, to)?;
let (_, _, i) = project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?;
// Saturate hostile deltas before the sibling-list clamp
let distance = usize::try_from(d.unsigned_abs()).unwrap_or(usize::MAX);
let to = if d < 0 { i.saturating_sub(distance) } else { i.saturating_add(distance) };
project.move_layer(id, to)?;
} else if let Some(i) = u64p(p, "index") {
s.doc.project.move_layer(id, usize::try_from(i).unwrap_or(usize::MAX))?;
project.move_layer(id, usize::try_from(i).unwrap_or(usize::MAX))?;
} else if p.get("above").is_some() {
let above = u64p(p, "above").map(LayerId);
s.doc.project.move_above(id, above, boolp(p, "inside").unwrap_or(false))?;
project.move_above(id, above, boolp(p, "inside").unwrap_or(false))?;
} else {
return Err(bad("layer.move", "give `delta`, `index` or `above`"));
}
Ok(())
})?;
Ok(Value::Null)
})
}
fn blend(s: &mut Session, p: &Value) -> Result<Value> {
@@ -278,6 +462,35 @@ fn blend(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
/// `layer.blending.set`: each listed channel gets its own mode and opacity in one undo step. Channels the layer
/// has disabled stay disabled, and channels not listed stay as they are.
fn blending_set(s: &mut Session, p: &Value) -> Result<Value> {
let id = content_param(s, "layer.blending.set", p)?;
let listed = p.get("channels").and_then(Value::as_object).ok_or_else(|| bad("layer.blending.set", "`channels` is required"))?;
let mut edits: Vec<(Channel, Option<BlendMode>, Option<f32>)> = Vec::new();
for (key, value) in listed {
let channel = Channel::parse(key).ok_or_else(|| bad("layer.blending.set", format!("unknown channel `{key}`")))?;
let mode = blend_param("layer.blending.set", value, "mode")?;
let opacity = f32p(value, "opacity").map(|o| o.clamp(0.0, 1.0));
edits.push((channel, mode, opacity));
}
s.edit("Layer blending", |s| {
let l = s.doc.project.layer_mut(id)?;
for (channel, mode, opacity) in edits {
if let Some(b) = l.channels.get_mut(&channel) {
if let Some(m) = mode {
b.mode = m;
}
if let Some(o) = opacity {
b.opacity = o;
}
}
}
Ok(())
})?;
Ok(Value::Null)
}
/// Which fill `layer.fill.*` edits: a fill layer's (`layer`) or a content fill effect's
/// (`effect`).
#[derive(Clone, Copy)]
@@ -309,89 +522,77 @@ fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> {
}
}
fn fill_set(s: &mut Session, p: &Value) -> Result<Value> {
let target = fill_target(s, p, "layer.fill.set")?;
let ch = channel_param("layer.fill.set", p, "channel")?.ok_or_else(|| bad("layer.fill.set", "`channel` is required"))?;
// `solo`: this channel on, every other one off.
let solo = boolp(p, "solo") == Some(true);
let enabled = if solo { Some(true) } else { boolp(p, "enabled") };
let normal_format = normal_format_param("layer.fill.set", p)?;
let low = color_param("layer.fill.set", p, "low")?.unwrap_or([0.0; 3]);
let high = color_param("layer.fill.set", p, "high")?.unwrap_or([1.0; 3]);
let color = color_param("layer.fill.set", p, "color")?;
let value = color_param("layer.fill.set", p, "value")?;
let source = if let Some(kind) = strp(p, "procedural") {
let kind = ProceduralKind::parse(kind).ok_or_else(|| bad("layer.fill.set", format!("unknown procedural `{kind}`")))?;
let mut pr = Procedural::new(kind);
if let Some(v) = f32p(p, "scale") {
pr.scale = v.clamp(0.001, 1000.0);
}
if let Some(v) = u64p(p, "seed") {
pr.seed = v as u32;
}
if let Some(v) = f32p(p, "contrast") {
pr.contrast = v.clamp(0.0, 20.0);
}
if let Some(v) = f32p(p, "balance") {
pr.balance = v.clamp(-1.0, 1.0);
}
pr.invert = boolp(p, "invert").unwrap_or(false);
Some(Source::Procedural { pattern: pr, low, high })
} else if let Some(c) = color.or(value) {
Some(Source::Uniform(c))
} else if let Some(name) = strp(p, "image") {
Some(Source::Image { name: name.to_string(), normal_format: normal_format.unwrap_or_default() })
} else if let Some(a) = u64p(p, "anchor") {
let reader = match target {
FillTarget::Layer(id) => Some(id),
FillTarget::Effect(e) => s.doc.project.effect(e).map(|(owner, _)| owner),
};
let reader = reader.ok_or_else(|| bad("layer.fill.set", "the fill is not in a layer"))?;
let anchor_channel = channel_param("layer.fill.set", p, "anchorChannel")?.unwrap_or(ch);
Some(crate::mask_cmds::anchor_source(s, "layer.fill.set", reader, LayerId(a), anchor_channel)?)
} else if enabled.is_some() || normal_format.is_some() {
None
} else {
return Err(bad("layer.fill.set", "give `color`, `value`, `procedural`, `image`, `anchor`, `normalFormat`, `enabled` or `solo`"));
};
if normal_format.is_some() && source.as_ref().is_some_and(|src| !matches!(src, Source::Image { .. })) {
return Err(bad("layer.fill.set", "`normalFormat` goes with `image` or alone"));
fn fill_set(session: &mut Session, params: &Value) -> Result<Value> {
const CMD: &str = "layer.fill.set";
let target = fill_target(session, params, CMD)?;
let channel = channel_param(CMD, params, "channel")?.ok_or_else(|| bad(CMD, "`channel` is required"))?;
// `solo`: this channel on, every other one off
let solo = boolp(params, "solo") == Some(true);
let enabled = if solo { Some(true) } else { boolp(params, "enabled") };
let normal_format = normal_format_param(CMD, params)?;
let colors = ramp_param(params, channel)?;
let init_ramp = boolp(params, "gradientMap") == Some(true);
if init_ramp && colors.is_some() {
return Err(bad(CMD, "give `gradientMap` or `colors`, not both"));
}
// A format-only edit leaves the channel on or off.
let source = fill_source_from(session, params, (target, channel), normal_format)?;
if source.is_none() && enabled.is_none() && normal_format.is_none() && colors.is_none() && !init_ramp {
return Err(bad(
CMD,
"give `color`, `value`, `procedural`, `image`, `anchor`, pattern settings (`tile`, `resolution`…), `colors`, `gradientMap`, `normalFormat`, `enabled` or `solo`",
));
}
if normal_format.is_some() && source.as_ref().is_some_and(|source| !matches!(source, Source::Image { .. })) {
return Err(bad(CMD, "`normalFormat` goes with `image` or alone"));
}
// Changing only the normal format or gradient stops leaves the layer channel on or off
let touches_channel = source.is_some() || enabled.is_some();
s.edit("Set fill", |s| {
let f = fill_mut(s, target)?;
// `normalFormat` alone: the convention of the channel's image.
if let (None, Some(nf)) = (&source, normal_format) {
match f.sources.get_mut(&ch) {
Some(Source::Image { normal_format, .. }) => *normal_format = nf,
_ => return Err(bad("layer.fill.set", "`normalFormat` needs an image on the channel")),
session.edit("Set fill", |session| {
let fill = fill_mut(session, target)?;
// `normalFormat` alone: the convention of the channel's image
if let (None, Some(format)) = (&source, normal_format) {
match fill.sources.get_mut(&channel) {
Some(Source::Image { normal_format, .. }) => *normal_format = format,
_ => return Err(bad(CMD, "`normalFormat` needs an image on the channel")),
}
}
let current = fill.sources.get(&channel);
let colors = if init_ramp { initial_ramp(channel, source.as_ref(), current)? } else { colors };
let source = with_ramp(channel, current, source, colors)?;
match target {
// A fill effect's channel is on while it has a source.
// A fill effect's channel is on while it has a source
FillTarget::Effect(_) if enabled == Some(false) => {
f.sources.remove(&ch);
fill.sources.remove(&channel);
}
// Removing stops (`colors: []`) from a channel the fill does not have adds nothing
FillTarget::Effect(_) if source.is_none() && enabled != Some(true) && current.is_none() => {}
FillTarget::Effect(_) => {
let src = source.unwrap_or_else(|| f.source(ch));
f.sources.insert(ch, src);
let source = source.unwrap_or_else(|| fill.source(channel));
fill.sources.insert(channel, source);
if solo {
f.sources.retain(|c, _| *c == ch);
fill.sources.retain(|kept, _| *kept == channel);
}
}
FillTarget::Layer(id) => {
if let Some(src) = source {
f.sources.insert(ch, src);
if let Some(source) = source {
fill.sources.insert(channel, source);
}
let l = s.doc.project.layer_mut(id)?;
let layer = session.doc.project.layer_mut(id)?;
if enabled == Some(false) {
l.channels.remove(&ch);
layer.channels.remove(&channel);
} else if touches_channel {
l.channels.entry(ch).or_default();
layer.channels.entry(channel).or_default();
}
if solo {
l.channels.retain(|c, _| *c == ch);
layer.channels.retain(|kept, _| *kept == channel);
}
}
}
@@ -400,6 +601,136 @@ fn fill_set(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
/// The source `params` give fill channel `channel` of `target`, or None when they only switch it or set its image's normal format
fn fill_source_from(
session: &mut Session,
params: &Value,
(target, channel): (FillTarget, Channel),
normal_format: Option<NormalFormat>,
) -> Result<Option<Source>> {
const CMD: &str = "layer.fill.set";
let low = color_param(CMD, params, "low")?.unwrap_or([0.0; 3]);
let high = color_param(CMD, params, "high")?.unwrap_or([1.0; 3]);
let uniform = color_param(CMD, params, "color")?.or(color_param(CMD, params, "value")?);
if let Some(name) = strp(params, "procedural") {
let kind = ProceduralKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown procedural `{name}`")))?;
let mut pattern = Procedural::new(kind);
crate::procedural_params::pattern_basics_from(params, &mut pattern);
// A pattern of the same kind keeps its resolution and Tile Generator settings
let current = fill_mut(session, target)?.sources.get(&channel);
if let Some(Source::Procedural { pattern: current, .. }) = current
&& current.kind == kind
{
pattern.resolution = current.resolution;
pattern.tile = current.tile.clone();
}
crate::procedural_params::pattern_settings_from(CMD, params, &mut pattern)?;
return Ok(Some(Source::Procedural { pattern, low, high, ramp: Vec::new() }));
}
if let Some(color) = uniform {
return Ok(Some(Source::Uniform(color)));
}
if let Some(name) = strp(params, "image") {
return Ok(Some(Source::Image { name: name.to_string(), normal_format: normal_format.unwrap_or_default() }));
}
if let Some(anchor) = u64p(params, "anchor") {
let reader = match target {
FillTarget::Layer(id) => Some(id),
FillTarget::Effect(effect) => session.doc.project.effect(effect).map(|(owner, _)| owner),
};
let reader = reader.ok_or_else(|| bad(CMD, "the fill is not in a layer"))?;
let anchor_channel = channel_param(CMD, params, "anchorChannel")?.unwrap_or(channel);
return Ok(Some(crate::mask_cmds::anchor_source(session, CMD, reader, LayerId(anchor), anchor_channel)?));
}
if !crate::procedural_params::has_pattern_settings(params) {
return Ok(None);
}
// Pattern settings alone edit the channel's current pattern
let Some(Source::Procedural { pattern, low, high, .. }) = fill_mut(session, target)?.sources.get(&channel) else {
return Err(bad(CMD, "the channel has no pattern: give `procedural` with its settings"));
};
let mut pattern = pattern.clone();
crate::procedural_params::pattern_basics_from(params, &mut pattern);
crate::procedural_params::pattern_settings_from(CMD, params, &mut pattern)?;
Ok(Some(Source::Procedural { pattern, low: *low, high: *high, ramp: Vec::new() }))
}
/// The gradient map stops from `colors` (None when absent, empty to remove).
fn ramp_param(params: &Value, channel: Channel) -> Result<Option<Vec<[f32; 3]>>> {
const MAX_GRADIENT_STOPS: usize = 16;
let Some(list) = params.get("colors").filter(|value| !value.is_null()) else { return Ok(None) };
let invalid = || bad("layer.fill.set", "`colors` must be up to 16 colors ([r, g, b] linear or \"#rrggbb\")");
let list = list.as_array().filter(|list| list.len() <= MAX_GRADIENT_STOPS).ok_or_else(invalid)?;
let colors: Vec<_> = list
.iter()
.map(|color| crate::commands::color_of(color).map(|rgb| rgb.map(|component| component.clamp(0.0, 1.0))).ok_or_else(invalid))
.collect::<Result<_>>()?;
if !colors.is_empty() && channel.kind() != ChannelKind::Color {
return Err(bad("layer.fill.set", "`colors` (a gradient map) goes on a color channel"));
}
Ok(Some(colors))
}
/// The stops `gradientMap: true` turns on for channel `ch`: those the source already has, else a
/// procedural's low, midpoint and high (so its look holds) or an anchor's black, gray and white.
/// `source` is the one the call sets, else the channel's `current` one.
fn initial_ramp(channel: Channel, source: Option<&Source>, current: Option<&Source>) -> Result<Option<Vec<[f32; 3]>>> {
if channel.kind() != ChannelKind::Color {
return Err(bad("layer.fill.set", "`gradientMap` goes on a color channel"));
}
if let Some(kept) = current.map(Source::ramp).filter(|r| !r.is_empty()) {
return Ok(Some(kept.to_vec()));
}
match source.or(current) {
Some(Source::Procedural { low, high, .. }) => Ok(Some(vec![*low, std::array::from_fn(|k| (low[k] + high[k]) * 0.5), *high])),
Some(Source::Anchor { .. }) => Ok(Some(vec![[0.0; 3], [0.5; 3], [1.0; 3]])),
_ => Err(bad("layer.fill.set", "`gradientMap` needs a procedural or an anchor on the channel")),
}
}
/// `source` (or, for `colors` alone, the channel's `current` source) with its gradient map stops:
/// `colors` when given, else those of `current`, so picking another pattern or anchor keeps them.
/// Only color channels keep stops, so a source copied onto another channel loses them; removing
/// stops (`colors: []`) where there are none changes nothing.
fn with_ramp(channel: Channel, current: Option<&Source>, source: Option<Source>, colors: Option<Vec<[f32; 3]>>) -> Result<Option<Source>> {
let adds = colors.as_ref().is_some_and(|colors| !colors.is_empty());
let needs = || bad("layer.fill.set", "`colors` needs a procedural or an anchor on the channel");
let mut source = match (source, current) {
(Some(source), _) => source,
(None, Some(current)) if colors.is_some() => current.clone(),
_ if adds => return Err(needs()),
_ => return Ok(None),
};
match &mut source {
Source::Procedural { ramp, .. } | Source::Anchor { ramp, .. } => {
*ramp = colors.unwrap_or_else(|| match current {
Some(current) if channel.kind() == ChannelKind::Color => current.ramp().to_vec(),
_ => Vec::new(),
});
}
_ if adds => return Err(needs()),
_ => {}
}
Ok(Some(source))
}
/// The projection `p` asks for. Fields it does not give keep their values from `current` when
/// that is of the same kind (or `p` names no kind), and the kind's defaults otherwise.
pub(crate) fn projection_from(p: &Value, cmd: &str, current: Option<&Projection>) -> Result<Projection> {
+3 -3
View File
@@ -128,7 +128,7 @@ fn paste(s: &mut Session, _: &Value) -> Result<Value> {
let sel = s.selected_layer();
let inside = sel.and_then(|l| s.doc.project.layer(l).ok()).is_some_and(|l| l.is_group());
let new = copy_tree(&src, id, &mut s.doc, ts, sel, inside, 0)?;
s.selected.insert(ts, new);
s.select_one(ts, new);
s.target = StackTarget::Content;
Ok(new)
})?;
@@ -147,8 +147,8 @@ fn to_all_sets(s: &mut Session, p: &Value) -> Result<Value> {
let new = if copy {
copy_tree(&src, id, &mut s.doc, ts, None, false, 0)?
} else {
// On top of the set: clear its selection first.
s.selected.remove(&ts);
// On top of the set: clear its selection first
s.select_none(ts);
crate::instance_cmds::make_instance(s, id, ts)?
};
made.push(new.0);
+260
View File
@@ -0,0 +1,260 @@
//! Several selected layers, as in the reference app: Shift+click selects the rows between the
//! last clicked layer and the clicked one, Ctrl/Cmd+click adds or removes one layer, and the
//! batch layer commands (remove, duplicate, group, visibility, move) act on every selected layer.
//!
//! The selected layer (`Session::selected`) stays the active one the properties panel shows. The
//! layers picked with it live beside it and count only while it is still the layer they were
//! picked with, so any command that selects another layer leaves a single selection without
//! having to know about this one.
use serde_json::{Value, json};
use texturecraft_core::project::MAX_DEPTH;
use texturecraft_core::{LayerId, LayerKind, Project};
use crate::commands::{bad, u64p};
use crate::session::StackTarget;
use crate::{Result, Session};
mod multi_selection;
pub use multi_selection::MultiSelection;
impl Session {
/// Every selected layer of the active texture set, top row first: the selected layer and the
/// layers picked with it (Shift/Ctrl+click), or the selected layer alone.
pub fn selected_layers(&self) -> Vec<LayerId> {
let ts = self.ts();
let picked = self.selection_in(ts);
if picked.len() < 2 {
return picked;
}
stack_rows(&self.doc.project, ts, false).into_iter().filter(|id| picked.contains(id)).collect()
}
/// Whether `id` is one of the [`Session::selected_layers`].
pub fn is_layer_selected(&self, id: LayerId) -> bool {
let ts = self.ts();
let Some(active) = self.active_in(ts) else { return false };
match self.multi.get(&ts).filter(|multi| multi.active == active) {
Some(multi) => multi.layers.contains(&id) && self.doc.project.locate(id).is_some_and(|(set, _, _)| set == ts),
None => active == id,
}
}
/// The selected layer of texture set `ts`, if it is still in that set's stack.
fn active_in(&self, ts: usize) -> Option<LayerId> {
self.selected.get(&ts).copied().filter(|id| self.doc.project.locate(*id).is_some_and(|(t, _, _)| t == ts))
}
/// The layers picked with the selected layer of `ts`, while it is still the one they were
/// picked with.
fn multi_in(&self, ts: usize) -> Option<&MultiSelection> {
let active = self.active_in(ts)?;
self.multi.get(&ts).filter(|multi| multi.active == active)
}
/// The selected layers of texture set `ts` in the order they were picked.
fn selection_in(&self, ts: usize) -> Vec<LayerId> {
match self.multi_in(ts) {
Some(multi) => multi.layers.iter().copied().filter(|id| self.doc.project.locate(*id).is_some_and(|(t, _, _)| t == ts)).collect(),
None => self.active_in(ts).into_iter().collect(),
}
}
/// Select layer `id` alone in texture set `ts`.
pub(crate) fn select_one(&mut self, ts: usize, id: LayerId) {
self.selected.insert(ts, id);
self.multi.remove(&ts);
}
/// Select no layer in texture set `ts`.
pub(crate) fn select_none(&mut self, ts: usize) {
self.selected.remove(&ts);
self.multi.remove(&ts);
}
/// Select `layers` of texture set `ts` with `active` as the active layer (one of them) and
/// `anchor` where the next Shift+click range starts.
pub(crate) fn select_several(&mut self, ts: usize, active: LayerId, anchor: LayerId, layers: Vec<LayerId>) {
self.selected.insert(ts, active);
if layers.len() > 1 {
self.multi.insert(ts, MultiSelection { active, anchor, layers });
} else {
self.multi.remove(&ts);
}
}
}
/// The rows of texture set `ts` from the top, as the Layers panel lists them: each layer, then
/// its children unless `expanded_only` and the folder is collapsed.
pub fn stack_rows(project: &Project, ts: usize, expanded_only: bool) -> Vec<LayerId> {
let mut rows = Vec::new();
if let Some(set) = project.texture_sets.get(ts) {
push_rows(project, &set.stack, expanded_only, 0, &mut rows);
}
rows
}
fn push_rows(project: &Project, list: &[LayerId], expanded_only: bool, depth: usize, rows: &mut Vec<LayerId>) {
if depth > MAX_DEPTH {
return;
}
for id in list.iter().rev() {
let Some(layer) = project.layers.get(id) else { continue };
rows.push(*id);
if let LayerKind::Group { children, collapsed } = &layer.kind
&& !(expanded_only && *collapsed)
{
push_rows(project, children, expanded_only, depth + 1, rows);
}
}
}
/// `layer.select` with `toggle` (Ctrl/Cmd+click) or `range` (Shift+click) on `id` of texture set
/// `ts`. Returns the layer that becomes the active one (none when nothing stays selected).
///
/// A range covers the rows shown between the anchor and `id` (a collapsed folder's layers are
/// not shown, so they are not selected); `id` becomes active and the anchor stays. A toggle adds
/// `id` and makes it the active layer and the anchor, or takes it out when it was selected (the
/// active layer and the anchor stay, or the last picked layer takes their place when it was them);
/// taking out the only selected layer leaves an empty selection.
pub(crate) fn extend(s: &mut Session, ts: usize, id: LayerId, range: bool) -> Option<LayerId> {
let current = s.selection_in(ts);
let anchor = s.multi_in(ts).map(|multi| multi.anchor).filter(|anchor| current.contains(anchor)).or_else(|| s.active_in(ts));
if range {
let rows = stack_rows(&s.doc.project, ts, true);
let span = anchor.and_then(|anchor| Some((anchor, rows.iter().position(|row| *row == anchor)?, rows.iter().position(|row| *row == id)?)));
match span {
Some((anchor, from, to)) => {
let layers = rows.get(from.min(to)..=from.max(to)).map(<[LayerId]>::to_vec).unwrap_or_else(|| vec![id]);
s.select_several(ts, id, anchor, layers);
}
// Nothing to range from (or it is hidden in a collapsed folder): start over at `id`
None => s.select_several(ts, id, id, vec![id]),
}
return Some(id);
}
let mut layers = current;
if layers.contains(&id) {
layers.retain(|layer| *layer != id);
// Taking out the only selected layer leaves nothing selected
let Some(last) = layers.last().copied() else {
s.select_none(ts);
return None;
};
let kept = |layer: Option<LayerId>| layer.filter(|layer| layers.contains(layer)).unwrap_or(last);
let (active, anchor) = (kept(s.active_in(ts)), kept(anchor));
s.select_several(ts, active, anchor, layers);
Some(active)
} else {
layers.push(id);
s.select_several(ts, id, id, layers);
Some(id)
}
}
/// `layer.select {layers, layer?}`: select every layer in `layers` at once, with `layer` (one of
/// them; default the last) as the active one.
pub(crate) fn select_list(s: &mut Session, p: &Value) -> Result<Value> {
let (ts, layers) = ids_param(s, "layer.select", p)?;
let active = match u64p(p, "layer").map(LayerId) {
Some(active) if layers.contains(&active) => active,
Some(_) => return Err(bad("layer.select", "`layer` must be one of `layers`")),
None => layers.last().copied().ok_or_else(|| bad("layer.select", "`layers` is empty"))?,
};
// Paths paint into the active set
if ts != s.ts() {
s.finish_path()?;
s.tool.clone_source = None;
}
s.active_set = ts;
s.select_several(ts, active, active, layers);
s.target = StackTarget::Content;
s.revision = s.revision.wrapping_add(1);
Ok(json!({ "layer": active.0, "textureSet": ts, "layers": ids_json(&s.selected_layers()) }))
}
/// `layer.select {all: true}` (Ctrl/Cmd+A in the Layers panel): every row shown in the active
/// texture set: the folder rows and the layers inside open folders, but not the layers inside
/// collapsed ones. The active layer and the Shift+click anchor stay when they are among them,
/// else the top row takes their place. An empty stack changes nothing.
pub(crate) fn select_all(s: &mut Session) -> Result<Value> {
let ts = s.ts();
let rows = stack_rows(&s.doc.project, ts, true);
let Some(top) = rows.first().copied() else {
return Ok(json!({ "layer": Value::Null, "textureSet": ts, "layers": [] }));
};
let active = s.active_in(ts).filter(|active| rows.contains(active)).unwrap_or(top);
let anchor = s.multi_in(ts).map(|multi| multi.anchor).filter(|anchor| rows.contains(anchor)).unwrap_or(active);
s.select_several(ts, active, anchor, rows);
s.target = StackTarget::Content;
s.revision = s.revision.wrapping_add(1);
Ok(json!({ "layer": active.0, "textureSet": ts, "layers": ids_json(&s.selected_layers()) }))
}
/// The `layers` param: ids of layers in one texture set's stack, without repeats.
fn ids_param(s: &Session, cmd: &str, p: &Value) -> Result<(usize, Vec<LayerId>)> {
let list = p.get("layers").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`layers` must be a list of layer ids"))?;
let mut set = None;
let mut ids = Vec::new();
for value in list {
let id = value.as_u64().map(LayerId).ok_or_else(|| bad(cmd, "`layers` must be a list of layer ids"))?;
let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| bad(cmd, format!("no layer {} in a stack", id.0)))?;
if *set.get_or_insert(ts) != ts {
return Err(bad(cmd, "`layers` must all be in one texture set"));
}
if !ids.contains(&id) {
ids.push(id);
}
}
let ts = set.ok_or_else(|| bad(cmd, "`layers` is empty"))?;
Ok((ts, ids))
}
/// The layers a batch command acts on, top row first: `layers`, else `layer` alone, else every
/// selected layer. With `outermost`, a layer whose folder is also in the list is left out (the
/// folder takes it along).
pub(crate) fn batch_param(s: &Session, cmd: &str, p: &Value, outermost: bool) -> Result<Vec<LayerId>> {
let ids = if p.get("layers").is_some() {
ids_param(s, cmd, p)?.1
} else if u64p(p, "layer").is_some() {
vec![crate::commands::layer_param(s, cmd, p)?]
} else {
s.selected_layers()
};
if ids.len() < 2 {
return if ids.is_empty() { Err(bad(cmd, "no layer selected and no `layer` given")) } else { Ok(ids) };
}
let project = &s.doc.project;
let Some((ts, _, _)) = ids.first().and_then(|id| project.locate(*id)) else { return Ok(ids) };
Ok(stack_rows(project, ts, false).into_iter().filter(|id| ids.contains(id) && !(outermost && in_listed_folder(project, *id, &ids))).collect())
}
/// Whether a folder holding `id` (at any depth) is in `ids`.
fn in_listed_folder(project: &Project, id: LayerId, ids: &[LayerId]) -> bool {
let mut at = id;
for _ in 0..=MAX_DEPTH {
match project.locate(at) {
Some((_, Some(parent), _)) if ids.contains(&parent) => return true,
Some((_, Some(parent), _)) => at = parent,
_ => return false,
}
}
false
}
pub(crate) fn ids_json(ids: &[LayerId]) -> Vec<u64> {
ids.iter().map(|id| id.0).collect()
}
@@ -0,0 +1,12 @@
use texturecraft_core::LayerId;
/// The layers selected in one texture set together with the active one.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MultiSelection {
/// The active layer these were picked with; another selected layer ends the selection.
pub active: LayerId,
/// Where a Shift+click range starts: the last layer clicked without Shift.
pub anchor: LayerId,
/// Every selected layer, the active one included, in the order they were picked.
pub layers: Vec<LayerId>,
}
+17 -2
View File
@@ -20,12 +20,16 @@ pub mod file_cmds;
pub mod fill_hit_test;
pub mod fill_mode;
pub mod filter_lib;
mod frame_target;
pub mod inspect;
pub mod instance_cmds;
pub mod layer_cmds;
pub mod layer_ops;
pub mod layer_selection;
pub mod link_cmds;
mod mask_bitmap;
pub mod mask_cmds;
pub mod mask_export;
mod mask_preview_pixel;
pub mod material_lib;
mod material_preview_pixel;
@@ -42,36 +46,47 @@ pub mod path_tool;
pub mod pbr_cmds;
mod polygon_fill;
mod polygon_fill_drag;
mod polygon_fill_mirror;
mod stencil_look;
// Mesh reimport reads files on native targets only
#[cfg(not(target_arch = "wasm32"))]
mod preserve;
pub mod preset_cmds;
pub mod preview;
mod procedural_params;
pub mod project_cmds;
pub mod quick_mask;
pub mod resource_cmds;
pub mod session;
pub mod set_cmds;
pub mod smart_masks;
mod solo;
pub mod template_cmds;
pub mod text_cmds;
pub mod thumbs;
mod tool_availability;
pub mod tool_cmds;
pub mod tool_settings;
mod triangle_partition;
mod uv_stroke_state;
mod uv_symmetry;
pub mod uv_tile_cmds;
pub mod view_cmds;
pub use bake::{BakeMesh, BakeMeshes, BakeTask, StreamedBake, StreamedMap};
pub use bake_preview::{BakePreview, PreviewShow};
pub use commands::{CommandSpec, command_specs, execute, find};
pub use commands::{CommandSpec, check_enabled, command_specs, execute, find};
pub use fill_hit_test::FillHitTest;
pub use fill_mode::FillMode;
pub use path_tool::PathState;
pub use project_cmds::sample_session;
pub use session::{CloneFrom, CloneSource, Document, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode};
pub use session::{
CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState, ViewMode, history_label,
stroke_template,
};
pub use set_cmds::{ResizeOutput, ResizeTask};
pub use solo::Solo;
pub use tool_settings::ToolSettings;
pub use texturecraft_compose as compose;
pub use texturecraft_core as core;
+124 -10
View File
@@ -312,16 +312,42 @@ impl LinkJob {
}
}
/// Decode every map of `m` (validating them) with the channel it feeds.
/// Most texels one map may have: 8192 x 8192, the largest texture set. Decoded as RGBA f32 that is
/// 1 GiB, so without this a single 16384 x 16384 map (a tiny PNG) would decode to 4 GiB.
const MAX_MAP_TEXELS: u64 = texturecraft_formats::MAX_RESOURCE_TEXELS;
/// Most texels all of a material's maps may decode to together: nine 4096 x 4096 images (151 M texels).
/// A decoded texel is an RGBA `f32` (16 bytes) and the decoded maps stay in the session, so this holds one
/// `.mcmat` to about 2.25 GiB of pixels however small the file is (a blank 8192 x 8192 PNG is a few hundred
/// KiB). This is a per-import memory policy, not the number of supported channels. It fits nine 4K maps,
/// or an 8K base colour with five 4K maps; larger imports are refused, never shrunk silently.
const MAX_DECODED_TEXELS: u64 = 9 * 4096 * 4096;
/// Decode every map of `m` (validating them) with the channel it feeds. A usage listed more than
/// once is decoded once (the last listing wins, as it did when each listing was painted over the
/// one before), and the maps together stay within [`MAX_DECODED_TEXELS`], so a `.mcmat` can't
/// multiply one small image into gigabytes of pixels.
fn decoded_maps(m: &PortableMaterial) -> Result<Vec<(Channel, Vec<u8>, texturecraft_formats::DecodedImage)>> {
m.maps
.iter()
.filter_map(|(usage, bytes)| Some((Channel::ALL.into_iter().find(|c| c.id() == usage)?, bytes)))
.map(|(c, bytes)| {
let img = texturecraft_formats::decode_image(bytes).map_err(|e| EngineError::Other(format!("{} map: {e}", c.id())))?;
Ok((c, bytes.clone(), img))
})
.collect()
decoded_maps_within(m, MAX_DECODED_TEXELS, MAX_MAP_TEXELS)
}
/// Decode the maps of `m` (one per usage, the last listing wins) within a total budget of `max_texels`,
/// each map at most `max_map_texels`. The size of each map is checked from its header before decoding: a
/// map over its limit, or one that no longer fits in what is left of the budget, is refused with an error
/// that names the map.
fn decoded_maps_within(m: &PortableMaterial, max_texels: u64, max_map_texels: u64) -> Result<Vec<(Channel, Vec<u8>, texturecraft_formats::DecodedImage)>> {
let listed: Vec<(Channel, &Vec<u8>)> =
m.maps.iter().filter_map(|(usage, bytes)| Some((Channel::ALL.into_iter().find(|c| c.id() == usage)?, bytes))).collect();
let mut left = max_texels;
let mut out = Vec::new();
for (i, (c, bytes)) in listed.iter().enumerate() {
if listed.iter().skip(i + 1).any(|(later, _)| later == c) {
continue;
}
let img = texturecraft_formats::decode_image_within(bytes, left.min(max_map_texels)).map_err(|e| EngineError::Other(format!("{} map: {e}", c.id())))?;
left = left.saturating_sub(u64::from(img.width) * u64::from(img.height));
out.push((*c, (*bytes).clone(), img));
}
Ok(out)
}
impl Session {
@@ -351,6 +377,7 @@ impl Session {
if maps.is_empty() {
return Err(EngineError::Other(format!("{} has no maps TextureCraft can paint with", m.manifest.name)));
}
let label = format!("Add {}", m.manifest.name);
let (id, names) = self.edit(&label, |s| {
let ts = s.ts();
@@ -376,7 +403,7 @@ impl Session {
let name = s.doc.project.next_layer_name(ts, &m.manifest.name);
let lid = crate::layer_cmds::insert_selected(s, Layer::new(lid, name, LayerKind::Fill(fill), &channels))?;
place.apply(s, lid)?;
s.selected.insert(ts, lid);
s.select_one(ts, lid);
s.target = crate::session::StackTarget::Content;
Ok((lid, names))
})?;
@@ -557,6 +584,93 @@ esac
#[cfg(test)]
mod tests {
use super::*;
use texturecraft_formats::mcmat::{Manifest, MapEntry};
/// A blank `side` x `side` RGBA PNG, as bytes.
fn png(side: u32) -> Vec<u8> {
let mut out = Vec::new();
image::RgbaImage::new(side, side).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
out
}
/// A portable material that lists the given (usage, image bytes) maps in order.
fn material(maps: Vec<(&str, Vec<u8>)>) -> PortableMaterial {
let manifest = Manifest {
format: "craft-material".into(),
version: 1,
name: "M".into(),
graph: "M".into(),
size: [4, 4],
maps: maps.iter().map(|(usage, _)| MapEntry { usage: usage.to_string(), file: "m.png".into() }).collect(),
parameters: vec![],
inputs: vec![],
presets: vec![],
source: "source.mcraft".into(),
};
PortableMaterial { manifest, maps: maps.into_iter().map(|(u, b)| (u.to_string(), b)).collect(), source: vec![] }
}
/// However many times one usage is listed, it is decoded only once.
#[test]
fn a_usage_listed_many_times_is_decoded_once() {
let m = material((0..64).map(|_| ("baseColor", png(4))).collect());
assert_eq!(decoded_maps(&m).unwrap().len(), 1, "64 listings of one usage, one decoded image");
}
/// When a usage is listed twice, the later image is the one that is kept.
#[test]
fn the_last_listing_of_a_usage_wins() {
let m = material(vec![("baseColor", png(4)), ("roughness", png(2)), ("baseColor", png(8))]);
let maps = decoded_maps(&m).unwrap();
let base = maps.iter().find(|(c, ..)| *c == Channel::BaseColor).unwrap();
assert_eq!(base.2.width, 8);
assert_eq!(maps.len(), 2);
}
/// A single map over the per-map limit is refused even when the total budget would allow it; one exactly at it is kept.
#[test]
fn one_map_over_the_per_map_limit_is_refused_though_the_total_would_allow_it() {
let m = material(vec![("baseColor", png(5))]);
assert!(decoded_maps_within(&m, 1000, 24).is_err(), "25 texels over a per-map limit of 24, total 1000");
assert_eq!(decoded_maps_within(&m, 1000, 25).unwrap().len(), 1, "exactly at the per-map limit");
// The real limits: one map is at most 8192 x 8192, and the total holds nine maps at 4096 x 4096.
assert_eq!(MAX_MAP_TEXELS, 8192 * 8192);
assert_eq!(MAX_DECODED_TEXELS, 9 * 4096 * 4096);
}
/// The maps together stay within the total budget, exactly: three 8 x 8 maps fit in 192 texels but not in 191.
#[test]
fn decoded_pixels_are_bounded_across_maps() {
let m = material(vec![("baseColor", png(8)), ("roughness", png(8)), ("metallic", png(8))]);
assert_eq!(decoded_maps_within(&m, 192, 64).unwrap().len(), 3, "at the budget");
assert!(decoded_maps_within(&m, 191, 64).is_err(), "one texel under: the third map goes over");
}
/// Shared version-2/SBS parsing retains its behavior before duplicate decode filtering.
#[test]
fn shared_version_two_archive_keeps_sbs_and_decodes_repeated_usage_once() {
use std::io::Write;
let manifest = serde_json::json!({
"format": "craft-material", "version": 2, "name": "M", "graph": "Second", "size": [4, 4],
"maps": (0..64).map(|_| serde_json::json!({"usage": "baseColor", "file": "maps/base.png"})).collect::<Vec<_>>(),
"source": "source.sbs"
});
let mut archive = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
for (name, bytes) in [("material.json", manifest.to_string().into_bytes()), ("maps/base.png", png(4)), ("source.sbs", b"source package".to_vec())] {
archive.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
archive.write_all(&bytes).unwrap();
}
let material = read_mcmat(&archive.finish().unwrap().into_inner()).unwrap();
assert_eq!(material.manifest.version, 2);
assert_eq!(material.manifest.graph, "Second");
assert_eq!(material.manifest.source, "source.sbs");
assert_eq!(material.source, b"source package");
let maps = decoded_maps(&material).unwrap();
assert_eq!(maps.len(), 1);
assert_eq!((maps[0].2.width, maps[0].2.height), (4, 4));
}
use super::typed;
use serde_json::json;
use texturecraft_core::layer::LinkParam;
+28
View File
@@ -0,0 +1,28 @@
use crate::{EngineError, Result};
/// An evaluated mask: `width × height` values in `0..=1`, row by row from the top
#[derive(Clone, Debug, PartialEq)]
pub struct MaskBitmap {
/// UDIM number of the tile (None: the whole texture set)
pub tile: Option<u32>,
pub width: u32,
pub height: u32,
pub values: Vec<f32>,
}
impl MaskBitmap {
/// The values as 16-bit gray levels
pub fn gray16(&self) -> Vec<u16> {
self.values.iter().map(|v| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16).collect()
}
/// The values as 8-bit gray levels
pub fn gray8(&self) -> Vec<u8> {
self.values.iter().map(|v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8).collect()
}
/// A 16-bit grayscale PNG
pub fn to_png16(&self) -> Result<Vec<u8>> {
texturecraft_formats::gray16_png(self.width, self.height, self.values.iter().copied()).map_err(|error| EngineError::Other(error.to_string()))
}
}
+58 -29
View File
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use texturecraft_core::{
BakedMap, BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask,
MaskBackground, MicroDetail, OutputResolution, Procedural, ProceduralKind, Project, ResolutionMode, Source,
MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Source,
};
use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p};
@@ -20,7 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add mask with color selection",
["Layers", "Mask"],
None,
"{layer?, color?: [r,g,b] ID color, tolerance?}",
"{layer?, color?: ID color as [r,g,b] linear or \"#rrggbb\" sRGB, tolerance?}",
has_layer,
add_color_mask
),
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add fill",
["Layers", "Effects"],
None,
"{layer?, target?: mask|content, name?, mask: value?: 0..1 | image?: resource name | procedural?: kind, scale?, seed? | anchor?: anchor effect id, anchorChannel?: channel (height); content: color?, roughness?, metallic?, height?, opacity? (default: every layer channel); projection?}",
"{layer?, target?: mask|content, name?, mask: value?: 0..1 | image?: resource name | procedural?: kind, scale?, seed?, contrast?, balance?, invert?, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true | anchor?: anchor effect id, anchorChannel?: channel (height); content: color? ([r,g,b] linear or \"#rrggbb\" sRGB), roughness?, metallic?, height?, opacity? (default: every layer channel); projection?}",
has_layer,
add_fill
),
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add filter",
["Layers", "Effects"],
None,
"{layer?, target?: mask|content, name?, filter?: id from filter.list (invert, threshold, blur, sharpen, hsl, levels, contrastLuminosity, colorBalance, gradientMap, posterize, clamp, histogramScan|Range|Shift, warp, blurDirectional, slopeBlur, matFinishGrind|Raw|Sanded|Hammered), level?, radius?, amount?, hue?: turns -1..1, saturation?, lightness?, contrast?, luminosity?, shadows?|midtones?|highlights?: [r,g,b] -1..1, colors?: [[r,g,b]|\"#rrggbb\", ...], levels?, min?, max?, position?, range?, offset?, intensity?, scale?, seed?, angle?} — material finishes go on the content",
"{layer?, target?: mask|content, name?, filter?: id from filter.list (invert, threshold, blur, sharpen, hsl, levels, contrastLuminosity, colorBalance, gradientMap, posterize, clamp, histogramScan|Range|Shift, warp, blurDirectional, slopeBlur, matFinishGrind|Raw|Sanded|Hammered), level?, radius?, amount?, hue?: turns -1..1, saturation?, lightness?, contrast?, luminosity?, shadows?|midtones?|highlights?: [r,g,b] -1..1, colors?: [[r,g,b] linear or \"#rrggbb\" sRGB, ...], levels?, min?, max?, position?, range?, offset?, intensity?, scale?, seed?, angle?} — material finishes go on the content",
has_layer,
add_filter
),
@@ -94,7 +94,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit effect",
[],
None,
"{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}",
"{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b] linear, ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}",
has_layer,
set
),
@@ -273,11 +273,12 @@ pub(crate) fn anchor_source(s: &Session, cmd: &str, reader: LayerId, anchor: Lay
Some((owner, e)) if matches!(e.kind, EffectKind::Anchor) => owner,
_ => return Err(bad(cmd, format!("{} is not an anchor point", anchor.0))),
};
let (ts, _, _) = s.doc.project.locate(reader).ok_or_else(|| bad(cmd, "layer not in a stack"))?;
let order: Vec<LayerId> = s.doc.project.walk(ts).into_iter().map(|(id, _)| id).collect();
let pos = |id: LayerId| order.iter().position(|x| *x == id);
match (pos(owner), pos(reader)) {
(Some(o), Some(r)) if o < r => Ok(Source::Anchor { anchor, channel }),
(Some(o), Some(r)) if o < r => Ok(Source::Anchor { anchor, channel, ramp: Vec::new() }),
_ => Err(bad(cmd, "the anchor point must be on a layer below this one in the same texture set")),
}
}
@@ -294,9 +295,6 @@ fn image_source(session: &Session, command: &str, name: &str) -> Result<Source>
fn add_fill(session: &mut Session, params: &Value) -> Result<Value> {
const CMD: &str = "effect.add.fill";
const MIN_PATTERN_SCALE: f32 = 0.001;
const MAX_PATTERN_SCALE: f32 = 1000.0;
let projection = projection_from(params, CMD, None)?;
let blend = blend_param(CMD, params, "blend")?.unwrap_or(BlendMode::Normal);
let layer = layer_param(session, CMD, params)?;
@@ -327,14 +325,10 @@ fn add_fill(session: &mut Session, params: &Value) -> Result<Value> {
Some(name) => {
let kind = ProceduralKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown procedural `{name}`")))?;
let mut pattern = Procedural::new(kind);
if let Some(scale) = f32p(params, "scale") {
pattern.scale = scale.clamp(MIN_PATTERN_SCALE, MAX_PATTERN_SCALE);
}
if let Some(seed) = u64p(params, "seed") {
pattern.seed = seed as u32;
}
crate::procedural_params::pattern_basics_from(params, &mut pattern);
crate::procedural_params::pattern_settings_from(CMD, params, &mut pattern)?;
Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }
Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }
}
None => Source::Uniform([f32p(params, "value").unwrap_or(1.0).clamp(0.0, 1.0); 3]),
};
@@ -377,17 +371,7 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R
if let Some(contrast) = f32p(params, "contrast") {
generator.global.contrast = contrast.clamp(0.0, 1.0);
}
if let Some(value) = params.get("resolution") {
let name = value.as_str().ok_or_else(|| bad(command, "`resolution` must be a string"))?;
generator.resolution.mode = ResolutionMode::parse(name).ok_or_else(|| bad(command, format!("unknown resolution `{name}`")))?;
}
if let Some(custom) = u64p(params, "customResolution") {
generator.resolution.custom = custom.clamp(1, u64::from(OutputResolution::MAX_SIZE)) as u32;
}
if let Some(factor) = params.get("resolutionFactor") {
let factor = factor.as_i64().ok_or_else(|| bad(command, "`resolutionFactor` must be a whole number"))?;
generator.resolution.factor = factor.clamp(i64::from(*OutputResolution::FACTORS.start()), i64::from(*OutputResolution::FACTORS.end())) as i8;
}
crate::procedural_params::resolution_from(command, params, &mut generator.resolution)?;
// A mode or sizes also give a curvature generator saved before detail sizes its detail
let mode = params
@@ -401,6 +385,7 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R
if mode.is_none() && weights.is_none() {
return Ok(());
}
if !matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) {
return Err(bad(command, "only curvature and edge wear generators have a mode and detail sizes"));
}
@@ -591,7 +576,7 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
let anchor = match session.doc.project.effect(effect) {
Some((owner, Effect { kind: EffectKind::Fill { source, .. }, .. })) => {
let (current, channel) = match source {
Source::Anchor { anchor, channel } => (Some(*anchor), *channel),
Source::Anchor { anchor, channel, .. } => (Some(*anchor), *channel),
_ => (None, Channel::Height),
};
let channel_param = channel_param(CMD, params, "anchorChannel")?;
@@ -687,18 +672,32 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
EffectKind::Filter(_) if swaps_filter => {}
EffectKind::Filter(filter) => crate::filter_lib::apply(params, filter, CMD)?,
EffectKind::Fill { source, projection } => {
// `uniform` picks the source, so it outranks settings that would edit the current pattern
let uniform = f32p(params, "uniform").filter(|_| strp(params, "procedural").is_none());
if let Some(anchor) = anchor {
*source = anchor;
} else if let Some(image) = image {
*source = image;
} else if let Some(value) = uniform {
*source = Source::Uniform([value.clamp(0.0, 1.0); 3]);
} else if let Some(pattern) = fill_pattern(CMD, params, source)? {
*source = pattern;
} else if let Some(value) = f32p(params, "value")
&& matches!(source, Source::Uniform(_) | Source::Anchor { .. } | Source::Image { .. })
{
*source = Source::Uniform([value.clamp(0.0, 1.0); 3]);
}
// While the fill reads a pattern, `scale` is the pattern's and leaves the projection alone
let mut placement = params.clone();
if matches!(source, Source::Procedural { .. })
&& let Some(fields) = placement.as_object_mut()
{
fields.remove("scale");
}
// Preserve projection fields that the edit does not supply
*projection = projection_from(params, CMD, Some(&*projection))?;
*projection = projection_from(&placement, CMD, Some(&*projection))?;
}
EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_cmds::apply_params(params, colors, tolerance)?,
EffectKind::Compare { tolerance, .. } => {
@@ -715,6 +714,36 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
Ok(Value::Null)
}
/// The pattern a mask fill reads after `params`: `procedural` picks one (a pattern of the kind it already reads keeps its settings), pattern settings alone edit the current one
fn fill_pattern(command: &str, params: &Value, current: &Source) -> Result<Option<Source>> {
let (current, range) = match current {
Source::Procedural { pattern, low, high, .. } => (Some(pattern), (*low, *high)),
_ => (None, ([0.0; 3], [1.0; 3])),
};
let mut pattern = match strp(params, "procedural") {
Some(name) => {
let kind = ProceduralKind::parse(name).ok_or_else(|| bad(command, format!("unknown procedural `{name}`")))?;
current.filter(|pattern| pattern.kind == kind).cloned().unwrap_or_else(|| Procedural::new(kind))
}
None => {
let has_settings = crate::procedural_params::has_pattern_settings(params);
let edits_pattern = has_settings || ["scale", "seed", "contrast", "balance", "invert"].iter().any(|key| params.get(key).is_some());
match current {
Some(pattern) if edits_pattern => pattern.clone(),
None if has_settings => {
return Err(bad(command, "the mask fill reads no pattern: give `procedural` with its settings"));
}
_ => return Ok(None),
}
}
};
crate::procedural_params::pattern_basics_from(params, &mut pattern);
crate::procedural_params::pattern_settings_from(command, params, &mut pattern)?;
Ok(Some(Source::Procedural { pattern, low: range.0, high: range.1, ramp: Vec::new() }))
}
/// The library id of the filter effect `effect` is, if it is one
fn current_filter_id(s: &Session, effect: LayerId) -> Option<&'static str> {
match &s.doc.project.effect(effect)?.1.kind {
+115
View File
@@ -0,0 +1,115 @@
//! Mask export: a layer's evaluated mask as a grayscale bitmap at the texture set's resolution
//! (`mask.export`, and the layer menu's "Copy mask to clipboard").
//!
//! The bitmap has the orientation of the exported texture maps (row 0 is the top of the UV
//! square) and is black where the mesh does not cover the texture. A classic texture set gives one
//! bitmap; a UV-tiled set gives one per tile (what the texture export does) or, for the clipboard,
//! one of the whole tile atlas.
use serde_json::Value;
#[cfg(not(target_arch = "wasm32"))]
use serde_json::json;
use texturecraft_core::LayerId;
use crate::commands::{CommandSpec, bad, has_layer};
#[cfg(not(target_arch = "wasm32"))]
use crate::commands::{layer_param, strp};
pub use crate::mask_bitmap::MaskBitmap;
use crate::{EngineError, Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"mask.export",
"Export mask to file...",
[],
None,
"{layer?, path: .png file} → {files}. Writes the evaluated mask as a 16-bit grayscale PNG at the texture set's resolution, black outside the mesh and oriented like the exported textures. A UV-tiled set writes one file per tile with the tile number before the extension (mask.1001.png). A layer without an enabled mask is an error",
has_layer,
export
)]
}
impl Session {
/// Layer `id`'s evaluated mask: one bitmap per UV tile (`per_tile`) or one of the whole
/// texture set. A tile smaller than its atlas block gives its own size. Errors without an
/// enabled mask.
pub fn mask_bitmaps(&mut self, id: LayerId, per_tile: bool) -> Result<Vec<MaskBitmap>> {
let (ts, _, _) = self.doc.project.locate(id).ok_or_else(|| EngineError::Other(format!("no layer {}", id.0)))?;
self.update();
let atlas = self
.with_inputs(ts, |inputs| texturecraft_compose::mask_texels(inputs, id).map(|values| (inputs.gbuf.width, inputs.gbuf.height, values)))
.ok_or_else(|| EngineError::Other("the layer has no enabled mask".into()))?;
let (width, height, values) = atlas;
let set = self.doc.project.texture_set(ts).map_err(|e| EngineError::Other(e.to_string()))?;
let Some(grid) = set.tile_grid().filter(|_| per_tile) else { return Ok(vec![MaskBitmap { tile: None, width, height, values }]) };
let block = set.block_resolution();
set.uv_tiles
.iter()
.map(|&tile| {
let (block_x, block_y) = grid.block(tile).ok_or_else(|| EngineError::Other(format!("UV tile {tile} is not in the set's grid")))?;
// A tile smaller than its block fills the block's top-left corner
let side = ((block as f32 * set.tile_scale(tile)).round() as u32).clamp(1, block);
let mut tile_values = Vec::with_capacity(side as usize * side as usize);
for row in 0..side {
let start = ((block_y * block + row) as usize) * width as usize + (block_x * block) as usize;
tile_values.extend_from_slice(values.get(start..start + side as usize).unwrap_or(&[]));
}
Ok(MaskBitmap { tile: Some(tile), width: side, height: side, values: tile_values })
})
.collect()
}
}
/// `path` as a `.png` path, with `tile` before the extension for a UV tile.
#[cfg(not(target_arch = "wasm32"))]
fn file_path(path: &str, tile: Option<u32>) -> std::path::PathBuf {
let path = std::path::Path::new(path);
let is_png = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("png"));
let name = path.file_name().map_or_else(|| "mask".into(), |n| n.to_string_lossy().into_owned());
let stem = if is_png { name[..name.len() - 4].to_string() } else { name };
let named = match tile {
Some(tile) => format!("{stem}.{tile}.png"),
None => format!("{stem}.png"),
};
path.with_file_name(named)
}
#[cfg(not(target_arch = "wasm32"))]
fn export(s: &mut Session, p: &Value) -> Result<Value> {
let path = strp(p, "path").filter(|path| !path.trim().is_empty()).ok_or_else(|| bad("mask.export", "`path` is required"))?;
let id = layer_param(s, "mask.export", p)?;
let bitmaps = s.mask_bitmaps(id, true)?;
let mut files = Vec::new();
for bitmap in &bitmaps {
let file = file_path(path, bitmap.tile);
texturecraft_formats::write_atomic(&file, &bitmap.to_png16()?).map_err(|e| bad("mask.export", format!("cannot write {}: {e}", file.display())))?;
files.push(file.display().to_string());
}
s.log.push(format!("Exported the mask to {}", files.join(", ")));
Ok(json!({ "files": files }))
}
#[cfg(target_arch = "wasm32")]
fn export(_: &mut Session, _: &Value) -> Result<Value> {
Err(bad("mask.export", "writing files is not available in the browser"))
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::file_path;
#[test]
fn the_tile_number_goes_before_the_png_extension() {
// Compared as paths: Windows writes the folder with backslashes
let name = |path: &str, tile| {
let file = file_path(path, tile);
assert_eq!(file.parent(), std::path::Path::new(path).parent(), "the folder is kept");
file.file_name().unwrap().to_string_lossy().into_owned()
};
assert_eq!(name("/a/mask.png", None), "mask.png");
assert_eq!(name("/a/mask", None), "mask.png");
assert_eq!(name("/a/mask.PNG", Some(1002)), "mask.1002.png");
assert_eq!(name("/a/skin.v2", Some(1001)), "skin.v2.1001.png");
}
}
+24 -17
View File
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add smart material from file",
[],
None,
"{path: .tcmat smart material, .mcmat MaterialCraft material or .mcraft package, above?: layer id, inside?: bool, index?: n} — above the selection by default, or placed like material.apply",
"{path: .tcmat smart material, .mcmat MaterialCraft material or .mcraft package, above?: layer id, inside?: bool, below?: layer id, top?: true, index?: n} — above the selection by default, or placed like material.apply",
always,
load
),
@@ -36,19 +36,16 @@ fn fe(e: texturecraft_formats::FormatError) -> EngineError {
EngineError::Other(e.to_string())
}
/// Image resources a layer subtree uses (fill sources and mask or content effects).
/// Image resources a layer subtree uses (fill sources and their patterns, mask fills and generator inputs)
pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec<String>, depth: usize) {
if depth > texturecraft_core::project::MAX_DEPTH {
return;
}
let Some(layer) = project.layers.get(&id) else { return };
if let LayerKind::Fill(fill) = &layer.kind {
for source in fill.sources.values() {
if let Source::Image { name, .. } = source {
out.push(name.clone());
}
}
out.extend(fill.sources.values().flat_map(Source::images).map(str::to_string));
out.extend(fill.link.as_ref().map(|link| link.package.clone()));
}
for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) {
@@ -59,24 +56,33 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec<String>,
}
}
/// An empty document with one texture set shaped like `src_set` (size, tiles, channels): what a saved library file holds.
pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document {
let mut project = Project::new(name, "builtin:none");
let mut set = TextureSet::new(name, 0, src_set.resolution);
set.uv_tiles = src_set.uv_tiles.clone();
set.tile_resolutions = src_set.tile_resolutions.clone();
set.channels = src_set.channels.clone();
project.texture_sets.push(set);
Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() }
}
impl Session {
/// Serialize layer `id` (with children, pixels and images) as a smart material file.
pub fn smart_material_bytes(&self, id: LayerId, name: &str) -> Result<Vec<u8>> {
let (ts, _, _) = self.doc.project.locate(id).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?;
let src_set = self.doc.project.texture_set(ts)?;
let mut project = Project::new(name, "builtin:none");
let mut set = TextureSet::new(name, 0, src_set.resolution);
set.uv_tiles = src_set.uv_tiles.clone();
set.tile_resolutions = src_set.tile_resolutions.clone();
set.channels = src_set.channels.clone();
project.texture_sets.push(set);
let mut mini = Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() };
let mut mini = one_set_document(self.doc.project.texture_set(ts)?, name);
let new = crate::layer_ops::copy_tree(&self.doc, id, &mut mini, 0, None, false, 0)?;
if let Ok(l) = mini.project.layer_mut(new) {
l.name = name.to_string();
}
self.file_bytes(mini, new)
}
/// The smart material file holding `mini` (a document from [`one_set_document`]) and the images layer `root` of it uses.
pub(crate) fn file_bytes(&self, mini: Document, root: LayerId) -> Result<Vec<u8>> {
let mut used = Vec::new();
images_used(&mini.project, new, &mut used, 0);
images_used(&mini.project, root, &mut used, 0);
let resources = used.iter().filter_map(|n| self.doc.resources.get(n).map(|b| (n.clone(), b.as_ref().clone()))).collect();
let pf = texturecraft_formats::ProjectFile {
project: mini.project,
@@ -104,6 +110,7 @@ impl Session {
if texturecraft_formats::mcmat::is_mcmat(bytes) || texturecraft_formats::mcmat::is_mcraft(bytes) {
return self.add_linked_material_bytes_at(bytes, place);
}
let pf = texturecraft_formats::load_project_bytes(bytes).map_err(fe)?;
let root = pf
.project
@@ -122,7 +129,7 @@ impl Session {
let inside = sel.and_then(|l| s.doc.project.layer(l).ok()).is_some_and(|l| l.is_group());
let id = crate::layer_ops::copy_tree(&src, root, &mut s.doc, ts, sel, inside, 0)?;
place.apply(s, id)?;
s.selected.insert(ts, id);
s.select_one(ts, id);
s.target = StackTarget::Content;
Ok(id)
})?;
+115 -30
View File
@@ -166,8 +166,9 @@ fn rgb(c: [f32; 3]) -> Source {
Source::Uniform(c)
}
/// A pattern between colors `low` and `high` (short: the material catalog calls it on almost every line)
fn pat(kind: ProceduralKind, scale: f32, seed: u32, contrast: f32, low: [f32; 3], high: [f32; 3]) -> Source {
Source::Procedural { pattern: Procedural { kind, scale, seed, contrast, balance: 0.0, invert: false }, low, high }
Source::Procedural { pattern: Procedural { scale, seed, contrast, ..Procedural::new(kind) }, low, high, ramp: Vec::new() }
}
/// A scalar pattern between `lo` and `hi`.
@@ -241,7 +242,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
use ProceduralKind as P;
let m = find(id).ok_or_else(|| EngineError::Other(format!("unknown material `{id}`")))?;
let one = |b: &mut Builder, s: Sources| -> Result<Vec<Layer>> { Ok(vec![b.fill(m.label, s)]) };
// A simple metal: subtle cloudy tone and roughness variation around the table values.
// A simple metal: subtle cloudy tone and roughness variation around the table values
let plain_metal = |b: &mut Builder, rough: Source| {
let lo = m.base.map(|v| v * 0.94);
one(b, metal(pat(P::Clouds, 3.0, 5, 1.0, lo, m.base), rough))
@@ -253,9 +255,11 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
"steel" | "steel_dark" | "iron" | "copper" | "brass" | "bronze" | "gold_polished" | "silver" | "aluminium" | "chrome" | "nickel" | "platinum"
| "cobalt" => plain_metal(b, clouds_rough(7)),
"steel_stainless" | "aluminium_brushed" | "titanium" => plain_metal(b, gray(P::Brushed, 3.0, 3, r * 0.75, r * 1.25)),
// Zinc plate: large crystalline spangles.
// Zinc plate: large crystalline spangles
"zinc" => one(b, metal(pat(P::Voronoi, 6.0, 21, 1.0, m.base.map(|v| v * 0.8), m.base), gray(P::Voronoi, 6.0, 21, r * 1.5, r * 0.6))),
// Brushing lines run along X; the highlights stretch across them (a quarter turn).
// Brushing lines run along X; the highlights stretch across them (a quarter turn)
"steel_brushed_aniso" => one(
b,
plus(
@@ -274,7 +278,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
height(gray(P::Hammered, 6.0, 1, -0.04, 0.0)),
),
),
// Iron oxide is a dielectric: rough, pitted, blotchy orange-brown.
// Iron oxide is a dielectric: rough, pitted, blotchy orange-brown
"rust" => one(
b,
plus(
@@ -292,14 +297,17 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
"sandstone" => {
one(b, plus(dielectric(pat(P::Noise, 4.0, 13, 1.0, [0.42, 0.3, 0.18], [0.6, 0.45, 0.28]), u(0.9)), height(gray(P::Perlin, 6.0, 13, -0.01, 0.0))))
}
// Stone chips in a pale binder, polished flat.
// Stone chips in a pale binder, polished flat
"terrazzo" => one(b, dielectric(pat(P::Voronoi, 18.0, 9, 1.0, [0.55, 0.55, 0.53], [0.85, 0.84, 0.8]), gray(P::Voronoi, 18.0, 9, 0.34, 0.26))),
// Fine grains in soft wind ripples.
// Fine grains in soft wind ripples
"sand" => one(
b,
plus(dielectric(pat(P::Noise, 12.0, 27, 1.0, [0.42, 0.32, 0.19], [0.6, 0.48, 0.31]), u(0.95)), height(gray(P::Perlin, 4.0, 27, -0.012, 0.0))),
),
// Glossy wet patches over rougher, drier mud.
// Glossy wet patches over rougher, drier mud
"mud" => one(
b,
plus(
@@ -307,7 +315,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
height(gray(P::Clouds, 3.0, 29, -0.03, 0.0)),
),
),
// Rounded stones with deep joints between them.
// Rounded stones with deep joints between them
"cobblestone" => one(
b,
plus(
@@ -315,7 +324,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
height(gray(P::Cells, 6.0, 37, 0.0, -0.05)),
),
),
// Small loose stones of mixed tones.
// Small loose stones of mixed tones
"gravel" => one(
b,
plus(
@@ -323,7 +333,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
height(gray(P::Cells, 30.0, 39, -0.03, 0.0)),
),
),
// Troweled wall: soft patches and a fine sandy tooth.
// Troweled wall: soft patches and a fine sandy tooth
"plaster" => one(
b,
plus(
@@ -331,7 +342,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
height(gray(P::Clouds, 2.0, 41, -0.008, 0.0)),
),
),
// Low cushions of tiny leaves.
// Low cushions of tiny leaves
"moss" => one(
b,
plus(
@@ -347,6 +359,7 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
plus(dielectric(pat(P::Clouds, 8.0, 19, 1.0, [0.78, 0.77, 0.73], [0.86, 0.85, 0.81]), u(0.92)), height(gray(P::Noise, 1.0, 19, -0.002, 0.0))),
),
"galvanized" => one(b, metal(pat(P::Voronoi, 10.0, 4, 1.0, [0.6, 0.62, 0.63], [0.78, 0.8, 0.81]), gray(P::Voronoi, 10.0, 4, 0.5, 0.28))),
// ---- Woods (grain along X, rings across Y) ---------------------------------------------
"wood" => one(
b,
@@ -374,12 +387,14 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
),
),
"plywood" => one(b, dielectric(pat(P::Wood, 1.2, 15, 0.6, [0.42, 0.27, 0.13], [0.66, 0.47, 0.27]), gray(P::Wood, 1.2, 15, 0.8, 0.7))),
// Dark, deep furrows between gray-brown ridges.
// Dark, deep furrows between gray-brown ridges
"bark" => one(
b,
plus(dielectric(pat(P::Streaks, 8.0, 25, 1.4, [0.13, 0.105, 0.08], [0.03, 0.022, 0.015]), u(0.9)), height(gray(P::Streaks, 8.0, 25, 0.0, -0.06))),
),
// Pale, fine and even grain.
// Pale, fine and even grain
"wood_maple" => one(
b,
plus(
@@ -387,7 +402,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
height(gray(P::Wood, 3.0, 31, -0.006, 0.0)),
),
),
// Reddish heartwood with a satin finish.
// Reddish heartwood with a satin finish
"wood_cherry" => one(
b,
plus(
@@ -395,7 +411,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
height(gray(P::Wood, 2.2, 33, -0.008, 0.0)),
),
),
// Long straight fibres with a few raised ridges.
// Long straight fibres with a few raised ridges
"bamboo" => one(
b,
plus(
@@ -410,6 +427,7 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
height(gray(P::Wood, 2.0, 7, -0.015, 0.0)),
),
),
// ---- Stone, masonry, earth ----------------------------------------------------------
"concrete" => one(
b,
@@ -446,11 +464,13 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
b,
plus(dielectric(pat(P::Clouds, 5.0, 2, 1.0, [0.4, 0.15, 0.07], [0.5, 0.21, 0.11]), clouds_rough(2)), height(gray(P::Noise, 0.8, 3, -0.005, 0.005))),
),
// ---- Plastics, rubber, composites ---------------------------------------------------
"plastic_glossy" | "plastic_matte" | "ceramic" => one(b, dielectric(rgb(m.base), clouds_rough(9))),
"plastic_textured" => one(b, plus(dielectric(rgb(m.base), gray(P::Leather, 40.0, 5, 0.66, 0.5)), height(gray(P::Leather, 40.0, 5, -0.01, 0.0)))),
"rubber" => one(b, dielectric(pat(P::Noise, 0.5, 3, 1.0, [0.025; 3], [0.035; 3]), gray(P::Noise, 0.5, 3, 0.84, 0.94))),
// Twill-woven tows under a clear coat: the warp catches the light, the weft stays dark.
// Twill-woven tows under a clear coat: the warp catches the light, the weft stays dark
"carbon_fiber" => one(
b,
plus(
@@ -458,19 +478,23 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
[(CoatWeight, u(1.0)), (CoatRoughness, u(r * 0.2)), (Height, gray(P::Twill, 12.0, 1, 0.0, 0.002))],
),
),
// ---- Fabric and leather -------------------------------------------------------------
"fabric" => {
one(b, plus(dielectric(pat(P::Weave, 18.0, 2, 1.0, [0.27, 0.29, 0.34], [0.6, 0.62, 0.7]), u(r)), height(gray(P::Weave, 18.0, 2, -0.01, 0.0))))
}
// Indigo twill: diagonal ribs.
// Indigo twill: diagonal ribs
"denim" => {
one(b, plus(dielectric(pat(P::Twill, 22.0, 5, 1.0, [0.015, 0.025, 0.07], [0.15, 0.2, 0.38]), u(r)), height(gray(P::Twill, 22.0, 5, -0.01, 0.0))))
}
// Coarse, slubby plain weave.
// Coarse, slubby plain weave
"linen" => {
one(b, plus(dielectric(pat(P::Weave, 30.0, 45, 1.0, [0.58, 0.52, 0.42], [0.8, 0.74, 0.62]), u(r)), height(gray(P::Weave, 30.0, 45, -0.006, 0.0))))
}
// Fuzzy knit: no visible threads, a soft sheen at grazing angles.
// Fuzzy knit: no visible threads, a soft sheen at grazing angles
"wool" => one(
b,
plus(
@@ -495,11 +519,12 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
"velvet" => one(
b,
plus(
// A pile, not a weave: soft crushed patches under a bright sheen.
// A pile, not a weave: soft crushed patches under a bright sheen
dielectric(pat(P::Clouds, 3.0, 3, 1.0, [0.06, 0.006, 0.045], m.base), u(r)),
[(SheenWeight, u(1.0)), (SheenColor, rgb([0.95, 0.55, 0.85])), (SheenRoughness, u(0.35)), (Height, gray(P::Noise, 1.0, 3, -0.002, 0.0))],
),
),
// ---- Coated and translucent ---------------------------------------------------------
"car_paint" => one(
b,
@@ -516,14 +541,17 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
),
),
"wax" => one(b, plus(dielectric(pat(P::Clouds, 2.0, 11, 1.0, [0.74, 0.66, 0.5], m.base), clouds_rough(11)), [(ScatterWeight, u(1.0))])),
// ---- Glass (the Transmission channel; the base color tints the light going through) ----
"glass" => one(b, plus(dielectric(rgb(m.base), u(r)), [(Transmission, u(1.0))])),
// Clear with cloudy patches of trapped air.
// Clear with cloudy patches of trapped air
"ice" => one(
b,
plus(dielectric(pat(P::Clouds, 4.0, 31, 1.0, m.base, [0.84, 0.88, 0.9]), clouds_rough(31)), [(Transmission, gray(P::Clouds, 4.0, 31, 0.9, 0.5))]),
),
// Bright, rough and slightly translucent.
// Bright, rough and slightly translucent
"snow" => one(
b,
plus(
@@ -531,7 +559,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
[(ScatterWeight, u(0.5)), (Height, gray(P::Perlin, 3.0, 33, -0.02, 0.0))],
),
),
// Porous, ivory to tan, with a little light under the surface.
// Porous, ivory to tan, with a little light under the surface
"bone" => one(
b,
plus(
@@ -540,6 +569,7 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
),
),
"glass_frosted" => one(b, plus(dielectric(rgb(m.base), gray(P::Noise, 1.0, 2, 0.4, 0.5)), [(Transmission, u(1.0))])),
// ---- Smart materials ----------------------------------------------------------------
"steel_painted_worn" => {
let mut v = build(b, "steel")?;
@@ -715,6 +745,47 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
}
}
/// The channel sources of simple material `id`: its single, unmasked fill layer. `None` for smart
/// materials (several layers, or a masked layer) and for unknown ids: a brush paints one fill's
/// sources, so those stay layers.
pub fn brush_sources(id: &str) -> Option<Vec<(Channel, Source)>> {
let m = find(id).filter(|m| !m.smart)?;
let mut scratch = Project::new("", "");
let layers = build(&mut Builder { p: &mut scratch, channels: Channel::LOBES.to_vec() }, m.id).ok()?;
let [layer] = layers.as_slice() else { return None };
let LayerKind::Fill(fill) = &layer.kind else { return None };
if layer.mask.is_some() {
return None;
}
Some(fill.sources.iter().map(|(channel, source)| (*channel, source.clone())).collect())
}
/// The brush's plain values for simple material `id`, one per channel it sets (what the tool's
/// material shows): a pattern counts as the middle between its two values. `None` as
/// [`brush_sources`].
pub fn brush_values(id: &str) -> Option<Vec<(Channel, [f32; 3])>> {
let mean = |low: &[f32; 3], high: &[f32; 3]| std::array::from_fn(|i| (low[i] + high[i]) * 0.5);
Some(
brush_sources(id)?
.into_iter()
.filter_map(|(channel, source)| match source {
Source::Uniform(value) => Some((channel, value)),
Source::Procedural { low, high, .. } => Some((channel, mean(&low, &high))),
Source::Image { .. } | Source::Anchor { .. } => None,
})
.collect(),
)
}
/// The fill a brush material paints through, as a layer: `sources` projected tri-planar at
/// `scale` (the same fill evaluation a layer with that material uses).
pub(crate) fn brush_fill(id: LayerId, sources: Vec<(Channel, Source)>, scale: f32) -> Layer {
let channels: Vec<Channel> = sources.iter().map(|(channel, _)| *channel).collect();
let projection = Projection::Triplanar { scale, sharpness: 8.0, offset: [0.0; 3] };
Layer::new(id, "Brush material", LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, link: None }), &channels)
}
/// Where [`apply_at`] puts a material.
#[derive(Clone, Copy, Debug)]
pub enum Place {
@@ -724,6 +795,10 @@ pub enum Place {
Above(LayerId, bool),
/// At this index of the top-level stack (0 = bottom).
Index(usize),
/// Directly below a layer, in the same stack or folder (a shelf drop on a layer row).
Below(LayerId),
/// At the top of the top-level stack (a shelf drop on the 3D or 2D view).
Top,
}
/// Add material `id` above the selection: a single fill layer, or a folder for multi-layer
@@ -739,7 +814,8 @@ pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result<LayerId> {
s.edit(&label, |s| {
let ts = s.ts();
let mut channels = s.doc.project.texture_set(ts)?.channel_list();
// Lobe channels the material uses join the texture set (other channels it lacks are skipped).
// Lobe channels the material uses join the texture set (other channels it lacks are skipped)
let missing: Vec<Channel> = Channel::LOBES.into_iter().filter(|c| !channels.contains(c)).collect();
let layers = build(&mut Builder { p: &mut s.doc.project, channels: [channels.clone(), missing.clone()].concat() }, m.id)?;
for c in missing.into_iter().filter(|c| layers.iter().any(|l| l.channels.contains_key(c))) {
@@ -759,7 +835,7 @@ pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result<LayerId> {
for l in layers {
s.doc.project.insert_layer(ts, l, Some(gid), true)?;
}
s.selected.insert(ts, gid);
s.select_one(ts, gid);
gid
};
place.apply(s, top)?;
@@ -770,10 +846,12 @@ pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result<LayerId> {
impl Place {
/// From `above` (+ `inside`) or `index` params; the selection by default.
pub(crate) fn from_params(p: &serde_json::Value) -> Place {
match (crate::commands::u64p(p, "above"), crate::commands::u64p(p, "index")) {
(Some(above), _) => Place::Above(LayerId(above), crate::commands::boolp(p, "inside").unwrap_or(false)),
(None, Some(i)) => Place::Index(usize::try_from(i).unwrap_or(usize::MAX)),
(None, None) => Place::Selection,
match (crate::commands::u64p(p, "above"), crate::commands::u64p(p, "below"), crate::commands::u64p(p, "index")) {
(Some(above), _, _) => Place::Above(LayerId(above), crate::commands::boolp(p, "inside").unwrap_or(false)),
(None, Some(below), _) => Place::Below(LayerId(below)),
(None, None, Some(i)) => Place::Index(usize::try_from(i).unwrap_or(usize::MAX)),
(None, None, None) if crate::commands::boolp(p, "top") == Some(true) => Place::Top,
(None, None, None) => Place::Selection,
}
}
@@ -786,6 +864,13 @@ impl Place {
s.doc.project.move_above(top, None, false)?;
s.doc.project.move_layer(top, i)?;
}
Place::Below(target) => {
s.doc.project.move_above(top, Some(target), false)?;
if let Some((_, _, index)) = s.doc.project.locate(top) {
s.doc.project.move_layer(top, index.saturating_sub(1))?;
}
}
Place::Top => s.doc.project.move_above(top, None, false)?,
}
Ok(())
}
+170 -47
View File
@@ -4,17 +4,24 @@
use std::collections::{BTreeMap, BTreeSet};
use texturecraft_compose::PaintTarget;
use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground};
use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground, Source};
use texturecraft_geom::glam::Vec2;
use texturecraft_paint::{
CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask, pick,
rasterize,
};
use crate::session::{ActiveStroke, CloneFrom, Session, StackTarget, Tool};
use crate::session::{ActiveStroke, CloneFrom, QUICK_MASK_STROKE_LABEL, Session, StackTarget, Tool, history_label, stroke_template};
use crate::uv_stroke_state::UvStrokeState;
use crate::uv_symmetry::UvMirror;
use crate::{EngineError, Result};
/// The brush size (as in `BrushSettings::size`) at which a brush material's pattern has its natural size; a smaller brush makes the pattern smaller in proportion
pub const BRUSH_PATTERN_SIZE: f32 = 0.1;
/// Brush size floor for the pattern scale
const MIN_PATTERN_BRUSH_SIZE: f32 = 0.0005;
/// Shortest distance between 2D view stamps, so a stamp with no radius (a pen at zero pressure) can't stall a stroke.
const MIN_UV_STAMP_STEP: f32 = 1e-5;
@@ -59,7 +66,8 @@ impl Session {
/// when painting a mask. Must run inside the stroke's history snapshot.
fn paint_target(&mut self) -> Result<PaintTarget> {
let id = self.selected_layer().ok_or_else(|| EngineError::Other("select a layer to paint on".into()))?;
// Painting an instance paints its source (its own mask when it overrides the mask).
// Painting an instance paints its source unless its own mask overrides the mask
let p = &self.doc.project;
let id = if self.target == StackTarget::Mask { p.mask_owner(id) } else { p.content_layer(id).map_or(id, |l| l.id) };
match self.target {
@@ -72,12 +80,13 @@ impl Session {
}
}
StackTarget::Effect(e) => match self.doc.project.effect(e) {
// Content paint effects hold channel pixels like a paint layer.
// Content paint effects hold channel pixels like a paint layer
Some((owner, eff)) if matches!(eff.kind, EffectKind::Paint) => {
let content = self.doc.project.layer(owner)?.content_effects.iter().any(|x| x.id == e);
Ok(if content { PaintTarget::Layer(e) } else { PaintTarget::Mask(e) })
}
// Path sublayers are painted only from their stored paths.
// Path sublayers are painted only from their stored paths
Some((owner, eff)) if matches!(eff.kind, EffectKind::Path(_)) && self.painting_paths => {
let content = self.doc.project.layer(owner)?.content_effects.iter().any(|x| x.id == e);
Ok(if content { PaintTarget::Layer(e) } else { PaintTarget::Mask(e) })
@@ -85,8 +94,8 @@ impl Session {
Some((_, eff)) if matches!(eff.kind, EffectKind::Path(_)) => {
Err(EngineError::Other("a path sublayer holds paths only: edit them with the Path tool, or paint on a paint sublayer".into()))
}
// A filter (or another effect) is selected, e.g. just added from the shelf: paint
// what lies beneath it, so the new paint goes through it.
// Paint below a selected non-paint effect so new paint passes through it
Some((owner, _)) => self.paint_target_below(owner, e),
None => Err(EngineError::Other("the selected effect is not a paint effect".into())),
},
@@ -97,12 +106,26 @@ impl Session {
if let Some(top) = mask.effects.last().filter(|e| matches!(e.kind, EffectKind::Paint)) {
return Ok(PaintTarget::Mask(top.id));
}
mask.effects.push(Effect::new(eid, EffectKind::Paint));
Ok(PaintTarget::Mask(eid))
}
}
}
/// Whether the stroke the selection starts paints a mask (the layer's mask, or a paint or
/// filter sublayer inside it).
fn paints_mask(&self) -> bool {
match self.target {
StackTarget::Content => false,
StackTarget::Mask => true,
StackTarget::Effect(effect) => {
let project = &self.doc.project;
project.effect(effect).and_then(|(owner, _)| project.layers.get(&owner)).is_some_and(|l| !l.content_effects.iter().any(|e| e.id == effect))
}
}
}
/// What a stroke paints while non-paint effect `effect` of layer `owner` is selected: the
/// nearest paint effect below it in the same stack, else the paint layer's own pixels (for
/// content) or a new paint effect inserted just below it (for a mask).
@@ -133,11 +156,44 @@ impl Session {
Ok(PaintTarget::Mask(eid))
}
/// The pattern of the brush's material (`tool.material`) as a pickup over the texture, for the
/// channels in `values`: the material's fill, evaluated with the compose fill code tri-planar
/// in world space, so it stays fixed to the surface and continuous across stamps and strokes.
/// Its size follows the brush size ([`BRUSH_PATTERN_SIZE`] is the natural size). Channels the
/// material lacks carry the tool's value. None without a brush material.
fn brush_pattern(&self, values: &BTreeMap<Channel, [f32; 3]>) -> Option<Pickup> {
let id = self.tool.material.clone()?;
let mut sources = crate::materials::brush_sources(&id)?;
sources.retain(|(channel, _)| values.contains_key(channel));
for (channel, value) in values {
if !sources.iter().any(|(set, _)| set == channel) {
sources.push((*channel, Source::Uniform(*value)));
}
}
let ts = self.ts();
let set = self.doc.project.texture_sets.get(ts)?;
let mut project = crate::material_lib::one_set_document(set, "Brush material").project;
let layer_id = project.alloc_id();
let scale = BRUSH_PATTERN_SIZE / self.tool.brush.size.max(MIN_PATTERN_BRUSH_SIZE);
project.insert_layer(0, crate::materials::brush_fill(layer_id, sources, scale), None, false).ok()?;
let snapshot = texturecraft_paint::pickup::PickupSnapshot {
project,
ts: 0,
target: PaintTarget::Layer(layer_id),
mesh: self.mesh.clone(),
bounds: self.mesh.bounds(),
pixels: Default::default(),
baked: self.doc.baked.get(&ts).cloned().unwrap_or_default(),
images: Default::default(),
};
Some(Pickup::from_snapshot(PickupMode::Clone { offset: [0; 2] }, snapshot, self.caches.get(ts)?.gbuf.clone(), values.keys().copied()))
}
fn stroke_values(&self, target: PaintTarget) -> BTreeMap<Channel, [f32; 3]> {
let ts = self.ts();
let Ok(set) = self.doc.project.texture_set(ts) else { return BTreeMap::new() };
let layer_channels = match target {
// A content paint effect paints its owner layer's channels.
// A content paint effect paints its owner layer's channels
PaintTarget::Layer(id) => {
let owner = self.doc.project.effect(id).map(|(owner, _)| owner).unwrap_or(id);
self.doc.project.layer(owner).map(|l| l.channels.keys().copied().collect::<BTreeSet<_>>()).unwrap_or_default()
@@ -162,13 +218,15 @@ impl Session {
let ts = self.ts();
let size = self.caches.get(ts).map(|c| c.size).unwrap_or((1024, 1024));
let pickup = if quick_mask { None } else { self.pickup_mode(first_uv)? };
if pickup.is_some() {
// Clone and smudge read the composite: bring it up to date first.
let composite_pickup = tool == Tool::Smudge || (tool == Tool::Clone && self.tool.clone_from == CloneFrom::Composite);
if pickup.is_some() && composite_pickup && !self.paints_mask() && self.solo.is_none() {
// Only a composite pickup reads the viewport cache
self.update();
}
// Cloning from the selected layer reads that layer alone.
// Cloning from the selected layer reads that layer alone
let layer_source = match self.selected_layer() {
Some(id) if pickup.is_some() && tool == Tool::Clone && self.tool.clone_from == CloneFrom::Layer => {
Some(id) if pickup.is_some() && tool == Tool::Clone && self.tool.clone_from == CloneFrom::Layer && !self.paints_mask() => {
Some(self.flatten(ts, id).ok_or_else(|| EngineError::Other("clone from a paint or fill layer (folders have no content of their own)".into()))?)
}
_ => None,
@@ -186,11 +244,15 @@ impl Session {
}
};
let values = target.map(|t| self.stroke_values(t)).unwrap_or_default();
// Clone and smudge on a mask read the mask as it was before the stroke
let mask_owner = match target {
Some(PaintTarget::Mask(effect)) if pickup.is_some() => self.doc.project.effect(effect).map(|(owner, _)| owner),
_ => None,
};
let stencil = if tool == Tool::Projection && !quick_mask { self.capture_stencil(viewport) } else { None };
let problem = if !erase && values.is_empty() && matches!(target, Some(PaintTarget::Layer(_))) {
Some("no channel enabled to paint: enable channels in the tool's material")
} else if pickup.is_some() && matches!(target, Some(PaintTarget::Mask(_))) {
Some("the Clone and Smudge tools paint layer content: select the layer instead of its mask")
} else if tool == Tool::Projection && !quick_mask && stencil.is_none() && !uv_mode {
Some("the Projection tool needs a stencil: pick an image in the tool properties (tool.stencil)")
} else {
@@ -200,13 +262,9 @@ impl Session {
self.doc = before;
return Err(EngineError::Other(msg.into()));
}
let depth = (!uv_mode).then(|| self.eye_depth(viewport));
let mut brush = self.tool.brush.clone();
if tool == Tool::Smudge {
// shortcut: smudge drags one stamp trail; mirrored trails would need one pickup each.
brush.symmetry = Default::default();
}
let stroke = Stroke::new(&brush, &self.mesh);
let stroke = Stroke::new(&self.tool.brush, &self.mesh);
let mut canvas = StrokeCanvas::new(size.0, size.1);
if !quick_mask {
canvas.limit = self.stroke_limit(ts, size);
@@ -220,24 +278,49 @@ impl Session {
}
m => m,
};
canvas.pickup = Some(match &layer_source {
Some(flat) => Pickup::from_layer(mode, flat, size, cache.gbuf.clone(), values.keys().copied()),
None => Pickup::new(mode, cache.composite.clone(), cache.gbuf.clone(), values.keys().copied()),
});
let mut pickup = match (&layer_source, mask_owner) {
// On a mask the stroke reads the mask's own values
(_, Some(owner)) => {
let snapshot = texturecraft_paint::pickup::PickupSnapshot {
project: self.doc.project.clone(),
ts,
target: PaintTarget::Mask(owner),
mesh: self.mesh.clone(),
bounds: self.mesh.bounds(),
pixels: self.doc.pixels.clone(),
baked: self.doc.baked.get(&ts).cloned().unwrap_or_default(),
images: self.images.clone(),
};
Pickup::from_snapshot(mode, snapshot, cache.gbuf.clone(), [])
}
(Some(flat), None) => Pickup::from_layer(mode, flat, size, cache.gbuf.clone(), values.keys().copied()),
(None, None) => Pickup::new(
mode,
self.document_composite(ts, &cache.covered_tiles).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.into_owned(),
cache.gbuf.clone(),
values.keys().copied(),
),
};
if tool == Tool::Smudge && stroke.settings.symmetry.any() {
// Every mirrored copy of a smudge drags its own trail, in the 3D and the 2D view
pickup.isolate_copies();
}
canvas.pickup = Some(pickup);
if tool == Tool::Clone
&& self.tool.clone_aligned
&& let Some(src) = self.tool.clone_source.as_mut()
{
src.offset.get_or_insert(offset);
}
}
if canvas.pickup.is_none() && tool == Tool::Paint && matches!(target, Some(PaintTarget::Layer(_))) {
canvas.pickup = self.brush_pattern(&values);
}
let label = if quick_mask {
"Quick mask stroke"
} else if erase {
"Eraser stroke"
} else if matches!(target, Some(PaintTarget::Mask(_))) {
"Mask stroke"
QUICK_MASK_STROKE_LABEL.to_string()
} else {
"Paint stroke"
let on_mask = matches!(target, Some(PaintTarget::Mask(_)));
history_label(stroke_template(tool, on_mask), &self.stroke_layer_name())
};
self.stroke = Some(ActiveStroke {
ts,
@@ -252,12 +335,20 @@ impl Session {
erase,
stencil,
before,
label: label.to_string(),
label,
staging: Staging::default(),
});
Ok(())
}
/// The name of the layer a stroke paints on (the owner layer when an effect is selected)
fn stroke_layer_name(&self) -> String {
let p = &self.doc.project;
let Some(id) = self.selected_layer() else { return String::new() };
let owner = p.effect(id).map_or(id, |(owner, _)| owner);
p.layer(owner).map(|l| l.name.clone()).unwrap_or_default()
}
/// Clone / smudge pickup for the current tool, with the clone offset (source minus
/// destination) in texture coordinates.
fn pickup_mode(&self, first_uv: Option<Vec2>) -> Result<Option<(PickupMode, [f32; 2])>> {
@@ -266,11 +357,15 @@ impl Session {
Tool::Clone => {
let src =
self.tool.clone_source.ok_or_else(|| EngineError::Other("set a clone source first: V + click on the mesh (tool.cloneSource)".into()))?;
let offset = match (src.offset, first_uv) {
// Not aligned: every stroke measures the offset from its own first point
let kept = if self.tool.clone_aligned { src.offset } else { None };
let offset = match (kept, first_uv) {
(Some(o), _) => o,
(None, Some(p)) => [src.uv[0] - p.x, src.uv[1] - p.y],
(None, None) => return Err(EngineError::Other("start the clone stroke on the mesh".into())),
};
Ok(Some((PickupMode::Clone { offset: [0; 2] }, offset)))
}
_ => Ok(None),
@@ -284,6 +379,7 @@ impl Session {
alpha: b.alpha,
image: b.alpha_image.as_ref().and_then(|n| images.get(n)).map(|i| &**i),
library: b.alpha_library.as_deref().and_then(texturecraft_paint::alphas::find).map(|a| a.image()),
params: b.alpha_params,
level: 0,
}
}
@@ -355,11 +451,18 @@ impl Session {
// The first sample is one stamp; a later one stamps every `step` along the segment from the previous
let (start, segment, mut distance) = match progress.last.replace(uv) {
None => (uv, Vec2::ZERO, 0.0),
// Pressure can shrink the step below the carry from the preceding sample
Some(previous) => (previous, uv - previous, (step - progress.carry).max(0.0)),
};
let length = segment.length();
let shape = Self::shape(&self.images, settings);
// The copies of each dab: the Clone tool's pickup offset is fixed, so it paints none
let material = self.doc.project.texture_sets.get(active.ts).map(|t| t.material).unwrap_or(0);
let mirror = (self.tool.tool != Tool::Clone)
.then(|| UvMirror::new(&settings.symmetry, active.stroke.center(), &self.mesh, &self.bvh, &cache.gbuf, material))
.flatten();
let mut batch = Vec::new();
let mut stamped = 0;
while distance <= length && stamped < MAX_UV_STAMPS_PER_SAMPLE {
@@ -368,11 +471,18 @@ impl Session {
while distance <= length && batch.len() < batch_size {
let center = start + segment * (distance / length.max(f32::MIN_POSITIVE));
let seed = progress.stamps.wrapping_add((stamped + batch.len()) as u32);
batch.push(texturecraft_paint::UvStamp { center, radius, angle, flow: settings.flow, hardness: settings.hardness, seed });
batch.push(texturecraft_paint::UvStamp { center, radius, angle, flow: settings.flow, hardness: settings.hardness, seed, source: None });
distance += step;
}
stamped += batch.len();
if let Some(mirror) = &mirror {
for index in 0..batch.len() {
if let Some(stamp) = batch.get(index).copied() {
mirror.add_copies(&stamp, &mut batch);
}
}
}
texturecraft_paint::rasterize_uv(&mut active.canvas, &cache.gbuf, shape, &batch);
}
@@ -538,7 +648,7 @@ impl Session {
pub(crate) fn paint_fill(&mut self, ts: usize, canvas: &StrokeCanvas) -> Result<()> {
let size = (canvas.alpha.width(), canvas.alpha.height());
let opacity = self.tool.brush.opacity;
let source = CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None };
let source = CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None, carried_mask: None };
if self.quick_mask.editing {
self.commit_quick_mask(ts, size, source);
return Ok(());
@@ -562,12 +672,11 @@ impl Session {
let (width, height) = (cache.size.0 as f32, cache.size.1 as f32);
let (x, y) = ((hit.uv.x * width).clamp(0.0, width - 1.0) as u32, (hit.uv.y * height).clamp(0.0, height - 1.0) as u32);
let mut picked = BTreeMap::new();
for channel in cache.composite.channels.keys() {
let value = cache.composite.value(*channel, x, y);
self.tool.values.insert(*channel, value);
picked.insert(*channel, value);
}
let tile = (x / texturecraft_texel::TILE, y / texturecraft_texel::TILE);
let source = self.document_composite(texture_set, &[tile]).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
let picked: BTreeMap<_, _> = source.channels.keys().map(|&channel| (channel, source.value(channel, x, y))).collect();
self.tool.values.extend(&picked);
self.tool.material = None;
Ok(picked)
}
@@ -576,17 +685,30 @@ impl Session {
self.stroke.as_ref().map(|s| s.canvas.dirty.len()).unwrap_or(0)
}
/// Where the Clone tool reads for destination `at` (texture coordinates) as a surface
/// point: the source itself until the first stroke fixes the offset, or when `at` is None.
pub fn clone_source_point(&self, at: Option<Vec2>) -> Option<texturecraft_geom::glam::Vec3> {
/// Where the Clone tool reads for destination `at` (texture coordinates), in texture
/// coordinates: the source itself until the first stroke fixes the offset, or when `at` is
/// None. None without a source or when that spot is outside the texture. The far edge
/// (1.0) counts as inside, so the 2D marker shows a source set on the edge; reads of the
/// surface use `clone_source_uv`, which stays half-open.
pub fn clone_source_marker_uv(&self, at: Option<Vec2>) -> Option<Vec2> {
let src = self.tool.clone_source?;
let uv = match (src.offset, at) {
(Some(o), Some(p)) => Vec2::new(p.x + o[0], p.y + o[1]),
_ => Vec2::from(src.uv),
};
if !((0.0..1.0).contains(&uv.x) && (0.0..1.0).contains(&uv.y)) {
return None;
}
((0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y)).then_some(uv)
}
/// Like `clone_source_marker_uv`, but half-open: None on the far edge, where the G-buffer
/// has no texel.
pub fn clone_source_uv(&self, at: Option<Vec2>) -> Option<Vec2> {
self.clone_source_marker_uv(at).filter(|uv| uv.x < 1.0 && uv.y < 1.0)
}
/// Where the Clone tool reads for destination `at` (texture coordinates) as a surface
/// point: the source itself until the first stroke fixes the offset, or when `at` is None.
pub fn clone_source_point(&self, at: Option<Vec2>) -> Option<texturecraft_geom::glam::Vec3> {
let uv = self.clone_source_uv(at)?;
let g = &self.caches.get(self.ts())?.gbuf;
let (x, y) = ((uv.x * g.width as f32) as usize, (uv.y * g.height as f32) as usize);
Some(g.surface(&self.mesh, y * g.width as usize + x)?.pos)
@@ -613,5 +735,6 @@ fn with_commit_source<R>(
};
let per_texel: Option<texturecraft_paint::TexelFn> = if st.stencil.is_some() { Some(&stencil_fn) } else { None };
let carried = st.canvas.pickup.as_ref().map(|p| &p.values);
f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried })
let carried_mask = st.canvas.pickup.as_ref().and_then(|p| p.mask_values());
f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried, carried_mask })
}
+226 -44
View File
@@ -15,7 +15,7 @@ use texturecraft_compose::{PaintTarget, PixelStore};
use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground, PathShape};
use texturecraft_geom::glam::{Mat3, Vec2, Vec3};
use texturecraft_geom::{OrbitCamera, surface_at};
use texturecraft_paint::{BrushSettings, Lasso, PickCtx, fill_coverage, pick, spline, spline_segments};
use texturecraft_paint::{BrushSettings, Lasso, PickCtx, fill_coverage, pick, spline_segments_with_corners, spline_with_corners};
use texturecraft_texel::TileImage;
use crate::commands::{CommandSpec, always, bad, boolp, has_layer, u64p};
@@ -47,6 +47,10 @@ const RAY_HIT_RELATIVE_TOLERANCE: f32 = 0.001;
pub struct PathState {
/// Control points: surface positions (3D view) or texture coordinates with z = 0 (2D view)
pub points: Vec<Vec3>,
/// Per control point: the curve turns sharply there (a corner). Empty or shorter than `points` means smooth;
/// read it through [`PathState::is_corner`] and [`PathState::corner_flags`]
#[serde(default)]
pub corners: Vec<bool>,
/// The points are texture coordinates (placed in the 2D view)
pub uv: bool,
/// The curve loops back to its first point
@@ -69,13 +73,38 @@ impl PathState {
pub fn push(&mut self, point: Vec3, uv: bool) {
if uv != self.uv {
self.points.clear();
self.corners.clear();
self.uv = uv;
}
if self.points.len() < MAX_PATH_POINTS {
self.points.push(point);
if !self.corners.is_empty() {
self.corners.resize(self.points.len(), false);
}
}
}
/// Does the curve turn sharply at point `i`?
pub fn is_corner(&self, i: usize) -> bool {
self.corners.get(i).copied().unwrap_or(false)
}
/// One flag per point for the curve and storage: empty when no point is a corner, so smooth paths look like old ones
pub fn corner_flags(&self) -> Vec<bool> {
if self.points.iter().enumerate().any(|(i, _)| self.is_corner(i)) { (0..self.points.len()).map(|i| self.is_corner(i)).collect() } else { Vec::new() }
}
/// Make point `i` a corner or smooth; false when there is no such point or it already is
pub fn set_corner(&mut self, i: usize, corner: bool) -> bool {
if i >= self.points.len() || self.is_corner(i) == corner {
return false;
}
self.corners.resize(self.points.len(), false);
self.corners[i] = corner;
true
}
/// Insert a control point before point `at` (on the segment ending there) and select it; None when it can't
pub fn insert(&mut self, at: usize, point: Vec3) -> Option<usize> {
if at > self.points.len() || self.points.len() >= MAX_PATH_POINTS {
@@ -83,18 +112,23 @@ impl PathState {
}
self.points.insert(at, point);
if !self.corners.is_empty() {
self.corners.resize(self.points.len() - 1, false);
self.corners.insert(at, false);
}
self.selected = Some(at);
self.selected
}
/// The same curve (points, open or closed, filled, view) as `other`
fn same_curve(&self, other: &PathState) -> bool {
(&self.points, self.closed, self.fill, self.uv) == (&other.points, other.closed, other.fill, other.uv)
(&self.points, self.corner_flags(), self.closed, self.fill, self.uv) == (&other.points, other.corner_flags(), other.closed, other.fill, other.uv)
}
/// Empty the tool for the next path: no points, open, nothing selected or edited
pub fn clear(&mut self) {
self.points.clear();
self.corners.clear();
self.closed = false;
self.selected = None;
self.editing = None;
@@ -106,6 +140,10 @@ impl PathState {
let at = self.selected.take().filter(|i| *i < self.points.len()).or(self.points.len().checked_sub(1));
if let Some(i) = at {
self.points.remove(i);
if !self.corners.is_empty() {
self.corners.resize(self.points.len() + 1, false);
self.corners.remove(i);
}
}
if self.closed && self.points.len() < 3 {
self.closed = false;
@@ -116,10 +154,10 @@ impl PathState {
/// A path sublayer's pixels after painting its first paths (`below`), with the mesh and
/// texture size they were painted for.
#[derive(Clone)]
// shortcut: the key doesn't cover image resources a path's brush alpha reads; replacing one
// leaves cached paths with the old alpha until a path below the edited one changes.
pub(crate) struct PathCache {
eid: LayerId,
pub(crate) eid: LayerId,
// Alpha image resources are not part of this cache key
// Replacing an alpha takes effect when a cached path changes
key: (u64, Option<(u32, u32)>),
below: Vec<PathShape>,
mask: Option<texturecraft_texel::TileImage>,
@@ -143,10 +181,19 @@ pub fn specs() -> Vec<CommandSpec> {
"Path",
["Tools"],
Some("7"),
"{points?: [[x,y],...] viewport pixels on the mesh | uvPoints?: [[u,v],...], viewport?: [w,h], closed?, fill?, commit?: bool, clear?: bool} — selects the Path tool and edits its curve; commit adds the path to the selected path sublayer (or a new one), painted with the current brush or filled when closed and filled. While a stored path is edited (path.edit), changes repaint it at once",
"{points?: [[x,y],...] viewport pixels on the mesh | uvPoints?: [[u,v],...], corners?: [bool,...] up to one per point (true: the curve turns sharply there; missing entries are smooth; applies to supplied points or the current curve), viewport?: [w,h], closed?, fill?, commit?: bool, clear?: bool} — selects the Path tool and edits its curve; commit adds the path to the selected path sublayer (or a new one), painted with the current brush or filled when closed and filled. While a stored path is edited (path.edit), changes repaint it at once",
always,
path
),
cmd!(
"path.corner",
"Toggle path corner",
["Tools"],
None,
"{index?: point (default: the selected point), corner?: bool (default: toggle)} — makes a control point of the Path tool's curve a corner (the curve turns sharply there) or smooth again; one undo step per change, repainting the edited path at once",
always,
path_corner
),
cmd!(
"path.edit",
"Edit path",
@@ -171,35 +218,60 @@ pub fn specs() -> Vec<CommandSpec> {
/// Set the curve from command parameters, then preview or commit it in the supplied viewport
fn path(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "tool.path";
let viewport = viewport_of(s, p);
let clear = boolp(p, "clear") == Some(true);
let placed = match (points_param(CMD, p, "points")?, points_param(CMD, p, "uvPoints")?) {
(Some(pixels), _) => {
if pixels.len() > MAX_PATH_POINTS {
return Err(bad(CMD, format!("at most {MAX_PATH_POINTS} control points")));
}
Some((
pixels
.iter()
.enumerate()
.map(|(i, pixel)| s.pick(*pixel, viewport).map(|hit| hit.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh"))))
.collect::<Result<Vec<_>>>()?,
false,
))
}
(None, Some(uvs)) => {
if uvs.len() > MAX_PATH_POINTS {
return Err(bad(CMD, format!("at most {MAX_PATH_POINTS} control points")));
}
Some((uvs.iter().map(|uv| uv.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true))
}
(None, None) => None,
};
let point_count = placed.as_ref().map_or(if clear { 0 } else { s.tool.path.points.len() }, |(points, _)| points.len());
let corners = match p.get("corners") {
Some(value) => {
let flags = value.as_array().ok_or_else(|| bad(CMD, "`corners` must be an array of booleans"))?;
if flags.len() > point_count || flags.len() > MAX_PATH_POINTS {
return Err(bad(CMD, "`corners` has more flags than control points"));
}
Some(flags.iter().map(Value::as_bool).collect::<Option<Vec<_>>>().ok_or_else(|| bad(CMD, "`corners` must be an array of booleans"))?)
}
None => None,
};
if s.tool.tool != Tool::Path {
set_tool(s, Tool::Path)?;
}
let viewport = viewport_of(s, p);
if boolp(p, "clear") == Some(true) {
if clear {
s.cancel_path();
}
let placed = match (points_param(CMD, p, "points")?, points_param(CMD, p, "uvPoints")?) {
(Some(pixels), _) => Some((
pixels
.iter()
.enumerate()
.map(|(i, pixel)| s.pick(*pixel, viewport).map(|hit| hit.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh"))))
.collect::<Result<Vec<_>>>()?,
false,
)),
(None, Some(uvs)) => Some((uvs.iter().map(|uv| uv.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true)),
(None, None) => None,
};
if let Some((points, uv)) = placed {
if points.len() > MAX_PATH_POINTS {
return Err(bad(CMD, format!("at most {MAX_PATH_POINTS} control points")));
}
s.tool.path.points = points;
s.tool.path.corners.clear();
s.tool.path.uv = uv;
}
if let Some(flags) = corners {
s.tool.path.corners = flags;
}
if let Some(v) = boolp(p, "closed") {
s.tool.path.closed = v;
}
@@ -224,6 +296,24 @@ fn path(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill, "editing": editing, "committed": committed }))
}
/// Make a control point a corner or smooth (a toggle by default) as one undoable point edit
fn path_corner(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "path.corner";
let path = &s.tool.path;
let index = match u64p(p, "index") {
Some(i) => usize::try_from(i).ok().filter(|i| *i < path.points.len()),
None => path.selected.filter(|i| *i < path.points.len()),
}
.ok_or_else(|| bad(CMD, "no such point: pass `index` or select a point of the Path tool's curve"))?;
let corner = boolp(p, "corner").unwrap_or(!path.is_corner(index));
s.set_path_point_corner(index, corner);
s.revision = s.revision.wrapping_add(1);
if s.path_live()? {
s.update();
}
Ok(json!({ "index": index, "corner": s.tool.path.is_corner(index) }))
}
/// The `effect` and `index` params naming a stored path, with the path.
fn path_ref(s: &Session, cmd: &str, p: &Value) -> Result<(LayerId, usize, PathShape)> {
let eid = LayerId(u64p(p, "effect").ok_or_else(|| bad(cmd, "`effect` (a path sublayer id) is required"))?);
@@ -282,7 +372,21 @@ fn read_paint(shape: &PathShape) -> Result<PathPaint> {
/// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`])
fn state_of(shape: &PathShape) -> PathState {
let points = shape.points.iter().filter(|p| p.iter().all(|v| v.is_finite())).take(MAX_PATH_POINTS).map(|p| Vec3::from_array(*p)).collect();
PathState { points, uv: shape.uv, closed: shape.closed, fill: shape.fill, ..PathState::default() }
// Points dropped as unreadable shift the later flags with them
let corners = if shape.corners.is_empty() {
Vec::new()
} else {
shape
.points
.iter()
.zip(shape.corners.iter().copied().chain(std::iter::repeat(false)))
.filter(|(p, _)| p.iter().all(|v| v.is_finite()))
.take(MAX_PATH_POINTS)
.map(|(_, c)| c)
.collect()
};
PathState { points, corners, uv: shape.uv, closed: shape.closed, fill: shape.fill, ..PathState::default() }
}
/// Tiles (x, y) where sublayer `eid`'s pixels differ between `before` and `after` (copy-on-write: an unchanged tile is the same allocation)
@@ -358,6 +462,7 @@ impl Session {
let paint = PathPaint { brush: t.brush.clone(), values: t.values.clone(), enabled: t.enabled.clone(), mask_value: t.mask_value, camera };
PathShape {
points: path.points.iter().map(|p| p.to_array()).collect(),
corners: path.corner_flags(),
uv: path.uv,
closed: path.closed,
fill: path.fill,
@@ -399,7 +504,8 @@ impl Session {
let shape = self.path_shape(self.camera, viewport);
let editing = self.tool.path.editing;
let label = editing.map_or(NEW_PATH_LABEL.to_string(), |(_, i)| format!("Edit path {}", i + 1));
let label =
editing.map_or(NEW_PATH_LABEL.to_string(), |(_, i)| crate::session::history_label(crate::session::EDIT_PATH_TEMPLATE, &(i + 1).to_string()));
let report = self.edit_merging(&label, editing.is_some() && self.tool.path.edited, |session| {
let (effect_id, index) = match editing {
Some(at) => at,
@@ -426,7 +532,11 @@ impl Session {
// JSON round trips can change float representation without changing the paint settings
read_paint(stored).is_ok_and(|paint| {
let current = self.path_shape(paint.camera, Vec2::from_array(stored.viewport));
(&current.points, current.uv, current.closed, current.fill) == (&stored.points, stored.uv, stored.closed, stored.fill)
// Normalised like the current flags: a short, long or all-smooth stored list must not count as a change
let stored_corners = state_of(stored).corner_flags();
(&current.points, &current.corners, current.uv, current.closed, current.fill)
== (&stored.points, &stored_corners, stored.uv, stored.closed, stored.fill)
&& read_paint(&current).is_ok_and(|current_paint| current_paint == paint)
})
}
@@ -457,16 +567,21 @@ impl Session {
if self.path_draft.is_some() {
self.cancel_path();
} else {
self.edit_merging(&format!("Edit path {}", index + 1), self.tool.path.edited, |session| {
if let Some(Effect { kind: EffectKind::Path(paths), .. }) = session.doc.project.effect_mut(effect) {
paths.remove(index);
}
session.render_paths(effect, index)
})?;
self.edit_merging(
&crate::session::history_label(crate::session::EDIT_PATH_TEMPLATE, &(index + 1).to_string()),
self.tool.path.edited,
|session| {
if let Some(Effect { kind: EffectKind::Path(paths), .. }) = session.doc.project.effect_mut(effect) {
paths.remove(index);
}
session.render_paths(effect, index)
},
)?;
self.cancel_path();
}
return Ok(true);
}
return Ok(false);
}
@@ -488,7 +603,7 @@ impl Session {
None => {
// The path's own repaint keeps its point changes undoable, unlike other steps
let steps = std::mem::take(&mut self.path_steps);
self.push_step(&format!("Edit path {}", index + 1), before, self.tool.path.edited);
self.push_step(&crate::session::history_label(crate::session::EDIT_PATH_TEMPLATE, &(index + 1).to_string()), before, self.tool.path.edited);
self.path_steps = steps;
self.tool.path.edited = true;
}
@@ -588,6 +703,37 @@ impl Session {
self.tool.path.remove_selected();
}
/// Make a point a corner or smooth again, with point undo; false when nothing changed
pub fn set_path_point_corner(&mut self, index: usize, corner: bool) -> bool {
if index >= self.tool.path.points.len() || self.tool.path.is_corner(index) == corner {
return false;
}
self.path_checkpoint();
self.tool.path.set_corner(index, corner)
}
/// Switch the selected point between corner and smooth, with point undo; false without a selected point
pub fn toggle_selected_path_corner(&mut self) -> bool {
let Some(i) = self.tool.path.selected.filter(|i| *i < self.tool.path.points.len()) else { return false };
let corner = !self.tool.path.is_corner(i);
self.set_path_point_corner(i, corner)
}
/// Append a point that is a corner, selecting it; as [`Session::append_path_point`]
pub fn append_path_corner(&mut self, point: Vec3, uv: bool) -> Option<usize> {
let at = self.append_path_point(point, uv)?;
self.tool.path.set_corner(at, true);
Some(at)
}
/// Insert a point that is a corner, selecting it; as [`Session::insert_path_point`]
pub fn insert_path_corner(&mut self, index: usize, point: Vec3) -> Option<usize> {
let at = self.insert_path_point(index, point)?;
self.tool.path.set_corner(at, true);
Some(at)
}
/// Change whether the path loops back to its first point, with point undo
pub fn set_path_closed(&mut self, closed: bool) {
if self.tool.path.closed != closed {
@@ -823,8 +969,9 @@ impl Session {
}
_ => 0,
};
// Each path goes through the regular stroke and fill code with its own settings; their
// own history entries are dropped (the caller records one step).
// Regular stroke and fill code paints each path with its own settings
// Discard its history entries because the caller records one undo step
let saved = (self.tool.clone(), self.camera, self.target, self.quick_mask.editing);
let history = (std::mem::take(&mut self.undo), std::mem::take(&mut self.redo));
self.target = StackTarget::Effect(eid);
@@ -866,15 +1013,20 @@ impl Session {
self.paint_path(viewport)
}
/// Where a 3D path's curve lands on the mesh painted through `camera`, per segment as [`spline_segments`] (None off the mesh)
/// Where a 3D path's curve lands on the mesh painted through `camera`, per segment as [`texturecraft_paint::spline_segments`] (None off the mesh)
pub fn path_surface(&self, points: &[Vec3], closed: bool, camera: OrbitCamera, viewport: Vec2) -> Vec<Vec<Option<Vec3>>> {
self.path_surface_with_corners(points, &[], closed, camera, viewport)
}
/// [`Session::path_surface`] for a curve with corner points (`corners` as [`PathState::corners`])
pub fn path_surface_with_corners(&self, points: &[Vec3], corners: &[bool], closed: bool, camera: OrbitCamera, viewport: Vec2) -> Vec<Vec<Option<Vec3>>> {
let aspect = viewport.x.max(1.0) / viewport.y.max(1.0);
let Some(screen) = points.iter().map(|p| camera.project(*p, aspect).map(|n| to_pixels(n.truncate(), viewport))).collect::<Option<Vec<_>>>() else {
return Vec::new();
};
let ctx = PickCtx { mesh: &self.mesh, bvh: &self.bvh, camera: &camera, viewport };
spline_segments(&screen, closed, SURFACE_STEP_PX)
spline_segments_with_corners(&screen, corners, closed, SURFACE_STEP_PX)
.into_iter()
.zip(&screen)
.map(|(samples, first)| std::iter::once(*first).chain(samples).map(|q| pick(&ctx, q).map(|hit| hit.pos)).collect())
@@ -890,7 +1042,7 @@ impl Session {
let (camera, viewport) = paint_view(shape, &read_paint(shape).ok()?);
let path = state_of(shape);
Some(self.path_surface(&path.points, path.closed, camera, viewport))
Some(self.path_surface_with_corners(&path.points, &path.corners, path.closed, camera, viewport))
}
/// Paint the Path tool's curve with the current brush (or fill it when closed and filled)
@@ -898,14 +1050,17 @@ impl Session {
fn paint_path(&mut self, viewport: Vec2) -> Result<Value> {
let (uv, closed) = (self.tool.path.uv, self.tool.path.closed);
let fill = closed && self.tool.path.fill;
let pts: Vec<Vec2> = self.path_view_points(viewport).into_iter().flatten().collect();
let (pts, corners): (Vec<Vec2>, Vec<bool>) =
self.path_view_points(viewport).into_iter().enumerate().filter_map(|(i, p)| Some((p?, self.tool.path.is_corner(i)))).unzip();
if pts.is_empty() {
return Err(EngineError::Other("the path has no points: click the surface to add some".into()));
}
if fill && pts.len() < 3 {
return Err(EngineError::Other("a filled path needs at least three points".into()));
}
let curve = spline(&pts, closed, if uv { STEP_UV } else { STEP_PX });
let curve = spline_with_corners(&pts, &corners, closed, if uv { STEP_UV } else { STEP_PX });
Ok(if fill {
json!({ "filledTiles": self.lasso_fill(curve, uv, viewport)? })
} else if uv {
@@ -1032,7 +1187,8 @@ mod tests {
eid = r["committed"]["effect"].as_u64().unwrap();
}
let eid = texturecraft_core::LayerId(eid);
// Live edits of the middle path reuse the bottom path's pixels.
// Live edits of the middle path reuse the bottom path's pixels
execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap();
for v in [0.4, 0.45] {
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap();
@@ -1045,6 +1201,32 @@ mod tests {
s.render_paths(eid, 0).unwrap();
assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path");
assert!(!cached.is_empty());
execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap();
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.35], [0.9, 0.4]]})).unwrap();
let cached_tiles = s.path_cache.as_ref().map_or(0, |cache| cache.layers.iter().map(|(_, image)| image.allocated_count()).sum::<usize>());
assert!(cached_tiles > 0);
execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap();
let remaining_tiles = s.path_cache.as_ref().map_or(0, |cache| cache.layers.iter().map(|(_, image)| image.allocated_count()).sum::<usize>());
assert_eq!(remaining_tiles, 0);
assert!(s.path_cache.is_none(), "deleting the path effect releases its cached tiles");
}
#[test]
fn failed_edit_releases_cached_path_tiles() {
let mut session = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 12, 6), "builtin:test", None, 128).unwrap();
let mut image = TileImage::new(64, 64, 1);
let tile = Arc::new(vec![1u16; texturecraft_texel::TILE_AREA]);
let retained = Arc::downgrade(&tile);
image.set_tile(0, 0, Some(tile));
session.path_cache = Some(PathCache { eid: LayerId(0), key: (0, None), below: Vec::new(), mask: Some(image), layers: Vec::new() });
let result: Result<()> = session.edit("Rejected edit", |_| Err(EngineError::Other("rejected".into())));
assert!(result.is_err());
assert!(session.path_cache.is_none());
assert!(retained.upgrade().is_none(), "the discarded document cannot retain the cache's tile");
}
#[test]
+6 -1
View File
@@ -104,6 +104,10 @@ impl Session {
drag.last_box = Some((low, high));
let selected = self.box_selection(low, high);
let selected = match self.polygon_fill_drag.as_ref() {
Some(drag) => self.with_symmetry_copies(&drag.fill_groups, selected),
None => selected,
};
self.show_box_fill(selected)
}
@@ -178,11 +182,12 @@ impl Session {
}
}
/// Fill the fill-mode group holding `triangle` (one undo step)
/// Fill the fill-mode group holding `triangle` and its symmetry copies (one undo step)
fn fill_group_of(&mut self, triangle: u32) -> Result<usize> {
let ts = self.ts();
let groups = self.fill_partition(self.fill_material()?);
let triangles: BTreeSet<u32> = groups.group(triangle).unwrap_or_default().iter().copied().collect();
let triangles = self.with_symmetry_copies(&groups, triangles);
let (gbuf, mut canvas) = self.fill_canvas(ts)?;
fill_triangles(&mut canvas, &gbuf, &triangles);
+240
View File
@@ -0,0 +1,240 @@
//! Polygon fill with symmetry: the fill also reaches the faces the brush's mirror planes and radial copies map it onto.
use std::collections::{BTreeSet, HashSet};
use texturecraft_geom::glam::Mat3;
use crate::session::Session;
use crate::triangle_partition::TrianglePartition;
/// How far a mirrored face centre may be from the surface and still count as on it, as a fraction of the mesh's bounding-box diagonal
const MIRROR_TOLERANCE: f32 = 1e-3;
impl Session {
/// `selected` plus the faces the brush symmetry copies it onto: for each group of `groups` (the fill mode's grouping) in `selected`, the group holding the face its first triangle's centre maps to under each mirror plane and radial turn.
/// Copies that land on no face of the texture set (an asymmetric mesh, or the other side of a thin shell) are skipped
pub(crate) fn with_symmetry_copies(&self, groups: &TrianglePartition, selected: BTreeSet<u32>) -> BTreeSet<u32> {
let symmetry = self.tool.brush.sanitized().symmetry;
let copies: Vec<Mat3> = symmetry.transforms().into_iter().filter(|copy| *copy != Mat3::IDENTITY).collect();
if copies.is_empty() || selected.is_empty() {
return selected;
}
let mesh = &self.mesh;
let (low, high) = mesh.bounds();
let tolerance = (high - low).length() * MIRROR_TOLERANCE;
let origin = symmetry.origin((low + high) * 0.5);
let corners = |triangle: u32| {
let [first, second, third] = mesh.tri(triangle as usize)?;
Some([*mesh.positions.get(first)?, *mesh.positions.get(second)?, *mesh.positions.get(third)?])
};
let mut seen_groups = HashSet::new();
let mut result = selected.clone();
for seed in selected.iter().copied().filter(|triangle| groups.index_of(*triangle).is_some_and(|group| seen_groups.insert(group))) {
let Some([first, second, third]) = corners(seed) else { continue };
let centre = (first + second + third) / 3.0;
let normal = (second - first).cross(third - first);
for copy in &copies {
let target = origin + *copy * (centre - origin);
let target_normal = *copy * normal;
// A face on the same side: a thin shell's other face lies at the same point but looks the other way
let faces_alike = |triangle: u32| {
groups.index_of(triangle).is_some() && corners(triangle).is_some_and(|[a, b, c]| (b - a).cross(c - a).dot(target_normal) > 0.0)
};
if let Some(hit) = self.bvh.nearest(target, tolerance, &faces_alike) {
result.extend(groups.group(hit.tri).unwrap_or_default().iter().copied());
}
}
}
result
}
}
#[cfg(test)]
mod tests {
use texturecraft_core::Channel;
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::mesh::Mesh;
use crate::fill_hit_test::FillHitTest;
use crate::fill_mode::FillMode;
use crate::session::{Session, Tool};
/// The roughness the test fills paint, to tell filled texels apart
const FILL_ROUGHNESS: f32 = 0.9;
/// The x ranges of the two quads on the right of the YZ plane; the left side mirrors them
const QUAD_RANGES: [(f32, f32); 2] = [(1.0, 2.0), (3.0, 4.0)];
/// Texture coordinate of the point `(x, y)` on the flat test mesh, each x its own place
fn uv_of(x: f32, y: f32) -> Vec2 {
Vec2::new((x + 4.0) / 8.0, 0.2 + 0.6 * y)
}
/// Four quads facing +Z (two triangles each): [`QUAD_RANGES`] on the right and their mirror images on the left, each with its own vertices and UV place
fn mirrored_quads() -> Mesh {
let (mut positions, mut uvs, mut indices) = (Vec::new(), Vec::new(), Vec::new());
for (low, high) in QUAD_RANGES {
for mirrored in [false, true] {
let sign = if mirrored { -1.0 } else { 1.0 };
let first = positions.len() as u32;
for (x, y) in [(low, 0.0), (high, 0.0), (high, 1.0), (low, 1.0)] {
positions.push(Vec3::new(sign * x, y, 0.0));
uvs.push(uv_of(sign * x, y));
}
// A mirror image has the opposite winding, so it keeps facing +Z
let corners = if mirrored { [0, 2, 1, 0, 3, 2] } else { [0, 1, 2, 0, 2, 3] };
indices.extend(corners.map(|corner| first + corner));
}
}
Mesh::from_parts(positions, None, uvs, indices, "m").unwrap()
}
/// A fill session on [`mirrored_quads`] mirroring across X
fn mirrored_session(fill_mode: FillMode) -> Session {
let mut session = Session::new_project("t", mirrored_quads(), "test", None, 128).unwrap();
session.tool.tool = Tool::PolygonFill;
session.tool.fill_mode = fill_mode;
session.tool.brush.symmetry.x = true;
session.tool.values.insert(Channel::Roughness, [FILL_ROUGHNESS; 3]);
session.update();
session
}
/// Whether the texel at the point `(x, y)` of the flat test mesh shows the fill
fn filled_at(session: &Session, x: f32, y: f32) -> bool {
let uv = uv_of(x, y);
let (width, height) = session.caches[0].size;
let roughness = session.caches[0].composite.value(Channel::Roughness, (uv.x * width as f32) as u32, (uv.y * height as f32) as u32);
(roughness[0] - FILL_ROUGHNESS).abs() < 0.01
}
/// Whether the quad over the x range starting at `low` (negative: its mirror image on the left) shows the fill
fn quad_filled(session: &Session, low: f32) -> bool {
filled_at(session, if low < 0.0 { low - 0.5 } else { low + 0.5 }, 0.5)
}
/// Which of the four quads show the fill: right near, left near, right far, left far
fn filled_quads(session: &Session) -> [bool; 4] {
[quad_filled(session, 1.0), quad_filled(session, -1.0), quad_filled(session, 3.0), quad_filled(session, -3.0)]
}
#[test]
fn a_triangle_click_also_fills_the_mirrored_triangle() {
let mut session = mirrored_session(FillMode::Triangle);
// The lower right triangle of the near quad
assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 2, "the triangle and its mirror image");
session.update();
assert!(filled_at(&session, 1.8, 0.2) && filled_at(&session, -1.8, 0.2), "the clicked triangle and the one across the plane");
assert!(!filled_at(&session, 1.2, 0.8) && !filled_at(&session, -1.2, 0.8), "the other triangle of each quad stays");
assert!(!quad_filled(&session, 3.0) && !quad_filled(&session, -3.0), "the far quads stay");
}
#[test]
fn a_uv_island_click_fills_the_mirrored_island() {
let mut session = mirrored_session(FillMode::UvIsland);
assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 4, "both triangles of the quad and of its mirror image");
session.update();
assert_eq!(filled_quads(&session), [true, true, false, false]);
}
#[test]
fn a_mesh_click_fills_the_mirrored_connected_part_only() {
let mut session = mirrored_session(FillMode::Mesh);
// Each quad is its own piece, as its vertices touch no other quad
assert_eq!(session.polygon_fill_uv(uv_of(3.5, 0.5)).unwrap(), 4);
session.update();
assert_eq!(filled_quads(&session), [false, false, true, true]);
}
#[test]
fn a_rectangle_fills_the_mirrored_side_too() {
let mut session = mirrored_session(FillMode::UvIsland);
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
// Around the far right quad only
let filled = session.polygon_fill_box_uv(uv_of(2.9, -0.1), uv_of(4.1, 1.1)).unwrap();
session.update();
assert_eq!(filled, 4);
assert_eq!(filled_quads(&session), [false, false, true, true]);
}
#[test]
fn one_undo_takes_back_the_fill_and_its_mirror() {
let mut session = mirrored_session(FillMode::UvIsland);
let history = session.history_labels().len();
session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap();
session.update();
assert_eq!(filled_quads(&session), [true, true, false, false], "the fill and its copy show");
assert_eq!(session.history_labels().len(), history + 1, "one step for the fill and its copy");
session.undo().unwrap();
session.update();
assert_eq!(filled_quads(&session), [false; 4]);
}
#[test]
fn symmetry_off_fills_only_what_was_clicked() {
let mut session = mirrored_session(FillMode::UvIsland);
session.tool.brush.symmetry.enabled = false;
assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 2);
session.update();
assert_eq!(filled_quads(&session), [true, false, false, false]);
}
#[test]
fn faces_without_a_mirror_match_are_skipped() {
let mut session = mirrored_session(FillMode::UvIsland);
// Moving the plane to x = 10 sends every copy to x ~ 20, where there is no surface
session.tool.brush.symmetry.offset = [10.0, 0.0, 0.0];
assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 2, "only the clicked quad");
session.update();
assert_eq!(filled_quads(&session), [true, false, false, false]);
}
#[test]
fn a_face_is_not_its_own_mirror_across_its_plane() {
let mut session = mirrored_session(FillMode::Triangle);
session.tool.brush.symmetry.x = false;
session.tool.brush.symmetry.z = true;
// The flat mesh lies in the mirror plane z = 0: each triangle maps onto itself looking the other way
assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 1);
}
#[test]
fn a_radial_copy_turns_the_fill_around_the_axis() {
let mut session = mirrored_session(FillMode::UvIsland);
// Half a turn around Z through the mesh centre (0, 0.5) sends the quad onto the quad on the left
session.tool.brush.symmetry = texturecraft_paint::Symmetry { x: false, radial: 2, axis: 2, ..Default::default() };
assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 4, "the turned copy lands on the left quad");
session.update();
assert_eq!(filled_quads(&session), [true, true, false, false]);
}
#[test]
fn a_radial_copy_with_the_axis_moved_away_lands_on_no_face() {
let mut session = mirrored_session(FillMode::UvIsland);
session.tool.brush.symmetry = texturecraft_paint::Symmetry { x: false, radial: 2, axis: 2, offset: [0.0, 5.0, 0.0], ..Default::default() };
assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 2, "the turned copy is far above the mesh");
}
}
+12 -3
View File
@@ -23,13 +23,21 @@ pub struct UserPresets {
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("export.presets", "Export presets", [], None, "{} → [{name, maps, builtin}]", always, list),
cmd!("export.preset.get", "Get an export preset", [], None, "{name} → {name, maps: [{file, format, bit_depth, channels}]}", always, get),
cmd!(
"export.preset.get",
"Get an export preset",
[],
None,
"{name} → {name, maps: [{file, format, bit_depth, channels, inverted?: [dest, ...]}]}",
always,
get
),
cmd!(
"export.preset.save",
"Save a user export preset",
[],
None,
"{preset: {name, maps}, unique?: true = add \" 2\", \" 3\"… on a name clash instead of failing, rename?: name of the user preset this one replaces} → {name}",
"{preset: {name, maps (a map may list `inverted` destinations such as [\"R\"] to write 1 minus the value)}, unique?: true = add \" 2\", \" 3\"… on a name clash instead of failing, rename?: name of the user preset this one replaces} → {name}",
always,
save
),
@@ -282,7 +290,8 @@ mod tests {
assert!((rough - 0.3).abs() < 0.01);
let set = s.doc.project.texture_sets[0].name.clone();
let dir = std::env::temp_dir().join(format!("tc_user_preset_export_{}", std::process::id()));
// By name and as an inline object: the same files.
// By name and as an inline object: the same files
for preset in [json!("packed"), packed] {
let _ = std::fs::remove_dir_all(&dir);
let r = run(&mut s, "file.exportTextures", json!({"dir": dir.display().to_string(), "preset": preset, "ts": 0})).unwrap();
+3 -2
View File
@@ -36,7 +36,7 @@ fn coords(n: Vec3) -> Coords {
fn source(s: &Source, proj: &Projection, c: &Coords) -> Option<[f32; 3]> {
match s {
Source::Uniform(v) => Some(*v),
Source::Procedural { pattern, low, high } => {
Source::Procedural { pattern, low, high, .. } => {
let t = procedural(pattern, proj, c);
Some([0, 1, 2].map(|k| low[k] + (high[k] - low[k]) * t))
}
@@ -110,7 +110,8 @@ pub fn filter(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
let gbuf = texturecraft_geom::UvGBuffer::new(&mesh, 0, res, res);
let mut p = Project::new("preview", "");
p.texture_sets.push(TextureSet::new("preview", 0, res));
let procedural = |kind, scale, low: [f32; 3], high: [f32; 3]| Source::Procedural { pattern: Procedural { scale, ..Procedural::new(kind) }, low, high };
let procedural =
|kind, scale, low: [f32; 3], high: [f32; 3]| Source::Procedural { pattern: Procedural { scale, ..Procedural::new(kind) }, low, high, ramp: Vec::new() };
let mut fill = Fill::default();
fill.sources.insert(Channel::BaseColor, procedural(ProceduralKind::Clouds, 2.0, [0.05, 0.2, 0.55], [0.95, 0.55, 0.1]));
fill.sources.insert(Channel::Roughness, procedural(ProceduralKind::Checker, 4.0, [0.25; 3], [0.7; 3]));
+142
View File
@@ -0,0 +1,142 @@
//! Pattern settings in commands: the resolution a pattern is computed at and the Tile Generator's settings
use serde_json::{Map, Value};
use texturecraft_core::{
OutputResolution, Procedural, ProceduralKind, ResolutionMode, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry,
};
use crate::Result;
use crate::commands::{bad, boolp, f32p, u64p};
/// The pattern's `scale`, `seed`, `contrast`, `balance` and `invert` in `params`, applied to `pattern` in range
pub(crate) fn pattern_basics_from(params: &Value, pattern: &mut Procedural) {
if let Some(scale) = f32p(params, "scale") {
pattern.scale = scale.clamp(Procedural::MIN_SCALE, Procedural::MAX_SCALE);
}
if let Some(seed) = u64p(params, "seed") {
pattern.seed = u32::try_from(seed).unwrap_or(u32::MAX);
}
if let Some(contrast) = f32p(params, "contrast") {
pattern.contrast = contrast.clamp(0.0, Procedural::MAX_CONTRAST);
}
if let Some(balance) = f32p(params, "balance") {
pattern.balance = balance.clamp(-Procedural::MAX_BALANCE, Procedural::MAX_BALANCE);
}
if let Some(invert) = boolp(params, "invert") {
pattern.invert = invert;
}
}
/// Whether `params` holds any pattern setting [`pattern_settings_from`] reads
pub(crate) fn has_pattern_settings(params: &Value) -> bool {
["resolution", "customResolution", "resolutionFactor", "tile", "tileDefaults"].iter().any(|key| params.get(key).is_some())
}
/// Apply the resolution and Tile Generator settings in `params` to `pattern`, using `command` in errors
pub(crate) fn pattern_settings_from(command: &str, params: &Value, pattern: &mut Procedural) -> Result<()> {
resolution_from(command, params, &mut pattern.resolution)?;
let resets = boolp(params, "tileDefaults") == Some(true);
let edits = params.get("tile");
if (resets || edits.is_some()) && pattern.kind != ProceduralKind::TileGenerator {
return Err(bad(command, "`tile` and `tileDefaults` go with the Tile Generator pattern"));
}
if resets {
pattern.tile = Some(Box::default());
}
if let Some(edits) = edits {
let current = pattern.tile.get_or_insert_with(Box::default);
**current = tile_from(command, edits, current)?;
}
Ok(())
}
/// The `resolution`, `customResolution` and `resolutionFactor` params applied to `resolution`
pub(crate) fn resolution_from(command: &str, params: &Value, resolution: &mut OutputResolution) -> Result<()> {
if let Some(value) = params.get("resolution") {
let name = value.as_str().ok_or_else(|| bad(command, "`resolution` must be a string"))?;
resolution.mode = ResolutionMode::parse(name).ok_or_else(|| bad(command, format!("unknown resolution `{name}`")))?;
}
if let Some(custom) = u64p(params, "customResolution") {
resolution.custom = custom.clamp(1, u64::from(OutputResolution::MAX_SIZE)) as u32;
}
if let Some(factor) = params.get("resolutionFactor") {
let factor = factor.as_i64().ok_or_else(|| bad(command, "`resolutionFactor` must be a whole number"))?;
resolution.factor = factor.clamp(i64::from(*OutputResolution::FACTORS.start()), i64::from(*OutputResolution::FACTORS.end())) as i8;
}
Ok(())
}
/// `current` with the camelCase settings in `edits` applied (menu choices by label or id), in range
fn tile_from(command: &str, edits: &Value, current: &TileGenerator) -> Result<TileGenerator> {
let edits = edits.as_object().ok_or_else(|| bad(command, "`tile` must be an object"))?;
let mut merged = serde_json::to_value(current).map_err(|error| bad(command, error.to_string()))?;
let fields = merged.as_object_mut().ok_or_else(|| bad(command, "the Tile Generator settings are not an object"))?;
for (key, value) in edits {
let field = snake_case(key);
if !fields.contains_key(&field) {
return Err(bad(command, format!("unknown Tile Generator setting `{key}`")));
}
fields.insert(field.clone(), choice_id(command, &field, value)?);
}
let tile: TileGenerator = serde_json::from_value(merged).map_err(|error| bad(command, format!("bad Tile Generator setting: {error}")))?;
Ok(tile.clamped())
}
/// A menu setting's value as its saved id (`"Half bell"` → `"HalfBell"`); other values unchanged
fn choice_id(command: &str, field: &str, value: &Value) -> Result<Value> {
let Some(text) = value.as_str() else { return Ok(value.clone()) };
let id = match field {
"shape" => find(&TileShape::ALL, TileShape::label, text),
"size_mode" => find(&TileSizeMode::ALL, TileSizeMode::label, text),
"input_distribution" => find(&TileInputDistribution::ALL, TileInputDistribution::label, text),
"symmetry" => find(&TileSymmetry::ALL, TileSymmetry::label, text),
"blending" => find(&TileBlending::ALL, TileBlending::label, text),
_ => return Ok(value.clone()),
};
id.map(Value::String).ok_or_else(|| bad(command, format!("unknown {} `{text}`", camel_case(field))))
}
/// The id of the choice in `all` whose label or id is `text` (any case, spaces optional)
fn find<T: Copy + std::fmt::Debug>(all: &[T], label: fn(T) -> &'static str, text: &str) -> Option<String> {
let normalize = |name: &str| name.to_ascii_lowercase().replace([' ', '_', '-', '+'], "");
let wanted = normalize(text);
all.iter().find(|choice| normalize(label(**choice)) == wanted || normalize(&format!("{choice:?}")) == wanted).map(|choice| format!("{choice:?}"))
}
/// The Tile Generator settings as `project.inspect` reports them: camelCase keys, as the commands take them
pub(crate) fn tile_report(tile: &TileGenerator) -> Value {
let Ok(Value::Object(fields)) = serde_json::to_value(tile) else { return Value::Null };
Value::Object(fields.into_iter().map(|(key, value)| (camel_case(&key), value)).collect::<Map<String, Value>>())
}
fn snake_case(key: &str) -> String {
let mut snake = String::with_capacity(key.len());
for character in key.chars() {
if character.is_ascii_uppercase() {
snake.push('_');
snake.push(character.to_ascii_lowercase());
} else {
snake.push(character);
}
}
snake
}
fn camel_case(field: &str) -> String {
let mut camel = String::with_capacity(field.len());
let mut upper = false;
for character in field.chars() {
if character == '_' {
upper = true;
} else if upper {
camel.push(character.to_ascii_uppercase());
upper = false;
} else {
camel.push(character);
}
}
camel
}
+2 -2
View File
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add smart material",
[],
None,
"{material: id or label, above?: layer id, inside?: bool, index?: n} — above the selection by default; `above` (+ `inside` for a folder) or `index` in the top-level stack (0 = bottom) place it",
"{material: id or label, above?: layer id, inside?: bool, below?: layer id, top?: true, index?: n} — above the selection by default; `above` (+ `inside` for a folder), `below`, `top` or `index` in the top-level stack (0 = bottom) place it",
always,
material
),
@@ -82,7 +82,7 @@ pub fn sample_session(resolution: u32, bake_resolution: u32) -> Result<Session>
// Paint above the smart material so new strokes remain visible
for set_index in (0..session.set_count()).rev() {
session.active_set = set_index;
session.selected.remove(&set_index);
session.select_none(set_index);
crate::execute(&mut session, "layer.add.paint", &Value::Null)?;
}
session.undo.clear();
+62 -9
View File
@@ -6,6 +6,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use texturecraft_compose::ImageRes;
use texturecraft_core::{Channel, Fill, Layer, LayerKind, Source};
use texturecraft_formats::{MAX_RESOURCE_NAME_LEN, sanitize_resource_name};
use crate::commands::{CommandSpec, always, bad, channel_param, strp};
use crate::{EngineError, Result, Session, cmd};
@@ -66,17 +67,28 @@ impl Session {
let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|error| EngineError::Other(format!("{file_name}: {error}")))?;
let leaf = std::path::Path::new(file_name).file_name().and_then(|name| name.to_str()).unwrap_or("image");
let mut base = texturecraft_formats::sanitize_resource_name(leaf);
if !prefix.trim().is_empty() {
// Names stay within the sanitized length; the file name keeps its room
let room = 120usize.saturating_sub(base.chars().count());
let prefix: String = texturecraft_formats::sanitize_resource_name(prefix.trim()).chars().take(room).collect();
base = format!("{prefix}{base}");
let mut base = sanitize_resource_name(leaf);
// The file name has priority over the optional prefix
let prefix_room = MAX_RESOURCE_NAME_LEN - base.len();
let prefix = prefix.trim();
if !prefix.is_empty() && prefix_room > 0 {
let mut prefix = sanitize_resource_name(prefix);
prefix.truncate(prefix_room);
base.insert_str(0, &prefix);
}
let (stem, extension) = base.rfind('.').map_or((base.as_str(), ""), |extension_start| base.split_at(extension_start));
let mut name = base.clone();
let mut duplicate_index = 2;
while self.doc.resources.contains_key(&name) {
name = format!("{duplicate_index}_{base}");
let discriminator = format!("{duplicate_index}_");
let available = MAX_RESOURCE_NAME_LEN - discriminator.len();
// Leave room for a stem even for names that end in an unusually long extension
let (stem, extension) = if extension.len() < available { (stem, extension) } else { (base.as_str(), "") };
let stem = stem.get(..stem.len().min(available - extension.len())).unwrap_or(stem);
name = format!("{discriminator}{stem}{extension}");
duplicate_index += 1;
}
@@ -137,10 +149,12 @@ pub(crate) fn read_image_file(cmd: &str, path: &str, max_bytes: u64) -> Result<V
let read_error = |error| bad(cmd, format!("cannot read {path}: {error}"));
let too_large = || bad(cmd, format!("{path} is too large (limit {max_bytes} bytes)"));
let metadata = std::fs::metadata(path).map_err(read_error)?;
// Pipes can block on open, and devices may never reach EOF
if !metadata.is_file() {
return Err(bad(cmd, format!("{path} is not a regular file")));
}
if metadata.len() > max_bytes {
return Err(too_large());
}
@@ -179,8 +193,7 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
/// Drop resources no layer, mask effect, the projection stencil or the environment uses (one undo
/// step).
/// Drop resources unused by layers, mask effects, the brush alpha, the stencil or the environment.
fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
let mut used = Vec::new();
for set in &s.doc.project.texture_sets {
@@ -189,6 +202,7 @@ fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
}
}
used.extend(s.tool.stencil.as_ref().map(|st| st.image.clone()));
used.extend(s.tool.brush.alpha_image.clone());
used.extend(s.doc.project.display.environment_resource().map(str::to_string));
let unused: Vec<String> = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect();
if !unused.is_empty() {
@@ -263,4 +277,43 @@ mod tests {
fn devices_are_rejected_before_reading() {
assert!(read_image_file("test", "/dev/null", 16).unwrap_err().to_string().contains("not a regular file"));
}
#[test]
fn duplicate_prefixed_image_names_survive_saving_and_reopening() {
let mut session = crate::sample_session(128, 32).unwrap();
let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
let file_name = format!("{}.png", "x".repeat(108));
let prefix = "material";
let mut names = Vec::new();
for _ in 0..10 {
let name = session.import_resource_bytes_prefixed(prefix, &file_name, png.clone()).unwrap();
crate::execute(&mut session, "layer.add.image", &json!({"name": name})).unwrap();
names.push(name);
}
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
assert_eq!(reopened.images.len(), names.len());
for name in names {
assert!(reopened.images.contains_key(&name), "missing image after reload: {name}");
assert!(name.ends_with(".png"));
}
}
#[test]
fn removing_unused_resources_keeps_the_active_brush_alpha() {
let mut session = crate::sample_session(128, 32).unwrap();
let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
let alpha = session.import_resource_bytes("brush.png", png.clone()).unwrap();
let unused = session.import_resource_bytes("unused.png", png).unwrap();
crate::execute(&mut session, "tool.brush", &json!({"alpha": {"image": alpha}})).unwrap();
let result = crate::execute(&mut session, "file.removeUnused", &Value::Null).unwrap();
assert_eq!(result["removed"], json!([unused]));
assert_eq!(session.tool.brush.alpha_image.as_deref(), Some(alpha.as_str()));
assert!(session.images.contains_key(&alpha));
assert!(!session.images.contains_key(&unused));
}
}
+144 -13
View File
@@ -14,6 +14,7 @@ use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas};
use texturecraft_texel::DilationMap;
use crate::fill_mode::FillMode;
pub use crate::stencil_look::StencilLook;
use crate::{EngineError, Result};
/// Padding (texels) applied to composites for display.
@@ -182,7 +183,24 @@ pub struct StencilState {
impl StencilState {
pub fn new(image: &str) -> StencilState {
StencilState { image: image.to_string(), center: [0.0, 0.0], scale: 0.8, rotation: 0.0, tile: false, opacity: 0.5 }
StencilState::with_look(image, StencilLook::default())
}
/// A stencil of `image` placed as `look` says.
pub fn with_look(image: &str, look: StencilLook) -> StencilState {
StencilState { image: image.to_string(), center: look.center, scale: look.scale, rotation: look.rotation, tile: look.tile, opacity: look.opacity }
}
pub fn look(&self) -> StencilLook {
StencilLook { center: self.center, scale: self.scale, rotation: self.rotation, tile: self.tile, opacity: self.opacity }
}
/// Back to the placement a new stencil starts with (center, scale and rotation); the image, tiling and opacity stay.
pub fn reset_placement(&mut self) {
let start = StencilState::new(&self.image);
self.center = start.center;
self.scale = start.scale;
self.rotation = start.rotation;
}
/// Placement for a viewport aspect (width / height): center, half extents in NDC, radians.
@@ -201,6 +219,10 @@ pub struct ToolState {
/// Material painted per channel (linear values) and whether each channel is painted.
pub values: BTreeMap<Channel, [f32; 3]>,
pub enabled: BTreeSet<Channel>,
/// The simple material (shelf id) the brush paints the pattern of, with `values` as its plain
/// stand-in; `None` for plain values (any edit of a value clears it).
#[serde(default)]
pub material: Option<String>,
/// Gray painted into masks.
pub mask_value: f32,
pub fill_mode: FillMode,
@@ -213,12 +235,21 @@ pub struct ToolState {
/// Stencil used by the Projection tool.
#[serde(default)]
pub stencil: Option<StencilState>,
/// Placement the next stencil starts with: the last stencil's, kept when the stencil is
/// cleared or the project changes (its image belongs to the project, the placement does not).
#[serde(default)]
pub stencil_look: StencilLook,
/// Smudge tool: how much of the picked-up values each stamp deposits (0..1).
#[serde(default = "default_smudge_strength")]
pub smudge_strength: f32,
/// Clone tool source (V + click).
/// Clone tool source (V + click). It belongs to the active texture set: switching the set
/// (`textureSet.select`, `layer.select` into another set) clears it.
#[serde(default)]
pub clone_source: Option<CloneSource>,
/// Clone tool: keep the offset of the first stroke for the following strokes (aligned, the
/// default). Off, every stroke starts sampling at the source point.
#[serde(default = "default_clone_aligned")]
pub clone_aligned: bool,
/// What the Clone tool copies: the composite or the selected layer alone.
#[serde(default)]
pub clone_from: CloneFrom,
@@ -227,10 +258,14 @@ pub struct ToolState {
pub path: crate::path_tool::PathState,
}
fn default_smudge_strength() -> f32 {
pub(crate) fn default_smudge_strength() -> f32 {
0.5
}
fn default_clone_aligned() -> bool {
true
}
fn default_fill_visible_only() -> bool {
true
}
@@ -250,7 +285,7 @@ pub enum CloneFrom {
pub struct CloneSource {
pub uv: [f32; 2],
/// Source minus destination, fixed by the first stroke after the source was set and kept
/// for the following strokes (aligned cloning).
/// for the following strokes (aligned cloning; never set when the tool is not aligned).
pub offset: Option<[f32; 2]>,
}
@@ -262,13 +297,16 @@ impl Default for ToolState {
brush: BrushSettings::default(),
values,
enabled: [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height, Channel::Normal].into_iter().collect(),
material: None,
mask_value: 1.0,
fill_mode: FillMode::Triangle,
fill_hit_test: Default::default(),
fill_visible_only: default_fill_visible_only(),
stencil: None,
stencil_look: StencilLook::default(),
smudge_strength: default_smudge_strength(),
clone_source: None,
clone_aligned: true,
clone_from: CloneFrom::Composite,
path: Default::default(),
};
@@ -315,6 +353,48 @@ pub(crate) struct ActiveStroke {
/// A stroke visibility buffer and what it was rendered for: camera, size, mesh id.
pub(crate) type DepthCache = (OrbitCamera, (u32, u32), u64, Arc<EyeDepth>);
/// History labels that name a layer, a path number or a smart mask: the UI translates the
/// template and fills the value in (the control channel and `edit.history` keep the English label).
/// `{layer}` is a layer name, `{n}` a path number, `{name}` a smart mask name.
pub const HISTORY_TEMPLATES: &[&str] = &[
"Paint on {layer}",
"Erase on {layer}",
"Clone on {layer}",
"Smudge on {layer}",
"Projection on {layer}",
"Paint mask of {layer}",
"Erase mask of {layer}",
"Projection mask of {layer}",
EDIT_PATH_TEMPLATE,
APPLY_SMART_MASK_TEMPLATE,
];
pub(crate) const EDIT_PATH_TEMPLATE: &str = "Edit path {n}";
pub(crate) const APPLY_SMART_MASK_TEMPLATE: &str = "Apply smart mask {name}";
pub(crate) const QUICK_MASK_STROKE_LABEL: &str = "Quick mask stroke";
/// `template` with its one `{...}` placeholder replaced by `value`
pub fn history_label(template: &str, value: &str) -> String {
match (template.find('{'), template.find('}')) {
(Some(open), Some(close)) if open < close => format!("{}{}{}", &template[..open], value, &template[close + 1..]),
_ => template.to_string(),
}
}
/// The history template of a stroke by `tool`, on a layer or (`on_mask`) on its mask
pub fn stroke_template(tool: Tool, on_mask: bool) -> &'static str {
match (tool, on_mask) {
(Tool::Eraser, false) => "Erase on {layer}",
(Tool::Eraser, true) => "Erase mask of {layer}",
(Tool::Clone, _) => "Clone on {layer}",
(Tool::Smudge, _) => "Smudge on {layer}",
(Tool::Projection, false) => "Projection on {layer}",
(Tool::Projection, true) => "Projection mask of {layer}",
(_, false) => "Paint on {layer}",
(_, true) => "Paint mask of {layer}",
}
}
pub struct Session {
pub doc: Document,
pub mesh: Arc<Mesh>,
@@ -340,9 +420,14 @@ pub struct Session {
pub active_set: usize,
/// Selected layer per texture set.
pub selected: BTreeMap<usize, LayerId>,
/// Layers selected together with the selected one (Shift+click, Ctrl+click), per texture set.
/// Counts only while the selected layer is the one they were picked with (see [`Session::selected_layers`]).
pub(crate) multi: BTreeMap<usize, crate::layer_selection::MultiSelection>,
pub target: StackTarget,
pub camera: OrbitCamera,
pub view: ViewMode,
/// The layer shown alone in the viewport (not saved, not in the history; see [`crate::solo`]).
pub solo: Option<crate::Solo>,
/// The live bake preview while the app bakes (see [`crate::bake_preview`]).
pub bake_preview: Option<crate::bake_preview::BakePreview>,
/// Viewport size (pixels) used by scripted strokes.
@@ -363,6 +448,10 @@ pub struct Session {
/// Point changes of the path being edited: (earlier states for undo, undone states for redo)
pub(crate) path_steps: (Vec<crate::path_tool::PathState>, Vec<crate::path_tool::PathState>),
pub path: Option<String>,
/// False in the empty state (the app at start, or after File > Close): the document is a
/// tiny placeholder that panels do not show. Project-independent commands remain available
/// (see [`crate::commands::check_enabled`]).
pub project_open: bool,
pub modified: bool,
/// Bumps on every document change.
pub revision: u64,
@@ -411,9 +500,11 @@ impl Session {
tool: ToolState::default(),
active_set: 0,
selected,
multi: BTreeMap::new(),
target: StackTarget::Content,
camera,
view: ViewMode::Material,
solo: None,
bake_preview: None,
viewport: Vec2::new(1280.0, 800.0),
stroke: None,
@@ -425,6 +516,7 @@ impl Session {
path_draft: None,
path_steps: Default::default(),
path: None,
project_open: true,
modified: false,
revision: 1,
log: Vec::new(),
@@ -436,8 +528,18 @@ impl Session {
})
}
/// Replace this session with `next` (another project), keeping the viewport size and the
/// user's brush presets, export presets and project templates.
/// The empty state: no project is open. Holds a tiny placeholder document that the UI never
/// shows; project-dependent commands are refused.
pub fn closed() -> Result<Session> {
// The hidden placeholder uses the minimum supported texture resolution
let mut session = Session::new_project("", texturecraft_geom::primitives::plane(1.0, 1), "builtin:plane", None, texturecraft_core::MIN_RESOLUTION)?;
session.project_open = false;
Ok(session)
}
/// Replace this session with `next` (another project), keeping the viewport size, the
/// user's brush presets, export presets and project templates and the tool settings.
pub fn switch_to(&mut self, mut next: Session) {
// Invalidate caches even when both projects were loaded with the same revision
next.revision = self.revision.wrapping_add(1);
@@ -446,6 +548,7 @@ impl Session {
next.export_presets = std::mem::take(&mut self.export_presets);
next.brush_presets = std::mem::take(&mut self.brush_presets);
next.templates = std::mem::take(&mut self.templates);
crate::tool_settings::ToolSettings::of(&self.tool).apply(&mut next.tool);
*self = next;
}
@@ -521,21 +624,35 @@ impl Session {
/// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the same label (a viewport drag is one step however many updates it makes).
pub fn edit_merging<T>(&mut self, label: &str, merge: bool, change: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> {
self.edit_if_changed(label, merge, |s| change(s).map(|value| (value, true)))
}
/// A conditional edit shares the usual rollback and history snapshot with layer reorders.
pub(crate) fn edit_if_changed<T>(&mut self, label: &str, merge: bool, change: impl FnOnce(&mut Session) -> Result<(T, bool)>) -> Result<T> {
// A box fill under way becomes its own step first, so this edit isn't written over or folded into it
self.end_polygon_fill_box();
let before = self.doc.clone();
let result = change(self).and_then(|value| match self.doc.project.instance_cycle() {
Some(id) => Err(EngineError::Other(format!("instance layer {} would draw itself", id.0))),
None => Ok(value),
let result = change(self).and_then(|(value, changed)| {
if changed && let Some(id) = self.doc.project.instance_cycle() {
return Err(EngineError::Other(format!("instance layer {} would draw itself", id.0)));
}
Ok((value, changed))
});
match result {
Ok(value) => {
self.record(label, before, merge);
Ok((value, changed)) => {
if changed {
self.record(label, before, merge);
}
Ok(value)
}
Err(error) => {
self.doc = before;
// A failed repaint may have cached tiles from the discarded document
self.path_cache = None;
Err(error)
}
}
@@ -588,6 +705,11 @@ impl Session {
self.follow_uv_layouts(&previous_document.project);
self.sync_caches();
// Removed path effects must release their cached painted tiles
if self.path_cache.as_ref().is_some_and(|cache| self.paths(cache.eid).is_none()) {
self.path_cache = None;
}
// Removed or replaced resources may change any set's rendered content
let removed_or_replaced_resource =
previous_document.resources.iter().any(|(name, previous)| !self.doc.resources.get(name).is_some_and(|current| Arc::ptr_eq(previous, current)));
@@ -595,7 +717,7 @@ impl Session {
let uses_added_resource = |texture_set_index: usize| {
use texturecraft_core::{EffectKind, Fill, Source};
let uses_source = |source: &Source| matches!(source, Source::Image { name, .. } if added_resource_names.contains(name));
let uses_source = |source: &Source| source.images().into_iter().any(|name| added_resource_names.iter().any(|added| added.as_str() == name));
let uses_fill =
|fill: &Fill| fill.sources.values().any(uses_source) || fill.link.as_ref().is_some_and(|link| added_resource_names.contains(&link.package));
let project = &self.doc.project;
@@ -801,6 +923,9 @@ impl Session {
fn after_history(&mut self, other: &Document) {
self.modified = true;
// Layers picked together belong to the stack they were picked in
self.multi.clear();
self.revision = self.revision.wrapping_add(1);
self.invalidate_changed(other);
@@ -849,10 +974,16 @@ impl Session {
values: stroke.values.clone(),
mask_value: self.tool.mask_value,
stencil: stroke.stencil.clone(),
carried_mask: stroke.canvas.pickup.as_ref().and_then(|pickup| pickup.mask_values()).cloned(),
carried: stroke.canvas.pickup.as_ref().map(|pickup| pickup.values.clone()).unwrap_or_default(),
})
});
// A soloed layer's view of the project; a removed layer ends the solo
if self.solo.is_some_and(|solo| self.doc.project.locate(solo.layer).is_none()) {
self.set_solo(None);
}
let solo_view = if self.pending_tiles() > 0 { self.solo_view() } else { None };
let active = self.ts();
let order = std::iter::once(active).chain((0..self.caches.len()).filter(|ts| *ts != active));
let mut changed = false;
@@ -883,7 +1014,7 @@ impl Session {
let empty = BakedMaps::default();
let inputs = texturecraft_compose::Inputs {
project: &self.doc.project,
project: solo_view.as_ref().unwrap_or(&self.doc.project),
ts,
mesh: &self.mesh,
gbuf: &cache.gbuf,
+3
View File
@@ -90,6 +90,9 @@ pub(crate) fn select_set(s: &mut Session, ts: usize) -> Result<()> {
// Paths paint into the active set
if ts != s.ts() {
s.finish_path()?;
// The clone source is a point of the set it was picked in
s.tool.clone_source = None;
}
s.active_set = ts;
+174 -8
View File
@@ -1,10 +1,15 @@
//! Smart masks: procedural mask presets (generators and patterns driven by the baked mesh maps)
//! that replace a layer's mask in one step. Smart materials build their masks from the same
//! presets.
//! presets. A user smart mask is a layer's mask saved to a `.tcmask` file (the `.tcraft`
//! container holding one layer that carries the mask) and applied back like a preset.
use std::collections::BTreeMap;
use std::sync::Arc;
use serde_json::{Value, json};
use texturecraft_core::{
BlendMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source,
BlendMode, Effect, EffectKind, Filter, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project,
Projection, Source,
};
use crate::commands::{CommandSpec, always, bad, has_layer, layer_param, strp};
@@ -13,13 +18,25 @@ use crate::{EngineError, Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("mask.smart.apply", "Apply smart mask", [], None, "{name: smart mask id or label, layer?}", has_layer, apply_cmd),
cmd!("mask.smart.apply", "Apply smart mask", [], None, "{name: smart mask id or label, layer?} or {path: .tcmask file, layer?}", has_layer, apply_cmd),
cmd!(
"mask.smart.create",
"Create smart mask",
[],
None,
"{layer?, path: .tcmask file, name?} — saves the layer's mask (all effects, parameters, painted pixels and images) as a user smart mask",
has_layer,
create_cmd
),
cmd!("mask.smart.list", "List smart masks", [], None, "{}", always, |_, _| Ok(json!(
SMART_MASKS.iter().map(|m| json!({"id": m.id, "label": m.label})).collect::<Vec<_>>()
))),
]
}
/// Smart mask file extension.
pub const SMART_MASK_EXT: &str = "tcmask";
pub struct SmartMask {
pub id: &'static str,
pub label: &'static str,
@@ -72,10 +89,10 @@ pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32,
EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, detail: None, ..Generator::new(kind) })
}
/// A triplanar grayscale pattern fill.
/// A triplanar grayscale pattern fill
pub(crate) fn pattern(kind: ProceduralKind, scale: f32, seed: u32, contrast: f32) -> EffectKind {
EffectKind::Fill {
source: Source::Procedural { pattern: Procedural { kind, scale, seed, contrast, balance: 0.0, invert: false }, low: [0.0; 3], high: [1.0; 3] },
source: Source::Procedural { pattern: Procedural { scale, seed, contrast, ..Procedural::new(kind) }, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() },
projection: Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] },
}
}
@@ -162,7 +179,7 @@ pub(crate) fn mask(p: &mut Project, id: &str, invert: bool) -> Result<Mask> {
/// Replace layer `layer`'s mask with smart mask `name` (one undo step).
pub fn apply(s: &mut Session, layer: LayerId, name: &str) -> Result<()> {
let sm = find(name).ok_or_else(|| EngineError::Other(format!("unknown smart mask `{name}`")))?;
s.edit(&format!("Apply smart mask {}", sm.label), |s| {
s.edit(&crate::session::history_label(crate::session::APPLY_SMART_MASK_TEMPLATE, sm.label), |s| {
let m = mask(&mut s.doc.project, sm.id, false)?;
let old = s.doc.project.layer_mut(layer)?.mask.replace(m);
for e in old.map(|m| m.effects).unwrap_or_default() {
@@ -173,13 +190,162 @@ pub fn apply(s: &mut Session, layer: LayerId, name: &str) -> Result<()> {
})
}
impl Session {
/// Serialize layer `layer`'s mask (an instance without its own mask has its source's) as a user smart mask file named `name`.
pub fn smart_mask_bytes(&self, layer: LayerId, name: &str) -> Result<Vec<u8>> {
let owner = self.doc.project.mask_owner(layer);
let mask = self.doc.project.layer(owner)?.mask.clone().ok_or_else(|| EngineError::Other("the layer has no mask".into()))?;
let (ts, _, _) = self.doc.project.locate(owner).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?;
let set = self.doc.project.texture_set(ts)?;
let mut mini = crate::material_lib::one_set_document(set, name);
let id = mini.project.alloc_id();
let mut holder = Layer::new(id, name, LayerKind::Paint, &set.channel_list());
// The mask comes back switched on whatever state it was saved in
holder.mask = Some(Mask { enabled: true, ..copy_mask(&self.doc, &mask, &mut mini, set.size())? });
mini.project.insert_layer(0, holder, None, false)?;
self.file_bytes(mini, id)
}
/// Replace layer `layer`'s mask with the one in a user smart mask file (one undo step).
pub fn apply_smart_mask_bytes(&mut self, layer: LayerId, bytes: &[u8]) -> Result<()> {
let pf = texturecraft_formats::load_project_bytes(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
self.apply_smart_mask_file(layer, pf)
}
fn apply_smart_mask_file(&mut self, layer: LayerId, pf: texturecraft_formats::ProjectFile) -> Result<()> {
let mask = pf
.project
.texture_sets
.first()
.and_then(|t| t.stack.last().copied())
.and_then(|root| pf.project.layers.get(&root))
.and_then(|l| l.mask.clone())
.ok_or_else(|| EngineError::Other("the smart mask file has no mask".into()))?;
let resources: BTreeMap<String, Arc<Vec<u8>>> = pf.resources.into_iter().map(|(k, v)| (k, Arc::new(v))).collect();
let src = crate::session::Document {
bake_paint: BTreeMap::new(),
project: pf.project,
pixels: pf.pixels,
baked: BTreeMap::new(),
resources: BTreeMap::new(),
};
let label = src.project.texture_sets.first().map(|t| t.name.clone()).unwrap_or_default();
self.edit(&format!("Apply smart mask {label}"), |s| {
let (ts, _, _) = s.doc.project.locate(layer).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?;
let size = s.doc.project.texture_set(ts)?.size();
// An image whose name the project already uses for other bytes comes in under a new name
let mut renames = BTreeMap::new();
for (name, bytes) in &resources {
let mut taken = name.clone();
let mut number = 2;
while s.doc.resources.get(&taken).is_some_and(|have| have != bytes) {
let (stem, ext) = name.rsplit_once('.').map_or((name.as_str(), String::new()), |(stem, ext)| (stem, format!(".{ext}")));
taken = format!("{stem}_{number}{ext}");
number += 1;
}
s.doc.resources.entry(taken.clone()).or_insert_with(|| bytes.clone());
if taken != *name {
renames.insert(name.clone(), taken);
}
}
let mut new = copy_mask(&src, &mask, &mut s.doc, size)?;
for source in new.effects.iter_mut().flat_map(|effect| sources_mut(&mut effect.kind)) {
if let Source::Image { name, .. } = source
&& let Some(renamed) = renames.get(name.as_str())
{
*name = renamed.clone();
}
}
let old = s.doc.project.layer_mut(layer)?.mask.replace(new);
for e in old.map(|m| m.effects).unwrap_or_default() {
s.doc.pixels.masks.remove(&e.id);
}
s.target = StackTarget::Mask;
Ok(())
})?;
self.sync_images();
Ok(())
}
}
/// The sources an effect reads.
fn sources_mut(kind: &mut EffectKind) -> Vec<&mut Source> {
match kind {
EffectKind::Fill { source, .. } => vec![source],
EffectKind::Material(fill) => fill.sources.values_mut().collect(),
EffectKind::Generator(generator) => generator.inputs.values_mut().collect(),
_ => Vec::new(),
}
}
/// `mask` of document `src` with fresh effect ids from `dst` (anchor sources follow), its painted pixels moved to `dst` at `size`.
fn copy_mask(src: &crate::session::Document, mask: &Mask, dst: &mut crate::session::Document, size: (u32, u32)) -> Result<Mask> {
let mut copy = mask.clone();
let mut moved = BTreeMap::new();
for e in &mut copy.effects {
let old = e.id;
e.id = dst.project.alloc_id();
if matches!(e.kind, EffectKind::Anchor) {
moved.insert(old, e.id);
}
if let Some(img) = src.pixels.masks.get(&old) {
dst.pixels.masks.insert(e.id, crate::layer_ops::fit(img, size, &[0, 0]));
}
}
// Sources that read an anchor effect of this mask follow it to its new id
for source in copy.effects.iter_mut().flat_map(|effect| sources_mut(&mut effect.kind)) {
if let Source::Anchor { anchor, .. } = source {
*anchor = *moved.get(anchor).ok_or_else(|| EngineError::Other(format!("smart mask refers to anchor {} outside this mask", anchor.0)))?;
}
}
Ok(copy)
}
fn apply_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let name = strp(p, "name").ok_or_else(|| bad("mask.smart.apply", "`name` is required"))?;
let layer = layer_param(s, "mask.smart.apply", p)?;
apply(s, layer, name)?;
if let Some(path) = strp(p, "path") {
apply_file(s, layer, path)?;
} else {
let name = strp(p, "name").ok_or_else(|| bad("mask.smart.apply", "`name` or `path` is required"))?;
apply(s, layer, name)?;
}
Ok(json!({ "layer": layer.0 }))
}
#[cfg(not(target_arch = "wasm32"))]
fn apply_file(s: &mut Session, layer: LayerId, path: &str) -> Result<()> {
let file = texturecraft_formats::load_project(std::path::Path::new(path)).map_err(|e| bad("mask.smart.apply", format!("cannot read {path}: {e}")))?;
s.apply_smart_mask_file(layer, file)
}
#[cfg(target_arch = "wasm32")]
fn apply_file(_: &mut Session, _: LayerId, _: &str) -> Result<()> {
Err(EngineError::Other("file paths are not available in the browser".into()))
}
#[cfg(not(target_arch = "wasm32"))]
fn create_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let layer = layer_param(s, "mask.smart.create", p)?;
let path = strp(p, "path").ok_or_else(|| bad("mask.smart.create", "`path` is required"))?;
let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| s.doc.project.layer(layer).map(|l| l.name.clone()).unwrap_or_default());
let bytes = s.smart_mask_bytes(layer, &name)?;
let path = if path.ends_with(&format!(".{SMART_MASK_EXT}")) { path.to_string() } else { format!("{path}.{SMART_MASK_EXT}") };
if let Some(dir) = std::path::Path::new(&path).parent().filter(|d| !d.as_os_str().is_empty()) {
std::fs::create_dir_all(dir).map_err(|e| bad("mask.smart.create", format!("cannot create {}: {e}", dir.display())))?;
}
texturecraft_formats::write_atomic(std::path::Path::new(&path), &bytes).map_err(|e| bad("mask.smart.create", format!("cannot write {path}: {e}")))?;
Ok(json!({ "path": path }))
}
#[cfg(target_arch = "wasm32")]
fn create_cmd(_: &mut Session, _: &Value) -> Result<Value> {
Err(EngineError::Other("file paths are not available in the browser".into()))
}
#[cfg(test)]
mod tests {
use super::*;
+88
View File
@@ -0,0 +1,88 @@
//! Solo: a view-only preview of one layer on its own. The compositor draws a copy of the project
//! in which the other layers of the soloed layer's texture set are hidden (see
//! [`texturecraft_compose::solo_project`]); the document, the undo history, saving, exporting and
//! baking never see it.
use serde_json::{Value, json};
use texturecraft_core::{LayerId, Project};
use crate::commands::{CommandSpec, always, bad, boolp, layer_param};
use crate::{Result, Session, cmd};
/// The layer shown alone and whether its mask is ignored (full coverage).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Solo {
pub layer: LayerId,
pub ignore_mask: bool,
}
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"view.solo",
"Solo layer",
[],
None,
"{layer?: id | null (default: the selected layer; null ends the solo), ignoreMask?: bool (show the layer at full coverage, default false)} → {layer: id | null, ignoreMask}. View only: nothing is saved, exported, baked or put in the undo history",
always,
solo
)]
}
fn solo(s: &mut Session, p: &Value) -> Result<Value> {
let next = match p.get("layer") {
Some(Value::Null) => None,
_ => {
let layer = layer_param(s, "view.solo", p)?;
if s.doc.project.locate(layer).is_none() {
return Err(bad("view.solo", "the layer is not in a stack"));
}
Some(Solo { layer, ignore_mask: boolp(p, "ignoreMask").unwrap_or(false) })
}
};
s.set_solo(next);
Ok(json!({ "layer": s.solo.map(|solo| solo.layer.0), "ignoreMask": s.solo.is_some_and(|solo| solo.ignore_mask) }))
}
impl Session {
/// Show `solo` alone (None: the whole stack again). Changes only the view: every covered
/// tile of every set is composited again, and the next frame draws it.
pub fn set_solo(&mut self, solo: Option<Solo>) {
if self.solo == solo {
return;
}
self.solo = solo;
for cache in &mut self.caches {
// What the cache holds was composited from the other stack
cache.below = Default::default();
cache.invalidate_all();
}
self.revision = self.revision.wrapping_add(1);
}
/// The project as the compositor draws it: the soloed layer's, or None for the document's own.
pub(crate) fn solo_view(&self) -> Option<Project> {
let solo = self.solo?;
texturecraft_compose::solo_project(&self.doc.project, solo.layer, solo.ignore_mask)
}
/// Sample document pixels while solo keeps its own composite in the viewport cache.
pub(crate) fn document_composite(&self, ts: usize, tiles: &[(u32, u32)]) -> Option<std::borrow::Cow<'_, texturecraft_compose::Composite>> {
use std::borrow::Cow;
use texturecraft_compose::{Composite, composite_tiles, pad_tiles};
let cache = self.caches.get(ts)?;
if self.solo.is_none() {
return Some(Cow::Borrowed(&cache.composite));
}
self.with_inputs(ts, |inputs| {
let set = inputs.project.texture_sets.get(ts)?;
let mut output = Composite { block_scales: inputs.block_scales.clone(), ..Composite::with_size(&set.channel_list(), cache.size.0, cache.size.1) };
composite_tiles(inputs, &mut output, tiles);
pad_tiles(&mut output, &cache.dilation, tiles);
Some(Cow::Owned(output))
})
}
}
+33
View File
@@ -0,0 +1,33 @@
use serde::{Deserialize, Serialize};
/// How a stencil sits on screen, without the image (which is a project resource)
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct StencilLook {
pub center: [f32; 2],
pub scale: f32,
pub rotation: f32,
pub tile: bool,
pub opacity: f32,
}
impl Default for StencilLook {
fn default() -> Self {
StencilLook { center: [0.0, 0.0], scale: 0.8, rotation: 0.0, tile: false, opacity: 0.5 }
}
}
impl StencilLook {
pub(crate) const MAX_CENTER_OFFSET: f32 = 4.0;
pub(crate) const MIN_SCALE: f32 = 0.01;
pub(crate) const MAX_SCALE: f32 = 10.0;
pub(crate) fn sanitized(mut self) -> Self {
let defaults = Self::default();
let finite = |value: f32, fallback| if value.is_finite() { value } else { fallback };
self.center = self.center.map(|v| finite(v, 0.0).clamp(-Self::MAX_CENTER_OFFSET, Self::MAX_CENTER_OFFSET));
self.scale = finite(self.scale, defaults.scale).clamp(Self::MIN_SCALE, Self::MAX_SCALE);
self.rotation = finite(self.rotation, defaults.rotation).rem_euclid(360.0);
self.opacity = finite(self.opacity, defaults.opacity).clamp(0.0, 1.0);
self
}
}
+1 -1
View File
@@ -15,7 +15,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add text",
[],
None,
"{text (lines split at \\n), font?: family (text.fonts; default a common sans-serif), style?: e.g. Bold (default Regular), size?: 8..1024 texels per em (default 256), color?: [r,g,b] linear or \"#rrggbb\" (default white), name?} — draws the text as an image resource with an alpha (white for tool.brush {alpha: {image}}, colored for layer.add.decal)",
"{text (lines split at \\n), font?: family (text.fonts; default a common sans-serif), style?: e.g. Bold (default Regular), size?: 8..1024 texels per em (default 256), color?: [r,g,b] linear or \"#rrggbb\" sRGB (default white), name?} — draws the text as an image resource with an alpha (white for tool.brush {alpha: {image}}, colored for layer.add.decal)",
always,
add_text
),
+21 -1
View File
@@ -293,7 +293,14 @@ impl ThumbService {
self.tick = self.tick.wrapping_add(1);
let fresh = self.cache.get(&target).is_some_and(|entry| entry.generation == self.generation);
let checked = self.checked(session);
if !fresh && checked && self.snapshot.is_some() && !self.in_flight.contains(&(self.generation, target)) && !self.queue.contains(&target) {
// A target the document no longer has would render for nothing, again each frame
if !fresh
&& checked
&& !self.in_flight.contains(&(self.generation, target))
&& !self.queue.contains(&target)
&& self.snapshot.as_ref().is_some_and(|snapshot| snapshot.has(target))
{
self.queue.push_back(target);
}
@@ -475,6 +482,19 @@ mod tests {
eprintln!("20 unchanged snapshot comparisons, 4K normal + AO (256 MiB): {:?}", start.elapsed());
}
#[test]
fn a_target_the_document_lacks_is_not_rendered() {
let session = test_session().unwrap();
let removed_anchor = ThumbTarget::Stage { effect: texturecraft_core::LayerId(u64::MAX), channel: Channel::Height };
let (mut service, jobs, _results) = held_worker();
service.begin_frame(&session, 0.0);
assert!(service.get(&session, removed_anchor).image.is_none());
assert!(!service.poll(&session), "nothing is rendered, so no frame is asked for");
assert!(jobs.try_recv().is_err());
}
#[test]
fn collecting_the_last_result_requests_a_frame_to_display_it() {
let session = test_session().unwrap();
+6 -4
View File
@@ -7,6 +7,10 @@ use crate::{Session, StackTarget, Tool};
impl Session {
/// Whether `tool` can act on the selection (or on the quick mask while it is being edited)
pub fn tool_usable(&self, tool: Tool) -> bool {
if !self.project_open {
return false;
}
match tool {
// The picker reads the composite under the cursor, whatever is selected
Tool::ColorPicker => return true,
@@ -22,11 +26,9 @@ impl Session {
let project = &self.doc.project;
let Some(layer) = self.selected_layer().and_then(|id| project.layers.get(&id)) else { return false };
// Smudge and Clone read layer content, so they can't yet paint mask values
let reads_content = matches!(tool, Tool::Smudge | Tool::Clone);
match self.target {
StackTarget::Content => matches!(layer.kind, LayerKind::Paint),
StackTarget::Mask => !reads_content,
StackTarget::Mask => true,
StackTarget::Effect(effect) => {
let Some((owner, found)) = project.effect(effect) else { return false };
let Some(owner_layer) = project.layers.get(&owner) else { return false };
@@ -37,7 +39,7 @@ impl Session {
// Paths saved in a fill layer before paths there were removed stay editable
EffectKind::Path(_) => tool == Tool::Path,
EffectKind::Paint if tool == Tool::Path => !in_fill_content,
EffectKind::Paint => in_content || !reads_content,
EffectKind::Paint => true,
_ => false,
}
}
+55 -7
View File
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Brush settings",
[],
None,
"{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, backfaceCulling?, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}",
"{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, alphaSizeX?: 5..100 and alphaSizeY?: 5..100 (percent of the stamp the alpha fills), alphaRoundness?: 0..100 (Round alpha only: 100 circle, 0 square), alphaContrast?: 1..8, alphaInvert?, backfaceCulling?, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), cloneAligned? (default true: the first stroke fixes the offset to the source for the following strokes; false: every stroke starts sampling at the source point), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}",
always,
brush
),
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Tool material",
[],
None,
"{channel, color?|value?, enabled?, solo?: true (paint this channel only)} or {maskValue?: 0..1}",
"{channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?, enabled?, solo?: true (paint this channel only)} or {maskValue?: 0..1} or {material: id or label of a simple material (see material.list, smart: false)} — the brush paints that material's pattern (colour, metallic, roughness, height…, fixed to the surface, its size following the brush size) in the channels that are on; no layer is added, smart materials are refused (add them with material.apply)",
always,
material
),
@@ -199,6 +199,19 @@ fn brush(session: &mut Session, params: &Value) -> Result<Value> {
(settings.alpha_image, settings.alpha_library) = (None, Some(alpha.id.clone()));
}
let alpha_params = &mut settings.alpha_params;
for (key, slot) in [("alphaSizeX", &mut alpha_params.size_x), ("alphaSizeY", &mut alpha_params.size_y), ("alphaRoundness", &mut alpha_params.roundness)] {
if let Some(value) = percent(key) {
*slot = value;
}
}
if let Some(value) = f32p(params, "alphaContrast") {
alpha_params.contrast = value;
}
if let Some(value) = boolp(params, "alphaInvert") {
alpha_params.invert = value;
}
if let Some(value) = boolp(params, "backfaceCulling") {
settings.backface_culling = value;
}
@@ -258,6 +271,16 @@ fn brush(session: &mut Session, params: &Value) -> Result<Value> {
session.tool.brush = settings.sanitized();
session.tool.clone_from = clone_from;
if let Some(aligned) = boolp(params, "cloneAligned")
&& aligned != session.tool.clone_aligned
{
session.tool.clone_aligned = aligned;
// A new mode starts without the offset of an earlier stroke
if let Some(source) = session.tool.clone_source.as_mut() {
source.offset = None;
}
}
if let Some(value) = f32p(params, "smudgeStrength") {
session.tool.smudge_strength = (value / 100.0).clamp(0.0, 1.0);
}
@@ -277,11 +300,14 @@ pub(crate) fn brush_json(session: &Session) -> Value {
(None, Some(id)) => json!({ "library": id }),
(None, None) => json!(settings.alpha.label()),
},
"alphaSizeX": settings.alpha_params.size_x * 100.0, "alphaSizeY": settings.alpha_params.size_y * 100.0,
"alphaRoundness": settings.alpha_params.roundness * 100.0, "alphaContrast": settings.alpha_params.contrast, "alphaInvert": settings.alpha_params.invert,
"backfaceCulling": settings.backface_culling, "symmetry": [settings.symmetry.x, settings.symmetry.y, settings.symmetry.z],
"radialSymmetry": { "copies": settings.symmetry.radial, "axis": (["x", "y", "z"].get(settings.symmetry.axis as usize)) },
"symmetryOffset": settings.symmetry.offset, "symmetryOn": settings.symmetry.enabled, "symmetryAngleSpan": settings.symmetry.angle_span,
"smudgeStrength": session.tool.smudge_strength * 100.0, "particles": settings.particles,
"material": session.tool.material, "smudgeStrength": session.tool.smudge_strength * 100.0, "particles": settings.particles,
"cloneSource": if session.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" },
"cloneAligned": session.tool.clone_aligned,
})
}
@@ -289,6 +315,23 @@ fn material(s: &mut Session, p: &Value) -> Result<Value> {
let channel = channel_param("tool.material", p, "channel")?;
let color = color_param("tool.material", p, "color")?;
let value = color_param("tool.material", p, "value")?;
if let Some(id) = strp(p, "material") {
let values = crate::materials::brush_values(id).ok_or_else(|| {
bad("tool.material", format!("`{id}` is not a simple material (a brush paints plain values; add smart materials with material.apply)"))
})?;
// Reset omitted channels so values from the previous brush material do not persist
// Normal maps remain flat
for channel in Channel::ALL {
if channel.kind() == texturecraft_core::ChannelKind::NormalMap {
continue;
}
let value = values.iter().find(|(set, _)| *set == channel).map_or(channel.default_value(), |(_, value)| *value);
s.tool.values.insert(channel, value);
}
s.tool.material = Some(crate::materials::find(id).map_or_else(|| id.to_string(), |m| m.id.to_string()));
}
if let Some(v) = f32p(p, "maskValue") {
s.tool.mask_value = v.clamp(0.0, 1.0);
}
@@ -297,6 +340,7 @@ fn material(s: &mut Session, p: &Value) -> Result<Value> {
let v = if c == Channel::Height { v.map(|x| x.clamp(-1.0, 1.0)) } else { v.map(|x| x.clamp(0.0, 1.0)) };
s.tool.values.insert(c, v);
s.tool.enabled.insert(c);
s.tool.material = None;
}
match boolp(p, "enabled") {
Some(true) => {
@@ -313,6 +357,7 @@ fn material(s: &mut Session, p: &Value) -> Result<Value> {
}
s.revision = s.revision.wrapping_add(1);
Ok(json!({
"material": s.tool.material,
"values": s.tool.values.iter().map(|(c, v)| (c.id().to_string(), json!(v))).collect::<serde_json::Map<_, _>>(),
"enabled": s.tool.enabled.iter().map(|c| c.id()).collect::<Vec<_>>(),
"maskValue": s.tool.mask_value,
@@ -345,7 +390,9 @@ fn swap_mask_value(session: &mut Session, _: &Value) -> Result<Value> {
fn stencil(session: &mut Session, params: &Value) -> Result<Value> {
if boolp(params, "clear") == Some(true) {
session.tool.stencil = None;
if let Some(cleared) = session.tool.stencil.take() {
session.tool.stencil_look = cleared.look();
}
return Ok(Value::Null);
}
@@ -355,19 +402,20 @@ fn stencil(session: &mut Session, params: &Value) -> Result<Value> {
}
let previous_stencil = session.tool.stencil.take();
let mut stencil_state = crate::session::StencilState::new(name);
let mut stencil_state = crate::session::StencilState::with_look(name, session.tool.stencil_look);
if let Some(previous_stencil) = previous_stencil {
stencil_state = crate::session::StencilState { image: name.to_string(), ..previous_stencil };
}
session.tool.stencil = Some(stencil_state);
}
use crate::session::StencilLook;
let stencil_state = session.tool.stencil.as_mut().ok_or_else(|| bad("tool.stencil", "no stencil: give `image`"))?;
if let Some(center) = pair(params, "center").or_else(|| params.get("center").and_then(color_of).map(|color| [color[0], color[1]])) {
stencil_state.center = center.map(|value| value.clamp(-4.0, 4.0));
stencil_state.center = center.map(|value| value.clamp(-StencilLook::MAX_CENTER_OFFSET, StencilLook::MAX_CENTER_OFFSET));
}
if let Some(scale) = f32p(params, "scale") {
stencil_state.scale = scale.clamp(0.01, 10.0);
stencil_state.scale = scale.clamp(StencilLook::MIN_SCALE, StencilLook::MAX_SCALE);
}
if let Some(rotation) = f32p(params, "rotation") {
stencil_state.rotation = rotation.rem_euclid(360.0);
+65
View File
@@ -0,0 +1,65 @@
//! The tool settings that outlive a project: they are kept when another project opens and are
//! saved with the UI state, so the next session starts with the same brush.
use serde::{Deserialize, Serialize};
use crate::session::{CloneFrom, StencilLook, ToolState};
use texturecraft_paint::BrushSettings;
/// Brush, symmetry, stencil placement, smudge strength, clone mode and alignment and path switches. Left out
/// because they belong to one project: the clone source point, the stencil image, the points of
/// the path being drawn and the brush's image alpha (an image resource of that project).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ToolSettings {
pub brush: BrushSettings,
pub stencil: StencilLook,
pub smudge_strength: f32,
pub clone_from: CloneFrom,
/// Settings saved before the Aligned switch existed keep its default (on)
#[serde(default = "aligned_by_default")]
pub clone_aligned: bool,
pub path_closed: bool,
pub path_fill: bool,
}
fn aligned_by_default() -> bool {
true
}
impl Default for ToolSettings {
fn default() -> Self {
ToolSettings::of(&ToolState::default())
}
}
impl ToolSettings {
/// The settings `tool` has now.
pub fn of(tool: &ToolState) -> ToolSettings {
let mut brush = tool.brush.clone();
brush.alpha_image = None;
ToolSettings {
brush,
stencil: tool.stencil.as_ref().map_or(tool.stencil_look, |stencil| stencil.look()),
smudge_strength: tool.smudge_strength,
clone_from: tool.clone_from,
clone_aligned: tool.clone_aligned,
path_closed: tool.path.closed,
path_fill: tool.path.fill,
}
}
/// Make `tool` use these settings, leaving what belongs to its project alone.
pub fn apply(&self, tool: &mut ToolState) {
let alpha_image = tool.brush.alpha_image.take();
tool.brush = self.brush.clone().sanitized();
// An image alpha names a resource of the project that was open; the library alpha is global
tool.brush.alpha_image = alpha_image;
tool.stencil_look = self.stencil.sanitized();
tool.smudge_strength = if self.smudge_strength.is_finite() { self.smudge_strength.clamp(0.0, 1.0) } else { crate::session::default_smudge_strength() };
tool.clone_from = self.clone_from;
tool.clone_aligned = self.clone_aligned;
tool.path.closed = self.path_closed;
tool.path.fill = self.path_fill;
}
}
+6
View File
@@ -0,0 +1,6 @@
//! Symmetry for strokes painted in the 2D view: a dab's copies land where the 3D view's copies would
mod frame;
mod uv_mirror;
pub(crate) use uv_mirror::UvMirror;
+10
View File
@@ -0,0 +1,10 @@
use texturecraft_geom::glam::Vec3;
/// A point on a triangle with the 3D directions of one UV unit along U and along V
pub(super) struct Frame {
pub(super) pos: Vec3,
pub(super) along_u: Vec3,
pub(super) along_v: Vec3,
/// Surface length of one UV unit, for the distance a copy may be from the mirrored point
pub(super) scale: f32,
}
+141
View File
@@ -0,0 +1,141 @@
use texturecraft_geom::glam::{Mat3, Vec2, Vec3};
use texturecraft_geom::{Bvh, Mesh, NO_TRI, UvGBuffer, surface_at};
use texturecraft_paint::{StampSource, Symmetry, UvStamp};
use super::frame::Frame;
/// The mirror and radial maps of one stroke, applied to dabs through the mesh surface
pub(crate) struct UvMirror<'a> {
mesh: &'a Mesh,
bvh: &'a Bvh,
gbuf: &'a UvGBuffer,
/// The texture set's material: copies land on its triangles only, the ones the texture covers
material: usize,
origin: Vec3,
/// Linear maps of the copies as `origin + map * (p - origin)`, without the identity
maps: Vec<Mat3>,
}
impl<'a> UvMirror<'a> {
/// The copies' maps for `symmetry` about a mesh centered at `center`, `None` when it paints no copies
pub(crate) fn new(symmetry: &Symmetry, center: Vec3, mesh: &'a Mesh, bvh: &'a Bvh, gbuf: &'a UvGBuffer, material: usize) -> Option<Self> {
if !symmetry.any() {
return None;
}
// The identity comes first: it is the dab itself
let maps: Vec<Mat3> = symmetry.transforms().into_iter().skip(1).collect();
(!maps.is_empty()).then(|| UvMirror { mesh, bvh, gbuf, material, origin: symmetry.origin(center), maps })
}
/// Add the copies of `stamp` to `out`
pub(crate) fn add_copies(&self, stamp: &UvStamp, out: &mut Vec<UvStamp>) {
let Some(frame) = self.frame_at(stamp.center) else { return };
// The stamp's x axis (turned by its angle, y up on screen) on the surface; v grows down, so an angle turns towards -V
let (sin, cos) = stamp.angle.to_radians().sin_cos();
let x_axis = frame.along_u * cos - frame.along_v * sin;
let reach = stamp.radius * frame.scale;
for map in &self.maps {
let target = self.origin + *map * (frame.pos - self.origin);
let Some(hit) = self.bvh.nearest(target, reach, &|triangle| self.mesh.material_of(triangle as usize) == Some(self.material)) else { continue };
let Some(surface) = surface_at(self.mesh, hit.tri, hit.u, hit.v) else { continue };
let Some(landing) = self.frame_of(hit.tri, hit.u, hit.v) else { continue };
// Keep the dab's orientation as the 3D view does: its direction is mapped, its shape is not mirrored
let angle = turn_towards(&landing, *map * x_axis).map_or(stamp.angle, f32::to_degrees);
let source = Some(StampSource { origin: self.origin, to_source: map.transpose() });
out.push(UvStamp { center: surface.uv, angle, source, ..*stamp });
}
}
/// The surface under texture coordinate `uv`, `None` off the texture or where no triangle covers it
fn frame_at(&self, uv: Vec2) -> Option<Frame> {
let (width, height) = (self.gbuf.width as f32, self.gbuf.height as f32);
if !(0.0..1.0).contains(&uv.x) || !(0.0..1.0).contains(&uv.y) {
return None;
}
let texel = (uv.y * height) as usize * self.gbuf.width as usize + (uv.x * width) as usize;
let triangle = *self.gbuf.tri.get(texel).filter(|triangle| **triangle != NO_TRI)?;
let [a, b, c] = self.mesh.tri(triangle as usize)?;
let (ua, ub, uc) = (*self.mesh.uvs.get(a)?, *self.mesh.uvs.get(b)?, *self.mesh.uvs.get(c)?);
// Exact barycentrics of the dab's center, not the texel center's the G-buffer holds
let (to_b, to_c, to_point) = (ub - ua, uc - ua, uv - ua);
let double_area = to_b.x * to_c.y - to_c.x * to_b.y;
if double_area.abs() < f32::EPSILON {
return None;
}
let b1 = (to_point.x * to_c.y - to_c.x * to_point.y) / double_area;
let b2 = (to_b.x * to_point.y - to_point.x * to_b.y) / double_area;
self.frame_of(triangle, b1, b2)
}
/// The point of `triangle` with barycentrics `b1` and `b2` of its second and third corners, with its UV directions
fn frame_of(&self, triangle: u32, b1: f32, b2: f32) -> Option<Frame> {
let [a, b, c] = self.mesh.tri(triangle as usize)?;
let (pa, pb, pc) = (*self.mesh.positions.get(a)?, *self.mesh.positions.get(b)?, *self.mesh.positions.get(c)?);
let (ua, ub, uc) = (*self.mesh.uvs.get(a)?, *self.mesh.uvs.get(b)?, *self.mesh.uvs.get(c)?);
let (edge_b, edge_c, to_b, to_c) = (pb - pa, pc - pa, ub - ua, uc - ua);
let double_area = to_b.x * to_c.y - to_c.x * to_b.y;
if double_area.abs() < f32::EPSILON {
return None;
}
let along_u = (edge_b * to_c.y - edge_c * to_b.y) / double_area;
let along_v = (edge_c * to_b.x - edge_b * to_c.x) / double_area;
let scale = (edge_b.cross(edge_c).length() / double_area.abs()).sqrt();
let pos = pa + edge_b * b1 + edge_c * b2;
(pos.is_finite() && along_u.is_finite() && along_v.is_finite() && scale.is_finite()).then_some(Frame { pos, along_u, along_v, scale })
}
}
/// The angle (radians) a stamp's x axis needs in the UV frame of `landing` to point along `direction` on the surface
fn turn_towards(landing: &Frame, direction: Vec3) -> Option<f32> {
// Least squares for direction = along_u * cos - along_v * sin, with (cos, -sin) the unknowns
let (uu, uv, vv) = (landing.along_u.dot(landing.along_u), landing.along_u.dot(landing.along_v), landing.along_v.dot(landing.along_v));
let (u_dot, v_dot) = (landing.along_u.dot(direction), landing.along_v.dot(direction));
let det = uu * vv - uv * uv;
if det.abs() < f32::EPSILON {
return None;
}
let (cos, minus_sin) = ((u_dot * vv - v_dot * uv) / det, (v_dot * uu - u_dot * uv) / det);
let sin = -minus_sin;
(cos != 0.0 || sin != 0.0).then(|| sin.atan2(cos)).filter(|angle| angle.is_finite())
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn a_quarter_turn_copy_turns_the_dab_angle_the_same_way() {
// A square in the XY plane: U along +X, V down along -Y
let positions = vec![Vec3::new(-1.0, -1.0, 0.0), Vec3::new(1.0, -1.0, 0.0), Vec3::new(1.0, 1.0, 0.0), Vec3::new(-1.0, 1.0, 0.0)];
let uvs = vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)];
let mesh = Mesh::from_parts(positions, None, uvs, vec![0, 1, 2, 0, 2, 3], "square").unwrap();
let (bvh, gbuf) = (Bvh::new(&mesh), UvGBuffer::new(&mesh, 0, 64, 64));
let symmetry = Symmetry { radial: 4, axis: 2, ..Symmetry::default() };
let mirror = UvMirror::new(&symmetry, Vec3::ZERO, &mesh, &bvh, &gbuf, 0).unwrap();
// The dab at world (0.5, 0) points 30 degrees up from +X
let stamp = UvStamp { center: Vec2::new(0.75, 0.5), radius: 0.05, angle: 30.0, flow: 1.0, hardness: 1.0, seed: 0, source: None };
let mut copies = Vec::new();
mirror.add_copies(&stamp, &mut copies);
assert_eq!(copies.len(), 3);
// A quarter turn about +Z puts the copy at world (0, 0.5), pointing 120 degrees from +X
let quarter = copies.iter().find(|copy| (copy.center - Vec2::new(0.5, 0.25)).length() < 0.01).unwrap();
assert!((quarter.angle - 120.0).abs() < 0.1, "angle {}", quarter.angle);
// Each copy is told apart from the stroke and the other copies (a smudge gives each its own trail)
let sources: Vec<_> = copies.iter().map(|copy| copy.source).collect();
assert!(sources.iter().all(Option::is_some), "copies carry their source");
assert!(sources.iter().enumerate().all(|(i, a)| sources.iter().skip(i + 1).all(|b| a != b)), "every copy has its own source");
}
}
+38 -4
View File
@@ -6,12 +6,30 @@ use texturecraft_core::{BakedMap, Channel, ToneMapping};
use texturecraft_geom::glam::Vec3;
use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p};
use crate::frame_target::FrameTarget;
use crate::session::ViewMode;
use crate::{Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("viewport.frame", "Show entire mesh", ["Viewport"], Some("F"), "{}", always, frame),
cmd!(
"viewport.frame",
"Show entire mesh",
["Viewport"],
Some("F"),
"{target?: \"all\" (default: the whole mesh, helper geometry included) | \"selection\" (the active texture set's geometry)} → the camera; the orbit turns around the framed center",
always,
frame
),
cmd!(
"viewport.frameSelection",
"Frame texture set",
["Viewport"],
Some("Shift+F"),
"{} → the camera, framing the active texture set's geometry",
always,
|s, _| frame_target(s, FrameTarget::Selection)
),
cmd!("viewport.displayMaterial", "Display material", ["Viewport"], Some("M"), "{}", always, |s, _| set_view(s, ViewMode::Material)),
cmd!("viewport.nextChannel", "Display next channel", ["Viewport"], Some("C"), "{}", always, |s, _| cycle_channel(s, 1)),
cmd!("viewport.previousChannel", "Display previous channel", ["Viewport"], Some("Shift+C"), "{}", always, |s, _| cycle_channel(s, -1)),
@@ -26,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Display settings",
[],
None,
"{environment?: <built-in>|resource:<image resource>, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, displacement? (the viewport moves the surface by the height channel), scatterColor?: [r,g,b] (linear) | \"#rrggbb\", scatterRadius? (0..1 of the mesh radius), ior? (1..3, transmission), dof?: {enabled?, focusDistance? (view depth, world units; 0 = the orbit target), aperture? (lens radius, 0..1 of the mesh radius)}}",
"{environment?: <built-in>|resource:<image resource>, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, displacement? (the viewport moves the surface by the height channel), scatterColor?: [r,g,b] linear or \"#rrggbb\" sRGB, scatterRadius? (0..1 of the mesh radius), ior? (1..3, transmission), dof?: {enabled?, focusDistance? (view depth, world units; 0 = the orbit target), aperture? (lens radius, 0..1 of the mesh radius)}}",
always,
display
),
@@ -80,8 +98,24 @@ fn repeat(s: &mut Session, p: &Value, step: fn(&mut Session) -> Result<String>)
Ok((last, n))
}
fn frame(s: &mut Session, _: &Value) -> Result<Value> {
let (lo, hi) = s.mesh.bounds();
fn frame(s: &mut Session, p: &Value) -> Result<Value> {
let target = match strp(p, "target") {
None | Some("all") => FrameTarget::All,
Some("selection") => FrameTarget::Selection,
Some(other) => return Err(bad("viewport.frame", format!("unknown target `{other}` (all or selection)"))),
};
frame_target(s, target)
}
/// Frame the whole mesh, or only the triangles of the active texture set's material (the thing
/// being painted, without a floor plane or other helper geometry), and orbit around that center.
fn frame_target(s: &mut Session, target: FrameTarget) -> Result<Value> {
let selection = match target {
FrameTarget::Selection => s.doc.project.texture_sets.get(s.ts()).and_then(|set| s.mesh.bounds_of_material(set.material)),
FrameTarget::All => None,
};
let (lo, hi) = selection.unwrap_or_else(|| s.mesh.bounds());
s.camera.frame(lo, hi);
s.revision = s.revision.wrapping_add(1);
Ok(camera_json(s))
+15
View File
@@ -637,6 +637,21 @@ fn a_failed_multi_set_bake_restores_settings_pixels_and_history() {
assert_eq!(session.history_labels(), history);
}
#[test]
fn obj_submesh_id_separates_objects_with_the_same_name_and_material() {
use texturecraft_engine::{core::IdColorSource, formats::import_mesh_bytes};
let file = b"o Part\nusemtl Shared\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 0.45 0\nvt 0 1\nf 1/1 2/2 3/3\no Part\nusemtl Shared\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0.5 0\nvt 0.95 0\nvt 0.5 1\nf 4/4 5/5 6/6";
let mesh = import_mesh_bytes("parts.obj", file).unwrap().mesh;
assert_eq!(mesh.materials.len(), 1);
assert_eq!(mesh.submeshes.len(), 2);
let mut session = Session::new_project("parts", mesh, "parts.obj", None, 128).unwrap();
session.doc.project.texture_sets[0].bake.maps.id.parameters.source = IdColorSource::Submesh;
execute(&mut session, "bake.run", &json!({"resolution":128,"maps":["id"],"dilation":0})).unwrap();
let map = &session.doc.baked[&0].maps[&BakedMap::Id];
let pixel = |x: usize| &map[(100 * 128 + x) * 3..(100 * 128 + x) * 3 + 3];
assert_ne!(pixel(10), pixel(74));
}
/// `file.changeMesh` swaps the mesh under a baked project: the high poly and the skew map stay,
/// the project counts as changed, and image resources are decoded in the new session.
#[test]
@@ -113,6 +113,7 @@ fn imported_mesh_maps_display_and_export_the_entire_overridden_tile() {
format: FileFormat::Png,
bit_depth: 8,
channels: vec![(Dest::L, SourceRef::Baked { map, component: 0 })],
inverted: Vec::new(),
}],
});
let files = session.export_files(&[0], &options).unwrap();
+195
View File
@@ -0,0 +1,195 @@
//! A simple shelf material can be the brush's material (`tool.material {material}`): no layer, and the
//! next stroke paints it. Shelf drops place new layers with `below` and `top`.
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, LayerId};
use texturecraft_engine::geom::glam::Vec2;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::materials::{MATERIALS, brush_values};
use texturecraft_engine::{Session, execute};
fn session() -> Session {
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap();
s.viewport = Vec2::new(400.0, 400.0);
s.camera.yaw = 0.0;
s.camera.pitch = 0.0;
s.update();
s
}
fn stack(s: &Session) -> Vec<LayerId> {
s.doc.project.texture_set(0).unwrap().stack.clone()
}
#[test]
fn every_simple_material_has_brush_values_and_no_smart_material_has() {
for material in MATERIALS {
let values = brush_values(material.id);
assert_eq!(values.is_some(), !material.smart, "{}", material.id);
if let Some(values) = values {
let channels: Vec<Channel> = values.iter().map(|(channel, _)| *channel).collect();
for channel in [Channel::BaseColor, Channel::Metallic, Channel::Roughness] {
assert!(channels.contains(&channel), "{} has no {channel:?}", material.id);
}
}
}
assert!(brush_values("nope").is_none());
}
#[test]
fn a_material_set_on_the_brush_adds_no_layer_and_no_history() {
let mut s = session();
let (layers, history) = (stack(&s), s.history_labels());
execute(&mut s, "tool.material", &json!({"material": "copper_hammered"})).unwrap();
assert_eq!(stack(&s), layers);
assert_eq!(s.history_labels(), history);
for (channel, value) in brush_values("copper_hammered").unwrap() {
assert_eq!(s.tool.values[&channel], value, "{channel:?}");
}
assert!(s.tool.values[&Channel::Height][0] < 0.0, "the material's height comes along");
assert!(s.tool.enabled.contains(&Channel::Roughness), "the channel toggles stay as they were");
}
#[test]
fn a_material_without_height_resets_the_height_of_the_previous_one() {
let mut s = session();
execute(&mut s, "tool.material", &json!({"material": "copper_hammered"})).unwrap();
assert!(s.tool.values[&Channel::Height][0] < 0.0);
execute(&mut s, "tool.material", &json!({"material": "copper"})).unwrap();
assert_eq!(s.tool.values[&Channel::Height], Channel::Height.default_value());
}
#[test]
fn a_smart_material_or_an_unknown_one_cannot_be_the_brush_material() {
let mut s = session();
let before = s.tool.values.clone();
for id in ["iron_rusted", "nope"] {
assert!(execute(&mut s, "tool.material", &json!({"material": id})).is_err(), "{id}");
}
assert_eq!(s.tool.values, before);
}
/// Texel of the sphere point under screen position `(x, y)`
fn texel(s: &Session, x: f32, y: f32) -> (u32, u32) {
let hit = s.pick(Vec2::new(x, y), s.viewport).unwrap();
((hit.uv.x * 256.0) as u32, (hit.uv.y * 256.0) as u32)
}
/// A session with `material` as the brush material, brush `size` (0..100), the stroke along y = 200 over `xs`
fn painted(material: &str, size: u32, xs: [f32; 2]) -> Session {
let mut s = session();
paint(&mut s, material, size, xs);
s
}
fn paint(s: &mut Session, material: &str, size: u32, xs: [f32; 2]) {
execute(s, "tool.material", &json!({"material": material})).unwrap();
execute(s, "tool.brush", &json!({"size": size, "hardness": 100})).unwrap();
execute(s, "tool.stroke", &json!({"points": [[xs[0], 200], [xs[1], 200]]})).unwrap();
s.update();
}
/// What a fill layer of `material` (projection scale `scale`) shows over the sphere
fn fill_of(material: &str, scale: f32) -> Session {
let mut s = session();
let layer = LayerId(execute(&mut s, "material.apply", &json!({"material": material})).unwrap()["layer"].as_u64().unwrap());
execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "projection": "triplanar", "scale": scale})).unwrap();
s.update();
s
}
fn at(s: &Session, channel: Channel, (x, y): (u32, u32)) -> f32 {
s.caches[0].composite.value(channel, x, y)[0]
}
#[test]
fn a_stroke_after_picking_a_material_paints_its_pattern_like_a_fill_of_it() {
// Brush size 40 is the pattern's natural size: the same as a fill layer with the material
let (stroke, fill) = (painted("cobblestone", 40, [150.0, 250.0]), fill_of("cobblestone", 1.0));
let samples: Vec<f32> = (0..24).map(|i| 170.0 + 3.0 * i as f32).collect();
let mut colours = Vec::new();
for x in samples {
let texel = texel(&stroke, x, 200.0);
for channel in [Channel::BaseColor, Channel::Roughness, Channel::Height] {
let (painted, expected) = (at(&stroke, channel, texel), at(&fill, channel, texel));
assert!((painted - expected).abs() < 0.02, "{channel:?} at x = {x}: {painted} vs {expected}");
}
colours.push(at(&stroke, Channel::BaseColor, texel));
}
let (low, high) = colours.iter().fold((f32::MAX, f32::MIN), |(low, high), v| (low.min(*v), high.max(*v)));
assert!(high - low > 0.05, "the colour varies along the stroke: {colours:?}");
}
#[test]
fn overlapping_strokes_agree_where_they_overlap() {
let mut s = painted("cobblestone", 40, [150.0, 215.0]);
let samples: Vec<(u32, u32)> = (0..8).map(|i| texel(&s, 190.0 + 3.0 * i as f32, 200.0)).collect();
let first: Vec<f32> = samples.iter().map(|t| at(&s, Channel::BaseColor, *t)).collect();
paint(&mut s, "cobblestone", 40, [185.0, 250.0]);
for (i, t) in samples.iter().enumerate() {
assert!((at(&s, Channel::BaseColor, *t) - first[i]).abs() < 0.005, "sample {i}");
}
}
#[test]
fn the_pattern_follows_the_brush_size() {
// A quarter of the natural brush size is a pattern four times as fine
let (stroke, fill) = (painted("cobblestone", 10, [194.0, 206.0]), fill_of("cobblestone", 4.0));
let natural = fill_of("cobblestone", 1.0);
let (mut fine, mut coarse) = (0.0_f32, 0.0_f32);
for x in [197.0, 199.0, 201.0, 203.0] {
let texel = texel(&stroke, x, 200.0);
let painted = at(&stroke, Channel::BaseColor, texel);
fine = fine.max((painted - at(&fill, Channel::BaseColor, texel)).abs());
coarse = coarse.max((painted - at(&natural, Channel::BaseColor, texel)).abs());
}
assert!(fine < 0.02, "matches the pattern at 4x: {fine}");
assert!(coarse > 0.02, "differs from the natural size: {coarse}");
}
#[test]
fn editing_a_brush_value_ends_the_pattern() {
let mut s = session();
execute(&mut s, "tool.material", &json!({"material": "cobblestone"})).unwrap();
assert_eq!(s.tool.material.as_deref(), Some("cobblestone"));
execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap();
assert_eq!(s.tool.material, None);
}
/// Add copper with `place` params (above, below, top, index)
fn apply(s: &mut Session, place: Value) -> LayerId {
let mut params = json!({"material": "copper"});
params.as_object_mut().unwrap().extend(place.as_object().unwrap().clone());
LayerId(execute(s, "material.apply", &params).unwrap()["layer"].as_u64().unwrap())
}
#[test]
fn a_material_dropped_on_a_row_goes_directly_below_it_and_one_dropped_on_the_view_goes_on_top() {
let mut s = session();
let paint = stack(&s)[0];
let upper = apply(&mut s, json!({}));
let lower = apply(&mut s, json!({"index": 0}));
assert_eq!(stack(&s), vec![lower, paint, upper]);
let below_paint = apply(&mut s, json!({"below": paint.0}));
assert_eq!(stack(&s), vec![lower, below_paint, paint, upper]);
let below_bottom = apply(&mut s, json!({"below": lower.0}));
assert_eq!(stack(&s)[0], below_bottom, "below the bottom row is the bottom");
s.selected.insert(0, lower);
let top = apply(&mut s, json!({"top": true}));
assert_eq!(stack(&s).last(), Some(&top), "the top, wherever the selection is");
assert_eq!(s.selected_layer(), Some(top));
s.doc.project.validate().unwrap();
}
+79
View File
@@ -0,0 +1,79 @@
//! The empty state (no project open): project-dependent commands are refused, and
//! File > Close returns to it.
use serde_json::json;
use texturecraft_engine::{EngineError, Session, Tool, check_enabled, command_specs, execute, find};
fn open_project() -> Session {
Session::new_project("Open", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap()
}
#[test]
fn a_closed_session_refuses_commands_that_need_a_project() {
let mut session = Session::closed().unwrap();
assert!(!session.project_open);
for id in ["layer.add.paint", "file.save", "file.close", "edit.undo", "tool.paint", "bake.run", "file.exportTextures", "viewport.view", "camera.add"] {
let error = execute(&mut session, id, &json!({})).unwrap_err();
assert!(matches!(error, EngineError::Disabled { .. }), "{id}: {error}");
}
assert!(!session.can_undo(), "nothing was changed");
assert!(!session.tool_usable(Tool::Paint), "no tool can act without a project");
}
#[test]
fn a_closed_session_lists_project_independent_commands_as_enabled() {
let session = Session::closed().unwrap();
for id in ["file.open", "file.new", "project.new", "project.sample"] {
assert!(check_enabled(find(id).unwrap(), &session).is_ok(), "{id} runs with no project");
}
let enabled: Vec<&str> = command_specs().iter().filter(|spec| check_enabled(spec, &session).is_ok()).map(|spec| spec.id).collect();
assert!(!enabled.iter().any(|id| id.starts_with("layer.") || id.starts_with("tool.") || id.starts_with("bake.")), "{enabled:?}");
}
#[test]
fn creating_a_project_from_the_closed_state_opens_it() {
let mut session = Session::closed().unwrap();
execute(&mut session, "project.new", &json!({"mesh": "cube", "resolution": 128})).unwrap();
assert!(session.project_open);
execute(&mut session, "layer.add.paint", &json!({})).unwrap();
}
#[test]
fn close_returns_to_the_empty_state_and_allows_reopening() {
let mut session = open_project();
session.modified = true;
execute(&mut session, "file.close", &json!({})).unwrap();
assert!(!session.project_open && !session.modified && session.path.is_none());
assert!(execute(&mut session, "file.close", &json!({})).is_err(), "closing again has nothing to close");
execute(&mut session, "project.new", &json!({"mesh": "cube", "resolution": 128})).unwrap();
assert!(session.project_open, "a project can be created again");
}
#[test]
fn the_libraries_and_presets_still_answer_without_a_project() {
let mut session = Session::closed().unwrap();
for id in [
"export.presets",
"brush.preset.list",
"alpha.list",
"filter.list",
"material.list",
"mask.smart.list",
"text.fonts",
"project.templates",
"project.inspect",
] {
execute(&mut session, id, &json!({})).unwrap_or_else(|error| panic!("{id}: {error}"));
}
assert_eq!(texturecraft_engine::inspect::session(&session)["projectOpen"], json!(false));
}
+110
View File
@@ -0,0 +1,110 @@
//! Frame texture set (Shift+F) and Show entire mesh (F): a floor plane must not decide the camera
use serde_json::{Value, json};
use texturecraft_engine::geom::glam::Vec3;
use texturecraft_engine::{Session, execute};
/// A small "Hydrant" (set 0) near the origin and a huge "Floor" (set 1) below and around it
const SCENE_OBJ: &str = "o Hydrant\nusemtl Hydrant\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n\
o Floor\nusemtl Floor\nv -100 -1 -100\nv 100 -1 -100\nv 0 -1 100\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n";
fn scene() -> Session {
let session = Session::from_mesh_bytes("scene.obj", SCENE_OBJ.as_bytes(), 256, "scene").unwrap();
let sets: Vec<_> = session.doc.project.texture_sets.iter().map(|set| session.mesh.materials[set.material].as_str()).collect();
assert_eq!(sets, ["Hydrant", "Floor"], "the sets follow the parts");
session
}
fn target(session: &Session) -> Vec3 {
session.camera.target
}
fn near(a: Vec3, b: Vec3) -> bool {
(a - b).length() < 1e-4
}
#[test]
fn frame_texture_set_frames_only_the_active_set() {
let mut session = scene();
let all = session.camera.distance;
execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap();
assert!(near(target(&session), Vec3::new(0.5, 0.5, 0.0)), "the camera looks at the hydrant, not the floor: {:?}", target(&session));
assert!(session.camera.distance < all * 0.05, "the hydrant is about 1 unit across, the whole scene about 280: {} vs {all}", session.camera.distance);
}
#[test]
fn frame_texture_set_follows_the_selected_set() {
let mut session = scene();
execute(&mut session, "textureSet.select", &json!({"ts": 1})).unwrap();
execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap();
assert!(near(target(&session), Vec3::new(0.0, -1.0, 0.0)), "{:?}", target(&session));
assert!(session.camera.distance > 100.0, "the floor is wide: {}", session.camera.distance);
}
#[test]
fn orbit_turns_around_the_framed_center() {
let mut session = scene();
execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap();
let (center, distance) = (target(&session), session.camera.distance);
for (dx, dy) in [(90.0, 0.0), (0.0, 30.0), (-45.0, -10.0)] {
execute(&mut session, "camera.orbit", &json!({"dx": dx, "dy": dy})).unwrap();
assert!(near(target(&session), center), "orbiting keeps the pivot");
assert!(((session.camera.eye() - center).length() - distance).abs() < 1e-3, "and the eye stays that far from the framed center");
}
}
#[test]
fn show_entire_mesh_restores_the_whole_scene() {
let mut session = scene();
let whole = (target(&session), session.camera.distance);
execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap();
assert!(!near(target(&session), whole.0));
execute(&mut session, "viewport.frame", &Value::Null).unwrap();
assert!(near(target(&session), whole.0), "{:?}", target(&session));
assert!((session.camera.distance - whole.1).abs() < 1e-3);
}
#[test]
fn viewport_frame_takes_a_target() {
let mut session = scene();
let whole = session.camera.distance;
let selection = execute(&mut session, "viewport.frame", &json!({"target": "selection"})).unwrap();
assert!(session.camera.distance < whole * 0.05);
assert_eq!(selection["target"], json!([0.5, 0.5, 0.0]));
execute(&mut session, "viewport.frame", &json!({"target": "all"})).unwrap();
assert!((session.camera.distance - whole).abs() < 1e-3);
assert!(execute(&mut session, "viewport.frame", &json!({"target": "floor"})).is_err());
}
#[test]
fn a_set_without_triangles_frames_the_whole_mesh() {
let mut session = scene();
let whole = (target(&session), session.camera.distance);
session.doc.project.texture_sets[0].material = 7;
execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap();
assert!(near(target(&session), whole.0) && (session.camera.distance - whole.1).abs() < 1e-3);
}
#[test]
fn a_saved_overview_camera_is_restored_after_framing_a_set() {
let mut session = scene();
execute(&mut session, "camera.add", &json!({"name": "Overview"})).unwrap();
let overview = session.camera.distance;
execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap();
execute(&mut session, "camera.select", &json!({"name": "Overview"})).unwrap();
assert!((session.camera.distance - overview).abs() < 1e-3, "{} vs {overview}", session.camera.distance);
}
+223
View File
@@ -0,0 +1,223 @@
//! Gradient maps on a fill's base color: color stops for a procedural or an anchor point,
//! through `layer.fill.set {colors}`, undo, inspect and a project round trip.
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, LayerId, LayerKind, Source};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
fn session() -> Session {
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap();
s.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0);
s.camera.yaw = 0.0;
s.camera.pitch = 0.0;
s.update();
s
}
/// Composited value of `c` under the viewport center.
fn center(s: &mut Session, c: Channel) -> [f32; 3] {
s.update();
let hit = s.pick(texturecraft_engine::geom::glam::Vec2::new(200.0, 200.0), s.viewport).unwrap();
s.caches[0].composite.value(c, (hit.uv.x * 256.0) as u32, (hit.uv.y * 256.0) as u32)
}
fn close(a: [f32; 3], b: [f32; 3]) -> bool {
(0..3).all(|i| (a[i] - b[i]).abs() < 2e-3)
}
fn id(v: Value, key: &str) -> u64 {
v[key].as_u64().unwrap()
}
/// The stops on `layer`'s base color source.
fn ramp(s: &Session, layer: u64) -> Vec<[f32; 3]> {
match &s.doc.project.layer(LayerId(layer)).unwrap().kind {
LayerKind::Fill(fill) => fill.source(Channel::BaseColor).ramp().to_vec(),
_ => panic!("not a fill layer"),
}
}
const RGB: [[f32; 3]; 3] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
#[test]
fn an_anchor_gradient_map_recolors_the_gray_below_and_undoes() {
let mut s = session();
execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap();
let anchor = id(execute(&mut s, "effect.add.anchor", &json!({})).unwrap(), "effect");
let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0], "roughness": 0.3, "metallic": 0.6})).unwrap(), "layer");
execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "anchor": anchor})).unwrap();
assert!(close(center(&mut s, Channel::BaseColor), [0.5; 3]), "{:?}", center(&mut s, Channel::BaseColor));
// Mid gray picks the middle stop; the other channels keep their values
execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "colors": RGB})).unwrap();
assert!(close(center(&mut s, Channel::BaseColor), [0.0, 1.0, 0.0]), "{:?}", center(&mut s, Channel::BaseColor));
assert!(close(center(&mut s, Channel::Roughness), [0.3; 3]));
assert!(close(center(&mut s, Channel::Metallic), [0.6; 3]));
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap();
let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == top).unwrap().clone();
assert_eq!(row["fill"]["sources"]["baseColor"]["colors"], json!(RGB), "{row}");
// One undo step each way
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!(ramp(&s, top).is_empty());
assert!(close(center(&mut s, Channel::BaseColor), [0.5; 3]));
execute(&mut s, "edit.redo", &Value::Null).unwrap();
assert_eq!(ramp(&s, top), RGB.to_vec());
assert!(close(center(&mut s, Channel::BaseColor), [0.0, 1.0, 0.0]));
// Picking the anchor again keeps the stops; hex colors work; an empty list removes them
execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "colors": ["#000000", "#ff0000"]})).unwrap();
execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "anchor": anchor})).unwrap();
assert!(close(center(&mut s, Channel::BaseColor), [0.5, 0.0, 0.0]), "{:?}", center(&mut s, Channel::BaseColor));
execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "colors": []})).unwrap();
assert!(ramp(&s, top).is_empty());
assert!(close(center(&mut s, Channel::BaseColor), [0.5; 3]));
}
#[test]
fn a_procedural_gradient_map_saves_and_loads() {
let mut s = session();
let layer = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0], "roughness": 0.4})).unwrap(), "layer");
execute(&mut s, "layer.fill.set", &json!({"layer": layer, "channel": "baseColor", "procedural": "Checker", "low": [0.2, 0.2, 0.2], "high": [0.8, 0.8, 0.8], "colors": [[1, 0, 0], [0, 0, 1]]})).unwrap();
let value = center(&mut s, Channel::BaseColor);
assert!(close(value, [1.0, 0.0, 0.0]) || close(value, [0.0, 0.0, 1.0]), "a stop, not low or high: {value:?}");
assert!(close(center(&mut s, Channel::Roughness), [0.4; 3]));
// Changing the pattern's settings without `colors` (as its sliders do) keeps the stops
execute(
&mut s,
"layer.fill.set",
&json!({"layer": layer, "channel": "baseColor", "procedural": "Checker", "scale": 8.0, "low": [0.2, 0.2, 0.2], "high": [0.8, 0.8, 0.8]}),
)
.unwrap();
assert_eq!(ramp(&s, layer), vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]);
let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
assert_eq!(back.doc.project, s.doc.project);
assert_eq!(ramp(&back, layer), vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]);
match &back.doc.project.layer(LayerId(layer)).unwrap().kind {
LayerKind::Fill(fill) => assert!(matches!(fill.source(Channel::BaseColor), Source::Procedural { .. })),
_ => panic!("not a fill layer"),
}
}
#[test]
fn gradient_map_colors_are_refused_where_they_cannot_apply() {
let mut s = session();
let layer = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0], "roughness": 0.4})).unwrap(), "layer");
let set = |s: &mut Session, extra: Value| {
let mut p = json!({"layer": layer});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
execute(s, "layer.fill.set", &p)
};
assert!(set(&mut s, json!({"channel": "baseColor", "colors": RGB})).is_err(), "a uniform color has no gray to map");
assert!(set(&mut s, json!({"channel": "roughness", "procedural": "Clouds", "colors": RGB})).is_err(), "only color channels");
assert!(set(&mut s, json!({"channel": "baseColor", "procedural": "Clouds", "colors": vec![[0.5; 3]; 17]})).is_err(), "at most 16 stops");
assert!(set(&mut s, json!({"channel": "baseColor", "procedural": "Clouds", "colors": ["red"]})).is_err());
assert!(ramp(&s, layer).is_empty(), "a refused edit changes nothing");
// Removing stops where there are none (a uniform color) changes nothing either
let before = s.doc.project.clone();
set(&mut s, json!({"channel": "baseColor", "colors": []})).unwrap();
assert_eq!(s.doc.project, before);
set(&mut s, json!({"channel": "baseColor", "procedural": "Clouds", "colors": [[2.0, -1.0, 0.5]]})).unwrap();
assert_eq!(ramp(&s, layer), vec![[1.0, 0.0, 0.5]], "stops clamp to 0..1");
}
#[test]
fn a_scalar_channel_drops_stuck_stops_when_its_source_is_set() {
let mut s = session();
let layer = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.4})).unwrap(), "layer");
// Replacing a scalar source must discard color stops hidden by the panel
let stuck = |s: &mut Session| {
let LayerKind::Fill(fill) = &mut s.doc.project.layer_mut(LayerId(layer)).unwrap().kind else { panic!("not a fill layer") };
let pattern = texturecraft_engine::core::Procedural::new(texturecraft_engine::core::ProceduralKind::Clouds);
fill.sources.insert(Channel::Roughness, Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: RGB.to_vec() });
};
let roughness_ramp = |s: &Session| match &s.doc.project.layer(LayerId(layer)).unwrap().kind {
LayerKind::Fill(fill) => fill.source(Channel::Roughness).ramp().to_vec(),
_ => panic!("not a fill layer"),
};
stuck(&mut s);
execute(&mut s, "layer.fill.set", &json!({"layer": layer, "channel": "roughness", "procedural": "Clouds", "scale": 8.0})).unwrap();
assert!(roughness_ramp(&s).is_empty(), "a new pattern on roughness keeps no stops");
stuck(&mut s);
execute(&mut s, "layer.fill.set", &json!({"layer": layer, "channel": "roughness", "colors": []})).unwrap();
assert!(roughness_ramp(&s).is_empty(), "`colors: []` removes them");
}
#[test]
fn removing_stops_from_an_absent_channel_adds_no_channel() {
let mut s = session();
// A content fill effect that supplies only roughness: a default gray base color would cover the layer
let effect = id(execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.7})).unwrap(), "effect");
let before = s.doc.project.clone();
execute(&mut s, "layer.fill.set", &json!({"effect": effect, "channel": "baseColor", "colors": []})).unwrap();
assert_eq!(s.doc.project, before, "no base color source appears on the effect");
// The same on a fill layer that has no base color channel
let layer = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.4})).unwrap(), "layer");
let before = s.doc.project.clone();
execute(&mut s, "layer.fill.set", &json!({"layer": layer, "channel": "baseColor", "colors": []})).unwrap();
assert_eq!(s.doc.project, before, "no base color channel appears on the layer");
// Turning the channel on still adds it
execute(&mut s, "layer.fill.set", &json!({"effect": effect, "channel": "baseColor", "enabled": true})).unwrap();
let (_, x) = s.doc.project.effect(texturecraft_engine::core::LayerId(effect)).unwrap();
match &x.kind {
texturecraft_engine::core::EffectKind::Material(f) => assert!(f.sources.contains_key(&Channel::BaseColor), "enabled adds the channel"),
_ => panic!("not a content fill effect"),
}
}
#[test]
fn gradient_map_true_starts_the_stops_from_the_current_source() {
let mut s = session();
let layer = id(execute(&mut s, "layer.add.fill", &json!({})).unwrap(), "layer");
let set = |s: &mut Session, p: Value| {
let mut p = p;
p["layer"] = json!(layer);
p["channel"] = json!("baseColor");
execute(s, "layer.fill.set", &p)
};
// A uniform color has nothing to start from
assert!(set(&mut s, json!({"gradientMap": true})).is_err());
// A procedural starts at low, halfway and high, so its look holds
set(&mut s, json!({"procedural": "Clouds", "low": [0.0, 0.25, 0.5], "high": [1.0, 0.75, 0.5]})).unwrap();
set(&mut s, json!({"gradientMap": true})).unwrap();
assert_eq!(ramp(&s, layer), vec![[0.0, 0.25, 0.5], [0.5; 3], [1.0, 0.75, 0.5]]);
// Stops already there stay
set(&mut s, json!({"colors": RGB})).unwrap();
set(&mut s, json!({"gradientMap": true})).unwrap();
assert_eq!(ramp(&s, layer), RGB.to_vec());
// Set together with a new pattern, the stops stay
set(&mut s, json!({"procedural": "Voronoi", "gradientMap": true})).unwrap();
assert_eq!(ramp(&s, layer), RGB.to_vec());
// It cannot go with `colors`, and it undoes in one step
assert!(set(&mut s, json!({"gradientMap": true, "colors": RGB})).is_err());
set(&mut s, json!({"colors": []})).unwrap();
set(&mut s, json!({"gradientMap": true})).unwrap();
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!(ramp(&s, layer).is_empty());
// An anchor starts at black, gray and white
execute(&mut s, "layer.add.fill", &json!({})).unwrap();
let anchor = id(execute(&mut s, "effect.add.anchor", &json!({})).unwrap(), "effect");
let top = id(execute(&mut s, "layer.add.fill", &json!({})).unwrap(), "layer");
execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "anchor": anchor})).unwrap();
execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "gradientMap": true})).unwrap();
assert_eq!(ramp(&s, top), vec![[0.0; 3], [0.5; 3], [1.0; 3]]);
// A scalar channel has no stops
assert!(execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "roughness", "gradientMap": true})).is_err());
}
@@ -0,0 +1,525 @@
//! Several selected layers, as in the reference app: Shift+click selects a range of rows,
//! Ctrl/Cmd+click adds or takes out one layer, and remove, duplicate, group, visibility and move
//! act on every selected layer in one undo step.
use serde_json::{Value, json};
use texturecraft_engine::core::{LayerId, LayerKind};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::layer_selection::stack_rows;
use texturecraft_engine::{Session, execute};
fn session() -> Session {
Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap()
}
fn id(v: Value, key: &str) -> LayerId {
LayerId(v[key].as_u64().unwrap())
}
fn add(s: &mut Session, name: &str) -> LayerId {
id(execute(s, "layer.add.paint", &json!({ "name": name })).unwrap(), "layer")
}
/// Paint layers A (bottom) to D (top) on texture set 0, D selected.
fn four(s: &mut Session) -> [LayerId; 4] {
execute(s, "textureSet.select", &json!({"ts": 0})).unwrap();
[add(s, "A"), add(s, "B"), add(s, "C"), add(s, "D")]
}
/// The names of set 0's rows from the top (folder contents included).
fn rows(s: &Session) -> Vec<String> {
stack_rows(&s.doc.project, 0, false).iter().map(|id| s.doc.project.layer(*id).unwrap().name.clone()).collect()
}
fn names(s: &Session, ids: &[LayerId]) -> Vec<String> {
ids.iter().map(|id| s.doc.project.layer(*id).unwrap().name.clone()).collect()
}
fn selected(s: &Session) -> Vec<String> {
names(s, &s.selected_layers())
}
fn click(s: &mut Session, layer: LayerId, how: &str) {
let params = match how {
"shift" => json!({"layer": layer.0, "range": true}),
"ctrl" => json!({"layer": layer.0, "toggle": true}),
_ => json!({"layer": layer.0}),
};
execute(s, "layer.select", &params).unwrap();
}
#[test]
fn shift_click_selects_the_rows_from_the_last_clicked_layer() {
let mut s = session();
let [a, b, _, d] = four(&mut s);
click(&mut s, b, "plain");
click(&mut s, d, "shift");
assert_eq!(selected(&s), ["D", "C", "B"]);
assert_eq!(s.selected_layer(), Some(d), "the clicked layer is the active one");
// The range still starts at B, not at the active D
click(&mut s, a, "shift");
assert_eq!(selected(&s), ["B", "A"]);
assert_eq!(s.selected_layer(), Some(a));
assert_eq!(texturecraft_engine::inspect::session(&s)["selectedLayers"], json!([b.0, a.0]));
// A plain click selects one layer again
click(&mut s, d, "plain");
assert_eq!(selected(&s), ["D"]);
}
#[test]
fn ctrl_click_adds_and_takes_out_one_layer() {
let mut s = session();
let [a, _, c, _] = four(&mut s);
click(&mut s, a, "plain");
click(&mut s, c, "ctrl");
assert_eq!(selected(&s), ["C", "A"]);
assert_eq!(s.selected_layer(), Some(c));
click(&mut s, c, "ctrl");
assert_eq!(selected(&s), ["A"], "a second Ctrl+click takes the layer out");
assert_eq!(s.selected_layer(), Some(a), "the remaining layer becomes the active one");
click(&mut s, a, "ctrl");
assert!(selected(&s).is_empty(), "Ctrl+click on the only selected layer leaves an empty selection");
assert_eq!(s.selected_layer(), None);
// The next Shift+click has no anchor and starts over at the clicked layer
click(&mut s, c, "shift");
assert_eq!(selected(&s), ["C"]);
click(&mut s, a, "ctrl");
assert_eq!(selected(&s), ["C", "A"]);
}
#[test]
fn ctrl_click_on_another_selected_layer_keeps_the_active_one_and_the_range_start() {
let mut s = session();
let [a, b, c, d] = four(&mut s);
click(&mut s, b, "plain");
click(&mut s, d, "shift");
click(&mut s, c, "ctrl");
assert_eq!(selected(&s), ["D", "B"]);
assert_eq!(s.selected_layer(), Some(d), "D stays the active layer");
click(&mut s, a, "shift");
assert_eq!(selected(&s), ["B", "A"], "the range still starts at B");
}
#[test]
fn a_range_covers_the_shown_rows_only() {
let mut s = session();
let [a, b, c, d] = four(&mut s);
execute(&mut s, "layer.select", &json!({"layers": [b.0, c.0]})).unwrap();
let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer");
assert_eq!(rows(&s)[..5], ["D", "Folder 1", "C", "B", "A"]);
click(&mut s, d, "plain");
click(&mut s, a, "shift");
assert_eq!(selected(&s), ["D", "Folder 1", "C", "B", "A"], "an open folder's layers are in the range");
if let LayerKind::Group { collapsed, .. } = &mut s.doc.project.layer_mut(folder).unwrap().kind {
*collapsed = true;
}
click(&mut s, d, "plain");
click(&mut s, a, "shift");
assert_eq!(selected(&s), ["D", "Folder 1", "A"], "a collapsed folder's layers are not");
}
#[test]
fn another_selected_layer_ends_the_multiple_selection() {
let mut s = session();
let [a, _, c, _] = four(&mut s);
click(&mut s, a, "plain");
click(&mut s, c, "ctrl");
add(&mut s, "E");
assert_eq!(selected(&s), ["E"], "a new layer is selected alone");
}
#[test]
fn delete_removes_every_selected_layer_in_one_undo_step() {
let mut s = session();
let [a, b, _, d] = four(&mut s);
execute(&mut s, "layer.select", &json!({"layers": [b.0, d.0]})).unwrap();
let depth = s.history_labels().len();
let r = execute(&mut s, "layer.remove", &Value::Null).unwrap();
assert_eq!(r["removed"], json!([d.0, b.0]));
assert_eq!(rows(&s)[..2], ["C", "A"]);
assert_eq!(selected(&s), ["A"], "the layer under the lowest removed one is selected");
assert_eq!(s.selected_layer(), Some(a));
assert_eq!(s.history_labels().len(), depth + 1, "one undo step");
s.undo().unwrap();
assert_eq!(rows(&s)[..4], ["D", "C", "B", "A"]);
}
#[test]
fn a_folder_and_its_own_layer_selected_remove_together() {
let mut s = session();
let [a, b, _, _] = four(&mut s);
let folder = id(execute(&mut s, "layer.group", &json!({"layer": b.0})).unwrap(), "layer");
execute(&mut s, "layer.select", &json!({"layers": [folder.0, b.0, a.0]})).unwrap();
execute(&mut s, "layer.remove", &Value::Null).unwrap();
assert_eq!(rows(&s)[..2], ["D", "C"]);
assert!(s.doc.project.layer(b).is_err() && s.doc.project.layer(a).is_err());
}
#[test]
fn duplicate_puts_the_copies_in_one_block_above_the_topmost_selected_layer() {
let mut s = session();
let [_, b, _, d] = four(&mut s);
execute(&mut s, "layer.select", &json!({"layers": [d.0, b.0], "layer": b.0})).unwrap();
execute(&mut s, "layer.duplicate", &Value::Null).unwrap();
assert_eq!(rows(&s)[..6], ["D copy", "B copy", "D", "C", "B", "A"], "the block sits directly above D, in stack order");
assert_eq!(selected(&s), ["D copy", "B copy"], "the copies are selected");
assert_eq!(names(&s, &[s.selected_layer().unwrap()]), ["B copy"], "the active layer's copy is the active one");
s.undo().unwrap();
assert_eq!(rows(&s)[..4], ["D", "C", "B", "A"]);
}
#[test]
fn duplicate_block_lands_at_the_topmost_layers_level_also_for_a_layer_from_a_folder() {
let mut s = session();
let [a, _, c, _] = four(&mut s);
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer");
execute(&mut s, "layer.move", &json!({"layers": [a.0], "above": folder.0, "inside": true})).unwrap();
assert_eq!(rows(&s)[..5], ["Folder 1", "A", "D", "C", "B"]);
// The topmost selected row is A, inside the folder, so the block goes there
execute(&mut s, "layer.select", &json!({"layers": [c.0, a.0]})).unwrap();
execute(&mut s, "layer.duplicate", &Value::Null).unwrap();
assert_eq!(rows(&s)[..7], ["Folder 1", "A copy", "C copy", "A", "D", "C", "B"]);
assert_eq!(selected(&s), ["A copy", "C copy"], "the copies are the selection");
}
#[test]
fn duplicate_of_a_root_layer_and_a_folder_layer_with_the_root_one_higher() {
let mut s = session();
let [a, b, _, d] = four(&mut s);
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer");
execute(&mut s, "layer.move", &json!({"layers": [a.0], "above": folder.0, "inside": true})).unwrap();
execute(&mut s, "layer.move", &json!({"layers": [folder.0], "above": b.0})).unwrap();
// Rows from the top: D, C, Folder 1 (A), B... select D (root, topmost) and A (in the folder)
assert_eq!(rows(&s)[..5], ["D", "C", "Folder 1", "A", "B"]);
execute(&mut s, "layer.select", &json!({"layers": [d.0, a.0]})).unwrap();
execute(&mut s, "layer.duplicate", &Value::Null).unwrap();
assert_eq!(rows(&s)[..4], ["D copy", "A copy", "D", "C"], "the block is at the root, above D");
}
#[test]
fn group_puts_the_selected_layers_into_one_folder_in_their_order() {
let mut s = session();
let [a, _, c, _] = four(&mut s);
execute(&mut s, "layer.select", &json!({"layers": [a.0, c.0]})).unwrap();
let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer");
assert_eq!(rows(&s)[..5], ["D", "Folder 1", "C", "A", "B"], "the folder takes the top layer's place");
assert_eq!(s.doc.project.layer(folder).unwrap().children(), [a, c], "bottom to top inside the folder");
assert_eq!(s.selected_layers(), [folder]);
s.undo().unwrap();
assert_eq!(rows(&s)[..4], ["D", "C", "B", "A"]);
}
#[test]
fn group_puts_the_folder_at_the_topmost_selected_layer_with_gaps_between() {
let mut s = session();
execute(&mut s, "textureSet.select", &json!({"ts": 0})).unwrap();
let [l1, l2, l3, l4, l5] = ["L1", "L2", "L3", "L4", "L5"].map(|n| add(&mut s, n));
execute(&mut s, "layer.select", &json!({"layers": [l2.0, l4.0]})).unwrap();
let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer");
assert_eq!(rows(&s)[..6], ["L5", "Folder 1", "L4", "L2", "L3", "L1"], "the folder sits where L4 was, L3 stays below it");
assert_eq!(s.doc.project.layer(folder).unwrap().children(), [l2, l4], "L2 stays below L4 inside");
let stack = &s.doc.project.texture_sets[0].stack;
assert_eq!(stack[stack.len() - 4..], [l1, l3, folder, l5], "L5 stays above the folder");
// Same result when the layers are picked in the other order
s.undo().unwrap();
execute(&mut s, "layer.select", &json!({"layers": [l4.0, l2.0]})).unwrap();
execute(&mut s, "layer.group", &Value::Null).unwrap();
assert_eq!(rows(&s)[..6], ["L5", "Folder 1", "L4", "L2", "L3", "L1"]);
}
#[test]
fn group_of_a_layer_inside_a_folder_and_one_outside_keeps_the_topmost_place() {
let mut s = session();
execute(&mut s, "textureSet.select", &json!({"ts": 0})).unwrap();
let [x, y, z] = ["X", "Y", "Z"].map(|n| add(&mut s, n));
let outer = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer");
execute(&mut s, "layer.move", &json!({"layers": [y.0, z.0], "above": outer.0, "inside": true})).unwrap();
// Rows from the top: Folder 1 (Z, Y), X
assert_eq!(rows(&s)[..4], ["Folder 1", "Z", "Y", "X"]);
// The topmost selected layer Z is inside the folder: the new folder replaces it there
execute(&mut s, "layer.select", &json!({"layers": [z.0, x.0]})).unwrap();
let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer");
assert_eq!(rows(&s)[..5], ["Folder 1", "Folder 2", "Z", "X", "Y"]);
assert_eq!(s.doc.project.layer(outer).unwrap().children(), [y, folder], "Z's place in the outer folder");
assert_eq!(s.doc.project.layer(folder).unwrap().children(), [x, z], "X keeps its place below Z");
s.undo().unwrap();
assert_eq!(rows(&s)[..4], ["Folder 1", "Z", "Y", "X"]);
// X is outside and Y inside: Y is the topmost, so the folder appears inside the outer folder
execute(&mut s, "layer.select", &json!({"layers": [x.0, y.0]})).unwrap();
let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer");
assert_eq!(rows(&s)[..5], ["Folder 1", "Z", "Folder 2", "Y", "X"]);
assert_eq!(s.doc.project.texture_sets[0].stack.last(), Some(&outer), "the outer folder stays on top");
assert_eq!(s.doc.project.layer(outer).unwrap().children(), [folder, z]);
assert_eq!(s.doc.project.layer(folder).unwrap().children(), [x, y]);
}
#[test]
fn group_with_the_topmost_layer_at_the_root_takes_the_folder_layer_out_of_its_folder() {
let mut s = session();
execute(&mut s, "textureSet.select", &json!({"ts": 0})).unwrap();
let [_x, fa, fb] = ["X", "Fill A", "Fill B"].map(|n| add(&mut s, n));
let outer = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer");
execute(&mut s, "layer.move", &json!({"layers": [fa.0, fb.0], "above": outer.0, "inside": true})).unwrap();
// Folder 1 (Fill B, Fill A) at the root above X; add Fill 3 above the folder
let f3 = add(&mut s, "Fill 3");
execute(&mut s, "layer.move", &json!({"layers": [f3.0], "above": outer.0})).unwrap();
assert_eq!(rows(&s)[..5], ["Fill 3", "Folder 1", "Fill B", "Fill A", "X"]);
execute(&mut s, "layer.select", &json!({"layers": [f3.0, fa.0]})).unwrap();
let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer");
assert_eq!(rows(&s)[..6], ["Folder 2", "Fill 3", "Fill A", "Folder 1", "Fill B", "X"], "the new folder is at the root slot of Fill 3");
assert_eq!(s.doc.project.layer(folder).unwrap().children(), [fa, f3], "stack order inside: the folder's own layer is lower");
assert_eq!(s.doc.project.layer(outer).unwrap().children(), [fb], "Fill A left its folder");
}
#[test]
fn shift_range_counts_the_folder_row_and_skips_the_layers_of_a_collapsed_folder() {
let mut s = session();
let [a, b, c, d] = four(&mut s);
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer");
execute(&mut s, "layer.move", &json!({"layers": [b.0, c.0], "above": folder.0, "inside": true})).unwrap();
// Rows from the top: Folder 1 (C, B), D, A... move the folder between D and A
execute(&mut s, "layer.move", &json!({"layers": [folder.0], "above": a.0})).unwrap();
assert_eq!(rows(&s)[..5], ["D", "Folder 1", "C", "B", "A"]);
click(&mut s, d, "plain");
click(&mut s, a, "shift");
assert_eq!(selected(&s), ["D", "Folder 1", "C", "B", "A"], "an open folder: the row and its layers");
if let LayerKind::Group { collapsed, .. } = &mut s.doc.project.layer_mut(folder).unwrap().kind {
*collapsed = true;
}
click(&mut s, d, "plain");
click(&mut s, a, "shift");
assert_eq!(selected(&s), ["D", "Folder 1", "A"], "a collapsed folder: the row, not its layers");
}
#[test]
fn select_all_takes_the_folder_rows_and_the_layers_of_open_folders_only() {
let mut s = session();
let [a, b, c, d] = four(&mut s);
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer");
execute(&mut s, "layer.move", &json!({"layers": [a.0, b.0], "above": folder.0, "inside": true})).unwrap();
click(&mut s, c, "plain");
let depth = s.history_labels().len();
// Open folder: the folder row and its layers
let r = execute(&mut s, "layer.select", &json!({"all": true})).unwrap();
let shown = stack_rows(&s.doc.project, 0, true);
assert_eq!(selected(&s)[..5], ["Folder 1", "B", "A", "D", "C"]);
assert_eq!(s.selected_layers(), shown, "every row of the set");
assert_eq!(r["layers"].as_array().unwrap().len(), shown.len());
assert_eq!(s.selected_layer(), Some(c), "the active layer stays");
assert_eq!(s.history_labels().len(), depth, "selecting is no undo step");
// Collapsed folder: the folder row, not its layers
if let LayerKind::Group { collapsed, .. } = &mut s.doc.project.layer_mut(folder).unwrap().kind {
*collapsed = true;
}
execute(&mut s, "layer.select", &json!({"layer": d.0})).unwrap();
execute(&mut s, "layer.select", &json!({"all": true})).unwrap();
assert_eq!(selected(&s)[..3], ["Folder 1", "D", "C"]);
assert!(!s.is_layer_selected(a) && !s.is_layer_selected(b), "the collapsed folder's layers stay unselected");
assert_eq!(s.selected_layer(), Some(d), "the active layer stays when it is picked again");
}
#[test]
fn the_visibility_of_one_layer_leaves_the_other_selected_layers_alone() {
let mut s = session();
let [a, _, c, _] = four(&mut s);
execute(&mut s, "layer.select", &json!({"layers": [a.0, c.0]})).unwrap();
execute(&mut s, "layer.visible", &json!({"layer": c.0})).unwrap();
assert!(!s.doc.project.layer(c).unwrap().visible && s.doc.project.layer(a).unwrap().visible, "only C is hidden");
assert_eq!(s.selected_layers().len(), 2, "the selection stays");
}
#[test]
fn visibility_of_several_layers_follows_the_layer_given_as_lead() {
let mut s = session();
let [a, b, c, _] = four(&mut s);
execute(&mut s, "layer.visible", &json!({"layer": a.0, "visible": false})).unwrap();
// The active layer is C (shown), but the eye of A (hidden) was clicked: all are shown
execute(&mut s, "layer.select", &json!({"layers": [a.0, b.0, c.0], "layer": c.0})).unwrap();
execute(&mut s, "layer.visible", &json!({"layers": [a.0, b.0, c.0], "layer": a.0})).unwrap();
let shown = |s: &Session| [a, b, c].map(|l| s.doc.project.layer(l).unwrap().visible);
assert_eq!(shown(&s), [true; 3], "A was hidden, so all are shown");
}
#[test]
fn visibility_toggles_every_selected_layer_the_way_of_the_active_one() {
let mut s = session();
let [a, b, c, _] = four(&mut s);
execute(&mut s, "layer.visible", &json!({"layer": a.0, "visible": false})).unwrap();
execute(&mut s, "layer.select", &json!({"layers": [a.0, b.0, c.0], "layer": c.0})).unwrap();
let depth = s.history_labels().len();
execute(&mut s, "layer.visible", &Value::Null).unwrap();
let shown = |s: &Session| [a, b, c].map(|l| s.doc.project.layer(l).unwrap().visible);
assert_eq!(shown(&s), [false; 3], "C was shown, so all are hidden");
assert_eq!(s.history_labels().len(), depth + 1, "one undo step");
execute(&mut s, "layer.visible", &json!({"layers": [a.0, b.0], "visible": true})).unwrap();
assert_eq!(shown(&s), [true, true, false]);
s.undo().unwrap();
s.undo().unwrap();
assert_eq!(shown(&s), [false, true, true]);
}
#[test]
fn selected_layers_move_together_keeping_their_order() {
let mut s = session();
let [a, b, c, d] = four(&mut s);
execute(&mut s, "layer.move", &json!({"layers": [a.0, c.0], "above": d.0})).unwrap();
assert_eq!(rows(&s)[..4], ["C", "A", "D", "B"]);
s.undo().unwrap();
assert_eq!(rows(&s)[..4], ["D", "C", "B", "A"]);
// Into a folder
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer");
execute(&mut s, "layer.move", &json!({"layers": [d.0, b.0], "above": folder.0, "inside": true})).unwrap();
assert_eq!(s.doc.project.layer(folder).unwrap().children(), [b, d]);
assert!(execute(&mut s, "layer.move", &json!({"layers": [a.0, c.0], "above": c.0})).is_err(), "not above one of themselves");
}
#[test]
fn selected_layers_moved_to_an_index_keep_their_order() {
for (pair, expected) in [("B", ["C", "D", "B", "A", "Layer 1"]), ("A", ["C", "D", "A", "B", "Layer 1"])] {
let mut s = session();
let [a, b, _, d] = four(&mut s);
let lower = if pair == "A" { a } else { b };
execute(&mut s, "layer.move", &json!({"layers": [d.0, lower.0], "index": 2})).unwrap();
assert_eq!(rows(&s)[..5], expected, "D and {pair} to index 2");
}
}
#[test]
fn extreme_move_deltas_clamp_to_the_stack_ends() {
let mut session = session();
let [_, layer, ..] = four(&mut session);
execute(&mut session, "layer.move", &json!({"layer": layer.0, "delta": i64::MAX})).unwrap();
assert_eq!(rows(&session)[0], "B", "a large positive delta moves to the top");
execute(&mut session, "layer.move", &json!({"layer": layer.0, "delta": i64::MIN})).unwrap();
assert_eq!(rows(&session).last().map(String::as_str), Some("B"), "a large negative delta moves to the bottom");
}
#[test]
fn layers_in_and_out_of_a_folder_dropped_below_the_stack_stay_together_at_its_bottom() {
let mut s = session();
let [_, b, _, d] = four(&mut s);
let folder = id(execute(&mut s, "layer.group", &json!({"layer": b.0})).unwrap(), "layer");
execute(&mut s, "layer.move", &json!({"layers": [d.0, b.0], "index": 0})).unwrap();
assert_eq!(s.doc.project.texture_sets[0].stack[..2], [b, d], "B at the bottom, D right above it");
assert!(s.doc.project.layer(folder).unwrap().children().is_empty(), "B left its folder");
}
#[test]
fn a_move_that_changes_nothing_is_not_an_undo_step() {
let mut s = session();
let [a, b, c, _] = four(&mut s);
let depth = s.history_labels().len();
execute(&mut s, "layer.move", &json!({"layer": b.0, "above": a.0})).unwrap();
execute(&mut s, "layer.move", &json!({"layers": [c.0, b.0], "above": a.0})).unwrap();
assert_eq!(s.history_labels().len(), depth, "B already sits above A, and C above B");
execute(&mut s, "layer.move", &json!({"layer": a.0, "above": c.0})).unwrap();
assert_eq!(s.history_labels().len(), depth + 1);
}
#[test]
fn an_explicit_layer_acts_on_that_layer_only_while_several_are_selected() {
let select = |s: &mut Session, b: LayerId, d: LayerId| execute(s, "layer.select", &json!({"layers": [b.0, d.0]})).unwrap();
let mut s = session();
let [_, b, _, d] = four(&mut s);
select(&mut s, b, d);
execute(&mut s, "layer.remove", &json!({"layer": b.0})).unwrap();
assert_eq!(rows(&s)[..3], ["D", "C", "A"], "remove");
let mut s = session();
let [_, b, _, d] = four(&mut s);
select(&mut s, b, d);
execute(&mut s, "layer.duplicate", &json!({"layer": b.0})).unwrap();
assert_eq!(rows(&s)[..5], ["D", "C", "B copy", "B", "A"], "duplicate");
let mut s = session();
let [_, b, _, d] = four(&mut s);
select(&mut s, b, d);
let folder = id(execute(&mut s, "layer.group", &json!({"layer": b.0})).unwrap(), "layer");
assert_eq!(s.doc.project.layer(folder).unwrap().children(), [b], "group");
let mut s = session();
let [_, b, _, d] = four(&mut s);
select(&mut s, b, d);
execute(&mut s, "layer.visible", &json!({"layer": b.0})).unwrap();
assert!(!s.doc.project.layer(b).unwrap().visible && s.doc.project.layer(d).unwrap().visible, "visible");
}
#[test]
fn undo_and_redo_end_the_multiple_selection() {
let mut s = session();
let [_, b, ..] = four(&mut s);
let e = add(&mut s, "E");
execute(&mut s, "layer.select", &json!({"layers": [b.0, e.0]})).unwrap();
s.undo().unwrap();
s.redo().unwrap();
assert_eq!(selected(&s), ["E"], "E is back alone, B is not picked again");
add(&mut s, "F");
assert_eq!(s.selected_layers().len(), 1);
assert!(!s.is_layer_selected(b));
}
#[test]
fn reselecting_an_earlier_active_layer_does_not_bring_back_its_multiple_selection() {
let mut s = session();
let [_, b, c, d] = four(&mut s);
click(&mut s, c, "plain");
let effect = execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap()["effect"].as_u64().unwrap();
execute(&mut s, "effect.copy", &json!({ "effect": effect })).unwrap();
execute(&mut s, "layer.select", &json!({"layers": [b.0, d.0], "layer": d.0})).unwrap();
add(&mut s, "E");
// Pasting the effect onto D selects D again, alone
execute(&mut s, "effect.paste", &json!({"layer": d.0})).unwrap();
assert_eq!(selected(&s), ["D"]);
}
#[test]
fn bad_layer_lists_are_errors() {
let mut s = session();
let [a, ..] = four(&mut s);
let other = id(execute(&mut s, "textureSet.select", &json!({"ts": 1})).and_then(|_| execute(&mut s, "layer.add.paint", &Value::Null)).unwrap(), "layer");
for command in ["layer.select", "layer.remove", "layer.duplicate", "layer.group", "layer.visible", "layer.move"] {
for layers in [json!("x"), json!([]), json!([u64::MAX]), json!([a.0, other.0]), json!([a.0, "x"])] {
assert!(execute(&mut s, command, &json!({"layers": layers, "above": null})).is_err(), "{command} {layers}");
}
}
assert!(execute(&mut s, "layer.select", &json!({"layers": [a.0], "layer": other.0})).is_err(), "the active layer must be listed");
}
#[test]
fn moving_layers_into_a_folder_in_another_set_preserves_the_document() {
let mut s = texturecraft_engine::sample_session(128, 64).unwrap();
let source = s.doc.project.texture_sets[0].stack[0];
execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap();
let folder = id(execute(&mut s, "layer.add.group", &json!({})).unwrap(), "layer");
let before = s.doc.project.clone();
let history = s.history_labels();
for params in [json!({"layer": source.0, "above": folder.0, "inside": true}), json!({"layers": [source.0], "above": folder.0, "inside": true})] {
assert!(execute(&mut s, "layer.move", &params).is_err());
assert_eq!(s.doc.project, before);
assert_eq!(s.history_labels(), history);
}
}
+11
View File
@@ -6,14 +6,21 @@ mod bake_checks;
mod bake_resolution;
mod bake_settings;
mod bake_tiles;
mod brush_material;
mod closed_session;
mod color_selection;
mod content_effects;
mod export_colour_space;
mod filter_swap;
mod filters;
mod frame_selection;
mod generator_inputs;
mod gradient_map;
mod high_poly_missed;
mod instances;
mod layer_multi_select;
mod mask_clone_smudge;
mod mask_export;
mod materialcraft_link;
mod materialx;
mod materialx_import;
@@ -26,10 +33,14 @@ mod perf;
mod polygon_fill;
mod project_recovery;
mod sample;
mod solo;
mod thumbs;
mod tile_generator;
mod tool_availability;
mod tool_settings;
mod tools;
mod udim;
mod user_smart_mask;
mod uv_strokes;
mod symmetry;
+158
View File
@@ -0,0 +1,158 @@
//! Clone and Smudge strokes on a layer mask read and write the mask's own values
use serde_json::json;
use texturecraft_engine::core::Channel;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
const SIZE: u32 = 256;
/// A paint layer with a black mask selected, a 2D-view brush of about 13 texels radius
fn session_on_mask() -> (Session, u64) {
let mut session = Session::new_project("mask", primitives::plane(2.0, 4), "builtin:plane", None, SIZE).unwrap();
session.update();
let layer = execute(&mut session, "layer.add.paint", &json!({})).unwrap()["layer"].as_u64().unwrap();
execute(&mut session, "mask.add.black", &json!({"layer": layer})).unwrap();
execute(&mut session, "layer.select", &json!({"layer": layer, "target": "mask"})).unwrap();
execute(&mut session, "tool.brush", &json!({"size": 10, "hardness": 100, "spacing": 10})).unwrap();
execute(&mut session, "tool.material", &json!({"maskValue": 1.0})).unwrap();
(session, layer)
}
fn paint_white_blob(session: &mut Session, uv: [f32; 2]) {
execute(session, "tool.paint", &serde_json::Value::Null).unwrap();
execute(session, "tool.strokeUv", &json!({"points": [uv, uv]})).unwrap();
}
fn mask_at(session: &Session, layer: u64, uv: [f32; 2]) -> f32 {
let texel = ((uv[0] * SIZE as f32) as u32, (uv[1] * SIZE as f32) as u32);
session.mask_at(texturecraft_engine::core::LayerId(layer), &[texel]).unwrap()[0]
}
/// A stroke of `tool` that changes the mask next to the white blob at u = 0.25: clone copies the
/// blob to u = 0.75, smudge drags it to the right
fn stroke_with(session: &mut Session, tool: &str) {
execute(session, tool, &serde_json::Value::Null).unwrap();
execute(session, "tool.cloneSource", &json!({"uv": [0.25, 0.5]})).unwrap();
let points = if tool == "tool.clone" { json!([[0.75, 0.5], [0.75, 0.5]]) } else { json!([[0.25, 0.5], [0.3, 0.5], [0.35, 0.5], [0.4, 0.5], [0.45, 0.5]]) };
execute(session, "tool.strokeUv", &json!({"points": points})).unwrap();
}
/// Mask values at probes inside the blob, where smudge drags it and where clone copies it
const PROBES: [[f32; 2]; 3] = [[0.25, 0.5], [0.4, 0.5], [0.75, 0.5]];
#[test]
fn clone_on_a_mask_copies_the_mask_values_from_the_source() {
let (mut session, layer) = session_on_mask();
paint_white_blob(&mut session, [0.25, 0.5]);
assert!(mask_at(&session, layer, [0.25, 0.5]) > 0.95);
assert!(mask_at(&session, layer, [0.75, 0.5]) < 0.05);
execute(&mut session, "tool.clone", &serde_json::Value::Null).unwrap();
execute(&mut session, "tool.cloneSource", &json!({"uv": [0.25, 0.5]})).unwrap();
execute(&mut session, "tool.strokeUv", &json!({"points": [[0.75, 0.5], [0.75, 0.5]]})).unwrap();
assert!(mask_at(&session, layer, [0.75, 0.5]) > 0.95, "the white blob is cloned");
assert!(mask_at(&session, layer, [0.75, 0.8]) < 0.05, "only the stroke is painted");
assert!(mask_at(&session, layer, [0.25, 0.5]) > 0.95, "the source stays");
}
#[test]
fn clone_on_a_mask_copies_black_over_white_too() {
let (mut session, layer) = session_on_mask();
paint_white_blob(&mut session, [0.75, 0.5]);
execute(&mut session, "tool.clone", &serde_json::Value::Null).unwrap();
execute(&mut session, "tool.cloneSource", &json!({"uv": [0.25, 0.5]})).unwrap();
execute(&mut session, "tool.strokeUv", &json!({"points": [[0.75, 0.5], [0.75, 0.5]]})).unwrap();
assert!(mask_at(&session, layer, [0.75, 0.5]) < 0.05, "the black source erases the white blob");
}
#[test]
fn smudge_on_a_mask_drags_values_along_the_stroke() {
let (mut session, layer) = session_on_mask();
paint_white_blob(&mut session, [0.25, 0.5]);
assert!(mask_at(&session, layer, [0.4, 0.5]) < 0.05);
execute(&mut session, "tool.smudge", &serde_json::Value::Null).unwrap();
execute(&mut session, "tool.strokeUv", &json!({"points": [[0.25, 0.5], [0.3, 0.5], [0.35, 0.5], [0.4, 0.5], [0.45, 0.5]]})).unwrap();
assert!(mask_at(&session, layer, [0.4, 0.5]) > 0.3, "white is dragged to the right");
assert!(mask_at(&session, layer, [0.4, 0.8]) < 0.05, "nothing beside the stroke");
}
#[test]
fn a_clone_or_smudge_stroke_on_a_mask_leaves_the_channels_alone() {
for tool in ["tool.clone", "tool.smudge"] {
let (mut session, _) = session_on_mask();
paint_white_blob(&mut session, [0.25, 0.5]);
let channels_before = session.doc.pixels.layers.clone();
let colour_before = session.caches[0].composite.value(Channel::BaseColor, 192, 128);
stroke_with(&mut session, tool);
session.update();
assert_eq!(session.doc.pixels.layers.len(), channels_before.len(), "{tool}: no channel image is created");
assert!(session.doc.pixels.layers.keys().all(|key| channels_before.contains_key(key)), "{tool}");
assert_eq!(session.caches[0].composite.value(Channel::BaseColor, 192, 128), colour_before, "{tool}: the composite colour is unchanged");
}
}
#[test]
fn one_undo_restores_the_mask_after_a_clone_or_smudge_stroke() {
for tool in ["tool.clone", "tool.smudge"] {
let (mut session, layer) = session_on_mask();
paint_white_blob(&mut session, [0.25, 0.5]);
let steps = session.history_labels().len();
let before: Vec<f32> = PROBES.iter().map(|uv| mask_at(&session, layer, *uv)).collect();
stroke_with(&mut session, tool);
assert_eq!(session.history_labels().len(), steps + 1, "{tool}: one undo step per stroke");
let after: Vec<f32> = PROBES.iter().map(|uv| mask_at(&session, layer, *uv)).collect();
assert_ne!(before, after, "{tool}: the stroke changed the mask");
session.undo().unwrap();
let restored: Vec<f32> = PROBES.iter().map(|uv| mask_at(&session, layer, *uv)).collect();
assert_eq!(restored, before, "{tool}");
}
}
#[test]
fn clone_works_on_a_folder_mask() {
let mut session = Session::new_project("mask", primitives::plane(2.0, 4), "builtin:plane", None, SIZE).unwrap();
session.update();
let folder = execute(&mut session, "layer.add.group", &json!({})).unwrap()["layer"].as_u64().unwrap();
execute(&mut session, "mask.add.black", &json!({"layer": folder})).unwrap();
execute(&mut session, "layer.select", &json!({"layer": folder, "target": "mask"})).unwrap();
execute(&mut session, "tool.brush", &json!({"size": 10, "hardness": 100, "spacing": 10})).unwrap();
paint_white_blob(&mut session, [0.25, 0.5]);
execute(&mut session, "tool.clone", &serde_json::Value::Null).unwrap();
execute(&mut session, "tool.cloneSource", &json!({"uv": [0.25, 0.5]})).unwrap();
execute(&mut session, "tool.strokeUv", &json!({"points": [[0.75, 0.5], [0.75, 0.5]]})).unwrap();
assert!(mask_at(&session, folder, [0.75, 0.5]) > 0.95, "a folder mask clones too");
}
#[test]
fn clone_from_the_layer_reads_the_mask_on_a_folder_mask_and_a_paint_layer_mask() {
for group in [true, false] {
let mut session = Session::new_project("mask", primitives::plane(2.0, 4), "builtin:plane", None, SIZE).unwrap();
session.update();
let command = if group { "layer.add.group" } else { "layer.add.paint" };
let layer = execute(&mut session, command, &json!({})).unwrap()["layer"].as_u64().unwrap();
execute(&mut session, "mask.add.black", &json!({"layer": layer})).unwrap();
execute(&mut session, "layer.select", &json!({"layer": layer, "target": "mask"})).unwrap();
execute(&mut session, "tool.brush", &json!({"size": 10, "hardness": 100, "spacing": 10, "cloneSource": "layer"})).unwrap();
paint_white_blob(&mut session, [0.25, 0.5]);
execute(&mut session, "tool.clone", &serde_json::Value::Null).unwrap();
execute(&mut session, "tool.cloneSource", &json!({"uv": [0.25, 0.5]})).unwrap();
execute(&mut session, "tool.strokeUv", &json!({"points": [[0.75, 0.5], [0.75, 0.5]]})).unwrap();
assert!(mask_at(&session, layer, [0.75, 0.5]) > 0.95, "group {group}");
}
}
+146
View File
@@ -0,0 +1,146 @@
//! `mask.export` and `Session::mask_bitmaps`: the evaluated mask as a bitmap at the texture
//! set's resolution, oriented like the exported textures.
use std::path::PathBuf;
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, LayerId};
use texturecraft_engine::geom::{NO_TRI, primitives};
use texturecraft_engine::{Session, execute};
/// A new folder for one test's files.
fn temp_dir(test: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("texturecraft-mask-export-{test}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// A session of `mesh` with a fill layer whose mask is `value` wherever the mesh covers the texture.
fn session_with_mask(mesh: texturecraft_engine::geom::Mesh, name: &str, resolution: u32, value: f32) -> (Session, LayerId) {
let mut s = Session::new_project("t", mesh, name, None, resolution).unwrap();
let layer = LayerId(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()["layer"].as_u64().unwrap());
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
execute(&mut s, "effect.add.fill", &json!({"value": value})).unwrap();
s.update();
(s, layer)
}
fn covered(s: &Session, x: u32, y: u32) -> bool {
let g = &s.caches[0].gbuf;
g.tri[(y * g.width + x) as usize] != NO_TRI
}
#[test]
fn the_bitmap_is_the_mask_the_composite_is_drawn_with_in_the_same_orientation() {
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap();
let layer = LayerId(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()["layer"].as_u64().unwrap());
// A white layer gives output = base + (1 - base) * mask, so its mask can be recovered
execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": false})).unwrap();
s.update();
let base: Vec<f32> = (0..256 * 256).map(|i| s.caches[0].composite.value(Channel::BaseColor, i % 256, i / 256)[0]).collect();
execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": true})).unwrap();
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
execute(&mut s, "effect.add.fill", &json!({"procedural": "clouds", "seed": 3})).unwrap();
s.update();
let bitmaps = s.mask_bitmaps(layer, true).unwrap();
assert_eq!(bitmaps.len(), 1, "a classic set gives one bitmap");
let bitmap = &bitmaps[0];
assert_eq!((bitmap.tile, bitmap.width, bitmap.height), (None, 256, 256));
assert_eq!(bitmap.values.len(), 256 * 256);
let (mut covered_texels, mut distinct) = (0, std::collections::BTreeSet::new());
for y in 0..256u32 {
for x in 0..256u32 {
let value = bitmap.values[(y * 256 + x) as usize];
if !covered(&s, x, y) {
assert_eq!(value, 0.0, "uncovered texel ({x}, {y}) is black");
continue;
}
covered_texels += 1;
distinct.insert((value * 100.0) as u32);
let base = base[(y * 256 + x) as usize];
let shown = s.caches[0].composite.value(Channel::BaseColor, x, y)[0];
assert!((base + (1.0 - base) * value - shown).abs() < 3e-3, "texel ({x}, {y}): mask {value} does not give the composite {shown} over {base}");
}
}
assert!(covered_texels > 1000, "the mesh covers part of the texture");
assert!(distinct.len() > 20, "the mask varies across the texture, so a mirrored bitmap would not match the composite");
}
#[test]
fn inverting_changes_the_bitmap_and_a_switched_off_or_missing_mask_is_an_error() {
let (mut s, layer) = session_with_mask(primitives::material_ball(), "builtin:material_ball", 128, 0.25);
execute(&mut s, "mask.invert", &json!({"layer": layer.0})).unwrap();
let bitmap = s.mask_bitmaps(layer, false).unwrap().remove(0);
let (x, y) = (0..128 * 128).map(|i| (i % 128, i / 128)).find(|&(x, y)| covered(&s, x, y)).unwrap();
assert!((bitmap.values[(y * 128 + x) as usize] - 0.75).abs() < 1e-3, "inverting 0.25 gives 0.75");
execute(&mut s, "mask.toggle", &json!({"layer": layer.0, "enabled": false})).unwrap();
assert!(s.mask_bitmaps(layer, false).is_err(), "a switched-off mask has nothing to export");
execute(&mut s, "mask.remove", &json!({"layer": layer.0})).unwrap();
assert!(s.mask_bitmaps(layer, false).is_err(), "so has a layer without a mask");
}
#[test]
fn mask_export_writes_a_16_bit_gray_png() {
let (mut s, layer) = session_with_mask(primitives::material_ball(), "builtin:material_ball", 128, 0.5);
let dir = temp_dir("png");
let path = dir.join("ball_mask.png");
let done = execute(&mut s, "mask.export", &json!({"layer": layer.0, "path": path.display().to_string()})).unwrap();
assert_eq!(done["files"], json!([path.display().to_string()]));
let image = image::open(&path).unwrap();
assert!(matches!(image, image::DynamicImage::ImageLuma16(_)), "16-bit grayscale, got {:?}", image.color());
let gray = image.into_luma16();
assert_eq!(gray.dimensions(), (128, 128));
let expected = s.mask_bitmaps(layer, true).unwrap().remove(0).gray16();
assert_eq!(gray.as_raw(), &expected, "the file holds the bitmap, top row first");
// 0.5 is a level 8-bit files cannot hold exactly
assert!(gray.pixels().any(|p| p.0[0] == 32768), "the 16-bit level of 0.5");
// The extension is added, and the layer defaults to the selected one
let done = execute(&mut s, "mask.export", &json!({"path": dir.join("other").display().to_string()})).unwrap();
assert_eq!(done["files"], json!([dir.join("other.png").display().to_string()]));
assert!(dir.join("other.png").exists());
assert!(execute(&mut s, "mask.export", &json!({"layer": layer.0})).is_err(), "a path is required");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_tiled_set_exports_one_file_per_tile_at_each_tiles_size() {
let (mut s, layer) = session_with_mask(primitives::udim_plane(), "builtin:udim_plane", 256, 0.5);
execute(&mut s, "textureSet.tile.resolution", &json!({"ts": 0, "tile": 1002, "resolution": 128})).unwrap();
s.update();
let (width, height) = s.caches[0].size;
assert_eq!((width, height), (512, 256), "two blocks of the larger tile's size");
let bitmaps = s.mask_bitmaps(layer, true).unwrap();
assert_eq!(bitmaps.iter().map(|b| (b.tile, b.width, b.height)).collect::<Vec<_>>(), [(Some(1001), 256, 256), (Some(1002), 128, 128)]);
// The smaller tile fills the top-left corner of its block
for (bitmap, block_x) in bitmaps.iter().zip([0, 256]) {
for y in 0..bitmap.height {
for x in 0..bitmap.width {
let expected = if covered(&s, block_x + x, y) { 0.5 } else { 0.0 };
let value = bitmap.values[(y * bitmap.width + x) as usize];
assert!((value - expected).abs() < 1e-3, "tile {:?} texel ({x}, {y}): {value}", bitmap.tile);
}
}
}
assert!(bitmaps.iter().all(|b| b.values.iter().any(|v| *v > 0.4)), "both tiles have mask");
let atlas = s.mask_bitmaps(layer, false).unwrap();
assert_eq!(atlas.len(), 1);
assert_eq!((atlas[0].tile, atlas[0].width, atlas[0].height), (None, 512, 256), "the clipboard copy is the whole atlas");
let dir = temp_dir("tiles");
let path = dir.join("plane_mask.png");
let done = execute(&mut s, "mask.export", &json!({"layer": layer.0, "path": path.display().to_string()})).unwrap();
assert_eq!(done["files"], json!([dir.join("plane_mask.1001.png").display().to_string(), dir.join("plane_mask.1002.png").display().to_string()]));
assert_eq!(image::open(dir.join("plane_mask.1001.png")).unwrap().into_luma16().dimensions(), (256, 256));
assert_eq!(image::open(dir.join("plane_mask.1002.png")).unwrap().into_luma16().dimensions(), (128, 128));
let _ = std::fs::remove_dir_all(dir);
}
+297 -6
View File
@@ -3,7 +3,7 @@
//! maps from images and fill projection transforms, through engine commands.
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, EffectKind, Filter, LayerId, LayerKind, Projection};
use texturecraft_engine::core::{Channel, Decal, EffectKind, Filter, LayerId, LayerKind, Projection, Source};
use texturecraft_engine::geom::NO_TRI;
use texturecraft_engine::geom::glam::Vec2;
use texturecraft_engine::geom::primitives;
@@ -171,7 +171,8 @@ fn solo_keeps_one_material_channel() {
#[test]
fn decals_project_an_image_from_a_frame_placed_on_the_surface() {
let mut s = session();
// A red disc on a transparent background.
// A red disc on a transparent background
let name = s
.import_resource_bytes("logo.png", png(32, 32, |x, y| if (x as i32 - 16).pow(2) + (y as i32 - 16).pow(2) < 196 { [255, 0, 0, 255] } else { [0; 4] }))
.unwrap();
@@ -184,9 +185,11 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() {
assert!(matches!(f.projection, Projection::Decal(_)));
assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the decal shows where it was placed");
assert!(!red(at(&mut s, Channel::BaseColor, 120.0, 200.0)), "and only there");
// The image's transparent corners leave the surface as it was.
// The image's transparent corners leave the surface as it was
assert!(!red(at(&mut s, Channel::BaseColor, 200.0 + 30.0, 200.0 - 30.0)));
// Bigger, then moved along its plane, then re-placed with a click.
// Bigger, then moved along its plane, then re-placed with a click
execute(&mut s, "layer.decal.set", &json!({"size": 1.2})).unwrap();
assert!(red(at(&mut s, Channel::BaseColor, 160.0, 200.0)));
execute(&mut s, "layer.decal.set", &json!({"size": 0.4, "offset": [0.6, 0.0], "rotation": 45})).unwrap();
@@ -196,7 +199,8 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() {
assert!(red(at(&mut s, Channel::BaseColor, 170.0, 180.0)));
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string();
assert!(inspect.contains("Decal projection") && inspect.contains("\"rotation\":45"), "inspect shows the decal");
// Not a decal; one undo step per edit.
// Not a decal; one undo step per edit
let plain = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer");
assert!(execute(&mut s, "layer.decal.set", &json!({"layer": plain.0, "size": 1})).is_err());
execute(&mut s, "edit.undo", &Value::Null).unwrap();
@@ -204,6 +208,106 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() {
assert!(!red(at(&mut s, Channel::BaseColor, 170.0, 180.0)));
}
/// The decal of mask fill effect `effect`
fn effect_decal(s: &Session, effect: LayerId) -> Decal {
let EffectKind::Fill { projection: Projection::Decal(decal), .. } = &s.doc.project.effect(effect).unwrap().1.kind else { panic!("a decal fill effect") };
*decal
}
#[test]
fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() {
let mut s = session();
let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 255, 255, 255])).unwrap();
let added = execute(&mut s, "layer.add.decal", &json!({"image": name, "channel": "mask", "x": 200, "y": 200, "size": 0.5})).unwrap();
let (layer, effect) = (id(added.clone(), "layer"), id(added, "maskEffect"));
let layer_decal = id(execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 200, "y": 200, "size": 0.5})).unwrap(), "layer");
let before = effect_decal(&s, effect);
let steps = s.history_labels().len();
// Only the effect id, with no layer selected
s.selected.clear();
assert!(s.selected_layer().is_none());
let r = execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "size": [0.3, 0.2], "offset": [0.1, -0.05], "rotation": 30, "depth": 0.2})).unwrap();
assert_eq!(r["layer"], json!(layer.0), "the owning layer is reported");
let after = effect_decal(&s, effect);
assert_eq!((after.size, after.offset, after.rotation), ([0.3, 0.2], [0.1, -0.05], 30.0));
assert_eq!(after.center, before.center, "the other fields stay");
assert_eq!(s.history_labels().len(), steps + 1, "one undo step per edit");
// Re-placing with a click
execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "layer": layer.0, "x": 170, "y": 180})).unwrap();
assert_eq!(effect_decal(&s, effect).offset, [0.0, 0.0]);
execute(&mut s, "edit.undo", &Value::Null).unwrap();
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(effect_decal(&s, effect), before, "undo restores the effect's decal");
// The layer decal is untouched by all of it
let LayerKind::Fill(f) = &s.doc.project.layer(layer_decal).unwrap().kind else { panic!("a fill layer") };
assert!(matches!(&f.projection, Projection::Decal(d) if d.size[1] == 0.5 && d.rotation == 0.0));
// Errors: unknown effect, an effect that is not a decal, an effect of another layer
assert!(execute(&mut s, "layer.decal.set", &json!({"effect": 999_999, "size": 1})).is_err());
execute(&mut s, "layer.select", &json!({"layer": layer.0})).unwrap();
let levels = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": "levels"})).unwrap(), "effect");
assert!(execute(&mut s, "layer.decal.set", &json!({"effect": levels.0, "size": 1})).is_err());
assert!(execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "layer": layer_decal.0, "size": 1})).is_err());
assert_eq!(effect_decal(&s, effect), before);
// A new image replaces the effect's source, not a layer channel
let other = s.import_resource_bytes("other.png", png(4, 4, |_, _| [0, 0, 0, 255])).unwrap();
execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "image": other})).unwrap();
assert!(matches!(&s.doc.project.effect(effect).unwrap().1.kind, EffectKind::Fill { source: Source::Image { name, .. }, .. } if *name == other));
}
#[test]
fn decals_keep_the_image_aspect_and_flip_their_image() {
let mut s = session();
// Twice as wide as tall, left half red and right half blue
let name = s.import_resource_bytes("wide.png", png(8, 4, |x, _| if x < 4 { [255, 0, 0, 255] } else { [0, 0, 255, 255] })).unwrap();
let r = execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 200, "y": 200, "size": 0.5})).unwrap();
let layer = id(r.clone(), "layer");
assert_eq!(r["decal"]["size"], json!([1.0, 0.5]), "a new decal follows its image");
assert!(r["decal"].get("flip").is_none(), "nothing flipped saves nothing extra");
let size = |s: &mut Session| {
let LayerKind::Fill(f) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") };
let Projection::Decal(d) = &f.projection else { panic!("a decal") };
(d.size, d.flip)
};
// A pair of sides is taken as given, unless the proportions are kept: then the width wins
execute(&mut s, "layer.decal.set", &json!({"size": [0.6, 0.6]})).unwrap();
assert_eq!(size(&mut s).0, [0.6, 0.6]);
execute(&mut s, "layer.decal.set", &json!({"size": [0.8, 0.8], "keepProportions": true})).unwrap();
assert_eq!(size(&mut s).0, [0.8, 0.4], "the width sets the height by the image's aspect");
execute(&mut s, "layer.decal.set", &json!({"size": 0.2, "keepProportions": true})).unwrap();
assert_eq!(size(&mut s).0, [0.4, 0.2], "a height sets the width");
execute(&mut s, "layer.decal.set", &json!({"size": [0.6, 0.6]})).unwrap();
execute(&mut s, "layer.decal.set", &json!({"keepProportions": true})).unwrap();
assert_eq!(size(&mut s).0, [0.6, 0.3], "turning the lock on fits the height to the width");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(size(&mut s).0, [0.6, 0.6], "one undo step");
// Flip U and V each on their own, kept by later edits, undone one step at a time
execute(&mut s, "layer.decal.set", &json!({"size": [1.0, 0.5]})).unwrap();
assert!(red(at(&mut s, Channel::BaseColor, 190.0, 200.0)) && !red(at(&mut s, Channel::BaseColor, 210.0, 200.0)));
let r = execute(&mut s, "layer.decal.set", &json!({"flipU": true})).unwrap();
assert_eq!(r["decal"]["flip"], json!([true, false]));
assert!(!red(at(&mut s, Channel::BaseColor, 190.0, 200.0)) && red(at(&mut s, Channel::BaseColor, 210.0, 200.0)), "Flip U mirrors the image in its frame");
execute(&mut s, "layer.decal.set", &json!({"flipV": true, "rotation": 10})).unwrap();
assert_eq!(size(&mut s).1, [true, true]);
execute(&mut s, "layer.decal.set", &json!({"flipU": false})).unwrap();
assert_eq!(size(&mut s).1, [false, true], "the other flip stays");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(size(&mut s).1, [true, true]);
// A new image in the same call sets the aspect: a tall one (1:2)
let tall = s.import_resource_bytes("tall.png", png(4, 8, |_, _| [255, 0, 0, 255])).unwrap();
execute(&mut s, "layer.decal.set", &json!({"image": tall, "size": 0.4, "keepProportions": true})).unwrap();
assert_eq!(size(&mut s).0, [0.2, 0.4]);
}
#[test]
fn a_decal_takes_its_up_from_the_params_or_a_rule_that_never_degenerates() {
let mut s = session();
@@ -616,7 +720,8 @@ fn directx_normal_images_flip_green() {
assert!(fill(&mut s, json!({"normalFormat": "sideways"})).is_err());
assert!(fill(&mut s, json!({"image": name, "normalFormat": 1})).is_err(), "not a string");
assert!(fill(&mut s, json!({"value": [0.5, 0.5, 1.0], "normalFormat": "directX"})).is_err(), "not an image");
// Marking an image on a channel that is off leaves it off.
// Marking an image on a channel that is off leaves it off
fill(&mut s, json!({"enabled": false})).unwrap();
fill(&mut s, json!({"normalFormat": "directX"})).unwrap();
assert!(!s.doc.project.layer(layer).unwrap().channels.contains_key(&Channel::Normal));
@@ -626,3 +731,189 @@ fn directx_normal_images_flip_green() {
let old: texturecraft_engine::core::Source = serde_json::from_value(json!({"Image": {"name": "n"}})).unwrap();
assert_eq!(old, texturecraft_engine::core::Source::image("n"));
}
/// Red texels of the cube's -X face (turned away from where the decals are placed) whose position satisfies `inside`
fn red_on_minus_x(s: &mut Session, inside: impl Fn(f32, f32) -> bool) -> usize {
s.update();
let cache = &s.caches[0];
let (w, h) = cache.size;
(0..w * h)
.filter(|&i| {
let Some(surface) = cache.gbuf.surface(&s.mesh, i as usize) else { return false };
surface.nrm.x < -0.99 && inside(surface.pos.y, surface.pos.z) && red(cache.composite.value(Channel::BaseColor, i % w, i / w))
})
.count()
}
fn decal_of(s: &Session, layer: LayerId) -> texturecraft_engine::core::Decal {
let LayerKind::Fill(fill) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") };
let Projection::Decal(decal) = fill.projection else { panic!("a decal") };
decal
}
#[test]
fn a_decal_with_symmetry_also_covers_the_mirrored_side_and_follows_its_edits() {
use texturecraft_engine::core::{DecalFlip, DecalSymmetry};
let mut s = Session::new_project("t", primitives::cube(2.0), "builtin:cube", None, 256).unwrap();
let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 0, 0, 255])).unwrap();
let place = json!({"image": name, "position": [1.0, 0.0, 0.0], "normal": [1.0, 0.0, 0.0], "up": [0.0, 1.0, 0.0], "size": 0.6});
let layer = id(execute(&mut s, "layer.add.decal", &place).unwrap(), "layer");
assert_eq!(decal_of(&s, layer).symmetry, None, "no copy unless asked for");
assert_eq!(red_on_minus_x(&mut s, |_, _| true), 0);
assert!(execute(&mut s, "layer.decal.set", &json!({"symmetry": "w"})).is_err());
assert!(execute(&mut s, "layer.decal.set", &json!({"symmetryFlip": "up"})).is_err());
let depth = s.history_labels().len();
let r = execute(&mut s, "layer.decal.set", &json!({"symmetry": "x", "symmetryFlip": "u"})).unwrap();
assert_eq!(r["decal"]["symmetry"], json!({"axis": 0, "flip": "u"}));
assert_eq!(s.history_labels().len(), depth + 1, "one undo step");
let centered = red_on_minus_x(&mut s, |y, z| y.abs() < 0.2 && z.abs() < 0.2);
assert!(centered > 20, "the mirrored copy shows opposite the decal: {centered}");
// The copy follows the decal when it moves (offset along its up) and when it grows
execute(&mut s, "layer.decal.set", &json!({"offset": [0.0, 0.5]})).unwrap();
assert!(red_on_minus_x(&mut s, |y, _| y > 0.3) > 20, "moved up with the decal");
assert_eq!(red_on_minus_x(&mut s, |y, _| y.abs() < 0.1), 0, "and left the middle");
execute(&mut s, "layer.decal.set", &json!({"size": 1.6})).unwrap();
assert!(red_on_minus_x(&mut s, |y, _| y.abs() < 0.1) > 20, "bigger with the decal");
execute(&mut s, "layer.decal.set", &json!({"size": 0.6})).unwrap();
// A flip alone keeps the axis; off removes the copy
execute(&mut s, "layer.decal.set", &json!({"symmetryFlip": "v"})).unwrap();
assert_eq!(decal_of(&s, layer).symmetry, Some(DecalSymmetry { axis: 0, flip: DecalFlip::V, offset: 0.0 }));
execute(&mut s, "layer.decal.set", &json!({"symmetry": "z"})).unwrap();
assert_eq!(decal_of(&s, layer).symmetry, Some(DecalSymmetry { axis: 2, flip: DecalFlip::V, offset: 0.0 }), "a new axis keeps the flip");
execute(&mut s, "layer.decal.set", &json!({"symmetry": "x"})).unwrap();
// The mirror plane's position is kept across axis changes, stays within the mesh and is saved
let r = execute(&mut s, "layer.decal.set", &json!({"symmetryOffset": 0.5})).unwrap();
assert_eq!(r["decal"]["symmetry"]["offset"], json!(0.5));
assert_eq!(red_on_minus_x(&mut s, |_, _| true), 0, "a plane at x = 0.5 puts the copy out of reach of the -X face");
let r = execute(&mut s, "layer.decal.set", &json!({"symmetryOffset": 9.0})).unwrap();
assert_eq!(r["decal"]["symmetry"]["offset"], json!(1.0), "the cube is 2 wide: at most 1 from its center");
assert_eq!(r["decal"]["symmetry"]["axis"], json!(0), "the axis is kept");
execute(&mut s, "layer.decal.set", &json!({"symmetryOffset": 0.5})).unwrap();
// Saved with the project
let reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
assert_eq!(reopened.doc.project, s.doc.project);
assert_eq!(decal_of(&reopened, layer).symmetry, Some(DecalSymmetry { axis: 0, flip: DecalFlip::V, offset: 0.5 }));
// Ten edits since the copy was asked for: undoing them all leaves the decal as placed
for _ in 0..10 {
execute(&mut s, "edit.undo", &Value::Null).unwrap();
}
assert_eq!(decal_of(&s, layer).symmetry, None);
assert_eq!(red_on_minus_x(&mut s, |_, _| true), 0);
execute(&mut s, "edit.redo", &Value::Null).unwrap();
assert!(red_on_minus_x(&mut s, |_, _| true) > 20, "redo brings the copy back");
execute(&mut s, "layer.decal.set", &json!({"symmetry": "off"})).unwrap();
assert_eq!(decal_of(&s, layer).symmetry, None);
assert_eq!(red_on_minus_x(&mut s, |_, _| true), 0, "off: the other side is bare again");
// A decal can be added with a copy right away
let both = execute(&mut s, "layer.add.decal", &json!({"image": name, "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0], "symmetry": "y"})).unwrap();
assert_eq!(both["decal"]["symmetry"], json!({"axis": 1, "flip": "none"}), "no offset is written while it is 0");
let shifted = execute(
&mut s,
"layer.add.decal",
&json!({"image": name, "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0], "symmetry": "y", "symmetryOffset": -0.4}),
)
.unwrap();
assert!((shifted["decal"]["symmetry"]["offset"].as_f64().unwrap() + 0.4).abs() < 1e-6);
}
/// A decal's up as the projection shows it: the stored up inside the surface plane.
fn plane_up(decal: &Value) -> texturecraft_engine::geom::glam::Vec3 {
use texturecraft_engine::geom::glam::Vec3;
let v = |key: &str| Vec3::new(decal[key][0].as_f64().unwrap() as f32, decal[key][1].as_f64().unwrap() as f32, decal[key][2].as_f64().unwrap() as f32);
let normal = v("normal").normalize();
(v("up") - normal * normal.dot(v("up"))).normalize_or_zero()
}
#[test]
fn a_decal_moved_onto_another_facing_surface_keeps_a_valid_frame_with_the_carried_up() {
use texturecraft_engine::geom::glam::Vec3;
let mut s = Session::new_project("t", primitives::cube(2.0), "builtin:cube", None, 256).unwrap();
s.viewport = Vec2::new(400.0, 400.0);
let name = s.import_resource_bytes("logo.png", png(8, 4, |_, _| [255, 0, 0, 255])).unwrap();
// On the +Z face, its up turned halfway between world X and Y, size and turn set by the user
let place = json!({"image": name, "position": [0.0, 0.0, 1.0], "normal": [0.0, 0.0, 1.0], "up": [1.0, 1.0, 0.0], "size": [0.6, 0.3], "rotation": 25});
let layer = id(execute(&mut s, "layer.add.decal", &place).unwrap(), "layer");
// Onto the +Y face: the up turns with the surface and follows the old up's direction in it
let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": [0.2, 1.0, 0.1], "normal": [0.0, 1.0, 0.0]})).unwrap();
let up = plane_up(&r["decal"]);
assert!((up.length() - 1.0).abs() < 1e-4 && up.dot(Vec3::Y).abs() < 1e-4, "an up inside the +Y face: {up}");
assert!(up.x > 0.5, "the old up's X side stays on the X side: {up}");
assert_eq!(r["decal"]["rotation"], json!(25.0), "the user's turn stays");
assert_eq!(r["decal"]["size"], json!([0.6_f32, 0.3_f32]), "and the size");
// Straight up the face with the old up along the new normal: no degenerate frame, nothing arbitrary
let r =
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": [0.0, 0.0, 1.0], "normal": [0.0, 0.0, 1.0], "up": [0.0, 1.0, 0.0]})).unwrap();
assert_eq!(plane_up(&r["decal"]), Vec3::Y);
let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0]})).unwrap();
assert!((plane_up(&r["decal"]) - Vec3::NEG_Z).length() < 1e-4, "the up that pointed up the +Z face points away over the edge: {:?}", r["decal"]["up"]);
// Onto the opposite face there is no smallest turn: the frame is still valid and follows the camera rule
let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": [0.0, -1.0, 0.0], "normal": [0.0, -1.0, 0.0]})).unwrap();
let up = plane_up(&r["decal"]);
assert!((up.length() - 1.0).abs() < 1e-4 && up.dot(Vec3::Y).abs() < 1e-4, "{up}");
// An explicit up still wins
let r =
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": [1.0, 0.0, 0.0], "normal": [1.0, 0.0, 0.0], "up": [0.0, 0.0, 1.0]})).unwrap();
assert_eq!(plane_up(&r["decal"]), Vec3::Z);
let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "up": [0.0, 1.0, 0.0]})).unwrap();
assert_eq!(plane_up(&r["decal"]), Vec3::Y, "an up without a move too");
}
#[test]
fn a_decal_dragged_over_the_sphere_never_flips_its_up_between_steps() {
use texturecraft_engine::geom::glam::Vec3;
let mut s = session();
let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 0, 0, 255])).unwrap();
let place = json!({"image": name, "position": [0.0, 0.0, 1.0], "normal": [0.0, 0.0, 1.0], "up": [0.0, 1.0, 0.0], "size": 0.3});
let layer = id(execute(&mut s, "layer.add.decal", &place).unwrap(), "layer");
// Over the pole (the old up lies along the normal there) and down the far side, in 5 degree steps
let mut last = Vec3::Y;
for step in 0..=72 {
let angle = (step as f32 * 5.0).to_radians();
let normal = [0.0, angle.sin(), angle.cos()];
let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": normal, "normal": normal, "merge": step > 0})).unwrap();
let up = plane_up(&r["decal"]);
assert!((up.length() - 1.0).abs() < 1e-4, "step {step}: no frame at {normal:?}");
assert!(up.dot(last) > 0.0, "step {step}: up turned from {last} to {up}");
last = up;
}
// The same drag through viewport points (what the 3D view sends), from the middle to the edge
for step in 0..25 {
let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "x": 200.0 + step as f32 * 2.0, "y": 200.0 - step as f32 * 2.0, "merge": true}))
.unwrap();
let up = plane_up(&r["decal"]);
assert!((up.length() - 1.0).abs() < 1e-4 && up.dot(last) > 0.0, "viewport step {step}: {last} to {up}");
last = up;
}
}
#[test]
fn a_saved_decal_with_an_out_of_range_axis_is_repaired_on_load_and_can_be_edited() {
let mut session = session();
let image = session.import_resource_bytes("decal.png", png(4, 4, |_, _| [255; 4])).unwrap();
let layer = id(execute(&mut session, "layer.add.decal", &json!({"image": image, "symmetry": "x"})).unwrap(), "layer");
let LayerKind::Fill(fill) = &mut session.doc.project.layer_mut(layer).unwrap().kind else { panic!("expected fill") };
let Projection::Decal(decal) = &mut fill.projection else { panic!("expected decal") };
decal.symmetry.as_mut().unwrap().axis = u8::MAX;
let bytes = session.to_project_bytes().unwrap();
let mut loaded = Session::from_project_bytes(&bytes).unwrap();
assert_eq!(decal_of(&loaded, layer).symmetry.unwrap().axis, 2);
execute(&mut loaded, "layer.decal.set", &json!({"layer": layer.0, "rotation": 12})).unwrap();
assert_eq!(decal_of(&loaded, layer).symmetry.unwrap().axis, 2);
}
+121
View File
@@ -709,3 +709,124 @@ fn removing_the_final_stored_point_removes_the_path_and_undo_restores_it() {
assert_eq!(session.doc.project, before.project);
assert_eq!(session.doc.pixels.layers, before.pixels.layers);
}
const SQUARE_UV: [[f32; 2]; 4] = [[0.2, 0.2], [0.8, 0.2], [0.8, 0.8], [0.2, 0.8]];
/// A closed path of corner points runs straight along its edges; the smooth one bulges past them
#[test]
fn corner_points_make_a_path_with_straight_edges() {
let mut s = session(wall());
execute(&mut s, "tool.path", &json!({"uvPoints": SQUARE_UV, "closed": true, "commit": true})).unwrap();
assert!(red_uv(&s, 0.5, 0.125), "a smooth closed path bulges outside the square's edge");
assert!(!red_uv(&s, 0.5, 0.2));
let mut s = session(wall());
execute(&mut s, "tool.path", &json!({"uvPoints": SQUARE_UV, "corners": [true, true, true, true], "closed": true, "commit": true})).unwrap();
assert!(red_uv(&s, 0.5, 0.2) && red_uv(&s, 0.8, 0.5) && red_uv(&s, 0.5, 0.8) && red_uv(&s, 0.2, 0.5), "the edges are straight");
assert!(!red_uv(&s, 0.5, 0.125) && !red_uv(&s, 0.875, 0.5), "no bulge past the edges");
// The fill of a corner path is the quadrilateral too
let mut s = session(wall());
execute(&mut s, "tool.path", &json!({"uvPoints": SQUARE_UV, "corners": [true, true, true, true], "closed": true, "fill": true, "commit": true})).unwrap();
assert!(red_uv(&s, 0.5, 0.21) && !red_uv(&s, 0.5, 0.15));
assert!(execute(&mut s, "tool.path", &json!({"corners": [true, 3]})).is_err());
}
#[test]
fn invalid_corner_flags_leave_the_current_curve_unchanged() {
let mut session = session(wall());
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.2], [0.5, 0.8], [0.8, 0.2]], "corners": [true, false, true]})).unwrap();
let before = session.tool.path.clone();
assert!(execute(&mut session, "tool.path", &json!({"uvPoints": SQUARE_UV, "corners": [true, 3]})).is_err());
assert_eq!(session.tool.path, before, "malformed flags leave the curve intact");
assert!(execute(&mut session, "tool.path", &json!({"corners": [true, true, true, true]})).is_err());
assert_eq!(session.tool.path, before, "extra flags cannot outlive their points");
}
/// Toggling a corner repaints the edited path, is one undo step that also restores the pixels, and is saved with the project
#[test]
fn toggling_a_corner_is_one_undo_step_and_is_saved() {
let mut s = session(wall());
let report = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.2], [0.5, 0.8], [0.8, 0.2]], "commit": true})).unwrap();
let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap());
execute(&mut s, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap();
let smooth_pixels = s.doc.pixels.clone();
let history = s.history_labels().len();
assert!(s.paths(effect).unwrap()[0].corners.is_empty());
assert!(execute(&mut s, "path.corner", &json!({"index": 3})).is_err(), "no such point");
assert!(execute(&mut s, "path.corner", &json!({})).is_err(), "no point selected");
let report = execute(&mut s, "path.corner", &json!({"index": 1})).unwrap();
assert_eq!(report["corner"], true);
assert_eq!(s.paths(effect).unwrap()[0].corners, vec![false, true, false]);
assert_ne!(s.doc.pixels.layers, smooth_pixels.layers, "the sharp turn repaints the path");
let corner_pixels = s.doc.pixels.clone();
assert_eq!(s.history_labels().len(), history + 1);
// Saved: the flags survive a project round trip
let saved = serde_json::to_string(&s.doc.project).unwrap();
let loaded: texturecraft_engine::core::Project = serde_json::from_str(&saved).unwrap();
s.doc.project = loaded;
assert_eq!(s.paths(effect).unwrap()[0].corners, vec![false, true, false]);
// One undo returns to the smooth curve and its pixels, one redo to the corner
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!(s.tool.path.corners.is_empty() && !s.tool.path.is_corner(1));
assert!(s.paths(effect).unwrap()[0].corners.is_empty());
assert_eq!(s.doc.pixels.layers, smooth_pixels.layers);
execute(&mut s, "edit.redo", &Value::Null).unwrap();
assert_eq!(s.paths(effect).unwrap()[0].corners, vec![false, true, false]);
assert_eq!(s.doc.pixels.layers, corner_pixels.layers);
// The selected point toggles back to smooth; the stored flags are empty again
s.select_path_point(1);
let report = execute(&mut s, "path.corner", &json!({})).unwrap();
assert_eq!(report["corner"], false);
assert!(s.paths(effect).unwrap()[0].corners.is_empty(), "an all-smooth path is stored like an old one");
assert_eq!(s.doc.pixels.layers, smooth_pixels.layers);
}
/// Inserting and removing points keeps the corner flags on their points
#[test]
fn corner_flags_follow_their_points_when_points_are_inserted_or_removed() {
let mut s = session(wall());
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.2], [0.5, 0.8], [0.8, 0.2]], "corners": [false, true, false]})).unwrap();
s.insert_path_corner(1, Vec3::new(0.35, 0.5, 0.0)).unwrap();
assert_eq!(s.tool.path.corner_flags(), vec![false, true, true, false]);
s.insert_path_point(0, Vec3::new(0.1, 0.1, 0.0)).unwrap();
assert_eq!(s.tool.path.corner_flags(), vec![false, false, true, true, false]);
s.select_path_point(2);
s.remove_selected_path_point();
assert_eq!(s.tool.path.corner_flags(), vec![false, false, true, false]);
s.append_path_point(Vec3::new(0.9, 0.9, 0.0), true).unwrap();
assert_eq!(s.tool.path.corner_flags(), vec![false, false, true, false, false]);
assert!(s.toggle_selected_path_corner(), "the appended point is selected");
assert_eq!(s.tool.path.corner_flags(), vec![false, false, true, false, true]);
// Undo steps through each change with its flags
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(s.tool.path.corner_flags(), vec![false, false, true, false, false]);
}
/// A path saved before corner points existed has no `corners` key: it loads smooth and unchanged
#[test]
fn paths_saved_without_corner_flags_load_smooth() {
let mut s = session(wall());
let report = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.2], [0.5, 0.8], [0.8, 0.2]], "commit": true})).unwrap();
let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap());
let stored = s.paths(effect).unwrap()[0].clone();
let mut json = serde_json::to_value(&stored).unwrap();
assert!(json.get("corners").is_none(), "a smooth path writes the same JSON as before");
json.as_object_mut().unwrap().remove("corners");
let old: texturecraft_engine::core::PathShape = serde_json::from_value(json).unwrap();
assert_eq!(old, stored);
let pixels = s.doc.pixels.clone();
execute(&mut s, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap();
assert!(s.tool.path.corners.is_empty());
assert!(!s.path_live().unwrap(), "a loaded smooth path matches what is stored");
assert_eq!(s.doc.pixels.layers, pixels.layers);
}
+152
View File
@@ -0,0 +1,152 @@
//! Solo: a view-only preview of one layer. The composite shows that layer alone (optionally at
//! full coverage); saving, exporting and the history never see it.
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, LayerId};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, Solo, execute};
fn session() -> Session {
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap();
s.update();
s
}
fn add_fill(s: &mut Session, color: [f32; 3], roughness: f32) -> LayerId {
let r = execute(s, "layer.add.fill", &json!({"color": color, "roughness": roughness})).unwrap();
LayerId(r["layer"].as_u64().unwrap())
}
/// A red fill below a green fill that a black mask hides everywhere, and the green one.
fn masked_stack() -> (Session, LayerId, LayerId) {
let mut s = session();
let red = add_fill(&mut s, [1.0, 0.0, 0.0], 0.2);
let green = add_fill(&mut s, [0.0, 1.0, 0.0], 0.8);
execute(&mut s, "mask.add.black", &json!({"layer": green.0})).unwrap();
s.update();
(s, red, green)
}
/// A texel the mesh covers.
fn covered(s: &Session) -> (u32, u32) {
let g = &s.caches[0].gbuf;
let i = g.tri.iter().position(|t| *t != texturecraft_engine::geom::NO_TRI).unwrap();
(i as u32 % g.width, i as u32 / g.width)
}
fn base(s: &mut Session) -> [f32; 3] {
s.update();
let (x, y) = covered(s);
s.caches[0].composite.value(Channel::BaseColor, x, y)
}
fn close(a: [f32; 3], b: [f32; 3]) -> bool {
(0..3).all(|i| (a[i] - b[i]).abs() < 2e-3)
}
#[test]
fn solo_shows_only_that_layer_and_ignoring_the_mask_shows_it_everywhere() {
let (mut s, red, green) = masked_stack();
assert!(close(base(&mut s), [1.0, 0.0, 0.0]), "the black mask hides the green layer");
s.set_solo(Some(Solo { layer: green, ignore_mask: false }));
assert!(close(base(&mut s), Channel::BaseColor.default_value()), "alone and masked away: nothing is left");
s.set_solo(Some(Solo { layer: green, ignore_mask: true }));
assert!(close(base(&mut s), [0.0, 1.0, 0.0]), "the mask is ignored: the whole material shows");
s.set_solo(Some(Solo { layer: red, ignore_mask: true }));
assert!(close(base(&mut s), [1.0, 0.0, 0.0]), "the other layer alone");
}
#[test]
fn the_solo_composite_equals_the_layer_alone_without_its_mask() {
let (mut s, _, green) = masked_stack();
s.set_solo(Some(Solo { layer: green, ignore_mask: true }));
s.update();
// The same layer in a project of its own, without mask and without the layer below
let mut alone = session();
add_fill(&mut alone, [0.0, 1.0, 0.0], 0.8);
alone.update();
assert!(s.caches[0].composite == alone.caches[0].composite, "every channel, every texel");
}
#[test]
fn the_solo_changes_neither_the_document_nor_the_history_nor_the_saved_file() {
let (mut s, _, green) = masked_stack();
let (project, labels, saved) =
(s.doc.project.clone(), s.history_labels(), Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap().doc.project);
s.set_solo(Some(Solo { layer: green, ignore_mask: true }));
s.update();
assert_eq!(s.doc.project, project);
assert_eq!(s.history_labels(), labels);
assert_eq!(Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap().doc.project, saved, "the file holds every layer and the mask");
}
#[test]
fn exports_hold_the_whole_stack_while_a_layer_is_soloed_and_the_solo_stays() {
let (mut s, _, green) = masked_stack();
let opts = texturecraft_engine::file_cmds::export_options(&s, &json!({"preset": "Document channels + Normal + AO", "format": "png"}), "t").unwrap();
let whole = s.export_files(&[0], &opts).unwrap();
s.set_solo(Some(Solo { layer: green, ignore_mask: true }));
s.update();
let revision = s.caches[0].revision;
let soloed = s.export_files(&[0], &opts).unwrap();
assert_eq!(s.pending_tiles(), 0, "export leaves the viewport cache ready to draw");
assert_eq!(s.caches[0].revision, revision);
assert_eq!(soloed.len(), whole.len());
assert!(soloed.iter().zip(&whole).all(|(a, b)| a.name == b.name && a.bytes == b.bytes), "the files are the whole stack's");
assert_eq!(s.solo, Some(Solo { layer: green, ignore_mask: true }), "the view keeps showing the solo");
assert!(close(base(&mut s), [0.0, 1.0, 0.0]), "and the viewport composite is the solo again");
}
#[test]
fn turning_the_solo_off_restores_the_original_composite() {
let (mut s, _, green) = masked_stack();
let before = s.caches[0].composite.clone();
s.set_solo(Some(Solo { layer: green, ignore_mask: true }));
s.update();
assert!(s.caches[0].composite != before);
s.set_solo(None);
s.update();
assert!(s.caches[0].composite == before);
}
#[test]
fn edits_while_soloed_show_in_the_solo_and_in_the_whole_stack_afterwards() {
let (mut s, red, _) = masked_stack();
s.set_solo(Some(Solo { layer: red, ignore_mask: false }));
s.update();
execute(&mut s, "layer.fill.set", &json!({"layer": red.0, "channel": "baseColor", "color": [0.0, 0.0, 1.0]})).unwrap();
assert!(close(base(&mut s), [0.0, 0.0, 1.0]), "the edited layer, alone");
s.set_solo(None);
assert!(close(base(&mut s), [0.0, 0.0, 1.0]), "the stack still hides the green layer behind its mask: blue shows");
}
#[test]
fn removing_the_soloed_layer_ends_the_solo() {
let (mut s, _, green) = masked_stack();
s.set_solo(Some(Solo { layer: green, ignore_mask: true }));
execute(&mut s, "layer.remove", &json!({"layer": green.0})).unwrap();
s.update();
assert_eq!(s.solo, None);
assert!(close(base(&mut s), [1.0, 0.0, 0.0]), "the whole stack again");
}
#[test]
fn the_view_solo_command_sets_reports_and_ends_the_solo() {
let (mut s, _, green) = masked_stack();
let r = execute(&mut s, "view.solo", &json!({"layer": green.0, "ignoreMask": true})).unwrap();
assert_eq!(r, json!({"layer": green.0, "ignoreMask": true}));
assert_eq!(texturecraft_engine::inspect::session(&s)["solo"], json!({"layer": green.0, "ignoreMask": true}));
// The selected layer is the default
execute(&mut s, "view.solo", &json!({"layer": null})).unwrap();
assert_eq!(s.solo, None);
execute(&mut s, "layer.select", &json!({"layer": green.0})).unwrap();
let r = execute(&mut s, "view.solo", &json!({})).unwrap();
assert_eq!(r, json!({"layer": green.0, "ignoreMask": false}));
assert!(execute(&mut s, "view.solo", &json!({"layer": 999_999})).is_err());
assert_eq!(texturecraft_engine::inspect::session(&s)["solo"]["layer"], json!(green.0));
execute(&mut s, "view.solo", &json!({"layer": null})).unwrap();
assert_eq!(texturecraft_engine::inspect::session(&s)["solo"], Value::Null);
}
+172 -1
View File
@@ -1,6 +1,6 @@
//! Symmetry around a moved plane or axis, driven through engine commands the way agents paint
use serde_json::json;
use serde_json::{Value, json};
use texturecraft_engine::core::Channel;
use texturecraft_engine::geom::glam::{Vec2, Vec3, Vec4};
use texturecraft_engine::geom::{Mesh, primitives};
@@ -281,3 +281,174 @@ fn disabling_symmetry_paints_only_the_source_and_keeps_the_settings() {
assert_eq!(session.tool.brush.symmetry, settings);
}
}
/// Base color of the composite at the surface point under world `point`
fn color_at(session: &Session, point: Vec3) -> [f32; 3] {
let hit = session.pick(screen(session, point), session.viewport).unwrap();
session.caches[0].composite.value(Channel::BaseColor, (hit.uv.x * TEXTURE_SIZE) as u32, (hit.uv.y * TEXTURE_SIZE) as u32)
}
/// A red dab at `x` (and its mirror image with symmetry on), then a smudge stroke from `x` along `step` pixels per sample. Returns the strokes' surface points
fn smudge_a_red_dab(session: &mut Session, symmetry: bool, x: f32, step: f32) -> (Vec3, Vec3) {
execute(session, "tool.brush", &json!({"size": 12, "hardness": 90, "symmetryX": symmetry})).unwrap();
execute(session, "tool.stroke", &json!({"points": [[x, 200.0]]})).unwrap();
session.update();
let (dragged_to, mirrored_to) = (surface(session, x + 35.0 * step, 200.0), surface(session, 400.0 - x - 35.0 * step, 200.0));
execute(session, "tool.smudge", &Value::Null).unwrap();
execute(session, "tool.brush", &json!({"size": 10, "smudgeStrength": 100, "spacing": 5})).unwrap();
let points: Vec<[f32; 2]> = (0..=40).map(|i| [x + i as f32 * step, 200.0]).collect();
execute(session, "tool.stroke", &json!({"points": points})).unwrap();
session.update();
(dragged_to, mirrored_to)
}
#[test]
fn smudge_drags_the_mirrored_spot_equally() {
let mut session = session(primitives::cube(2.0));
let (right, left) = smudge_a_red_dab(&mut session, true, 240.0, 1.0);
assert!(right.x > 0.0 && left.x < 0.0 && (right.x + left.x).abs() < 1e-3, "{right:?} {left:?}");
let (on_source, on_copy) = (color_at(&session, right), color_at(&session, left));
assert!(on_source[0] - on_source[1] > 0.2, "the stroke drags red along +X: {on_source:?}");
for channel in 0..3 {
assert!((on_source[channel] - on_copy[channel]).abs() < 0.1, "the copy drags the same on -X: {on_source:?} vs {on_copy:?}");
}
}
#[test]
fn smudge_without_symmetry_leaves_the_mirrored_spot_alone() {
let mut session = session(primitives::cube(2.0));
let (right, left) = smudge_a_red_dab(&mut session, false, 240.0, 1.0);
let (on_source, on_far_side) = (color_at(&session, right), color_at(&session, left));
assert!(on_source[0] - on_source[1] > 0.2, "the stroke drags red along +X: {on_source:?}");
assert!(on_far_side[0] - on_far_side[1] < 0.05, "nothing on the mirrored spot: {on_far_side:?}");
}
/// Is the composite red at texture coordinate `uv`?
fn red_at_uv(session: &Session, uv: Vec2) -> bool {
let color = session.caches[0].composite.value(Channel::BaseColor, (uv.x * TEXTURE_SIZE) as u32, (uv.y * TEXTURE_SIZE) as u32);
color[0] > 0.85 && color[1] < 0.15
}
/// Texture coordinate of the surface a ray from `from` along `direction` hits first
fn uv_hit(session: &Session, from: Vec3, direction: Vec3) -> Vec2 {
let hit = session.bvh.closest(from, direction, f32::MAX).unwrap();
texturecraft_engine::geom::surface_at(&session.mesh, hit.tri, hit.u, hit.v).unwrap().uv
}
/// A stroke of one dab in the 2D view at `uv`
fn dab_uv(session: &mut Session, uv: Vec2) {
execute(session, "tool.strokeUv", &json!({"points": [[uv.x, uv.y]]})).unwrap();
session.update();
}
#[test]
fn a_2d_dab_paints_its_copy_where_the_3d_stroke_paints_it() {
let brush = json!({"size": 1, "symmetryX": true, "symmetryOffset": [0.25, 0.0, 0.0]});
// Paint one surface point in the 3D view
let mut in_3d = session(wall());
execute(&mut in_3d, "tool.brush", &brush).unwrap();
let hit = in_3d.pick(Vec2::new(300.0, 200.0), in_3d.viewport).unwrap();
execute(&mut in_3d, "tool.stroke", &json!({"points": [[300, 200]]})).unwrap();
in_3d.update();
// Paint its UV in the 2D view
let mut in_2d = session(wall());
execute(&mut in_2d, "tool.brush", &brush).unwrap();
dab_uv(&mut in_2d, hit.uv);
let mirrored = Vec3::new(0.5 - hit.pos.x, hit.pos.y, hit.pos.z);
for (name, session) in [("3D", &in_3d), ("2D", &in_2d)] {
assert!(red_at(session, hit.pos), "the dab in {name}");
assert!(red_at(session, mirrored), "its copy across x = 0.25 in {name}");
assert!(!red_at(session, Vec3::new(-hit.pos.x, hit.pos.y, hit.pos.z)), "nothing across the mesh center in {name}");
}
}
#[test]
fn a_2d_dab_on_the_cube_paints_the_opposite_face() {
let mut session = session(primitives::cube(2.0));
execute(&mut session, "tool.brush", &json!({"size": 1, "symmetryX": true})).unwrap();
let right = uv_hit(&session, Vec3::new(5.0, 0.3, 0.2), Vec3::NEG_X);
dab_uv(&mut session, right);
assert!(red_at_uv(&session, right), "the dab");
assert!(red_at_uv(&session, uv_hit(&session, Vec3::new(-5.0, 0.3, 0.2), Vec3::X)), "its copy on the left face, at the mirrored point");
assert!(!red_at_uv(&session, uv_hit(&session, Vec3::new(-5.0, -0.3, 0.2), Vec3::X)), "not elsewhere on the left face");
assert!(!red_at_uv(&session, uv_hit(&session, Vec3::new(0.3, 5.0, 0.2), Vec3::NEG_Y)), "not on the top face");
}
#[test]
fn a_2d_dab_with_four_radial_copies_paints_three_more() {
let mut session = session(wall());
execute(&mut session, "tool.brush", &json!({"size": 1, "symmetryRadial": 4, "symmetryAxis": "z"})).unwrap();
let hit = session.pick(Vec2::new(290.0, 160.0), session.viewport).unwrap();
dab_uv(&mut session, hit.uv);
let at = hit.pos;
assert!(red_at(&session, at), "the dab");
for (name, point) in
[("a quarter turn", Vec3::new(-at.y, at.x, 0.0)), ("a half turn", Vec3::new(-at.x, -at.y, 0.0)), ("three quarters", Vec3::new(at.y, -at.x, 0.0))]
{
assert!(red_at(&session, point), "the copy {name} around Z");
}
assert!(!red_at(&session, Vec3::new(at.x, -at.y, 0.0)), "no mirrored copy");
let painted = (0..TEXTURE_SIZE as u32).flat_map(|y| (0..TEXTURE_SIZE as u32).map(move |x| (x, y))).filter(|&(x, y)| {
let color = session.caches[0].composite.value(Channel::BaseColor, x, y);
color[0] - color[1] > PAINTED_TINT
});
let mut blobs: Vec<(u32, u32)> = Vec::new();
for (x, y) in painted {
if !blobs.iter().any(|&(bx, by)| bx.abs_diff(x) < 16 && by.abs_diff(y) < 16) {
blobs.push((x, y));
}
}
assert_eq!(blobs.len(), 4, "the dab and three copies, no more");
}
#[test]
fn a_2d_dab_paints_no_copy_with_symmetry_off() {
let mut session = session(wall());
let hit = session.pick(Vec2::new(300.0, 200.0), session.viewport).unwrap();
let mirrored = Vec3::new(-hit.pos.x, hit.pos.y, hit.pos.z);
execute(&mut session, "tool.brush", &json!({"size": 1})).unwrap();
dab_uv(&mut session, hit.uv);
assert!(red_at(&session, hit.pos), "the dab");
assert!(!red_at(&session, mirrored), "no copy without symmetry");
// The toolbar toggle off keeps the settings but paints no copies
execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOn": false})).unwrap();
dab_uv(&mut session, hit.uv);
assert!(!red_at(&session, mirrored), "no copy with the toggle off");
}
#[test]
fn a_2d_smudge_with_symmetry_drags_both_sides_alike_at_the_mirror_plane() {
let mut session = session(wall());
let uv = |session: &Session, x: f32| uv_hit(session, Vec3::new(x, 0.0, 5.0), Vec3::NEG_Z);
let color = |session: &Session, uv: Vec2| session.caches[0].composite.value(Channel::BaseColor, (uv.x * TEXTURE_SIZE) as u32, (uv.y * TEXTURE_SIZE) as u32);
// A red dab next to the mirror plane (and its copy on the other side), then a smudge away from the plane
execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90, "symmetryX": true})).unwrap();
let start = uv(&session, 0.05);
dab_uv(&mut session, start);
execute(&mut session, "tool.smudge", &Value::Null).unwrap();
execute(&mut session, "tool.brush", &json!({"size": 6, "smudgeStrength": 100, "spacing": 5})).unwrap();
let end = uv(&session, 0.4);
let points: Vec<[f32; 2]> = (0..=40).map(|i| start + (end - start) * (i as f32 / 40.0)).map(|p| [p.x, p.y]).collect();
execute(&mut session, "tool.strokeUv", &json!({"points": points})).unwrap();
session.update();
// The copies overlap at the plane; each drags its own trail, so both sides end up mirror images
let dragged = color(&session, uv(&session, 0.2));
assert!(dragged[0] - dragged[1] > 0.1, "the smudge drags red away from the plane: {dragged:?}");
for x in [0.01, 0.03, 0.05, 0.08, 0.12, 0.2, 0.3] {
let (right, left) = (color(&session, uv(&session, x)), color(&session, uv(&session, -x)));
for channel in 0..3 {
assert!((right[channel] - left[channel]).abs() < 0.03, "x = ±{x}: {right:?} vs {left:?}");
}
}
}
+320
View File
@@ -0,0 +1,320 @@
//! The Tile Generator pattern and pattern resolutions through engine commands
use serde_json::{Value, json};
use texturecraft_engine::core::{
Channel, EffectKind, LayerId, LayerKind, Procedural, ProceduralKind, Projection, ResolutionMode, Source, TileGenerator, TileShape,
};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
fn session() -> Session {
Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap()
}
/// A fill layer whose base color reads the Tile Generator, and its id
fn tile_fill(session: &mut Session) -> u64 {
let layer = execute(session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap();
execute(session, "layer.fill.set", &json!({"channel": "baseColor", "procedural": "Tile Generator"})).unwrap();
layer
}
fn base_color_pattern(session: &Session, layer: u64) -> Procedural {
let LayerKind::Fill(fill) = &session.doc.project.layer(LayerId(layer)).unwrap().kind else { panic!("not a fill layer") };
let Source::Procedural { pattern, .. } = fill.source(Channel::BaseColor) else { panic!("the base color is not a pattern") };
pattern
}
fn tile(pattern: &Procedural) -> TileGenerator {
pattern.tile.as_deref().cloned().unwrap()
}
/// A mask fill effect reading a uniform value, on a fresh fill layer's black mask
fn mask_fill(session: &mut Session) -> u64 {
execute(session, "layer.add.fill", &Value::Null).unwrap();
execute(session, "mask.add.black", &Value::Null).unwrap();
execute(session, "effect.add.fill", &json!({"value": 1.0})).unwrap()["effect"].as_u64().unwrap()
}
fn mask_pattern(session: &Session, effect: u64) -> Procedural {
let Some((_, effect)) = session.doc.project.effect(LayerId(effect)) else { panic!("no effect {effect}") };
let EffectKind::Fill { source: Source::Procedural { pattern, .. }, .. } = &effect.kind else { panic!("the mask fill reads no pattern") };
pattern.clone()
}
#[test]
fn a_new_tile_generator_starts_from_the_reference_defaults() {
let mut session = session();
let layer = tile_fill(&mut session);
let pattern = base_color_pattern(&session, layer);
assert_eq!(pattern.kind, ProceduralKind::TileGenerator);
assert_eq!(tile(&pattern), TileGenerator::default());
assert_eq!(pattern.scale, 1.0, "the tile counts set its frequency: the grid covers one repeat of the projection");
}
#[test]
fn tile_settings_alone_edit_the_channels_pattern() {
let mut session = session();
let layer = tile_fill(&mut session);
execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"amount": [4, 2], "shape": "Half bell", "offset": 0.5}})).unwrap();
let tile = tile(&base_color_pattern(&session, layer));
assert_eq!(tile.amount, [4, 2]);
assert_eq!(tile.shape, TileShape::HalfBell, "a menu choice is taken by its label");
assert_eq!(tile.offset, 0.5);
assert_eq!(tile.specific, TileGenerator::default().specific, "settings not named keep their value");
}
#[test]
fn tile_settings_with_a_seed_edit_both() {
let mut session = session();
let layer = tile_fill(&mut session);
execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"amount": [3, 3]}, "seed": 9, "invert": true})).unwrap();
let pattern = base_color_pattern(&session, layer);
assert_eq!(tile(&pattern).amount, [3, 3]);
assert_eq!((pattern.seed, pattern.invert), (9, true), "the seed and invert beside a tile setting are applied, not dropped");
}
#[test]
fn picking_the_tile_generator_again_keeps_its_settings() {
let mut session = session();
let layer = tile_fill(&mut session);
execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"amount": [3, 3]}, "resolution": "custom", "customResolution": 128}))
.unwrap();
// The panel's scale and seed edits send the pattern again with its kind
execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "procedural": "Tile Generator", "seed": 9})).unwrap();
let pattern = base_color_pattern(&session, layer);
assert_eq!(pattern.seed, 9);
assert_eq!(tile(&pattern).amount, [3, 3]);
assert_eq!((pattern.resolution.mode, pattern.resolution.custom), (ResolutionMode::Custom, 128));
}
#[test]
fn hostile_tile_settings_are_brought_into_range() {
let mut session = session();
let layer = tile_fill(&mut session);
execute(
&mut session,
"layer.fill.set",
&json!({"channel": "baseColor", "tile": {"amount": [0, 999], "specific": -5.0, "shapeTiling": 400, "rotation": 450.0, "shapeResolution": [3, 100000]}}),
)
.unwrap();
let tile = tile(&base_color_pattern(&session, layer));
assert_eq!(tile.amount, [1, 64]);
assert_eq!(tile.specific, 0.0);
assert_eq!(tile.shape_tiling, 16);
assert_eq!(tile.rotation, 90.0, "angles wrap around the turn");
assert_eq!(tile.shape_resolution, [256, 4096]);
}
#[test]
fn unknown_or_misplaced_tile_settings_are_errors() {
let mut session = session();
tile_fill(&mut session);
let unknown = execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"colour": 0.5}}));
assert!(unknown.unwrap_err().to_string().contains("colour"), "the unknown setting is named");
let bad_shape = execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"shape": "Hexagon"}}));
assert!(bad_shape.is_err());
execute(&mut session, "layer.fill.set", &json!({"channel": "roughness", "procedural": "Clouds"})).unwrap();
let on_clouds = execute(&mut session, "layer.fill.set", &json!({"channel": "roughness", "tile": {"offset": 0.5}}));
assert!(on_clouds.is_err(), "tile settings go with the Tile Generator only");
let no_pattern = execute(&mut session, "layer.fill.set", &json!({"channel": "metallic", "tile": {"offset": 0.5}}));
assert!(no_pattern.is_err(), "a uniform channel has no pattern to edit");
}
#[test]
fn a_mask_fill_picks_and_edits_a_pattern_with_effect_set() {
let mut session = session();
let effect = mask_fill(&mut session);
execute(&mut session, "effect.set", &json!({"effect": effect, "procedural": "Tile Generator"})).unwrap();
execute(&mut session, "effect.set", &json!({"effect": effect, "tile": {"checkerMask": true}, "seed": 4})).unwrap();
let pattern = mask_pattern(&session, effect);
assert!(tile(&pattern).checker_mask);
assert_eq!(pattern.seed, 4);
execute(&mut session, "effect.set", &json!({"effect": effect, "tileDefaults": true})).unwrap();
assert_eq!(tile(&mask_pattern(&session, effect)), TileGenerator::default(), "Restore defaults puts every tile setting back");
// Only an explicit uniform pick replaces an active pattern
execute(&mut session, "effect.set", &json!({"effect": effect, "value": 0.3})).unwrap();
assert_eq!(mask_pattern(&session, effect).kind, ProceduralKind::TileGenerator);
execute(&mut session, "effect.set", &json!({"effect": effect, "uniform": 0.3})).unwrap();
let Some((_, edited)) = session.doc.project.effect(LayerId(effect)) else { panic!("the mask fill is gone") };
assert!(matches!(&edited.kind, EffectKind::Fill { source: Source::Uniform(value), .. } if *value == [0.3; 3]), "a uniform pick reads the value again");
}
#[test]
fn a_uniform_pick_outranks_pattern_edits_on_a_mask_fill() {
let mut session = session();
let effect = mask_fill(&mut session);
execute(&mut session, "effect.set", &json!({"effect": effect, "procedural": "Tile Generator"})).unwrap();
execute(&mut session, "effect.set", &json!({"effect": effect, "uniform": 0.3, "seed": 4})).unwrap();
let Some((_, edited)) = session.doc.project.effect(LayerId(effect)) else { panic!("the mask fill is gone") };
assert!(matches!(&edited.kind, EffectKind::Fill { source: Source::Uniform(value), .. } if *value == [0.3; 3]), "the fill reads the value, not the pattern");
}
/// A fill effect's `scale` is also its projection's: while it reads a pattern, the pattern takes it
#[test]
fn a_pattern_scale_edit_leaves_the_mask_fills_projection_alone() {
let mut session = session();
let effect = mask_fill(&mut session);
execute(&mut session, "effect.set", &json!({"effect": effect, "procedural": "Tile Generator"})).unwrap();
execute(&mut session, "effect.set", &json!({"effect": effect, "scale": 3.0})).unwrap();
let Some((_, edited)) = session.doc.project.effect(LayerId(effect)) else { panic!("the mask fill is gone") };
let EffectKind::Fill { source: Source::Procedural { pattern, .. }, projection } = &edited.kind else { panic!("the fill reads a pattern") };
assert_eq!(pattern.scale, 3.0);
assert_eq!(*projection, Projection::default(), "the projection keeps its scale");
}
#[test]
fn a_mask_fill_added_with_tile_settings_keeps_them() {
let mut session = session();
execute(&mut session, "layer.add.fill", &Value::Null).unwrap();
execute(&mut session, "mask.add.black", &Value::Null).unwrap();
let added = execute(&mut session, "effect.add.fill", &json!({"procedural": "Tile Generator", "tile": {"amount": [6, 6]}, "resolutionFactor": -2})).unwrap();
let pattern = mask_pattern(&session, added["effect"].as_u64().unwrap());
assert_eq!(tile(&pattern).amount, [6, 6]);
assert_eq!(pattern.resolution.factor, -2);
}
#[test]
fn inspect_reports_the_tile_settings_and_a_patterns_resolution() {
let mut session = session();
tile_fill(&mut session);
execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"amount": [5, 7]}, "resolution": "textureSet"})).unwrap();
let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string();
assert!(inspected.contains("\"amount\":[5,7]"), "the settings are reported: {inspected}");
assert!(inspected.contains("\"randomMask\""), "under the camelCase names the commands take");
assert!(inspected.contains("\"mode\":\"TextureSet\""), "the pattern's resolution is reported");
}
/// Imports a small gray PNG as resource `name` and returns its resource name
fn import_gray(session: &mut Session, name: &str) -> String {
let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255]));
let mut bytes = Vec::new();
image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
session.import_resource_bytes(name, bytes).unwrap()
}
#[test]
fn removing_unused_resources_keeps_the_images_a_tile_generator_reads() {
let mut session = session();
let input = import_gray(&mut session, "vent.png");
let background = import_gray(&mut session, "plate.png");
let unused = import_gray(&mut session, "unused.png");
tile_fill(&mut session);
execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"shape": "Image", "inputs": [input], "backgroundImage": background}}))
.unwrap();
execute(&mut session, "file.removeUnused", &Value::Null).unwrap();
assert!(session.doc.resources.contains_key(&input), "the pattern input is still read");
assert!(session.doc.resources.contains_key(&background), "the background image is still read");
assert!(!session.doc.resources.contains_key(&unused));
}
/// The composited base color of every texel of the texture set
fn base_colors(session: &mut Session) -> Vec<f32> {
session.update();
let composite = &session.caches[0].composite;
let size = composite.resolution;
(0..size * size).map(|texel| composite.value(Channel::BaseColor, texel % size, texel / size)[0]).collect()
}
#[test]
fn the_compositor_draws_a_tile_generators_image_input() {
let mut session = session();
let input = import_gray(&mut session, "plate.png");
tile_fill(&mut session);
// One tile with no gap: the image covers the whole texture
execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"shape": "Image", "inputs": [input], "amount": [1, 1]}})).unwrap();
let colors = base_colors(&mut session);
let mid_gray = colors.iter().filter(|value| (**value - 0.5).abs() < 0.05).count();
assert!(mid_gray > colors.len() / 2, "the image's gray reaches the texture, not an empty shape: {mid_gray} of {}", colors.len());
}
#[test]
fn importing_the_image_a_tile_generator_names_redraws_it() {
let mut session = session();
tile_fill(&mut session);
execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"shape": "Image", "inputs": ["plate.png"], "amount": [1, 1]}})).unwrap();
let before = base_colors(&mut session);
assert_eq!(import_gray(&mut session, "plate.png"), "plate.png");
let after = base_colors(&mut session);
assert_ne!(before, after, "the image that arrived later reaches the texture");
}
#[test]
fn a_coarser_pattern_resolution_changes_the_composite() {
let mut session = session();
tile_fill(&mut session);
let exact = base_colors(&mut session);
execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "resolutionFactor": -3})).unwrap();
let coarse = base_colors(&mut session);
let changed = exact.iter().zip(&coarse).filter(|(exact, coarse)| (**exact - **coarse).abs() > 0.05).count();
assert!(changed > 0, "an eighth of the resolution blurs the bricks' bevels");
}
#[test]
fn a_tile_generator_gradient_map_reads_the_image_input() {
let mut session = session();
let input = import_gray(&mut session, "plate.png");
tile_fill(&mut session);
let colors = [[0.0; 3], [1.0, 0.0, 0.0]];
execute(
&mut session,
"layer.fill.set",
&json!({"channel": "baseColor", "tile": {"shape": "Image", "inputs": [input], "amount": [1, 1]}, "colors": colors}),
)
.unwrap();
let red = base_colors(&mut session);
let mid_red = red.iter().filter(|value| (**value - 0.5).abs() < 0.05).count();
assert!(mid_red > red.len() / 2, "the gradient map recolors the input image's gray: {mid_red} of {}", red.len());
assert_eq!(session.caches[0].composite.value(Channel::BaseColor, 64, 64)[1], 0.0);
}
#[test]
fn a_tile_generator_gradient_map_keeps_the_selected_resolution() {
let mut session = session();
let layer = tile_fill(&mut session);
let colors = [[0.0; 3], [1.0, 0.0, 0.0]];
execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "colors": colors})).unwrap();
let exact = base_colors(&mut session);
execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "resolution": "uvTile", "resolutionFactor": -3})).unwrap();
let coarse = base_colors(&mut session);
let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap();
let row = inspected["layers"].as_array().unwrap().iter().find(|row| row["id"] == layer).unwrap();
let source = &row["fill"]["sources"]["baseColor"];
assert_ne!(exact, coarse, "the gradient map samples the coarser pattern");
assert_eq!(source["colors"], json!(colors));
assert_eq!(source["resolution"]["mode"], "UvTile");
assert_eq!(source["resolution"]["factor"], -3);
assert_eq!(source["tile"]["amount"], json!(TileGenerator::default().amount));
}
@@ -56,16 +56,13 @@ impl Selection {
/// Whether the shelf offers `tool` for this selection
pub(super) fn offers(self, tool: Tool) -> bool {
let reads_content = matches!(tool, Tool::Smudge | Tool::Clone);
match tool {
Tool::ColorPicker => true,
Tool::GeometryMask => !matches!(self, Selection::Nothing | Selection::QuickMaskOverNothing),
_ => match self {
Selection::PaintContent | Selection::PaintSublayer => true,
Selection::PaintSublayerInFill => tool != Tool::Path,
Selection::PaintMask | Selection::FillMask | Selection::FolderMask | Selection::InstanceOwnMask | Selection::PaintSublayerInMask => {
!reads_content
}
Selection::PaintMask | Selection::FillMask | Selection::FolderMask | Selection::InstanceOwnMask | Selection::PaintSublayerInMask => true,
Selection::PathSublayer => tool == Tool::Path,
Selection::QuickMaskOverPaint | Selection::QuickMaskOverFill | Selection::QuickMaskOverNothing => tool != Tool::Path,
_ => false,
+150
View File
@@ -0,0 +1,150 @@
//! Brush, symmetry and other tool settings outlive the project; what belongs to a project does not
use serde_json::json;
use texturecraft_engine::geom::glam::Vec3;
use texturecraft_engine::paint::BrushAlpha;
use texturecraft_engine::{CloneFrom, CloneSource, Session, ToolSettings, execute, sample_session};
fn another_project() -> Session {
sample_session(128, 64).unwrap()
}
fn import_image(session: &mut Session, file: &str) -> String {
let mut png_bytes = Vec::new();
let image = image::RgbaImage::from_fn(4, 4, |_, _| image::Rgba([200, 100, 50, 255]));
image.write_to(&mut std::io::Cursor::new(&mut png_bytes), image::ImageFormat::Png).unwrap();
session.import_resource_bytes(file, png_bytes).unwrap()
}
/// A session with every kind of tool setting changed from its default
fn tuned() -> Session {
let mut session = another_project();
execute(
&mut session,
"tool.brush",
&json!({
"size": 33, "hardness": 80, "flow": 40, "angle": 15, "spacing": 30, "alpha": "star",
"symmetryOn": true, "symmetryX": true, "symmetryY": false, "symmetryZ": true,
"symmetryRadial": 8, "symmetryAxis": "x", "symmetryOffset": [0.1, 0.0, 0.2],
"smudgeStrength": 80, "cloneSource": "layer", "cloneAligned": false,
}),
)
.unwrap();
session.tool.path.closed = true;
session.tool.path.fill = true;
session
}
#[test]
fn opening_another_project_keeps_the_brush_symmetry_and_tool_settings() {
let mut session = tuned();
let before = session.tool.clone();
session.switch_to(another_project());
assert_eq!(session.tool.brush, before.brush);
assert_eq!(session.tool.brush.alpha, BrushAlpha::Star);
assert!(session.tool.brush.symmetry.x && session.tool.brush.symmetry.z && !session.tool.brush.symmetry.y);
assert_eq!(session.tool.smudge_strength, 0.8);
assert_eq!(session.tool.clone_from, CloneFrom::Layer);
assert!(!session.tool.clone_aligned, "the Clone tool's Aligned switch is kept too");
assert!(session.tool.path.closed && session.tool.path.fill);
}
#[test]
fn a_project_loaded_from_a_file_gets_the_tool_settings_too() {
let mut session = tuned();
let before_size = session.tool.brush.size;
let bytes = another_project().to_project_bytes().unwrap();
session.switch_to(Session::from_project_bytes(&bytes).unwrap());
assert_ne!(session.tool.brush.size, another_project().tool.brush.size);
assert_eq!(session.tool.brush.size, before_size);
assert_eq!(session.tool.smudge_strength, 0.8);
}
#[test]
fn what_belongs_to_the_old_project_is_reset() {
let mut session = tuned();
let before_size = session.tool.brush.size;
let image = import_image(&mut session, "stamp.png");
execute(&mut session, "tool.brush", &json!({"alpha": {"image": image.clone()}})).unwrap();
execute(&mut session, "tool.stencil", &json!({"image": image, "scale": 2.0, "rotation": 30, "tile": true, "opacity": 0.9})).unwrap();
session.tool.clone_source = Some(CloneSource { uv: [0.3, 0.4], offset: Some([0.1, 0.1]) });
session.tool.path.push(Vec3::new(1.0, 2.0, 3.0), false);
session.switch_to(another_project());
assert_eq!(session.tool.clone_source, None);
assert_eq!(session.tool.stencil, None);
assert_eq!(session.tool.brush.alpha_image, None);
assert!(session.tool.path.points.is_empty());
// The rest of the brush came along
assert_ne!(session.tool.brush.size, another_project().tool.brush.size);
assert_eq!(session.tool.brush.size, before_size);
}
#[test]
fn the_stencil_placement_carries_over_to_the_next_stencil() {
let mut session = another_project();
let image = import_image(&mut session, "stamp.png");
execute(&mut session, "tool.stencil", &json!({"image": image, "scale": 2.0, "rotation": 30, "tile": true, "opacity": 0.9})).unwrap();
session.switch_to(another_project());
let image = import_image(&mut session, "other.png");
execute(&mut session, "tool.stencil", &json!({"image": image})).unwrap();
let stencil = session.tool.stencil.as_ref().unwrap();
assert_eq!((stencil.scale, stencil.rotation, stencil.tile, stencil.opacity), (2.0, 30.0, true, 0.9));
}
#[test]
fn clearing_the_stencil_keeps_its_placement_for_the_next_one() {
let mut session = another_project();
let image = import_image(&mut session, "stamp.png");
execute(&mut session, "tool.stencil", &json!({"image": image.clone(), "scale": 2.0})).unwrap();
execute(&mut session, "tool.stencil", &json!({"clear": true})).unwrap();
execute(&mut session, "tool.stencil", &json!({"image": image})).unwrap();
assert_eq!(session.tool.stencil.as_ref().unwrap().scale, 2.0);
}
#[test]
fn settings_survive_json_and_apply_to_a_fresh_tool() {
let session = tuned();
let saved = ToolSettings::of(&session.tool);
let loaded: ToolSettings = serde_json::from_str(&serde_json::to_string(&saved).unwrap()).unwrap();
let mut fresh = another_project();
loaded.apply(&mut fresh.tool);
assert_eq!(ToolSettings::of(&fresh.tool), saved);
assert_eq!(fresh.tool.brush.size, session.tool.brush.size);
}
#[test]
fn settings_saved_before_the_clone_aligned_switch_load_with_it_on() {
let mut saved = serde_json::to_value(ToolSettings::of(&tuned().tool)).unwrap();
saved.as_object_mut().unwrap().remove("clone_aligned");
let loaded: ToolSettings = serde_json::from_value(saved).unwrap();
assert!(loaded.clone_aligned);
}
#[test]
fn restored_stencil_and_smudge_settings_use_the_tool_limits() {
let mut session = another_project();
let mut settings = ToolSettings::default();
settings.smudge_strength = 2.0;
settings.stencil.center = [-20.0, 30.0];
settings.stencil.opacity = -1.0;
settings.stencil.scale = 0.0;
settings.stencil.rotation = -15.0;
settings.apply(&mut session.tool);
assert_eq!(session.tool.smudge_strength, 1.0);
let look = session.tool.stencil_look;
assert_eq!((look.center, look.scale, look.opacity, look.rotation), ([-4.0, 4.0], 0.01, 0.0, 345.0));
}
+214 -4
View File
@@ -53,15 +53,93 @@ fn clone_copies_values_from_the_source_offset() {
dab(&mut s, 240.0, 200.0);
let v = color_at(&s, 240.0, 200.0);
assert!(red(v), "cloned red: {v:?}");
// The offset stays for the next strokes: the source moved along with the destination.
// The offset stays for the next strokes: the source moved along with the destination
let off = s.tool.clone_source.unwrap().offset.unwrap();
assert!(off[0].abs() > 0.01, "{off:?}");
// One undo step per clone stroke.
// One undo step per clone stroke
execute(&mut s, "edit.undo", &Value::Null).unwrap();
s.update();
assert!(!red(color_at(&s, 240.0, 200.0)));
}
/// A red dab at (160, 200) as the clone source, the Clone tool selected with a small brush.
fn clone_ready() -> Session {
let mut s = session();
paint_red(&mut s, 20.0);
dab(&mut s, 160.0, 200.0);
execute(&mut s, "tool.clone", &Value::Null).unwrap();
execute(&mut s, "tool.cloneSource", &json!({"x": 160, "y": 200})).unwrap();
execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap();
s
}
#[test]
fn aligned_clone_keeps_the_first_offset_for_later_strokes() {
let mut s = clone_ready();
assert_eq!(execute(&mut s, "tool.brush", &Value::Null).unwrap()["cloneAligned"], true, "aligned by default");
dab(&mut s, 240.0, 200.0);
assert!(red(color_at(&s, 240.0, 200.0)));
// The second stroke reads at the same offset, 40 points left of the first source: nothing red there
dab(&mut s, 200.0, 200.0);
assert!(!red(color_at(&s, 200.0, 200.0)), "aligned: the source moved along");
assert!(s.tool.clone_source.unwrap().offset.is_some());
}
#[test]
fn not_aligned_clone_starts_every_stroke_at_the_source() {
let mut s = clone_ready();
let r = execute(&mut s, "tool.brush", &json!({"cloneAligned": false})).unwrap();
assert_eq!(r["cloneAligned"], false);
dab(&mut s, 240.0, 200.0);
assert!(red(color_at(&s, 240.0, 200.0)), "first stroke copies the source");
assert!(s.tool.clone_source.unwrap().offset.is_none(), "no offset is kept");
dab(&mut s, 200.0, 200.0);
assert!(red(color_at(&s, 200.0, 200.0)), "the second stroke starts at the source again");
}
#[test]
fn switching_the_clone_mode_forgets_the_offset_of_earlier_strokes() {
let mut s = clone_ready();
dab(&mut s, 240.0, 200.0);
assert!(s.tool.clone_source.unwrap().offset.is_some());
execute(&mut s, "tool.brush", &json!({"cloneAligned": false})).unwrap();
execute(&mut s, "tool.brush", &json!({"cloneAligned": true})).unwrap();
assert!(s.tool.clone_source.unwrap().offset.is_none(), "the next aligned stroke fixes a fresh offset");
}
#[test]
fn the_clone_source_is_forgotten_when_another_texture_set_becomes_active() {
let mut s = texturecraft_engine::sample_session(256, 64).unwrap();
execute(&mut s, "tool.clone", &Value::Null).unwrap();
execute(&mut s, "tool.cloneSource", &json!({"uv": [0.3, 0.6]})).unwrap();
// Selecting the active set again keeps it
let active = s.ts();
execute(&mut s, "textureSet.select", &json!({"ts": active})).unwrap();
assert!(s.tool.clone_source.is_some());
execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap();
assert!(s.tool.clone_source.is_none(), "a point of set 0 means nothing in set 1");
assert!(execute(&mut s, "tool.stroke", &json!({"points": [[200, 200]]})).is_err(), "asks for a source again");
// The same through selecting a layer that lives in another set
let other = s.doc.project.texture_sets[0].stack.last().copied().expect("set 0 has a layer");
execute(&mut s, "tool.cloneSource", &json!({"uv": [0.3, 0.6]})).unwrap();
execute(&mut s, "layer.select", &json!({"layer": other.0})).unwrap();
assert_eq!(s.ts(), 0);
assert!(s.tool.clone_source.is_none());
execute(&mut s, "tool.cloneSource", &json!({"uv": [0.3, 0.6]})).unwrap();
execute(&mut s, "layer.select", &json!({"layers": [other.0]})).unwrap();
assert!(s.tool.clone_source.is_some());
let layers = s.doc.project.texture_sets[1].stack.clone();
execute(&mut s, "layer.select", &json!({"layers": layers})).unwrap();
assert_eq!(s.ts(), 1);
assert!(s.tool.clone_source.is_none());
}
#[test]
fn smudge_drags_color_along_the_stroke() {
let mut s = session();
@@ -77,6 +155,21 @@ fn smudge_drags_color_along_the_stroke() {
assert!(after[0] - before[0] > 0.2 && after[1] < before[1], "red dragged right: {before:?} -> {after:?}");
}
#[test]
fn smudge_leaves_a_channel_alone_that_the_material_has_off() {
let mut s = session();
paint_red(&mut s, 12.0);
dab(&mut s, 170.0, 200.0);
let before = color_at(&s, 205.0, 200.0);
execute(&mut s, "tool.material", &json!({"channel": "baseColor", "enabled": false})).unwrap();
execute(&mut s, "tool.smudge", &Value::Null).unwrap();
execute(&mut s, "tool.brush", &json!({"size": 10, "smudgeStrength": 100, "spacing": 5})).unwrap();
let pts: Vec<[f32; 2]> = (0..=40).map(|i| [170.0 + i as f32, 200.0]).collect();
execute(&mut s, "tool.stroke", &json!({"points": pts})).unwrap();
let after = color_at(&s, 205.0, 200.0);
assert!((after[0] - before[0]).abs() < 0.02 && (after[1] - before[1]).abs() < 0.02, "base color not dragged: {before:?} -> {after:?}");
}
#[test]
fn image_alpha_shapes_the_stamp() {
let mut s = session();
@@ -273,7 +366,8 @@ fn stroke_after_undoing_mask_is_paint_stroke() {
s.update();
let undone = execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(undone["undone"], "Paint stroke", "the stroke after undoing the mask was recorded as {}", undone["undone"]);
let layer = s.doc.project.layer(s.selected_layer().unwrap()).unwrap().name.clone();
assert_eq!(undone["undone"], format!("Paint on {layer}"), "the stroke after undoing the mask was recorded as {}", undone["undone"]);
execute(&mut s, "edit.redo", &Value::Null).unwrap();
s.update();
@@ -300,5 +394,121 @@ fn undoing_after_painting_on_instance_source_mask_keeps_mask_target() {
execute(&mut s, "tool.stroke", &json!({"points": [[180, 180], [210, 200]]})).unwrap();
let undone = execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(undone["undone"], "Mask stroke");
let layer = s.doc.project.layer(s.selected_layer().unwrap()).unwrap().name.clone();
assert_eq!(undone["undone"], format!("Paint mask of {layer}"));
}
/// The name of the selected layer
fn selected_name(s: &Session) -> String {
s.doc.project.layer(s.selected_layer().unwrap()).unwrap().name.clone()
}
/// The label of the newest history step
fn last_label(s: &Session) -> String {
s.history_labels().pop().unwrap()
}
#[test]
fn strokes_are_named_by_tool_and_layer() {
let mut s = session();
execute(&mut s, "layer.rename", &json!({"name": "Rust"})).unwrap();
paint_red(&mut s, 20.0);
dab(&mut s, 160.0, 200.0);
assert_eq!(last_label(&s), "Paint on Rust");
execute(&mut s, "tool.clone", &Value::Null).unwrap();
execute(&mut s, "tool.cloneSource", &json!({"x": 160, "y": 200})).unwrap();
dab(&mut s, 240.0, 200.0);
assert_eq!(last_label(&s), "Clone on Rust");
execute(&mut s, "tool.smudge", &Value::Null).unwrap();
execute(&mut s, "tool.brush", &json!({"size": 10, "smudgeStrength": 100, "spacing": 5})).unwrap();
execute(&mut s, "tool.stroke", &json!({"points": [[150, 200], [200, 200], [250, 200]]})).unwrap();
assert_eq!(last_label(&s), "Smudge on Rust");
execute(&mut s, "tool.eraser", &Value::Null).unwrap();
dab(&mut s, 160.0, 200.0);
assert_eq!(last_label(&s), "Erase on Rust");
// Another layer gives another name
execute(&mut s, "layer.add.paint", &Value::Null).unwrap();
execute(&mut s, "layer.rename", &json!({"name": "Dust"})).unwrap();
execute(&mut s, "tool.paint", &Value::Null).unwrap();
dab(&mut s, 160.0, 200.0);
assert_eq!(last_label(&s), format!("Paint on {}", selected_name(&s)));
assert_eq!(selected_name(&s), "Dust");
}
#[test]
fn the_label_template_of_every_tool_is_listed_for_translation() {
use texturecraft_engine::{HISTORY_TEMPLATES, Tool, history_label, stroke_template};
for tool in Tool::ALL {
for on_mask in [false, true] {
let template = stroke_template(tool, on_mask);
assert!(HISTORY_TEMPLATES.contains(&template), "{template} is not in HISTORY_TEMPLATES");
assert!(history_label(template, "Rust").contains("Rust"));
}
}
assert_eq!(history_label("Paint on {layer}", "A {b}"), "Paint on A {b}");
}
/// Texels of base color red along a viewport row
fn red_width(s: &Session, y: f32) -> usize {
(100..300).filter(|x| s.pick(Vec2::new(*x as f32, y), s.viewport).is_some() && red(color_at(s, *x as f32, y))).count()
}
#[test]
fn brush_alpha_parameters_are_set_read_back_and_narrow_the_stamp() {
let mut full_session = session();
paint_red(&mut full_session, 30.0);
dab(&mut full_session, 200.0, 200.0);
let full = red_width(&full_session, 200.0);
assert!(full > 20, "{full}");
let mut s = session();
paint_red(&mut s, 30.0);
let brush = execute(&mut s, "tool.brush", &json!({"alphaSizeX": 50, "alphaRoundness": 0, "alphaContrast": 2.5, "alphaInvert": false})).unwrap();
assert_eq!((brush["alphaSizeX"].as_f64(), brush["alphaSizeY"].as_f64(), brush["alphaRoundness"].as_f64()), (Some(50.0), Some(100.0), Some(0.0)));
assert_eq!((brush["alphaContrast"].as_f64(), brush["alphaInvert"].as_bool()), (Some(2.5), Some(false)));
execute(&mut s, "tool.brush", &json!({"alphaRoundness": 100, "alphaContrast": 1})).unwrap();
dab(&mut s, 200.0, 200.0);
let narrow = red_width(&s, 200.0);
assert!(narrow > 5 && narrow * 10 < full * 7, "half the stamp width: {narrow} of {full}");
// Out-of-range values are clamped, not rejected
let brush = execute(&mut s, "tool.brush", &json!({"alphaSizeX": 0, "alphaContrast": 99})).unwrap();
assert_eq!((brush["alphaSizeX"].as_f64(), brush["alphaContrast"].as_f64()), (Some(5.0), Some(8.0)));
}
#[test]
fn brushes_saved_without_alpha_parameters_load_unchanged() {
use texturecraft_engine::paint::{AlphaParams, BrushSettings};
let mut saved = serde_json::to_value(BrushSettings::default()).unwrap();
assert!(saved.as_object_mut().unwrap().remove("alpha_params").is_some());
let loaded: BrushSettings = serde_json::from_value(saved.clone()).unwrap();
assert_eq!(loaded, BrushSettings::default());
saved["alpha_params"] = json!({"size_x": 0.5, "invert": true});
let partial: BrushSettings = serde_json::from_value(saved).unwrap();
assert_eq!(partial.alpha_params, AlphaParams { size_x: 0.5, invert: true, ..AlphaParams::default() });
}
#[test]
fn solo_keeps_the_document_source_for_clone_and_the_material_picker() {
let mut s = clone_ready();
let layer = s.selected_layer().unwrap();
let empty = execute(&mut s, "layer.add.paint", &json!({})).unwrap()["layer"].as_u64().unwrap();
execute(&mut s, "view.solo", &json!({"layer": empty})).unwrap();
execute(&mut s, "layer.select", &json!({"layer": layer.0})).unwrap();
s.update();
assert!(!red(color_at(&s, 160.0, 200.0)));
let picked = s.color_pick(Vec2::new(160.0, 200.0), s.viewport).unwrap();
assert!(red(picked[&Channel::BaseColor]));
dab(&mut s, 240.0, 200.0);
execute(&mut s, "view.solo", &json!({"layer": null})).unwrap();
s.update();
assert!(red(color_at(&s, 240.0, 200.0)));
}
+210
View File
@@ -0,0 +1,210 @@
//! A layer's mask saved as a user smart mask (`.tcmask`) and applied to other layers and projects.
use serde_json::{Value, json};
use texturecraft_engine::core::{Effect, EffectKind, LayerId, Source};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::smart_masks::SMART_MASK_EXT;
use texturecraft_engine::{Session, execute};
use texturecraft_texel::TileImage;
fn session(resolution: u32) -> Session {
Session::new_project("t", primitives::sphere(1.0, 24, 12), "builtin:sphere", None, resolution).unwrap()
}
fn layer(s: &mut Session) -> LayerId {
LayerId(execute(s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap())
}
/// A mask with a generator, a filter, an image fill and painted pixels. Returns the layer and the image's name.
fn multi_effect_mask(s: &mut Session) -> (LayerId, String) {
let mut png = Vec::new();
image::RgbaImage::from_fn(8, 8, |x, y| image::Rgba([(x * 30) as u8, (y * 30) as u8, 90, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let name = s.import_resource_bytes("stencil.png", png).unwrap();
let id = layer(s);
execute(s, "mask.add.black", &json!({"layer": id.0})).unwrap();
execute(s, "effect.add.generator", &json!({"layer": id.0, "generator": "edgeWear"})).unwrap();
execute(s, "effect.add.filter", &json!({"layer": id.0, "target": "mask", "filter": "invert"})).unwrap();
let fill = execute(s, "effect.add.fill", &json!({"layer": id.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap();
let paint = execute(s, "effect.add.paint", &json!({"layer": id.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap();
let mask = s.doc.project.layer_mut(id).unwrap().mask.as_mut().unwrap();
for effect in &mut mask.effects {
if effect.id.0 == fill {
effect.kind = EffectKind::Fill { source: Source::image(&name), projection: Default::default() };
}
}
let size = s.doc.project.texture_set(0).unwrap().resolution;
let mut pixels = TileImage::new(size, size, 2);
pixels.set(10, 12, &[40000, 65535]);
s.doc.pixels.masks.insert(LayerId(paint), pixels);
(id, name)
}
/// The mask's effects without their ids (those are new in every project).
fn effects(s: &Session, layer: LayerId) -> Vec<Effect> {
s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| Effect { id: LayerId(0), ..effect.clone() }).collect()
}
fn painted(s: &Session, layer: LayerId) -> Vec<[u16; 4]> {
let mask = s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap();
mask.effects.iter().filter(|effect| matches!(effect.kind, EffectKind::Paint)).map(|effect| s.doc.pixels.masks[&effect.id].get(10, 12)).collect()
}
#[test]
fn a_saved_mask_applies_to_another_layer_with_parameters_pixels_and_images() {
let mut s = session(256);
let (source, image) = multi_effect_mask(&mut s);
let bytes = s.smart_mask_bytes(source, "Worn stencil").unwrap();
let other = layer(&mut s);
execute(&mut s, "mask.add.white", &json!({"layer": other.0})).unwrap();
let before = s.doc.project.layers.len();
s.apply_smart_mask_bytes(other, &bytes).unwrap();
assert_eq!(effects(&s, other), effects(&s, source), "every effect keeps its type and parameters");
assert_eq!(painted(&s, other), painted(&s, source), "and the painted pixels");
assert_eq!(s.doc.project.layer(other).unwrap().mask.as_ref().unwrap().background, s.doc.project.layer(source).unwrap().mask.as_ref().unwrap().background);
assert_eq!(s.doc.project.layers.len(), before, "no layer is added");
let ids: Vec<_> = s.doc.project.layer(other).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect();
assert!(ids.iter().all(|id| !s.doc.project.layer(source).unwrap().mask.as_ref().unwrap().effects.iter().any(|e| e.id == *id)), "the effects are new ones");
assert!(s.doc.resources.contains_key(&image));
s.doc.project.validate().unwrap();
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(s.doc.project.layer(other).unwrap().mask.as_ref().unwrap().effects.len(), 0, "one undo step restores the old mask");
}
#[test]
fn a_saved_mask_applies_in_a_fresh_project_of_another_size() {
let mut s = session(256);
let (source, image) = multi_effect_mask(&mut s);
let bytes = s.smart_mask_bytes(source, "Worn stencil").unwrap();
let expected = effects(&s, source);
let mut fresh = session(128);
let target = layer(&mut fresh);
assert!(fresh.doc.resources.is_empty());
fresh.apply_smart_mask_bytes(target, &bytes).unwrap();
assert_eq!(effects(&fresh, target), expected);
assert_eq!(fresh.doc.resources.get(&image), s.doc.resources.get(&image), "the image arrives byte for byte");
assert!(fresh.images.contains_key(&image), "and is decoded for the mask to read");
let mask = fresh.doc.project.layer(target).unwrap().mask.as_ref().unwrap();
let paint = mask.effects.iter().find(|effect| matches!(effect.kind, EffectKind::Paint)).unwrap();
assert_eq!(fresh.doc.pixels.masks[&paint.id].width(), 128, "painted pixels are fitted to the project's size");
fresh.doc.project.validate().unwrap();
}
#[test]
fn the_commands_write_a_file_and_apply_it_by_path() {
let mut s = session(128);
let (source, _) = multi_effect_mask(&mut s);
let dir = std::env::temp_dir().join(format!("tc_user_smart_mask_{}", std::process::id()));
let path = dir.join("lib").join("worn");
let saved = execute(&mut s, "mask.smart.create", &json!({"layer": source.0, "path": path.display().to_string(), "name": "Worn"})).unwrap();
let file = dir.join("lib").join(format!("worn.{SMART_MASK_EXT}"));
assert_eq!(saved["path"], file.display().to_string(), "the extension is added and the folder made");
let other = layer(&mut s);
execute(&mut s, "mask.smart.apply", &json!({"layer": other.0, "path": file.display().to_string()})).unwrap();
assert_eq!(effects(&s, other), effects(&s, source));
std::fs::remove_dir_all(&dir).ok();
let plain = layer(&mut s);
assert!(execute(&mut s, "mask.smart.create", &json!({"layer": plain.0, "path": "unused"})).is_err(), "a layer without a mask has nothing to save");
assert!(execute(&mut s, "mask.smart.apply", &json!({"layer": plain.0, "path": file.display().to_string()})).is_err(), "a missing file changes nothing");
assert!(s.doc.project.layer(plain).unwrap().mask.is_none());
}
#[test]
fn a_file_without_a_mask_is_refused_and_a_disabled_mask_comes_back_on() {
let mut s = session(128);
let plain = layer(&mut s);
let material = s.smart_material_bytes(plain, "Plain").unwrap();
assert!(s.apply_smart_mask_bytes(plain, &material).is_err(), "a smart material file has no mask to take");
assert!(s.apply_smart_mask_bytes(plain, b"junk").is_err());
let (source, _) = multi_effect_mask(&mut s);
s.doc.project.layer_mut(source).unwrap().mask.as_mut().unwrap().enabled = false;
let bytes = s.smart_mask_bytes(source, "Off").unwrap();
s.apply_smart_mask_bytes(plain, &bytes).unwrap();
assert!(s.doc.project.layer(plain).unwrap().mask.as_ref().unwrap().enabled);
}
#[test]
fn an_image_name_the_project_uses_for_other_bytes_gets_a_new_name() {
let mut s = session(128);
let (source, image) = multi_effect_mask(&mut s);
let bytes = s.smart_mask_bytes(source, "Stencil").unwrap();
let mut other = session(128);
let mut png = Vec::new();
image::RgbaImage::from_fn(4, 4, |_, _| image::Rgba([1, 2, 3, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
assert_eq!(other.import_resource_bytes("stencil.png", png).unwrap(), image);
let own = other.doc.resources[&image].clone();
let target = layer(&mut other);
other.apply_smart_mask_bytes(target, &bytes).unwrap();
assert_eq!(other.doc.resources[&image], own, "the project's own image is untouched");
let mask = other.doc.project.layer(target).unwrap().mask.as_ref().unwrap();
let read: Vec<&str> = mask.effects.iter().flat_map(|effect| effect.kind.images_read()).collect();
assert_eq!(read.len(), 1);
assert_ne!(read[0], image, "the mask reads its own image under another name");
assert_eq!(other.doc.resources[read[0]], s.doc.resources[&image]);
}
#[test]
fn effects_reading_an_anchor_of_the_mask_follow_it() {
let mut s = session(128);
let id = layer(&mut s);
let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": id.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap();
let fill = execute(&mut s, "effect.add.fill", &json!({"layer": id.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap();
let mask = s.doc.project.layer_mut(id).unwrap().mask.as_mut().unwrap();
for effect in &mut mask.effects {
if effect.id.0 == fill {
effect.kind = EffectKind::Fill {
source: Source::Anchor { anchor: LayerId(anchor), channel: texturecraft_engine::core::Channel::Height, ramp: Vec::new() },
projection: Default::default(),
};
}
}
let bytes = s.smart_mask_bytes(id, "Anchored").unwrap();
let target = layer(&mut s);
s.apply_smart_mask_bytes(target, &bytes).unwrap();
let mask = s.doc.project.layer(target).unwrap().mask.as_ref().unwrap();
let new_anchor = mask.effects.iter().find(|effect| matches!(effect.kind, EffectKind::Anchor)).unwrap().id;
let reads = mask.effects.iter().find_map(|effect| match &effect.kind {
EffectKind::Fill { source: Source::Anchor { anchor, .. }, .. } => Some(*anchor),
_ => None,
});
assert_eq!(reads, Some(new_anchor), "the fill reads the copied anchor, not the old one");
}
#[test]
fn an_external_anchor_cannot_be_saved_or_rebound_in_another_project() {
let mut s = session(128);
let (source, _) = multi_effect_mask(&mut s);
let external = layer(&mut s);
let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": external.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap();
let source_ref = Source::Anchor { anchor: LayerId(anchor), channel: texturecraft_engine::core::Channel::Height, ramp: Vec::new() };
let mut file = texturecraft_engine::formats::load_project_bytes(&s.smart_mask_bytes(source, "Preset").unwrap()).unwrap();
let holder = file.project.texture_sets[0].stack[0];
for (project, id) in [(&mut file.project, holder), (&mut s.doc.project, source)] {
let mask = project.layer_mut(id).unwrap().mask.as_mut().unwrap();
let fill = mask.effects.iter_mut().find(|effect| matches!(effect.kind, EffectKind::Fill { .. })).unwrap();
fill.kind = EffectKind::Fill { source: source_ref.clone(), projection: Default::default() };
}
assert!(s.smart_mask_bytes(source, "Preset").unwrap_err().to_string().contains("outside this mask"));
let bytes = texturecraft_engine::formats::save_project_bytes(&file).unwrap();
let before = s.doc.project.clone();
let history = s.history_labels();
assert!(s.apply_smart_mask_bytes(external, &bytes).unwrap_err().to_string().contains("outside this mask"));
assert_eq!(s.doc.project, before);
assert_eq!(s.history_labels(), history);
}
+91 -10
View File
@@ -247,6 +247,37 @@ fn panic_hunt() {
}
}
/// A colour param is `[r, g, b]` in linear 0..1 or `"#rrggbb"` in sRGB, and the same digits differ
/// between the two, so every command that takes a colour says which form is which.
#[test]
fn colour_params_name_their_colour_space() {
for spec in command_specs() {
if ["color?", "colors?", "Color?"].iter().any(|k| spec.params.contains(k)) {
assert!(spec.params.contains("linear"), "{}: {}", spec.id, spec.params);
let hex = spec.params.matches("\"#rrggbb\"").count();
assert_eq!(hex, spec.params.matches("\"#rrggbb\" sRGB").count(), "{}: {}", spec.id, spec.params);
}
}
// These read their colours through `color_param`, which takes both forms.
for id in
["layer.add.fill", "layer.fill.set", "effect.add.fill", "effect.add.filter", "tool.material", "mask.add.colorSelection", "resource.text", "display.set"]
{
let spec = command_specs().iter().find(|c| c.id == id).unwrap();
assert!(spec.params.contains("[r,g,b] linear or \"#rrggbb\" sRGB"), "{id}: {}", spec.params);
}
let base_color = |color: Value| {
let mut s = session();
execute(&mut s, "layer.add.fill", &json!({ "color": color })).unwrap();
s.update();
s.caches[0].composite.value(Channel::BaseColor, 128, 128)
};
let hex = base_color(json!("#c8102e"));
let linear = base_color(json!([0.5776, 0.0052, 0.0273]));
assert!(hex.iter().zip(&linear).all(|(a, b)| (a - b).abs() < 2e-3), "{hex:?} {linear:?}");
let digits = base_color(json!([0.7843, 0.0627, 0.1804]));
assert!(digits[0] - hex[0] > 0.1, "{digits:?} {hex:?}");
}
#[test]
fn copy_paste_flatten_and_resize_keep_the_look() {
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap();
@@ -747,43 +778,43 @@ fn changing_generator_kind_keeps_the_effect_identity_and_settings() {
fn unparseable_color_param_returns_error() {
let mut s = session();
let err = execute(&mut s, "layer.add.fill", &json!({"color": "#fff"})).unwrap_err();
assert_eq!(err.to_string(), "`layer.add.fill`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")");
assert_eq!(err.to_string(), "`layer.add.fill`: `color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)");
let err = execute(&mut s, "layer.fill.set", &json!({"channel": "baseColor", "color": "#123"})).unwrap_err();
assert_eq!(err.to_string(), "`layer.fill.set`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")");
assert_eq!(err.to_string(), "`layer.fill.set`: `color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)");
let err = execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": "invalid"})).unwrap_err();
assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")");
assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)");
let err = execute(&mut s, "mask.add.colorSelection", &json!({"color": "#xyz"})).unwrap_err();
assert_eq!(err.to_string(), "`mask.add.colorSelection`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")");
assert_eq!(err.to_string(), "`mask.add.colorSelection`: `color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)");
let err = execute(&mut s, "display.set", &json!({"scatterColor": "#12345"})).unwrap_err();
assert_eq!(err.to_string(), "`display.set`: `scatterColor` must be a color ([r, g, b] linear or \"#rrggbb\")");
assert_eq!(err.to_string(), "`display.set`: `scatterColor` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)");
let rev_before = s.revision;
let exposure_before = s.doc.project.display.env_exposure;
let err = execute(&mut s, "display.set", &json!({"exposure": 2.0, "scatterColor": "invalid"})).unwrap_err();
assert_eq!(err.to_string(), "`display.set`: `scatterColor` must be a color ([r, g, b] linear or \"#rrggbb\")");
assert_eq!(err.to_string(), "`display.set`: `scatterColor` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)");
assert_eq!(s.doc.project.display.env_exposure, exposure_before);
assert_eq!(s.revision, rev_before);
let mask_before = s.tool.mask_value;
let err = execute(&mut s, "tool.material", &json!({"maskValue": 0.25, "channel": "baseColor", "color": "invalid"})).unwrap_err();
assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")");
assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)");
assert_eq!(s.tool.mask_value, mask_before);
assert_eq!(s.revision, rev_before);
let err = execute(&mut s, "tool.material", &json!({"color": "invalid"})).unwrap_err();
assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")");
assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)");
assert_eq!(s.revision, rev_before);
let err = execute(&mut s, "layer.add.fill", &json!({"color": [1e40, 0.0, 0.0]})).unwrap_err();
assert_eq!(err.to_string(), "`layer.add.fill`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")");
assert_eq!(err.to_string(), "`layer.add.fill`: `color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)");
assert_eq!(s.revision, rev_before);
let err = execute(&mut s, "layer.fill.set", &json!({"channel": "baseColor", "procedural": "noise", "color": "red"})).unwrap_err();
assert_eq!(err.to_string(), "`layer.fill.set`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")");
assert_eq!(err.to_string(), "`layer.fill.set`: `color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)");
assert_eq!(s.revision, rev_before);
assert!(execute(&mut s, "tool.cloneSource", &json!({"uv": [0.2, 0.8, 0.4]})).is_err());
@@ -791,3 +822,53 @@ fn unparseable_color_param_returns_error() {
let err = execute(&mut s, "tool.click", &json!({"uv": [0.2, 0.8, 0.4]})).unwrap_err();
assert_eq!(err.to_string(), "`tool.click`: a 2D view point needs `uv` as [u, v]");
}
#[test]
fn resetting_a_stencil_puts_back_its_placement_only() {
let mut stencil = texturecraft_engine::StencilState::new("logo.png");
stencil.center = [0.4, -0.2];
stencil.scale = 2.0;
stencil.rotation = 30.0;
stencil.opacity = 0.9;
stencil.tile = true;
stencil.reset_placement();
assert_eq!((stencil.center, stencil.scale, stencil.rotation, stencil.opacity, stencil.tile), ([0.0, 0.0], 0.8, 0.0, 0.9, true));
}
#[test]
fn blending_set_gives_each_channel_its_own_mode_and_opacity_in_one_undo_step() {
let mut s = session();
let layer = execute(&mut s, "layer.add.paint", &json!({})).unwrap()["layer"].as_u64().unwrap();
let read = |s: &Session| s.doc.project.layers[&texturecraft_engine::core::LayerId(layer)].channels.clone();
let before = read(&s);
execute(
&mut s,
"layer.blending.set",
&json!({"layer": layer, "channels": {"baseColor": {"mode": "Multiply", "opacity": 0.25}, "roughness": {"opacity": 0.5}}}),
)
.unwrap();
let after = read(&s);
assert_eq!((after[&Channel::BaseColor].mode, after[&Channel::BaseColor].opacity), (texturecraft_engine::core::BlendMode::Multiply, 0.25));
assert_eq!((after[&Channel::Roughness].mode, after[&Channel::Roughness].opacity), (before[&Channel::Roughness].mode, 0.5));
assert_eq!(after[&Channel::Metallic], before[&Channel::Metallic], "channels not listed stay as they were");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(read(&s), before, "one undo step restores every listed channel");
execute(&mut s, "edit.redo", &Value::Null).unwrap();
// A channel the layer has disabled stays disabled
execute(&mut s, "layer.blend", &json!({"layer": layer, "channel": "metallic", "enabled": false})).unwrap();
execute(&mut s, "layer.blending.set", &json!({"layer": layer, "channels": {"metallic": {"opacity": 0.1}}})).unwrap();
assert!(!read(&s).contains_key(&Channel::Metallic));
let stable = read(&s);
for bad in [
json!({"layer": layer}),
json!({"layer": layer, "channels": {"nope": {}}}),
json!({"layer": layer, "channels": {"baseColor": {"mode": "Multiply"}, "nope": {}}}),
json!({"layer": layer, "channels": {"baseColor": {"mode": "???"}}}),
] {
assert!(execute(&mut s, "layer.blending.set", &bad).is_err(), "{bad}");
assert_eq!(read(&s), stable, "an error changes nothing");
}
execute(&mut s, "layer.blending.set", &json!({"layer": layer, "channels": {"baseColor": {"opacity": 2.0}, "roughness": {"opacity": -1.0}}})).unwrap();
assert_eq!((read(&s)[&Channel::BaseColor].opacity, read(&s)[&Channel::Roughness].opacity), (1.0, 0.0), "opacity is clamped");
}
+1 -1
View File
@@ -78,7 +78,7 @@ pub fn preset_from_json(json: &str) -> Result<ExportPreset>;
pub fn preset_to_json(preset: &ExportPreset) -> Result<String>;
```
- `ExportPreset { name, maps: Vec<MapSpec> }`, `MapSpec { file, format, bit_depth, channels: Vec<(Dest, SourceRef)> }`
- `ExportPreset { name, maps: Vec<MapSpec> }`, `MapSpec { file, format, bit_depth, channels: Vec<(Dest, SourceRef)>, inverted: Vec<Dest> }`
(serde JSON, so presets can be user files).
- `Dest`: `R G B A` or `L` (gray; `L` + `A` = gray + alpha).
- `SourceRef`: `Channel { channel, component }` (`Normal` = the **final** normal in the export
+59 -23
View File
@@ -253,6 +253,10 @@ pub struct MapSpec {
pub format: FileFormat,
pub bit_depth: u8,
pub channels: Vec<(Dest, SourceRef)>,
/// Destination channels written as `1 - value` (absent in old files: none). The source value
/// is inverted before the colour-space encoding, so a colour map is inverted in linear light.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub inverted: Vec<Dest>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -268,26 +272,38 @@ impl ExportPreset {
if self.name.trim().is_empty() || self.name.chars().count() > MAX_PRESET_NAME || self.name.chars().any(char::is_control) {
return bad(format!("the name must be 1 to {MAX_PRESET_NAME} characters without control characters"));
}
if self.maps.len() > MAX_MAPS {
return bad(format!("more than {MAX_MAPS} maps"));
}
for m in &self.maps {
if let Some(e) = template_error(&m.file) {
return bad(e);
}
if !matches!(m.bit_depth, 8 | 16 | 32) {
return bad(format!("map \"{}\" has bit depth {} (8, 16 or 32)", m.file, m.bit_depth));
}
if m.channels.iter().any(|(_, s)| s.component() != s.raw_component()) {
return bad(format!("map \"{}\" picks a component other than 0, 1 or 2", m.file));
}
let dests: BTreeSet<Dest> = m.channels.iter().map(|(d, _)| *d).collect();
if dests.len() != m.channels.len() || m.channels.is_empty() {
return bad(format!("map \"{}\" needs distinct destination channels", m.file));
}
if dests.contains(&Dest::L) && dests.iter().any(|d| matches!(d, Dest::R | Dest::G | Dest::B)) {
return bad(format!("map \"{}\" mixes L with R/G/B", m.file));
}
let inv: BTreeSet<Dest> = m.inverted.iter().copied().collect();
if inv.len() != m.inverted.len() || !inv.is_subset(&dests) {
return bad(format!("map \"{}\" inverts a channel it does not write, or one twice", m.file));
}
if m.channels.iter().any(|(_, s)| matches!(s, SourceRef::Constant(v) if !v.is_finite())) {
return bad(format!("map \"{}\" has a non-finite constant", m.file));
}
@@ -389,7 +405,7 @@ pub struct PlannedFile {
}
// ---------------------------------------------------------------------------------------------
// Planning: which maps exist for a texture set and what their files are called.
// Planning: which maps exist for a texture set and what their files are called
fn normal_present(set: &TextureSet) -> bool {
set.has_channel(Channel::Normal) || set.has_channel(Channel::Height) || set.baked.contains(&BakedMap::Normal)
@@ -476,6 +492,7 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
{
return Err(FormatError::Invalid(format!("export size {s} must be a power of two up to {MAX_IMAGE_SIZE}")));
}
let mut used = BTreeSet::new();
let mut out = Vec::new();
let tiles: Vec<Option<u32>> = if set.uv_tiles.is_empty() || opts.atlas { vec![None] } else { set.uv_tiles.iter().copied().map(Some).collect() };
@@ -483,6 +500,7 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
if !map.channels.iter().any(|(_, s)| source_present(set, s)) {
continue;
}
let format = opts.format_override.unwrap_or(map.format);
let bit_depth = format.depth(opts.bit_depth_override.unwrap_or(map.bit_depth));
let space = opts.space_for(format);
@@ -491,9 +509,11 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
(true, ColorSpace::Srgb) => "sRGB",
(true, other) => other.name(),
};
// Integer files clamp to 0-1, which wide-gamut linear colour can leave.
// Integer files clamp wide-gamut linear color to 0–1
let clamps = is_color(map) && !format.is_float() && matches!(space, ColorSpace::AcesCg | ColorSpace::Aces2065);
// One file per UV tile: names without `$udim` get it appended.
// Append `$udim` to names for separate UV tiles
let template = if tiles.iter().any(Option::is_some) && !map.file.contains("$udim") { format!("{}.$udim", map.file) } else { map.file.clone() };
for &tile in &tiles {
let stem = template
@@ -503,7 +523,8 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
.replace("$textureSet", &set.name)
.replace("$channel", channel_label(map))
.replace("$colorSpace", color_space);
// The same name with the tile number as a placeholder, to write it as `<UDIM>` after.
// Replace the tile number with `<UDIM>` in the shared name
let token_stem = tile.map(|_| {
let t = template
.replace("$udim", "UDIMTOKEN")
@@ -525,7 +546,8 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
format.extension().to_uppercase()
));
}
// Case-insensitive: Windows and macOS file systems are.
// Compare names case-insensitively for Windows and macOS
let mut k = 2;
while used.contains(&name.to_ascii_lowercase()) {
name = format!("{stem}_{k}.{ext}");
@@ -535,8 +557,9 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
warnings.push(format!("\"{stem}.{ext}\" is produced by more than one map; this one was renamed to \"{name}\""));
}
used.insert(name.to_ascii_lowercase());
// Only when putting the tile number back gives this file's name: the length limit cuts the
// longer placeholder elsewhere (or off), and a name may hold the placeholder text itself.
// Use a UDIM name only when substituting its tile recovers the output name
// Truncation or literal placeholder text can make that substitution ambiguous
let udim_name = token_stem.filter(|t| tile.is_some_and(|n| t.contains("UDIMTOKEN") && t.replace("UDIMTOKEN", &n.to_string()) == stem)).map(|t| {
let renamed = if k > 2 { format!("_{}", k - 1) } else { String::new() };
format!("{t}{renamed}.{ext}").replace("UDIMTOKEN", "<UDIM>")
@@ -548,7 +571,7 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
}
// ---------------------------------------------------------------------------------------------
// Sampling.
// Sampling
/// Which texel a value is taken from.
#[derive(Clone, Copy, PartialEq)]
@@ -702,10 +725,12 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result<Vec<Expo
if tile_res == 0 || tile_res > MAX_IMAGE_SIZE || height != tile_res * grid.map_or(1, |g| g.rows) {
return Err(FormatError::Invalid(format!("composite size {res}×{height} does not fit texture set \"{}\"", set.name)));
}
if input.coverage.len() != res as usize * height as usize {
return Err(FormatError::Invalid(format!("coverage has {} texels, expected {res}×{height}", input.coverage.len())));
}
// Padding stays inside each UV tile.
// Padding stays inside each UV tile
let dmap = match opts.padding {
Padding::None => None,
Padding::Dilation(d) | Padding::DilationDefault(d) => Some(DilationMap::in_blocks(input.coverage, res, height, Some(d), tile_res)),
@@ -729,11 +754,14 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result<Vec<Expo
let map = opts.preset.maps.get(p.map).ok_or_else(|| FormatError::Invalid("planned map out of range".into()))?;
let lay = layout(set, map);
let n = lay.len();
// The texels written: one tile, or the whole set.
let inverted: Vec<bool> = lay.iter().map(|(d, _)| map.inverted.contains(d)).collect();
// The texels written: one tile, or the whole set
let (x0, y0, w, h) = match (p.tile, grid) {
(Some(t), Some(g)) => {
let (bx, by) = g.block(t).ok_or_else(|| FormatError::Invalid(format!("UV tile {t} is not in the set's grid")))?;
// A tile smaller than its block fills the block's top-left corner.
// A tile smaller than its block fills the block's top-left corner
let side = ((tile_res as f32 * set.tile_scale(t)).round() as u32).clamp(1, tile_res);
(bx * tile_res, by * tile_res, side, side)
}
@@ -755,17 +783,19 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result<Vec<Expo
let mut cache = None;
for (k, (_, src)) in lay.iter().enumerate() {
if let Some(v) = row.get_mut(col * n + k) {
*v = sampler.sample(src, at, &mut cache);
let s = sampler.sample(src, at, &mut cache);
*v = if inverted.get(k).copied().unwrap_or(false) { 1.0 - s } else { s };
}
}
}
});
// `size` is per tile: an atlas scales with it.
// `size` is per tile: an atlas scales with it
let scale = |v: u32| (u64::from(v) * u64::from(opts.size.unwrap_or(tile_res)) / u64::from(tile_res)) as u32;
let size = (scale(w), scale(h));
let data = resize(data, (w, h), n, size);
// Colour maps leave linear Rec.709 for the chosen space. sRGB in integer files is
// encoded by `encode`; every other case is converted here (float sRGB included).
// Integer sRGB converts in `encode`; other color spaces convert here
let space = opts.space_for(p.format);
let rgb = lay.len() >= 3 && lay.iter().take(3).map(|(d, _)| *d).eq([Dest::R, Dest::G, Dest::B]);
let mut data = data;
@@ -781,7 +811,8 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result<Vec<Expo
warnings.push(format!("\"{}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", p.name, space.name()));
}
let srgb: Vec<bool> = lay.iter().map(|(d, _)| *d != Dest::A && is_color(map) && !p.format.is_float() && space == ColorSpace::Srgb).collect();
// A colour space the user chose is written into the colour maps (data maps have none).
// A colour space the user chose is written into the colour maps (data maps have none)
let embed = (opts.color_space.is_some() && is_color(map) && rgb).then_some(space);
let bytes = encode(p.format, p.bit_depth, size, n, &data, &srgb, embed, &mut warnings)?;
Ok(ExportedFile { name: p.name, bytes, width: size.0, height: size.1, warnings })
@@ -839,8 +870,8 @@ fn encode(
warnings: &mut Vec<String>,
) -> Result<Vec<u8>> {
let failed = |e: &dyn std::fmt::Display| FormatError::Invalid(format!("{} encoding failed: {e}", format.extension()));
// Where the colour space goes: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities
// attribute in EXR. The other formats have no place for it.
// Embed ICC or EXR chromaticities only where the format supports them
if let Some(space) = embed
&& matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr)
{
@@ -858,7 +889,8 @@ fn encode(
}
_ => {}
}
// Integer formats: transfer function and quantization first, then fit the channel layout.
// Integer formats: transfer function and quantization first, then fit the channel layout
let encoded: Vec<f32> =
data.iter().enumerate().map(|(i, v)| if srgb.get(i % n).copied().unwrap_or(false) { linear_to_srgb(*v) } else { v.clamp(0.0, 1.0) }).collect();
let (encoded, n) = match (format, n) {
@@ -890,7 +922,8 @@ fn remap(data: &[f32], n: usize, pick: &[usize]) -> Vec<f32> {
fn write_image(format: FileFormat, bytes: &[u8], (w, h): (u32, u32), color: image::ExtendedColorType, icc: Option<Vec<u8>>) -> image::ImageResult<Vec<u8>> {
use image::ImageEncoder;
let mut out = Cursor::new(Vec::new());
// `set_icc_profile` says no (an error to ignore) for an encoder without a place for it.
// `set_icc_profile` says no (an error to ignore) for an encoder without a place for it
let fmt = match format {
FileFormat::Jpeg => {
let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, JPEG_QUALITY);
@@ -957,13 +990,15 @@ fn write_exr((w, h): (u32, u32), n: usize, data: &[f32], half: bool, space: Opti
let layer = Layer::new((w as usize, h as usize), LayerAttributes::default(), Encoding::SMALL_LOSSLESS, AnyChannels::sort(channels));
let mut out = Cursor::new(Vec::new());
let mut image = Image::from_layer(layer);
// The primaries and white point of the values, in the attribute OpenEXR readers look for.
// Store primaries and white point in the OpenEXR attribute
if let Some(space) = space {
let [r, g, b, white] = space.chromaticities().map(|xy| Vec2(xy[0] as f32, xy[1] as f32));
image.attributes.chromaticities = Some(exr::meta::attribute::Chromaticities { red: r, green: g, blue: b, white });
}
let writer = image.write();
// No worker threads on the web.
// The web build has no worker threads
#[cfg(target_arch = "wasm32")]
let writer = writer.non_parallel();
writer.to_buffered(&mut out)?;
@@ -978,11 +1013,12 @@ pub fn write_files(files: &[ExportedFile], dir: &std::path::Path) -> Result<Vec<
files
.iter()
.map(|f| {
// The planned name is `<sanitized stem>.<ext>`; the stem alone is capped at MAX_STEM.
// Cap the sanitized stem before adding the extension
let (stem, ext) = f.name.rsplit_once('.').unwrap_or((&f.name, ""));
if f.name.is_empty() || stem != sanitize_file_stem(stem) || !ext.chars().all(|c| c.is_ascii_alphanumeric()) || f.name.trim_matches('.').is_empty() {
return Err(FormatError::Invalid(format!("\"{}\" is not a plain file name", f.name)));
}
let path = dir.join(&f.name);
crate::write_atomic(&path, &f.bytes)?;
Ok(path)
+137 -10
View File
@@ -242,6 +242,7 @@ fn templates_are_sanitized_and_collisions_suffixed() {
format: FileFormat::Png,
bit_depth: 8,
channels: vec![(Dest::L, SourceRef::Channel { channel: Channel::Roughness, component: 0 })],
inverted: Vec::new(),
};
let preset = ExportPreset {
name: "t".into(),
@@ -316,6 +317,7 @@ fn every_format_encodes_and_decodes() {
format: FileFormat::Png,
bit_depth: 8,
channels: vec![(Dest::L, SourceRef::Channel { channel: Channel::Roughness, component: 0 }), (Dest::A, SourceRef::Constant(0.5))],
inverted: Vec::new(),
};
let mut preset = builtin_preset("glTF PBR Metal Roughness").unwrap();
preset.maps.push(gray_alpha);
@@ -331,9 +333,11 @@ fn every_format_encodes_and_decodes() {
if format == FileFormat::Exr && f.name.starts_with("la") {
continue; // Y/A EXR: covered by `exr_values_are_linear`.
}
assert_eq!(decode(f).dimensions(), (RES, RES), "{}", f.name);
}
// Roughness 0.25 everywhere survives every format (JPEG within its loss).
// Roughness 0.25 everywhere survives every format (JPEG within its loss)
let px = decode(find(&files, "OcclusionRoughnessMetallic.")).to_rgba32f().get_pixel(1, 1)[1];
assert!((px - 0.25).abs() < 0.01, "{format:?}/{depth}: {px}");
let base = find(&files, "_BaseColor.");
@@ -407,7 +411,7 @@ fn write_files_accepts_planned_name_with_max_length_stem() {
}
fn gray_map(file: &str, src: SourceRef) -> MapSpec {
MapSpec { file: file.into(), format: FileFormat::Png, bit_depth: 8, channels: vec![(Dest::L, src)] }
MapSpec { file: file.into(), format: FileFormat::Png, bit_depth: 8, channels: vec![(Dest::L, src)], inverted: Vec::new() }
}
#[test]
@@ -449,6 +453,7 @@ fn converted_maps_invert_and_derive_normals() {
format: FileFormat::Png,
bit_depth: 8,
channels: [Dest::R, Dest::G, Dest::B].into_iter().zip(0u8..).map(|(d, k)| (d, SourceRef::Virtual { map, component: k })).collect(),
inverted: Vec::new(),
};
let preset = ExportPreset {
name: "converted".into(),
@@ -467,7 +472,8 @@ fn converted_maps_invert_and_derive_normals() {
assert_eq!(hn.get_pixel(30, 30), full.get_pixel(30, 30), "without a normal channel the final normal is the height normal");
let (a, b) = (hn.get_pixel(30, 30), decode(find(&files, "dx")).to_rgb8().get_pixel(30, 30).to_owned());
assert!(a[1] > 136 && (a[1] as i32 + b[1] as i32 - 255).abs() <= 1, "DirectX flips green: {a:?} vs {b:?}");
// Converted maps only exist when their source channel does.
// Converted maps only exist when their source channel does
let fx = Fx::new(&default_channels());
let only = ExportPreset { name: "c".into(), maps: vec![gray_map("rough", virt(VirtualMap::Roughness)), rgb("hn", VirtualMap::HeightNormal)] };
let names: Vec<String> = list_outputs(&fx.project, 0, "m", &ExportOptions::new(only)).unwrap().into_iter().map(|p| p.name).collect();
@@ -476,7 +482,7 @@ fn converted_maps_invert_and_derive_normals() {
#[test]
fn uv_tiles_export_one_file_per_tile_without_padding_across() {
// Tiles 1001 (left block: red, only x < 16 covered) and 1002 (right block: blue).
// Tiles 1001 (left block: red, only x < 16 covered) and 1002 (right block: blue)
let mut project = Project::new("My Project", "builtin:udim_plane");
let mut ts = TextureSet::new("Body Set", 0, RES);
ts.uv_tiles = vec![1001, 1002];
@@ -505,6 +511,7 @@ fn uv_tiles_export_one_file_per_tile_without_padding_across() {
(Dest::G, SourceRef::Channel { channel: Channel::BaseColor, component: 1 }),
(Dest::B, SourceRef::Channel { channel: Channel::BaseColor, component: 2 }),
],
inverted: Vec::new(),
}],
};
let files = render_maps(&input, &ExportOptions::new(preset.clone())).unwrap();
@@ -512,10 +519,12 @@ fn uv_tiles_export_one_file_per_tile_without_padding_across() {
assert_eq!(names, ["Body_Set_color.1001.png", "Body_Set_color.1002.png"]);
let (left, right) = (decode(&files[0]).to_rgb8(), decode(&files[1]).to_rgb8());
assert_eq!((left.width(), left.height(), right.width()), (RES, RES, RES));
// Infinite padding fills tile 1001 from its own island only.
// Infinite padding fills tile 1001 from its own island only
assert!(left.pixels().all(|p| p.0 == [255, 0, 0]), "tile 1001 is red");
assert!(right.pixels().all(|p| p.0 == [0, 0, 255]), "tile 1002 is blue");
// `$udim` placed by the template; a size applies per tile; the atlas is one image.
// `$udim` placed by the template; a size applies per tile; the atlas is one image
let mut named = preset.clone();
named.maps[0].file = "$udim_$textureSet".into();
let opts = ExportOptions { size: Some(32), ..ExportOptions::new(named) };
@@ -534,12 +543,13 @@ fn the_udim_name_is_the_file_name_with_its_tile_number_as_placeholder() {
project.texture_sets.push(ts);
let udim_names = |file: String| {
let channels = vec![(Dest::R, SourceRef::Channel { channel: Channel::BaseColor, component: 0 })];
let preset = ExportPreset { name: "t".into(), maps: vec![MapSpec { file, format: FileFormat::Png, bit_depth: 8, channels }] };
let preset = ExportPreset { name: "t".into(), maps: vec![MapSpec { file, format: FileFormat::Png, bit_depth: 8, channels, inverted: Vec::new() }] };
list_outputs(&project, 0, "m", &ExportOptions::new(preset)).unwrap().into_iter().map(|f| f.udim_name).collect::<Vec<_>>()
};
let placeholder = Some("Body_<UDIM>.png".to_string());
assert_eq!(udim_names("$textureSet_$udim".into()), [placeholder.clone(), placeholder]);
// The length limit cuts the longer placeholder where it doesn't cut the tile number: none then.
// The length limit cuts the longer placeholder where it doesn't cut the tile number: none then
assert_eq!(udim_names(format!("{}_$udim_$textureSet", "a".repeat(MAX_STEM - 10))), [None, None]);
}
@@ -635,6 +645,7 @@ fn colour_space_names_the_files_and_warns_when_integer_files_clamp() {
(Dest::G, SourceRef::Channel { channel: Channel::BaseColor, component: 1 }),
(Dest::B, SourceRef::Channel { channel: Channel::BaseColor, component: 2 }),
],
inverted: Vec::new(),
}],
};
let plan = |space: Option<ColorSpace>, format: Option<FileFormat>| {
@@ -648,7 +659,8 @@ fn colour_space_names_the_files_and_warns_when_integer_files_clamp() {
assert!(aces.warnings.iter().any(|w| w.contains("clamped")), "{:?}", aces.warnings);
assert!(plan(Some(ColorSpace::AcesCg), Some(FileFormat::Exr)).warnings.is_empty(), "float files keep the values");
assert!(plan(None, None).warnings.is_empty() && plan(Some(ColorSpace::LinearRec709), None).warnings.is_empty());
// The planned names are the rendered names.
// The planned names are the rendered names
let opts = ExportOptions { color_space: Some(ColorSpace::Aces2065), ..ExportOptions::new(named) };
let names: Vec<String> = fx.render(&opts).into_iter().map(|f| f.name).collect();
assert_eq!(names, list_outputs(&fx.project, 0, "sphere", &opts).unwrap().into_iter().map(|p| p.name).collect::<Vec<_>>());
@@ -685,13 +697,15 @@ fn a_chosen_colour_space_is_embedded_as_an_icc_profile() {
if depth == 16 && matches!(format, FileFormat::Jpeg | FileFormat::Webp) {
continue;
}
for space in ColorSpace::ALL {
let mut warnings = Vec::new();
let bytes = encode(format, depth, (8, 8), 3, &data, &[false; 3], Some(space), &mut warnings).unwrap();
assert_eq!(embedded_icc(format, &bytes), crate::icc::profile(space), "{format:?} {depth}-bit {space:?}");
assert!(warnings.is_empty(), "{warnings:?}");
}
// No colour space chosen (a data map, or the default): nothing is embedded.
// No colour space chosen (a data map, or the default): nothing is embedded
let bytes = encode(format, depth, (8, 8), 3, &data, &[false; 3], None, &mut Vec::new()).unwrap();
assert_eq!(embedded_icc(format, &bytes), None, "{format:?} {depth}-bit");
}
@@ -727,3 +741,116 @@ fn formats_without_a_place_for_a_colour_space_say_so() {
assert!(quiet.is_empty(), "{format:?}: nothing to say without a chosen space: {quiet:?}");
}
}
/// R packs roughness (0.25) and B metallic (0.75); G and A are constants.
fn invert_map(depth: u8, inverted: Vec<Dest>) -> MapSpec {
let ch = |channel| SourceRef::Channel { channel, component: 0 };
MapSpec {
file: "packed".into(),
format: FileFormat::Png,
bit_depth: depth,
channels: vec![
(Dest::R, ch(Channel::Roughness)),
(Dest::G, SourceRef::Constant(0.5)),
(Dest::B, ch(Channel::Metallic)),
(Dest::A, SourceRef::Constant(1.0)),
],
inverted,
}
}
#[test]
fn inverted_channels_write_one_minus_the_source() {
let fx = Fx::new(&default_channels());
for depth in [8u8, 16] {
let preset = |inverted| ExportPreset { name: "inv".into(), maps: vec![invert_map(depth, inverted)] };
let px = |p: ExportPreset| {
let files = fx.render(&ExportOptions::new(p));
let img = decode(find(&files, "packed")).to_rgba16();
let p = img.get_pixel(9, 9).0;
// Compare 16-bit values for both depths: an 8-bit file widens to value * 257
p.map(i32::from)
};
let plain = px(preset(Vec::new()));
let inv = px(preset(vec![Dest::R, Dest::A]));
let tol = if depth == 8 { 257 } else { 2 };
// Roughness 0.25 inverts to 0.75, constant alpha 1 to 0; G and B stay
assert!((inv[0] - (65535 - plain[0])).abs() <= tol, "depth {depth}: R {} vs {}", inv[0], 65535 - plain[0]);
assert!((inv[0] - 49151).abs() <= tol, "depth {depth}: R {}", inv[0]);
assert!(inv[3] <= tol, "depth {depth}: A {}", inv[3]);
assert_eq!((inv[1], inv[2]), (plain[1], plain[2]), "depth {depth}: channels not listed stay as they are");
assert!((plain[0] - 16384).abs() <= tol && plain[3] == 65535, "depth {depth}: un-inverted {plain:?}");
}
// Gray maps and float files too
let gray = gray_map("g", SourceRef::Channel { channel: Channel::Metallic, component: 0 });
let gray = MapSpec { inverted: vec![Dest::L], ..gray };
let files = fx.render(&ExportOptions::new(ExportPreset { name: "inv".into(), maps: vec![gray] }));
assert_eq!(decode(find(&files, "g.png")).to_luma8().get_pixel(4, 4)[0], 64, "1 - metallic 0.75");
let mut float = invert_map(32, vec![Dest::B]);
float.format = FileFormat::Exr;
let files = fx.render(&ExportOptions::new(ExportPreset { name: "inv".into(), maps: vec![float] }));
let v = decode(find(&files, "packed.exr")).to_rgba32f().get_pixel(4, 4).0;
assert!((v[2] - 0.25).abs() < 1e-3 && (v[0] - 0.25).abs() < 1e-3, "metallic 0.75 inverted, roughness 0.25 not: {v:?}");
}
#[test]
fn inverted_flag_round_trips_and_old_json_loads() {
let mut map = invert_map(8, vec![Dest::B]);
let preset = ExportPreset { name: "Mine".into(), maps: vec![map.clone()] };
let json = preset_to_json(&preset).unwrap();
assert_eq!(preset_from_json(&json).unwrap(), preset);
// A file written before the flag existed has no `inverted` and keeps none on save
map.inverted.clear();
let old = ExportPreset { name: "Old".into(), maps: vec![map] };
let json = preset_to_json(&old).unwrap();
assert!(!json.contains("inverted"), "{json}");
assert_eq!(preset_from_json(&json).unwrap(), old);
assert!(preset_from_json(&json).unwrap().maps[0].inverted.is_empty());
}
#[test]
fn validation_rejects_inverting_a_channel_the_map_lacks() {
let ok = ExportPreset { name: "Mine".into(), maps: vec![invert_map(8, vec![Dest::R])] };
ok.validate().unwrap();
let mut bad = ok.clone();
bad.maps[0].inverted = vec![Dest::L];
assert!(bad.validate().is_err());
bad.maps[0].inverted = vec![Dest::R, Dest::R];
assert!(bad.validate().is_err());
}
#[test]
fn inverting_a_colour_channel_inverts_the_linear_value_before_encoding() {
let fx = Fx::new(&default_channels());
let base = |inverted: Vec<Dest>, size: Option<u32>| {
let map = MapSpec {
file: "col".into(),
format: FileFormat::Png,
bit_depth: 8,
channels: [Dest::R, Dest::G, Dest::B]
.into_iter()
.zip(0u8..)
.map(|(d, k)| (d, SourceRef::Channel { channel: Channel::BaseColor, component: k }))
.collect(),
inverted,
};
let mut opts = ExportOptions::new(ExportPreset { name: "c".into(), maps: vec![map] });
opts.size = size;
decode(find(&fx.render(&opts), "col")).to_rgb8()
};
let (plain, inv) = (base(Vec::new(), None), base(vec![Dest::R], None));
// Texel (9, 9): linear red 9/63, written as sRGB
let want = linear_to_srgb(1.0 - 9.0 / 63.0) * 255.0;
assert!((inv.get_pixel(9, 9)[0] as f32 - want).abs() <= 1.0, "{} vs {want}", inv.get_pixel(9, 9)[0]);
assert_eq!(inv.get_pixel(9, 9).0[1..], plain.get_pixel(9, 9).0[1..], "G and B stay");
// A size override goes through the resize path: the left-most texels are 1 - 0 -> white red
let half = base(vec![Dest::R], Some(RES / 2));
assert_eq!(half.width(), RES / 2);
assert!(half.get_pixel(0, 5)[0] >= 250, "{}", half.get_pixel(0, 5)[0]);
}
+2 -2
View File
@@ -51,8 +51,8 @@ pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_h
pub use presets::load_preset;
pub use presets::{builtin_preset, builtin_presets, preset_from_json, preset_to_json};
pub use project_file::{
BakePaintData, DEFAULT_PROJECT_OPEN_LIMIT_GIB, ProjectFile, load_project_bytes, project_open_limit_gib, sanitize_resource_name, save_project_bytes,
set_project_open_limit_gib,
BakePaintData, DEFAULT_PROJECT_OPEN_LIMIT_GIB, MAX_RESOURCE_NAME_LEN, ProjectFile, load_project_bytes, project_open_limit_gib, sanitize_resource_name,
save_project_bytes, set_project_open_limit_gib,
};
#[cfg(not(target_arch = "wasm32"))]
+1 -1
View File
@@ -72,7 +72,7 @@ pub fn usd_export_options() -> ExportOptions {
"ClearcoatRoughness" => gray(ch(Channel::CoatRoughness, 0)),
_ => gray(ch(Channel::Opacity, 0)),
};
MapSpec { file: stem.into(), format: FileFormat::Png, bit_depth: 8, channels }
MapSpec { file: stem.into(), format: FileFormat::Png, bit_depth: 8, channels, inverted: Vec::new() }
})
.collect();
super::png8_options(ExportPreset { name: "USD preview surface".into(), maps }, NormalFormat::OpenGl)
+17 -15
View File
@@ -292,21 +292,23 @@ fn check_buffer_uris(doc: &gltf::Document) -> Result<()> {
}
pub(crate) fn percent_decode(s: &str) -> Option<String> {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while let Some(&c) = b.get(i) {
let hex = |k: usize| b.get(k).and_then(|h| (*h as char).to_digit(16));
match (c, hex(i + 1), hex(i + 2)) {
(b'%', Some(h), Some(l)) => {
out.push((h * 16 + l) as u8);
i += 3;
}
_ => {
out.push(c);
i += 1;
}
craft_mesh::gltf::uri_decode_strict(s)
}
#[cfg(test)]
mod uri_decode_tests {
use super::percent_decode;
#[test]
fn strict_shared_uri_decoder_preserves_reference_policy() {
assert_eq!(percent_decode("texture%20é%2B.png"), Some("texture é+.png".into()));
assert_eq!(percent_decode("a+b%GG%2"), Some("a+b%GG%2".into()));
assert_eq!(percent_decode("%252e%252e"), Some("%2e%2e".into()));
// Decoding does not replace the external-reference confinement checks.
assert_eq!(percent_decode("%2e%2e%2fsecret"), Some("../secret".into()));
assert_eq!(percent_decode("%00"), Some("\0".into()));
for uri in ["%FF", "%C0%AF", "%ED%A0%80", "%E2%82"] {
assert_eq!(percent_decode(uri), None, "{uri}");
}
}
String::from_utf8(out).ok()
}
+8 -3
View File
@@ -130,6 +130,9 @@ pub(crate) struct RawMesh {
pub colors: Option<Vec<Vec4>>,
/// Triangles (vertex indices) per (material, part name); an empty part is unnamed.
pub groups: Vec<(String, String, Vec<u32>)>,
// Build-time index; group names are restored only after polygon collection ends
// Nested maps allow borrowed lookups without allocating keys for every polygon
group_index: HashMap<String, HashMap<String, usize>>,
pub warnings: Vec<String>,
pub cameras: Vec<RawCamera>,
/// Materials whose base color is not plain white (glTF).
@@ -148,11 +151,13 @@ pub(crate) struct RawBaseColor {
impl RawMesh {
/// Triangle list of `material` in `part`, created on first use.
pub fn group(&mut self, material: &str, part: &str) -> &mut Vec<u32> {
let i = match self.groups.iter().position(|(m, p, _)| m == material && p == part) {
let i = match self.group_index.get(material).and_then(|parts| parts.get(part)).copied() {
Some(i) => i,
None => {
self.groups.push((material.to_string(), part.to_string(), Vec::new()));
self.groups.len() - 1
let i = self.groups.len();
self.groups.push((material.to_owned(), part.to_owned(), Vec::new()));
self.group_index.entry(material.to_owned()).or_default().insert(part.to_owned(), i);
i
}
};
&mut self.groups[i].2
+30 -3
View File
@@ -31,10 +31,11 @@ fn read_inner(bytes: &[u8]) -> Result<RawMesh> {
let mut raw = RawMesh::default();
let (mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new());
let (mut missing_normals, mut missing_uvs) = (false, false);
for mesh in &scene.meshes {
for (mesh_id, mesh) in scene.meshes.iter().enumerate() {
// The shared reader preserves declarations as meshes, even when their names match
let declaration = mesh_id.to_string();
for part in &mesh.parts {
let material = part.material.and_then(|i| scene.materials.get(i)).map_or("Default", |m| m.name.as_str());
let name = if part.name.is_empty() { mesh.name.as_str() } else { part.name.as_str() };
// OBJ model/material runs have independent v/vt/vn deduplication.
let mut ids = HashMap::new();
for face in part.faces() {
@@ -73,10 +74,16 @@ fn read_inner(bytes: &[u8]) -> Result<RawMesh> {
};
polygon.push(id);
}
raw.polygon(material, name, &polygon);
raw.polygon(material, &declaration, &polygon);
}
}
}
// Restore display names only after grouping by declaration and material
for (_, name, _) in &mut raw.groups {
if let Some(mesh) = name.parse::<usize>().ok().and_then(|id| scene.meshes.get(id)) {
*name = mesh.name.clone();
}
}
if missing_uvs {
raw.warnings.push("some objects have no UVs; default UVs were assigned".into());
}
@@ -85,3 +92,23 @@ fn read_inner(bytes: &[u8]) -> Result<RawMesh> {
raw.colors = any_colors.then_some(colors);
Ok(raw)
}
#[cfg(test)]
mod tests {
#[test]
#[ignore = "release benchmark for declaration-heavy OBJ input"]
fn declaration_import_benchmark() {
for count in [10_000, 50_000] {
let mut source = String::from("v 0 0 0\nv 1 0 0\nv 0 1 0\n");
for _ in 0..count {
source.push_str("o repeated\nf 1 2 3\n");
}
let start = std::time::Instant::now();
let raw = super::read(source.as_bytes()).unwrap();
println!("{count} declarations: {:?}", start.elapsed());
assert_eq!(raw.groups.len(), count);
assert_eq!(raw.triangle_count(), count);
assert!(raw.groups.iter().all(|(_, name, tris)| name == "repeated" && tris.len() == 3));
}
}
}
+2 -1
View File
@@ -55,7 +55,8 @@ pub(crate) fn read(bytes: &[u8]) -> Result<RawMesh> {
if has_colors {
raw.colors = Some(vertex_colors);
}
raw.groups.push(("Default".into(), String::new(), (0..raw.positions.len() as u32).collect()));
let vertex_count = raw.positions.len() as u32;
raw.group("Default", "").extend(0..vertex_count);
Ok(raw)
}
Loaded 100 of 234 files, more files were not shown because too many files have changed in this diff. Show more