mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-28 09:09:25 +01:00
Merge main into feat/materialx-import
# Conflicts: # crates/engine/src/lib.rs
This commit is contained in:
commit
296f439f53
17 files changed
+192
-7
No files matched your search
@@ -63,6 +63,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::camera_cmds::specs());
|
||||
v.extend(crate::quick_mask::specs());
|
||||
v.extend(crate::set_cmds::specs());
|
||||
v.extend(crate::meshmap_cmds::specs());
|
||||
v.extend(crate::uv_tile_cmds::specs());
|
||||
v.extend(crate::template_cmds::specs());
|
||||
v.extend(crate::project_cmds::specs());
|
||||
|
||||
@@ -23,6 +23,7 @@ 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;
|
||||
// Mesh reimport reads files: native only.
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
//! Mesh map slots of the Texture Set Settings: use an image resource as a mesh map (baked in
|
||||
//! another app, or edited by hand) instead of baking it, or clear a slot.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use rayon::prelude::*;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_compose::ImageRes;
|
||||
use texturecraft_core::{BakedMap, MAX_RESOLUTION, NormalFormat};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, strp};
|
||||
use crate::set_cmds::ts_param;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"textureSet.meshMap.set",
|
||||
"Use image as mesh map",
|
||||
[],
|
||||
None,
|
||||
"{ts?, map: mesh map id (normal_base, ambient_occlusion, curvature, id, height…), image: resource name} → {map, resolution} — resampled to the size of the set's other mesh maps (or its bake size); a normal map is read in the project's normal format",
|
||||
always,
|
||||
set
|
||||
),
|
||||
cmd!("textureSet.meshMap.clear", "Clear mesh map", [], None, "{ts?, map}", always, clear),
|
||||
]
|
||||
}
|
||||
|
||||
fn map_param(p: &Value, cmd: &str) -> Result<BakedMap> {
|
||||
let id = strp(p, "map").ok_or_else(|| bad(cmd, "`map` is required"))?;
|
||||
BakedMap::parse(id).ok_or_else(|| bad(cmd, format!("unknown mesh map `{id}`")))
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "textureSet.meshMap.set";
|
||||
let ts = ts_param(s, p, CMD)?;
|
||||
let map = map_param(p, CMD)?;
|
||||
let name = strp(p, "image").ok_or_else(|| bad(CMD, "`image` (an image resource name) is required"))?;
|
||||
let img = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?;
|
||||
let set = s.doc.project.texture_set(ts)?;
|
||||
// shortcut: one image spans the whole set; UV-tiled sets would need one image per tile.
|
||||
if !set.uv_tiles.is_empty() {
|
||||
return Err(bad(CMD, format!("\"{}\" has UV tiles: mesh maps from images need a set without them", set.name)));
|
||||
}
|
||||
// Every mesh map of a set shares one size: the other maps', or what a bake would make.
|
||||
let res = s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()).map_or(set.bake.resolution, |b| b.resolution);
|
||||
if !(1..=MAX_RESOLUTION).contains(&res) {
|
||||
return Err(bad(CMD, format!("mesh map size {res} is not in 1..={MAX_RESOLUTION}")));
|
||||
}
|
||||
let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX;
|
||||
let data = resample(&img, map.components(), res, directx);
|
||||
s.edit("Use image as mesh map", |s| {
|
||||
let entry = s.doc.baked.entry(ts).or_default();
|
||||
entry.resolution = res;
|
||||
entry.maps.insert(map, Arc::new(data));
|
||||
s.doc.project.texture_set_mut(ts)?.baked.insert(map);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "map": map.id(), "resolution": res }))
|
||||
}
|
||||
|
||||
/// `img` as `res` × `res` texels of `comps` values each, as stored in the file (mesh maps hold
|
||||
/// data, not colors, so nothing is linearized); `flip_green` reads a DirectX normal map.
|
||||
fn resample(img: &ImageRes, comps: usize, res: u32, flip_green: bool) -> Vec<f32> {
|
||||
let n = res as usize;
|
||||
let mut out = vec![0.0; n * n * comps];
|
||||
out.par_chunks_mut(n * comps).enumerate().for_each(|(y, row)| {
|
||||
let v = (y as f32 + 0.5) / res as f32;
|
||||
for (x, texel) in row.chunks_exact_mut(comps).enumerate() {
|
||||
let mut c = img.sample((x as f32 + 0.5) / res as f32, v);
|
||||
if flip_green {
|
||||
c[1] = 1.0 - c[1];
|
||||
}
|
||||
for (o, c) in texel.iter_mut().zip(c) {
|
||||
*o = c;
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "textureSet.meshMap.clear";
|
||||
let ts = ts_param(s, p, CMD)?;
|
||||
let map = map_param(p, CMD)?;
|
||||
if !s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) {
|
||||
return Err(bad(CMD, format!("texture set {ts} has no {} map", map.label())));
|
||||
}
|
||||
s.edit("Clear mesh map", |s| {
|
||||
if let Some(b) = s.doc.baked.get_mut(&ts) {
|
||||
b.maps.remove(&map);
|
||||
}
|
||||
s.doc.project.texture_set_mut(ts)?.baked.remove(&map);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The filter library, geometry decals, cloning from the selected layer, placing saved smart
|
||||
//! materials, anchors inside a content stack and instances across texture set resolutions,
|
||||
//! through engine commands.
|
||||
//! materials, anchors inside a content stack, instances across texture set resolutions and mesh
|
||||
//! maps from images, through engine commands.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{Channel, EffectKind, Filter, LayerId, LayerKind, Projection};
|
||||
@@ -375,3 +375,37 @@ fn geometry_mask_tool_toggles_the_clicked_part() {
|
||||
assert_eq!(s.doc.project.layer(layer).unwrap().geometry_mask, Some(vec!["Lid".to_string()]));
|
||||
assert!(execute(&mut s, "tool.click", &json!({"x": 1, "y": 1})).is_err(), "nothing under the point");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn images_fill_mesh_map_slots() {
|
||||
use texturecraft_engine::core::BakedMap;
|
||||
let mut s = session();
|
||||
// Dark on the left, light on the right.
|
||||
let ao = s.import_resource_bytes("ao.png", png(8, 8, |x, _| if x < 4 { [64, 64, 64, 255] } else { [192, 192, 192, 255] })).unwrap();
|
||||
let r = execute(&mut s, "textureSet.meshMap.set", &json!({"map": "ambient_occlusion", "image": ao})).unwrap();
|
||||
let res = s.doc.project.texture_sets[0].bake.resolution;
|
||||
assert_eq!(r, json!({"map": "ambient_occlusion", "resolution": res}));
|
||||
assert!(s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion));
|
||||
let sample = |s: &Session, m: BakedMap, x: u32| s.baked(0).unwrap().sample(m, x, 50, 100).unwrap();
|
||||
assert!((sample(&s, BakedMap::AmbientOcclusion, 10)[0] - 64.0 / 255.0).abs() < 1e-3, "raw file values, not linearized");
|
||||
assert!((sample(&s, BakedMap::AmbientOcclusion, 90)[0] - 192.0 / 255.0).abs() < 1e-3);
|
||||
// A normal map is read in the project's normal format (DirectX: green flipped).
|
||||
execute(&mut s, "textureSet.settings", &json!({"normalFormat": "directX"})).unwrap();
|
||||
let n = s.import_resource_bytes("n.png", png(2, 2, |_, _| [128, 64, 255, 255])).unwrap();
|
||||
execute(&mut s, "textureSet.meshMap.set", &json!({"map": "normal", "image": n})).unwrap();
|
||||
let v = sample(&s, BakedMap::Normal, 50);
|
||||
assert!((v[1] - (1.0 - 64.0 / 255.0)).abs() < 1e-3 && (v[2] - 1.0).abs() < 1e-3, "{v:?}");
|
||||
// Clearing empties the slot (one undo step); bad params are errors.
|
||||
execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambient_occlusion"})).unwrap();
|
||||
assert!(s.baked(0).unwrap().sample(BakedMap::AmbientOcclusion, 0, 0, 100).is_none());
|
||||
assert!(!s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion));
|
||||
assert!(execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambient_occlusion"})).is_err(), "already empty");
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
assert!(s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion));
|
||||
assert!(execute(&mut s, "textureSet.meshMap.set", &json!({"map": "nope", "image": ao})).is_err());
|
||||
assert!(execute(&mut s, "textureSet.meshMap.set", &json!({"map": "curvature", "image": "missing.png"})).is_err());
|
||||
assert!(execute(&mut s, "textureSet.meshMap.set", &json!({"map": "curvature"})).is_err());
|
||||
// The maps are saved with the project.
|
||||
let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
|
||||
assert_eq!(back.doc.baked, s.doc.baked);
|
||||
}
|
||||
@@ -762,10 +762,10 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
});
|
||||
});
|
||||
let baked = app.session.doc.baked.get(&ts);
|
||||
let images: Vec<String> = app.session.doc.resources.keys().cloned().collect();
|
||||
for m in BakedMap::ALL {
|
||||
let present = baked.is_some_and(|b| b.maps.contains_key(&m));
|
||||
ui.horizontal(|ui| {
|
||||
let present = app.session.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&m));
|
||||
let row = ui.horizontal(|ui| {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(26.0, 26.0), Sense::hover());
|
||||
ui.painter().rect_filled(r, 2.0, if present { mesh_map_color(m) } else { tk.button });
|
||||
ui.vertical(|ui| {
|
||||
@@ -776,7 +776,36 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
.color(tk.text_dim),
|
||||
);
|
||||
});
|
||||
// An image resource instead of a bake, or no map.
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.menu_button(RichText::new(ic::DOTS_THREE).size(13.0), |ui| {
|
||||
ui.label(caption(tr("Images")));
|
||||
for name in &images {
|
||||
if ui.button(name).clicked() {
|
||||
app.run("textureSet.meshMap.set", json!({"ts": ts, "map": m.id(), "image": name}));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
if ui.button(tr("Import...")).clicked() {
|
||||
crate::menus::invoke(app, ui.ctx(), "resource.import");
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if ui.add_enabled(present, egui::Button::new(tr("Clear"))).clicked() {
|
||||
app.run("textureSet.meshMap.clear", json!({"ts": ts, "map": m.id()}));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
// A shelf image dropped on the row becomes this mesh map.
|
||||
let resp = row.response.interact(Sense::hover()).on_hover_text(tr("Drop an image from the Assets panel here to use it as this mesh map"));
|
||||
if resp.dnd_hover_payload::<ShelfDrag>().is_some_and(|d| matches!(d.asset, Asset::Texture(_))) {
|
||||
ui.painter().rect_stroke(resp.rect.shrink(1.0), 3.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside);
|
||||
}
|
||||
if let Some(Asset::Texture(name)) = dnd_release::<ShelfDrag>(&resp).map(|d| d.asset.clone()) {
|
||||
app.run("textureSet.meshMap.set", json!({"ts": ts, "map": m.id(), "image": name}));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -263,6 +263,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Drag the frame to move the decal, a corner to scale it, the round handle to turn it",
|
||||
"اسحب الإطار لتحريك الملصق، أو الزاوية لتغيير حجمه، أو المقبض الدائري لتدويره",
|
||||
),
|
||||
("Drop an image from the Assets panel here to use it as this mesh map", "أفلت صورة من لوحة الأصول هنا لاستخدامها كخريطة المجسم هذه"),
|
||||
("Dry streaks", "خطوط جافة"),
|
||||
("Duplicate layer(s)", "تكرار الطبقة (الطبقات)"),
|
||||
("Duplicate the selected template", "تكرار القالب المحدد"),
|
||||
|
||||
@@ -281,6 +281,10 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Drag the frame to move the decal, a corner to scale it, the round handle to turn it",
|
||||
"Rahmen ziehen, um das Decal zu verschieben, eine Ecke zum Skalieren, den runden Griff zum Drehen",
|
||||
),
|
||||
(
|
||||
"Drop an image from the Assets panel here to use it as this mesh map",
|
||||
"Ein Bild aus dem Assets-Panel hier ablegen, um es als diese Mesh-Map zu verwenden",
|
||||
),
|
||||
("Dry streaks", "Trockene Schlieren"),
|
||||
("Duplicate layer(s)", "Ebene(n) duplizieren"),
|
||||
("Duplicate the selected template", "Ausgewählte Vorlage duplizieren"),
|
||||
|
||||
@@ -278,6 +278,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Drag the frame to move the decal, a corner to scale it, the round handle to turn it",
|
||||
"Arrastra el marco para mover la calcomanía, una esquina para escalarla y el tirador redondo para girarla",
|
||||
),
|
||||
("Drop an image from the Assets panel here to use it as this mesh map", "Suelta aquí una imagen del panel Recursos para usarla como este mapa de malla"),
|
||||
("Dry streaks", "Trazos secos"),
|
||||
("Duplicate layer(s)", "Duplicar capa(s)"),
|
||||
("Duplicate the selected template", "Duplicar la plantilla seleccionada"),
|
||||
|
||||
@@ -281,6 +281,10 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Drag the frame to move the decal, a corner to scale it, the round handle to turn it",
|
||||
"Faites glisser le cadre pour déplacer le décalque, un coin pour le mettre à l'échelle, la poignée ronde pour le faire pivoter",
|
||||
),
|
||||
(
|
||||
"Drop an image from the Assets panel here to use it as this mesh map",
|
||||
"Déposez ici une image du panneau Ressources pour l'utiliser comme cette carte de maillage",
|
||||
),
|
||||
("Dry streaks", "Traînées sèches"),
|
||||
("Duplicate layer(s)", "Dupliquer le(s) calque(s)"),
|
||||
("Duplicate the selected template", "Dupliquer le modèle sélectionné"),
|
||||
|
||||
@@ -284,6 +284,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Drag the frame to move the decal, a corner to scale it, the round handle to turn it",
|
||||
"Trascina il riquadro per spostare la decal, un angolo per scalarla, la maniglia rotonda per ruotarla",
|
||||
),
|
||||
("Drop an image from the Assets panel here to use it as this mesh map", "Rilascia qui un'immagine dal pannello Risorse per usarla come questa mappa mesh"),
|
||||
("Dry streaks", "Striature secche"),
|
||||
("Duplicate layer(s)", "Duplica livello/i"),
|
||||
("Duplicate the selected template", "Duplica il modello selezionato"),
|
||||
|
||||
@@ -272,6 +272,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Draws {name} of texture set \"{set}\". Edits to the source show in every instance.",
|
||||
"テクスチャセット「{set}」の {name} を描画します。ソースへの編集はすべてのインスタンスに反映されます。",
|
||||
),
|
||||
("Drop an image from the Assets panel here to use it as this mesh map", "アセットパネルから画像をここにドロップすると、このメッシュマップとして使用します"),
|
||||
("Dry streaks", "かすれ"),
|
||||
("Duplicate layer(s)", "レイヤーを複製"),
|
||||
("Duplicate the selected template", "選択中のテンプレートを複製"),
|
||||
|
||||
@@ -269,6 +269,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Draws {name} of texture set \"{set}\". Edits to the source show in every instance.",
|
||||
"텍스처 세트 \"{set}\"의 {name}을(를) 그립니다. 원본을 편집하면 모든 인스턴스에 반영됩니다.",
|
||||
),
|
||||
("Drop an image from the Assets panel here to use it as this mesh map", "에셋 패널의 이미지를 여기에 놓으면 이 메시 맵으로 사용합니다"),
|
||||
("Dry streaks", "마른 붓자국"),
|
||||
("Duplicate layer(s)", "레이어 복제"),
|
||||
("Duplicate the selected template", "선택한 템플릿을 복제합니다"),
|
||||
|
||||
@@ -278,6 +278,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Drag the frame to move the decal, a corner to scale it, the round handle to turn it",
|
||||
"Arraste o quadro para mover o decalque, um canto para redimensioná-lo e a alça redonda para girá-lo",
|
||||
),
|
||||
("Drop an image from the Assets panel here to use it as this mesh map", "Solte aqui uma imagem do painel Recursos para usá-la como este mapa de malha"),
|
||||
("Dry streaks", "Estrias secas"),
|
||||
("Duplicate layer(s)", "Duplicar camada(s)"),
|
||||
("Duplicate the selected template", "Duplicar o modelo selecionado"),
|
||||
|
||||
@@ -239,6 +239,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "拖动边框移动贴花,拖动角缩放,拖动圆形手柄旋转"),
|
||||
("Drags the layer stack's values along the stroke into the selected layer.", "沿笔画将图层堆栈的值拖入所选图层。"),
|
||||
("Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", "绘制纹理集“{set}”的 {name}。对源的编辑会显示在每个实例中。"),
|
||||
("Drop an image from the Assets panel here to use it as this mesh map", "将资产面板中的图像拖放到此处,用作此网格贴图"),
|
||||
("Dry streaks", "干笔条纹"),
|
||||
("Duplicate layer(s)", "创建图层副本"),
|
||||
("Duplicate the selected template", "创建所选模板的副本"),
|
||||
|
||||
@@ -62,6 +62,11 @@ fn window_snapshots() {
|
||||
h.state_mut().ui.windows.settings = true;
|
||||
save(&mut h, &dir, "window-settings");
|
||||
h.state_mut().ui.windows.settings = false;
|
||||
// The mesh map slots, each with its menu of images (a tall window shows them all).
|
||||
h.state_mut().ui.dock.focus(Panel::TextureSetSettings);
|
||||
h.set_size(egui::vec2(1600.0, 1800.0));
|
||||
save(&mut h, &dir, "panel-texture-set-settings");
|
||||
h.set_size(egui::vec2(1600.0, 960.0));
|
||||
// A mask's levels effect over clouds: the histogram in Properties.
|
||||
let s = &mut h.state_mut().session;
|
||||
for (id, p) in [
|
||||
|
||||
@@ -129,7 +129,7 @@ takes a font family, not a path: it reads only the system's font folders.
|
||||
| `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter |
|
||||
| `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (usda / usdc textures next to it) → `{path, textures?}` |
|
||||
| `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` |
|
||||
| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil` |
|
||||
| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot) |
|
||||
| `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root |
|
||||
| `material_load` | `{path}` | Add a `.tcmat` smart material above the selection |
|
||||
| `textures_export` | `{dir, preset?, ts?, format?, padding?, size?}` | Writes files below the write root |
|
||||
|
||||
+3
-1
@@ -79,7 +79,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
|
||||
- **Bake mesh maps** on the GPU (ray traced, about 12× the CPU path) or on every CPU core: ambient
|
||||
occlusion, curvature, thickness, world-space normal, position, ID, bent normals, opacity, color
|
||||
and direction maps, and normal and height maps from high-poly meshes, with a cage, ray distances
|
||||
and matching by mesh name.
|
||||
and matching by mesh name. Or **use your own images** as mesh maps (baked in another app, or
|
||||
edited): drop one from the Assets panel on a slot of the Texture Set Settings, or pick it from
|
||||
the slot's menu.
|
||||
- **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map),
|
||||
Unity Standard, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz,
|
||||
anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in
|
||||
|
||||
Reference in new issue
Block a user