Merge remote-tracking branch 'origin/main' into HEAD

This commit is contained in:
bflatastic committed 2026-11-02 12:23:33 +07:00
commit 88c92dbf71
33 files changed
+1010 -44

No files matched your search

+1 -1
View File
@@ -19,7 +19,7 @@ end to end today (engine + UI + automation + tests), not what is planned.
| Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — |
| Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Hardware ray tracing |
| Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — |
| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, `$udim` tiles, **MaterialX** (`file.exportTextures` with `materialX`: a `.mtlx` OpenPBR material per set, `<UDIM>` aware), OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) |
| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, **colour space** of the colour maps (sRGB, Linear Rec.709, ACEScg, ACES2065-1; data maps never converted), `$udim` tiles, **MaterialX** (`file.exportTextures` with `materialX`: a `.mtlx` OpenPBR material per set, `<UDIM>` aware), OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) |
| UI and UX | 8 | 96% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts, a compact color picker (saturation/value square, hue strip, copyable RGB); all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations |
| Platforms | 4 | 76% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish |
| **Total** | **100** | **≈ 94%** | | |
+12 -4
View File
@@ -42,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export textures",
["File"],
None,
"{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)} → {files, warnings}",
"{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)}",
always,
export_textures
),
@@ -60,7 +60,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List export outputs",
[],
None,
"{preset?: name or preset object, ts?, format?, bitDepth?, size?} → [{ts, map, file, format, bitDepth, warnings}]",
"{preset?: name or preset object, ts?, format?, bitDepth?, size?, colorSpace?} → [{ts, map, file, format, bitDepth, warnings}]",
always,
plan
),
@@ -269,6 +269,12 @@ pub fn export_options(s: &Session, p: &Value, cmd: &str) -> Result<ExportOptions
Some(other) => return Err(bad(cmd, format!("unknown normal format `{other}`"))),
None => None,
};
if let Some(name) = strp(p, "colorSpace") {
o.color_space = Some(
texturecraft_texel::ColorSpace::from_name(name)
.ok_or_else(|| bad(cmd, format!("unknown colorSpace `{name}` (sRGB, Linear Rec.709, ACEScg or ACES2065-1)")))?,
);
}
Ok(o)
}
@@ -451,6 +457,9 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std:
if opts.normal_format == Some(NormalFormat::DirectX) {
warnings.push("MaterialX: the normalmap node reads OpenGL (+Y) normals; this export wrote DirectX normals, so flip the green channel".into());
}
if opts.color_space == Some(texturecraft_texel::ColorSpace::Aces2065) {
warnings.push("MaterialX: version 1.39 has no ACES2065-1 colour space; the colour maps are tagged lin_ap0_scene, its name in later versions, which older readers may not know".into());
}
let mut out = Vec::new();
let mut stems = std::collections::HashSet::new();
for &ts in sets {
@@ -463,8 +472,7 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std:
Some(t) => f.name.replacen(&format!(".{t}."), ".<UDIM>.", 1),
None => f.name.clone(),
};
// Float files hold linear values; 8/16-bit colour maps are sRGB encoded.
let colorspace = if f.format.is_float() { "lin_rec709" } else { "srgb_texture" };
let colorspace = materialx::colorspace_name(opts.space_for(f.format));
if !textures.iter().any(|t| t.input == input) {
textures.push(Texture { input: input.to_owned(), file, colorspace });
}
+55 -1
View File
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use texturecraft_core::{
BlendMode, Channel, CompareOp, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, Procedural, ProceduralKind,
Source,
Project, Source,
};
use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p};
@@ -99,6 +99,8 @@ pub fn specs() -> Vec<CommandSpec> {
set
),
cmd!("effect.remove", "Remove effect", [], None, "{effect}", has_layer, remove_effect),
cmd!("effect.duplicate", "Duplicate effect", [], None, "{effect} → {effect} (the copy, just above it, pixels included)", has_layer, duplicate_effect),
cmd!("effect.move", "Move effect", [], None, "{effect, index: position in its stack, 0 = bottom (applied first)}", has_layer, move_effect),
cmd!(
"effect.histogram",
"Effect input histogram",
@@ -456,6 +458,58 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
/// The stack (a mask's or a layer's content effects) holding effect `eid`, and its position there.
fn stack_of(project: &mut Project, eid: LayerId) -> Option<(&mut Vec<Effect>, usize)> {
project.layers.values_mut().find_map(|l| {
l.mask.iter_mut().map(|m| &mut m.effects).chain(std::iter::once(&mut l.content_effects)).find_map(|list| {
let i = list.iter().position(|e| e.id == eid)?;
Some((list, i))
})
})
}
fn duplicate_effect(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "effect.duplicate";
let eid = effect_id(p, CMD)?;
let new = s.edit("Duplicate effect", |s| {
let new = s.doc.project.alloc_id();
let (list, i) = stack_of(&mut s.doc.project, eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?;
let mut e = list.get(i).cloned().ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?;
e.id = new;
e.name = format!("{} copy", e.name);
list.insert(i + 1, e);
// Painted effects keep their pixels (copy-on-write tiles: cheap).
let px = &mut s.doc.pixels;
if let Some(img) = px.masks.get(&eid).cloned() {
px.masks.insert(new, img);
}
for c in Channel::ALL {
if let Some(img) = px.layer(eid, c).cloned() {
px.layers.insert((new, c), img);
}
}
Ok(new)
})?;
if s.target == StackTarget::Effect(eid) {
s.target = StackTarget::Effect(new);
}
Ok(json!({ "effect": new.0 }))
}
fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "effect.move";
let eid = effect_id(p, CMD)?;
let index = u64p(p, "index").ok_or_else(|| bad(CMD, "`index` is required"))?;
s.edit("Move effect", |s| {
let (list, i) = stack_of(&mut s.doc.project, eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?;
let e = list.remove(i);
let to = usize::try_from(index).unwrap_or(usize::MAX).min(list.len());
list.insert(to, e);
Ok(())
})?;
Ok(Value::Null)
}
fn remove_effect(s: &mut Session, p: &Value) -> Result<Value> {
let eid = effect_id(p, "effect.remove")?;
s.edit("Remove effect", |s| {
+12
View File
@@ -601,6 +601,10 @@ impl Session {
pub fn redo_label(&self) -> Option<&str> {
self.redo.last().map(|(l, _)| l.as_str())
}
/// The undone steps, the next one to redo first.
pub fn redo_labels(&self) -> Vec<String> {
self.redo.iter().rev().map(|(l, _)| l.clone()).collect()
}
pub fn history_labels(&self) -> Vec<String> {
self.undo.iter().map(|(l, _)| l.clone()).collect()
}
@@ -629,6 +633,14 @@ impl Session {
self.modified = true;
self.revision = self.revision.wrapping_add(1);
self.invalidate_changed(other);
// An undone add or duplicate takes the selected effect away: select the stack it was in.
if let StackTarget::Effect(e) = self.target
&& self.doc.project.effect(e).is_none()
{
let p = &other.project;
let content = p.effect(e).and_then(|(owner, _)| p.layers.get(&owner)).is_some_and(|l| l.content_effects.iter().any(|x| x.id == e));
self.target = if content { StackTarget::Content } else { StackTarget::Mask };
}
}
// -----------------------------------------------------------------------------------------
+42 -5
View File
@@ -5,7 +5,7 @@ use texturecraft_core::project::ENVIRONMENTS;
use texturecraft_core::{BakedMap, Channel, ToneMapping};
use texturecraft_geom::glam::Vec3;
use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp};
use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p};
use crate::session::ViewMode;
use crate::{Result, Session, cmd};
@@ -35,14 +35,51 @@ pub fn specs() -> Vec<CommandSpec> {
pub(crate) fn edit_specs() -> Vec<CommandSpec> {
vec![
cmd!("edit.undo", "Undo", ["Edit"], Some("Ctrl+Z"), "{}", can_undo, |s, _| Ok(json!({ "undone": s.undo()? }))),
cmd!("edit.redo", "Redo", ["Edit"], Some("Ctrl+Y"), "{}", can_redo, |s, _| Ok(json!({ "redone": s.redo()? }))),
cmd!("edit.history", "History", [], None, "{}", always, |s, _| Ok(
json!({ "undo": s.history_labels(), "redo": s.redo.iter().rev().map(|(l, _)| l.clone()).collect::<Vec<_>>() })
cmd!(
"edit.undo",
"Undo",
["Edit"],
Some("Ctrl+Z"),
"{steps?: 1 (as many as there are)} → {undone: the last step undone, steps}",
can_undo,
|s, p| {
let (last, n) = repeat(s, p, Session::undo)?;
Ok(json!({ "undone": last, "steps": n }))
}
),
cmd!(
"edit.redo",
"Redo",
["Edit"],
Some("Ctrl+Y"),
"{steps?: 1 (as many as there are)} → {redone: the last step redone, steps}",
can_redo,
|s, p| {
let (last, n) = repeat(s, p, Session::redo)?;
Ok(json!({ "redone": last, "steps": n }))
}
),
cmd!("edit.history", "History", [], None, "{} → {undo: steps, oldest first, redo: undone steps, next first}", always, |s, _| Ok(
json!({ "undo": s.history_labels(), "redo": s.redo_labels() })
)),
]
}
/// Run `step` (undo or redo) `steps` times (default 1) or until the history runs out: the last
/// step's label and how many ran (the History panel jumps to a step this way).
fn repeat(s: &mut Session, p: &Value, step: fn(&mut Session) -> Result<String>) -> Result<(String, u64)> {
let steps = u64p(p, "steps").unwrap_or(1).max(1);
let mut last = step(s)?;
let mut n = 1;
while n < steps
&& let Ok(l) = step(s)
{
last = l;
n += 1;
}
Ok((last, n))
}
fn frame(s: &mut Session, _: &Value) -> Result<Value> {
let (lo, hi) = s.mesh.bounds();
s.camera.frame(lo, hi);
+43
View File
@@ -112,6 +112,49 @@ fn painting_into_a_content_paint_effect() {
assert!(center(&mut s, Channel::Roughness)[0] > 0.85);
}
#[test]
fn effects_move_within_their_stack_and_duplicate_with_their_pixels() {
let mut s = session();
let layer = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3})).unwrap(), "layer");
let paint = id(execute(&mut s, "effect.add.paint", &json!({"target": "content"})).unwrap(), "effect");
execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.9})).unwrap();
execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap();
execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap();
let fill = id(execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.2})).unwrap(), "effect");
let order = |s: &Session| s.doc.project.layer(LayerId(layer)).unwrap().content_effects.iter().map(|e| e.id.0).collect::<Vec<_>>();
assert!(close(center(&mut s, Channel::Roughness), [0.2; 3]), "the fill covers the paint");
// To the bottom, the paint shows again; an index past the end means the top.
execute(&mut s, "effect.move", &json!({"effect": fill, "index": 0})).unwrap();
assert_eq!(order(&s), [fill, paint]);
assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "{:?}", center(&mut s, Channel::Roughness));
execute(&mut s, "effect.move", &json!({"effect": fill, "index": 99})).unwrap();
assert_eq!(order(&s), [paint, fill]);
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(order(&s), [fill, paint]);
assert!(execute(&mut s, "effect.move", &json!({"effect": fill})).is_err(), "index is required");
assert!(execute(&mut s, "effect.move", &json!({"effect": 999_999, "index": 0})).is_err());
// A duplicate sits just above its original with the painted pixels, and takes the selection.
execute(&mut s, "layer.select", &json!({"layer": layer, "target": paint})).unwrap();
let copy = id(execute(&mut s, "effect.duplicate", &json!({"effect": paint})).unwrap(), "effect");
assert_eq!(order(&s), [fill, paint, copy]);
assert_eq!(s.target, StackTarget::Effect(LayerId(copy)));
assert!(s.doc.project.effect(LayerId(copy)).unwrap().1.name.ends_with(" copy"));
// Undoing it leaves no missing effect selected, but the stack it was in.
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(s.target, StackTarget::Content);
execute(&mut s, "edit.redo", &Value::Null).unwrap();
execute(&mut s, "effect.remove", &json!({"effect": paint})).unwrap();
assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "the copy keeps the strokes");
assert!(execute(&mut s, "effect.duplicate", &json!({"effect": 999_999})).is_err());
// Mask effects move within the mask.
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
let a = id(execute(&mut s, "effect.add.fill", &json!({"target": "mask", "value": 0.3})).unwrap(), "effect");
let b = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect");
execute(&mut s, "effect.move", &json!({"effect": b, "index": 0})).unwrap();
let mask: Vec<u64> = s.doc.project.layer(LayerId(layer)).unwrap().mask.as_ref().unwrap().effects.iter().map(|e| e.id.0).collect();
assert_eq!(mask, [b, a]);
}
#[test]
fn histogram_counts_what_an_effect_reads() {
let mut s = session();
@@ -0,0 +1,57 @@
//! `file.exportTextures` / `export.plan` with `colorSpace`.
use serde_json::{Value, json};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::texel::ColorSpace;
use texturecraft_engine::{Session, execute};
fn session() -> Session {
let mut s = Session::new_project("t", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap();
execute(&mut s, "layer.add.fill", &json!({ "color": [0.8, 0.2, 0.1] })).unwrap();
s
}
fn export(s: &mut Session, tag: &str, extra: Value) -> (Value, std::path::PathBuf) {
let dir = std::env::temp_dir().join(format!("tc_export_cs_{tag}_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut p = json!({ "dir": dir.display().to_string(), "preset": "glTF PBR Metal Roughness", "format": "exr", "bitDepth": 32, "padding": "infinite" });
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
(execute(s, "file.exportTextures", &p).unwrap(), dir)
}
fn first_pixel(path: &std::path::Path) -> [f32; 3] {
let img = image::open(path).unwrap().to_rgb32f();
// The plane's UV layout covers the whole image; read its middle.
let px = img.get_pixel(img.width() / 2, img.height() / 2);
[px[0], px[1], px[2]]
}
#[test]
fn colour_maps_are_written_in_the_chosen_space() {
let mut s = session();
let (plain, dir_plain) = export(&mut s, "plain", json!({}));
let (aces, dir_aces) = export(&mut s, "aces", json!({ "colorSpace": "ACEScg" }));
let base =
|r: &Value| std::path::PathBuf::from(r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).find(|f| f.contains("BaseColor")).unwrap());
let (a, b) = (first_pixel(&base(&plain)), first_pixel(&base(&aces)));
let want = ColorSpace::AcesCg.from_linear_rec709(a);
assert!((0..3).all(|k| (b[k] - want[k]).abs() < 1e-3), "{b:?} vs {want:?}");
assert!((0..3).any(|k| (a[k] - b[k]).abs() > 0.01), "the colour actually changed: {a:?} vs {b:?}");
for d in [dir_plain, dir_aces] {
let _ = std::fs::remove_dir_all(d);
}
}
#[test]
fn the_plan_reports_the_space_and_clamping_and_bad_names_are_errors() {
let mut s = session();
let plan = execute(&mut s, "export.plan", &json!({ "preset": "glTF PBR Metal Roughness", "colorSpace": "ACEScg" })).unwrap();
assert!(plan.as_array().unwrap().iter().any(|f| f["warnings"].as_array().is_some_and(|w| !w.is_empty())), "8-bit ACEScg warns: {plan}");
let float = execute(&mut s, "export.plan", &json!({ "preset": "glTF PBR Metal Roughness", "colorSpace": "ACEScg", "format": "exr" })).unwrap();
assert!(float.as_array().unwrap().iter().all(|f| f["warnings"].as_array().is_some_and(Vec::is_empty)), "{float}");
for bad in ["Display P3", "", "Rec.2020"] {
assert!(execute(&mut s, "export.plan", &json!({ "preset": "glTF PBR Metal Roughness", "colorSpace": bad })).is_err(), "{bad:?}");
}
}
+19
View File
@@ -82,6 +82,25 @@ fn float_colour_maps_are_tagged_linear() {
assert!(text.contains("_base_color.exr\" colorspace=\"lin_rec709\"") && !text.contains("srgb_texture"), "{text}");
}
#[test]
fn colour_maps_are_tagged_with_the_export_colour_space() {
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
for (space, tag, warns) in [("ACEScg", "acescg", false), ("ACES2065-1", "lin_ap0_scene", true), ("sRGB", "srgb_texture", false)] {
let dir = temp(tag);
let r = execute(
&mut s,
"file.exportTextures",
&json!({"dir": dir.display().to_string(), "preset": OPENPBR, "format": "exr", "colorSpace": space, "materialX": true}),
)
.unwrap();
let mtlx = files(&r).into_iter().find(|f| f.ends_with(".mtlx")).unwrap();
let text = std::fs::read_to_string(mtlx).unwrap();
assert!(text.contains(&format!("_base_color.exr\" colorspace=\"{tag}\"")), "{space}: {text}");
let warned = r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("ACES2065-1"));
assert_eq!(warned, warns, "{space}: {r}");
}
}
#[test]
fn sets_with_the_same_file_name_warn_instead_of_overwriting() {
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
+24
View File
@@ -69,6 +69,30 @@ fn layer_rename_and_undo() {
assert_eq!(s.doc.project.layer(layer_id).unwrap().name, "Custom Paint");
}
#[test]
fn undo_and_redo_jump_several_steps() {
let mut s = session();
let layer = s.selected_layer().unwrap();
let name = |s: &Session| s.doc.project.layer(layer).unwrap().name.clone();
let first = name(&s);
for n in ["A", "B", "C"] {
execute(&mut s, "layer.rename", &json!({"name": n})).unwrap();
}
let base = s.history_labels().len() - 3;
// Two back to "A": the undone steps wait to be redone, next first.
assert_eq!(execute(&mut s, "edit.undo", &json!({"steps": 2})).unwrap(), json!({"undone": "Rename layer", "steps": 2}));
assert_eq!(name(&s), "A");
assert_eq!(s.redo_labels().len(), 2);
assert_eq!(execute(&mut s, "edit.history", &Value::Null).unwrap()["redo"].as_array().unwrap().len(), 2);
// Forward past the end stops at "C"; back past the start stops at the first state.
assert_eq!(execute(&mut s, "edit.redo", &json!({"steps": 99})).unwrap()["steps"], 2);
assert_eq!(name(&s), "C");
let r = execute(&mut s, "edit.undo", &json!({"steps": 1_000_000})).unwrap();
assert_eq!(r["steps"].as_u64().unwrap() as usize, base + 3);
assert_eq!(name(&s), first);
assert!(execute(&mut s, "edit.undo", &json!({"steps": 2})).is_err(), "nothing left to undo");
}
#[test]
fn polygon_fill_and_color_picker() {
let mut s = session();
+54 -5
View File
@@ -20,7 +20,7 @@ use serde::{Deserialize, Serialize};
use texturecraft_compose::{BakedMaps, Composite};
use texturecraft_core::{AoMixing, BakedMap, Channel, ChannelKind, NormalFormat, NormalMixing, Project, TextureSet};
use texturecraft_geom::glam::Vec3;
use texturecraft_texel::{DilationMap, linear_to_srgb};
use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb};
use crate::{FormatError, MAX_IMAGE_SIZE, Result};
@@ -41,7 +41,7 @@ pub const FILE_TOKENS: [(&str, &str); 6] = [
("$textureSet", "Texture set name"),
("$project", "Project name"),
("$channel", "Channel or map id"),
("$colorSpace", "sRGB or linear"),
("$colorSpace", "Colour maps: sRGB, linear, ACEScg or ACES2065-1; data maps: linear"),
("$udim", "UV tile number (1001 for sets without UV tiles)"),
];
@@ -323,11 +323,31 @@ pub struct ExportOptions {
/// UV-tiled sets: one image of the whole tile atlas per map instead of a file per tile
/// (for formats without UDIM support, with the mesh's UVs in atlas space).
pub atlas: bool,
/// The colour space of the colour maps (data maps are never converted); None writes sRGB
/// into 8/16-bit files and linear Rec.709 into float files (EXR, HDR).
#[serde(skip)]
pub color_space: Option<ColorSpace>,
}
impl ExportOptions {
/// The colour space colour maps are written in when `format` is used.
pub fn space_for(&self, format: FileFormat) -> ColorSpace {
self.color_space.unwrap_or(if format.is_float() { ColorSpace::LinearRec709 } else { ColorSpace::Srgb })
}
}
impl ExportOptions {
pub fn new(preset: ExportPreset) -> ExportOptions {
ExportOptions { preset, format_override: None, bit_depth_override: None, padding: Padding::Infinite, size: None, normal_format: None, atlas: false }
ExportOptions {
preset,
format_override: None,
bit_depth_override: None,
padding: Padding::Infinite,
size: None,
normal_format: None,
atlas: false,
color_space: None,
}
}
}
@@ -462,7 +482,14 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
}
let format = opts.format_override.unwrap_or(map.format);
let bit_depth = format.depth(opts.bit_depth_override.unwrap_or(map.bit_depth));
let color_space = if is_color(map) && !format.is_float() { "sRGB" } else { "linear" };
let space = opts.space_for(format);
let color_space = match (is_color(map), space) {
(false, _) | (true, ColorSpace::LinearRec709) => "linear",
(true, ColorSpace::Srgb) => "sRGB",
(true, other) => other.name(),
};
// Integer files clamp to 0-1, which wide-gamut linear colour can leave.
let clamps = is_color(map) && !format.is_float() && matches!(space, ColorSpace::AcesCg | ColorSpace::Aces2065);
// One file per UV tile: names without `$udim` get it appended.
let template = if tiles.iter().any(Option::is_some) && !map.file.contains("$udim") { format!("{}.$udim", map.file) } else { map.file.clone() };
for &tile in &tiles {
@@ -477,6 +504,13 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
let ext = format.extension();
let mut name = format!("{stem}.{ext}");
let mut warnings = Vec::new();
if clamps {
warnings.push(format!(
"{} colours outside 0-1 are clamped in {} files; use EXR or HDR to keep them",
space.name(),
format.extension().to_uppercase()
));
}
// Case-insensitive: Windows and macOS file systems are.
let mut k = 2;
while used.contains(&name.to_ascii_lowercase()) {
@@ -697,8 +731,23 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result<Vec<Expo
let scale = |v: u32| (u64::from(v) * u64::from(opts.size.unwrap_or(tile_res)) / u64::from(tile_res)) as u32;
let size = (scale(w), scale(h));
let data = resize(data, (w, h), n, size);
let srgb: Vec<bool> = lay.iter().map(|(d, _)| *d != Dest::A && is_color(map) && !p.format.is_float()).collect();
// Colour maps leave linear Rec.709 for the chosen space. sRGB in integer files is
// encoded by `encode`; every other case is converted here (float sRGB included).
let space = opts.space_for(p.format);
let rgb = lay.len() >= 3 && lay.iter().take(3).map(|(d, _)| *d).eq([Dest::R, Dest::G, Dest::B]);
let mut data = data;
let mut warnings = p.warnings;
let convert = is_color(map) && (space != ColorSpace::Srgb || p.format.is_float()) && space != ColorSpace::LinearRec709;
if convert && rgb {
data.par_chunks_mut(n).for_each(|px| {
if let [r, g, b, ..] = px {
[*r, *g, *b] = space.from_linear_rec709([*r, *g, *b]);
}
});
} else if convert {
warnings.push(format!("\"{}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", p.name, space.name()));
}
let srgb: Vec<bool> = lay.iter().map(|(d, _)| *d != Dest::A && is_color(map) && !p.format.is_float() && space == ColorSpace::Srgb).collect();
let bytes = encode(p.format, p.bit_depth, size, n, &data, &srgb, &mut warnings)?;
Ok(ExportedFile { name: p.name, bytes, width: size.0, height: size.1, warnings })
})
+88
View File
@@ -509,3 +509,91 @@ fn lobe_channels_export_as_document_maps_and_gltf_extension_maps() {
let plain = Fx::new(&default_channels()).render_preset("glTF PBR Metal Roughness");
assert!(!plain.iter().any(|f| f.name.contains("Clearcoat") || f.name.contains("Sheen")), "sets without the lobes export no extension maps");
}
#[test]
fn colour_space_converts_colour_maps_only() {
let fx = Fx::new(&default_channels());
let preset = builtin_preset("glTF PBR Metal Roughness").unwrap();
let want_at = |space: ColorSpace, x, y| space.from_linear_rec709(fx.comp.value(Channel::BaseColor, x, y));
// ACEScg in a float EXR: the base colour is the converted triple, above-1 values aside.
let mut exr = ExportOptions::new(preset.clone());
exr.format_override = Some(FileFormat::Exr);
exr.bit_depth_override = Some(32);
exr.color_space = Some(ColorSpace::AcesCg);
let files = fx.render(&exr);
let img = decode(find(&files, "_BaseColor.exr")).to_rgb32f();
for (x, y) in [(0, 0), (10, 40), (63, 63)] {
let (px, want) = (img.get_pixel(x, y), want_at(ColorSpace::AcesCg, x, y));
assert!((0..3).all(|k| (px[k] - want[k]).abs() < 1e-4), "({x},{y}) {px:?} vs {want:?}");
}
// Data maps are never converted: roughness and metalness (packed in the ORM map) are as before.
let default_files =
fx.render(&ExportOptions { format_override: Some(FileFormat::Exr), bit_depth_override: Some(32), ..ExportOptions::new(preset.clone()) });
assert_eq!(find(&files, "OcclusionRoughnessMetallic").bytes, find(&default_files, "OcclusionRoughnessMetallic").bytes);
assert_eq!(find(&files, "_Normal").bytes, find(&default_files, "_Normal").bytes);
assert_ne!(find(&files, "_BaseColor").bytes, find(&default_files, "_BaseColor").bytes);
// Linear Rec.709 in an 8-bit PNG: the values are written without the sRGB curve.
let mut lin = ExportOptions::new(preset.clone());
lin.color_space = Some(ColorSpace::LinearRec709);
let png = decode(find(&fx.render(&lin), "_BaseColor.png"));
let v = fx.comp.value(Channel::BaseColor, 10, 40);
for k in 0..3 {
assert!((png.get_pixel(10, 40)[k] as f32 - v[k] * 255.0).abs() <= 1.0, "[{k}]");
}
// The default is unchanged: sRGB for integer files (None and explicit sRGB agree).
let default_png = fx.render(&ExportOptions::new(preset.clone()));
let mut srgb = ExportOptions::new(preset.clone());
srgb.color_space = Some(ColorSpace::Srgb);
assert_eq!(find(&default_png, "_BaseColor.png").bytes, find(&fx.render(&srgb), "_BaseColor.png").bytes);
// An explicit sRGB in a float file is encoded once, not twice.
let mut float_srgb = ExportOptions::new(preset);
float_srgb.format_override = Some(FileFormat::Exr);
float_srgb.bit_depth_override = Some(32);
float_srgb.color_space = Some(ColorSpace::Srgb);
let px = *decode(find(&fx.render(&float_srgb), "_BaseColor.exr")).to_rgb32f().get_pixel(10, 40);
assert!((px[0] - linear_to_srgb(v[0])).abs() < 1e-4, "{px:?}");
}
#[test]
fn colour_space_names_the_files_and_warns_when_integer_files_clamp() {
let fx = Fx::new(&default_channels());
let named = ExportPreset {
name: "named".into(),
maps: vec![MapSpec {
file: "$textureSet_$channel_$colorSpace".into(),
format: FileFormat::Png,
bit_depth: 8,
channels: vec![
(Dest::R, SourceRef::Channel { channel: Channel::BaseColor, component: 0 }),
(Dest::G, SourceRef::Channel { channel: Channel::BaseColor, component: 1 }),
(Dest::B, SourceRef::Channel { channel: Channel::BaseColor, component: 2 }),
],
}],
};
let plan = |space: Option<ColorSpace>, format: Option<FileFormat>| {
let opts = ExportOptions { color_space: space, format_override: format, ..ExportOptions::new(named.clone()) };
list_outputs(&fx.project, 0, "sphere", &opts).unwrap().remove(0)
};
assert!(plan(None, None).name.ends_with("_sRGB.png") && plan(None, Some(FileFormat::Exr)).name.ends_with("_linear.exr"), "defaults keep their names");
assert!(plan(Some(ColorSpace::LinearRec709), None).name.ends_with("_linear.png"));
let aces = plan(Some(ColorSpace::AcesCg), None);
assert!(aces.name.ends_with("_ACEScg.png"), "{}", aces.name);
assert!(aces.warnings.iter().any(|w| w.contains("clamped")), "{:?}", aces.warnings);
assert!(plan(Some(ColorSpace::AcesCg), Some(FileFormat::Exr)).warnings.is_empty(), "float files keep the values");
assert!(plan(None, None).warnings.is_empty() && plan(Some(ColorSpace::LinearRec709), None).warnings.is_empty());
// The planned names are the rendered names.
let opts = ExportOptions { color_space: Some(ColorSpace::Aces2065), ..ExportOptions::new(named) };
let names: Vec<String> = fx.render(&opts).into_iter().map(|f| f.name).collect();
assert_eq!(names, list_outputs(&fx.project, 0, "sphere", &opts).unwrap().into_iter().map(|p| p.name).collect::<Vec<_>>());
assert!(names[0].ends_with("_ACES2065-1.png"), "{names:?}");
}
#[test]
fn colour_packed_into_one_channel_warns_instead_of_converting_silently() {
let fx = Fx::new(&default_channels());
let preset = ExportPreset { name: "l".into(), maps: vec![gray_map("$textureSet_red", SourceRef::Channel { channel: Channel::BaseColor, component: 0 })] };
let opts = |space| ExportOptions { color_space: space, format_override: Some(FileFormat::Exr), ..ExportOptions::new(preset.clone()) };
assert!(fx.render(&opts(Some(ColorSpace::AcesCg)))[0].warnings.iter().any(|w| w.contains("ACEScg")));
assert!(fx.render(&opts(None))[0].warnings.is_empty(), "linear Rec.709 needs no conversion");
}
+16 -3
View File
@@ -9,14 +9,15 @@
//! `displacement` shader on the material and `geometry_normal` goes through a `normalmap` node
//! (OpenGL, +Y up, which is what that node expects).
//!
//! Colour textures (base, fuzz and emission colour) are tagged with their file's colour space
//! (`srgb_texture` for 8/16-bit files, `lin_rec709` for float ones); every data map is left
//! untagged (linear). UDIM sets write the `<UDIM>` filename token MaterialX defines.
//! Colour textures (base, fuzz and emission colour) are tagged with the colour space they were
//! exported in ([`colorspace_name`]); every data map is left untagged (linear). UDIM sets write the `<UDIM>` filename token MaterialX defines.
//! Texture file names are relative to the document.
use std::collections::HashSet;
use std::fmt::Write as _;
use texturecraft_texel::ColorSpace;
/// How an OpenPBR input is typed in the document.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
@@ -63,6 +64,18 @@ pub struct Texture {
pub colorspace: &'static str,
}
/// The MaterialX colour space of colour maps written in `space`. MaterialX 1.39 defines no
/// ACES2065-1 (AP0) space: it gets `lin_ap0_scene`, its name in later versions of the
/// specification, which 1.39 readers may not know.
pub fn colorspace_name(space: ColorSpace) -> &'static str {
match space {
ColorSpace::Srgb => "srgb_texture",
ColorSpace::LinearRec709 => "lin_rec709",
ColorSpace::AcesCg => "acescg",
ColorSpace::Aces2065 => "lin_ap0_scene",
}
}
/// The OpenPBR input a preset map's file template feeds (`$mesh_$textureSet_base_color` →
/// `base_color`), or None for templates this module has no place for.
pub fn input_of_template(template: &str) -> Option<&'static str> {
+217
View File
@@ -0,0 +1,217 @@
//! Built-in colour spaces as plain maths: sRGB, linear Rec.709, ACEScg and ACES2065-1.
//!
//! The conversion matrices are derived at first use from the published primaries and white points
//! (ITU-R BT.709, ACES S-2014-004 for AP1, SMPTE ST 2065-1 for AP0) with Bradford chromatic
//! adaptation, so nothing is copied from a colour-management library. TextureCraft's colour
//! channels are linear Rec.709 internally; this module converts them for export.
//!
//! Only colour is converted. Data (normal, height, roughness...) has no colour space and never
//! goes through here.
use std::sync::OnceLock;
use crate::linear_to_srgb;
/// The colour space of exported colour images.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ColorSpace {
/// sRGB-encoded (display-referred, 0–1), Rec.709 primaries.
#[default]
Srgb,
/// Scene-linear Rec.709 / sRGB primaries, D65.
LinearRec709,
/// Scene-linear ACES AP1 primaries.
AcesCg,
/// Scene-linear ACES AP0 primaries (the archival interchange space).
Aces2065,
}
impl ColorSpace {
pub const ALL: [ColorSpace; 4] = [ColorSpace::Srgb, ColorSpace::LinearRec709, ColorSpace::AcesCg, ColorSpace::Aces2065];
pub fn name(self) -> &'static str {
match self {
ColorSpace::Srgb => "sRGB",
ColorSpace::LinearRec709 => "Linear Rec.709",
ColorSpace::AcesCg => "ACEScg",
ColorSpace::Aces2065 => "ACES2065-1",
}
}
/// A space by name, ignoring case, spaces and punctuation ("linear rec709", "ap1", "srgb_texture").
pub fn from_name(name: &str) -> Option<ColorSpace> {
let key: String = name.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();
Some(match key.as_str() {
"srgb" | "srgbtexture" => ColorSpace::Srgb,
"linearrec709" | "linearsrgb" | "linear" | "rec709" => ColorSpace::LinearRec709,
"acescg" | "ap1" => ColorSpace::AcesCg,
"aces20651" | "aces2065" | "ap0" | "aces" => ColorSpace::Aces2065,
_ => return None,
})
}
/// Whether values are scene-linear light.
pub fn is_linear(self) -> bool {
self != ColorSpace::Srgb
}
fn primaries(self) -> Primaries {
match self {
ColorSpace::Srgb | ColorSpace::LinearRec709 => REC709,
ColorSpace::AcesCg => AP1,
ColorSpace::Aces2065 => AP0,
}
}
/// Linear Rec.709 `rgb` as values in this space: the primaries are converted, and sRGB
/// also gets its transfer curve (clamped to 0–1). Linear spaces keep values outside 0–1.
/// Non-finite input becomes 0.
pub fn from_linear_rec709(self, rgb: [f32; 3]) -> [f32; 3] {
let rgb = rgb.map(|v| if v.is_finite() { v } else { 0.0 });
let out = match matrix_to(self) {
Some(m) => [0, 1, 2].map(|i| m[i][0] * rgb[0] + m[i][1] * rgb[1] + m[i][2] * rgb[2]),
None => rgb,
};
if self == ColorSpace::Srgb { out.map(linear_to_srgb) } else { out }
}
}
type M3 = [[f64; 3]; 3];
#[derive(Clone, Copy)]
struct Primaries {
r: [f64; 2],
g: [f64; 2],
b: [f64; 2],
white: [f64; 2],
}
const D65: [f64; 2] = [0.3127, 0.3290];
const D60_ACES: [f64; 2] = [0.32168, 0.33767];
const REC709: Primaries = Primaries { r: [0.640, 0.330], g: [0.300, 0.600], b: [0.150, 0.060], white: D65 };
const AP1: Primaries = Primaries { r: [0.713, 0.293], g: [0.165, 0.830], b: [0.128, 0.044], white: D60_ACES };
const AP0: Primaries = Primaries { r: [0.7347, 0.2653], g: [0.0, 1.0], b: [0.0001, -0.0770], white: D60_ACES };
const BRADFORD: M3 = [[0.8951, 0.2664, -0.1614], [-0.7502, 1.7135, 0.0367], [0.0389, -0.0685, 1.0296]];
fn mul(a: &M3, b: &M3) -> M3 {
let mut o = [[0.0; 3]; 3];
for (i, row) in o.iter_mut().enumerate() {
for (j, v) in row.iter_mut().enumerate() {
*v = (0..3).map(|k| a[i][k] * b[k][j]).sum();
}
}
o
}
fn apply(m: &M3, v: [f64; 3]) -> [f64; 3] {
[0, 1, 2].map(|i| m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2])
}
fn inverse(m: &M3) -> Option<M3> {
let c = |r: usize, c: usize| {
let (r1, r2) = ((r + 1) % 3, (r + 2) % 3);
let (c1, c2) = ((c + 1) % 3, (c + 2) % 3);
m[r1][c1] * m[r2][c2] - m[r1][c2] * m[r2][c1]
};
let det = m[0][0] * c(0, 0) + m[0][1] * c(0, 1) + m[0][2] * c(0, 2);
if det.abs() < 1e-12 || !det.is_finite() {
return None;
}
let mut o = [[0.0; 3]; 3];
for (i, row) in o.iter_mut().enumerate() {
for (j, v) in row.iter_mut().enumerate() {
*v = c(j, i) / det;
}
}
Some(o)
}
fn xy_to_xyz(xy: [f64; 2]) -> [f64; 3] {
[xy[0] / xy[1], 1.0, (1.0 - xy[0] - xy[1]) / xy[1]]
}
/// RGB (linear) to XYZ for a set of primaries, scaled so white maps to the white point.
fn rgb_to_xyz(p: &Primaries) -> Option<M3> {
let (r, g, b) = (xy_to_xyz(p.r), xy_to_xyz(p.g), xy_to_xyz(p.b));
let cols = [[r[0], g[0], b[0]], [r[1], g[1], b[1]], [r[2], g[2], b[2]]];
let s = apply(&inverse(&cols)?, xy_to_xyz(p.white));
Some([[r[0] * s[0], g[0] * s[1], b[0] * s[2]], [r[1] * s[0], g[1] * s[1], b[1] * s[2]], [r[2] * s[0], g[2] * s[1], b[2] * s[2]]])
}
/// Bradford chromatic adaptation from one white point to another.
fn adapt(from: [f64; 2], to: [f64; 2]) -> Option<M3> {
let (cs, cd) = (apply(&BRADFORD, xy_to_xyz(from)), apply(&BRADFORD, xy_to_xyz(to)));
let scale = [[cd[0] / cs[0], 0.0, 0.0], [0.0, cd[1] / cs[1], 0.0], [0.0, 0.0, cd[2] / cs[2]]];
Some(mul(&inverse(&BRADFORD)?, &mul(&scale, &BRADFORD)))
}
/// The matrix from linear Rec.709 to the linear primaries of `to` (cached).
fn matrix_to(to: ColorSpace) -> Option<[[f32; 3]; 3]> {
static CACHE: OnceLock<[Option<[[f32; 3]; 3]>; 4]> = OnceLock::new();
let table = CACHE.get_or_init(|| {
ColorSpace::ALL.map(|s| {
let (from, to) = (REC709, s.primaries());
let m = mul(&inverse(&rgb_to_xyz(&to)?)?, &mul(&adapt(from.white, to.white)?, &rgb_to_xyz(&from)?));
Some(m.map(|r| r.map(|v| v as f32)))
})
});
let i = ColorSpace::ALL.iter().position(|s| *s == to)?;
table.get(i).copied().flatten()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::srgb_to_linear;
fn close(a: [f32; 3], b: [f32; 3], tol: f32) -> bool {
a.iter().zip(b).all(|(x, y)| (x - y).abs() <= tol)
}
#[test]
fn white_stays_white_in_every_linear_space() {
for s in [ColorSpace::LinearRec709, ColorSpace::AcesCg, ColorSpace::Aces2065] {
assert!(close(s.from_linear_rec709([1.0; 3]), [1.0; 3], 1e-4), "{s:?}");
}
assert!(close(ColorSpace::Srgb.from_linear_rec709([1.0; 3]), [1.0; 3], 1e-5));
}
#[test]
fn rec709_primaries_in_acescg_match_published_values() {
// Rec.709 red in ACEScg (AP1, D60): the widely published 0.6131 0.0702 0.0206.
assert!(close(ColorSpace::AcesCg.from_linear_rec709([1.0, 0.0, 0.0]), [0.6131, 0.0702, 0.0206], 2e-3));
// And in ACES2065-1 (AP0): 0.4397 0.0897 0.0175.
assert!(close(ColorSpace::Aces2065.from_linear_rec709([1.0, 0.0, 0.0]), [0.4397, 0.0897, 0.0175], 2e-3));
}
#[test]
fn grey_stays_neutral_and_srgb_is_the_transfer_curve() {
for s in ColorSpace::ALL {
let o = s.from_linear_rec709([0.18; 3]);
assert!(close(o, [o[0]; 3], 1e-4), "{s:?} {o:?}");
}
assert!(close(ColorSpace::Srgb.from_linear_rec709([0.5; 3]), [linear_to_srgb(0.5); 3], 1e-6));
assert!((srgb_to_linear(ColorSpace::Srgb.from_linear_rec709([0.25; 3])[0]) - 0.25).abs() < 1e-5);
assert_eq!(ColorSpace::LinearRec709.from_linear_rec709([0.3, 2.0, -1.0]), [0.3, 2.0, -1.0], "linear Rec.709 is the identity, values above 1 kept");
}
#[test]
fn hostile_values_stay_finite() {
for s in ColorSpace::ALL {
assert!(s.from_linear_rec709([f32::NAN, f32::INFINITY, f32::NEG_INFINITY]).iter().all(|v| v.is_finite()), "{s:?}");
}
}
#[test]
fn names_round_trip_and_aliases_work() {
for s in ColorSpace::ALL {
assert_eq!(ColorSpace::from_name(s.name()), Some(s));
}
assert_eq!(ColorSpace::from_name("srgb_texture"), Some(ColorSpace::Srgb));
assert_eq!(ColorSpace::from_name("AP1"), Some(ColorSpace::AcesCg));
assert_eq!(ColorSpace::from_name("linear"), Some(ColorSpace::LinearRec709));
assert_eq!(ColorSpace::from_name("nope"), None);
assert!(!ColorSpace::Srgb.is_linear() && ColorSpace::AcesCg.is_linear());
}
}
+2
View File
@@ -6,10 +6,12 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod colorspace;
pub mod dilate;
pub mod noise;
pub mod tile;
pub use colorspace::ColorSpace;
pub use dilate::DilationMap;
pub use tile::{TILE, TILE_AREA, TileData, TileImage, from_u16, from_u16_signed, to_u16, to_u16_signed};
+41 -8
View File
@@ -5,7 +5,7 @@ use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2};
use egui_phosphor::regular as ic;
use serde_json::{Value, json};
use texturecraft_engine::core::{
BakedMap, BlendMode, Channel, Decal, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, ProceduralKind, Source,
BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, ProceduralKind, Source,
};
use texturecraft_engine::filter_lib::{FILTERS, scalar_params};
use texturecraft_engine::paint::{BrushAlpha, alphas};
@@ -255,11 +255,11 @@ fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize)
let Some(layer) = app.session.doc.project.layers.get(&id).cloned() else { return };
layer_row(app, ui, &layer, depth);
for e in layer.content_effects.iter().rev() {
effect_row(app, ui, &layer, e.id, &e.name, e.visible, depth + 1, ic::SPHERE);
effect_row(app, ui, &layer, &layer.content_effects, e, depth + 1, ic::SPHERE);
}
if let Some(m) = &layer.mask {
for e in m.effects.iter().rev() {
effect_row(app, ui, &layer, e.id, &e.name, e.visible, depth + 1, ic::MAGIC_WAND);
effect_row(app, ui, &layer, &m.effects, e, depth + 1, ic::MAGIC_WAND);
}
}
if let LayerKind::Group { children, collapsed } = &layer.kind
@@ -522,12 +522,16 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
resp.context_menu(|ui| layer_context_menu(app, ui, layer));
}
/// One effect of a layer's content (`glyph` sphere) or mask (`glyph` wand) stack.
#[allow(clippy::too_many_arguments)]
fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId, name: &str, visible: bool, depth: usize, glyph: &str) {
/// The drag-and-drop payload of an effect row (the effect id).
struct EffectDrag(u64);
/// Effect `e` of `stack`, a layer's content (`glyph` sphere) or mask (`glyph` wand) effects.
fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, depth: usize, glyph: &str) {
let tk = Tokens::get(ui.ctx());
let (eid, visible) = (e.id, e.visible);
let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(eid);
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag());
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &e.name));
let p = ui.painter().clone();
p.rect_filled(
rect.shrink2(vec2(0.0, 1.0)),
@@ -548,13 +552,40 @@ fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerI
let er = ui.interact(eye, ui.scope_id().with(("eff_eye", eid.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect"));
p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(12.0), tk.text_dim);
p.text(pos2(x0 + 22.0, rect.center().y), egui::Align2::LEFT_CENTER, glyph, egui::FontId::proportional(11.0), tk.text_dim);
p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(11.5), tk.text);
p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, &e.name, egui::FontId::proportional(11.5), tk.text);
if er.clicked() {
app.run("effect.set", json!({"effect": eid.0, "visible": !visible}));
} else if resp.clicked() {
app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0}));
}
// Drag to reorder within the stack: a drop lands above this row, or below it from its lower half.
if resp.drag_started() {
resp.dnd_set_drag_payload(EffectDrag(eid.0));
}
let pos = |id: u64| stack.iter().position(|x| x.id.0 == id);
let below = ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| p.y > rect.center().y);
if resp.dnd_hover_payload::<EffectDrag>().is_some_and(|src| src.0 != eid.0 && pos(src.0).is_some()) {
let y = if below { rect.bottom() } else { rect.top() };
p.line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(2.0, tk.accent));
}
if let Some(src) = dnd_release::<EffectDrag>(&resp)
&& let (Some(from), Some(to)) = (pos(src.0), pos(eid.0))
&& from != to
{
// Rows list the stack top first, so above this row is the next index up.
let index = match (from < to, below) {
(true, false) | (false, true) => to,
(true, true) => to - 1,
(false, false) => to + 1,
};
app.run("effect.move", json!({"effect": src.0, "index": index}));
}
resp.context_menu(|ui| {
if ui.button(tr("Duplicate effect")).clicked() {
app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0}));
app.run("effect.duplicate", json!({"effect": eid.0}));
ui.close();
}
if ui.button(tr("Remove effect")).clicked() {
app.run("effect.remove", json!({"effect": eid.0}));
ui.close();
@@ -1056,6 +1087,8 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) {
fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) {
let b = &mut app.session.tool.brush;
ui.label(caption(tr("Brush")));
let hint = tr("Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.");
ui.label(RichText::new(hint).size(10.5).color(Tokens::get(ui.ctx()).text_dim));
section(ui, "sec_size", tr("Size"), true, |ui| {
let mut size = b.size / 0.25 * 100.0;
if slider(ui, tr("Size"), &mut size, 0.05..=100.0, 1).changed() {
+7
View File
@@ -206,6 +206,10 @@ pub const TABLE: &[(&str, &str)] = &[
("Crate", "صندوق"),
("Create", "إنشاء"),
("Create smart material", "إنشاء مادة ذكية"),
(
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
"Ctrl+السحب بالزر الأيمن في عرض يضبط الحجم والصلابة، وCtrl+السحب بالزر الأيسر يضبط التدفق والزاوية.",
),
("Cube", "مكعب"),
("Current layer", "الطبقة الحالية"),
("Curvature", "الانحناء"),
@@ -265,6 +269,7 @@ pub const TABLE: &[(&str, &str)] = &[
),
("Drop an image from the Assets panel here to use it as this mesh map", "أفلت صورة من لوحة الأصول هنا لاستخدامها كخريطة المجسم هذه"),
("Dry streaks", "خطوط جافة"),
("Duplicate effect", "تكرار التأثير"),
("Duplicate layer(s)", "تكرار الطبقة (الطبقات)"),
("Duplicate the selected template", "تكرار القالب المحدد"),
("Edge Detect", "اكتشاف الحواف"),
@@ -528,6 +533,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal from height", "ناظم من الارتفاع"),
("Normal map combine", "دمج خرائط النواظم"),
("Normal map detail", "تفاصيل خريطة النواظم"),
("Color space", "فضاء الألوان"),
("Normal map format", "صيغة خريطة النواظم"),
("Normal map inverse detail", "عكس تفاصيل خريطة النواظم"),
("Normal: painting uses the flat normal", "عادي: يستخدم الرسم الناظم المسطح"),
@@ -659,6 +665,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Resizing", "تغيير الحجم"),
("Restore every default shortcut", "استعادة كل الاختصارات الافتراضية"),
("Return to painting mode", "العودة إلى نمط الرسم"),
("Return to this step", "العودة إلى هذه الخطوة"),
("Right-click a layer > Create smart material", "انقر بزر الفأرة الأيمن على طبقة > إنشاء مادة ذكية"),
("Rotation", "التدوير"),
("Rotation (degrees)", "التدوير (بالدرجات)"),
+7
View File
@@ -218,6 +218,10 @@ pub const TABLE: &[(&str, &str)] = &[
("Crate", "Kiste"),
("Create", "Erstellen"),
("Create smart material", "Smart-Material erstellen"),
(
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
"Strg+Ziehen mit RMT in einer Ansicht stellt Größe und Härte ein, Strg+Ziehen mit LMT Fluss und Winkel.",
),
("Cube", "Würfel"),
("Current layer", "Aktuelle Ebene"),
("Curvature", "Krümmung"),
@@ -286,6 +290,7 @@ pub const TABLE: &[(&str, &str)] = &[
"Ein Bild aus dem Assets-Panel hier ablegen, um es als diese Mesh-Map zu verwenden",
),
("Dry streaks", "Trockene Schlieren"),
("Duplicate effect", "Effekt duplizieren"),
("Duplicate layer(s)", "Ebene(n) duplizieren"),
("Duplicate the selected template", "Ausgewählte Vorlage duplizieren"),
("Edge Detect", "Kantenerkennung"),
@@ -558,6 +563,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal from height", "Normale aus Höhe"),
("Normal map combine", "Normal-Map kombinieren"),
("Normal map detail", "Normal-Map-Detail"),
("Color space", "Farbraum"),
("Normal map format", "Normal-Map-Format"),
("Normal map inverse detail", "Normal-Map-Detail invertiert"),
("Normal: painting uses the flat normal", "Normale: Malen verwendet die flache Normale"),
@@ -701,6 +707,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Resizing", "Größe wird geändert"),
("Restore every default shortcut", "Alle Standard-Tastenkürzel wiederherstellen"),
("Return to painting mode", "Zurück zum Malmodus"),
("Return to this step", "Zu diesem Schritt zurückkehren"),
("Right-click a layer > Create smart material", "Rechtsklick auf eine Ebene > Smart-Material erstellen"),
("Rotation", "Drehung"),
("Rotation (degrees)", "Drehung (Grad)"),
+7
View File
@@ -215,6 +215,10 @@ pub const TABLE: &[(&str, &str)] = &[
("Crate", "Caja"),
("Create", "Crear"),
("Create smart material", "Crear material inteligente"),
(
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
"Ctrl+arrastrar con botón der. en una vista ajusta el tamaño y la dureza; Ctrl+arrastrar con botón izq., el flujo y el ángulo.",
),
("Cube", "Cubo"),
("Current layer", "Capa actual"),
("Curvature", "Curvatura"),
@@ -280,6 +284,7 @@ pub const TABLE: &[(&str, &str)] = &[
),
("Drop an image from the Assets panel here to use it as this mesh map", "Suelta aquí una imagen del panel Recursos para usarla como este mapa de malla"),
("Dry streaks", "Trazos secos"),
("Duplicate effect", "Duplicar efecto"),
("Duplicate layer(s)", "Duplicar capa(s)"),
("Duplicate the selected template", "Duplicar la plantilla seleccionada"),
("Edge Detect", "Detección de bordes"),
@@ -549,6 +554,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal from height", "Normal desde altura"),
("Normal map combine", "Combinar mapa de normales"),
("Normal map detail", "Detalle de mapa de normales"),
("Color space", "Espacio de color"),
("Normal map format", "Formato del mapa de normales"),
("Normal map inverse detail", "Detalle inverso de mapa de normales"),
("Normal: painting uses the flat normal", "Normal: la pintura usa la normal plana"),
@@ -689,6 +695,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Resizing", "Redimensionando"),
("Restore every default shortcut", "Restaurar todos los atajos predeterminados"),
("Return to painting mode", "Volver al modo de pintura"),
("Return to this step", "Volver a este paso"),
("Right-click a layer > Create smart material", "Clic derecho en una capa > Crear material inteligente"),
("Rotation", "Rotación"),
("Rotation (degrees)", "Rotación (grados)"),
+7
View File
@@ -218,6 +218,10 @@ pub const TABLE: &[(&str, &str)] = &[
("Crate", "Caisse"),
("Create", "Créer"),
("Create smart material", "Créer un matériau intelligent"),
(
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
"Ctrl+glisser (clic droit) dans une vue règle la taille et la dureté, Ctrl+glisser (clic gauche) le flux et l'angle.",
),
("Cube", "Cube"),
("Current layer", "Calque actuel"),
("Curvature", "Courbure"),
@@ -286,6 +290,7 @@ pub const TABLE: &[(&str, &str)] = &[
"Déposez ici une image du panneau Ressources pour l'utiliser comme cette carte de maillage",
),
("Dry streaks", "Traînées sèches"),
("Duplicate effect", "Dupliquer l'effet"),
("Duplicate layer(s)", "Dupliquer le(s) calque(s)"),
("Duplicate the selected template", "Dupliquer le modèle sélectionné"),
("Edge Detect", "Détection des contours"),
@@ -561,6 +566,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal from height", "Normale depuis la hauteur"),
("Normal map combine", "Normales : combinaison"),
("Normal map detail", "Normales : détail"),
("Color space", "Espace colorimétrique"),
("Normal map format", "Format de carte de normales"),
("Normal map inverse detail", "Normales : détail inverse"),
("Normal: painting uses the flat normal", "Normal : la peinture utilise la normale plate"),
@@ -701,6 +707,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Resizing", "Redimensionnement"),
("Restore every default shortcut", "Restaurer tous les raccourcis par défaut"),
("Return to painting mode", "Revenir au mode peinture"),
("Return to this step", "Revenir à cette étape"),
("Right-click a layer > Create smart material", "Clic droit sur un calque > Créer un matériau intelligent"),
("Rotation", "Rotation"),
("Rotation (degrees)", "Rotation (degrés)"),
+7
View File
@@ -221,6 +221,10 @@ pub const TABLE: &[(&str, &str)] = &[
("Crate", "Cassa"),
("Create", "Crea"),
("Create smart material", "Crea materiale intelligente"),
(
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
"Ctrl+trascina con il tasto destro in una vista per regolare dimensione e durezza, con il sinistro flusso e angolo.",
),
("Cube", "Cubo"),
("Current layer", "Livello corrente"),
("Curvature", "Curvatura"),
@@ -286,6 +290,7 @@ pub const TABLE: &[(&str, &str)] = &[
),
("Drop an image from the Assets panel here to use it as this mesh map", "Rilascia qui un'immagine dal pannello Risorse per usarla come questa mappa mesh"),
("Dry streaks", "Striature secche"),
("Duplicate effect", "Duplica effetto"),
("Duplicate layer(s)", "Duplica livello/i"),
("Duplicate the selected template", "Duplica il modello selezionato"),
("Edge Detect", "Rilevamento bordi"),
@@ -555,6 +560,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal from height", "Normale da altezza"),
("Normal map combine", "Combina mappa normali"),
("Normal map detail", "Dettaglio mappa normali"),
("Color space", "Spazio colore"),
("Normal map format", "Formato mappa normali"),
("Normal map inverse detail", "Dettaglio inverso mappa normali"),
("Normal: painting uses the flat normal", "Normale: la pittura usa la normale piatta"),
@@ -698,6 +704,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Resizing", "Ridimensionamento"),
("Restore every default shortcut", "Ripristina tutte le scorciatoie predefinite"),
("Return to painting mode", "Torna alla modalità pittura"),
("Return to this step", "Torna a questo passaggio"),
("Right-click a layer > Create smart material", "Clic destro su un livello > Crea materiale intelligente"),
("Rotation", "Rotazione"),
("Rotation (degrees)", "Rotazione (gradi)"),
+7
View File
@@ -218,6 +218,10 @@ pub const TABLE: &[(&str, &str)] = &[
("Crate", "木箱"),
("Create", "作成"),
("Create smart material", "スマートマテリアルを作成"),
(
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
"ビューでCtrl+右ドラッグでサイズと硬さ、Ctrl+左ドラッグでフローと角度を設定します。",
),
("Cube", "立方体"),
("Current layer", "現在のレイヤー"),
("Curvature", "曲率"),
@@ -274,6 +278,7 @@ pub const TABLE: &[(&str, &str)] = &[
),
("Drop an image from the Assets panel here to use it as this mesh map", "アセットパネルから画像をここにドロップすると、このメッシュマップとして使用します"),
("Dry streaks", "かすれ"),
("Duplicate effect", "エフェクトを複製"),
("Duplicate layer(s)", "レイヤーを複製"),
("Duplicate the selected template", "選択中のテンプレートを複製"),
("Edge Detect", "エッジ検出"),
@@ -540,6 +545,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal from height", "ハイトからノーマル"),
("Normal map combine", "ノーマルマップ合成"),
("Normal map detail", "ノーマルマップ ディテール"),
("Color space", "カラースペース"),
("Normal map format", "ノーマルマップ形式"),
("Normal map inverse detail", "ノーマルマップ 逆ディテール"),
("Normal: painting uses the flat normal", "ノーマル: ペイントにはフラットな法線を使用"),
@@ -677,6 +683,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Resizing", "サイズ変更中"),
("Restore every default shortcut", "すべてのショートカットをデフォルトに戻す"),
("Return to painting mode", "ペイントモードに戻る"),
("Return to this step", "このステップに戻る"),
("Right-click a layer > Create smart material", "レイヤーを右クリック > スマートマテリアルを作成"),
("Rotation", "回転"),
("Rotation (degrees)", "回転 (度)"),
+7
View File
@@ -209,6 +209,10 @@ pub const TABLE: &[(&str, &str)] = &[
("Crate", "상자"),
("Create", "만들기"),
("Create smart material", "스마트 머티리얼 만들기"),
(
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
"뷰에서 Ctrl+오른쪽 드래그로 크기와 경도를, Ctrl+왼쪽 드래그로 흐름과 각도를 설정합니다.",
),
("Cube", "큐브"),
("Current layer", "현재 레이어"),
("Curvature", "곡률"),
@@ -271,6 +275,7 @@ pub const TABLE: &[(&str, &str)] = &[
),
("Drop an image from the Assets panel here to use it as this mesh map", "에셋 패널의 이미지를 여기에 놓으면 이 메시 맵으로 사용합니다"),
("Dry streaks", "마른 붓자국"),
("Duplicate effect", "이펙트 복제"),
("Duplicate layer(s)", "레이어 복제"),
("Duplicate the selected template", "선택한 템플릿을 복제합니다"),
("Edge Detect", "가장자리 검출"),
@@ -534,6 +539,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal from height", "높이에서 노멀"),
("Normal map combine", "노멀 맵 결합"),
("Normal map detail", "노멀 맵 디테일"),
("Color space", "색 공간"),
("Normal map format", "노멀 맵 형식"),
("Normal map inverse detail", "노멀 맵 역 디테일"),
("Normal: painting uses the flat normal", "노멀: 평면 노멀로 페인팅합니다"),
@@ -668,6 +674,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Resizing", "크기 조정 중"),
("Restore every default shortcut", "모든 기본 단축키를 복원합니다"),
("Return to painting mode", "페인팅 모드로 돌아가기"),
("Return to this step", "이 단계로 돌아가기"),
("Right-click a layer > Create smart material", "레이어 마우스 오른쪽 클릭 > 스마트 머티리얼 만들기"),
("Rotation", "회전"),
("Rotation (degrees)", "회전 (도)"),
+7
View File
@@ -215,6 +215,10 @@ pub const TABLE: &[(&str, &str)] = &[
("Crate", "Caixote"),
("Create", "Criar"),
("Create smart material", "Criar material inteligente"),
(
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
"Ctrl+arrastar com botão direito em uma vista ajusta o tamanho e a dureza; Ctrl+arrastar com botão esquerdo, o fluxo e o ângulo.",
),
("Cube", "Cubo"),
("Current layer", "Camada atual"),
("Curvature", "Curvatura"),
@@ -280,6 +284,7 @@ pub const TABLE: &[(&str, &str)] = &[
),
("Drop an image from the Assets panel here to use it as this mesh map", "Solte aqui uma imagem do painel Recursos para usá-la como este mapa de malha"),
("Dry streaks", "Estrias secas"),
("Duplicate effect", "Duplicar efeito"),
("Duplicate layer(s)", "Duplicar camada(s)"),
("Duplicate the selected template", "Duplicar o modelo selecionado"),
("Edge Detect", "Detecção de bordas"),
@@ -546,6 +551,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal from height", "Normal a partir da altura"),
("Normal map combine", "Combinação de mapa normal"),
("Normal map detail", "Detalhe de mapa normal"),
("Color space", "Espaço de cor"),
("Normal map format", "Formato do mapa normal"),
("Normal map inverse detail", "Detalhe inverso de mapa normal"),
("Normal: painting uses the flat normal", "Normal: a pintura usa a normal plana"),
@@ -686,6 +692,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Resizing", "Redimensionando"),
("Restore every default shortcut", "Restaurar todos os atalhos padrão"),
("Return to painting mode", "Voltar ao modo de pintura"),
("Return to this step", "Voltar a esta etapa"),
("Right-click a layer > Create smart material", "Clique com o botão direito em uma camada > Criar material inteligente"),
("Rotation", "Rotação"),
("Rotation (degrees)", "Rotação (graus)"),
+7
View File
@@ -188,6 +188,10 @@ pub const TABLE: &[(&str, &str)] = &[
("Crate", "箱子"),
("Create", "创建"),
("Create smart material", "创建智能材质"),
(
"Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.",
"在视图中按住 Ctrl 右键拖动可调整大小和硬度,Ctrl 左键拖动可调整流量和角度。",
),
("Cube", "立方体"),
("Current layer", "当前图层"),
("Curvature", "曲率"),
@@ -241,6 +245,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", "绘制纹理集“{set}”的 {name}。对源的编辑会显示在每个实例中。"),
("Drop an image from the Assets panel here to use it as this mesh map", "将资产面板中的图像拖放到此处,用作此网格贴图"),
("Dry streaks", "干笔条纹"),
("Duplicate effect", "创建效果副本"),
("Duplicate layer(s)", "创建图层副本"),
("Duplicate the selected template", "创建所选模板的副本"),
("Edge Detect", "边缘检测"),
@@ -489,6 +494,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal from height", "由高度生成法线"),
("Normal map combine", "法线贴图合并"),
("Normal map detail", "法线贴图细节"),
("Color space", "色彩空间"),
("Normal map format", "法线贴图格式"),
("Normal map inverse detail", "法线贴图反向细节"),
("Normal: painting uses the flat normal", "法线:绘画使用平坦法线"),
@@ -617,6 +623,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Resizing", "正在调整大小"),
("Restore every default shortcut", "恢复所有默认快捷键"),
("Return to painting mode", "返回绘画模式"),
("Return to this step", "返回到此步骤"),
("Right-click a layer > Create smart material", "右键单击图层 > 创建智能材质"),
("Rotation", "旋转"),
("Rotation (degrees)", "旋转(度)"),
+4
View File
@@ -183,6 +183,9 @@ pub struct ExportUi {
pub size: u32,
/// "" (project), openGl or directX.
pub normal_format: String,
/// "" (by file format: sRGB, or linear for float files), or a colour space name.
#[serde(default)]
pub color_space: String,
/// Texture sets excluded from export.
pub skip: Vec<usize>,
pub tab: u8,
@@ -205,6 +208,7 @@ impl Default for ExportUi {
dilation: 16,
size: 0,
normal_format: String::new(),
color_space: String::new(),
skip: Vec::new(),
tab: 0,
draft: None,
+77 -8
View File
@@ -199,14 +199,16 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
app.session.viewport = Vec2::new(size.x.max(16.0), size.y.max(16.0));
let (alt, shift) = ui.input(|i| (i.modifiers.alt, i.modifiers.shift));
let local = |p: egui::Pos2| Vec2::new(p.x - rect.left(), p.y - rect.top());
let navigating = alt || ui.input(|i| i.pointer.middle_down() || i.pointer.secondary_down());
let adjusting = brush_drag(app, ui, &resp);
let navigating = !adjusting && (alt || ui.input(|i| i.pointer.middle_down() || i.pointer.secondary_down()));
// Navigation (S + drag manipulates the projection stencil instead, below).
let delta = ui.input(|i| i.pointer.delta());
let s_held = ui.input(|i| i.key_down(egui::Key::S)) && !ui.ctx().egui_wants_keyboard_input();
let stencil_drag = s_held && app.session.tool.stencil.is_some();
if stencil_drag {
// The stencil moves, turns and scales instead of the camera (handled below).
if stencil_drag || adjusting {
// The stencil moves, turns and scales instead of the camera (handled below), or the
// brush changes.
} else if resp.dragged_by(PointerButton::Middle) {
app.session.camera.pan(delta.x / size.y, delta.y / size.y);
} else if alt && resp.dragged_by(PointerButton::Primary) {
@@ -302,8 +304,15 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
// The selected decal's frame and handles: drag to move, scale or turn it.
let decal_drag = !alt && !s_held && !v_held && !focus_pick && placing.is_none() && touch.is_none() && decal_input(app, ui, &resp, rect);
// Painting.
let painting =
app.ui.mode == crate::state::Mode::Painting && !alt && !s_held && !v_held && !focus_pick && placing.is_none() && touch.is_none() && !decal_drag;
let painting = app.ui.mode == crate::state::Mode::Painting
&& !alt
&& !adjusting
&& !s_held
&& !v_held
&& !focus_pick
&& placing.is_none()
&& touch.is_none()
&& !decal_drag;
let path_tool = app.session.tool.tool == Tool::Path;
let vp = app.session.viewport;
let show = |app: &TextureCraftApp, p: Vec3| project(app, rect, p);
@@ -368,8 +377,9 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
if app.ui.mode == crate::state::Mode::Painting
&& !navigating
&& resp.hovered()
&& matches!(app.session.tool.tool, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path)
&& let Some(hp) = resp.hover_pos()
&& brush_tool(app.session.tool.tool)
// While a Ctrl+drag changes the brush, its cursor stays where the drag began.
&& let Some(hp) = if adjusting { ui.input(|i| i.pointer.press_origin()) } else { resp.hover_pos() }
&& let Some(hit) = app.session.pick(local(hp), app.session.viewport)
{
ui.ctx().set_cursor_icon(egui::CursorIcon::None);
@@ -392,6 +402,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
}
stencil_overlay(app, ui, rect);
decal_overlay(app, ui, rect);
brush_readout(app, ui, &resp, adjusting);
if app.session.quick_mask.editing {
ui.painter_at(rect).text(
rect.left_top() + vec2(12.0, 40.0),
@@ -754,6 +765,62 @@ fn clone_marker(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3) {
}
}
/// Tools that paint with the brush (and show its cursor).
fn brush_tool(t: Tool) -> bool {
matches!(t, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path)
}
/// Ctrl (Cmd on macOS) + drag in a view changes the brush instead of painting or navigating: a
/// right drag its size (left/right) and hardness (up/down), a left drag its flow and angle. True
/// while Ctrl is held with a brush tool and no stroke is under way.
fn brush_drag(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response) -> bool {
let held =
app.ui.mode == crate::state::Mode::Painting && brush_tool(app.session.tool.tool) && !app.session.stroke_active() && ui.input(|i| i.modifiers.command);
if held && let Some(right) = brush_drag_button(resp) {
adjust_brush(&mut app.session.tool.brush, right, ui.input(|i| i.pointer.delta()));
}
held
}
/// The button of a drag on `resp`: Some(true) right, Some(false) left.
fn brush_drag_button(resp: &egui::Response) -> Option<bool> {
let right = resp.dragged_by(PointerButton::Secondary);
(right || resp.dragged_by(PointerButton::Primary)).then_some(right)
}
/// While a Ctrl+drag changes the brush, its values beside where the drag began (drawn over the
/// view; the tool bar and Properties show them too).
fn brush_readout(app: &TextureCraftApp, ui: &Ui, resp: &egui::Response, adjusting: bool) {
let Some(right) = brush_drag_button(resp).filter(|_| adjusting) else { return };
let Some(at) = ui.input(|i| i.pointer.press_origin()) else { return };
// The pointer would cover the values; the brush cursor stays where the drag began.
ui.ctx().set_cursor_icon(egui::CursorIcon::None);
let b = &app.session.tool.brush;
let text = if right {
format!("{} {:.1} {} {:.0}", tr("Size"), b.size / 0.25 * 100.0, tr("Hardness"), b.hardness * 100.0)
} else {
format!("{} {:.0} {} {:.0}°", tr("Flow"), b.flow * 100.0, tr("Angle"), b.angle)
};
let tk = Tokens::get(ui.ctx());
let p = ui.painter_at(resp.rect);
let g = p.layout_no_wrap(text, egui::FontId::proportional(12.0), tk.text_strong);
let r = Rect::from_min_size(at + vec2(18.0, -30.0), g.size()).expand2(vec2(6.0, 3.0));
p.rect_filled(r, 3.0, tk.panel);
p.galley(r.min + vec2(6.0, 3.0), g, tk.text_strong);
}
/// Brush change for a Ctrl+drag by `d` points: `right` sets the size (x) and hardness (y), else
/// the flow (x) and angle (y); dragging up raises hardness and angle.
fn adjust_brush(b: &mut texturecraft_engine::paint::BrushSettings, right: bool, d: egui::Vec2) {
if right {
b.size = (b.size * (1.0 + d.x * 0.005)).clamp(0.0005, 0.25);
b.hardness = (b.hardness - d.y * 0.005).clamp(0.0, 0.999);
} else {
b.flow = (b.flow + d.x * 0.005).clamp(0.0, 1.0);
b.angle = (b.angle - d.y * 0.5 + 180.0).rem_euclid(360.0) - 180.0;
}
}
fn brush_cursor(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3, nrm: Vec3) {
let (lo, hi) = app.session.mesh.bounds();
let r = app.session.tool.brush.size * (hi - lo).length();
@@ -791,6 +858,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
let resp = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag());
let size = rect.size();
let alt = ui.input(|i| i.modifiers.alt);
let adjusting = brush_drag(app, ui, &resp);
let delta = ui.input(|i| i.pointer.delta());
if resp.dragged_by(PointerButton::Middle) || (alt && resp.dragged_by(PointerButton::Primary)) {
app.ui.uv_pan[0] += delta.x / size.x * 2.0;
@@ -836,7 +904,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
let uv = to_uv(p);
app.run("tool.cloneSource", json!({"uv": [uv.x, uv.y]}));
}
let painting = app.ui.mode == crate::state::Mode::Painting && !alt && !v_held;
let painting = app.ui.mode == crate::state::Mode::Painting && !alt && !adjusting && !v_held;
if painting && path_tool {
path_input(app, ui, &resp, true, |_, p| Some(to_uv(p).extend(0.0)), show);
} else if painting {
@@ -898,6 +966,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
if app.ui.mode == crate::state::Mode::Painting && path_tool {
path_overlay(app, ui, rect, &resp, true, show);
}
brush_readout(app, ui, &resp, adjusting);
view_header(app, ui, rect, "v2d");
axis_gizmo(ui, rect, app, true);
let name = app.session.doc.project.texture_sets.get(ts).map(|t| t.name.clone()).unwrap_or_default();
+30 -7
View File
@@ -281,16 +281,27 @@ pub(crate) fn shader(app: &mut TextureCraftApp, ui: &mut Ui) {
/// The History panel body (a dock tab).
pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) {
let tk = Tokens::get(ui.ctx());
let labels = app.session.history_labels();
let (done, undone) = (app.session.history_labels(), app.session.redo_labels());
// A click on a step goes back (or forward) to it: steps to undo, or to redo when negative.
let mut jump = 0i64;
egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {
ui.label(RichText::new(tr("Project opened")).color(tk.text_dim));
for l in &labels {
ui.label(l);
}
if let Some(r) = app.session.redo_label() {
ui.label(RichText::new(trf("{action} (undone)", &[("action", &r)])).color(tk.text_dim));
let n = done.len() as i64;
let rows = std::iter::once(RichText::new(tr("Project opened")).color(tk.text_dim))
.chain(done.iter().map(RichText::new))
.chain(undone.iter().map(|l| RichText::new(trf("{action} (undone)", &[("action", l)])).color(tk.text_dim)));
for (i, text) in rows.enumerate() {
// Row i is the state after i steps.
let steps = n - i as i64;
if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() {
jump = steps;
}
}
});
if jump > 0 {
app.run("edit.undo", json!({ "steps": jump }));
} else if jump < 0 {
app.run("edit.redo", json!({ "steps": -jump }));
}
ui.horizontal(|ui| {
if ui.add_enabled(app.session.can_undo(), egui::Button::new(format!("{} {}", ic::ARROW_COUNTER_CLOCKWISE, tr("Undo")))).clicked() {
app.run("edit.undo", json!({}));
@@ -1144,6 +1155,9 @@ pub(crate) fn export_params(app: &TextureCraftApp) -> serde_json::Value {
if !e.normal_format.is_empty() {
p["normalFormat"] = json!(e.normal_format);
}
if !e.color_space.is_empty() {
p["colorSpace"] = json!(e.color_space);
}
p
}
@@ -1243,6 +1257,15 @@ fn export_settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, presets: &[textur
}
});
ui.end_row();
ui.label(tr("Color space"));
let shown = if app.ui.export.color_space.is_empty() { tr("Default") } else { app.ui.export.color_space.as_str() };
egui::ComboBox::from_id_salt("exp_cs").selected_text(shown).show_ui(ui, |ui| {
ui.selectable_value(&mut app.ui.export.color_space, String::new(), tr("Default"));
for name in ["sRGB", "Linear Rec.709", "ACEScg", "ACES2065-1"] {
ui.selectable_value(&mut app.ui.export.color_space, name.to_string(), name);
}
});
ui.end_row();
});
}
+46
View File
@@ -0,0 +1,46 @@
//! Ctrl+drag in the 3D view changes the brush instead of painting or orbiting.
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
use egui_kittest::Harness;
use texturecraft_ui_egui::TextureCraftApp;
/// Drag with `button` from `from` by `by` in a few moves.
fn drag(h: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: Pos2, by: egui::Vec2, modifiers: Modifiers) {
h.event(Event::ModifiersChanged(modifiers));
h.hover_at(from);
h.event(Event::PointerButton { pos: from, button, pressed: true, modifiers });
h.run_steps(2);
for k in 1..=4 {
h.hover_at(from + by * (k as f32 / 4.0));
h.run_steps(1);
}
h.event(Event::PointerButton { pos: from + by, button, pressed: false, modifiers });
h.event(Event::ModifiersChanged(Modifiers::NONE));
h.run_steps(3);
}
#[test]
fn ctrl_drag_changes_the_brush_instead_of_painting_or_orbiting() {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
let c = h.state().viewport_rect.center();
let (brush, yaw, history) = {
let s = &h.state().session;
(s.tool.brush.clone(), s.camera.yaw, s.history_labels().len())
};
// Right drag to the right and up: a bigger, harder brush; the camera stays.
drag(&mut h, PointerButton::Secondary, c, vec2(80.0, -40.0), Modifiers::COMMAND);
let b = h.state().session.tool.brush.clone();
assert!(b.size > brush.size && b.hardness > brush.hardness, "{} {} → {} {}", brush.size, brush.hardness, b.size, b.hardness);
assert_eq!(h.state().session.camera.yaw, yaw, "no orbit");
// Left drag to the left and up: less flow, a turned brush, and no stroke.
drag(&mut h, PointerButton::Primary, c, vec2(-80.0, -40.0), Modifiers::COMMAND);
let b2 = h.state().session.tool.brush.clone();
assert!(b2.flow < b.flow && b2.angle != b.angle, "{} {} → {} {}", b.flow, b.angle, b2.flow, b2.angle);
assert_eq!(h.state().session.history_labels().len(), history, "nothing painted");
// Without Ctrl, a right drag orbits again and the brush keeps its values.
drag(&mut h, PointerButton::Secondary, c, vec2(80.0, -40.0), Modifiers::NONE);
assert_ne!(h.state().session.camera.yaw, yaw);
assert_eq!(h.state().session.tool.brush, b2);
}
+48
View File
@@ -0,0 +1,48 @@
//! Effect rows in the layer stack: dragging one reorders its stack.
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::{Value, json};
use texturecraft_engine::core::LayerId;
use texturecraft_engine::execute;
use texturecraft_ui_egui::TextureCraftApp;
fn id(v: Value, key: &str) -> u64 {
v[key].as_u64().unwrap()
}
/// Drag the row labelled `from` onto the upper (`below` false) or lower half of the row `to`.
fn drag(h: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) {
let start = h.get_by_label(from).rect().center();
let r = h.get_by_label(to).rect();
let end = egui::pos2(r.center().x, if below { r.bottom() - 4.0 } else { r.top() + 4.0 });
h.drag_at(start);
h.run_steps(2);
h.hover_at(end);
h.run_steps(2);
h.drop_at(end);
h.run_steps(3);
}
#[test]
fn dragging_an_effect_row_reorders_its_stack() {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"));
let mut add =
|name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect");
let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C"));
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
let order = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::<Vec<_>>();
assert_eq!(order(&h), [a, b, c]);
// The rows list the top first: C, B, A. A dropped on C's upper half goes to the top.
drag(&mut h, "Effect A", "Effect C", false);
assert_eq!(order(&h), [b, c, a]);
// A dropped on B's lower half goes back to the bottom.
drag(&mut h, "Effect A", "Effect B", true);
assert_eq!(order(&h), [a, b, c]);
// C dropped on A's upper half lands between A and B.
drag(&mut h, "Effect C", "Effect A", false);
assert_eq!(order(&h), [a, c, b]);
}
+36
View File
@@ -0,0 +1,36 @@
//! A click on a step of the History panel goes back or forward to it.
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::docking::Panel;
#[test]
fn clicking_a_history_step_returns_to_it() {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
let layer = session.selected_layer().unwrap();
for name in ["Step A", "Step B", "Step C"] {
texturecraft_engine::execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": name})).unwrap();
}
let done = session.history_labels().len();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.dock.focus(Panel::History);
h.run_steps(4);
let name = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].name.clone();
// The first state: everything undone, and listed as undone.
h.get_by_label("Project opened").click();
h.run_steps(3);
assert!(!h.state().session.can_undo());
assert_eq!(h.state().session.redo_labels().len(), done);
// The first undone row is the next step: one redo.
h.get_all_by_label("Rename layer (undone)").next().unwrap().click();
h.run_steps(3);
assert_eq!(h.state().session.history_labels().len(), 1);
assert_eq!(h.state().session.redo_labels().len(), done - 1);
// The last undone row: all the way forward again.
h.get_all_by_label("Rename layer (undone)").last().unwrap().click();
h.run_steps(3);
assert_eq!(name(&h), "Step C");
assert!(!h.state().session.can_redo());
}
+12
View File
@@ -78,4 +78,16 @@ fn window_snapshots() {
texturecraft_engine::execute(s, id, &p).unwrap();
}
save(&mut h, &dir, "properties-levels");
// Ctrl+right drag in the 3D view: the brush cursor where it began and the readout.
let c = h.state().viewport_rect.center();
let (m, button) = (egui::Modifiers::COMMAND, egui::PointerButton::Secondary);
h.event(egui::Event::ModifiersChanged(m));
h.event(egui::Event::PointerButton { pos: c, button, pressed: true, modifiers: m });
for k in 1..=4 {
h.hover_at(c + egui::vec2(15.0 * k as f32, -8.0 * k as f32));
h.run_steps(1);
}
save(&mut h, &dir, "brush-ctrl-drag");
h.event(egui::Event::PointerButton { pos: c, button, pressed: false, modifiers: m });
h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
}
+6 -1
View File
@@ -14,7 +14,12 @@ Programmatic calls never open dialogs: a command runs with its defaults. Only `u
behaves like a menu click. `session.inspect` shows every layer, mask, effect, fill source and
painted tile count, so an agent can verify its work without a screenshot.
`effect.histogram {effect, channel?, bins?}` counts the values an effect reads (a levels
effect's input), so an agent can pick its input range from the data.
effect's input), so an agent can pick its input range from the data. `effect.move {effect,
index}` reorders an effect within its stack (0 = bottom) and `effect.duplicate {effect}` copies
one just above itself.
`edit.undo {steps?}` and `edit.redo {steps?}` go back or forward several steps at once (as far
as the history reaches); `edit.history` lists the steps done and the undone ones, next first.
## Control channel (desktop app)
+5 -1
View File
@@ -7,6 +7,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
- **Brushes** with size, flow, stroke opacity, spacing, hardness, angle and follow path; size,
angle, flow and position jitter; tangent or camera alignment, angle fade, backface culling, lazy
mouse, X/Y/Z mirror and radial symmetry (copies paint the far side too) and pen pressure.
Ctrl+drag in a view sets them on the fly: right-drag the size and hardness, left-drag the flow
and angle.
**67 procedural brush alphas** in their own shelf tab, or any imported image as the alpha.
**18 brush presets** (basic, wear and grunge, details) in the shelf's Brushes tab set the
stroke and keep the size; save your own brushes there too.
@@ -42,7 +44,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
- **Masks** with a white or black background and a stack of effects: painted strokes, fills,
**mesh-map generators** (edge wear, dirt, thin areas, curvature, AO, position and direction
gradients, all with world-space noise), filters, ID color selection and compare. Alt+click a
mask to view it alone.
mask to view it alone. Drag an effect to reorder its stack, or right-click it to duplicate it
(painted strokes included).
- **Fill layers** take uniform values, **23 procedurals** (clouds, cells, grunge, scratches, wood
grain, bricks, fabric weave, twill, leather grain, marble veins, Voronoi, paint chips…) or your own
**images**, through UV, tri-planar, planar, spherical, cylindrical or decal projection.
@@ -120,6 +123,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
- A **start window** at launch: a new project, a project file, a recent project or the sample
(Settings › Interface › Start window).
- A **shortcut editor** with conflict detection, and every shortcut shown in its tooltip.
- A **History** panel: click any step to go back to it, or forward again to an undone one.
- **10 languages:** English, French, German, Spanish, Portuguese, Italian, Japanese, Chinese,
Korean and Arabic, switchable live.
- **In the browser:** the same app compiled to WebAssembly, on WebGPU or WebGL2, with touch