diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs index fce718c2..f82af292 100644 --- a/crates/compose/src/display.rs +++ b/crates/compose/src/display.rs @@ -151,7 +151,8 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 let (ao, m, s) = (get(Channel::AmbientOcclusion), get(Channel::Metallic), get(Channel::SpecularLevel)); // Specular/glossiness sets: the viewport shades roughness = 1 − glossiness. let gloss = comp.channels.contains_key(&Channel::Glossiness); - let (r, r_default) = if gloss { (get(Channel::Glossiness), default16(Channel::Glossiness)) } else { (get(Channel::Roughness), default16(Channel::Roughness)) }; + let (r, r_default) = + if gloss { (get(Channel::Glossiness), default16(Channel::Glossiness)) } else { (get(Channel::Roughness), default16(Channel::Roughness)) }; for i in 0..TILE_AREA { let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); let baked_ao = baked.scalar(BakedMap::AmbientOcclusion, x, y, res).unwrap_or(1.0); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index e10ddbc1..5435acdb 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -15,5 +15,8 @@ pub mod store; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; -pub use eval::{Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, flatten_layer, mask_image, pad_tiles}; +pub use eval::{ + Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, flatten_layer, mask_image, + pad_tiles, +}; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index f63c198e..da4c7a20 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -15,8 +15,8 @@ pub mod project; pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; pub use layer::{ - ChannelBlend, CompareOp, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, Mask, MaskBackground, - Procedural, ProceduralKind, Projection, Source, gradient, hsl_adjust, per_unit, + ChannelBlend, CompareOp, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, Mask, + MaskBackground, Procedural, ProceduralKind, Projection, Source, gradient, hsl_adjust, per_unit, }; pub use project::{ AoMixing, BakeMatch, BakeSettings, BakedMap, Camera, DepthOfField, DirectionMode, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 75dcf25b..dd79825e 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -1008,7 +1008,10 @@ mod tests { let id = p.insert_layer(0, l, None, false).unwrap(); let mut top = paint(&mut p, "y"); let source = Source::Anchor { anchor, channel: Channel::Height }; - top.mask = Some(Mask { effects: vec![Effect::new(p.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })], ..Mask::new(MaskBackground::Black) }); + top.mask = Some(Mask { + effects: vec![Effect::new(p.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })], + ..Mask::new(MaskBackground::Black) + }); p.insert_layer(0, top, Some(id), false).unwrap(); let json = serde_json::to_string(&p).unwrap(); let back: Project = serde_json::from_str(&json).unwrap(); diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index c7b156a7..95736cbd 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -16,7 +16,15 @@ pub fn specs() -> Vec { cmd!("resource.list", "List resources", [], None, "{}", always, |s, _| Ok(list(s))), cmd!("resource.remove", "Remove resource", [], None, "{name}", always, remove), cmd!("file.removeUnused", "Remove unused resources...", ["File"], None, "{}", always, remove_unused), - cmd!("layer.add.image", "Add fill layer from image", [], None, "{name, channel?: baseColor, projection?: uv|triplanar|planar, scale?}", always, add_image_fill), + cmd!( + "layer.add.image", + "Add fill layer from image", + [], + None, + "{name, channel?: baseColor, projection?: uv|triplanar|planar, scale?}", + always, + add_image_fill + ), ] } @@ -55,7 +63,8 @@ impl Session { pub fn sync_images(&mut self) { let keep: Vec = self.doc.resources.keys().cloned().collect(); self.images.retain(|k, _| keep.contains(k)); - let missing: Vec<(String, Arc>)> = self.doc.resources.iter().filter(|(k, _)| !self.images.contains_key(*k)).map(|(k, v)| (k.clone(), v.clone())).collect(); + let missing: Vec<(String, Arc>)> = + self.doc.resources.iter().filter(|(k, _)| !self.images.contains_key(*k)).map(|(k, v)| (k.clone(), v.clone())).collect(); for (k, bytes) in missing { match texturecraft_formats::decode_image(&bytes) { Ok(d) => { diff --git a/crates/engine/tests/perf.rs b/crates/engine/tests/perf.rs index 95dbc802..0cc1871c 100644 --- a/crates/engine/tests/perf.rs +++ b/crates/engine/tests/perf.rs @@ -254,8 +254,18 @@ fn bench_single_layers() { let cases: &[(&str, &[(&str, Value)])] = &[ ("uniform fill", &[("layer.add.fill", json!({"color": [0.5, 0.5, 0.5], "roughness": 0.4}))]), ("fill + clouds", &[("layer.add.fill", json!({})), ("layer.fill.set", json!({"channel": "baseColor", "procedural": "clouds"}))]), - ("fill + triplanar clouds", &[("layer.add.fill", json!({})), ("layer.fill.set", json!({"channel": "baseColor", "procedural": "clouds"})), ("layer.fill.projection", json!({"projection": "triplanar"}))]), - ("fill + black mask + edge wear", &[("layer.add.fill", json!({})), ("mask.add.black", Value::Null), ("effect.add.generator", json!({"generator": "edgeWear"}))]), + ( + "fill + triplanar clouds", + &[ + ("layer.add.fill", json!({})), + ("layer.fill.set", json!({"channel": "baseColor", "procedural": "clouds"})), + ("layer.fill.projection", json!({"projection": "triplanar"})), + ], + ), + ( + "fill + black mask + edge wear", + &[("layer.add.fill", json!({})), ("mask.add.black", Value::Null), ("effect.add.generator", json!({"generator": "edgeWear"}))], + ), ("fill + black mask + dirt", &[("layer.add.fill", json!({})), ("mask.add.black", Value::Null), ("effect.add.generator", json!({"generator": "dirt"}))]), ]; for (label, cmds) in cases { diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs index a2bc2ebb..9d1a7654 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -15,14 +15,13 @@ pub struct DecodedImage { /// Decode PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR or HDR bytes. pub fn decode_image(bytes: &[u8]) -> Result { - let reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?; + let reader = + image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?; let (w, h) = reader.into_dimensions().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?; if w == 0 || h == 0 || w > MAX_IMAGE_SIZE || h > MAX_IMAGE_SIZE { return Err(FormatError::TooLarge(format!("image is {w}x{h} (limit {MAX_IMAGE_SIZE})"))); } - let img = crate::guard("image", || { - image::load_from_memory(bytes).map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() }) - })?; + let img = crate::guard("image", || image::load_from_memory(bytes).map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() }))?; let srgb = !matches!(img, image::DynamicImage::ImageRgb32F(_) | image::DynamicImage::ImageRgba32F(_)); let f = img.into_rgba32f(); let (width, height) = f.dimensions(); diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 22ca6c8e..f0d69614 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -34,9 +34,9 @@ pub use export::{ pub use image_res::{DecodedImage, 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, MeshReport, import_high_poly_bytes, import_mesh_bytes}; -pub use presets::{builtin_preset, builtin_presets, preset_from_json, preset_to_json}; #[cfg(not(target_arch = "wasm32"))] pub use presets::load_preset; +pub use presets::{builtin_preset, builtin_presets, preset_from_json, preset_to_json}; pub use project_file::{ProjectFile, load_project_bytes, sanitize_resource_name, save_project_bytes}; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 4510d445..8d6dcd87 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -14,9 +14,9 @@ mod ply; #[cfg(test)] mod scene_tests; mod stl; -pub(crate) mod usd; #[cfg(test)] pub(crate) mod tests; +pub(crate) mod usd; use std::collections::HashMap; use std::collections::hash_map::Entry; diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 2765e3de..2073c731 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -525,7 +525,8 @@ fn set_bind_group(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, sampler /// points draw line lists. type ColorOut<'a> = (&'a str, wgpu::TextureFormat, Option); -const ADD: wgpu::BlendComponent = wgpu::BlendComponent { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add }; +const ADD: wgpu::BlendComponent = + wgpu::BlendComponent { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add }; const ADDITIVE: wgpu::BlendState = wgpu::BlendState { color: ADD, alpha: ADD }; #[allow(clippy::too_many_arguments)] @@ -607,16 +608,32 @@ fn target_view(device: &wgpu::Device, label: &str, size: [u32; 2], format: wgpu: } fn shadow_view(device: &wgpu::Device, size: u32) -> wgpu::TextureView { - texture(device, "tc_shadow", [size, size], DEPTH_FORMAT, 1, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING).create_view(&Default::default()) + texture(device, "tc_shadow", [size, size], DEPTH_FORMAT, 1, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING) + .create_view(&Default::default()) } /// One fullscreen-triangle pass into `target`. -fn fullscreen(encoder: &mut wgpu::CommandEncoder, label: &str, target: &wgpu::TextureView, load: wgpu::LoadOp, pipe: &wgpu::RenderPipeline, bg: &wgpu::BindGroup) { +fn fullscreen( + encoder: &mut wgpu::CommandEncoder, + label: &str, + target: &wgpu::TextureView, + load: wgpu::LoadOp, + pipe: &wgpu::RenderPipeline, + bg: &wgpu::BindGroup, +) { fullscreen_blend(encoder, label, target, load, pipe, bg, 1.0); } /// [`fullscreen`] with a blend constant (for pipelines that blend by it). -fn fullscreen_blend(encoder: &mut wgpu::CommandEncoder, label: &str, target: &wgpu::TextureView, load: wgpu::LoadOp, pipe: &wgpu::RenderPipeline, bg: &wgpu::BindGroup, constant: f64) { +fn fullscreen_blend( + encoder: &mut wgpu::CommandEncoder, + label: &str, + target: &wgpu::TextureView, + load: wgpu::LoadOp, + pipe: &wgpu::RenderPipeline, + bg: &wgpu::BindGroup, + constant: f64, +) { let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some(label), color_attachments: &[Some(wgpu::RenderPassColorAttachment { @@ -652,19 +669,30 @@ const CLEAR: wgpu::LoadOp = wgpu::LoadOp::Clear(wgpu::Color::TRANSP impl Renderer { /// `target_format`: the format of the pass [`Renderer::blit`] draws into. pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, target_format: wgpu::TextureFormat) -> Renderer { - let shader = |label: &str, source: &str| device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(source.into()) }); + let shader = |label: &str, source: &str| { + device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(source.into()) }) + }; let module = shader("tc_mesh", include_str!("shaders/mesh.wgsl")); let util_module = shader("tc_util", include_str!("shaders/util.wgsl")); let post_module = shader("tc_post", concat!(include_str!("shaders/util.wgsl"), include_str!("shaders/post.wgsl"), include_str!("shaders/fx.wgsl"))); let shadow_module = shader("tc_shadow", include_str!("shaders/shadow.wgsl")); - let bgl = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries }); + let bgl = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| { + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries }) + }; let globals_bgl = bgl( "tc_globals", &[ uniform_entry(0), tex_entry(1), sampler_entry(2), - fragment_entry(3, wgpu::BindingType::Texture { multisampled: false, sample_type: wgpu::TextureSampleType::Depth, view_dimension: wgpu::TextureViewDimension::D2 }), + fragment_entry( + 3, + wgpu::BindingType::Texture { + multisampled: false, + sample_type: wgpu::TextureSampleType::Depth, + view_dimension: wgpu::TextureViewDimension::D2, + }, + ), fragment_entry(4, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison)), ], ); @@ -694,7 +722,8 @@ impl Renderer { let hdr_format = if hdr_renderable(device) { HDR_FORMAT } else { COLOR_FORMAT }; let hdr = |fs, blend| Some((fs, hdr_format, blend)); let always = || Some(depth_state(false, wgpu::CompareFunction::Always)); - let mesh_pipeline = pipeline(device, "tc_mesh", &layout, &module, "vs_mesh", &vb, hdr("fs_mesh", None), MSAA, Some(depth_state(true, wgpu::CompareFunction::Less))); + let mesh_pipeline = + pipeline(device, "tc_mesh", &layout, &module, "vs_mesh", &vb, hdr("fs_mesh", None), MSAA, Some(depth_state(true, wgpu::CompareFunction::Less))); let uv_pipeline = pipeline(device, "tc_uv", &layout, &module, "vs_uv", &vb, hdr("fs_uv", None), MSAA, always()); let blend = Some(wgpu::BlendState::ALPHA_BLENDING); let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vb, hdr("fs_wire", blend), MSAA, always()); @@ -705,7 +734,8 @@ impl Renderer { let post_pipeline = pipeline(device, "tc_post", &fx_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None); let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))] .map(|(fs, blend)| pipeline(device, "tc_bloom", &fx_layout, &post_module, "vs_full", &[], hdr(fs, blend), 1, None)); - let gbuf_pipeline = pipeline(device, "tc_gbuf", &layout, &module, "vs_mesh", &vb, hdr("fs_gbuf", None), 1, Some(depth_state(true, wgpu::CompareFunction::Less))); + let gbuf_pipeline = + pipeline(device, "tc_gbuf", &layout, &module, "vs_mesh", &vb, hdr("fs_gbuf", None), 1, Some(depth_state(true, wgpu::CompareFunction::Less))); let sss_pipelines = ["fs_sss_h", "fs_sss_v"].map(|fs| pipeline(device, "tc_sss", &fx_layout, &post_module, "vs_full", &[], hdr(fs, None), 1, None)); let dof_pipeline = pipeline(device, "tc_dof", &fx_layout, &post_module, "vs_full", &[], hdr("fs_dof", None), 1, None); let dof_target = Some(wgpu::ColorTargetState { format: hdr_format, blend: None, write_mask: wgpu::ColorWrites::ALL }); @@ -731,7 +761,11 @@ impl Renderer { }; let shadow_pipeline = pipeline(device, "tc_shadow", &shadow_layout, &shadow_module, "vs_shadow", &vb, None, 1, Some(shadow_depth)); // accum = hdr * k + accum * (1 - k) with k = 1 / (sample + 1): a running average. - let average = wgpu::BlendComponent { src_factor: wgpu::BlendFactor::Constant, dst_factor: wgpu::BlendFactor::OneMinusConstant, operation: wgpu::BlendOperation::Add }; + let average = wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::Constant, + dst_factor: wgpu::BlendFactor::OneMinusConstant, + operation: wgpu::BlendOperation::Add, + }; let accum_layout = pl("tc_accum", &[Some(&mip_bgl)]); let accum_blend = Some(wgpu::BlendState { color: average, alpha: average }); let accum_pipeline = pipeline(device, "tc_accum", &accum_layout, &util_module, "vs_full", &[], hdr("fs_mip", accum_blend), 1, None); @@ -1227,7 +1261,12 @@ impl Renderer { /// Index ranges of `ranges` (first, count, material) whose texture set is visible (and is /// `only`, when given), with that set. - fn drawable<'a>(&'a self, ranges: &'a [(u32, u32, usize)], visible: &'a [bool], only: Option) -> impl Iterator, &'a SetGpu)> + 'a { + fn drawable<'a>( + &'a self, + ranges: &'a [(u32, u32, usize)], + visible: &'a [bool], + only: Option, + ) -> impl Iterator, &'a SetGpu)> + 'a { ranges.iter().filter_map(move |&(start, count, material)| { let ts = self.material_sets.get(material).copied().flatten()?; if only.is_some_and(|o| o != ts) || !visible.get(ts).copied().unwrap_or(true) { diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index ce507c7f..22e64d06 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -22,8 +22,8 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_compose::{Composite, ImageRes}; -use texturecraft_core::project::{DisplaySettings, ToneMapping}; use texturecraft_core::Channel; +use texturecraft_core::project::{DisplaySettings, ToneMapping}; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Bvh, Mesh, OrbitCamera}; @@ -1091,7 +1091,8 @@ mod tests { let n = 40_000; let mut sum = Vec3::ZERO; for _ in 0..n { - sum += trace(s, Vec3::new(0.3, 0.4, 4.0), Vec3::new(-0.07, -0.1, -1.0).normalize(), &TraceSettings { bounces: 3 }, &mut rng).map_or(Vec3::ZERO, |s| s.radiance); + sum += trace(s, Vec3::new(0.3, 0.4, 4.0), Vec3::new(-0.07, -0.1, -1.0).normalize(), &TraceSettings { bounces: 3 }, &mut rng) + .map_or(Vec3::ZERO, |s| s.radiance); } sum / n as f32 }; diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 3104b0f9..2321dc0b 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -176,10 +176,14 @@ fn shadows_darken_the_key_light() { top.camera.pitch = 0.9; render(&mut h, &top, "shadows_on_top"); // Rotating the environment turns the key light and its shadow. - let turned = render(&mut h, &shaded(&lit, |s| { - s.shadows = true; - s.env_rotation_deg = 120.0; - }), "shadows_env_rotated"); + let turned = render( + &mut h, + &shaded(&lit, |s| { + s.shadows = true; + s.env_rotation_deg = 120.0; + }), + "shadows_env_rotated", + ); assert_ne!(turned.px, b.px); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b9756f35..df57709f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -264,10 +264,16 @@ impl TextureCraftApp { } self.next_autosave = now + period; let dir = user_dir("autosave"); - let path = dir.join(format!("{}.{}", texturecraft_engine::formats::export::sanitize_file_stem(&self.session.doc.project.name), texturecraft_engine::core::PROJECT_EXT)); + let path = dir.join(format!( + "{}.{}", + texturecraft_engine::formats::export::sanitize_file_stem(&self.session.doc.project.name), + texturecraft_engine::core::PROJECT_EXT + )); let pf = self.session.project_file(); let spawned = std::thread::Builder::new().name("texturecraft-autosave".into()).spawn(move || { - let result = std::fs::create_dir_all(&dir).map_err(|e| e.to_string()).and_then(|_| texturecraft_engine::formats::save_project(&path, &pf).map_err(|e| e.to_string())); + let result = std::fs::create_dir_all(&dir) + .map_err(|e| e.to_string()) + .and_then(|_| texturecraft_engine::formats::save_project(&path, &pf).map_err(|e| e.to_string())); match result { Ok(()) => log::info!("autosaved {}", path.display()), Err(e) => log::warn!("autosave to {} failed: {e}", path.display()), @@ -341,9 +347,9 @@ impl eframe::App for TextureCraftApp { toolbar::rail(self, ui); } let hide = self.ui.hide_ui; - egui::CentralPanel::default().frame(egui::Frame::NONE.fill(if hide { theme::TOKENS.viewport } else { theme::TOKENS.separator })).show(ui, |ui| { - if hide { viewport::central(self, ui) } else { docking::show(self, ui) } - }); + egui::CentralPanel::default() + .frame(egui::Frame::NONE.fill(if hide { theme::TOKENS.viewport } else { theme::TOKENS.separator })) + .show(ui, |ui| if hide { viewport::central(self, ui) } else { docking::show(self, ui) }); windows::show(self, &ctx); toasts(self, &ctx); let end = now_ms();