mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-28 09:09:25 +01:00
Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts: # ROADMAP.md
This commit is contained in:
commit
34eae81910
31 files changed
+1299
-25
No files matched your search
+3
-3
@@ -11,13 +11,13 @@ end to end today (engine + UI + automation + tests), not what is planned.
|
||||
|
||||
| Area | Weight | Done | What works | Main gaps |
|
||||
|---|---:|---:|---|---|
|
||||
| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project (in the browser too, and before the tab closes), recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) |
|
||||
| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project (in the browser too, and before the tab closes), recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, **MaterialX import** (`file.importMaterialX`: a `.mtlx` material with `open_pbr_surface`, `standard_surface` or `gltf_pbr` becomes one fill layer with its textures and values), image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) |
|
||||
| Texture sets | 6 | 95% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile**, one texture per tile at its own size, `$udim` export), list with visibility (show or hide all, invert, **focus** on one set), sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | Filter radii and height slopes of a tile smaller than its atlas block follow the block; mesh maps from images need a set without UV tiles |
|
||||
| Layer stack | 16 | 98% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels (with a histogram of its input), invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; effects **dragged to reorder**, duplicated, and **copied, cut and pasted** across layers, masks and sets (Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+D and Delete act on a selected effect); smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **30 library filters** (adjustments incl. histogram scan, range and shift, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog |
|
||||
| Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt (not exposed by the windowing layer) |
|
||||
| Materials and assets | 8 | 90% | 63 procedural materials (incl. car paint, velvet, brushed steel, skin, wax, ice, snow, bark), 21 smart materials, 18 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 23 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's |
|
||||
| Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; **mesh maps from images** (baked elsewhere or edited) dropped on a slot; 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 |
|
||||
| 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; **Auto-rebake** (`bake.autoRebake`: one map bakes itself again in the background when its bake settings, the low poly or the high polys change); **mesh maps from images** (baked elsewhere or edited) dropped on a slot; 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**; picks a discrete GPU on multi-GPU machines (`--gpu`, `WGPU_ADAPTER_NAME`, `WGPU_POWER_PREF`), and display textures are made on demand so a mesh with many materials imports on a small GPU | Hardware ray tracing |
|
||||
| Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — |
|
||||
| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, **colour space** of the colour maps (sRGB, Linear Rec.709, ACEScg, ACES2065-1; data maps never converted), `$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 | 97% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **History** panel that jumps to any step (back or forward), a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts, a compact color picker (saturation/value square, hue strip, copyable RGB); all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations |
|
||||
|
||||
@@ -10,14 +10,14 @@ use serde_json::{Value, json};
|
||||
use texturecraft_automation::security::{client_token, server_token};
|
||||
use texturecraft_automation::{AuthorizedWorkspace, BridgeClient, Filesystem, Headless, RenderOptions, TexturecraftMcp, rpc};
|
||||
use texturecraft_engine::core::PROJECT_EXT;
|
||||
use texturecraft_engine::formats::{MeshReport, import_mesh, import_mesh_bytes};
|
||||
use texturecraft_engine::formats::{MeshReport, import_mesh, import_mesh_bytes, mesh_report};
|
||||
|
||||
const USAGE: &str = "\
|
||||
texturecraft-cli: headless TextureCraft
|
||||
|
||||
USAGE:
|
||||
texturecraft-cli --version
|
||||
texturecraft-cli info <project.tcraft | mesh file>
|
||||
texturecraft-cli info <project.tcraft | mesh file | builtin:<id>>
|
||||
Texture sets, layers, triangles, materials and the UV report, as JSON.
|
||||
texturecraft-cli commands [--filter <text>]
|
||||
List the engine commands (id, label, params).
|
||||
@@ -220,6 +220,14 @@ fn report_json(r: &MeshReport) -> Value {
|
||||
|
||||
fn info(a: &Args) -> R {
|
||||
let file = a.pos(0, "<file>")?;
|
||||
if let Some(id) = file.strip_prefix("builtin:") {
|
||||
let m = texturecraft_engine::geom::primitives::builtin(id).ok_or_else(|| format!("unknown built-in mesh `{id}`"))?;
|
||||
let report = mesh_report(&m);
|
||||
return print_json(&json!({
|
||||
"file": file, "kind": "mesh", "triangles": m.triangle_count(), "vertices": m.vertex_count(),
|
||||
"materials": m.materials, "textureSets": m.materials, "uv": report_json(&report),
|
||||
}));
|
||||
}
|
||||
if !is_project(file) {
|
||||
let m = import_mesh(Path::new(file)).map_err(|e| format!("cannot read {file}: {e}"))?;
|
||||
return print_json(&json!({
|
||||
|
||||
@@ -115,6 +115,16 @@ fn serve_takes_the_automation_root_spelling_too() {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_on_a_builtin_mesh() {
|
||||
let info = json(&["info", "builtin:cube"]);
|
||||
assert_eq!(info["kind"], "mesh");
|
||||
assert_eq!(info["file"], "builtin:cube");
|
||||
assert_eq!(info["triangles"], 1728);
|
||||
assert_eq!(info["uv"]["uvsGenerated"], false);
|
||||
assert_eq!(cli(&["info", "builtin:bogus"]).status.code(), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_writes_a_png() {
|
||||
let d = tmp("render");
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
//! Auto-rebake: one mesh map that bakes itself again when what it was baked from changes.
|
||||
//!
|
||||
//! The map is chosen with `bake.autoRebake`. From then on, [`Session::auto_rebake_due`] names the
|
||||
//! texture sets whose bake inputs (the set's bake settings except the list of maps, the low poly,
|
||||
//! the high polys and the cage) differ from those of their last bake of that map.
|
||||
//! The apps poll it each frame and bake the due sets in the background; `bake.autoRebake.run`
|
||||
//! does the same thing once, blocking, for agents and scripts.
|
||||
//!
|
||||
//! A set only takes part once it has the map baked at its current output size: Auto-rebake
|
||||
//! keeps a bake up to date, it doesn't start one, and it never leaves a set's maps at two sizes.
|
||||
//! The choice isn't part of the project.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_bake::Progress;
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
use crate::bake_cmds::BakeTask;
|
||||
use crate::commands::{CommandSpec, always, bad, boolp};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
/// Which map rebakes itself, and what each texture set was last baked from.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct AutoRebake {
|
||||
pub map: Option<BakedMap>,
|
||||
/// Fingerprint of each set's bake inputs when it last baked [`AutoRebake::map`].
|
||||
seen: BTreeMap<usize, u64>,
|
||||
/// Fingerprint taken when a set's bake started, kept when that bake finishes.
|
||||
pending: BTreeMap<usize, u64>,
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"bake.autoRebake",
|
||||
"Auto-rebake",
|
||||
[],
|
||||
None,
|
||||
"{map?: map id (e.g. \"normal_base\", \"height\") to keep up to date, or null / off: true to turn it off; no params: just report} → {map, due: [texture sets that need a rebake]}",
|
||||
always,
|
||||
auto_rebake
|
||||
),
|
||||
cmd!(
|
||||
"bake.autoRebake.run",
|
||||
"Run Auto-rebake",
|
||||
[],
|
||||
None,
|
||||
"{cpu?: true (skip the GPU)} → {rebaked: [texture sets]}: bakes the Auto-rebake map of every set whose bake inputs changed since it was last baked, now",
|
||||
always,
|
||||
auto_rebake_run
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// A fingerprint of everything a bake of texture set `ts` is made from, except which maps it
|
||||
/// makes.
|
||||
pub fn bake_inputs_key(&self, ts: usize) -> Option<u64> {
|
||||
let set = self.doc.project.texture_sets.get(ts)?;
|
||||
let mut settings = set.bake.clone();
|
||||
settings.maps.clear();
|
||||
settings.enabled = true;
|
||||
let mut h = DefaultHasher::new();
|
||||
serde_json::to_string(&settings).ok()?.hash(&mut h);
|
||||
(Arc::as_ptr(&self.mesh) as usize).hash(&mut h);
|
||||
for m in &self.bake_meshes.high {
|
||||
(Arc::as_ptr(&m.mesh) as usize).hash(&mut h);
|
||||
}
|
||||
self.bake_meshes.cage.as_ref().map(|c| Arc::as_ptr(&c.mesh) as usize).hash(&mut h);
|
||||
Some(h.finish())
|
||||
}
|
||||
|
||||
/// Texture sets whose Auto-rebake map is out of date. A set seen for the first time (a project
|
||||
/// just opened, a bake from before Auto-rebake was on) is taken as up to date.
|
||||
pub fn auto_rebake_due(&mut self) -> Vec<usize> {
|
||||
let Some(map) = self.auto_rebake.map else { return Vec::new() };
|
||||
let mut due = Vec::new();
|
||||
for ts in 0..self.doc.project.texture_sets.len() {
|
||||
let Some(set) = self.doc.project.texture_sets.get(ts).filter(|t| t.bake.enabled) else { continue };
|
||||
let columns = set.tile_grid().map_or(1, |g| g.cols);
|
||||
let baked = self.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map) && b.resolution == set.bake.resolution.saturating_mul(columns));
|
||||
let Some(key) = self.bake_inputs_key(ts).filter(|_| baked) else { continue };
|
||||
match self.auto_rebake.seen.get(&ts) {
|
||||
None => {
|
||||
self.auto_rebake.seen.insert(ts, key);
|
||||
}
|
||||
Some(seen) if *seen != key => due.push(ts),
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
due
|
||||
}
|
||||
|
||||
/// Call right before building the bake task of `ts`: remembers what it is baked from, so a
|
||||
/// finished bake of the Auto-rebake map marks the set up to date (and a change made while it
|
||||
/// ran still triggers another).
|
||||
pub fn begin_bake(&mut self, ts: usize) {
|
||||
if let Some(key) = self.bake_inputs_key(ts) {
|
||||
self.auto_rebake.pending.insert(ts, key);
|
||||
}
|
||||
}
|
||||
|
||||
/// The bake task of `ts` restricted to one map (Auto-rebake's: the other maps stay as they are).
|
||||
pub fn bake_task_for(&self, ts: usize, only: Option<BakedMap>) -> Result<BakeTask> {
|
||||
let mut task = self.bake_task(ts)?;
|
||||
if let Some(m) = only {
|
||||
task.settings.maps = std::iter::once(m).collect();
|
||||
}
|
||||
Ok(task)
|
||||
}
|
||||
|
||||
/// Records a finished bake: when it made the Auto-rebake map, the set is up to date.
|
||||
pub(crate) fn note_baked(&mut self, ts: usize, mut made: impl Iterator<Item = BakedMap>) {
|
||||
let key = self.auto_rebake.pending.remove(&ts);
|
||||
if let (Some(key), Some(map)) = (key, self.auto_rebake.map)
|
||||
&& made.any(|m| m == map)
|
||||
{
|
||||
self.auto_rebake.seen.insert(ts, key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Records bakes of `sets` that were cancelled, failed or never started: Auto-rebake leaves
|
||||
/// those sets alone until their bake inputs change again, instead of retrying every frame.
|
||||
pub fn bake_abandoned(&mut self, sets: impl IntoIterator<Item = usize>) {
|
||||
for ts in sets {
|
||||
if let Some(key) = self.auto_rebake.pending.remove(&ts).or_else(|| self.bake_inputs_key(ts)) {
|
||||
self.auto_rebake.seen.insert(ts, key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bakes every due set's Auto-rebake map now (blocking); returns the sets.
|
||||
pub fn auto_rebake_now(&mut self, cpu: bool) -> Result<Vec<usize>> {
|
||||
let due = self.auto_rebake_due();
|
||||
let map = self.auto_rebake.map;
|
||||
for &ts in &due {
|
||||
self.begin_bake(ts);
|
||||
let mut task = self.bake_task_for(ts, map)?;
|
||||
if cpu {
|
||||
task.tracer = None;
|
||||
}
|
||||
let out = task.run(&Progress::new())?;
|
||||
self.apply_bake(ts, out)?;
|
||||
}
|
||||
Ok(due)
|
||||
}
|
||||
}
|
||||
|
||||
fn state(s: &mut Session) -> Value {
|
||||
json!({ "map": s.auto_rebake.map.map(BakedMap::id), "due": s.auto_rebake_due() })
|
||||
}
|
||||
|
||||
fn auto_rebake(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if boolp(p, "off") == Some(true) || p.get("map").is_some_and(Value::is_null) {
|
||||
s.auto_rebake = AutoRebake::default();
|
||||
} else if let Some(id) = p.get("map") {
|
||||
let map = id.as_str().and_then(BakedMap::parse).ok_or_else(|| bad("bake.autoRebake", format!("unknown mesh map {id}")))?;
|
||||
if s.auto_rebake.map != Some(map) {
|
||||
s.auto_rebake = AutoRebake { map: Some(map), ..AutoRebake::default() };
|
||||
}
|
||||
}
|
||||
Ok(state(s))
|
||||
}
|
||||
|
||||
fn auto_rebake_run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.auto_rebake.map.is_none() {
|
||||
return Err(bad("bake.autoRebake.run", "no Auto-rebake map is set; run bake.autoRebake {map} first"));
|
||||
}
|
||||
let rebaked = s.auto_rebake_now(boolp(p, "cpu") == Some(true))?;
|
||||
s.update();
|
||||
Ok(json!({ "rebaked": rebaked }))
|
||||
}
|
||||
@@ -177,6 +177,7 @@ impl Session {
|
||||
/// Store a finished bake (one undo step).
|
||||
pub fn apply_bake(&mut self, ts: usize, out: BakeOutput) -> Result<()> {
|
||||
self.log.push(format!("Baked texture set {ts} ({})", out.tracer));
|
||||
let made: Vec<BakedMap> = out.maps.keys().copied().collect();
|
||||
self.edit("Bake mesh maps", |s| {
|
||||
let maps: BTreeSet<BakedMap> = out.maps.keys().copied().collect();
|
||||
let entry = s.doc.baked.entry(ts).or_default();
|
||||
@@ -186,11 +187,14 @@ impl Session {
|
||||
}
|
||||
s.doc.project.texture_set_mut(ts)?.baked.extend(maps);
|
||||
Ok(())
|
||||
})
|
||||
})?;
|
||||
self.note_baked(ts, made.into_iter());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran.
|
||||
pub fn bake_now(&mut self, ts: usize, cpu: bool) -> Result<String> {
|
||||
self.begin_bake(ts);
|
||||
let mut task = self.bake_task(ts)?;
|
||||
if cpu {
|
||||
task.tracer = None;
|
||||
|
||||
@@ -68,7 +68,9 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::uv_tile_cmds::specs());
|
||||
v.extend(crate::template_cmds::specs());
|
||||
v.extend(crate::project_cmds::specs());
|
||||
v.extend(crate::auto_rebake::specs());
|
||||
v.extend(crate::bake_cmds::specs());
|
||||
v.extend(crate::materialx_cmds::specs());
|
||||
v.extend(crate::file_cmds::specs());
|
||||
v.extend(crate::preset_cmds::specs());
|
||||
v.extend(crate::resource_cmds::specs());
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
/// The copied effect, if the clipboard holds one.
|
||||
fn clipboard_effect(s: &Session) -> Option<LayerId> {
|
||||
pub fn clipboard_effect(s: &Session) -> Option<LayerId> {
|
||||
s.clipboard.as_ref().and_then(|(doc, id)| doc.project.effect(*id).map(|_| *id))
|
||||
}
|
||||
|
||||
@@ -114,10 +114,13 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.doc.pixels.layers.insert((new, c), fit(img, size, &empty_texel(c)));
|
||||
}
|
||||
}
|
||||
// The target belongs to the active set's selection: a paste into another set leaves it.
|
||||
if let Some((lts, _, _)) = s.doc.project.locate(layer) {
|
||||
s.selected.insert(lts, layer);
|
||||
if lts == s.ts() {
|
||||
s.target = StackTarget::Effect(new);
|
||||
}
|
||||
}
|
||||
s.target = StackTarget::Effect(new);
|
||||
Ok(new)
|
||||
})?;
|
||||
Ok(json!({ "effect": new.0 }))
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod auto_rebake;
|
||||
pub mod bake_cmds;
|
||||
pub mod brush_preset_cmds;
|
||||
pub mod camera_cmds;
|
||||
@@ -23,6 +24,7 @@ pub mod layer_ops;
|
||||
pub mod mask_cmds;
|
||||
pub mod material_lib;
|
||||
pub mod materials;
|
||||
pub mod materialx_cmds;
|
||||
pub mod meshmap_cmds;
|
||||
pub mod painting;
|
||||
pub mod path_tool;
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
//! `file.importMaterialX`: a MaterialX (`.mtlx`) material becomes one fill layer.
|
||||
//!
|
||||
//! The document is read by [`texturecraft_formats::materialx_read`]; here its image files are
|
||||
//! loaded (only from the document's own folder and below: a document is untrusted, and its
|
||||
//! `file` values must not reach other files), added to the project as resources and set as the
|
||||
//! fill's sources, with constants as uniform sources. The whole import is one undo step. Channels
|
||||
//! the texture set doesn't have, images that can't be read and anything the reader skipped are
|
||||
//! reported in `warnings`; the import goes ahead with the rest.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{Channel, Fill, Layer, LayerKind, Projection, Source};
|
||||
use texturecraft_formats::materialx_read::{Material, Value as Mtlx};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, strp};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"file.importMaterialX",
|
||||
"Import MaterialX material...",
|
||||
["File"],
|
||||
None,
|
||||
"{path: a .mtlx file, material?: the surfacematerial to read (default: the first), name?: layer name} → {layer, material, channels, resources, warnings}: one fill layer with the material's textures (read from the file's folder) and values; open_pbr_surface, standard_surface and gltf_pbr are read",
|
||||
always,
|
||||
import
|
||||
)]
|
||||
}
|
||||
|
||||
/// Loads an image file named in the document (relative to it): its bytes, or why not.
|
||||
pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result<Vec<u8>, String>;
|
||||
|
||||
impl Session {
|
||||
/// Add `material` as a fill layer on the active texture set, loading its images with `load`.
|
||||
/// Returns the reply of `file.importMaterialX`.
|
||||
pub fn import_material(&mut self, material: Material, name: Option<&str>, load: Loader) -> Result<Value> {
|
||||
let mut warnings = material.warnings.clone();
|
||||
let ts = self.ts();
|
||||
let available = self.doc.project.texture_set(ts).map(|t| t.channel_list()).unwrap_or_default();
|
||||
let mut fill = Fill { projection: Projection::Uv { scale: material.uv_tiling, rotation: 0.0, offset: [0.0, 0.0] }, ..Fill::default() };
|
||||
// Resources to add (name and encoded bytes), and their decoded images for the session.
|
||||
let mut added: Vec<(String, Arc<Vec<u8>>)> = Vec::new();
|
||||
let mut decoded = Vec::new();
|
||||
let mut names: BTreeMap<String, String> = BTreeMap::new();
|
||||
let mut channels: Vec<Channel> = Vec::new();
|
||||
for (channel, value) in &material.channels {
|
||||
if !available.contains(channel) {
|
||||
warnings.push(format!("{} was skipped: this texture set has no such channel", channel.id()));
|
||||
continue;
|
||||
}
|
||||
let source = match value {
|
||||
Mtlx::Constant(c) => Source::Uniform(*c),
|
||||
Mtlx::Image(file) => {
|
||||
let resource = match names.get(file) {
|
||||
Some(n) => n.clone(),
|
||||
None => {
|
||||
let loaded =
|
||||
load(file).and_then(|bytes| texturecraft_formats::decode_image(&bytes).map(|image| (bytes, image)).map_err(|e| e.to_string()));
|
||||
let (bytes, image) = match loaded {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
warnings.push(format!("{} was skipped: {file}: {e}", channel.id()));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let leaf = file.rsplit(['/', '\\']).next().unwrap_or(file);
|
||||
let base = texturecraft_formats::sanitize_resource_name(leaf);
|
||||
let (mut unique, mut n) = (base.clone(), 2);
|
||||
while self.doc.resources.contains_key(&unique) || added.iter().any(|(a, _)| *a == unique) {
|
||||
unique = format!("{n}_{base}");
|
||||
n += 1;
|
||||
}
|
||||
added.push((unique.clone(), Arc::new(bytes)));
|
||||
decoded.push((unique.clone(), crate::resource_cmds::decoded(image)));
|
||||
names.insert(file.clone(), unique.clone());
|
||||
unique
|
||||
}
|
||||
};
|
||||
Source::Image { name: resource }
|
||||
}
|
||||
};
|
||||
fill.sources.insert(*channel, source);
|
||||
channels.push(*channel);
|
||||
}
|
||||
if channels.is_empty() {
|
||||
let why = if warnings.is_empty() { String::new() } else { format!(" ({})", warnings.join("; ")) };
|
||||
return Err(EngineError::Other(format!("file.importMaterialX: nothing to import from {:?}{why}", material.name)));
|
||||
}
|
||||
let layer_name = name.map(str::to_string).unwrap_or_else(|| self.doc.project.next_layer_name(ts, &material.name));
|
||||
let resource_names: Vec<String> = added.iter().map(|(n, _)| n.clone()).collect();
|
||||
let id = self.edit("Import MaterialX material", |s| {
|
||||
for (n, bytes) in &added {
|
||||
s.doc.resources.insert(n.clone(), bytes.clone());
|
||||
}
|
||||
let id = s.doc.project.alloc_id();
|
||||
crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name, LayerKind::Fill(fill), &channels))
|
||||
})?;
|
||||
self.images.extend(decoded);
|
||||
Ok(json!({
|
||||
"layer": id.0,
|
||||
"material": material.name,
|
||||
"channels": channels.iter().map(|c| c.id()).collect::<Vec<_>>(),
|
||||
"resources": resource_names,
|
||||
"warnings": warnings,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use std::path::{Component, Path};
|
||||
let cmd = "file.importMaterialX";
|
||||
let path = strp(p, "path").filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, "`path` is required"))?;
|
||||
let meta = std::fs::metadata(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?;
|
||||
if !meta.is_file() || meta.len() > texturecraft_formats::materialx_read::MAX_BYTES as u64 {
|
||||
return Err(bad(cmd, format!("{path} is not a MaterialX file of a readable size")));
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?;
|
||||
let material = texturecraft_formats::materialx_read::read_materialx(&bytes, strp(p, "material")).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
let folder = Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
|
||||
let dir = folder.canonicalize().map_err(|e| bad(cmd, format!("cannot read the folder of {path}: {e}")))?;
|
||||
let load = |file: &str| -> std::result::Result<Vec<u8>, String> {
|
||||
// `<UDIM>` stands for a tile number; the first tile is read.
|
||||
let file = file.replace("<UDIM>", "1001");
|
||||
let rel = Path::new(&file);
|
||||
let outside = "the file is outside the material's folder";
|
||||
if rel.is_absolute() || rel.components().any(|c| matches!(c, Component::ParentDir | Component::Prefix(_) | Component::RootDir)) {
|
||||
return Err(outside.into());
|
||||
}
|
||||
let full = dir.join(rel).canonicalize().map_err(|e| e.to_string())?;
|
||||
if !full.starts_with(&dir) {
|
||||
return Err(outside.into());
|
||||
}
|
||||
let len = std::fs::metadata(&full).map_err(|e| e.to_string())?.len();
|
||||
if len > crate::resource_cmds::MAX_BYTES as u64 {
|
||||
return Err(format!("the file is over {} MB", crate::resource_cmds::MAX_BYTES >> 20));
|
||||
}
|
||||
std::fs::read(&full).map_err(|e| e.to_string())
|
||||
};
|
||||
s.import_material(material, strp(p, "name"), &load)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn import(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(EngineError::Other("file paths are not available in the browser".into()))
|
||||
}
|
||||
@@ -29,9 +29,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
/// Largest accepted resource file.
|
||||
const MAX_BYTES: usize = 512 << 20;
|
||||
pub(crate) const MAX_BYTES: usize = 512 << 20;
|
||||
|
||||
fn decoded(d: texturecraft_formats::DecodedImage) -> Arc<ImageRes> {
|
||||
pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc<ImageRes> {
|
||||
Arc::new(ImageRes { width: d.width, height: d.height, rgba: d.rgba, srgb: d.srgb })
|
||||
}
|
||||
|
||||
|
||||
@@ -320,6 +320,8 @@ pub struct Session {
|
||||
pub mesh_source: Option<(String, Vec<u8>)>,
|
||||
/// High-definition meshes and cage for baking (saved inside the project).
|
||||
pub bake_meshes: crate::BakeMeshes,
|
||||
/// The map that bakes itself again when its inputs change (not saved).
|
||||
pub auto_rebake: crate::auto_rebake::AutoRebake,
|
||||
pub caches: Vec<SetCache>,
|
||||
pub(crate) undo: Vec<(String, Document)>,
|
||||
pub(crate) redo: Vec<(String, Document)>,
|
||||
@@ -375,6 +377,7 @@ impl Session {
|
||||
bvh: Arc::new(bvh),
|
||||
mesh_source,
|
||||
bake_meshes: Default::default(),
|
||||
auto_rebake: Default::default(),
|
||||
caches,
|
||||
undo: Vec::new(),
|
||||
redo: Vec::new(),
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Auto-rebake: one mesh map bakes itself again when its bake inputs change.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::BakedMap;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
/// A plane with a high poly just above it, baked once with height and opacity.
|
||||
fn baked_session(tag: &str) -> (Session, std::path::PathBuf) {
|
||||
let mesh = primitives::builtin("plane").unwrap();
|
||||
let mut obj = String::from("o Part_high\n");
|
||||
for p in &mesh.positions {
|
||||
obj += &format!("v {} {} {}\n", p.x, p.y + 0.002, p.z);
|
||||
}
|
||||
for t in mesh.indices.chunks_exact(3) {
|
||||
obj += &format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1);
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("tc_auto_rebake_{tag}_{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("hp.obj");
|
||||
std::fs::write(&path, obj).unwrap();
|
||||
let mut s = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap();
|
||||
execute(&mut s, "bake.highPoly.add", &json!({ "path": path.display().to_string() })).unwrap();
|
||||
execute(&mut s, "bake.settings", &json!({ "resolution": 128, "dilation": 0, "maps": ["height", "opacity"] })).unwrap();
|
||||
execute(&mut s, "bake.run", &json!({ "cpu": true })).unwrap();
|
||||
(s, dir)
|
||||
}
|
||||
|
||||
fn due(s: &mut Session) -> Vec<u64> {
|
||||
execute(s, "bake.autoRebake", &Value::Null).unwrap()["due"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect()
|
||||
}
|
||||
|
||||
fn image(s: &Session, map: BakedMap) -> Arc<Vec<f32>> {
|
||||
s.doc.baked[&0].maps[&map].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_bake_input_rebakes_only_the_chosen_map() {
|
||||
let (mut s, dir) = baked_session("rebake");
|
||||
// Off by default; nothing is due and the run command says what to do first.
|
||||
assert_eq!(execute(&mut s, "bake.autoRebake", &Value::Null).unwrap()["map"], Value::Null);
|
||||
assert!(execute(&mut s, "bake.autoRebake.run", &Value::Null).is_err());
|
||||
let r = execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap();
|
||||
assert_eq!(r["map"], "height");
|
||||
assert!(due(&mut s).is_empty(), "turning it on takes the current bake as up to date");
|
||||
|
||||
// Which maps are ticked is not a bake input; a setting is.
|
||||
execute(&mut s, "bake.settings", &json!({ "maps": ["height", "opacity", "ambient_occlusion"] })).unwrap();
|
||||
assert!(due(&mut s).is_empty());
|
||||
execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.2, "maps": ["height", "opacity"] })).unwrap();
|
||||
assert_eq!(due(&mut s), [0]);
|
||||
|
||||
let (height, opacity) = (image(&s, BakedMap::Height), image(&s, BakedMap::Opacity));
|
||||
let r = execute(&mut s, "bake.autoRebake.run", &json!({ "cpu": true })).unwrap();
|
||||
assert_eq!(r["rebaked"], json!([0]));
|
||||
assert!(!Arc::ptr_eq(&height, &image(&s, BakedMap::Height)), "the Auto-rebake map was baked again");
|
||||
assert!(Arc::ptr_eq(&opacity, &image(&s, BakedMap::Opacity)), "the other maps were left alone");
|
||||
assert!(due(&mut s).is_empty(), "and the set is up to date");
|
||||
assert_eq!(execute(&mut s, "bake.autoRebake.run", &Value::Null).unwrap()["rebaked"], json!([]));
|
||||
|
||||
// A manual bake of the map also counts; a changed high poly list is a change again.
|
||||
execute(&mut s, "bake.settings", &json!({ "antialiasing": 2 })).unwrap();
|
||||
assert_eq!(due(&mut s), [0]);
|
||||
s.begin_bake(0);
|
||||
let out = s.bake_task_for(0, None).unwrap().run(&texturecraft_engine::bake::Progress::new()).unwrap();
|
||||
s.apply_bake(0, out).unwrap();
|
||||
assert!(due(&mut s).is_empty(), "a manual bake of the map marks it up to date");
|
||||
execute(&mut s, "bake.highPoly.remove", &json!({ "all": true })).unwrap();
|
||||
assert_eq!(due(&mut s), [0]);
|
||||
|
||||
// A different output size is left to a manual bake: the maps would end up at two sizes.
|
||||
execute(&mut s, "bake.settings", &json!({ "resolution": 256 })).unwrap();
|
||||
assert!(due(&mut s).is_empty());
|
||||
|
||||
// Hostile input, and turning it off.
|
||||
for bad in [json!({ "map": "nonsense" }), json!({ "map": 3 })] {
|
||||
assert!(execute(&mut s, "bake.autoRebake", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(execute(&mut s, "bake.autoRebake", &json!({ "map": null })).unwrap()["map"], Value::Null);
|
||||
assert!(due(&mut s).is_empty());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_or_failed_bake_is_not_queued_again_until_the_inputs_change() {
|
||||
let (mut s, dir) = baked_session("cancel");
|
||||
execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap();
|
||||
assert!(due(&mut s).is_empty());
|
||||
execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.2 })).unwrap();
|
||||
assert_eq!(due(&mut s), [0]);
|
||||
|
||||
// What the app does: start the bake, cancel it, record the abandoned bake.
|
||||
s.begin_bake(0);
|
||||
let mut task = s.bake_task_for(0, Some(BakedMap::Height)).unwrap();
|
||||
task.tracer = None;
|
||||
let progress = texturecraft_engine::bake::Progress::new();
|
||||
progress.cancel();
|
||||
assert!(task.run(&progress).is_err(), "a cancelled bake fails");
|
||||
s.bake_abandoned([0]);
|
||||
assert!(due(&mut s).is_empty(), "not queued again on the next frame");
|
||||
|
||||
// The next change makes it due again; a bake that never started (queued behind a failed
|
||||
// one) is recorded the same way.
|
||||
execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.3 })).unwrap();
|
||||
assert_eq!(due(&mut s), [0]);
|
||||
s.bake_abandoned([0]);
|
||||
assert!(due(&mut s).is_empty());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_set_without_the_map_baked_is_left_alone() {
|
||||
let mut s = Session::new_project("t", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap();
|
||||
execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap();
|
||||
execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.3 })).unwrap();
|
||||
assert!(due(&mut s).is_empty(), "Auto-rebake keeps a bake up to date, it doesn't start one");
|
||||
}
|
||||
@@ -200,6 +200,21 @@ fn effects_copy_and_paste_between_layers_and_stacks() {
|
||||
assert!(execute(&mut s, "effect.paste", &Value::Null).is_err(), "the anchor is on the layer itself");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasting_an_effect_into_another_texture_set_keeps_the_active_target() {
|
||||
let mut s = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
execute(&mut s, "layer.add.fill", &Value::Null).unwrap();
|
||||
execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap();
|
||||
execute(&mut s, "effect.copy", &Value::Null).unwrap();
|
||||
execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap();
|
||||
let other = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer");
|
||||
execute(&mut s, "textureSet.select", &json!({"ts": 0})).unwrap();
|
||||
let before = s.target;
|
||||
let pasted = id(execute(&mut s, "effect.paste", &json!({"layer": other})).unwrap(), "effect");
|
||||
assert_eq!(s.target, before, "the active set's selection keeps its target");
|
||||
assert_eq!(s.doc.project.effect(LayerId(pasted)).map(|(owner, _)| owner), Some(LayerId(other)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn histogram_counts_what_an_effect_reads() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! `file.importMaterialX`: a .mtlx material becomes one fill layer with its textures.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{Channel, LayerKind, Source};
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
fn session() -> Session {
|
||||
Session::new_project("t", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap()
|
||||
}
|
||||
|
||||
fn png(path: &Path, rgb: [u8; 3]) {
|
||||
image::RgbImage::from_pixel(4, 4, image::Rgb(rgb)).save(path).unwrap();
|
||||
}
|
||||
|
||||
fn folder(tag: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("tc_mtlx_import_{tag}_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("tex")).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
const MATERIAL: &str = r#"<?xml version="1.0"?>
|
||||
<materialx version="1.39" fileprefix="tex/">
|
||||
<open_pbr_surface name="S" type="surfaceshader">
|
||||
<input name="base_color" type="color3" nodename="img_base" />
|
||||
<input name="specular_roughness" type="float" nodename="img_rough" />
|
||||
<input name="base_metalness" type="float" value="1" />
|
||||
<input name="geometry_normal" type="vector3" nodename="nm" />
|
||||
<input name="coat_weight" type="float" value="0.5" />
|
||||
</open_pbr_surface>
|
||||
<tiledimage name="img_base" type="color3">
|
||||
<input name="file" type="filename" value="base.png" />
|
||||
<input name="uvtiling" type="vector2" value="3, 3" />
|
||||
</tiledimage>
|
||||
<tiledimage name="img_rough" type="float"><input name="file" type="filename" value="base.png" /></tiledimage>
|
||||
<tiledimage name="img_n" type="vector3"><input name="file" type="filename" value="../../escape.png" /></tiledimage>
|
||||
<normalmap name="nm" type="vector3"><input name="in" type="vector3" nodename="img_n" /></normalmap>
|
||||
<tiledimage name="img_gone" type="float"><input name="file" type="filename" value="missing.png" /></tiledimage>
|
||||
<displacement name="D" type="displacementshader"><input name="displacement" type="float" nodename="img_gone" /></displacement>
|
||||
<surfacematerial name="Brick" type="material">
|
||||
<input name="surfaceshader" type="surfaceshader" nodename="S" />
|
||||
<input name="displacementshader" type="displacementshader" nodename="D" />
|
||||
</surfacematerial>
|
||||
</materialx>"#;
|
||||
|
||||
fn fill_of(s: &Session, layer: u64) -> texturecraft_engine::core::Fill {
|
||||
let l = s.doc.project.layer(texturecraft_engine::core::LayerId(layer)).unwrap();
|
||||
match &l.kind {
|
||||
LayerKind::Fill(f) => f.clone(),
|
||||
other => panic!("not a fill: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_material_becomes_one_fill_layer_in_one_undo_step() {
|
||||
let dir = folder("ok");
|
||||
png(&dir.join("tex/base.png"), [200, 40, 40]);
|
||||
// A file next to the folder that a hostile document tries to reach.
|
||||
png(&dir.parent().unwrap().join("escape.png"), [1, 2, 3]);
|
||||
let mtlx = dir.join("brick.mtlx");
|
||||
std::fs::write(&mtlx, MATERIAL).unwrap();
|
||||
|
||||
let mut s = session();
|
||||
let before = s.doc.resources.len();
|
||||
let r = execute(&mut s, "file.importMaterialX", &json!({ "path": mtlx.display().to_string() })).unwrap();
|
||||
assert_eq!(r["material"], "Brick");
|
||||
let fill = fill_of(&s, r["layer"].as_u64().unwrap());
|
||||
// The one image used twice is one resource; the constant is uniform.
|
||||
assert_eq!(r["resources"].as_array().unwrap().len(), 1, "{r}");
|
||||
let name = r["resources"][0].as_str().unwrap().to_string();
|
||||
assert!(matches!(fill.sources.get(&Channel::BaseColor), Some(Source::Image { name: n }) if *n == name));
|
||||
assert!(matches!(fill.sources.get(&Channel::Roughness), Some(Source::Image { name: n }) if *n == name));
|
||||
assert_eq!(fill.sources.get(&Channel::Metallic), Some(&Source::Uniform([1.0; 3])));
|
||||
assert!(matches!(fill.projection, texturecraft_engine::core::Projection::Uv { scale, .. } if scale == [3.0, 3.0]), "{:?}", fill.projection);
|
||||
assert_eq!(s.doc.resources.len(), before + 1);
|
||||
assert!(s.images.contains_key(&name), "the image is decoded for the viewport");
|
||||
|
||||
// The traversal and the missing file were skipped with a warning, not read.
|
||||
let warnings = r["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect::<Vec<_>>();
|
||||
assert!(!fill.sources.contains_key(&Channel::Normal) && !fill.sources.contains_key(&Channel::Height), "{fill:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains("outside")), "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains("missing.png")), "{warnings:?}");
|
||||
// A channel the texture set doesn't have is reported, not invented.
|
||||
let has_coat = s.doc.project.texture_set(s.ts()).unwrap().channel_list().contains(&Channel::CoatWeight);
|
||||
assert_eq!(fill.sources.contains_key(&Channel::CoatWeight), has_coat);
|
||||
assert_eq!(warnings.iter().any(|w| w.contains("no such channel")), !has_coat, "{warnings:?}");
|
||||
assert!(!s.doc.resources.keys().any(|k| k.contains("escape")), "nothing outside the folder was imported");
|
||||
|
||||
// One undo removes the layer and its images together.
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
assert_eq!(s.doc.resources.len(), before);
|
||||
assert!(s.doc.project.layer(texturecraft_engine::core::LayerId(r["layer"].as_u64().unwrap())).is_err());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let _ = std::fs::remove_file(dir.parent().unwrap().join("escape.png"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_documents_and_paths_are_errors_that_change_nothing() {
|
||||
let dir = folder("bad");
|
||||
let mut s = session();
|
||||
let layers = |s: &Session| s.doc.project.texture_sets[0].stack.len();
|
||||
let (n, res) = (layers(&s), s.doc.resources.len());
|
||||
let run = |s: &mut Session, p: Value| execute(s, "file.importMaterialX", &p);
|
||||
assert!(run(&mut s, json!({})).is_err());
|
||||
assert!(run(&mut s, json!({ "path": dir.join("nope.mtlx").display().to_string() })).is_err());
|
||||
for (i, text) in ["", "garbage", "<materialx/>", "<materialx><surfacematerial name=\"M\"/></materialx>"].iter().enumerate() {
|
||||
let f = dir.join(format!("bad{i}.mtlx"));
|
||||
std::fs::write(&f, text).unwrap();
|
||||
assert!(run(&mut s, json!({ "path": f.display().to_string() })).is_err(), "{text:?}");
|
||||
}
|
||||
// Only images that can't be read: nothing to import is an error, not an empty layer.
|
||||
let only_missing = MATERIAL.replace("base.png", "none.png");
|
||||
let f = dir.join("missing.mtlx");
|
||||
std::fs::write(&f, only_missing.replace("<input name=\"base_metalness\" type=\"float\" value=\"1\" />", "")).unwrap();
|
||||
assert!(run(&mut s, json!({ "path": f.display().to_string() })).is_err());
|
||||
// A material that isn't in the document.
|
||||
std::fs::write(dir.join("m.mtlx"), MATERIAL).unwrap();
|
||||
assert!(run(&mut s, json!({ "path": dir.join("m.mtlx").display().to_string(), "material": "Nope" })).is_err());
|
||||
assert_eq!((layers(&s), s.doc.resources.len()), (n, res), "refused imports leave the project alone");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -28,6 +28,7 @@ pub mod export;
|
||||
pub mod fonts;
|
||||
pub mod image_res;
|
||||
pub mod materialx;
|
||||
pub mod materialx_read;
|
||||
pub mod mesh_export;
|
||||
pub mod mesh_import;
|
||||
pub mod presets;
|
||||
@@ -38,7 +39,7 @@ pub use export::{
|
||||
};
|
||||
pub use image_res::{DecodedImage, coverage_png, decode_image};
|
||||
pub use mesh_export::{GlbTextures, UsdExport, UsdFormat, glb_bytes, glb_export_options, obj_bytes, usd_bytes, usd_export_options};
|
||||
pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_high_poly_bytes, import_mesh_bytes, self_contained_mesh};
|
||||
pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_high_poly_bytes, import_mesh_bytes, mesh_report, self_contained_mesh};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use presets::load_preset;
|
||||
pub use presets::{builtin_preset, builtin_presets, preset_from_json, preset_to_json};
|
||||
|
||||
@@ -0,0 +1,545 @@
|
||||
//! Reading a MaterialX (`.mtlx`) material into TextureCraft's channels, written from the ASWF
|
||||
//! MaterialX specification (1.39) and the OpenPBR Surface and glTF PBR node definitions. Pure
|
||||
//! Rust: no MaterialX library is linked.
|
||||
//!
|
||||
//! [`read_materialx`] finds a `surfacematerial`, follows its `surfaceshader` to an
|
||||
//! `open_pbr_surface`, `standard_surface` or `gltf_pbr` node, and turns each input TextureCraft
|
||||
//! has a channel for into a literal value or an image file:
|
||||
//!
|
||||
//! - a literal `value` becomes a constant (`color3` values tagged `srgb_texture` are converted
|
||||
//! to linear; a colour given for a scalar channel is averaged);
|
||||
//! - an input wired to a `tiledimage` or `image` node (directly or through a `nodegraph`
|
||||
//! output) becomes that node's `file` (with `fileprefix` applied); `normalmap`, `convert` and
|
||||
//! `constant` nodes in between are passed through;
|
||||
//! - the material's `displacementshader` becomes the height channel;
|
||||
//! - `uvtiling` of the first tiled image is returned as the UV tiling.
|
||||
//!
|
||||
//! Anything else (maths nodes, procedural patterns, other shaders) is skipped with a warning
|
||||
//! rather than guessed at. Emission follows the specifications' defaults: OpenPBR emits nothing
|
||||
//! unless `emission_luminance` is above 0, and `standard_surface` unless `emission` is.
|
||||
//!
|
||||
//! The reader takes untrusted bytes: the document size, nesting and element count are capped, a
|
||||
//! wiring loop stops at a depth limit, and every failure is an error, never a panic.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use quick_xml::events::{BytesStart, Event};
|
||||
use texturecraft_core::Channel;
|
||||
use texturecraft_texel::srgb_to_linear;
|
||||
|
||||
use crate::{FormatError, Result, malformed};
|
||||
|
||||
const KIND: &str = "MaterialX document";
|
||||
/// Largest document read, in bytes.
|
||||
pub const MAX_BYTES: usize = 16 << 20;
|
||||
const MAX_DEPTH: usize = 64;
|
||||
const MAX_ELEMENTS: usize = 200_000;
|
||||
/// Longest chain of nodes followed from one shader input.
|
||||
const MAX_HOPS: usize = 16;
|
||||
|
||||
/// What one channel is set from.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Value {
|
||||
/// A constant: linear RGB for colours, `[v, v, v]` for scalars.
|
||||
Constant([f32; 3]),
|
||||
/// An image file, as written in the document (`fileprefix` applied), relative to it.
|
||||
Image(String),
|
||||
}
|
||||
|
||||
/// A material read from a document.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Material {
|
||||
pub name: String,
|
||||
/// The channels the material sets, in a fixed order.
|
||||
pub channels: Vec<(Channel, Value)>,
|
||||
/// The first image's `uvtiling` (1, 1 when none).
|
||||
pub uv_tiling: [f32; 2],
|
||||
/// What was skipped and why.
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// XML.
|
||||
|
||||
#[derive(Default)]
|
||||
struct El {
|
||||
name: String,
|
||||
attrs: Vec<(String, String)>,
|
||||
children: Vec<El>,
|
||||
}
|
||||
|
||||
impl El {
|
||||
fn attr(&self, k: &str) -> Option<&str> {
|
||||
self.attrs.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
/// The child element named `name` (the `name` attribute: inputs and nodes are looked up by it).
|
||||
fn input(&self, name: &str) -> Option<&El> {
|
||||
self.children.iter().find(|c| c.attr("name") == Some(name))
|
||||
}
|
||||
}
|
||||
|
||||
fn element(e: &BytesStart) -> El {
|
||||
let text = |b: &[u8]| String::from_utf8_lossy(b).into_owned();
|
||||
let attrs = e
|
||||
.attributes()
|
||||
.with_checks(false)
|
||||
.flatten()
|
||||
.map(|a| {
|
||||
(text(a.key.local_name().as_ref()), a.normalized_value(quick_xml::XmlVersion::Implicit1_0).map_or_else(|_| text(&a.value), |v| v.into_owned()))
|
||||
})
|
||||
.collect();
|
||||
El { name: text(e.local_name().as_ref()), attrs, children: Vec::new() }
|
||||
}
|
||||
|
||||
fn parse_xml(bytes: &[u8]) -> Result<El> {
|
||||
let mut reader = quick_xml::Reader::from_reader(bytes);
|
||||
let mut stack = vec![El::default()];
|
||||
let mut count = 0usize;
|
||||
loop {
|
||||
let event = reader.read_event().map_err(|e| malformed(KIND, e))?;
|
||||
if matches!(event, Event::Start(_) | Event::Empty(_)) {
|
||||
count += 1;
|
||||
if count > MAX_ELEMENTS || stack.len() > MAX_DEPTH {
|
||||
return Err(FormatError::TooLarge(format!(
|
||||
"the MaterialX document has more than {MAX_ELEMENTS} elements or is nested deeper than {MAX_DEPTH}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
match event {
|
||||
Event::Start(e) => stack.push(element(&e)),
|
||||
Event::Empty(e) => {
|
||||
if let Some(parent) = stack.last_mut() {
|
||||
parent.children.push(element(&e));
|
||||
}
|
||||
}
|
||||
Event::End(_) => {
|
||||
let el = stack.pop().filter(|_| !stack.is_empty()).ok_or_else(|| malformed(KIND, "unbalanced end tag"))?;
|
||||
if let Some(parent) = stack.last_mut() {
|
||||
parent.children.push(el);
|
||||
}
|
||||
}
|
||||
Event::Eof => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
match (stack.pop(), stack.is_empty()) {
|
||||
(Some(root), true) => Ok(root),
|
||||
_ => Err(malformed(KIND, "unclosed elements at the end of the document")),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Shader input tables: (shader input, channel). `kind` says how to read the value.
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Shader {
|
||||
OpenPbr,
|
||||
Standard,
|
||||
Gltf,
|
||||
}
|
||||
|
||||
const OPEN_PBR: &[(&str, Channel)] = &[
|
||||
("base_color", Channel::BaseColor),
|
||||
("base_metalness", Channel::Metallic),
|
||||
("specular_roughness", Channel::Roughness),
|
||||
("geometry_normal", Channel::Normal),
|
||||
("geometry_opacity", Channel::Opacity),
|
||||
("emission_color", Channel::Emissive),
|
||||
("coat_weight", Channel::CoatWeight),
|
||||
("coat_roughness", Channel::CoatRoughness),
|
||||
("geometry_coat_normal", Channel::CoatNormal),
|
||||
("fuzz_weight", Channel::SheenWeight),
|
||||
("fuzz_color", Channel::SheenColor),
|
||||
("fuzz_roughness", Channel::SheenRoughness),
|
||||
("specular_roughness_anisotropy", Channel::AnisotropyLevel),
|
||||
("transmission_weight", Channel::Transmission),
|
||||
("subsurface_weight", Channel::ScatterWeight),
|
||||
];
|
||||
|
||||
const STANDARD: &[(&str, Channel)] = &[
|
||||
("base_color", Channel::BaseColor),
|
||||
("metalness", Channel::Metallic),
|
||||
("specular_roughness", Channel::Roughness),
|
||||
("normal", Channel::Normal),
|
||||
("opacity", Channel::Opacity),
|
||||
("emission_color", Channel::Emissive),
|
||||
("coat", Channel::CoatWeight),
|
||||
("coat_roughness", Channel::CoatRoughness),
|
||||
("coat_normal", Channel::CoatNormal),
|
||||
("sheen", Channel::SheenWeight),
|
||||
("sheen_color", Channel::SheenColor),
|
||||
("sheen_roughness", Channel::SheenRoughness),
|
||||
("specular_anisotropy", Channel::AnisotropyLevel),
|
||||
("transmission", Channel::Transmission),
|
||||
("subsurface", Channel::ScatterWeight),
|
||||
];
|
||||
|
||||
const GLTF: &[(&str, Channel)] = &[
|
||||
("base_color", Channel::BaseColor),
|
||||
("metallic", Channel::Metallic),
|
||||
("roughness", Channel::Roughness),
|
||||
("normal", Channel::Normal),
|
||||
("alpha", Channel::Opacity),
|
||||
("emission", Channel::Emissive),
|
||||
("occlusion", Channel::AmbientOcclusion),
|
||||
("clearcoat", Channel::CoatWeight),
|
||||
("clearcoat_roughness", Channel::CoatRoughness),
|
||||
("clearcoat_normal", Channel::CoatNormal),
|
||||
("sheen_color", Channel::SheenColor),
|
||||
("sheen_roughness", Channel::SheenRoughness),
|
||||
("transmission", Channel::Transmission),
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Resolving what feeds an input.
|
||||
|
||||
struct Doc<'a> {
|
||||
root: &'a El,
|
||||
/// Every node by name: the document's own, and each nodegraph's (qualified `graph/node`).
|
||||
nodes: HashMap<String, &'a El>,
|
||||
/// Each nodegraph's outputs: `graph/output` to the node name inside (qualified).
|
||||
outputs: HashMap<String, String>,
|
||||
tiling: Option<[f32; 2]>,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
enum Found {
|
||||
Constant(Vec<f32>),
|
||||
Image(String),
|
||||
None,
|
||||
}
|
||||
|
||||
fn numbers(text: &str) -> Option<Vec<f32>> {
|
||||
let v: Option<Vec<f32>> = text.split(',').map(|p| p.trim().parse::<f32>().ok().filter(|f| f.is_finite())).collect();
|
||||
v.filter(|v| !v.is_empty() && v.len() <= 4)
|
||||
}
|
||||
|
||||
impl<'a> Doc<'a> {
|
||||
fn new(root: &'a El) -> Doc<'a> {
|
||||
let mut nodes = HashMap::new();
|
||||
let mut outputs = HashMap::new();
|
||||
for c in &root.children {
|
||||
match (c.name.as_str(), c.attr("name")) {
|
||||
("nodegraph", Some(g)) => {
|
||||
for n in &c.children {
|
||||
let Some(name) = n.attr("name") else { continue };
|
||||
if n.name == "output" {
|
||||
if let Some(from) = n.attr("nodename") {
|
||||
outputs.insert(format!("{g}/{name}"), format!("{g}/{from}"));
|
||||
}
|
||||
} else {
|
||||
nodes.insert(format!("{g}/{name}"), n);
|
||||
}
|
||||
}
|
||||
}
|
||||
(_, Some(name)) => {
|
||||
nodes.insert(name.to_owned(), c);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Doc { root, nodes, outputs, tiling: None, warnings: Vec::new() }
|
||||
}
|
||||
|
||||
/// What `input` (an `<input>` element of a node) resolves to; `scope` is the nodegraph the
|
||||
/// node lives in, if any.
|
||||
fn resolve(&mut self, input: &El, scope: Option<&str>, hops: usize) -> Found {
|
||||
if hops > MAX_HOPS {
|
||||
self.warnings.push("a node chain is longer than 16 nodes (or loops); skipped".into());
|
||||
return Found::None;
|
||||
}
|
||||
if let Some(v) = input.attr("value") {
|
||||
return numbers(v).map_or(Found::None, |n| Found::Constant(self.tag(input, n)));
|
||||
}
|
||||
let target = match (input.attr("nodegraph"), input.attr("output"), input.attr("nodename")) {
|
||||
(Some(g), out, _) => {
|
||||
let out = out.map(str::to_owned).or_else(|| self.outputs.keys().find_map(|k| k.strip_prefix(&format!("{g}/")).map(str::to_owned)));
|
||||
out.and_then(|o| self.outputs.get(&format!("{g}/{o}")).cloned())
|
||||
}
|
||||
(None, _, Some(n)) => {
|
||||
Some(scope.map_or_else(|| n.to_owned(), |g| format!("{g}/{n}"))).filter(|q| self.nodes.contains_key(q)).or_else(|| Some(n.to_owned()))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let Some(node) = target.as_deref().and_then(|t| self.nodes.get(t).copied()) else { return Found::None };
|
||||
let scope = target.as_deref().and_then(|t| t.split_once('/')).map(|(g, _)| g.to_owned());
|
||||
let scope = scope.as_deref();
|
||||
match node.name.as_str() {
|
||||
"tiledimage" | "image" => {
|
||||
let Some(file) = node.input("file").and_then(|f| f.attr("value")) else {
|
||||
self.warnings.push(format!("image node {:?} has no file", node.attr("name").unwrap_or("")));
|
||||
return Found::None;
|
||||
};
|
||||
let prefix =
|
||||
[node.input("file").and_then(|f| f.attr("fileprefix")), node.attr("fileprefix"), self.root.attr("fileprefix")].into_iter().flatten().next();
|
||||
if self.tiling.is_none()
|
||||
&& let Some(t) =
|
||||
node.input("uvtiling").and_then(|t| t.attr("value")).and_then(numbers).filter(|t| t.len() == 2 && t.iter().all(|v| *v > 0.0))
|
||||
{
|
||||
// The range a fill's UV scale accepts (`layer.fill.projection`).
|
||||
self.tiling = Some([t[0].clamp(0.001, 1000.0), t[1].clamp(0.001, 1000.0)]);
|
||||
}
|
||||
Found::Image(format!("{}{file}", prefix.unwrap_or("")))
|
||||
}
|
||||
"normalmap" | "convert" => match node.input("in") {
|
||||
Some(i) => self.resolve(i, scope, hops + 1),
|
||||
None => Found::None,
|
||||
},
|
||||
"constant" => match node.input("value") {
|
||||
Some(v) => self.resolve(v, scope, hops + 1),
|
||||
None => Found::None,
|
||||
},
|
||||
other => {
|
||||
self.warnings.push(format!("a {other} node ({:?}) is not supported; its input was skipped", node.attr("name").unwrap_or("")));
|
||||
Found::None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Literal values tagged with an sRGB colour space are converted to linear.
|
||||
fn tag(&self, input: &El, mut n: Vec<f32>) -> Vec<f32> {
|
||||
let space = input.attr("colorspace").or_else(|| self.root.attr("colorspace")).unwrap_or("");
|
||||
if input.attr("colorspace").is_some() && (space.starts_with("srgb") || space.starts_with("g22") || space.starts_with("g18")) && n.len() >= 3 {
|
||||
n.iter_mut().take(3).for_each(|c| *c = srgb_to_linear(*c));
|
||||
}
|
||||
n
|
||||
}
|
||||
}
|
||||
|
||||
fn to_constant(channel: Channel, n: &[f32]) -> [f32; 3] {
|
||||
match (channel.kind(), n) {
|
||||
(_, [a]) => [*a; 3],
|
||||
(texturecraft_core::ChannelKind::Color, [r, g, b, ..]) => [*r, *g, *b],
|
||||
(_, [r, g, b, ..]) => {
|
||||
let mean = (r + g + b) / 3.0;
|
||||
[mean; 3]
|
||||
}
|
||||
_ => Channel::default_value(channel),
|
||||
}
|
||||
}
|
||||
|
||||
/// The literal number of `input`, if it is one.
|
||||
fn literal(shader: &El, name: &str) -> Option<f32> {
|
||||
shader.input(name).and_then(|i| i.attr("value")).and_then(numbers).and_then(|n| n.first().copied())
|
||||
}
|
||||
|
||||
/// Read the material called `material` (default: the first) from a `.mtlx` document.
|
||||
pub fn read_materialx(bytes: &[u8], material: Option<&str>) -> Result<Material> {
|
||||
crate::guard(KIND, || read_inner(bytes, material))
|
||||
}
|
||||
|
||||
fn read_inner(bytes: &[u8], material: Option<&str>) -> Result<Material> {
|
||||
if bytes.len() > MAX_BYTES {
|
||||
return Err(FormatError::TooLarge(format!("the MaterialX document is over {} MiB", MAX_BYTES >> 20)));
|
||||
}
|
||||
let top = parse_xml(bytes)?;
|
||||
let root = top.children.iter().find(|c| c.name == "materialx").ok_or_else(|| malformed(KIND, "no <materialx> element"))?;
|
||||
let mut doc = Doc::new(root);
|
||||
let materials: Vec<&El> = root.children.iter().filter(|c| c.name == "surfacematerial").collect();
|
||||
let mat = match material {
|
||||
Some(name) => materials
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|m| m.attr("name") == Some(name))
|
||||
.ok_or_else(|| FormatError::Invalid(format!("no material named {name:?} (found: {})", names(&materials))))?,
|
||||
None => materials.first().copied().ok_or_else(|| FormatError::Unsupported("the document has no surfacematerial".into()))?,
|
||||
};
|
||||
let mut out = Material { name: mat.attr("name").unwrap_or("Material").to_owned(), channels: Vec::new(), uv_tiling: [1.0, 1.0], warnings: Vec::new() };
|
||||
let shader = mat
|
||||
.input("surfaceshader")
|
||||
.and_then(|i| i.attr("nodename"))
|
||||
.and_then(|n| doc.nodes.get(n).copied())
|
||||
.ok_or_else(|| malformed(KIND, "the material has no surface shader"))?;
|
||||
let (kind, table) = match shader.name.as_str() {
|
||||
"open_pbr_surface" => (Shader::OpenPbr, OPEN_PBR),
|
||||
"standard_surface" => (Shader::Standard, STANDARD),
|
||||
"gltf_pbr" => (Shader::Gltf, GLTF),
|
||||
other => return Err(FormatError::Unsupported(format!("the surface shader is a {other}; open_pbr_surface, standard_surface and gltf_pbr are read"))),
|
||||
};
|
||||
// Emission is off by default in OpenPBR and standard_surface.
|
||||
let emits = match kind {
|
||||
Shader::OpenPbr => {
|
||||
shader.input("emission_luminance").is_some_and(|i| i.attr("value").is_none() || literal(shader, "emission_luminance").is_some_and(|v| v > 0.0))
|
||||
}
|
||||
Shader::Standard => shader.input("emission").is_some_and(|i| i.attr("value").is_none() || literal(shader, "emission").is_some_and(|v| v > 0.0)),
|
||||
Shader::Gltf => true,
|
||||
};
|
||||
let weight = match kind {
|
||||
Shader::OpenPbr => literal(shader, "base_weight"),
|
||||
Shader::Standard => literal(shader, "base"),
|
||||
Shader::Gltf => None,
|
||||
};
|
||||
if weight.is_some_and(|w| (w - 1.0).abs() > 1e-6) {
|
||||
doc.warnings.push("the base weight isn't 1; it was ignored".into());
|
||||
}
|
||||
for &(input, channel) in table {
|
||||
let Some(el) = shader.input(input) else { continue };
|
||||
if channel == Channel::Emissive && !emits && kind != Shader::Gltf {
|
||||
doc.warnings.push(format!("{input} was skipped: the shader's emission is 0"));
|
||||
continue;
|
||||
}
|
||||
match doc.resolve(el, None, 0) {
|
||||
Found::Constant(n) => out.channels.push((channel, Value::Constant(to_constant(channel, &n)))),
|
||||
Found::Image(f) => out.channels.push((channel, Value::Image(f))),
|
||||
Found::None => {}
|
||||
}
|
||||
}
|
||||
// The displacement shader's `displacement` input is the height.
|
||||
if let Some(d) = mat.input("displacementshader").and_then(|i| i.attr("nodename")).and_then(|n| doc.nodes.get(n).copied())
|
||||
&& let Some(i) = d.input("displacement")
|
||||
{
|
||||
match doc.resolve(i, None, 0) {
|
||||
Found::Constant(n) => out.channels.push((Channel::Height, Value::Constant(to_constant(Channel::Height, &n)))),
|
||||
Found::Image(f) => out.channels.push((Channel::Height, Value::Image(f))),
|
||||
Found::None => {}
|
||||
}
|
||||
}
|
||||
out.uv_tiling = doc.tiling.unwrap_or([1.0, 1.0]);
|
||||
out.warnings = doc.warnings;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn names(materials: &[&El]) -> String {
|
||||
let n: Vec<&str> = materials.iter().filter_map(|m| m.attr("name")).collect();
|
||||
if n.is_empty() { "none".into() } else { n.join(", ") }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const OPENPBR: &str = r#"<?xml version="1.0"?>
|
||||
<materialx version="1.39" colorspace="lin_rec709">
|
||||
<open_pbr_surface name="S" type="surfaceshader">
|
||||
<input name="base_color" type="color3" nodename="img_base" />
|
||||
<input name="base_metalness" type="float" value="1" />
|
||||
<input name="specular_roughness" type="float" nodename="img_rough" />
|
||||
<input name="geometry_normal" type="vector3" nodename="nm" />
|
||||
<input name="emission_color" type="color3" value="1, 0.5, 0" />
|
||||
<input name="emission_luminance" type="float" value="2" />
|
||||
<input name="coat_weight" type="float" value="0.25" />
|
||||
</open_pbr_surface>
|
||||
<tiledimage name="img_base" type="color3">
|
||||
<input name="file" type="filename" value="stone_base.png" colorspace="srgb_texture" />
|
||||
<input name="uvtiling" type="vector2" value="4, 2" />
|
||||
</tiledimage>
|
||||
<tiledimage name="img_rough" type="float"><input name="file" type="filename" value="stone_r.png" /></tiledimage>
|
||||
<tiledimage name="img_n" type="vector3"><input name="file" type="filename" value="stone_n.png" /></tiledimage>
|
||||
<normalmap name="nm" type="vector3"><input name="in" type="vector3" nodename="img_n" /></normalmap>
|
||||
<tiledimage name="img_h" type="float"><input name="file" type="filename" value="stone_h.png" /></tiledimage>
|
||||
<displacement name="D" type="displacementshader"><input name="displacement" type="float" nodename="img_h" /></displacement>
|
||||
<surfacematerial name="Stone" type="material">
|
||||
<input name="surfaceshader" type="surfaceshader" nodename="S" />
|
||||
<input name="displacementshader" type="displacementshader" nodename="D" />
|
||||
</surfacematerial>
|
||||
</materialx>"#;
|
||||
|
||||
fn get(m: &Material, c: Channel) -> Option<&Value> {
|
||||
m.channels.iter().find(|(ch, _)| *ch == c).map(|(_, v)| v)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_pbr_inputs_become_channels() {
|
||||
let m = read_materialx(OPENPBR.as_bytes(), None).unwrap();
|
||||
assert_eq!(m.name, "Stone");
|
||||
assert_eq!(get(&m, Channel::BaseColor), Some(&Value::Image("stone_base.png".into())));
|
||||
assert_eq!(get(&m, Channel::Roughness), Some(&Value::Image("stone_r.png".into())));
|
||||
assert_eq!(get(&m, Channel::Normal), Some(&Value::Image("stone_n.png".into())), "through the normalmap node");
|
||||
assert_eq!(get(&m, Channel::Height), Some(&Value::Image("stone_h.png".into())), "from the displacement shader");
|
||||
assert_eq!(get(&m, Channel::Metallic), Some(&Value::Constant([1.0; 3])));
|
||||
assert_eq!(get(&m, Channel::CoatWeight), Some(&Value::Constant([0.25; 3])));
|
||||
assert_eq!(get(&m, Channel::Emissive), Some(&Value::Constant([1.0, 0.5, 0.0])));
|
||||
assert_eq!(m.uv_tiling, [4.0, 2.0]);
|
||||
assert!(m.warnings.is_empty(), "{:?}", m.warnings);
|
||||
let extreme = OPENPBR.replace(r#"value="4, 2""#, r#"value="1e9, 1e-9""#);
|
||||
assert_eq!(read_materialx(extreme.as_bytes(), None).unwrap().uv_tiling, [1000.0, 0.001], "clamped like a fill's UV scale");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emission_is_off_unless_the_shader_emits() {
|
||||
let x = OPENPBR.replace(r#"<input name="emission_luminance" type="float" value="2" />"#, "");
|
||||
let m = read_materialx(x.as_bytes(), None).unwrap();
|
||||
assert!(get(&m, Channel::Emissive).is_none());
|
||||
assert!(m.warnings.iter().any(|w| w.contains("emission")), "{:?}", m.warnings);
|
||||
let zero = OPENPBR.replace(r#"value="2" />"#, r#"value="0" />"#);
|
||||
assert!(get(&read_materialx(zero.as_bytes(), None).unwrap(), Channel::Emissive).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standard_surface_nodegraphs_prefixes_and_colour_spaces() {
|
||||
let x = r#"<materialx version="1.38" fileprefix="tex/">
|
||||
<nodegraph name="NG">
|
||||
<tiledimage name="t" type="color3"><input name="file" type="filename" value="a.png" /></tiledimage>
|
||||
<output name="out" type="color3" nodename="t" />
|
||||
</nodegraph>
|
||||
<standard_surface name="SS" type="surfaceshader">
|
||||
<input name="base_color" type="color3" nodegraph="NG" output="out" />
|
||||
<input name="specular_roughness" type="float" value="0.4" />
|
||||
<input name="opacity" type="color3" value="0.5, 0.5, 0.5" />
|
||||
<input name="sheen_color" type="color3" value="0.5, 0.5, 0.5" colorspace="srgb_texture" />
|
||||
<input name="base" type="float" value="0.5" />
|
||||
</standard_surface>
|
||||
<surfacematerial name="M1" type="material"><input name="surfaceshader" type="surfaceshader" nodename="SS" /></surfacematerial>
|
||||
<surfacematerial name="M2" type="material"><input name="surfaceshader" type="surfaceshader" nodename="SS" /></surfacematerial>
|
||||
</materialx>"#;
|
||||
let m = read_materialx(x.as_bytes(), Some("M2")).unwrap();
|
||||
assert_eq!(m.name, "M2");
|
||||
assert_eq!(get(&m, Channel::BaseColor), Some(&Value::Image("tex/a.png".into())), "through the nodegraph, with the prefix");
|
||||
assert_eq!(get(&m, Channel::Roughness), Some(&Value::Constant([0.4; 3])));
|
||||
assert_eq!(get(&m, Channel::Opacity), Some(&Value::Constant([0.5; 3])), "a colour on a scalar channel is averaged");
|
||||
let Some(Value::Constant(c)) = get(&m, Channel::SheenColor) else { panic!("sheen colour") };
|
||||
assert!((c[0] - 0.214).abs() < 1e-3, "sRGB 0.5 is linear 0.214: {c:?}");
|
||||
assert!(m.warnings.iter().any(|w| w.contains("base weight")), "{:?}", m.warnings);
|
||||
assert!(read_materialx(x.as_bytes(), Some("nope")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_nodes_and_shaders_are_reported() {
|
||||
let x = OPENPBR.replace(r#"<tiledimage name="img_rough""#, r#"<multiply name="img_rough" type="float"/><tiledimage name="unused""#);
|
||||
let m = read_materialx(x.as_bytes(), None).unwrap();
|
||||
assert!(get(&m, Channel::Roughness).is_none());
|
||||
assert!(m.warnings.iter().any(|w| w.contains("multiply")), "{:?}", m.warnings);
|
||||
let other = r#"<materialx><UsdPreviewSurface name="U" type="surfaceshader"/><surfacematerial name="M" type="material"><input name="surfaceshader" type="surfaceshader" nodename="U"/></surfacematerial></materialx>"#;
|
||||
assert!(matches!(read_materialx(other.as_bytes(), None), Err(FormatError::Unsupported(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_documents_are_errors() {
|
||||
for bad in ["", "not xml", "<materialx>", "<a><b></a>", "<materialx/>", "<materialx><surfacematerial name=\"M\"/></materialx>"] {
|
||||
assert!(read_materialx(bad.as_bytes(), None).is_err(), "{bad:?}");
|
||||
}
|
||||
// A wiring loop and a deep tree stop instead of running forever or overflowing.
|
||||
let loop_doc = r#"<materialx><open_pbr_surface name="S"><input name="base_color" nodename="c"/></open_pbr_surface>
|
||||
<convert name="c"><input name="in" nodename="c"/></convert>
|
||||
<surfacematerial name="M"><input name="surfaceshader" nodename="S"/></surfacematerial></materialx>"#;
|
||||
let m = read_materialx(loop_doc.as_bytes(), None).unwrap();
|
||||
assert!(m.channels.is_empty() && m.warnings.iter().any(|w| w.contains("loops")), "{:?}", m.warnings);
|
||||
let deep = format!("<materialx>{}{}</materialx>", "<a>".repeat(200), "</a>".repeat(200));
|
||||
assert!(matches!(read_materialx(deep.as_bytes(), None), Err(FormatError::TooLarge(_))));
|
||||
// Numbers: NaN, inf and over-long lists are not values.
|
||||
let nan = OPENPBR.replace(r#"value="0.25""#, r#"value="NaN""#);
|
||||
assert!(get(&read_materialx(nan.as_bytes(), None).unwrap(), Channel::CoatWeight).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xml_entities_in_file_names_are_decoded() {
|
||||
let x = OPENPBR.replace("stone_base.png", "a&b <1>.png");
|
||||
let m = read_materialx(x.as_bytes(), None).unwrap();
|
||||
assert_eq!(get(&m, Channel::BaseColor), Some(&Value::Image("a&b <1>.png".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mutated_documents_never_panic() {
|
||||
// Truncations and byte flips of a real document: errors or materials, never a panic.
|
||||
let bytes = OPENPBR.as_bytes();
|
||||
for cut in (0..bytes.len()).step_by(7) {
|
||||
let _ = read_materialx(&bytes[..cut], None);
|
||||
}
|
||||
for i in (0..bytes.len()).step_by(5) {
|
||||
let mut b = bytes.to_vec();
|
||||
b[i] ^= 0x5a;
|
||||
let _ = read_materialx(&b, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -496,6 +496,11 @@ fn smooth_normals(mesh: &Mesh) -> Vec<Vec3> {
|
||||
weld.iter().map(|w| acc.get(*w as usize).and_then(|n| n.try_normalize()).unwrap_or(Vec3::Y)).collect()
|
||||
}
|
||||
|
||||
/// Inspects `mesh` and generates its UV report (overlaps, out-of-range UVs, warnings).
|
||||
pub fn mesh_report(mesh: &Mesh) -> MeshReport {
|
||||
report(mesh, false, Vec::new())
|
||||
}
|
||||
|
||||
fn report(mesh: &Mesh, uvs_generated: bool, mut warnings: Vec<String>) -> MeshReport {
|
||||
let (mut out_of_range, mut zero_area) = (0, 0);
|
||||
for t in 0..mesh.triangle_count() {
|
||||
|
||||
@@ -582,7 +582,8 @@ fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Ef
|
||||
}
|
||||
resp.context_menu(|ui| {
|
||||
let keymap = app.ui.keymap.clone();
|
||||
let paste = crate::menus::enabled(app, "effect.paste");
|
||||
// The row is selected before the paste runs, so a copied effect is all it needs.
|
||||
let paste = texturecraft_engine::effect_clipboard::clipboard_effect(&app.session).is_some();
|
||||
// The clipboard items show the layer clipboard's shortcuts, which act on a selected effect.
|
||||
for (label, id, keys, enabled) in [
|
||||
(tr("Copy effect"), "effect.copy", Some("layer.copy"), true),
|
||||
@@ -693,7 +694,8 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) {
|
||||
ui.separator();
|
||||
run(app, ui, tr("Cut layer(s)"), "layer.cut", json!({"layer": lid}), true);
|
||||
run(app, ui, tr("Copy layer(s)"), "layer.copy", json!({"layer": lid}), true);
|
||||
let (paste_layer, paste_effect) = (crate::menus::enabled(app, "layer.paste"), crate::menus::enabled(app, "effect.paste"));
|
||||
let paste_layer = crate::menus::enabled(app, "layer.paste");
|
||||
let paste_effect = texturecraft_engine::effect_clipboard::clipboard_effect(&app.session).is_some();
|
||||
run(app, ui, tr("Paste layer(s)"), "layer.paste", json!({}), paste_layer);
|
||||
run(app, ui, tr("Paste effect"), "effect.paste", json!({}), paste_effect);
|
||||
let paste_instance = crate::menus::enabled(app, "layer.pasteInstance");
|
||||
|
||||
@@ -413,6 +413,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Import an image (File > Import resources) to project it onto the mesh.", "استورد صورة (ملف > استيراد الموارد) لإسقاطها على المجسم."),
|
||||
("Import images to use them in fills and masks", "استورد الصور لاستخدامها في التعبئة والأقنعة"),
|
||||
("Import resources...", "استيراد الموارد..."),
|
||||
("Import MaterialX material...", "استيراد مادة MaterialX..."),
|
||||
("MaterialX materials", "مواد MaterialX"),
|
||||
("Import...", "استيراد..."),
|
||||
("Imported template \"{name}\"", "تم استيراد القالب \"{name}\""),
|
||||
("Imported {name}", "تم استيراد {name}"),
|
||||
@@ -677,6 +679,11 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Restore every default shortcut", "استعادة كل الاختصارات الافتراضية"),
|
||||
("Return to painting mode", "العودة إلى نمط الرسم"),
|
||||
("Return to this step", "العودة إلى هذه الخطوة"),
|
||||
("Auto-rebake", "إعادة الخبز تلقائيًا"),
|
||||
(
|
||||
"Bake this map again by itself when its bake settings, the low poly or the high polys change",
|
||||
"يعيد خبز هذه الخريطة تلقائيًا عند تغيّر إعدادات الخبز أو المجسّم منخفض الدقة أو المجسّمات عالية الدقة",
|
||||
),
|
||||
("Right-click a layer > Create smart material", "انقر بزر الفأرة الأيمن على طبقة > إنشاء مادة ذكية"),
|
||||
("Rotation", "التدوير"),
|
||||
("Rotation (degrees)", "التدوير (بالدرجات)"),
|
||||
|
||||
@@ -440,6 +440,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
),
|
||||
("Import images to use them in fills and masks", "Bilder importieren, um sie in Füllungen und Masken zu verwenden"),
|
||||
("Import resources...", "Ressourcen importieren..."),
|
||||
("Import MaterialX material...", "MaterialX-Material importieren..."),
|
||||
("MaterialX materials", "MaterialX-Materialien"),
|
||||
("Import...", "Importieren..."),
|
||||
("Imported template \"{name}\"", "Vorlage „{name}“ importiert"),
|
||||
("Imported {name}", "{name} importiert"),
|
||||
@@ -719,6 +721,11 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("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"),
|
||||
("Auto-rebake", "Automatisch neu backen"),
|
||||
(
|
||||
"Bake this map again by itself when its bake settings, the low poly or the high polys change",
|
||||
"Diese Map automatisch neu backen, wenn sich ihre Bake-Einstellungen, das Low-Poly- oder die High-Poly-Meshes ändern",
|
||||
),
|
||||
("Right-click a layer > Create smart material", "Rechtsklick auf eine Ebene > Smart-Material erstellen"),
|
||||
("Rotation", "Drehung"),
|
||||
("Rotation (degrees)", "Drehung (Grad)"),
|
||||
|
||||
@@ -431,6 +431,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
),
|
||||
("Import images to use them in fills and masks", "Importar imágenes para usarlas en rellenos y máscaras"),
|
||||
("Import resources...", "Importar recursos..."),
|
||||
("Import MaterialX material...", "Importar material MaterialX..."),
|
||||
("MaterialX materials", "Materiales MaterialX"),
|
||||
("Import...", "Importar..."),
|
||||
("Imported template \"{name}\"", "Plantilla \"{name}\" importada"),
|
||||
("Imported {name}", "{name} importado"),
|
||||
@@ -707,6 +709,11 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("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"),
|
||||
("Auto-rebake", "Rehornear automáticamente"),
|
||||
(
|
||||
"Bake this map again by itself when its bake settings, the low poly or the high polys change",
|
||||
"Vuelve a hornear este mapa automáticamente cuando cambian sus ajustes de horneado, la malla low poly o las high poly",
|
||||
),
|
||||
("Right-click a layer > Create smart material", "Clic derecho en una capa > Crear material inteligente"),
|
||||
("Rotation", "Rotación"),
|
||||
("Rotation (degrees)", "Rotación (grados)"),
|
||||
|
||||
@@ -443,6 +443,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
),
|
||||
("Import images to use them in fills and masks", "Importez des images pour les utiliser dans les remplissages et les masques"),
|
||||
("Import resources...", "Importer des ressources..."),
|
||||
("Import MaterialX material...", "Importer un matériau MaterialX..."),
|
||||
("MaterialX materials", "Matériaux MaterialX"),
|
||||
("Import...", "Importer..."),
|
||||
("Imported template \"{name}\"", "Modèle « {name} » importé"),
|
||||
("Imported {name}", "{name} importé"),
|
||||
@@ -722,6 +724,11 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("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"),
|
||||
("Auto-rebake", "Précalcul automatique"),
|
||||
(
|
||||
"Bake this map again by itself when its bake settings, the low poly or the high polys change",
|
||||
"Précalcule à nouveau cette carte automatiquement quand ses réglages de précalcul, le maillage low poly ou les maillages high poly changent",
|
||||
),
|
||||
("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)"),
|
||||
|
||||
@@ -434,6 +434,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Import an image (File > Import resources) to project it onto the mesh.", "Importa un'immagine (File > Importa risorse) per proiettarla sulla mesh."),
|
||||
("Import images to use them in fills and masks", "Importa immagini per usarle in riempimenti e maschere"),
|
||||
("Import resources...", "Importa risorse..."),
|
||||
("Import MaterialX material...", "Importa materiale MaterialX..."),
|
||||
("MaterialX materials", "Materiali MaterialX"),
|
||||
("Import...", "Importa..."),
|
||||
("Imported template \"{name}\"", "Modello \"{name}\" importato"),
|
||||
("Imported {name}", "{name} importato"),
|
||||
@@ -716,6 +718,11 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("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"),
|
||||
("Auto-rebake", "Bake automatico"),
|
||||
(
|
||||
"Bake this map again by itself when its bake settings, the low poly or the high polys change",
|
||||
"Esegue di nuovo il bake di questa mappa quando cambiano le sue impostazioni di bake, la mesh low poly o le mesh high poly",
|
||||
),
|
||||
("Right-click a layer > Create smart material", "Clic destro su un livello > Crea materiale intelligente"),
|
||||
("Rotation", "Rotazione"),
|
||||
("Rotation (degrees)", "Rotazione (gradi)"),
|
||||
|
||||
@@ -425,6 +425,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
),
|
||||
("Import images to use them in fills and masks", "画像をインポートして塗りつぶしやマスクで使用"),
|
||||
("Import resources...", "リソースをインポート..."),
|
||||
("Import MaterialX material...", "MaterialX マテリアルをインポート..."),
|
||||
("MaterialX materials", "MaterialX マテリアル"),
|
||||
("Import...", "インポート..."),
|
||||
("Imported template \"{name}\"", "テンプレート「{name}」をインポートしました"),
|
||||
("Imported {name}", "{name} をインポートしました"),
|
||||
@@ -698,6 +700,11 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Restore every default shortcut", "すべてのショートカットをデフォルトに戻す"),
|
||||
("Return to painting mode", "ペイントモードに戻る"),
|
||||
("Return to this step", "このステップに戻る"),
|
||||
("Auto-rebake", "自動再ベイク"),
|
||||
(
|
||||
"Bake this map again by itself when its bake settings, the low poly or the high polys change",
|
||||
"ベイク設定、ローポリ、またはハイポリが変わると、このマップを自動的にベイクし直します",
|
||||
),
|
||||
("Right-click a layer > Create smart material", "レイヤーを右クリック > スマートマテリアルを作成"),
|
||||
("Rotation", "回転"),
|
||||
("Rotation (degrees)", "回転 (度)"),
|
||||
|
||||
@@ -419,6 +419,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Import an image (File > Import resources) to project it onto the mesh.", "메시에 투영할 이미지를 가져오세요 (파일 > 리소스 가져오기)."),
|
||||
("Import images to use them in fills and masks", "채우기와 마스크에 사용할 이미지를 가져옵니다"),
|
||||
("Import resources...", "리소스 가져오기..."),
|
||||
("Import MaterialX material...", "MaterialX 머티리얼 가져오기..."),
|
||||
("MaterialX materials", "MaterialX 머티리얼"),
|
||||
("Import...", "가져오기..."),
|
||||
("Imported template \"{name}\"", "템플릿 \"{name}\" 가져옴"),
|
||||
("Imported {name}", "가져옴: {name}"),
|
||||
@@ -689,6 +691,11 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Restore every default shortcut", "모든 기본 단축키를 복원합니다"),
|
||||
("Return to painting mode", "페인팅 모드로 돌아가기"),
|
||||
("Return to this step", "이 단계로 돌아가기"),
|
||||
("Auto-rebake", "자동 다시 베이크"),
|
||||
(
|
||||
"Bake this map again by itself when its bake settings, the low poly or the high polys change",
|
||||
"베이크 설정, 로우 폴리 또는 하이 폴리가 바뀌면 이 맵을 자동으로 다시 베이크합니다",
|
||||
),
|
||||
("Right-click a layer > Create smart material", "레이어 마우스 오른쪽 클릭 > 스마트 머티리얼 만들기"),
|
||||
("Rotation", "회전"),
|
||||
("Rotation (degrees)", "회전 (도)"),
|
||||
|
||||
@@ -428,6 +428,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Import an image (File > Import resources) to project it onto the mesh.", "Importe uma imagem (Arquivo > Importar recursos) para projetá-la na malha."),
|
||||
("Import images to use them in fills and masks", "Importe imagens para usá-las em preenchimentos e máscaras"),
|
||||
("Import resources...", "Importar recursos..."),
|
||||
("Import MaterialX material...", "Importar material MaterialX..."),
|
||||
("MaterialX materials", "Materiais MaterialX"),
|
||||
("Import...", "Importar..."),
|
||||
("Imported template \"{name}\"", "Modelo \"{name}\" importado"),
|
||||
("Imported {name}", "{name} importado"),
|
||||
@@ -704,6 +706,11 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("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"),
|
||||
("Auto-rebake", "Refazer bake automaticamente"),
|
||||
(
|
||||
"Bake this map again by itself when its bake settings, the low poly or the high polys change",
|
||||
"Refaz o bake deste mapa automaticamente quando as configurações de bake, a malha low poly ou as high poly mudam",
|
||||
),
|
||||
("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)"),
|
||||
|
||||
@@ -374,6 +374,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Import an image (File > Import resources) to project it onto the mesh.", "导入图像(文件 > 导入资源)以将其投影到网格上。"),
|
||||
("Import images to use them in fills and masks", "导入图像以在填充和遮罩中使用"),
|
||||
("Import resources...", "导入资源..."),
|
||||
("Import MaterialX material...", "导入 MaterialX 材质..."),
|
||||
("MaterialX materials", "MaterialX 材质"),
|
||||
("Import...", "导入..."),
|
||||
("Imported template \"{name}\"", "已导入模板“{name}”"),
|
||||
("Imported {name}", "已导入 {name}"),
|
||||
@@ -635,6 +637,8 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Restore every default shortcut", "恢复所有默认快捷键"),
|
||||
("Return to painting mode", "返回绘画模式"),
|
||||
("Return to this step", "返回到此步骤"),
|
||||
("Auto-rebake", "自动重新烘焙"),
|
||||
("Bake this map again by itself when its bake settings, the low poly or the high polys change", "当烘焙设置、低模或高模发生变化时,自动重新烘焙此贴图"),
|
||||
("Right-click a layer > Create smart material", "右键单击图层 > 创建智能材质"),
|
||||
("Rotation", "旋转"),
|
||||
("Rotation (degrees)", "旋转(度)"),
|
||||
|
||||
+32
-10
@@ -51,6 +51,8 @@ pub struct BakeJob {
|
||||
pub queue: Vec<usize>,
|
||||
pub current: Option<(usize, Arc<Progress>, std::sync::mpsc::Receiver<texturecraft_engine::Result<texturecraft_engine::bake::BakeOutput>>)>,
|
||||
pub total: usize,
|
||||
/// Bake only this map (an Auto-rebake); None bakes every ticked map.
|
||||
pub only: Option<texturecraft_engine::core::BakedMap>,
|
||||
}
|
||||
|
||||
/// The browser build's notice when WebGPU is unavailable and wgpu fell back to WebGL2.
|
||||
@@ -188,7 +190,7 @@ impl TextureCraftApp {
|
||||
return;
|
||||
}
|
||||
let total = sets.len();
|
||||
self.bake = Some(BakeJob { queue: sets, current: None, total });
|
||||
self.bake = Some(BakeJob { queue: sets, current: None, total, only: None });
|
||||
}
|
||||
|
||||
fn poll_bake(&mut self, ctx: &egui::Context) {
|
||||
@@ -200,19 +202,19 @@ impl TextureCraftApp {
|
||||
let ts = *ts;
|
||||
job.current = None;
|
||||
if let Err(e) = self.session.apply_bake(ts, out) {
|
||||
self.session.bake_abandoned([ts]);
|
||||
self.toast(e.to_string(), true);
|
||||
}
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
job.current = None;
|
||||
let msg = e.to_string();
|
||||
self.bake = None;
|
||||
self.cancel_bake();
|
||||
self.toast(msg, true);
|
||||
return;
|
||||
}
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => return,
|
||||
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
|
||||
self.bake = None;
|
||||
self.cancel_bake();
|
||||
self.toast(i18n::tr("The bake worker stopped"), true);
|
||||
return;
|
||||
}
|
||||
@@ -225,8 +227,9 @@ impl TextureCraftApp {
|
||||
self.toast(i18n::tr("Mesh maps baked"), false);
|
||||
return;
|
||||
}
|
||||
let ts = job.queue.remove(0);
|
||||
match self.session.bake_task(ts) {
|
||||
let (ts, only) = (job.queue.remove(0), job.only);
|
||||
self.session.begin_bake(ts);
|
||||
match self.session.bake_task_for(ts, only) {
|
||||
Ok(task) => {
|
||||
let progress = Arc::new(Progress::new());
|
||||
let p = progress.clone();
|
||||
@@ -235,17 +238,35 @@ impl TextureCraftApp {
|
||||
job.current = Some((ts, progress, rx));
|
||||
}
|
||||
}
|
||||
Err(e) => self.toast(e.to_string(), true),
|
||||
Err(e) => {
|
||||
self.session.bake_abandoned([ts]);
|
||||
self.toast(e.to_string(), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Auto-rebake: when the chosen map's bake inputs changed, bake it again in the background
|
||||
/// (one set after another, only that map), unless a bake or a stroke is running.
|
||||
fn drive_auto_rebake(&mut self) {
|
||||
if self.bake.is_some() || self.session.stroke_active() || self.session.auto_rebake.map.is_none() {
|
||||
return;
|
||||
}
|
||||
let due = self.session.auto_rebake_due();
|
||||
if !due.is_empty() {
|
||||
let total = due.len();
|
||||
self.bake = Some(BakeJob { queue: due, current: None, total, only: self.session.auto_rebake.map });
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops the bake job (also after an error). The set being baked and the queued ones wait for
|
||||
/// their next bake input change before Auto-rebake tries them again.
|
||||
pub fn cancel_bake(&mut self) {
|
||||
if let Some(job) = self.bake.take()
|
||||
&& let Some((_, p, _)) = job.current
|
||||
{
|
||||
let Some(job) = self.bake.take() else { return };
|
||||
if let Some((_, p, _)) = &job.current {
|
||||
p.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
self.session.bake_abandoned(job.current.map(|(ts, ..)| ts).into_iter().chain(job.queue));
|
||||
}
|
||||
|
||||
/// Resize texture set `ts` to `resolution` on a worker thread (the document changes when
|
||||
@@ -381,6 +402,7 @@ impl eframe::App for TextureCraftApp {
|
||||
web_files::dropped(self, ctx, f);
|
||||
}
|
||||
self.poll_bake(ctx);
|
||||
self.drive_auto_rebake();
|
||||
self.poll_resize(ctx);
|
||||
let scale = self.ui.prefs.ui_scale.clamp(0.5, 3.0);
|
||||
if (ctx.zoom_factor() - scale).abs() > 1e-3 {
|
||||
|
||||
@@ -45,6 +45,7 @@ pub const CATALOG: &[Item] = &[
|
||||
it("File", "Remove unused resources...", "file.removeUnused", None),
|
||||
sep("File"),
|
||||
it("File", "Import resources...", "resource.import", None),
|
||||
it("File", "Import MaterialX material...", "file.importMaterialX", None),
|
||||
it("File", "Export Textures...", "ui.export", Some("Ctrl+Shift+E")),
|
||||
it("File", "Export Mesh...", "file.exportMesh", None),
|
||||
sep("File"),
|
||||
|
||||
@@ -723,7 +723,17 @@ fn bake_panel(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
ui.separator();
|
||||
match selected {
|
||||
None => common_params(app, ui, &mut b),
|
||||
Some(m) => map_params(ui, m, &mut b),
|
||||
Some(m) => {
|
||||
let mut auto = app.session.auto_rebake.map == Some(m);
|
||||
if ui
|
||||
.checkbox(&mut auto, tr("Auto-rebake"))
|
||||
.on_hover_text(tr("Bake this map again by itself when its bake settings, the low poly or the high polys change"))
|
||||
.changed()
|
||||
{
|
||||
app.run("bake.autoRebake", if auto { json!({ "map": m.id() }) } else { json!({ "off": true }) });
|
||||
}
|
||||
map_params(ui, m, &mut b)
|
||||
}
|
||||
}
|
||||
if b.direction == [0.0; 3] {
|
||||
b.direction = before.direction;
|
||||
@@ -1038,6 +1048,19 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) ->
|
||||
app.ui.dock.focus(crate::docking::Panel::Assets);
|
||||
true
|
||||
}
|
||||
"file.importMaterialX" => {
|
||||
if let Some(p) = rfd::FileDialog::new().add_filter(tr("MaterialX materials"), &["mtlx"]).pick_file()
|
||||
&& let Some(r) = app.run("file.importMaterialX", json!({"path": p.display().to_string()}))
|
||||
{
|
||||
let name = r.get("material").and_then(|n| n.as_str()).unwrap_or_default().to_string();
|
||||
for w in r.get("warnings").and_then(|w| w.as_array()).into_iter().flatten().filter_map(|w| w.as_str()) {
|
||||
app.session.log.push(format!("MaterialX {name}: {w}"));
|
||||
}
|
||||
app.toast(trf("Imported {name}", &[("name", &name)]), false);
|
||||
app.ui.dock.focus(crate::docking::Panel::Layers);
|
||||
}
|
||||
true
|
||||
}
|
||||
"file.exportMesh" => {
|
||||
let name = format!("{}.obj", texturecraft_engine::formats::export::sanitize_file_stem(&app.session.doc.project.name));
|
||||
if let Some(p) = rfd::FileDialog::new()
|
||||
|
||||
+2
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Each row is a menu item of the target menu layout with TextureCraft's command id; **live** means the id is implemented. Feature parity beyond menus is tracked in [`ROADMAP.md`](../ROADMAP.md).
|
||||
|
||||
**53 of 53 menu items live (100%).**
|
||||
**54 of 54 menu items live (100%).**
|
||||
|
||||
## File
|
||||
|
||||
@@ -17,6 +17,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac
|
||||
| Save a copy... | `file.saveCopy` | | live |
|
||||
| Remove unused resources... | `file.removeUnused` | | live |
|
||||
| Import resources... | `resource.import` | | live |
|
||||
| Import MaterialX material... | `file.importMaterialX` | | live |
|
||||
| Export Textures... | `ui.export` | Ctrl+Shift+E | live |
|
||||
| Export Mesh... | `file.exportMesh` | | live |
|
||||
| Quit | `ui.quit` | Ctrl+Q | live |
|
||||
|
||||
Reference in new issue
Block a user