Load OBJ, glTF and GLB meshes into the 3D view

Meshes are normalized to the unit sphere, keep their normals and UVs (box
projection when they have none) and get MikkTSpace tangents. Scene > Load
mesh in the 3D view, view.3d.loadMesh for agents, file drops and the browser
picker; headless renders use the mesh too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bflatasticandClaude Opus 5.5 committed 2026-11-02 04:35:43 +07:00
1 parent 5dcc8942bc
commit 39f9d65621
14 files changed
+410 -21

No files matched your search

Generated
+75 -2
View File
@@ -415,6 +415,12 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
[[package]]
name = "base64"
version = "0.22.1"
@@ -514,6 +520,12 @@ dependencies = [
"syn 3.0.9",
]
[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
@@ -1573,6 +1585,45 @@ dependencies = [
"web-sys",
]
[[package]]
name = "gltf"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3ce1918195723ce6ac74e80542c5a96a40c2b26162c1957a5cd70799b8cacf7"
dependencies = [
"base64 0.13.1",
"byteorder",
"gltf-json",
"image",
"lazy_static",
"serde_json",
"urlencoding",
]
[[package]]
name = "gltf-derive"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14070e711538afba5d6c807edb74bcb84e5dbb9211a3bf5dea0dfab5b24f4c51"
dependencies = [
"inflections",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "gltf-json"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6176f9d60a7eab0a877e8e96548605dedbde9190a7ae1e80bbcc1c9af03ab14"
dependencies = [
"gltf-derive",
"serde",
"serde_derive",
"serde_json",
]
[[package]]
name = "glutin"
version = "0.32.3"
@@ -1974,6 +2025,12 @@ dependencies = [
"serde_core",
]
[[package]]
name = "inflections"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a257582fdcde896fd96463bf2d40eefea0580021c0712a0e2b028b60b47a837a"
[[package]]
name = "io-extras"
version = "0.19.0"
@@ -2266,7 +2323,7 @@ dependencies = [
name = "materialcraft-automation"
version = "0.1.0"
dependencies = [
"base64",
"base64 0.22.1",
"cap-std",
"getrandom 0.3.4",
"image",
@@ -2309,6 +2366,7 @@ dependencies = [
"materialcraft-core",
"materialcraft-eval",
"materialcraft-formats",
"materialcraft-geom",
"materialcraft-image",
"materialcraft-nodes",
"serde",
@@ -2330,11 +2388,14 @@ dependencies = [
name = "materialcraft-formats"
version = "0.1.0"
dependencies = [
"gltf",
"image",
"materialcraft-core",
"materialcraft-geom",
"materialcraft-image",
"serde_json",
"thiserror 2.0.21",
"tobj",
"zip",
]
@@ -2379,7 +2440,7 @@ dependencies = [
name = "materialcraft-ui-egui"
version = "0.1.0"
dependencies = [
"base64",
"base64 0.22.1",
"craft-ui",
"eframe",
"egui",
@@ -4009,6 +4070,12 @@ dependencies = [
"zerovec",
]
[[package]]
name = "tobj"
version = "4.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6eb8e04167c1c0c76b5de63226fd733485ad63ef71e40de31e16272f47b099e2"
[[package]]
name = "tokio"
version = "1.54.1"
@@ -4215,6 +4282,12 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"
[[package]]
name = "urlencoding"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
[[package]]
name = "utf16_iter"
version = "1.1.0"
+2
View File
@@ -69,6 +69,8 @@ egui = "0.37"
wgpu = "30"
rfd = "0.17"
zip = { version = "2", default-features = false, features = ["deflate"] }
gltf = { version = "1.4", default-features = false, features = ["import", "utils"] }
tobj = { version = "4", default-features = false }
mikktspace = { version = "0.3", default-features = false, features = ["glam"] }
rmcp = { version = "3.5", default-features = false, features = ["server", "macros", "transport-io"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] }
+8 -2
View File
@@ -212,8 +212,14 @@ impl Headless {
fn render_3d(&mut self, o: &RenderOptions, max: u32) -> (u32, u32, Vec<u8>) {
let v = &self.session.view3d;
let scene_id = o.scene.clone().unwrap_or_else(|| v.scene.clone());
if self.scene.as_ref().is_none_or(|(id, _)| *id != scene_id) {
self.scene = Some((scene_id.clone(), Scene::builtin(&scene_id)));
let custom = self.session.custom_mesh.clone().filter(|_| scene_id == "custom");
let key = custom.as_ref().map_or_else(|| scene_id.clone(), |(n, _)| format!("custom:{n}"));
if self.scene.as_ref().is_none_or(|(id, _)| *id != key) {
let scene = match custom {
Some((_, mesh)) => Scene::new((*mesh).clone()),
None => Scene::builtin(&scene_id),
};
self.scene = Some((key, scene));
}
if self.light.as_ref().is_none_or(|l| l.name != v.environment) {
self.light = Some(Lighting::new(&v.environment));
+1
View File
@@ -14,6 +14,7 @@ materialcraft-image = { workspace = true }
materialcraft-nodes = { workspace = true }
materialcraft-eval = { workspace = true }
materialcraft-formats = { workspace = true }
materialcraft-geom = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
+11
View File
@@ -101,6 +101,8 @@ pub struct Session {
pub dirty: bool,
/// Cooked node outputs, shared with background cooks.
pub cache: Arc<Mutex<Cache>>,
/// A mesh loaded for the 3D view (`scene: "custom"`): its file name and geometry.
pub custom_mesh: Option<(String, Arc<materialcraft_geom::Mesh>)>,
undo: Vec<Snapshot>,
redo: Vec<Snapshot>,
/// Edits with the same key coalesce into one undo step (slider drags).
@@ -124,6 +126,7 @@ impl Session {
cooked: Cooked::default(),
dirty: true,
cache: Arc::new(Mutex::new(Cache::default())),
custom_mesh: None,
undo: Vec::new(),
redo: Vec::new(),
merge_key: None,
@@ -305,6 +308,14 @@ impl Session {
materialcraft_eval::outputs(g, &self.cooked).into_iter().filter_map(|(_, usage, _, img)| Some((usage, img?))).collect()
}
/// Show a mesh file in the 3D view (OBJ, glTF, GLB).
pub fn load_mesh_bytes(&mut self, name: &str, bytes: &[u8]) -> Result<()> {
let mesh = materialcraft_formats::mesh::load_mesh(name, bytes)?;
self.custom_mesh = Some((name.to_string(), Arc::new(mesh)));
self.view3d.scene = "custom".into();
Ok(())
}
pub fn log(&mut self, msg: impl Into<String>) {
self.log.push(msg.into());
if self.log.len() > 500 {
+22 -2
View File
@@ -33,6 +33,7 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
always,
view3d
),
cmd!("view.3d.loadMesh", "Load mesh...", [], None, "{path} shows an OBJ, glTF or GLB mesh in the 3D view (scene \"custom\")", always, load_mesh),
cmd!("view.3d.reset", "Reset scene", [], None, "{}", always, |s, _| {
s.view3d = crate::View3d::default();
Ok(J::Null)
@@ -81,13 +82,17 @@ fn view2d(s: &mut Session, p: &J) -> Result<J> {
}
fn view3d(s: &mut Session, p: &J) -> Result<J> {
let v = &mut s.view3d;
if let Some(sc) = strp(p, "scene") {
if !SCENES.iter().any(|(id, _)| *id == sc) {
if sc == "custom" && s.custom_mesh.is_none() {
return Err(bad("view.3d", "no mesh is loaded: use view.3d.loadMesh"));
}
let v = &mut s.view3d;
if sc != "custom" && !SCENES.iter().any(|(id, _)| *id == sc) {
return Err(bad("view.3d", format!("unknown scene `{sc}`")));
}
v.scene = sc.into();
}
let v = &mut s.view3d;
if let Some(e) = strp(p, "environment") {
if !ENVIRONMENTS.iter().any(|(id, _)| *id == e) {
return Err(bad("view.3d", format!("unknown environment `{e}`")));
@@ -124,6 +129,21 @@ fn view3d(s: &mut Session, p: &J) -> Result<J> {
Ok(serde_json::to_value(&s.view3d).unwrap_or(J::Null))
}
#[cfg(not(target_arch = "wasm32"))]
fn load_mesh(s: &mut Session, p: &J) -> Result<J> {
let path = strp(p, "path").ok_or_else(|| bad("view.3d.loadMesh", "`path` is required"))?;
let bytes = std::fs::read(path).map_err(|e| bad("view.3d.loadMesh", format!("{path}: {e}")))?;
let name = std::path::Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or(path).to_string();
s.load_mesh_bytes(&name, &bytes)?;
let tris = s.custom_mesh.as_ref().map_or(0, |(_, m)| m.triangle_count());
Ok(json!({"name": name, "triangles": tris}))
}
#[cfg(target_arch = "wasm32")]
fn load_mesh(_: &mut Session, _: &J) -> Result<J> {
Err(bad("view.3d.loadMesh", "the browser loads meshes with the file picker"))
}
fn preview_size(s: &mut Session, p: &J) -> Result<J> {
let size = u64p(p, "size").ok_or_else(|| bad("view.previewSize", "`size` is required"))?;
s.preview_size = if size == 0 { None } else { Some(size.clamp(64, 8192) as u32) };
+3
View File
@@ -11,6 +11,9 @@ workspace = true
[dependencies]
materialcraft-core = { workspace = true }
materialcraft-image = { workspace = true }
materialcraft-geom = { workspace = true }
gltf = { workspace = true }
tobj = { workspace = true }
image = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
+4 -1
View File
@@ -2,11 +2,14 @@
//!
//! File formats, L2: the native `.mcraft` package (a zip holding `package.json` and the embedded
//! `resources/`), bitmap decoding for Bitmap nodes, and texture export (PNG 8/16, JPEG, TGA,
//! TIFF 8/16, BMP, WEBP, EXR 32F, HDR) with the output naming pattern. Byte-based APIs work
//! TIFF 8/16, BMP, WEBP, EXR 32F, HDR) with the output naming pattern, and meshes for the 3D view
//! (OBJ, glTF/GLB). Byte-based APIs work
//! everywhere, including the browser; path helpers are native only.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod mesh;
use std::io::{Cursor, Read, Write};
use std::sync::Arc;
+163
View File
@@ -0,0 +1,163 @@
//! Meshes for the 3D view: OBJ and glTF/GLB (self-contained: embedded or data-URI buffers),
//! normalized to fit a unit sphere at the origin, with normals, tangents and (when the file has
//! none) generated UVs.
use materialcraft_geom::Mesh;
use materialcraft_geom::glam::{Vec2, Vec3};
use crate::{FormatError, Result};
/// Mesh file extensions [`load_mesh`] reads.
pub const MESH_EXTENSIONS: &[&str] = &["obj", "glb", "gltf"];
/// Largest mesh accepted (triangles).
const MAX_TRIANGLES: usize = 4_000_000;
fn bad(msg: impl Into<String>) -> FormatError {
FormatError::BadPackage(msg.into())
}
/// Parse a mesh file by extension.
pub fn load_mesh(name: &str, bytes: &[u8]) -> Result<Mesh> {
let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();
let mut mesh = match ext.as_str() {
"obj" => obj(bytes)?,
"glb" | "gltf" => gltf(bytes)?,
other => return Err(bad(format!("unsupported mesh format `{other}` (OBJ, glTF or GLB)"))),
};
if mesh.indices.is_empty() || mesh.positions.is_empty() {
return Err(bad("the mesh has no triangles"));
}
if mesh.triangle_count() > MAX_TRIANGLES {
return Err(bad(format!("the mesh has {} triangles (limit {MAX_TRIANGLES})", mesh.triangle_count())));
}
if mesh.uvs.len() != mesh.positions.len() || mesh.uvs.iter().all(|u| *u == mesh.uvs[0]) {
// No usable UVs: a box projection keeps materials tiling across the surface.
mesh.uvs = box_uvs(&mesh);
}
mesh.normalize_to(1.0);
if mesh.normals.len() != mesh.positions.len() {
mesh.compute_normals();
}
mesh.compute_tangents();
mesh.validate().map_err(|e| bad(e.to_string()))?;
Ok(mesh)
}
fn obj(bytes: &[u8]) -> Result<Mesh> {
let mut reader = std::io::BufReader::new(bytes);
let opts = tobj::LoadOptions { triangulate: true, single_index: true, ..Default::default() };
let (models, _) = tobj::load_obj_buf(&mut reader, &opts, |_| Ok((Vec::new(), Default::default()))).map_err(|e| bad(format!("OBJ: {e}")))?;
let mut positions = Vec::new();
let mut normals = Vec::new();
let mut uvs = Vec::new();
let mut indices = Vec::new();
for m in models {
let base = positions.len() as u32;
let mesh = &m.mesh;
let n = mesh.positions.len() / 3;
for i in 0..n {
positions.push(Vec3::new(mesh.positions[i * 3], mesh.positions[i * 3 + 1], mesh.positions[i * 3 + 2]));
if mesh.normals.len() == mesh.positions.len() {
normals.push(Vec3::new(mesh.normals[i * 3], mesh.normals[i * 3 + 1], mesh.normals[i * 3 + 2]));
}
// OBJ UVs have their origin at the bottom left.
uvs.push(mesh.texcoords.get(i * 2..i * 2 + 2).map_or(Vec2::ZERO, |t| Vec2::new(t[0], 1.0 - t[1])));
}
indices.extend(mesh.indices.iter().filter(|i| (**i as usize) < n).map(|i| i + base));
if indices.len() / 3 > MAX_TRIANGLES {
return Err(bad("the mesh is too large"));
}
}
indices.truncate(indices.len() / 3 * 3);
let normals = (normals.len() == positions.len()).then_some(normals);
Mesh::from_parts(positions, normals, uvs, indices, "material").map_err(|e| bad(e.to_string()))
}
fn gltf(bytes: &[u8]) -> Result<Mesh> {
let (doc, buffers, _) = gltf::import_slice(bytes).map_err(|e| bad(format!("glTF: {e}")))?;
let mut positions = Vec::new();
let mut normals = Vec::new();
let mut uvs = Vec::new();
let mut indices = Vec::new();
let mut all_normals = true;
for node in doc.nodes() {
let Some(mesh) = node.mesh() else { continue };
let m = materialcraft_geom::glam::Mat4::from_cols_array_2d(&node.transform().matrix());
for prim in mesh.primitives() {
if prim.mode() != gltf::mesh::Mode::Triangles {
continue;
}
let reader = prim.reader(|b| buffers.get(b.index()).map(|d| d.0.as_slice()));
let Some(pos) = reader.read_positions() else { continue };
let base = positions.len() as u32;
let pos: Vec<Vec3> = pos.map(|p| m.transform_point3(Vec3::from(p))).collect();
let n = pos.len();
match reader.read_normals() {
Some(ns) => normals.extend(ns.map(|q| m.transform_vector3(Vec3::from(q)).normalize_or_zero())),
None => all_normals = false,
}
match reader.read_tex_coords(0) {
Some(t) => uvs.extend(t.into_f32().map(Vec2::from)),
None => uvs.extend(std::iter::repeat_n(Vec2::ZERO, n)),
}
match reader.read_indices() {
Some(ix) => indices.extend(ix.into_u32().filter(|i| (*i as usize) < n).map(|i| i + base)),
None => indices.extend((0..n as u32).map(|i| i + base)),
}
positions.extend(pos);
if indices.len() / 3 > MAX_TRIANGLES {
return Err(bad("the mesh is too large"));
}
}
}
indices.truncate(indices.len() / 3 * 3);
let normals = (all_normals && normals.len() == positions.len()).then_some(normals);
Mesh::from_parts(positions, normals, uvs, indices, "material").map_err(|e| bad(e.to_string()))
}
/// Box-projected UVs: each vertex takes the plane of its normal's largest axis.
fn box_uvs(mesh: &Mesh) -> Vec<Vec2> {
let (lo, hi) = mesh.bounds();
let size = (hi - lo).max_element().max(1e-6);
mesh.positions
.iter()
.enumerate()
.map(|(i, p)| {
let q = (*p - lo) / size;
let n = mesh.normals.get(i).copied().unwrap_or(Vec3::Y).abs();
if n.x >= n.y && n.x >= n.z {
Vec2::new(q.z, 1.0 - q.y)
} else if n.y >= n.z {
Vec2::new(q.x, q.z)
} else {
Vec2::new(q.x, 1.0 - q.y)
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn obj_quad_loads_with_uvs_and_tangents() {
let obj = b"v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n";
let m = load_mesh("quad.obj", obj).unwrap();
assert_eq!(m.triangle_count(), 2);
assert_eq!(m.tangents.len(), m.positions.len());
assert!(m.radius() <= 1.0 + 1e-4);
// A mesh without UVs gets projected ones.
let m = load_mesh("tri.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n").unwrap();
assert!(m.uvs.iter().any(|u| *u != m.uvs[0]));
}
#[test]
fn bad_meshes_are_errors() {
assert!(load_mesh("x.obj", b"").is_err());
assert!(load_mesh("x.glb", b"glTF garbage").is_err());
assert!(load_mesh("x.fbx", b"").is_err());
assert!(load_mesh("x.obj", b"v 0 0 0\nf 1 2 3\n").is_err());
}
}
+23 -10
View File
@@ -54,16 +54,8 @@ pub fn poll(app: &mut MaterialCraftApp, ctx: &egui::Context) {
let reqs: Vec<ControlRequest> = rx.try_iter().collect();
for r in reqs {
if r.method == "ui.screenshot" {
let reply = r.reply;
let repaint = ctx.clone();
let callback = egui::ScreenshotCallback::new(move |img| {
let answer = encode_png(img.size[0] as u32, img.size[1] as u32, img.pixels.iter().flat_map(|c| c.to_array()).collect())
.map(|(w, h, png)| ok(json!({ "width": w, "height": h, "png": base64::engine::general_purpose::STANDARD.encode(png) })))
.unwrap_or_else(|| err("could not encode the screenshot"));
let _ = reply.send(answer);
repaint.request_repaint();
});
ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(callback));
// Captured from the UI pass (`request_screenshots`), where viewport commands land.
app.pending_screenshots.push(r.reply);
ctx.request_repaint();
continue;
}
@@ -73,6 +65,27 @@ pub fn poll(app: &mut MaterialCraftApp, ctx: &egui::Context) {
}
}
/// Ask for one window capture answering every pending `ui.screenshot` (call from the UI pass).
pub fn request_screenshots(app: &mut MaterialCraftApp, ctx: &egui::Context) {
if app.pending_screenshots.is_empty() {
return;
}
let replies = std::mem::take(&mut app.pending_screenshots);
let repaint = ctx.clone();
let callback = egui::ScreenshotCallback::new(move |img| {
let answer = encode_png(img.size[0] as u32, img.size[1] as u32, img.pixels.iter().flat_map(|c| c.to_array()).collect())
.map(|(w, h, png)| ok(json!({ "width": w, "height": h, "png": base64::engine::general_purpose::STANDARD.encode(png) })))
.unwrap_or_else(|| err("could not encode the screenshot"));
for r in &replies {
let _ = r.send(answer.clone());
}
repaint.request_repaint();
});
ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(callback));
ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden);
ctx.request_repaint();
}
pub(crate) fn encode_png(w: u32, h: u32, rgba: Vec<u8>) -> Option<(u32, u32, Vec<u8>)> {
let img = image::RgbaImage::from_raw(w, h, rgba)?;
let mut png = Vec::new();
+4
View File
@@ -58,6 +58,8 @@ pub struct MaterialCraftApp {
pub fn_editor: Option<function_editor::FnEditor>,
/// Synthetic input from the control channel, fed to egui on the next frames.
pub input_queue: VecDeque<control::Scripted>,
/// Replies waiting for the next window capture (`ui.screenshot`).
pub pending_screenshots: Vec<std::sync::mpsc::Sender<Value>>,
pub fps: f32,
/// Smoothed CPU time spent building the UI per frame (ms).
pub ui_ms: f32,
@@ -99,6 +101,7 @@ impl MaterialCraftApp {
view2d: view2d::View2dState::default(),
fn_editor: None,
input_queue: VecDeque::new(),
pending_screenshots: Vec::new(),
fps: 0.0,
ui_ms: 0.0,
status: String::new(),
@@ -245,6 +248,7 @@ impl MaterialCraftApp {
windows::show(self, &ctx);
function_editor::show(self, &ctx);
toasts(self, &ctx);
control::request_screenshots(self, &ctx);
let dt = (now_ms() - t0) as f32;
self.ui_ms = if self.ui_ms == 0.0 { dt } else { self.ui_ms * 0.9 + dt * 0.1 };
}
+29 -3
View File
@@ -27,6 +27,11 @@ pub struct View3dState {
pub fn scene_label(app: &MaterialCraftApp) -> String {
let id = &app.session.view3d.scene;
if id == "custom"
&& let Some((name, _)) = &app.session.custom_mesh
{
return name.clone();
}
SCENES.iter().find(|(s, _)| s == id).map_or(id.as_str(), |(_, l)| l).to_string()
}
@@ -42,6 +47,15 @@ fn menus(app: &mut MaterialCraftApp, ui: &mut Ui) {
}
}
ui.separator();
if ui.button(tr("Load mesh...")).clicked() {
crate::web_files::load_mesh(app, ui.ctx());
ui.close();
}
if app.session.custom_mesh.is_some() && ui.selectable_label(app.session.view3d.scene == "custom", scene_label_custom(app)).clicked() {
app.run("view.3d", json!({"scene": "custom"}));
ui.close();
}
ui.separator();
if ui.button(tr("Reset scene")).clicked() {
app.run("view.3d.reset", json!({}));
ui.close();
@@ -162,11 +176,15 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
});
}
fn scene_label_custom(app: &MaterialCraftApp) -> String {
app.session.custom_mesh.as_ref().map_or_else(String::new, |(n, _)| n.clone())
}
fn content_key(app: &MaterialCraftApp, w: u32, h: u32, show_env: bool) -> u64 {
use std::hash::{DefaultHasher, Hash, Hasher};
let mut hs = DefaultHasher::new();
let v = &app.session.view3d;
(w, h, show_env, &v.scene, &v.environment).hash(&mut hs);
(w, h, show_env, &v.scene, &v.environment, app.session.custom_mesh.as_ref().map(|(n, _)| n)).hash(&mut hs);
for f in [v.yaw, v.pitch, v.distance, v.tiling, v.exposure, v.env_rotation, v.height_scale] {
f.to_bits().hash(&mut hs);
}
@@ -188,8 +206,16 @@ fn render(app: &mut MaterialCraftApp, ctx: &egui::Context, rect: Rect, moving: b
return;
}
let v = app.session.view3d.clone();
if app.view3d.scene.as_ref().is_none_or(|(id, _)| *id != v.scene) {
app.view3d.scene = Some((v.scene.clone(), Scene::builtin(&v.scene)));
let scene_key = match (&*v.scene, &app.session.custom_mesh) {
("custom", Some((name, _))) => format!("custom:{name}"),
_ => v.scene.clone(),
};
if app.view3d.scene.as_ref().is_none_or(|(id, _)| *id != scene_key) {
let scene = match (&*v.scene, &app.session.custom_mesh) {
("custom", Some((_, mesh))) => Scene::new((**mesh).clone()),
_ => Scene::builtin(&v.scene),
};
app.view3d.scene = Some((scene_key, scene));
}
if app.view3d.light.as_ref().is_none_or(|l| l.name != v.environment) {
app.view3d.light = Some(Lighting::new(&v.environment));
+39 -1
View File
@@ -13,6 +13,7 @@ use crate::i18n::tr;
enum Pick {
Package,
Bitmap,
Mesh,
}
/// Files picked in the browser, waiting for the next frame: (file name, bytes, purpose).
@@ -22,13 +23,45 @@ static INBOX: Mutex<Vec<(String, Vec<u8>, Pick)>> = Mutex::new(Vec::new());
pub fn poll(app: &mut MaterialCraftApp) {
let picked = std::mem::take(&mut *INBOX.lock().unwrap_or_else(PoisonError::into_inner));
for (name, bytes, pick) in picked {
load(app, &name, bytes, pick == Pick::Bitmap);
if pick == Pick::Mesh {
mesh(app, &name, &bytes);
} else {
load(app, &name, bytes, pick == Pick::Bitmap);
}
}
}
/// Show a mesh file's bytes in the 3D view.
fn mesh(app: &mut MaterialCraftApp, name: &str, bytes: &[u8]) {
match app.session.load_mesh_bytes(name, bytes) {
Ok(()) => app.toast(format!("{} {name}", tr("Showing")), false),
Err(e) => app.toast(format!("{} {name}: {e}", tr("Couldn't load")), true),
}
}
/// 3D view ▸ Scene ▸ Load mesh: a native dialog on the desktop, the file picker in the browser.
pub fn load_mesh(app: &mut MaterialCraftApp, ctx: &egui::Context) {
#[cfg(not(target_arch = "wasm32"))]
{
let _ = ctx;
if let Some(p) = rfd::FileDialog::new().add_filter("Meshes", materialcraft_engine::formats::mesh::MESH_EXTENSIONS).pick_file() {
app.run("view.3d.loadMesh", serde_json::json!({"path": p.display().to_string()}));
}
}
#[cfg(target_arch = "wasm32")]
{
let _ = app;
web::pick_mesh(ctx);
}
}
/// Open a package or import an image (by extension unless `bitmap` forces an image).
pub fn load(app: &mut MaterialCraftApp, name: &str, bytes: Vec<u8>, bitmap: bool) {
let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();
if materialcraft_engine::formats::mesh::MESH_EXTENSIONS.contains(&ext.as_str()) {
mesh(app, name, &bytes);
return;
}
if bitmap || materialcraft_engine::formats::IMAGE_EXTENSIONS.contains(&ext.as_str()) {
match materialcraft_engine::file_cmds::add_resource(&mut app.session, name, bytes, None) {
Ok(res) => {
@@ -130,6 +163,11 @@ mod web {
pick(ctx, "MaterialCraft package", &["mcraft"], Pick::Package);
}
/// 3D view ▸ Scene ▸ Load mesh.
pub fn pick_mesh(ctx: &egui::Context) {
pick(ctx, "Meshes", materialcraft_engine::formats::mesh::MESH_EXTENSIONS, Pick::Mesh);
}
/// File ▸ Import bitmap.
pub fn import_bitmap(ctx: &egui::Context) {
pick(ctx, "Images", materialcraft_engine::formats::IMAGE_EXTENSIONS, Pick::Bitmap);
+26
View File
@@ -84,3 +84,29 @@ fn snapshots() {
settle(&mut h, 40);
save(&mut h, &dir, "function-editor");
}
/// Steady-state UI build time per frame with each panel closed in turn (release):
/// `cargo test -p materialcraft-ui-egui --release --test snapshot perf -- --ignored --nocapture`.
#[test]
#[ignore]
fn perf() {
use materialcraft_ui_egui::docking::Panel;
let app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
let mut h = harness(app, 1600.0, 960.0);
settle(&mut h, 60);
let measure = |h: &mut Harness<'static, MaterialCraftApp>| {
let t = std::time::Instant::now();
for _ in 0..30 {
h.step();
}
t.elapsed().as_secs_f64() * 1000.0 / 30.0
};
println!("all panels: {:.2} ms/frame", measure(&mut h));
for p in [Panel::Library, Panel::View3d, Panel::View2d, Panel::Properties, Panel::Explorer] {
h.state_mut().ui.dock.close(p);
settle(&mut h, 3);
println!("without {p:?}: {:.2} ms/frame", measure(&mut h));
h.state_mut().ui.dock.focus(p);
settle(&mut h, 3);
}
}