From cfb94811ebcea12d9a9558f95be43663a24fd7d1 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 06:47:48 +0800 Subject: [PATCH 01/17] formats: decode cooked linked PNGs through the shared codec --- crates/formats/src/image_res.rs | 53 ++++++++++++++++++++++++++------- 1 file changed, 42 insertions(+), 11 deletions(-) diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs index 676b40d0..903b5b53 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -25,21 +25,21 @@ pub fn decode_image(bytes: &[u8]) -> Result { pub fn decode_image_within(bytes: &[u8], max_texels: u64) -> Result { let limits = image::Limits::default(); if craft_image_codecs::detect(bytes) == Some(Format::Png) { - return decode_imported_png(bytes, max_texels, limits.max_alloc.unwrap_or(u64::MAX)); + return decode_png(bytes, Limits::new(MAX_IMAGE_SIZE, MAX_IMAGE_SIZE, max_texels, limits.max_alloc.unwrap_or(u64::MAX))); } decode_image_with_limits(bytes, max_texels, limits) } -fn decode_imported_png(bytes: &[u8], max_texels: u64, max_alloc: u64) -> Result { +fn decode_png(bytes: &[u8], limits: Limits) -> Result { if let Ok((width, height, _)) = craft_image_codecs::png_probe::header(bytes) { if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE { return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_IMAGE_SIZE})"))); } - if u64::from(width) * u64::from(height) > max_texels { - return Err(FormatError::TooLarge(format!("image is {width}x{height}, more than {max_texels} texels"))); + if u64::from(width) * u64::from(height) > limits.max_pixels { + return Err(FormatError::TooLarge(format!("image is {width}x{height}, more than {} texels", limits.max_pixels))); } } - let options = DecodeOptions { limits: Limits::new(MAX_IMAGE_SIZE, MAX_IMAGE_SIZE, max_texels, max_alloc), keep_orientation: true }; + let options = DecodeOptions { limits, keep_orientation: true }; let png = crate::guard("image", || { craft_image_codecs::decode_as_with(Format::Png, bytes, &options).map_err(|error| match error { CodecError::LimitExceeded(message) => FormatError::TooLarge(message), @@ -78,11 +78,16 @@ fn decode_imported_png(bytes: &[u8], max_texels: u64, max_alloc: u64) -> Result< /// Decode a cook output under both its declared dimensions and decoder allocation budget. pub fn decode_cooked_image(bytes: &[u8], size: [u32; 2], max_decoder_bytes: u64) -> Result { + let [width, height] = size; + let texels = (u64::from(width) * u64::from(height)).min(MAX_RESOURCE_TEXELS); + if craft_image_codecs::detect(bytes) == Some(Format::Png) { + let limits = Limits::new(width.min(MAX_IMAGE_SIZE), height.min(MAX_IMAGE_SIZE), texels, max_decoder_bytes); + return decode_png(bytes, limits); + } let mut limits = image::Limits::default(); limits.max_alloc = Some(max_decoder_bytes); - limits.max_image_width = Some(size[0]); - limits.max_image_height = Some(size[1]); - let texels = (u64::from(size[0]) * u64::from(size[1])).min(MAX_RESOURCE_TEXELS); + limits.max_image_width = Some(width); + limits.max_image_height = Some(height); decode_image_with_limits(bytes, texels, limits) } @@ -337,22 +342,48 @@ mod tests { } #[test] - fn imported_png_keeps_color_under_alpha_and_gray16_precision() { + fn imported_and_cooked_png_keeps_color_under_alpha_and_integer_precision() { + use image::ImageEncoder; + let rgba = image::DynamicImage::ImageRgba8( image::RgbaImage::from_raw(2, 2, vec![61, 113, 173, 0, 37, 103, 237, 81, 34, 99, 5, 193, 89, 211, 239, 255]).unwrap(), ); let gray_alpha = image::DynamicImage::ImageLumaA16(image::ImageBuffer::from_raw(2, 2, vec![1234, 0, 1, 27, 0xabcd, 60211, 0xffff, 0xffff]).unwrap()); - for pixels in [rgba, gray_alpha] { + let rgb = + image::DynamicImage::ImageRgb16(image::ImageBuffer::from_raw(2, 2, vec![0, 19, 256, 17, 1_235, 89, 0xabcd, 1_024, 65_534, 0, 1, 65_535]).unwrap()); + for pixels in [rgba, gray_alpha, rgb] { let mut png = Vec::new(); - pixels.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut encoder = image::codecs::png::PngEncoder::new(&mut png); + // A generated TIFF Orientation=6 tag. Cooked data maps stay in stored row order. + let exif = b"II\x2a\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0\x06\0\0\0\0\0\0\0"; + encoder.set_exif_metadata(exif.to_vec()).unwrap(); + encoder.write_image(pixels.as_bytes(), 2, 2, pixels.color().into()).unwrap(); let expected = pixels.into_rgba32f(); let imported = decode_image_within(&png, 4).unwrap(); assert_eq!((imported.width, imported.height), (2, 2)); assert!(imported.srgb); assert_eq!(imported.rgba, expected.into_raw().as_chunks::<4>().0); + assert_eq!(decode_cooked_image(&png, [2, 2], 1 << 20).unwrap(), imported); } } + #[test] + fn cooked_png_checks_reported_sides_and_decoder_allowance() { + let mut png = Vec::new(); + image::RgbaImage::from_pixel(8, 2, image::Rgba([3, 47, 187, 0])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let header = &png[..33]; + // Each report allows 16 texels but falls short on an individual axis. + for size in [[4, 4], [16, 1]] { + for data in [png.as_slice(), header] { + assert!(matches!(decode_cooked_image(data, size, 1 << 20), Err(FormatError::TooLarge(_)))); + } + } + assert!(matches!(decode_cooked_image(header, [8, 2], 1 << 20), Err(FormatError::Malformed { .. }))); + assert!(matches!(decode_cooked_image(&png, [8, 2], 8 * 2 * 4 - 1), Err(FormatError::TooLarge(_)))); + let valid = decode_cooked_image(&png, [8, 2], 1 << 20).unwrap(); + assert_eq!([valid.width, valid.height], [8, 2]); + } + #[test] fn png_import_checks_texels_before_requiring_the_pixel_payload() { let png = coverage_png(4, 3, &[255; 12], [13, 27, 83]).unwrap(); From b8afd896fa7e9a23fdfbecf977a422a1c3beec20 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 12:48:52 +0800 Subject: [PATCH 02/17] formats: share PNG inspection for GLB and USD export (#751) --- crates/formats/src/mesh_export.rs | 85 ++++++++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 2 deletions(-) diff --git a/crates/formats/src/mesh_export.rs b/crates/formats/src/mesh_export.rs index 2e0f2c53..d35156a9 100644 --- a/crates/formats/src/mesh_export.rs +++ b/crates/formats/src/mesh_export.rs @@ -7,6 +7,7 @@ pub(crate) mod usd; use std::collections::BTreeSet; use std::fmt::Write as _; +use craft_image_codecs::{DecodeOptions, Format, Limits, SampleType, decode_as_with, png_probe}; use texturecraft_core::{Channel, NormalFormat}; use texturecraft_geom::{Mesh, SubMesh}; @@ -182,12 +183,25 @@ fn png8_options(preset: ExportPreset, normal: NormalFormat) -> ExportOptions { } fn is_black(png: &[u8]) -> bool { - image::load_from_memory_with_format(png, image::ImageFormat::Png).map_or(true, |img| img.to_rgb8().iter().all(|v| *v == 0)) + // Keep the previous PNG decoder's 512 MiB allocation ceiling. + let options = DecodeOptions { limits: Limits { max_alloc: 512 << 20, ..Limits::none() }, keep_orientation: true }; + let Ok(image) = decode_as_with(Format::Png, png, &options) else { return true }; + let sample = image.sample_type(); + let layout = image.layout(); + let pixel_bytes = layout.channels() * sample.bytes(); + let color_bytes = layout.color_channels() * sample.bytes(); + let mut colors = image.data().chunks_exact(pixel_bytes).map(|pixel| &pixel[..color_bytes]); + match sample { + SampleType::U8 => colors.all(|color| color.iter().all(|&value| value == 0)), + // The prior RGB8 conversion rounds 16-bit values through 128 to zero. + SampleType::U16 => colors.all(|color| color.as_chunks::<2>().0.iter().all(|&value| u16::from_ne_bytes(value) <= 128)), + _ => true, + } } /// PNG color type 4 (gray + alpha) or 6 (RGBA), from the IHDR chunk. fn png_has_alpha(png: &[u8]) -> bool { - matches!(png.get(25), Some(4 | 6)) + png_probe::pixel_model(png).is_ok_and(|model| matches!(model.color_type, 4 | 6)) } /// The mesh as binary glTF (GLB) named `name`, with `textures[i]` on material `i` (materials @@ -426,6 +440,73 @@ mod tests { assert_eq!((sampler.mag_filter(), sampler.min_filter()), expected); } + #[test] + fn mesh_png_maps_keep_only_nonblack_color() { + let png = |color, samples: &[u8]| { + let mut out = std::io::Cursor::new(Vec::new()); + image::write_buffer_with_format(&mut out, samples, 1, 1, color, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mesh = texturecraft_geom::primitives::cube(1.0); + for (bytes, keep) in [ + (png(image::ColorType::Rgba8, &[0, 0, 0, 255]), false), + (png(image::ColorType::Rgba8, &[0, 1, 0, 0]), true), + (png(image::ColorType::L16, &128u16.to_ne_bytes()), false), + (png(image::ColorType::L16, &129u16.to_ne_bytes()), true), + (b"PNG without image data".to_vec(), false), + ] { + let file = |name: &str, bytes: &[u8]| ExportedFile { name: name.into(), bytes: bytes.to_vec(), width: 1, height: 1, warnings: Vec::new() }; + let emissive = file("Emissive.png", &bytes); + let textures = GlbTextures::from_files(vec![emissive.clone()]); + assert_eq!(textures.emissive.as_deref(), keep.then_some(bytes.as_slice())); + let glb = glb_bytes(&mesh, "PNG maps", &[textures]).unwrap(); + let glb = gltf::Gltf::from_slice(&glb).unwrap(); + assert_eq!(glb.materials().next().unwrap().emissive_texture().is_some(), keep); + + let roughness = png(image::ColorType::L8, &[64]); + let usd_maps = vec![emissive, file("Clearcoat.png", &bytes), file("ClearcoatRoughness.png", &roughness)]; + let usd = usd_bytes(&mesh, "PNG maps", &[usd_maps], UsdFormat::Usda).unwrap(); + if keep { + assert_eq!(usd.textures.len(), 3); + for (suffix, expected) in [("_Emissive.png", &bytes), ("_Clearcoat.png", &bytes), ("_ClearcoatRoughness.png", &roughness)] { + let (_, written) = usd.textures.iter().find(|(name, _)| name.ends_with(suffix)).unwrap(); + assert_eq!(written, expected); + } + } else { + assert!(usd.textures.is_empty()); + } + } + } + + #[test] + fn mesh_png_alpha_requires_a_png_with_stored_alpha() { + let encode = |color: png::ColorType, samples: &[u8], color_key: bool| { + let mut output = Vec::new(); + let mut encoder = png::Encoder::new(&mut output, 1, 1); + encoder.set_color(color); + if color_key { + encoder.set_trns(vec![0; 6]); + } + let mut writer = encoder.write_header().unwrap(); + writer.write_image_data(samples).unwrap(); + writer.finish().unwrap(); + output + }; + let mut impostor = vec![0; 26]; + impostor[25] = 6; + let mesh = texturecraft_geom::primitives::cube(1.0); + for (bytes, expected) in [ + (encode(png::ColorType::Rgba, &[0, 1, 2, 120], false), gltf::material::AlphaMode::Blend), + (encode(png::ColorType::Rgb, &[0, 0, 0], true), gltf::material::AlphaMode::Opaque), + (impostor, gltf::material::AlphaMode::Opaque), + ] { + let textures = GlbTextures { base_color: Some(bytes), ..GlbTextures::default() }; + let glb = glb_bytes(&mesh, "PNG alpha", &[textures]).unwrap(); + let glb = gltf::Gltf::from_slice(&glb).unwrap(); + assert_eq!(glb.materials().next().unwrap().alpha_mode(), expected); + } + } + #[test] fn glb_writes_clearcoat_and_sheen_extensions() { use serde_json::{Value, json}; From eeeb27013dbea08af6fd46182865b3cccceea5c2 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:10 +0000 Subject: [PATCH 03/17] Properties: the shared sheet controls (rows, bands, sliders, number fields that hold the pointer, switches, picture dropdowns, section tabs) --- crates/ui-egui/src/pointer_lock/hold.rs | 36 +++ crates/ui-egui/src/pointer_lock/lock.rs | 19 ++ crates/ui-egui/src/pointer_lock/mod.rs | 129 +++++++++ .../src/pointer_lock/system_pointer.rs | 75 +++++ crates/ui-egui/src/pointer_lock/tests.rs | 117 ++++++++ .../ui-egui/src/property_sheet/axis_rows.rs | 135 +++++++++ .../src/property_sheet/band_response.rs | 9 + .../ui-egui/src/property_sheet/button_icon.rs | 14 + crates/ui-egui/src/property_sheet/choice.rs | 256 ++++++++++++++++++ .../ui-egui/src/property_sheet/eye_toggle.rs | 48 ++++ crates/ui-egui/src/property_sheet/group.rs | 134 +++++++++ crates/ui-egui/src/property_sheet/hold_pad.rs | 34 +++ .../ui-egui/src/property_sheet/info_icon.rs | 86 ++++++ crates/ui-egui/src/property_sheet/mod.rs | 208 ++++++++++++++ .../src/property_sheet/number_field.rs | 212 +++++++++++++++ .../ui-egui/src/property_sheet/open_card.rs | 10 + .../src/property_sheet/preview_block.rs | 153 +++++++++++ .../src/property_sheet/preview_edit.rs | 8 + .../src/property_sheet/preview_lower.rs | 10 + .../src/property_sheet/preview_size.rs | 20 ++ crates/ui-egui/src/property_sheet/row.rs | 236 ++++++++++++++++ crates/ui-egui/src/property_sheet/row_lead.rs | 30 ++ .../src/property_sheet/section_tabs.rs | 136 ++++++++++ .../section_tabs/section_scope.rs | 8 + .../section_tabs/section_tops.rs | 21 ++ .../src/property_sheet/sheet_measure.rs | 15 + crates/ui-egui/src/property_sheet/slider.rs | 238 ++++++++++++++++ crates/ui-egui/src/property_sheet/slot.rs | 64 +++++ .../src/property_sheet/stack_slider.rs | 20 ++ .../src/property_sheet/switch_control.rs | 204 ++++++++++++++ crates/ui-egui/src/property_sheet/tests.rs | 243 +++++++++++++++++ .../src/property_sheet/tests/filtering.rs | 19 ++ .../src/property_sheet/tests/gallery.rs | 15 + crates/ui-egui/src/property_sheet/tooltip.rs | 32 +++ crates/ui-egui/src/property_sheet/track.rs | 13 + .../ui-egui/src/property_sheet/value_text.rs | 63 +++++ 36 files changed, 3070 insertions(+) create mode 100644 crates/ui-egui/src/pointer_lock/hold.rs create mode 100644 crates/ui-egui/src/pointer_lock/lock.rs create mode 100644 crates/ui-egui/src/pointer_lock/mod.rs create mode 100644 crates/ui-egui/src/pointer_lock/system_pointer.rs create mode 100644 crates/ui-egui/src/pointer_lock/tests.rs create mode 100644 crates/ui-egui/src/property_sheet/axis_rows.rs create mode 100644 crates/ui-egui/src/property_sheet/band_response.rs create mode 100644 crates/ui-egui/src/property_sheet/button_icon.rs create mode 100644 crates/ui-egui/src/property_sheet/choice.rs create mode 100644 crates/ui-egui/src/property_sheet/eye_toggle.rs create mode 100644 crates/ui-egui/src/property_sheet/group.rs create mode 100644 crates/ui-egui/src/property_sheet/hold_pad.rs create mode 100644 crates/ui-egui/src/property_sheet/info_icon.rs create mode 100644 crates/ui-egui/src/property_sheet/number_field.rs create mode 100644 crates/ui-egui/src/property_sheet/open_card.rs create mode 100644 crates/ui-egui/src/property_sheet/preview_block.rs create mode 100644 crates/ui-egui/src/property_sheet/preview_edit.rs create mode 100644 crates/ui-egui/src/property_sheet/preview_lower.rs create mode 100644 crates/ui-egui/src/property_sheet/preview_size.rs create mode 100644 crates/ui-egui/src/property_sheet/row.rs create mode 100644 crates/ui-egui/src/property_sheet/row_lead.rs create mode 100644 crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs create mode 100644 crates/ui-egui/src/property_sheet/section_tabs/section_tops.rs create mode 100644 crates/ui-egui/src/property_sheet/sheet_measure.rs create mode 100644 crates/ui-egui/src/property_sheet/slider.rs create mode 100644 crates/ui-egui/src/property_sheet/slot.rs create mode 100644 crates/ui-egui/src/property_sheet/stack_slider.rs create mode 100644 crates/ui-egui/src/property_sheet/switch_control.rs create mode 100644 crates/ui-egui/src/property_sheet/tests.rs create mode 100644 crates/ui-egui/src/property_sheet/tests/filtering.rs create mode 100644 crates/ui-egui/src/property_sheet/tests/gallery.rs create mode 100644 crates/ui-egui/src/property_sheet/tooltip.rs create mode 100644 crates/ui-egui/src/property_sheet/track.rs create mode 100644 crates/ui-egui/src/property_sheet/value_text.rs diff --git a/crates/ui-egui/src/pointer_lock/hold.rs b/crates/ui-egui/src/pointer_lock/hold.rs new file mode 100644 index 00000000..e4d6dc5c --- /dev/null +++ b/crates/ui-egui/src/pointer_lock/hold.rs @@ -0,0 +1,36 @@ +//! How the system lets a drag hold its pointer + +/// How a drag holds the pointer on this platform +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Hold { + /// The pointer moves, and is put back where the press began after every frame; the put-back's own move arrives among the others (X11) + PutBack, + /// Put back the same way, but the system folds its waiting moves into one, read from where it put the pointer (Windows) + PutBackFolded, + /// The system keeps the pointer still and reports raw motion (macOS, Wayland, which cannot move a pointer) + Locked, + /// The pointer cannot be held (the browser): drags read it as it moves + Free, +} + +impl Hold { + /// The way this platform holds a pointer; Wayland is told apart from X11 the way the window system picks it + pub(crate) fn of_platform() -> Hold { + if cfg!(target_arch = "wasm32") { + Hold::Free + } else if cfg!(target_os = "macos") { + Hold::Locked + } else if cfg!(target_os = "windows") { + Hold::PutBackFolded + } else if std::env::var_os("WAYLAND_DISPLAY").is_none() { + Hold::PutBack + } else { + Hold::Locked + } + } + + /// The pointer is held by putting it back after every frame + pub(crate) fn puts_back(self) -> bool { + matches!(self, Hold::PutBack | Hold::PutBackFolded) + } +} diff --git a/crates/ui-egui/src/pointer_lock/lock.rs b/crates/ui-egui/src/pointer_lock/lock.rs new file mode 100644 index 00000000..bb593ce2 --- /dev/null +++ b/crates/ui-egui/src/pointer_lock/lock.rs @@ -0,0 +1,19 @@ +use egui::Pos2; + +use super::Hold; + +/// A drag holding the pointer, kept in egui's memory between frames +#[derive(Clone, Copy, Debug)] +pub(super) struct Lock { + pub(super) hold: Hold, + /// Where the press began: the pointer is kept there and comes back there + pub(super) anchor: Pos2, + /// Where the system's pointer is + pub(super) seen: Pos2, + /// Where egui sees the pointer: the anchor plus every move since, as far as it goes + pub(super) at: Pos2, + /// A put-back is on its way: the pointer move that brings it back is no motion + pub(super) putting_back: bool, + /// The drag let go: the next frame shows egui the pointer back at the anchor and forgets the lock + pub(super) let_go: bool, +} diff --git a/crates/ui-egui/src/pointer_lock/mod.rs b/crates/ui-egui/src/pointer_lock/mod.rs new file mode 100644 index 00000000..f3e09661 --- /dev/null +++ b/crates/ui-egui/src/pointer_lock/mod.rs @@ -0,0 +1,129 @@ +//! Drags that hold the pointer (Move on model, number fields that scrub): hidden while held, its motion endless so no screen edge stops it, back where the press began when let go. egui sees a pointer that keeps going: the raw input is rewritten to that endless position, so every drag reads its usual positions and deltas + +mod hold; +mod lock; +#[cfg(test)] +pub(crate) mod system_pointer; +#[cfg(test)] +mod tests; + +use egui::{Context, CursorIcon, Event, Id, RawInput, ViewportCommand}; + +pub(crate) use hold::Hold; +use lock::Lock; + +/// Points from where the press began within which a pointer move is the put-back arriving (the system rounds it to whole pixels) +const PUT_BACK_REACH: f32 = 1.0; + +fn lock_id() -> Id { + Id::unique("tc_pointer_lock") +} + +fn asked_id() -> Id { + Id::unique("tc_pointer_lock_asked") +} + +fn hold_override_id() -> Id { + Id::unique("tc_pointer_lock_hold") +} + +/// A drag under way asks for the pointer this frame; it keeps it as long as it asks every frame +pub(crate) fn ask_for_hold(ctx: &Context) { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|data| data.insert_temp(asked_id(), pass)); +} + +/// The app's raw input hook: while a drag holds the pointer, its moves become moves of the endless pointer egui sees +pub(crate) fn rewrite(ctx: &Context, raw: &mut RawInput) { + let Some(mut lock) = ctx.data(|data| data.get_temp::(lock_id())) else { + return; + }; + + if lock.let_go { + raw.events.insert(0, Event::PointerMoved(lock.anchor)); + ctx.data_mut(|data| data.remove::(lock_id())); + return; + } + + let zoom = ctx.zoom_factor().max(f32::EPSILON); + let events = std::mem::take(&mut raw.events); + for event in events { + match event { + Event::PointerMoved(to) => { + let put_back = lock.putting_back && to.distance(lock.anchor) <= PUT_BACK_REACH; + lock.putting_back &= !put_back; + if lock.hold.puts_back() && !put_back { + lock.at += to - lock.seen; + raw.events.push(Event::PointerMoved(lock.at)); + } + lock.seen = to; + } + Event::MouseMoved(delta) => { + if lock.hold == Hold::Locked { + lock.at += delta / zoom; + raw.events.push(Event::PointerMoved(lock.at)); + } + raw.events.push(event); + } + Event::PointerButton { button, pressed, modifiers, .. } => raw.events.push(Event::PointerButton { pos: lock.at, button, pressed, modifiers }), + // The pointer never really leaves: the drag goes on + Event::PointerGone => {} + other => raw.events.push(other), + } + } + ctx.data_mut(|data| data.insert_temp(lock_id(), lock)); +} + +/// The end of the app's frame: a drag that asked this frame takes or keeps the pointer (hidden, put back), one that stopped asking lets it go +pub(crate) fn settle(ctx: &Context) { + let asked = ctx.data(|data| data.get_temp::(asked_id())) == Some(ctx.cumulative_pass_nr()); + let held = ctx.data(|data| data.get_temp::(lock_id())).filter(|lock| !lock.let_go); + let mut lock = match (asked, held) { + (true, Some(lock)) => lock, + (true, None) => { + let hold = ctx.data(|data| data.get_temp::(hold_override_id())).unwrap_or_else(Hold::of_platform); + let (origin, latest) = ctx.input(|input| (input.pointer.press_origin(), input.pointer.latest_pos())); + let (Some(seen), false) = (latest, hold == Hold::Free) else { + return; + }; + + if hold == Hold::Locked { + ctx.send_viewport_cmd(ViewportCommand::CursorGrab(egui::CursorGrab::Locked)); + } + Lock { hold, anchor: origin.unwrap_or(seen), seen, at: seen, putting_back: false, let_go: false } + } + (false, Some(mut lock)) => { + // Put back before the grab ends: Wayland moves only a locked pointer + if lock.seen.distance(lock.anchor) > PUT_BACK_REACH { + ctx.send_viewport_cmd(ViewportCommand::CursorPosition(lock.anchor)); + } + if lock.hold == Hold::Locked { + ctx.send_viewport_cmd(ViewportCommand::CursorGrab(egui::CursorGrab::None)); + } + lock.let_go = true; + ctx.data_mut(|data| data.insert_temp(lock_id(), lock)); + ctx.request_repaint(); + return; + } + (false, None) => return, + }; + + ctx.set_cursor_icon(CursorIcon::None); + if lock.hold.puts_back() && lock.seen.distance(lock.anchor) > PUT_BACK_REACH { + ctx.send_viewport_cmd(ViewportCommand::CursorPosition(lock.anchor)); + + // A folding system reads every later move from where it put the pointer, its own move folded in + if lock.hold == Hold::PutBackFolded { + lock.seen = lock.anchor; + } else { + lock.putting_back = true; + } + } + ctx.data_mut(|data| data.insert_temp(lock_id(), lock)); +} + +/// Tests pick how the pointer is held, as a platform would +#[cfg(test)] +pub(crate) fn hold_like(ctx: &Context, hold: Hold) { + ctx.data_mut(|data| data.insert_temp(hold_override_id(), hold)); +} diff --git a/crates/ui-egui/src/pointer_lock/system_pointer.rs b/crates/ui-egui/src/pointer_lock/system_pointer.rs new file mode 100644 index 00000000..156cd8ee --- /dev/null +++ b/crates/ui-egui/src/pointer_lock/system_pointer.rs @@ -0,0 +1,75 @@ +//! The system's pointer in tests: the mouse moves it, and it obeys the app's put-backs, grabs and hidden cursor as a window system does + +use egui::{CursorGrab, CursorIcon, Event, Modifiers, PointerButton, Pos2, Vec2, ViewportCommand, ViewportId}; +use egui_kittest::Harness; + +/// Where the system's pointer is and how the app holds it +#[derive(Clone, Copy, Debug)] +pub(crate) struct SystemPointer { + pub(crate) at: Pos2, + pub(crate) locked: bool, + pub(crate) hidden: bool, + pub(crate) put_backs: usize, + /// The system folds a put-back into the next move, as Windows does, instead of reporting it as a move of its own + pub(crate) folds: bool, +} + +impl SystemPointer { + /// The pointer resting at `at` over the window + pub(crate) fn at(harness: &mut Harness<'_, S>, at: Pos2) -> SystemPointer { + let mut pointer = SystemPointer { at, locked: false, hidden: false, put_backs: 0, folds: false }; + harness.input_mut().events.push(Event::PointerMoved(at)); + pointer.frame(harness); + pointer + } + + /// One frame in which the mouse moves by `by` with `modifiers` held: a held pointer reports raw motion only, a free one moves + pub(crate) fn moves(&mut self, harness: &mut Harness<'_, S>, by: Vec2, modifiers: Modifiers) { + let input = harness.input_mut(); + input.events.push(Event::ModifiersChanged(modifiers)); + input.events.push(Event::MouseMoved(by)); + if !self.locked { + self.at += by; + input.events.push(Event::PointerMoved(self.at)); + } + self.frame(harness); + } + + /// The mouse moves by `by` over `frames` frames + pub(crate) fn drags(&mut self, harness: &mut Harness<'_, S>, by: Vec2, frames: usize, modifiers: Modifiers) { + for _ in 0..frames { + self.moves(harness, by / frames as f32, modifiers); + } + } + + /// One frame in which `button` goes down or up where the pointer is + pub(crate) fn button(&mut self, harness: &mut Harness<'_, S>, button: PointerButton, pressed: bool, modifiers: Modifiers) { + let input = harness.input_mut(); + input.events.push(Event::ModifiersChanged(modifiers)); + input.events.push(Event::PointerButton { pos: self.at, button, pressed, modifiers }); + self.frame(harness); + } + + /// One frame of everything the system sent since the last: the app's raw input hook rewrites it, the app runs, and the pointer does what the app asked + pub(crate) fn frame(&mut self, harness: &mut Harness<'_, S>) { + let ctx = harness.ctx.clone(); + super::rewrite(&ctx, harness.input_mut()); + harness.step(); + let output = harness.output(); + self.hidden = output.platform_output.cursor_icon == CursorIcon::None; + let commands = output.viewport_output.get(&ViewportId::ROOT).map(|viewport| viewport.commands.clone()).unwrap_or_default(); + for command in commands { + match command { + ViewportCommand::CursorPosition(to) => { + self.at = to; + self.put_backs += 1; + if !self.folds { + harness.input_mut().events.push(Event::PointerMoved(to)); + } + } + ViewportCommand::CursorGrab(grab) => self.locked = grab == CursorGrab::Locked, + _ => {} + } + } + } +} diff --git a/crates/ui-egui/src/pointer_lock/tests.rs b/crates/ui-egui/src/pointer_lock/tests.rs new file mode 100644 index 00000000..bbce1297 --- /dev/null +++ b/crates/ui-egui/src/pointer_lock/tests.rs @@ -0,0 +1,117 @@ +use egui::{Modifiers, PointerButton, Pos2, Rect, Sense, Vec2, pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; + +use super::system_pointer::SystemPointer; +use super::{Hold, ask_for_hold, hold_like, settle}; + +/// A strip that scrubs: dragging it adds the pointer's moves to the state, holding the pointer while it does +fn scrub_strip(hold_as: Hold) -> Harness<'static, Vec2> { + let mut harness = Harness::builder().with_size(vec2(400.0, 300.0)).build_ui_state( + |ui, moved: &mut Vec2| { + let response = ui.interact(Rect::from_min_size(pos2(10.0, 10.0), vec2(100.0, 24.0)), ui.scope_id().with("scrub"), Sense::drag()); + if response.dragged() { + ask_for_hold(ui.ctx()); + *moved += response.drag_delta(); + } + settle(ui.ctx()); + }, + Vec2::ZERO, + ); + hold_like(&harness.ctx, hold_as); + harness.run_steps(1); + harness +} + +const PRESS: Pos2 = pos2(60.0, 20.0); + +/// Drags the strip 1500 points right (far past the 400-point window) and back up 40, then lets go +fn scrub_past_the_edge(harness: &mut Harness<'static, Vec2>) -> SystemPointer { + let mut pointer = SystemPointer::at(harness, PRESS); + pointer.button(harness, PointerButton::Primary, true, Modifiers::NONE); + pointer.drags(harness, vec2(1500.0, -40.0), 30, Modifiers::NONE); + assert!(pointer.hidden, "the pointer is hidden while the drag holds it"); + assert!((*harness.state() - vec2(1500.0, -40.0)).length() < 0.01, "every move counts, past the window's edge: {:?}", harness.state()); + pointer +} + +#[test] +fn a_put_back_pointer_never_reaches_the_edge_and_comes_back_where_the_press_began() { + let mut harness = scrub_strip(Hold::PutBack); + let mut pointer = scrub_past_the_edge(&mut harness); + assert!(pointer.put_backs >= 30, "the pointer went back after every move: {}", pointer.put_backs); + assert!(pointer.at.distance(PRESS) < 1.0, "it never strayed from the press: {:?}", pointer.at); + + pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); + pointer.frame(&mut harness); + assert!(!pointer.hidden, "let go, the pointer shows again"); + assert_eq!(pointer.at, PRESS, "where the press began"); + assert_eq!(harness.ctx.input(|input| input.pointer.latest_pos()), Some(PRESS), "egui sees it there too"); + let moved = *harness.state(); + pointer.moves(&mut harness, vec2(30.0, 0.0), Modifiers::NONE); + assert_eq!(pointer.at, PRESS + vec2(30.0, 0.0), "a free pointer moves again"); + assert_eq!(*harness.state(), moved, "and drags nothing"); +} + +/// A system that folds the put-back into the next move (Windows) reads that move from the press point: the drag counts in full and never stalls +#[test] +fn a_folded_put_back_counts_every_move_from_the_press() { + let mut harness = scrub_strip(Hold::PutBackFolded); + let mut pointer = SystemPointer::at(&mut harness, PRESS); + pointer.folds = true; + pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); + pointer.drags(&mut harness, vec2(1500.0, -40.0), 30, Modifiers::NONE); + assert!(pointer.hidden && pointer.put_backs >= 30, "hidden, and put back after every move: {pointer:?}"); + assert!((*harness.state() - vec2(1500.0, -40.0)).length() < 0.01, "every move counts: {:?}", harness.state()); + + pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); + pointer.frame(&mut harness); + assert!(!pointer.hidden && pointer.at == PRESS, "let go, it shows again where the press began: {pointer:?}"); +} + +#[test] +fn a_locked_pointer_reads_raw_motion_and_is_let_go_where_the_press_began() { + let mut harness = scrub_strip(Hold::Locked); + let mut pointer = scrub_past_the_edge(&mut harness); + assert!(pointer.locked, "the system holds the pointer"); + assert_eq!(pointer.at, PRESS, "it never moved"); + + pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); + pointer.frame(&mut harness); + assert!(!pointer.locked && !pointer.hidden, "let go, the pointer is free and shows"); + assert_eq!(harness.ctx.input(|input| input.pointer.latest_pos()), Some(PRESS), "egui sees it where the press began"); +} + +#[test] +fn a_browser_pointer_is_not_held() { + let mut harness = scrub_strip(Hold::Free); + let mut pointer = SystemPointer::at(&mut harness, PRESS); + pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); + pointer.drags(&mut harness, vec2(100.0, 0.0), 10, Modifiers::NONE); + assert!(!pointer.hidden && pointer.put_backs == 0, "the pointer moves and shows"); + assert_eq!(*harness.state(), vec2(100.0, 0.0), "the drag reads it as it moves"); +} + +/// A number field in the Properties panel scrubs with the pointer held: hidden, kept where the press began, a drag far past the window's edge counted in full +#[test] +fn a_number_field_scrubs_past_the_edge_with_the_pointer_held() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = crate::frame_gizmo::tests::fill_app("triplanar"); + hold_like(&harness.ctx, Hold::PutBack); + let press = harness.get_by_label("Offset X").rect().center(); + let mut pointer = SystemPointer::at(&mut harness, press); + pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); + let window = harness.ctx.content_rect().width(); + pointer.drags(&mut harness, vec2(2.0 * window, 0.0), 40, Modifiers::NONE); + assert!(pointer.hidden && pointer.at.distance(press) < 1.0, "the pointer is hidden and kept on the field: {pointer:?}"); + pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); + pointer.frame(&mut harness); + assert!(!pointer.hidden && pointer.at == press, "let go, it shows again on the field: {pointer:?}"); + + let texturecraft_engine::core::Projection::Triplanar { offset, .. } = crate::frame_gizmo::tests::projection(&harness, layer) else { + panic!("still tri-planar") + }; + + let expected = 2.0 * window * crate::fill_panel::OFFSET_FIELD_SPEED; + assert!((offset[0] - expected).abs() < 0.05 * expected, "the whole drag counts, not only the part inside the window: {offset:?}, {expected}"); +} diff --git a/crates/ui-egui/src/property_sheet/axis_rows.rs b/crates/ui-egui/src/property_sheet/axis_rows.rs new file mode 100644 index 00000000..13d65ee9 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/axis_rows.rs @@ -0,0 +1,135 @@ +//! Rows a symmetry needs: a section caption with its own switch, sliders lettered by axis, and a picture beside a stack of sliders + +use std::ops::RangeInclusive; + +use egui::{Align2, Color32, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; + +use super::row::SECTION_CAPTION_CENTER; +use super::slider::KNOB_RADIUS; +use super::switch_control::PILL_SIZE; +use super::track::Track; +use super::{BLOCK_MARGIN, PropertySheet, SMALL_TEXT_SIZE, StackSlider, TEXT_SIZE}; +use crate::theme::semibold; + +/// From the right edge to the centre of a caption's switch: the pill ends on the edge +const CAPTION_SWITCH_INSET: f32 = PILL_SIZE.x / 2.0; + +/// The click area around a caption's switch +const CAPTION_SWITCH_HIT: egui::Vec2 = vec2(30.0, 20.0); + +/// Least air between a caption and the reason standing in for its switch +const UNAVAILABLE_AIR: f32 = 12.0; + +/// From the controls column to where a lettered slider's track starts, past its axis letter +const LETTER_TO_TRACK: f32 = 16.0; + +/// From one part of a lettered value to the next +const PART_LINE: f32 = 22.0; + +/// A stacked slider's caption line, its track's line, and the air between stacked sliders +const STACK_CAPTION_LINE: f32 = 18.0; +const STACK_PART_LINE: f32 = 22.0; +const STACK_GAP: f32 = 6.0; + +/// The picture's top below the block's (the first caption's letters), how much shorter it is than the stack, and its air before the controls column +const PICTURE_TOP: f32 = 4.0; +const PICTURE_SHORTER: f32 = 10.0; +const PICTURE_TO_COLUMN: f32 = 6.0; + +impl PropertySheet<'_> { + /// A section caption with its on/off switch at the right edge + pub(crate) fn section_switch(&mut self, title: &str, on: bool) -> Response { + self.section_in(title, false, self.tokens.text); + let top = self.sections.last().map_or(self.cursor_y(), |(_, top)| *top); + let center = pos2(self.right - CAPTION_SWITCH_INSET, top + SECTION_CAPTION_CENTER); + let id = self.next_id(); + let response = self.ui.interact(Rect::from_center_size(center, CAPTION_SWITCH_HIT), id, Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, on, title)); + self.pill(center, on, true); + response + } + + /// A dim section caption whose switch can't be used: `reason` stands in its place at the right edge, cut with "…" to fit (then its tooltip reads it whole) + pub(crate) fn section_unavailable(&mut self, title: &str, reason: &str) { + let tokens = self.tokens; + self.section_in(title, false, tokens.text_dim); + let top = self.sections.last().map_or(self.cursor_y(), |(_, top)| *top); + let center_y = top + SECTION_CAPTION_CENTER; + let painter = self.ui.painter().clone(); + let caption = painter.layout_no_wrap(title.to_uppercase(), semibold(SMALL_TEXT_SIZE), tokens.text_dim).size().x; + let room = self.right - self.left - caption - UNAVAILABLE_AIR; + let galley = crate::widgets::elided(&painter, reason, SMALL_TEXT_SIZE, tokens.text_dim, room); + let cut = galley.elided; + let rect = Rect::from_min_size(pos2(self.right - galley.size().x, center_y - galley.size().y / 2.0), galley.size()); + painter.galley(rect.min, galley, tokens.text_dim); + let id = self.next_id(); + let response = self.ui.interact(rect, id, Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Label, false, reason)); + if cut { + self.tip(response, reason); + } + } + + /// One value's parts on lettered signed sliders (Axis position X, Y): the label on the first row, each part's axis letter in its colour; returns the part edited and whether it merges + pub(crate) fn lettered_sliders( + &mut self, + label: &str, + parts: &mut [(&str, Color32, f32)], + range: RangeInclusive, + decimals: usize, + ) -> Option<(usize, bool)> { + let (control, first) = self.row(label); + let extra = parts.len().saturating_sub(1) as f32 * PART_LINE; + if extra > 0.0 { + self.take(extra); + } + let mut edit = None; + for (index, (letter, color, value)) in parts.iter_mut().enumerate() { + let center_y = first + index as f32 * PART_LINE; + self.ui.painter().text(pos2(control.left(), center_y), Align2::LEFT_CENTER, *letter, semibold(TEXT_SIZE), *color); + let id = self.next_id(); + let track = Track { start: control.left() + LETTER_TO_TRACK + KNOB_RADIUS, end: self.track_end(), center_y, zero: Some(0.0), ramp: false }; + let name = format_args!("{label} {letter}"); + let dragged = self.track(id, name, &track, value, &range); + let typed = self.value_field(id, name, center_y, *value, &range, decimals, ""); + if let Some(merge) = Self::apply_typed(value, typed, dragged) { + edit = Some((index, merge)); + } + self.drawn(center_y + super::CONTROL_HEIGHT / 2.0); + } + edit + } + + /// A picture at the left edge beside captioned sliders in the controls column, as tall as their stack; returns the slider edited and whether it merges + pub(crate) fn picture_sliders(&mut self, picture: &dyn Fn(&Painter, Rect), sliders: &mut [StackSlider<'_>]) -> Option<(usize, bool)> { + let count = sliders.len().max(1) as f32; + let height = count * (STACK_CAPTION_LINE + STACK_PART_LINE) + (count - 1.0) * STACK_GAP; + self.space(BLOCK_MARGIN); + let block = self.take(height); + let x0 = self.column(); + let side = (height - PICTURE_SHORTER).min(x0 - self.left - PICTURE_TO_COLUMN).max(1.0); + let square = Rect::from_min_size(pos2(self.left, block.top() + PICTURE_TOP), vec2(side, side)); + picture(self.ui.painter(), square); + self.ui.painter().rect_stroke(square, 0, Stroke::new(1.0, self.tokens.field_border), StrokeKind::Inside); + + let mut edit = None; + let mut y = block.top(); + for (index, slider) in sliders.iter_mut().enumerate() { + let dim = self.tokens.text_dim; + let caption = pos2(x0, y + STACK_CAPTION_LINE / 2.0); + self.ui.painter().text(caption, Align2::LEFT_CENTER, slider.label, FontId::proportional(SMALL_TEXT_SIZE), dim); + let center_y = y + STACK_CAPTION_LINE + STACK_PART_LINE / 2.0; + let id = self.next_id(); + let track = Track { start: x0 + KNOB_RADIUS, end: self.track_end(), center_y, zero: None, ramp: false }; + let dragged = self.track(id, slider.label, &track, slider.value, &slider.range); + let typed = self.value_field(id, slider.label, center_y, *slider.value, &slider.typed, slider.decimals, slider.suffix); + if let Some(merge) = Self::apply_typed(slider.value, typed, dragged) { + edit = Some((index, merge)); + } + y += STACK_CAPTION_LINE + STACK_PART_LINE + STACK_GAP; + } + self.drawn(square.bottom().max(block.bottom() - STACK_PART_LINE / 2.0 + KNOB_RADIUS)); + self.space(BLOCK_MARGIN); + edit + } +} diff --git a/crates/ui-egui/src/property_sheet/band_response.rs b/crates/ui-egui/src/property_sheet/band_response.rs new file mode 100644 index 00000000..fb230951 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/band_response.rs @@ -0,0 +1,9 @@ +/// What a band did this frame +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct BandResponse { + /// The band is open: show its rows + pub(crate) open: bool, + + /// Its Restore defaults button was clicked + pub(crate) reset: bool, +} diff --git a/crates/ui-egui/src/property_sheet/button_icon.rs b/crates/ui-egui/src/property_sheet/button_icon.rs new file mode 100644 index 00000000..be97a317 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/button_icon.rs @@ -0,0 +1,14 @@ +//! What a full-width button shows before its words: an icon font glyph or an icon drawn in code + +/// A full-width button's icon +#[derive(Clone, Copy, Debug)] +pub(crate) enum ButtonIcon<'a> { + /// A glyph of the icon font + Glyph(&'a str), +} + +impl<'a> From<&'a str> for ButtonIcon<'a> { + fn from(glyph: &'a str) -> Self { + ButtonIcon::Glyph(glyph) + } +} diff --git a/crates/ui-egui/src/property_sheet/choice.rs b/crates/ui-egui/src/property_sheet/choice.rs new file mode 100644 index 00000000..15d3d03f --- /dev/null +++ b/crates/ui-egui/src/property_sheet/choice.rs @@ -0,0 +1,256 @@ +use egui::{Align2, Color32, CornerRadius, FontId, Frame, Margin, Painter, Rect, RectAlign, Response, Role, Sense, Shadow, Stroke, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::{CONTROL_HEIGHT, CONTROL_RADIUS, ICON_SIZE, PropertySheet, RowLead, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::theme::{HARD_SHADOW, semibold}; + +/// Draws an option's picture into its square +pub(super) type ChoicePicture<'a, T> = &'a dyn Fn(&Painter, Rect, T); + +/// Size of a picture in a dropdown button and in its list +const PICTURE_SIZE: f32 = 18.0; + +/// From a picture dropdown's left edge to its picture +const PICTURE_INSET: f32 = 6.0; + +/// From a plain dropdown's left edge to its value +pub(super) const VALUE_INSET: f32 = 8.0; + +/// Air between a picture and the words after it +const PICTURE_TO_TEXT: f32 = 8.0; + +/// From a dropdown's right edge to its caret's centre +pub(super) const CARET_INSET: f32 = 10.0; + +/// Room a dropdown keeps for its caret: its value is cut with "…" before it +pub(super) const CARET_ROOM: f32 = 24.0; + +/// The open list's border, drawn outside its options: the list's outer edge is its button's +pub(super) const LIST_BORDER: f32 = 1.0; + +/// The open list's corner radius and the air above its first option and below its last +const LIST_RADIUS: u8 = 6; +const LIST_PADDING: i8 = 4; + +/// The open list's hard shadow, offset down and right like the other popups' +const LIST_SHADOW: Shadow = Shadow { offset: [2, 3], blur: 0, spread: 0, color: HARD_SHADOW }; + +/// Height of one option in an open list +const OPTION_HEIGHT: f32 = 26.0; + +/// How far an option's words sit above its centre, to look centred beside their capitals +const OPTION_TEXT_LIFT: f32 = 1.0; + +/// Gap under an option's hover fill, so neighbouring fills never touch +const HOVER_BOTTOM_GAP: f32 = 2.0; + +/// How far an option's hover fill sits inside the list's edges +const HOVER_INSET: f32 = 3.0; + +/// From the list's right edge to the hovered option's preview eye +const EYE_INSET: f32 = 16.0; + +/// Lists narrower than this have no room for the preview eye +const EYE_MIN_LIST_WIDTH: f32 = 80.0; + +/// The lettering of a set-once choice, cut with "…" to fit `room` +pub(super) fn truncated(painter: &Painter, text: &str, room: f32, color: Color32) -> std::sync::Arc { + let font = semibold(TEXT_SIZE); + let full = painter.layout_no_wrap(text.to_owned(), font.clone(), color); + if full.size().x <= room { + return full; + } + + let mut cut: String = text.to_owned(); + while cut.pop().is_some() { + let candidate = painter.layout_no_wrap(format!("{}…", cut.trim_end()), font.clone(), color); + if candidate.size().x <= room { + return candidate; + } + } + painter.layout_no_wrap("…".to_owned(), font, color) +} + +/// The chosen option's accent bar, inset from the option's left, top and bottom +const CHOSEN_BAR_LEFT: f32 = 2.0; +const CHOSEN_BAR_RIGHT: f32 = 4.0; +const CHOSEN_BAR_TOP: f32 = 5.0; +const CHOSEN_BAR_BOTTOM: f32 = 7.0; + +/// The chosen option's accent bar is 2 px wide: a 1 px radius rounds its ends fully +const CHOSEN_BAR_RADIUS: u8 = 1; + +/// The hovered option's eye glyph size +const EYE_SIZE: f32 = 13.0; + +impl PropertySheet<'_> { + /// A set-once choice whose list hangs from its button; returns the picked and the hovered option + pub(crate) fn dropdown( + &mut self, + label: &str, + current: T, + options: &[T], + name: impl Fn(T) -> String, + picture: Option>, + ) -> (Option, Option) { + self.dropdown_led(RowLead::label(label), current, options, name, picture) + } + + /// [`Self::dropdown`] led by `lead` (a label stacked above it, when its values differ only at their end) + pub(crate) fn dropdown_led( + &mut self, + lead: RowLead<'_>, + current: T, + options: &[T], + name: impl Fn(T) -> String, + picture: Option>, + ) -> (Option, Option) { + let response = self.dropdown_row(lead, current, &name, picture); + self.hanging_list(&response, current, options, &name, picture) + } + + /// [`Self::dropdown`] whose `options` are built only while its list is open + pub(crate) fn dropdown_built>( + &mut self, + label: &str, + current: T, + options: impl FnOnce() -> Options, + name: impl Fn(T) -> String, + picture: Option>, + ) -> (Option, Option) { + let response = self.dropdown_row(RowLead::label(label), current, &name, picture); + self.hanging_groups(&response, current, || [(None, options())], &name, picture) + } + + /// A dropdown's row led by `lead`, its button showing `current` and described by the row's name; returns the button's response + fn dropdown_row(&mut self, lead: RowLead<'_>, current: T, name: &impl Fn(T) -> String, picture: Option>) -> Response { + let x0 = self.lead_with(lead); + let row = self.take(super::ROW_HEIGHT); + let center_y = row.center().y; + self.drawn(center_y + CONTROL_HEIGHT / 2.0); + let button = self.control_box(x0, center_y); + let response = self.dropdown_button(button, &name(current), picture.map(|draw| move |painter: &Painter, rect: Rect| draw(painter, rect, current))); + self.ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(lead.text())); + response + } + + /// Paints a dropdown's button in `rect` and returns its response + pub(super) fn dropdown_button(&mut self, rect: Rect, value: &str, picture: Option) -> Response { + self.dropdown_button_led(rect, value, |painter| match picture { + Some(draw) => { + let picture_rect = + Rect::from_min_size(pos2(rect.left() + PICTURE_INSET, rect.center().y - PICTURE_SIZE / 2.0), vec2(PICTURE_SIZE, PICTURE_SIZE)); + draw(painter, picture_rect); + picture_rect.right() + PICTURE_TO_TEXT + } + None => rect.left() + VALUE_INSET, + }) + } + + /// [`Self::dropdown_button`] whose left end `lead` paints on the button's face, returning where the value starts + pub(super) fn dropdown_button_led(&mut self, rect: Rect, value: &str, lead: impl FnOnce(&Painter) -> f32) -> Response { + let id = self.next_id(); + let response = self.ui.interact(rect, id, Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::ComboBox, true, value)); + let tokens = self.tokens; + let painter = self.ui.painter(); + painter.rect_filled(rect, CornerRadius::same(CONTROL_RADIUS), if response.hovered() { tokens.row_hover } else { tokens.button }); + + let text_x = lead(painter); + let galley = truncated(painter, value, rect.right() - CARET_ROOM - text_x, tokens.text); + painter.galley(pos2(text_x, rect.center().y - galley.size().y / 2.0), galley, tokens.text); + painter.text(pos2(rect.right() - CARET_INSET, rect.center().y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(ICON_SIZE), tokens.text); + response + } + + /// The open list of `button`: 1 px below it, its width, over the rows below; returns the picked and the hovered option + pub(crate) fn hanging_list( + &mut self, + button: &Response, + current: T, + options: &[T], + name: &impl Fn(T) -> String, + picture: Option>, + ) -> (Option, Option) { + self.hanging_groups(button, current, || [(None, options.iter().copied())], name, picture) + } + + /// [`Self::hanging_list`] of options in groups, each under its caption (a dim line that can't be picked) when it has one; `groups` runs only while the list is open + fn hanging_groups<'g, T: Copy + PartialEq, Groups: IntoIterator, Options)>, Options: IntoIterator>( + &mut self, + button: &Response, + current: T, + groups: impl FnOnce() -> Groups, + name: &impl Fn(T) -> String, + picture: Option>, + ) -> (Option, Option) { + let tokens = self.tokens; + let width = button.rect.width() - 2.0 * LIST_BORDER; + let frame = Frame::NONE + .fill(tokens.chrome) + .stroke(Stroke::new(LIST_BORDER, tokens.field_border)) + .corner_radius(CornerRadius::same(LIST_RADIUS)) + .inner_margin(Margin::symmetric(0, LIST_PADDING)) + .shadow(LIST_SHADOW); + let shown = egui::Popup::from_toggle_button_response(button).align(RectAlign::BOTTOM_START).gap(1.0).width(width).frame(frame).show(|ui| { + let mut picked = None; + let mut hovered = None; + for (caption, options) in groups() { + if let Some(caption) = caption { + let (rect, response) = ui.allocate_exact_size(vec2(width, OPTION_HEIGHT), Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, caption)); + let center_y = rect.top() + OPTION_HEIGHT / 2.0 - OPTION_TEXT_LIFT; + ui.painter().text( + pos2(rect.left() - LIST_BORDER + VALUE_INSET, center_y), + Align2::LEFT_CENTER, + caption, + FontId::proportional(SMALL_TEXT_SIZE), + tokens.text_dim, + ); + } + for option in options { + let (rect, response) = ui.allocate_exact_size(vec2(width, OPTION_HEIGHT), Sense::click()); + let painter = ui.painter(); + let chosen = option == current; + response.widget_info(|| WidgetInfo::selected(Role::ListBoxOption, true, chosen, name(option))); + if response.hovered() { + hovered = Some(option); + let fill = + Rect::from_min_max(pos2(rect.left() + HOVER_INSET, rect.top()), pos2(rect.right() - HOVER_INSET, rect.bottom() - HOVER_BOTTOM_GAP)); + painter.rect_filled(fill, CornerRadius::same(CONTROL_RADIUS), tokens.button); + } + if chosen { + let bar = Rect::from_min_max( + pos2(rect.left() + CHOSEN_BAR_LEFT, rect.top() + CHOSEN_BAR_TOP), + pos2(rect.left() + CHOSEN_BAR_RIGHT, rect.bottom() - CHOSEN_BAR_BOTTOM), + ); + painter.rect_filled(bar, CornerRadius::same(CHOSEN_BAR_RADIUS), tokens.accent); + } + + // The rows sit inside the list's border: measured from the button's edge, text and picture keep the button's x + let button_left = rect.left() - LIST_BORDER; + let center_y = rect.top() + OPTION_HEIGHT / 2.0 - OPTION_TEXT_LIFT; + let mut text_x = button_left + VALUE_INSET; + if let Some(draw) = picture { + draw( + painter, + Rect::from_min_size(pos2(button_left + PICTURE_INSET, center_y - PICTURE_SIZE / 2.0), vec2(PICTURE_SIZE, PICTURE_SIZE)), + option, + ); + text_x = button_left + PICTURE_INSET + PICTURE_SIZE + PICTURE_TO_TEXT; + } + let font = if chosen { semibold(TEXT_SIZE) } else { FontId::proportional(TEXT_SIZE) }; + painter.text(pos2(text_x, center_y), Align2::LEFT_CENTER, name(option), font, tokens.text); + if response.hovered() && width >= EYE_MIN_LIST_WIDTH { + painter.text(pos2(rect.right() - EYE_INSET, center_y), Align2::CENTER_CENTER, ic::EYE, FontId::proportional(EYE_SIZE), tokens.accent); + } + if response.clicked() && !chosen { + picked = Some(option); + } + } + } + (picked, hovered) + }); + shown.map(|inner| inner.inner).unwrap_or((None, None)) + } +} diff --git a/crates/ui-egui/src/property_sheet/eye_toggle.rs b/crates/ui-egui/src/property_sheet/eye_toggle.rs new file mode 100644 index 00000000..17fff24e --- /dev/null +++ b/crates/ui-egui/src/property_sheet/eye_toggle.rs @@ -0,0 +1,48 @@ +//! A dropdown row that ends in an eye: shows or hides what the setting draws over the 3D view + +use egui::{Align2, CornerRadius, FontId, Painter, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::choice::ChoicePicture; +use super::{CONTROL_HEIGHT, CONTROL_RADIUS, PropertySheet}; + +/// Air between the dropdown and its eye +const EYE_GAP: f32 = 6.0; + +/// Size of the eye glyph +const EYE_GLYPH_SIZE: f32 = 14.0; + +impl PropertySheet<'_> { + /// [`Self::dropdown`] narrowed by an eye at the row's end (`eye`: open while shown, else slashed and dim; its tip); returns the pick and the eye's click + pub(crate) fn dropdown_with_eye( + &mut self, + label: &str, + current: T, + options: &[T], + name: impl Fn(T) -> String, + picture: Option>, + (shown, tip): (bool, &str), + ) -> (Option, bool) { + let right = self.right; + self.right -= CONTROL_HEIGHT + EYE_GAP; + let (picked, _) = self.dropdown(label, current, options, name, picture); + self.right = right; + + let center_y = self.cursor_y() - super::ROW_HEIGHT / 2.0; + let rect = Rect::from_center_size(pos2(right - CONTROL_HEIGHT / 2.0, center_y), vec2(CONTROL_HEIGHT, CONTROL_HEIGHT)); + let id = self.next_id(); + let response = self.ui.interact(rect, id, Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, shown, tip)); + let response = self.tip(response, tip); + paint_eye(self.ui.painter(), rect, shown, response.hovered(), &self.tokens); + (picked, response.clicked()) + } +} + +/// The eye's square: button fill, its edge lit while hovered; the eye open, or slashed and dim +fn paint_eye(painter: &Painter, rect: Rect, shown: bool, hovered: bool, tokens: &crate::theme::Tokens) { + let border = if hovered { tokens.accent } else { tokens.button_border }; + painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), tokens.button, Stroke::new(1.0, border), StrokeKind::Inside); + let (glyph, color) = if shown { (ic::EYE, tokens.text) } else { (ic::EYE_SLASH, tokens.text_dim) }; + painter.text(rect.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(EYE_GLYPH_SIZE), color); +} diff --git a/crates/ui-egui/src/property_sheet/group.rs b/crates/ui-egui/src/property_sheet/group.rs new file mode 100644 index 00000000..d115e162 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/group.rs @@ -0,0 +1,134 @@ +use egui::{Align2, CornerRadius, FontId, Rect, Sense, Shape, Stroke, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::row::{EDGE_GLYPH_INSET, RESET_ICON_SIZE}; +use crate::theme::semibold; + +/// Draws a band's picture in its rect +type BandPicture<'a> = &'a dyn Fn(&egui::Painter, Rect); + +/// Height of a top-level band +const BAND_HEIGHT: f32 = 30.0; + +/// A card's padding above its name and below its last control +const CARD_PADDING: f32 = 10.0; + +/// How far a card's face reaches past its rows on both sides +pub(super) const CARD_BLEED: f32 = 6.0; + +/// Corner radius of a card +pub(super) const CARD_RADIUS: u8 = 6; + +/// From the right edge to the centre of a band's reset button +const BAND_RESET_INSET: f32 = 26.0; + +/// From the right edge to where a band's or folded group's value ends +const BAND_VALUE_INSET: f32 = 22.0; + +/// Side of the picture before a band's value, and the air between them +const BAND_PICTURE_SIZE: f32 = 16.0; +const BAND_PICTURE_AIR: f32 = 8.0; + +/// A band's reset button click square +const BAND_RESET_TARGET: f32 = 20.0; + +impl PropertySheet<'_> { + /// A top-level group across the whole panel with a caret and a reset (`Some(changed)`) or a value; a click folds it + pub(crate) fn band(&mut self, title: &str, default_open: bool, reset: Option, value: Option<&str>) -> BandResponse { + self.band_drawn(title, default_open, reset, value, None) + } + + fn band_drawn(&mut self, title: &str, default_open: bool, reset: Option, value: Option<&str>, picture: Option>) -> BandResponse { + if self.card.is_none() { + self.space(GROUP_GAP); + } + + // A band is top-level: it ends a held card too + self.release_card(); + + self.scope = self.id; + let id = self.named_id("band", title); + self.band_scope = id; + self.scope = id; + + let rect = self.take(BAND_HEIGHT); + let band = Rect::from_x_y_ranges(self.ui.max_rect().x_range(), rect.y_range()); + + let mut open = self.ui.data(|data| data.get_temp::(id)).unwrap_or(default_open); + let response = self.ui.interact(band, id, Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, title)); + + let reset_rect = Rect::from_center_size(pos2(self.right - BAND_RESET_INSET, rect.center().y), vec2(BAND_RESET_TARGET, BAND_RESET_TARGET)); + let mut reset_clicked = false; + let mut reset_hovered = false; + if let Some(changed) = reset { + // At the defaults it is inert: a click there folds the band like the rest of it + let sense = if changed { Sense::click() } else { Sense::hover() }; + let reset_response = self.ui.interact(reset_rect, id.with("reset"), sense); + if changed { + // Right above the glyph, as far right as it: over the card or toggles above the band, never a value + let mut tooltip = egui::Tooltip::for_enabled(&reset_response); + tooltip.popup = tooltip.popup.anchor(reset_rect).align(egui::RectAlign::TOP_END).align_alternatives(&[egui::RectAlign::LEFT]); + tooltip.show(|ui| ui.label(crate::i18n::tr("Restore defaults"))); + } + reset_response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, changed, crate::i18n::tr("Restore defaults"))); + reset_clicked = changed && reset_response.clicked(); + reset_hovered = reset_response.hovered(); + } + if response.clicked() && !reset_clicked { + open = !open; + self.ui.data_mut(|data| data.insert_temp(id, open)); + } + + let tokens = self.tokens; + let painter = self.ui.painter(); + painter.rect_filled(band, CornerRadius::ZERO, self.band_fill()); + painter.line_segment([band.left_top(), band.right_top()], Stroke::new(1.0, tokens.separator)); + painter.line_segment([band.left_bottom(), band.right_bottom()], Stroke::new(1.0, tokens.separator)); + let center_y = rect.center().y; + painter.text(pos2(self.left, center_y), Align2::LEFT_CENTER, title, semibold(TEXT_SIZE), tokens.text); + if let Some(changed) = reset { + // The round section reset, as on a section caption: faint where it does nothing + let color = self.reset_glyph_color(changed, reset_hovered, tokens.text_strong); + painter.text(reset_rect.center(), Align2::CENTER_CENTER, ic::CLOCK_COUNTER_CLOCKWISE, FontId::proportional(RESET_ICON_SIZE), color); + } + if let Some(value) = value { + let shown = + painter.text(pos2(self.right - BAND_VALUE_INSET, center_y), Align2::RIGHT_CENTER, value, FontId::proportional(TEXT_SIZE), tokens.text_dim); + if let Some(draw) = picture { + let left = shown.left() - BAND_PICTURE_AIR - BAND_PICTURE_SIZE; + draw(painter, Rect::from_min_size(pos2(left, center_y - BAND_PICTURE_SIZE / 2.0), vec2(BAND_PICTURE_SIZE, BAND_PICTURE_SIZE))); + } + } + self.caret(pos2(self.right - EDGE_GLYPH_INSET, center_y), open, tokens.text_dim); + + self.drawn(band.bottom()); + self.space(GROUP_GAP); + self.air_at = Some(self.cursor_y()); + BandResponse { open, reset: reset_clicked } + } + + /// Ends [`Self::hold_card`] and closes the held card + pub(crate) fn release_card(&mut self) { + self.held = false; + self.close_card(); + } + + /// Ends the open card (not a held one: [`Self::release_card`] ends that): its face reaches [`CARD_PADDING`] below what its rows painted + pub(crate) fn close_card(&mut self) { + if self.held { + return; + } + + let Some(card) = self.card.take() else { return }; + + self.scope = self.band_scope; + + let bottom = self.drawn_bottom + CARD_PADDING; + let face = Rect::from_min_max(pos2(self.left - CARD_BLEED, card.top), pos2(self.right + CARD_BLEED, bottom)); + self.ui.painter().set(card.face, Shape::rect_filled(face, CornerRadius::same(CARD_RADIUS), self.tokens.row)); + let below = bottom + GROUP_GAP - self.cursor_y(); + self.space(below.max(0.0)); + self.air_at = Some(self.cursor_y()); + } +} diff --git a/crates/ui-egui/src/property_sheet/hold_pad.rs b/crates/ui-egui/src/property_sheet/hold_pad.rs new file mode 100644 index 00000000..24fd7dd7 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/hold_pad.rs @@ -0,0 +1,34 @@ +//! A picture that is also a press-and-hold surface: a badge in its corner says so, and the edge and badge light while hovered or held + +use egui::{Align2, CornerRadius, FontId, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, vec2}; + +use super::PropertySheet; + +/// Side of the badge in the picture's bottom-right corner, and its inset from the picture's edges +const BADGE_SIZE: f32 = 16.0; +const BADGE_INSET: f32 = 4.0; +const BADGE_ROUNDING: u8 = 3; + +/// Size of the badge's glyph +const BADGE_GLYPH_SIZE: f32 = 11.0; + +impl PropertySheet<'_> { + /// Makes the already painted `picture` a press-and-hold surface named `name`, marked by `glyph` in a badge; `held` lights it as hover does. It follows a drag that starts on it, wherever the pointer goes + pub(crate) fn hold_pad(&mut self, picture: Rect, glyph: &str, name: &str, held: bool) -> Response { + let id = self.next_id(); + let response = self.ui.interact(picture, id, Sense::click_and_drag()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, name)); + + let tokens = self.tokens; + let lit = held || response.hovered(); + let painter = self.ui.painter(); + let badge = Rect::from_min_size(picture.right_bottom() - vec2(BADGE_INSET + BADGE_SIZE, BADGE_INSET + BADGE_SIZE), vec2(BADGE_SIZE, BADGE_SIZE)); + let (fill, edge) = if lit { (tokens.accent_dim, tokens.accent) } else { (tokens.button, tokens.button_border) }; + painter.rect(badge, CornerRadius::same(BADGE_ROUNDING), fill, Stroke::new(1.0, edge), StrokeKind::Inside); + painter.text(badge.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(BADGE_GLYPH_SIZE), tokens.text); + if lit { + painter.rect_stroke(picture, 0, Stroke::new(1.0, tokens.accent), StrokeKind::Inside); + } + response + } +} diff --git a/crates/ui-egui/src/property_sheet/info_icon.rs b/crates/ui-egui/src/property_sheet/info_icon.rs new file mode 100644 index 00000000..b18c0513 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/info_icon.rs @@ -0,0 +1,86 @@ +use egui::{Align2, CornerRadius, FontId, Frame, Margin, Rect, RectAlign, RichText, Role, Sense, Shadow, Stroke, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::{PropertySheet, ROW_HEIGHT, SMALL_TEXT_SIZE}; +use crate::theme::HARD_SHADOW; + +/// The i's slot at the panel edge; a row with an i at its left starts this much further right +pub(super) const INFO_SLOT: f32 = 16.0; + +/// The i's centre, from the panel's left padding +const INFO_CENTER: f32 = 6.0; + +/// Size of the i glyph +const INFO_ICON_SIZE: f32 = 13.0; + +/// Room the tooltip leaves at the panel's right edge, so it covers no number, dial or switch +const TIP_VALUE_ROOM: f32 = 70.0; + +/// How far the tooltip reaches up into its row +const TIP_OVERLAP: f32 = 2.0; + +/// The tooltip's text padding, line pitch, rounding and shadow +const TIP_MARGIN: Margin = Margin::symmetric(8, 5); +const TIP_LINE_HEIGHT: f32 = 15.0; +const TIP_ROUNDING: u8 = 5; +const TIP_SHADOW: Shadow = Shadow { offset: [2, 3], blur: 0, spread: 0, color: HARD_SHADOW }; + +impl<'u> PropertySheet<'u> { + /// Gives the next row led by a label or picture an i at the panel edge that explains it on hover; its lead and its child rows move right to make room + pub(crate) fn info(&mut self, tip: &'u str) -> &mut Self { + self.info = Some(tip); + self + } + + /// How far the next row's lead moves right: past a pending i + pub(super) fn lead_shift(&self) -> f32 { + if self.info.is_some() { INFO_SLOT } else { 0.0 } + } + + /// Paints the pending i at the panel edge on the row centred at `center_y`, and its tooltip while the pointer rests on it + pub(super) fn paint_info(&mut self, center_y: f32) { + self.paint_info_in(self.left, self.left + INFO_CENTER, center_y); + } + + /// [`Self::paint_info`] at the row's right end, the i's right edge on the values' edge + pub(super) fn paint_info_at_end(&mut self, center_y: f32) { + self.paint_info_in(self.right - INFO_SLOT, self.right - INFO_ICON_SIZE / 2.0, center_y); + } + + /// Paints the pending i at `glyph_x` in its slot from `slot_left` + fn paint_info_in(&mut self, slot_left: f32, glyph_x: f32, center_y: f32) { + let Some(tip) = self.info.take() else { return }; + let row_top = center_y - ROW_HEIGHT / 2.0; + let slot = Rect::from_min_size(pos2(slot_left, row_top), vec2(INFO_SLOT, ROW_HEIGHT)); + let id = self.next_id(); + let response = self.ui.interact(slot, id, Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Image, true, tip)); + + let tokens = self.tokens; + let color = if response.hovered() { tokens.text } else { tokens.text_dim }; + self.ui.painter().text(pos2(glyph_x, center_y), Align2::CENTER_CENTER, ic::INFO, FontId::proportional(INFO_ICON_SIZE), color); + + // Under the row from the i, ending before the value column; above it where the window ends first + let anchor = Rect::from_min_max(pos2(self.left, row_top), pos2(self.right - TIP_VALUE_ROOM, row_top + ROW_HEIGHT)); + let frame = Frame::NONE + .fill(tokens.chrome) + .stroke(Stroke::new(1.0, tokens.field_border)) + .corner_radius(CornerRadius::same(TIP_ROUNDING)) + .inner_margin(TIP_MARGIN) + .shadow(TIP_SHADOW); + let text_width = anchor.width() - TIP_MARGIN.sum().x; + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip + .popup + .anchor(anchor) + .align(RectAlign::BOTTOM_START) + .align_alternatives(&[RectAlign::TOP_START]) + .gap(-TIP_OVERLAP) + .frame(frame) + .width(text_width); + tooltip.show(|ui| { + ui.set_width(text_width); + ui.label(RichText::new(tip).size(SMALL_TEXT_SIZE).color(tokens.text).line_height(Some(TIP_LINE_HEIGHT))); + }); + } +} diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 53afe419..cbd25d6a 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -1,8 +1,216 @@ //! The Properties panel's rows, groups and controls, shared by every panel so they line up +mod axis_rows; +mod band_response; +mod button_icon; +mod choice; +mod eye_toggle; +mod group; +mod hold_pad; +mod info_icon; +mod number_field; +mod open_card; +mod preview_block; +mod preview_edit; +mod preview_lower; +mod preview_size; +mod row; +mod row_lead; mod section_tabs; +mod sheet_measure; +mod slider; +mod slot; +mod stack_slider; +mod switch_control; +mod tooltip; +mod track; +mod value_text; pub(crate) use section_tabs::{full_height_tab_rect, shown_tab_box}; +#[cfg(test)] +mod tests; + +pub(crate) use band_response::BandResponse; +pub(crate) use button_icon::ButtonIcon; +pub(crate) use number_field::NumberField; +pub(crate) use preview_lower::PreviewLower; +pub(crate) use preview_size::PreviewSize; +pub(crate) use row_lead::RowLead; +pub(crate) use stack_slider::StackSlider; + +use egui::{Color32, FontId, Id, Rect, Ui, pos2, vec2}; + +use crate::theme::{Tokens, semibold}; +use open_card::OpenCard; +use sheet_measure::SheetMeasure; /// Side padding: every row starts and ends this far inside the panel pub(crate) const PAD: f32 = 12.0; + +/// Row pitch: every control row is one box this tall with its control centred +pub(crate) const ROW_HEIGHT: f32 = 28.0; + +/// Height of dropdowns, fields, switches and buttons +const CONTROL_HEIGHT: f32 = 24.0; + +/// Air between groups and after loose rows +const GROUP_GAP: f32 = 6.0; + +/// The narrowest label column, from the panel's left padding to the controls +const LABEL_COLUMN_MIN: f32 = 90.0; + +/// Labels wider than this stack above a full-width control and never widen the column +const LABEL_MAX: f32 = 132.0; + +/// Air between the widest label and the controls column +const LABEL_TO_CONTROL: f32 = 12.0; + +/// A label fits beside its control when it leaves at least this much air before the column +const LABEL_MIN_AIR: f32 = 8.0; + +/// The least air a loose label leaves before the controls column +const LOOSE_LABEL_AIR: f32 = 2.0; + +/// The narrowest value column at a slider's right end +const VALUE_MIN_WIDTH: f32 = 26.0; + +/// Air between a slider track's end and the value column, room for the knob and a gap +const TRACK_TO_VALUE: f32 = 14.0; + +/// Size of regular labels and SemiBold values +const TEXT_SIZE: f32 = 12.0; + +/// Size of captions, pill names and the switch's words +const SMALL_TEXT_SIZE: f32 = 11.0; + +/// Size of the caret and small glyphs drawn as icons +const ICON_SIZE: f32 = 12.0; + +/// Size of a picture row's picture, and the air after it +const ROW_PICTURE_SIZE: f32 = 18.0; +const ROW_PICTURE_AIR: f32 = 8.0; + +/// How far above and below a row's centre a slider track or a typed value takes the pointer +const ROW_HIT_HALF_HEIGHT: f32 = 10.0; + +/// Corner radius of dropdowns, fields and buttons +const CONTROL_RADIUS: u8 = 4; + +/// Air above and below a picture block, as a control has in its row +const BLOCK_MARGIN: f32 = 2.0; + +/// The Properties panel being laid out this frame: where the controls column is, which card is open, and what this frame measured for the next one +pub(crate) struct PropertySheet<'u> { + pub(crate) ui: &'u mut Ui, + tokens: Tokens, + id: Id, + scope: Id, + band_scope: Id, + named: Vec, + left: f32, + right: f32, + used: SheetMeasure, + seen: SheetMeasure, + card: Option, + air_at: Option, + drawn_bottom: f32, + empty: bool, + sections: Vec<(String, f32)>, + info: Option<&'u str>, + held: bool, +} + +impl<'u> PropertySheet<'u> { + /// Lays out `body` as one panel; when its measured columns change, egui reruns the frame unseen + pub(crate) fn show(ui: &'u mut Ui, id_salt: impl egui::AsIdSalt, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { + let id = ui.make_persistent_id(id_salt); + let used = ui.data(|data| data.get_temp::(id)).unwrap_or_default(); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + let rect = ui.available_rect_before_wrap(); + let mut sheet = PropertySheet { + tokens: Tokens::get(ui.ctx()), + id, + scope: id, + band_scope: id, + named: Vec::new(), + left: rect.left() + PAD, + right: rect.right() - PAD, + used, + seen: SheetMeasure::default(), + card: None, + air_at: None, + drawn_bottom: rect.top(), + empty: true, + sections: Vec::new(), + info: None, + held: false, + ui, + }; + let result = body(&mut sheet); + sheet.close_card(); + if !sheet.sections.is_empty() { + let view_top = sheet.ui.clip_rect().top(); + section_tabs::remember(sheet.ui, section_tabs::SectionTops { tops: std::mem::take(&mut sheet.sections), view_top }); + } + + let seen = sheet.seen; + if seen != used { + sheet.ui.data_mut(|data| data.insert_temp(id, seen)); + sheet.ui.ctx().request_discard("Properties columns changed"); + } + result + } + + /// The controls column: wide enough for this panel's labels, capped at [`LABEL_MAX`] + fn column(&self) -> f32 { + self.left + LABEL_COLUMN_MIN.max(self.used.label_width + LABEL_TO_CONTROL) + } + + /// Where the knob of a slider's track ends: left of this panel's widest value + fn track_end(&self) -> f32 { + self.right - self.used.value_width.max(VALUE_MIN_WIDTH) - TRACK_TO_VALUE + } + + /// Records a value's width for the panel's value column + fn measure_value(&mut self, text: &str) { + let width = self.text_width(text, semibold(TEXT_SIZE)); + self.seen.value_width = self.seen.value_width.max(width); + } + + fn text_width(&self, text: &str, font: FontId) -> f32 { + self.ui.painter().layout_no_wrap(text.to_owned(), font, Color32::WHITE).size().x + } + + /// Takes the next `height` pixels of the panel, full width; marks what it draws down to + fn take(&mut self, height: f32) -> Rect { + let (rect, _) = self.ui.allocate_exact_size(vec2(self.ui.available_width(), height), egui::Sense::hover()); + self.empty = false; + rect + } + + /// Leaves `height` pixels of air + fn space(&mut self, height: f32) { + self.ui.add_space(height); + } + + fn cursor_y(&self) -> f32 { + self.ui.cursor().top() + } + + /// Notes that something was painted down to `bottom`, so an open card ends its padding below it + fn drawn(&mut self, bottom: f32) { + self.drawn_bottom = self.drawn_bottom.max(bottom); + } + + /// A control's box: [`CONTROL_HEIGHT`] tall, centred in its row, from `x0` to the right edge + fn control_box(&self, x0: f32, center_y: f32) -> Rect { + Rect::from_min_max(pos2(x0, center_y - CONTROL_HEIGHT / 2.0), pos2(self.right, center_y + CONTROL_HEIGHT / 2.0)) + } + + /// The colour of a top-level band: between the window frame and a card + fn band_fill(&self) -> Color32 { + let tokens = &self.tokens; + let mid = |a: u8, b: u8| ((u16::from(a) + u16::from(b)) / 2) as u8; + Color32::from_rgb(mid(tokens.chrome.r(), tokens.row.r()), mid(tokens.chrome.g(), tokens.row.g()), mid(tokens.chrome.b(), tokens.row.b())) + } +} diff --git a/crates/ui-egui/src/property_sheet/number_field.rs b/crates/ui-egui/src/property_sheet/number_field.rs new file mode 100644 index 00000000..22337ebb --- /dev/null +++ b/crates/ui-egui/src/property_sheet/number_field.rs @@ -0,0 +1,212 @@ +use egui::{Align2, Color32, CornerRadius, FontId, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::{CONTROL_RADIUS, ICON_SIZE, PropertySheet, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::theme::semibold; + +/// Air between neighbouring fields of one row +const FIELD_GAP: f32 = 4.0; + +/// Room kept at the row's end for the link button, on every row of a group that has one +const LINK_SLOT: f32 = 26.0; + +/// Size of the link button +pub(super) const LINK_SIZE: f32 = 18.0; + +/// From a field's left edge to its axis letter's left edge +const TAG_LETTER_INSET: f32 = 7.0; + +/// From a field's left edge to its glyph's centre +const TAG_GLYPH_CENTER: f32 = 10.0; + +/// From a field's right edge to its value's right end +const VALUE_INSET: f32 = 6.0; + +/// Least air between a field's tag and its value: a value that would come closer drops decimals +const TAG_VALUE_GAP: f32 = 5.0; + +/// One part of a row of number fields: its tag (an axis letter in its colour, or a glyph) and value +pub(crate) struct NumberField<'a> { + pub(crate) tag: &'a str, + + /// The axis letter's colour; `None` draws `tag` as a dim glyph + pub(crate) tag_color: Option, + + pub(crate) value: f32, + + /// Change per pixel dragged + pub(crate) speed: f32, + + pub(crate) decimals: usize, + + /// A unit after the value ("°") + pub(crate) suffix: &'a str, +} + +/// The air between a field's axis tag and its typing box +const TAG_TO_TYPING: f32 = 6.0; + +impl PropertySheet<'_> { + /// A row of number fields (drag or type); returns the edited index and whether it continues a drag + pub(crate) fn number_fields(&mut self, label: &str, fields: &mut [NumberField], link: Option<&mut bool>, keep_link_slot: bool) -> Option<(usize, bool)> { + let (control, center_y) = self.row(label); + let slot = if link.is_some() || keep_link_slot { LINK_SLOT } else { 0.0 }; + let count = fields.len().max(1) as f32; + let width = (control.width() - slot - (count - 1.0) * FIELD_GAP) / count; + + let mut edited = None; + for (index, field) in fields.iter_mut().enumerate() { + let left = control.left() + index as f32 * (width + FIELD_GAP); + let rect = Rect::from_min_size(pos2(left, control.top()), vec2(width, control.height())); + if let Some(merge) = self.number_field(rect, label, field) { + edited = Some((index, merge)); + } + } + + if let Some(linked) = link { + self.link_button(pos2(self.right - LINK_SIZE / 2.0, center_y), linked); + } + edited + } + + /// The link that keeps two values together; returns whether it was clicked + pub(super) fn link_button(&mut self, center: egui::Pos2, linked: &mut bool) -> bool { + let rect = Rect::from_center_size(center, vec2(LINK_SIZE, LINK_SIZE)); + let id = self.next_id(); + let response = self.ui.interact(rect, id, Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, *linked, crate::i18n::tr("Link"))); + let response = self.tip(response, crate::i18n::tr("Link")); + if response.clicked() { + *linked = !*linked; + } + + let tokens = self.tokens; + let (fill, border) = if *linked { (tokens.accent_dim, tokens.accent) } else { (tokens.button, tokens.button_border) }; + let painter = self.ui.painter(); + painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, border), StrokeKind::Inside); + let glyph = if *linked { ic::LINK_SIMPLE_HORIZONTAL } else { ic::LINK_SIMPLE_HORIZONTAL_BREAK }; + painter.text(rect.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(ICON_SIZE), tokens.text); + response.clicked() + } + + /// One field: its tag on the left, the value on the right; drag or click to type. Named "`label` `tag`" ("Scale X") + fn number_field(&mut self, rect: Rect, label: &str, field: &mut NumberField) -> Option { + let id = self.next_id(); + let typing_id = id.with("typed"); + let tokens = self.tokens; + let painter = self.ui.painter().clone(); + painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), tokens.field, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); + match field.tag_color { + Some(color) => { + painter.text(pos2(rect.left() + TAG_LETTER_INSET, rect.center().y), Align2::LEFT_CENTER, field.tag, semibold(SMALL_TEXT_SIZE), color); + } + None => { + painter.text( + pos2(rect.left() + TAG_GLYPH_CENTER, rect.center().y), + Align2::CENTER_CENTER, + field.tag, + FontId::proportional(ICON_SIZE), + tokens.text_dim, + ); + } + } + + let decimals = field.decimals; + if let Some(mut text) = self.ui.data(|data| data.get_temp::(typing_id)) { + let edit = egui::TextEdit::singleline(&mut text).id(typing_id).font(semibold(TEXT_SIZE)).align(egui::Align2::RIGHT_CENTER); + let response = self.typing_edit(rect.left() + 2.0 * TAG_LETTER_INSET + TAG_TO_TYPING, rect.right() - VALUE_INSET, rect.center().y, edit); + painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(1.0, tokens.accent), StrokeKind::Inside); + if !response.lost_focus() { + self.ui.data_mut(|data| data.insert_temp(typing_id, text)); + return None; + } + + let untouched = self.end_typing(typing_id, &text); + if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) { + return None; + } + + // Leaving the field as it opened changes nothing: no undo step, no rounding to the shown decimals, no overwriting a value changed meanwhile + if untouched || text.trim() == shown_number(field.value, decimals) { + return None; + } + + let typed: f32 = text.trim().trim_end_matches(field.suffix).trim().parse().ok()?; + if !typed.is_finite() || typed == field.value { + return None; + } + + field.value = typed; + return Some(false); + } + + self.skip_typing_edit(); + let response = self.ui.interact(rect, id, Sense::click_and_drag()).on_hover_cursor(egui::CursorIcon::ResizeHorizontal); + response.widget_info(|| egui::WidgetInfo::slider(true, f64::from(field.value), format!("{label} {}", field.tag))); + let tag_right = match field.tag_color { + Some(_) => rect.left() + TAG_LETTER_INSET + painter.layout_no_wrap(field.tag.to_owned(), semibold(SMALL_TEXT_SIZE), tokens.text).size().x, + None => rect.left() + TAG_GLYPH_CENTER + ICON_SIZE / 2.0, + }; + let room = rect.right() - VALUE_INSET - tag_right - TAG_VALUE_GAP; + let shown = fitting_number(field.value, decimals, field.suffix, room, |text| { + painter.layout_no_wrap(text.to_owned(), semibold(TEXT_SIZE), tokens.text).size().x + }); + painter.text(pos2(rect.right() - VALUE_INSET, rect.center().y), Align2::RIGHT_CENTER, shown, semibold(TEXT_SIZE), tokens.text); + if response.hovered() || response.dragged() { + painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + } + + if response.clicked() { + self.start_typing(typing_id, shown_number(field.value, decimals)); + return None; + } + + if response.dragged() { + crate::pointer_lock::ask_for_hold(self.ui.ctx()); + } + let delta = response.drag_delta().x; + let moved = response.dragged() && delta != 0.0; + if moved { + field.value += delta * field.speed; + } + crate::widgets::press_edit(self.ui, response.id, moved) + } +} + +/// `value` and `suffix` with up to `decimals` decimals, as many as fit `room` wide (as measured by `width`), at least none +fn fitting_number(value: f32, decimals: usize, suffix: &str, room: f32, width: impl Fn(&str) -> f32) -> String { + let mut decimals = decimals; + loop { + let shown = format!("{}{suffix}", shown_number(value, decimals)); + if decimals == 0 || width(&shown) <= room { + return shown; + } + + decimals -= 1; + } +} + +/// `value` with `decimals` decimals, a value that rounds to zero reading 0 without a minus sign +pub(super) fn shown_number(value: f32, decimals: usize) -> String { + let shown = format!("{value:.decimals$}"); + let zero = shown.trim_start_matches('-').chars().all(|digit| matches!(digit, '0' | '.')); + if zero { shown.trim_start_matches('-').to_owned() } else { shown } +} + +#[cfg(test)] +mod tests { + use super::fitting_number; + + /// Every character is 7 wide + fn width(text: &str) -> f32 { + 7.0 * text.chars().count() as f32 + } + + #[test] + fn a_value_too_wide_for_its_field_drops_decimals_before_it_reaches_the_tag() { + assert_eq!(fitting_number(1.0, 2, "", 28.0, width), "1.00"); + assert_eq!(fitting_number(1.0, 2, "", 27.0, width), "1.0"); + assert_eq!(fitting_number(-12.5, 2, "°", 30.0, width), "-12°"); + assert_eq!(fitting_number(12345.0, 2, "", 1.0, width), "12345"); + } +} diff --git a/crates/ui-egui/src/property_sheet/open_card.rs b/crates/ui-egui/src/property_sheet/open_card.rs new file mode 100644 index 00000000..2063742d --- /dev/null +++ b/crates/ui-egui/src/property_sheet/open_card.rs @@ -0,0 +1,10 @@ +use egui::layers::ShapeIdx; + +/// A card whose rows are being laid out; its face is painted behind them once they end +pub(super) struct OpenCard { + /// Where the card starts + pub(super) top: f32, + + /// The placeholder the card's face is painted into, behind its rows + pub(super) face: ShapeIdx, +} diff --git a/crates/ui-egui/src/property_sheet/preview_block.rs b/crates/ui-egui/src/property_sheet/preview_block.rs new file mode 100644 index 00000000..e76045cf --- /dev/null +++ b/crates/ui-egui/src/property_sheet/preview_block.rs @@ -0,0 +1,153 @@ +use egui::{Align2, FontId, Painter, Rect, Stroke, StrokeKind, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::number_field::LINK_SIZE; +use super::preview_edit::PreviewEdit; +use super::preview_lower::PreviewLower; +use super::preview_size::PreviewSize; +use super::row::CAPTION_LINE; +use super::track::Track; +use super::{BLOCK_MARGIN, ICON_SIZE, PropertySheet, SMALL_TEXT_SIZE}; + +/// One slider line beside the preview square +const PART_LINE: f32 = 22.0; + +/// Air between the size and what follows it +const PART_GAP: f32 = 6.0; + +/// From the block's top to the square's top: the first caption's letters +const SQUARE_TOP: f32 = 4.0; + +/// The square stops this far above the block's bottom: the last knob's bottom +const SQUARE_SHORTER: f32 = 10.0; + +/// Air between the square and the controls beside it +const SQUARE_TO_SIDE: f32 = 12.0; + +/// From the side's left edge to a direction glyph's centre, and to the track after it +const GLYPH_CENTER: f32 = 5.0; +const GLYPH_TRACK: f32 = 18.0; + +/// Room kept at the right edge for the link, on every line, so the tracks end together +pub(super) const LINK_ROOM: f32 = 24.0; + +/// The value column's width beside the square: every track ends this far left of the value's end +const SIDE_VALUE_WIDTH: f32 = 46.0; + +/// The air kept between a side slider's track and its value +const SIDE_VALUE_AIR: f32 = 8.0; + +impl PropertySheet<'_> { + /// A preview square beside its stack (the size, then Offset or one setting), exactly as tall as the stack + pub(crate) fn preview_block(&mut self, picture: &dyn Fn(&Painter, Rect), size: PreviewSize<'_>, lower: PreviewLower<'_>) -> PreviewEdit { + let size_rows = if *size.linked { 1 } else { 2 }; + let lower_rows = match lower { + PreviewLower::Offset { .. } => 2, + PreviewLower::Slider { .. } => 1, + }; + let height = CAPTION_LINE + PART_LINE * size_rows as f32 + PART_GAP + CAPTION_LINE + PART_LINE * lower_rows as f32; + self.space(BLOCK_MARGIN); + let block = self.take(height); + let top = block.top(); + + let side = (height - SQUARE_SHORTER).max(1.0); + let square = Rect::from_min_size(pos2(self.left, top + SQUARE_TOP), vec2(side, side)); + picture(self.ui.painter(), square); + self.ui.painter().rect_stroke(square, 0, Stroke::new(1.0, self.tokens.field_border), StrokeKind::Inside); + + let x0 = square.right() + SQUARE_TO_SIDE; + let value_right = self.right - LINK_ROOM; + let track_end = value_right - SIDE_VALUE_WIDTH; + let mut edit = PreviewEdit { square, size: None, lower: None }; + let mut y = top; + + self.side_caption(x0, y, size.label); + y += CAPTION_LINE; + let linked = *size.linked; + for part in 0..size_rows { + let center_y = y + PART_LINE / 2.0; + let start = if linked { x0 } else { self.direction_glyph(x0, center_y, part) }; + let mut value = size.values[part]; + let label = format_args!("{}{}", size.label, part_suffix(part)); + if let Some(merge) = self.side_slider(label, start, track_end, value_right, center_y, &mut value, (&size.range, &size.typed), size.decimals, false) + { + size.values[part] = value; + if linked { + size.values[1] = value; + } + edit.size = Some(merge); + } + y += PART_LINE; + } + let link_center = pos2(self.right - LINK_SIZE / 2.0, y - PART_LINE / 2.0); + if self.link_button(link_center, size.linked) && *size.linked && size.values[1] != size.values[0] { + size.values[1] = size.values[0]; + edit.size = Some(false); + } + y += PART_GAP; + + match lower { + PreviewLower::Offset { values, range, typed } => { + let offset = crate::i18n::tr("Offset"); + self.side_caption(x0, y, offset); + y += CAPTION_LINE; + for part in 0..2 { + let center_y = y + PART_LINE / 2.0; + let start = self.direction_glyph(x0, center_y, part); + let label = format_args!("{offset}{}", part_suffix(part)); + if let Some(merge) = self.side_slider(label, start, track_end, value_right, center_y, &mut values[part], (&range, &typed), 2, true) { + edit.lower = Some(merge); + } + y += PART_LINE; + } + } + PreviewLower::Slider { label, value, range, decimals } => { + self.side_caption(x0, y, label); + y += CAPTION_LINE; + if let Some(merge) = self.side_slider(label, x0, track_end, value_right, y + PART_LINE / 2.0, value, (&range, &range), decimals, false) { + edit.lower = Some(merge); + } + } + } + self.drawn(square.bottom()); + self.space(BLOCK_MARGIN); + edit + } + + fn side_caption(&self, x: f32, top: f32, text: &str) { + let dim = self.tokens.text_dim; + self.ui.painter().text(pos2(x, top + CAPTION_LINE / 2.0), Align2::LEFT_CENTER, text, FontId::proportional(SMALL_TEXT_SIZE), dim); + } + + /// The ⇄ (across) or ⇅ (down) glyph before a part's track; returns where the track starts + fn direction_glyph(&self, x0: f32, center_y: f32, part: usize) -> f32 { + let glyph = if part == 0 { ic::ARROWS_LEFT_RIGHT } else { ic::ARROWS_DOWN_UP }; + let dim = self.tokens.text_dim; + self.ui.painter().text(pos2(x0 + GLYPH_CENTER, center_y), Align2::CENTER_CENTER, glyph, FontId::proportional(ICON_SIZE), dim); + x0 + GLYPH_TRACK + } + + #[allow(clippy::too_many_arguments)] + fn side_slider( + &mut self, + label: impl std::fmt::Display, + start: f32, + end: f32, + value_right: f32, + center_y: f32, + value: &mut f32, + (range, typed_range): (&std::ops::RangeInclusive, &std::ops::RangeInclusive), + decimals: usize, + signed: bool, + ) -> Option { + let id = self.next_id(); + let dragged = self.track(id, &label, &Track { start, end, center_y, zero: signed.then_some(0.0), ramp: false }, value, range); + let typed = self.value_field_at(id, &label, value_right, SIDE_VALUE_WIDTH - SIDE_VALUE_AIR, center_y, *value, typed_range, decimals, ""); + Self::apply_typed(value, typed, dragged) + } +} + +/// What a part's name adds to its caption: nothing for the first, " 2" for the second +fn part_suffix(part: usize) -> &'static str { + if part == 0 { "" } else { " 2" } +} diff --git a/crates/ui-egui/src/property_sheet/preview_edit.rs b/crates/ui-egui/src/property_sheet/preview_edit.rs new file mode 100644 index 00000000..8ba1324f --- /dev/null +++ b/crates/ui-egui/src/property_sheet/preview_edit.rs @@ -0,0 +1,8 @@ +/// What a preview block's controls changed this frame (`Some(merge)` per edited part), and where its square is +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PreviewEdit { + /// Where the preview square sits, for a surface over it + pub(crate) square: egui::Rect, + pub(crate) size: Option, + pub(crate) lower: Option, +} diff --git a/crates/ui-egui/src/property_sheet/preview_lower.rs b/crates/ui-egui/src/property_sheet/preview_lower.rs new file mode 100644 index 00000000..085ff6c5 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/preview_lower.rs @@ -0,0 +1,10 @@ +use std::ops::RangeInclusive; + +/// What sits under the size beside a preview square +pub(crate) enum PreviewLower<'a> { + /// Offset across and down, signed + Offset { values: &'a mut [f32; 2], range: RangeInclusive, typed: RangeInclusive }, + + /// One other setting (tri-planar Hardness) + Slider { label: &'a str, value: &'a mut f32, range: RangeInclusive, decimals: usize }, +} diff --git a/crates/ui-egui/src/property_sheet/preview_size.rs b/crates/ui-egui/src/property_sheet/preview_size.rs new file mode 100644 index 00000000..c2ebc45e --- /dev/null +++ b/crates/ui-egui/src/property_sheet/preview_size.rs @@ -0,0 +1,20 @@ +use std::ops::RangeInclusive; + +/// The size beside a preview square: one slider while linked, one per direction otherwise +pub(crate) struct PreviewSize<'a> { + /// The caption above it (Tiling, Size (cm), Scaling) + pub(crate) label: &'a str, + + /// Across and down; while linked, down follows across + pub(crate) values: &'a mut [f32; 2], + + /// What the track spans + pub(crate) range: RangeInclusive, + + /// What a typed value may be: wider than the track + pub(crate) typed: RangeInclusive, + + pub(crate) decimals: usize, + + pub(crate) linked: &'a mut bool, +} diff --git a/crates/ui-egui/src/property_sheet/row.rs b/crates/ui-egui/src/property_sheet/row.rs new file mode 100644 index 00000000..28af9dd7 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/row.rs @@ -0,0 +1,236 @@ +use egui::{Align2, FontId, Id, Rect, Response, Sense, Stroke, pos2}; +use egui_phosphor::regular as ic; + +use super::{ + CONTROL_HEIGHT, ICON_SIZE, LABEL_MAX, LABEL_MIN_AIR, LOOSE_LABEL_AIR, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, RowLead, + SMALL_TEXT_SIZE, TEXT_SIZE, +}; +use crate::theme::semibold; + +/// Air above a stacked label +const STACK_AIR: f32 = 4.0; + +/// Height of a stacked label's line, from its air to the control row under it +const STACK_LABEL_LINE: f32 = 14.0; + +/// A stacked label's centre below its line's top +const STACK_LABEL_CENTER: f32 = 8.0; + +/// A caption line's height +pub(super) const CAPTION_LINE: f32 = 18.0; + +/// How far small text reaches below its centre line +const SMALL_TEXT_HALF_LINE: f32 = 6.0; + +/// The square a row-end glyph answers the pointer in +const GLYPH_BOX: f32 = 20.0; + +/// Air above a section caption that follows other rows, and the hairline's distance below it +const SECTION_AIR: f32 = 6.0; + +/// The hairline above a later section caption, to the caption's top +pub(super) const SECTION_RULE_TO_CAPTION: f32 = 12.0; + +/// Air above the panel's first section caption +const FIRST_SECTION_AIR: f32 = 12.0; + +/// Height of a section caption's line, including the air under it +const SECTION_CAPTION_LINE: f32 = 24.0; + +/// From a section caption's line top to its text's centre +pub(super) const SECTION_CAPTION_CENTER: f32 = 7.0; + +/// Size of a section's menu glyph +const SECTION_MENU_ICON_SIZE: f32 = 14.0; + +/// Distance from the right edge to the centre of a right-edge glyph (caret, menu) +pub(super) const EDGE_GLYPH_INSET: f32 = 6.0; + +/// Size of the round reset glyph on a section caption or a band +pub(super) const RESET_ICON_SIZE: f32 = 14.0; + +/// Opacity of a reset glyph at the defaults, where it does nothing +const RESET_AT_DEFAULT_OPACITY: f32 = 0.4; + +/// From the right edge to the centre of a section caption's reset: its 14 px glyph ends at the dropdowns' right edge +const SECTION_RESET_INSET: f32 = RESET_ICON_SIZE / 2.0; + +impl PropertySheet<'_> { + /// [`Self::section`] with the round section reset at the caption's right end: faint and inert at the defaults (`changed` false); returns whether it was clicked + pub(crate) fn section_reset(&mut self, title: &str, changed: bool) -> bool { + let text = self.tokens.text; + let center_y = self.section_caption(title, text); + + let glyph = Rect::from_center_size(pos2(self.right - SECTION_RESET_INSET, center_y), egui::Vec2::splat(GLYPH_BOX)); + let id = self.id.with(("section_reset", title)); + let sense = if changed { Sense::click() } else { Sense::hover() }; + let response = self.ui.interact(glyph, id, sense); + + let label = crate::i18n::tr("Reset to defaults"); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, changed, format_args!("{title}: {label}"))); + + if changed { + // Left of the glyph, on the caption's line: it covers no value + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip.popup.anchor(glyph).align(egui::RectAlign::LEFT).align_alternatives(&[egui::RectAlign::BOTTOM_END]); + tooltip.show(|ui| ui.label(crate::i18n::tr("Restore defaults"))); + } + + let color = self.reset_glyph_color(changed, response.hovered(), self.tokens.text_strong); + self.ui.painter().text(glyph.center(), Align2::CENTER_CENTER, ic::CLOCK_COUNTER_CLOCKWISE, FontId::proportional(RESET_ICON_SIZE), color); + changed && response.clicked() + } + + /// A reset or clear glyph's colour: faint where it does nothing (`live` false), `hover_color` under the pointer, dim otherwise + pub(super) fn reset_glyph_color(&self, live: bool, hovered: bool, hover_color: egui::Color32) -> egui::Color32 { + match (live, hovered) { + (false, _) => self.tokens.text_dim.gamma_multiply(RESET_AT_DEFAULT_OPACITY), + (true, true) => hover_color, + (true, false) => self.tokens.text_dim, + } + } + + /// [`Self::section`] with its caption in `color` + pub(super) fn section_in(&mut self, title: &str, menu: bool, color: egui::Color32) -> Option { + let center_y = self.section_caption(title, color); + if !menu { + return None; + } + + let glyph = Rect::from_center_size(pos2(self.right - EDGE_GLYPH_INSET, center_y), egui::Vec2::splat(GLYPH_BOX)); + let id = self.id.with(("section_menu", title)); + let response = self.ui.interact(glyph, id, Sense::click()); + let color = if response.hovered() { self.tokens.text } else { self.tokens.text_dim }; + self.ui.painter().text(glyph.center(), Align2::CENTER_CENTER, ic::LIST, FontId::proportional(SECTION_MENU_ICON_SIZE), color); + Some(response) + } + + /// A section caption in capitals in `color`, a hairline above a later one; returns the caption's centre line + fn section_caption(&mut self, title: &str, color: egui::Color32) -> f32 { + self.close_card(); + + // Named state before the section's first band is keyed by the section, not by the band above it + if self.card.is_none() { + let section = self.id.with(("section", title)); + self.band_scope = section; + self.scope = section; + } + + if !self.empty { + self.space(SECTION_AIR); + let y = self.cursor_y(); + self.ui.painter().line_segment([pos2(self.left, y), pos2(self.right, y)], Stroke::new(1.0, self.tokens.separator)); + self.space(SECTION_RULE_TO_CAPTION); + } else { + self.space(FIRST_SECTION_AIR); + } + + let rect = self.take(SECTION_CAPTION_LINE); + self.sections.push((title.to_owned(), rect.top())); + if super::section_tabs::take_jump(self.ui, title) { + // Scroll by the distance itself: a top-aligned scroll_to_rect stops short by the scroll area's item spacing, which the sheet cannot see + let hairline = rect.top() - SECTION_RULE_TO_CAPTION; + let to_top = self.ui.clip_rect().top() - hairline; + self.ui.scroll_with_delta(egui::vec2(0.0, to_top)); + } + + let center_y = rect.top() + SECTION_CAPTION_CENTER; + self.ui.painter().text(pos2(self.left, center_y), Align2::LEFT_CENTER, title.to_uppercase(), semibold(SMALL_TEXT_SIZE), color); + self.drawn(center_y + SMALL_TEXT_HALF_LINE); + self.air_at = None; + center_y + } + + /// One setting's row: label beside the controls column or stacked above; returns the control's box and centre + pub(crate) fn row(&mut self, label: &str) -> (Rect, f32) { + self.row_with(RowLead::label(label)) + } + + /// [`Self::row`] led by `lead` + pub(crate) fn row_with(&mut self, lead: RowLead<'_>) -> (Rect, f32) { + let x0 = self.lead_with(lead); + let rect = self.take(ROW_HEIGHT); + let center_y = rect.center().y; + let picture = matches!(lead, RowLead::Picture { .. }); + self.drawn(center_y + if picture { ROW_PICTURE_SIZE } else { CONTROL_HEIGHT } / 2.0); + (self.control_box(x0, center_y), center_y) + } + + /// Paints a row's lead and returns where its control starts; pictures and children never widen the column + pub(crate) fn lead_with(&mut self, lead: RowLead<'_>) -> f32 { + let font = FontId::proportional(TEXT_SIZE); + let center_y = self.cursor_y() + ROW_HEIGHT / 2.0; + let shift = self.lead_shift(); + let label_x = self.left + shift + ROW_PICTURE_SIZE + ROW_PICTURE_AIR; + let (label, stack, text_color) = match lead { + RowLead::Label { text, stack } => (text, stack, self.tokens.text), + RowLead::Loose(text) if shift + self.text_width(text, font.clone()) <= self.column() - self.left - LOOSE_LABEL_AIR => { + self.paint_info(center_y); + self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, text, font, self.tokens.text); + return self.column(); + } + RowLead::Loose(text) => return self.stacked_label(text, shift), + RowLead::Picture { picture, text } => { + self.paint_info(center_y); + let square = Rect::from_center_size(pos2(self.left + shift + ROW_PICTURE_SIZE / 2.0, center_y), egui::vec2(ROW_PICTURE_SIZE, ROW_PICTURE_SIZE)); + picture(self.ui.painter(), square); + self.ui.painter().text(pos2(label_x, center_y), Align2::LEFT_CENTER, text, font, self.tokens.text); + return self.column(); + } + RowLead::Child(text) => { + self.ui.painter().text(pos2(self.left, center_y), Align2::LEFT_CENTER, text, font, self.tokens.text_dim); + return self.column(); + } + }; + + // The i's slot counts as part of the label + let width = shift + self.text_width(label, font.clone()); + if width <= LABEL_MAX { + self.seen.label_width = self.seen.label_width.max(width); + } + + if width <= self.column() - self.left - LABEL_MIN_AIR && !stack { + self.paint_info(center_y); + self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, font, text_color); + return self.column(); + } + + self.stacked_label(label, shift) + } + + /// Paints `label` on its own line above a full-width control, `shift` right of the edge after its i; returns the control's left edge + fn stacked_label(&mut self, label: &str, shift: f32) -> f32 { + self.space(STACK_AIR); + let rect = self.take(STACK_LABEL_LINE); + let center_y = rect.top() + STACK_LABEL_CENTER; + self.paint_info(center_y); + let text = self.tokens.text; + self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), text); + self.left + } + + /// A caret pointing down (open) or right (folded), centred on `center` + pub(super) fn caret(&self, center: egui::Pos2, open: bool, color: egui::Color32) { + let glyph = if open { ic::CARET_DOWN } else { ic::CARET_RIGHT }; + self.ui.painter().text(center, Align2::CENTER_CENTER, glyph, FontId::proportional(ICON_SIZE), color); + } + + /// The next control's id: stable while the panel shows the same rows + pub(super) fn next_id(&mut self) -> Id { + let id = self.ui.next_auto_id(); + self.ui.skip_ahead_auto_ids(1); + id + } + + /// The id of a group or colour bar whose state outlives the frame: keyed by its name inside the open band and card, so rows shown or hidden above it never hand it another's state + pub(super) fn named_id(&mut self, kind: &str, title: &str) -> Id { + let mut id = self.scope.with((kind, title)); + + // A repeated name in one scope (two cards of one effect) takes the next free id + while self.named.contains(&id) { + id = id.with(kind); + } + self.named.push(id); + id + } +} diff --git a/crates/ui-egui/src/property_sheet/row_lead.rs b/crates/ui-egui/src/property_sheet/row_lead.rs new file mode 100644 index 00000000..5d3b981c --- /dev/null +++ b/crates/ui-egui/src/property_sheet/row_lead.rs @@ -0,0 +1,30 @@ +use egui::{Painter, Rect}; + +/// What leads a setting's row, left of its control +#[derive(Clone, Copy)] +pub(crate) enum RowLead<'a> { + /// A label beside the controls column; it stacks above a full-width control when it doesn't fit, or always with `stack` + Label { text: &'a str, stack: bool }, + + /// A label beside the controls column that never widens it; it stacks only when it can't fit with [`super::LOOSE_LABEL_AIR`] before the column + Loose(&'a str), + + /// A picture at the left edge with its label after it (culling rows) + Picture { picture: &'a dyn Fn(&Painter, Rect), text: &'a str }, + + /// A setting of the row above, dim, its label on the label column like its parent's + Child(&'a str), +} + +impl<'a> RowLead<'a> { + /// A label beside the controls column + pub(crate) fn label(text: &'a str) -> RowLead<'a> { + RowLead::Label { text, stack: false } + } + + /// The row's name, as assistive tech reads it + pub(crate) fn text(self) -> &'a str { + match self { + } + } +} diff --git a/crates/ui-egui/src/property_sheet/section_tabs.rs b/crates/ui-egui/src/property_sheet/section_tabs.rs index 5b7d6187..99edf990 100644 --- a/crates/ui-egui/src/property_sheet/section_tabs.rs +++ b/crates/ui-egui/src/property_sheet/section_tabs.rs @@ -1,13 +1,116 @@ use egui::{CornerRadius, Painter, Rect, pos2}; +use egui::{Align2, Color32, CornerRadius, FontId, Id, Painter, Rect, Role, Sense, Ui, WidgetInfo, pos2, vec2}; use crate::theme::Tokens; +use super::row::SECTION_RULE_TO_CAPTION; +use super::{PAD, SMALL_TEXT_SIZE}; +use crate::theme::{Tokens, semibold}; + +mod section_scope; +mod section_tops; + +pub(crate) use section_scope::SectionScope; +pub(super) use section_tops::SectionTops; + +/// Height of the tab strip +const STRIP_HEIGHT: f32 = 30.0; + +/// How far the first tab reaches left of the rows' side padding +const FIRST_TAB_OUTDENT: f32 = 4.0; + +/// From the panel's left edge to the first tab +const FIRST_TAB: f32 = PAD - FIRST_TAB_OUTDENT; + +/// A tab's width beyond its name: icon and air (the resource picker's tabs share these measures) +pub(crate) const TAB_PADDING: f32 = 38.0; + +/// Air between tabs +pub(crate) const TAB_GAP: f32 = 2.0; /// The chosen tab starts this far below the strip's top and reaches this far into the panel +pub(crate) const TAB_TOP: f32 = 4.0; const TAB_BELOW: f32 = 6.0; /// Corner rounding of the chosen tab pub(crate) const TAB_ROUNDING: u8 = 5; +/// From a tab's left edge to its icon's centre, and to its name +pub(crate) const TAB_ICON_CENTER: f32 = 14.0; +pub(crate) const TAB_NAME_LEFT: f32 = 26.0; + +/// Size of a tab's icon and of its name +pub(crate) const TAB_ICON_SIZE: f32 = 13.0; +pub(crate) const TAB_TEXT_SIZE: f32 = SMALL_TEXT_SIZE; + +/// A section counts as in view once its caption is this close to the top of the scrolled area +const IN_VIEW_SLACK: f32 = 30.0; + +/// Where the scope of the sections being drawn is kept while a strip's contents run +fn scope_id() -> Id { + Id::unique("property_sheet_section_scope") +} + +/// Where a strip keeps its section positions and the section one of its tabs asked to jump to +fn sections_id(scope: SectionScope) -> Id { + Id::unique("property_sheet_sections").with(scope) +} + +fn jump_id(scope: SectionScope) -> Id { + Id::unique("property_sheet_jump").with(scope) +} + +/// Runs `body` with its section captions tied to the `scope` strip +pub(crate) fn in_scope(ui: &mut Ui, scope: SectionScope, body: impl FnOnce(&mut Ui) -> R) -> R { + let outer = ui.data(|data| data.get_temp::(scope_id())); + ui.data_mut(|data| data.insert_temp(scope_id(), scope)); + let result = body(ui); + ui.data_mut(|data| data.insert_temp(scope_id(), outer.unwrap_or(SectionScope::Docked))); + result +} + +/// The strip the sections being drawn belong to: the docked panel's unless a caller said otherwise +fn current_scope(ui: &Ui) -> SectionScope { + ui.data(|data| data.get_temp::(scope_id())).unwrap_or(SectionScope::Docked) +} + +/// Stores this frame's section captions for the tabs +pub(super) fn remember(ui: &Ui, tops: SectionTops) { + let scope = current_scope(ui); + ui.data_mut(|data| data.insert_temp(sections_id(scope), tops)); +} + +/// Drops the captions the sheets stored last frame, so a list drawn without sections leaves none behind; call before drawing the list +pub(crate) fn forget_sections(ui: &Ui) { + let scope = current_scope(ui); + ui.data_mut(|data| data.remove::(sections_id(scope))); +} + +/// Room to leave under the sheets just drawn in `ui`'s scroll area so the last section's top can reach the top of the view +pub(crate) fn room_past_end(ui: &Ui) -> f32 { + let scope = current_scope(ui); + let last_top = ui.data(|data| data.get_temp::(sections_id(scope))).and_then(|tops| tops.last_top()); + let Some(last_top) = last_top else { return 0.0 }; + + // Where a jump to the section scrolls to: its hairline at the top + let reach = last_top - SECTION_RULE_TO_CAPTION; + (reach + ui.clip_rect().height() - ui.min_rect().bottom()).max(0.0) +} + +/// Whether a tab asked to show `title`: the caller scrolls to it once +pub(super) fn take_jump(ui: &Ui, title: &str) -> bool { + let jump = jump_id(current_scope(ui)); + let wanted = ui.data(|data| data.get_temp::(jump)).is_some_and(|wanted| wanted == title); + if wanted { + ui.data_mut(|data| data.remove::(jump)); + } + wanted +} + +/// A tab from `left` to `right` on `strip`: from just under the strip's top down into the panel the strip sits on +fn tab_rect(strip: Rect, left: f32, right: f32) -> Rect { + Rect::from_min_max(pos2(left, strip.top() + TAB_TOP), pos2(right, strip.bottom() + TAB_BELOW)) +} + /// A tab from `left` to `right` filling `strip`'s whole height and reaching as far into the panel as a section tab: a docked group's shown tab pub(crate) fn full_height_tab_rect(strip: Rect, left: f32, right: f32) -> Rect { Rect::from_min_max(pos2(left, strip.top()), pos2(right, strip.bottom() + TAB_BELOW)) @@ -17,3 +120,36 @@ pub(crate) fn full_height_tab_rect(strip: Rect, left: f32, right: f32) -> Rect { pub(crate) fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) { painter.rect_filled(tab, CornerRadius::same(TAB_ROUNDING), tokens.panel); } + +/// The tab strip on the `scope` panel's top edge, top corners rounded by `top_corner`: one tab per section; a click scrolls to it +pub(crate) fn section_tabs(ui: &mut Ui, scope: SectionScope, top_corner: u8, tabs: &[(&str, &str)]) { + let tokens = Tokens::get(ui.ctx()); + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); + let corners = CornerRadius { nw: top_corner, ne: top_corner, sw: 0, se: 0 }; + ui.painter().rect_filled(strip, corners, tokens.chrome); + let seen = ui.data(|data| data.get_temp::(sections_id(scope))).unwrap_or_default(); + let lit = seen.lit(); + + let mut x = strip.left() + FIRST_TAB; + for (index, (icon, title)) in tabs.iter().enumerate() { + let on = lit.map_or(index == 0, |lit| lit == *title); + let width = ui.painter().layout_no_wrap((*title).to_owned(), semibold(TAB_TEXT_SIZE), Color32::WHITE).size().x + TAB_PADDING; + let tab = tab_rect(strip, x, x + width); + let response = ui.interact(tab, ui.scope_id().with(("section_tab", index)), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Tab, true, on, *title)); + if response.clicked() { + ui.data_mut(|data| data.insert_temp(jump_id(scope), (*title).to_owned())); + } + + let color = if on || response.hovered() { tokens.text } else { tokens.text_dim }; + let painter = ui.painter(); + if on { + shown_tab_box(painter, &tokens, tab); + } + let center_y = strip.center().y + TAB_TOP / 2.0; + painter.text(pos2(x + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, *icon, FontId::proportional(TAB_ICON_SIZE), color); + let font = if on { semibold(TAB_TEXT_SIZE) } else { FontId::proportional(TAB_TEXT_SIZE) }; + painter.text(pos2(x + TAB_NAME_LEFT, center_y), Align2::LEFT_CENTER, *title, font, color); + x += width + TAB_GAP; + } +} diff --git a/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs b/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs new file mode 100644 index 00000000..5fe48e1f --- /dev/null +++ b/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs @@ -0,0 +1,8 @@ +/// Which strip the sections belong to: the docked panel and the right-click popup can show the same sections at once +#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] +pub(crate) enum SectionScope { + /// The docked Properties panel + Docked, + /// The right-click Properties popup over a view + Popup, +} diff --git a/crates/ui-egui/src/property_sheet/section_tabs/section_tops.rs b/crates/ui-egui/src/property_sheet/section_tabs/section_tops.rs new file mode 100644 index 00000000..5165c7eb --- /dev/null +++ b/crates/ui-egui/src/property_sheet/section_tabs/section_tops.rs @@ -0,0 +1,21 @@ +use super::IN_VIEW_SLACK; + +/// The sections' captions seen last frame, top to bottom, and the top of the area they scroll in +#[derive(Clone, Default)] +pub(crate) struct SectionTops { + pub(crate) tops: Vec<(String, f32)>, + pub(crate) view_top: f32, +} + +impl SectionTops { + /// The section in view: the last caption at the top (the panel scrolls far enough for the last one to get there) + pub(crate) fn lit(&self) -> Option<&str> { + let reached = self.tops.iter().rev().find(|(_, top)| *top <= self.view_top + IN_VIEW_SLACK); + reached.or(self.tops.first()).map(|(title, _)| title.as_str()) + } + + /// The top of the last section's caption + pub(crate) fn last_top(&self) -> Option { + self.tops.last().map(|(_, top)| *top) + } +} diff --git a/crates/ui-egui/src/property_sheet/sheet_measure.rs b/crates/ui-egui/src/property_sheet/sheet_measure.rs new file mode 100644 index 00000000..e4a16d55 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/sheet_measure.rs @@ -0,0 +1,15 @@ +/// What one pass of a Properties panel measured, used to place the next pass's columns +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(super) struct SheetMeasure { + /// The widest label that sits beside its control + pub(super) label_width: f32, + + /// Where the widest toggle label ends, from the panel's left padding + pub(super) toggle_label_end: f32, + + /// Where the widest picture row's name ends, from the panel's left padding + pub(super) picture_label_end: f32, + + /// The widest value at a slider's right end + pub(super) value_width: f32, +} diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs new file mode 100644 index 00000000..cfd35af1 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -0,0 +1,238 @@ +use std::ops::RangeInclusive; + + +use super::number_field::shown_number; +use super::track::Track; +use super::value_text::ValueText; +use crate::theme::semibold; + +/// Radius of a slider's knob +pub(super) const KNOB_RADIUS: f32 = 5.0; + +/// Width of a slider's knob outline +const KNOB_STROKE: f32 = 1.5; + +/// Width of a slider's track +const TRACK_WIDTH: f32 = 2.0; + +/// Half the height of a signed slider's zero tick +const ZERO_TICK_HALF: f32 = 4.0; + +/// Radius of an angle row's dial +const DIAL_RADIUS: f32 = 8.0; + +/// The quarter turn back from the screen's 0 rad (pointing right) that points the dial's hand straight up at 0° +const DIAL_ZERO_DEGREES: f32 = 90.0; + +/// Air between the dial and the value, and between the track's end and the dial +const DIAL_AIR: f32 = 6.0; + +impl PropertySheet<'_> { + /// [`Self::slider_with_suffix`] led by `lead` (a picture row, a child setting) + pub(crate) fn slider_led(&mut self, lead: RowLead<'_>, value: &mut f32, range: RangeInclusive, decimals: usize, suffix: &str) -> Option { + let (control, center_y) = self.row_with(lead); + let id = self.next_id(); + let track = Track { start: control.left() + KNOB_RADIUS, end: self.track_end(), center_y, zero: None, ramp: false }; + let dragged = self.track(id, lead.text(), &track, value, &range); + let typed = self.value_field(id, lead.text(), center_y, *value, &range, decimals, suffix); + Self::apply_typed(value, typed, dragged) + } + + /// An angle in degrees: the track, then a small dial just before the value + pub(crate) fn angle(&mut self, label: &str, degrees: &mut f32, range: RangeInclusive) -> Option { + self.angle_led(RowLead::label(label), degrees, range) + } + + /// [`Self::angle`] led by `lead` + pub(crate) fn angle_led(&mut self, lead: RowLead<'_>, degrees: &mut f32, range: RangeInclusive) -> Option { + self.angle_shown(lead, degrees, range, false) + } + + /// [`Self::angle_led`], the value shown with its sign when `plus` + fn angle_shown(&mut self, lead: RowLead<'_>, degrees: &mut f32, range: RangeInclusive, plus: bool) -> Option { + let (control, center_y) = self.row_with(lead); + let id = self.next_id(); + let dial_x = self.right - self.used.value_width.max(super::VALUE_MIN_WIDTH) - DIAL_AIR - DIAL_RADIUS; + let track = Track { + start: control.left() + KNOB_RADIUS, + end: dial_x - DIAL_RADIUS - DIAL_AIR, + center_y, + zero: (*range.start() < 0.0).then_some(0.0), + ramp: false, + }; + let name = lead.text(); + let dragged = self.track(id, name, &track, degrees, &range); + + let tokens = self.tokens; + let painter = self.ui.painter(); + painter.circle_stroke(pos2(dial_x, center_y), DIAL_RADIUS, Stroke::new(KNOB_STROKE, tokens.button_border)); + let turn = (*degrees - DIAL_ZERO_DEGREES).to_radians(); + let hand = pos2(dial_x + DIAL_RADIUS * turn.cos(), center_y + DIAL_RADIUS * turn.sin()); + painter.line_segment([pos2(dial_x, center_y), hand], Stroke::new(TRACK_WIDTH, tokens.text)); + + let shown = if plus { format!("{:+.0}°", *degrees) } else { format!("{:.0}°", *degrees) }; + let typed = self.column_value_field(id, &name, center_y, &shown, "°", *degrees, &range, 0); + Self::apply_typed(degrees, typed, dragged) + } + + /// A typed value wins over a drag in the same frame and starts its own undo step + pub(super) fn apply_typed(value: &mut f32, typed: Option, dragged: Option) -> Option { + match typed { + Some(typed) => { + *value = typed; + Some(false) + } + None => dragged, + } + } + + /// Paints a track with its knob and moves `value` while it is clicked or dragged + pub(super) fn track(&mut self, id: Id, label: impl std::fmt::Display, track: &Track, value: &mut f32, range: &RangeInclusive) -> Option { + let (minimum, maximum) = (*range.start(), *range.end()); + let span = (maximum - minimum).max(f32::EPSILON); + let length = (track.end - track.start).max(1.0); + let hit = Rect::from_min_max( + pos2(track.start - KNOB_RADIUS, track.center_y - ROW_HIT_HALF_HEIGHT), + pos2(track.end + KNOB_RADIUS, track.center_y + ROW_HIT_HALF_HEIGHT), + ); + let response = self.ui.interact(hit, id, Sense::click_and_drag()); + response.widget_info(|| WidgetInfo::slider(true, f64::from(*value), &label)); + + let mut moved = false; + if (response.dragged() || response.clicked()) + && let Some(pointer) = response.interact_pointer_pos() + { + let picked = kept_in(minimum + (pointer.x - track.start) / length * span, range); + if picked != *value { + *value = picked; + moved = true; + } + } + + // A press's first change starts an undo step, its later changes continue it + let edit = crate::widgets::press_edit(self.ui, response.id, moved); + + let tokens = self.tokens; + let at = |v: f32| track.start + ((v - minimum) / span).clamp(0.0, 1.0) * length; + let knob_x = at(*value); + let zero_x = track.zero.map_or(track.start, |zero| at(kept_in(zero, range))); + let painter = self.ui.painter(); + if !track.ramp { + painter.line_segment([pos2(track.start, track.center_y), pos2(track.end, track.center_y)], Stroke::new(TRACK_WIDTH, tokens.button_border)); + painter.line_segment([pos2(zero_x.min(knob_x), track.center_y), pos2(zero_x.max(knob_x), track.center_y)], Stroke::new(TRACK_WIDTH, tokens.accent)); + } + if track.zero.is_some() { + let tick = [pos2(zero_x, track.center_y - ZERO_TICK_HALF), pos2(zero_x, track.center_y + ZERO_TICK_HALF)]; + painter.line_segment(tick, Stroke::new(1.0, tokens.text_dim)); + } + let outline = if response.hovered() || response.dragged() { tokens.accent } else { tokens.text }; + painter.circle(pos2(knob_x, track.center_y), KNOB_RADIUS, tokens.panel, Stroke::new(KNOB_STROKE, outline)); + edit + } + + /// The value at the row's end, answering as `label`'s value; a click turns it into a field, which returns the typed value when done + #[allow(clippy::too_many_arguments)] + pub(super) fn value_field( + &mut self, + id: Id, + label: impl std::fmt::Display, + center_y: f32, + value: f32, + range: &RangeInclusive, + decimals: usize, + suffix: &str, + ) -> Option { + let shown = format!("{}{suffix}", shown_number(value, decimals)); + self.column_value_field(id, &label, center_y, &shown, suffix, value, range, decimals) + } + + /// [`Self::value_field`] reading `shown`: the panel's value column grows to fit it + #[allow(clippy::too_many_arguments)] + pub(super) fn column_value_field( + &mut self, + id: Id, + label: &dyn std::fmt::Display, + center_y: f32, + shown: &str, + suffix: &str, + value: f32, + range: &RangeInclusive, + decimals: usize, + ) -> Option { + self.measure_value(shown); + let width = self.used.value_width.max(super::VALUE_MIN_WIDTH); + self.value_text_field(id, ValueText { label, right: self.right, width, center_y, shown, suffix }, value, range, decimals) + } + + /// [`Self::value_field`] ending at `right`, `width` wide, outside the panel's value column + #[allow(clippy::too_many_arguments)] + pub(super) fn value_field_at( + &mut self, + id: Id, + label: impl std::fmt::Display, + right: f32, + width: f32, + center_y: f32, + value: f32, + range: &RangeInclusive, + decimals: usize, + suffix: &str, + ) -> Option { + let shown = format!("{}{suffix}", shown_number(value, decimals)); + self.value_text_field(id, ValueText { label: &label, right, width, center_y, shown: &shown, suffix }, value, range, decimals) + } + + /// A value drawn as `text.shown` that turns into a field when clicked; returns the typed value (its `text.suffix` and a leading "×" or "x" allowed), kept in `range` + pub(super) fn value_text_field(&mut self, id: Id, value_text: ValueText<'_>, value: f32, range: &RangeInclusive, decimals: usize) -> Option { + let ValueText { label, right, width, center_y, shown, suffix } = value_text; + let rect = Rect::from_min_max(pos2(right - width, center_y - ROW_HIT_HALF_HEIGHT), pos2(right, center_y + ROW_HIT_HALF_HEIGHT)); + let field_id = id.with("typed"); + let editing = self.ui.data(|data| data.get_temp::(field_id)); + let seeded = || shown_number(value, decimals); + + let tokens = self.tokens; + let Some(mut typed_text) = editing else { + self.skip_typing_edit(); + let response = self.ui.interact(rect, id.with("value"), Sense::click()).on_hover_cursor(egui::CursorIcon::Text); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, true, crate::i18n::trf("{label} value", &[("label", label)]))); + self.ui.painter().text(pos2(right, center_y), Align2::RIGHT_CENTER, shown, semibold(TEXT_SIZE), tokens.text); + + if response.hovered() { + self.value_line(rect.left(), right, center_y, tokens.field_border); + } + if response.clicked() { + self.start_typing(field_id, seeded()); + } + return None; + }; + + // Typing happens on the value's own line: no box, the line under it goes accent + let edit = egui::TextEdit::singleline(&mut typed_text).id(field_id).font(semibold(TEXT_SIZE)).align(egui::Align2::RIGHT_CENTER); + let response = self.typing_edit(rect.left(), right, center_y, edit); + self.value_line(rect.left(), right, center_y, tokens.accent); + if !response.lost_focus() { + self.ui.data_mut(|data| data.insert_temp(field_id, typed_text)); + return None; + } + + let untouched = self.end_typing(field_id, &typed_text); + if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) { + return None; + } + + // Leaving the field as it opened changes nothing: no undo step, no rounding to the shown decimals, no overwriting a value changed meanwhile + if untouched || typed_text.trim() == seeded() { + return None; + } + + let typed: f32 = typed_text.trim().trim_end_matches(suffix).trim_start_matches(['×', 'x']).trim().parse().ok()?; + + // A typed value that lands on the current one (a clamp, "0.750" for 0.75) is no edit either + typed.is_finite().then(|| kept_in(typed, range)).filter(|kept| *kept != value) + } +} + +/// `value` kept in `range`; unlike `clamp`, a reversed or NaN range never panics +pub(super) fn kept_in(value: f32, range: &RangeInclusive) -> f32 { + value.max(*range.start()).min(*range.end()) +} diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs new file mode 100644 index 00000000..96e72f7e --- /dev/null +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -0,0 +1,64 @@ + + +/// Air between a full-width button's icon and its words +const BUTTON_ICON_GAP: f32 = 8.0; + +/// Size of a full-width button's icon +const BUTTON_ICON_SIZE: f32 = 14.0; + +impl PropertySheet<'_> { + /// A full-width button: centred icon and words + pub(crate) fn button<'a>(&mut self, icon: impl Into>, text: &str) -> egui::Response { + self.button_lit(icon, text, false) + } + + /// A full-width button lit in the accent while what it turns on stays on + pub(crate) fn button_lit<'a>(&mut self, icon: impl Into>, text: &str, lit: bool) -> egui::Response { + self.button_enabled(icon, text, lit, true) + } + + /// [`Self::button_lit`] that answers no clicks and dims its words while not `enabled` + pub(crate) fn button_enabled<'a>(&mut self, icon: impl Into>, text: &str, lit: bool, enabled: bool) -> egui::Response { + self.button_sensing(icon.into(), text, lit, if enabled { Sense::click() } else { Sense::hover() }) + } + + fn button_sensing(&mut self, icon: ButtonIcon<'_>, text: &str, lit: bool, sense: Sense) -> egui::Response { + let enabled = sense != Sense::hover(); + let rect = self.take(ROW_HEIGHT); + let button = self.control_box(self.left, rect.center().y); + let id = self.next_id(); + let response = self.ui.interact(button, id, sense); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, text)); + + let tokens = self.tokens; + let painter = self.ui.painter(); + painter.rect( + button, + CornerRadius::same(CONTROL_RADIUS), + match (lit, enabled && response.hovered()) { + (true, _) => tokens.accent_dim, + (false, true) => tokens.row_hover, + (false, false) => tokens.button, + }, + Stroke::new(1.0, if lit { tokens.accent } else { tokens.button_border }), + StrokeKind::Inside, + ); + let color = if enabled { tokens.text } else { tokens.text_dim }; + let font = FontId::proportional(TEXT_SIZE); + let (icon_width, icon_galley) = match icon { + ButtonIcon::Glyph(glyph) => { + let galley = painter.layout_no_wrap(glyph.to_owned(), FontId::proportional(BUTTON_ICON_SIZE), color); + (galley.size().x, Some(galley)) + } + }; + let text_galley = painter.layout_no_wrap(text.to_owned(), font, color); + let total = icon_width + BUTTON_ICON_GAP + text_galley.size().x; + let x = button.center().x - total / 2.0; + if let Some(galley) = icon_galley { + painter.galley(pos2(x, button.center().y - galley.size().y / 2.0), galley, color); + } + painter.galley(pos2(x + icon_width + BUTTON_ICON_GAP, button.center().y - text_galley.size().y / 2.0), text_galley, color); + self.drawn(button.bottom()); + response + } +} diff --git a/crates/ui-egui/src/property_sheet/stack_slider.rs b/crates/ui-egui/src/property_sheet/stack_slider.rs new file mode 100644 index 00000000..b68c602d --- /dev/null +++ b/crates/ui-egui/src/property_sheet/stack_slider.rs @@ -0,0 +1,20 @@ +use std::ops::RangeInclusive; + +/// One captioned slider in the stack beside a picture +pub(crate) struct StackSlider<'a> { + /// The dim caption above the track (Count, Angle span) + pub(crate) label: &'a str, + + pub(crate) value: &'a mut f32, + + /// What the track spans + pub(crate) range: RangeInclusive, + + /// What a typed value may reach, at least the track's span (a radial Count types past its track's most) + pub(crate) typed: RangeInclusive, + + pub(crate) decimals: usize, + + /// A unit after the value ("°") + pub(crate) suffix: &'a str, +} diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs new file mode 100644 index 00000000..e0107857 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -0,0 +1,204 @@ +use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; + +use crate::theme::semibold; + +/// Draws a picture row's picture into its square +type RowPicture<'a> = &'a dyn Fn(&Painter, Rect); + +/// Draws option `index`'s picture into its square +type SegmentPicture<'a> = &'a dyn Fn(&Painter, Rect, usize); + +/// Side of a picture beside a switch's word, and the air between them +const SEGMENT_PICTURE_SIZE: f32 = 14.0; +const SEGMENT_PICTURE_AIR: f32 = 6.0; + +/// Room a switch's word needs in its segment beyond its own width (6 px each side: Bevel Smooth's Out | In | In/Out fits beside the widest label column) +const SEGMENT_AIR: f32 = 12.0; + +/// How far the chosen segment sits inside the switch's box +const SEGMENT_INSET: f32 = 2.0; + +/// Corner radius of a switch's box +const SWITCH_RADIUS: u8 = 6; + +/// Size of a toggle's pill +pub(super) const PILL_SIZE: egui::Vec2 = vec2(22.0, 13.0); + +/// Corner radius of a toggle's pill: about half its height, so its ends are round +const PILL_RADIUS: u8 = 6; + +/// Radius of a toggle's knob, and how far it sits from the pill's middle +const TOGGLE_KNOB_RADIUS: f32 = 4.0; +const TOGGLE_KNOB_TRAVEL: f32 = 4.5; + +/// From one of a pair's toggles to the next, and from its name to its pill's centre +const PAIR_PITCH: f32 = 76.0; +const PAIR_NAME_TO_PILL: f32 = 32.0; + +impl PropertySheet<'_> { + /// Two to four short choices as a boxed switch, or a dropdown when one doesn't fit; returns the picked index + pub(crate) fn switch(&mut self, label: &str, options: &[&str], selected: usize) -> Option { + self.switch_tinted(label, options, selected, &[]) + } + + /// [`Self::switch`] whose chosen word takes its colour from `tints` (axis colours) + pub(crate) fn switch_tinted(&mut self, label: &str, options: &[&str], selected: usize, tints: &[Color32]) -> Option { + let stacks = self.text_width(label, FontId::proportional(TEXT_SIZE)) > self.column() - self.left - super::LABEL_MIN_AIR; + let left = if stacks { self.left } else { self.column() }; + if !self.switch_fits(options, left) { + return self.switch_dropdown(label, options, selected); + } + + let (control, _) = self.row(label); + let runs = |index: usize| tints.get(index).map(std::slice::from_ref).unwrap_or_default(); + self.segments(control, options, selected, runs, None) + } + + /// Whether every option's word fits its share of a switch from `left` to the panel's right edge + fn switch_fits(&self, options: &[&str], left: f32) -> bool { + let segment = (self.right - left) / options.len().max(1) as f32; + options.iter().all(|option| self.text_width(option, semibold(SMALL_TEXT_SIZE)) + SEGMENT_AIR <= segment) + } + + /// The dropdown a switch whose words don't fit becomes; returns the picked index + fn switch_dropdown(&mut self, label: &str, options: &[&str], selected: usize) -> Option { + let name = |index: usize| options.get(index).copied().unwrap_or_default().to_owned(); + self.dropdown_built(label, selected, || 0..options.len(), name, None).0 + } + + /// A boxed switch's box and segments in `control`, the chosen word in the colours `tints` gives its index (none: the text colour); returns the segment clicked when it was not the chosen one + pub(super) fn segments<'t>( + &mut self, + control: Rect, + options: &[&str], + selected: usize, + tints: impl Fn(usize) -> &'t [Color32], + picture: Option>, + ) -> Option { + let segment = control.width() / options.len().max(1) as f32; + let tokens = self.tokens; + self.ui.painter().rect(control, CornerRadius::same(SWITCH_RADIUS), tokens.field, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); + let mut picked = None; + for (index, option) in options.iter().enumerate() { + let rect = Rect::from_min_size(pos2(control.left() + index as f32 * segment, control.top()), vec2(segment, control.height())); + let id = self.next_id(); + let response = self.ui.interact(rect, id, Sense::click()); + let on = index == selected; + response.widget_info(|| WidgetInfo::selected(Role::RadioButton, true, on, *option)); + if response.clicked() && !on { + picked = Some(index); + } + + let painter = self.ui.painter(); + if on { + painter.rect_filled(rect.shrink(SEGMENT_INSET), CornerRadius::same(CONTROL_RADIUS), tokens.button); + } else if response.hovered() { + painter.rect_filled(rect.shrink(SEGMENT_INSET), CornerRadius::same(CONTROL_RADIUS), tokens.row_hover); + } + let runs = tints(index); + let tint = runs.first().copied().unwrap_or(tokens.text); + let (font, color) = if on { (semibold(SMALL_TEXT_SIZE), tint) } else { (FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim) }; + let Some(draw) = picture else { + let word = + if on && runs.len() > 1 { split_word(painter, option, runs, &font) } else { painter.layout_no_wrap((*option).to_owned(), font, color) }; + painter.galley(rect.center() - word.size() / 2.0, word, color); + continue; + }; + + // The picture and the word centred together in the segment + let word = painter.layout_no_wrap((*option).to_owned(), font, color); + let left = rect.center().x - (SEGMENT_PICTURE_SIZE + SEGMENT_PICTURE_AIR + word.size().x) / 2.0; + draw( + painter, + Rect::from_min_size(pos2(left, rect.center().y - SEGMENT_PICTURE_SIZE / 2.0), vec2(SEGMENT_PICTURE_SIZE, SEGMENT_PICTURE_SIZE)), + index, + ); + let word_left = left + SEGMENT_PICTURE_SIZE + SEGMENT_PICTURE_AIR; + painter.galley(pos2(word_left, rect.center().y - word.size().y / 2.0), word, color); + } + picked + } + + /// A culling row on the panel's grid: its name on the label column, its picture where the controls start with the switch after it, a pending i at the row's right end + pub(crate) fn picture_toggle(&mut self, picture: RowPicture<'_>, label: &str, on: &mut bool) -> bool { + let rect = self.take(ROW_HEIGHT); + let center_y = rect.center().y; + self.paint_info_at_end(center_y); + let font = FontId::proportional(TEXT_SIZE); + + // A name too long for the label column pushes every picture row's picture right instead of running under it + let label_end = self.text_width(label, font.clone()) + super::LABEL_MIN_AIR; + self.seen.picture_label_end = self.seen.picture_label_end.max(label_end); + let picture_x = self.left + (self.column() - self.left).max(self.used.picture_label_end).max(label_end); + let square = Rect::from_min_size(pos2(picture_x, center_y - ROW_PICTURE_SIZE / 2.0), vec2(ROW_PICTURE_SIZE, ROW_PICTURE_SIZE)); + let pill = Rect::from_min_size(pos2(square.right() + ROW_PICTURE_AIR, center_y - PILL_SIZE.y / 2.0), PILL_SIZE); + let clicked = self.toggle_hit(Rect::from_min_max(pos2(self.left, rect.top()), pos2(pill.right(), rect.bottom())), label, on); + + let text = self.tokens.text; + picture(self.ui.painter(), square); + self.ui.painter().text(pos2(self.left, center_y), Align2::LEFT_CENTER, label, font, text); + self.pill(pill.center(), *on, true); + self.drawn(square.bottom()); + clicked + } + + /// A toggle's clickable area: a click flips `on`; returns whether it was clicked + fn toggle_hit(&mut self, hit: Rect, label: &str, on: &mut bool) -> bool { + let id = self.next_id(); + let response = self.ui.interact(hit, id, Sense::click()); + if response.clicked() { + *on = !*on; + } + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *on, label)); + response.clicked() + } + + /// Two named toggles side by side after one label (Flip copy: U, V); returns the index clicked + pub(crate) fn toggle_pair(&mut self, label: &str, names: [&str; 2], on: &mut [bool; 2]) -> Option { + let (control, center_y) = self.row(label); + let font = FontId::proportional(TEXT_SIZE); + let mut clicked = None; + for (index, (name, state)) in names.into_iter().zip(on.iter_mut()).enumerate() { + let x = control.left() + index as f32 * PAIR_PITCH; + let pill = pos2(x + PAIR_NAME_TO_PILL, center_y); + let hit = Rect::from_min_max(pos2(x, control.top()), pos2(pill.x + PILL_SIZE.x / 2.0, control.bottom())); + let id = self.next_id(); + let response = self.ui.interact(hit, id, Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *state, format!("{label} {name}"))); + if response.clicked() { + *state = !*state; + clicked = Some(index); + } + let tokens = self.tokens; + self.ui.painter().text(pos2(x, center_y), Align2::LEFT_CENTER, name, font.clone(), if *state { tokens.text } else { tokens.text_dim }); + self.pill(pill, *state, true); + } + clicked + } + + /// A toggle's pill centred on `center`: on (accent), off, or greyed out when not `enabled` + pub(super) fn pill(&self, center: egui::Pos2, on: bool, enabled: bool) { + let tokens = self.tokens; + let (fill, border, knob, knob_x) = match (enabled, on) { + (false, _) => (tokens.field, tokens.separator, tokens.separator, center.x - TOGGLE_KNOB_TRAVEL), + (true, true) => (tokens.accent_dim, tokens.accent, tokens.text, center.x + TOGGLE_KNOB_TRAVEL), + (true, false) => (tokens.button, tokens.button_border, tokens.text_dim, center.x - TOGGLE_KNOB_TRAVEL), + }; + let painter = self.ui.painter(); + painter.rect(Rect::from_center_size(center, PILL_SIZE), CornerRadius::same(PILL_RADIUS), fill, Stroke::new(1.0, border), StrokeKind::Inside); + painter.circle_filled(pos2(knob_x, center.y), TOGGLE_KNOB_RADIUS, knob); + } +} + +/// `word` laid out with its letters split as evenly as they go between the colours of `runs` +fn split_word(painter: &Painter, word: &str, runs: &[Color32], font: &FontId) -> std::sync::Arc { + let letters: Vec = word.chars().collect(); + let mut job = egui::text::LayoutJob::default(); + let parts = runs.len().max(1); + for (part, color) in runs.iter().enumerate() { + let (start, end) = (letters.len() * part / parts, letters.len() * (part + 1) / parts); + let text: String = letters.get(start..end).unwrap_or_default().iter().collect(); + job.append(&text, 0.0, egui::TextFormat::simple(font.clone(), *color)); + } + painter.layout_job(job) +} diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs new file mode 100644 index 00000000..546bddf2 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -0,0 +1,243 @@ +use egui::{Color32, CornerRadius, Painter, Rect}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable as _; + +use super::number_field::shown_number; +use super::{NumberField, PropertySheet}; +use crate::theme::{Accent, Brightness, Tokens}; + +mod filtering; +mod gallery; + +use filtering::Filtering; +use gallery::Gallery; + +/// Width of the Properties panel the mockups are drawn at +const PANEL_WIDTH: f32 = 300.0; + +/// The harness window: the panel plus room on its right for popups and tips, tall enough for the whole gallery unscrolled +const HARNESS_SIZE: egui::Vec2 = egui::vec2(PANEL_WIDTH + 260.0, 1000.0); + +fn swatch(color: Color32) -> impl Fn(&Painter, Rect) { + move |painter: &Painter, rect: Rect| { + painter.rect_filled(rect, CornerRadius::ZERO, color); + } +} + +fn filtering_picture(painter: &Painter, rect: Rect, filtering: Filtering) { + let shade = match filtering { + Filtering::BilinearHq => 200, + Filtering::BilinearSharp => 150, + Filtering::Nearest => 100, + }; + painter.rect_filled(rect.shrink(2.0), CornerRadius::same(2), Color32::from_gray(shade)); +} + +fn gallery(ui: &mut egui::Ui, state: &mut Gallery) { + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "gallery", |sheet| { + if let Some(picked) = sheet + .dropdown( + "Filtering", + state.filtering, + &[Filtering::BilinearHq, Filtering::BilinearSharp, Filtering::Nearest], + Filtering::name, + Some(&filtering_picture), + ) + .0 + { + state.filtering = picked; + } + + let reset = sheet.band("3D projection settings", true, Some(state.position != [0.0; 3]), None); + if reset.reset { + state.position = [0.0; 3]; + } + if reset.open { + let mut fields = [("X", 0), ("Y", 1), ("Z", 2)].map(|(tag, axis)| NumberField { + tag, + tag_color: crate::theme::AXIS_COLORS.get(axis).copied(), + value: state.position[axis], + speed: 0.01, + decimals: 2, + suffix: "", + }); + if let Some((axis, merge)) = sheet.number_fields("Position", &mut fields, Some(&mut state.linked), false) + && let Some(slot) = state.position.get_mut(axis) + { + *slot = fields[axis].value; + state.position_merges.push(merge); + } + } + }); + }); +} + +/// A harness in `brightness`, with the app's fonts from the first frame +fn builder(brightness: Brightness) -> egui_kittest::HarnessBuilder { + Harness::builder().with_size(HARNESS_SIZE).with_context_setup(move |ctx| { + crate::theme::install(ctx); + crate::theme::apply(ctx, brightness, Accent::default()); + }) +} + +fn gallery_harness(brightness: Brightness, gallery_state: Gallery) -> Harness<'static, Gallery> { + let mut harness = builder(brightness).build_ui_state(gallery, gallery_state); + harness.run_steps(3); + harness +} + +/// Two culling rows, the second named past the label column +fn culling_rows(ui: &mut egui::Ui, on: &mut [bool; 2]) { + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "culling", |sheet| { + sheet.picture_toggle(&swatch(Color32::from_gray(160)), "Depth", &mut on[0]); + sheet.picture_toggle(&swatch(Color32::from_gray(100)), "Backface culling past the column", &mut on[1]); + }); + }); +} + +/// A culling name too long for the label column moves every culling row's picture and switch, so the switches stay one column +#[test] +fn culling_rows_keep_their_switches_in_one_column_when_a_name_is_long() { + let mut harness = builder(Brightness::MediumDark).build_ui_state(culling_rows, [false; 2]); + harness.run_steps(3); + + let short = harness.get_by_label("Depth").rect(); + let long = harness.get_by_label("Backface culling past the column").rect(); + + assert_eq!(short.right(), long.right(), "both switches end at one x: {short:?} vs {long:?}"); +} + +/// A gray slider in a panel-wide column; records the column's right edge +fn gray_row(ui: &mut egui::Ui, state: &mut (f32, f32)) { + ui.set_width(PANEL_WIDTH); + state.1 = ui.max_rect().right(); + crate::gray_slider::gray_slider(ui, "Color", &mut state.0); +} + +/// A gray slider's invert button ends on the column's right edge (a plain button was wider than the room kept for it) +#[test] +fn a_gray_sliders_invert_button_ends_on_its_columns_right_edge() { + // the slider's typed value field (upstream's) carries no accessible name + let mut harness = builder(Brightness::MediumDark).with_accessibility_check(false).build_ui_state(gray_row, (0.5, 0.0)); + harness.run_steps(3); + + let invert = harness.get_by_role(egui::accesskit::Role::Button).rect(); + let right = harness.state().1; + assert!(invert.right() <= right + 0.5, "the button ends at {} past the column's {right}", invert.right()); +} + +/// Where `wanted` is painted, first to last +fn painted_at(harness: &Harness<'_, State>, wanted: &str) -> Vec { + let shapes = harness.output().shapes.iter(); + shapes + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == wanted => Some(text.pos), + _ => None, + }) + .collect() +} + +/// An open dropdown's options start their words at the button's own word x (they started 1 px in, inside the list's border) +#[test] +fn an_open_dropdowns_options_start_at_the_buttons_word() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let button = harness.get_by_label("Bilinear | HQ").rect(); + + let at = button.center(); + click_at(&mut harness, at); + harness.run_steps(2); + + let button_word = painted_at(&harness, "Bilinear | HQ").into_iter().find(|at| button.contains(*at)).map(|at| at.x); + let option_word = painted_at(&harness, "Nearest").first().map(|at| at.x); + assert!(button_word.is_some() && option_word == button_word, "the option's word at {option_word:?}, the button's at {button_word:?}"); +} + +#[test] +fn dropdown_list_hangs_from_its_button_at_its_width_and_picks() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let button = harness.get_by_label("Bilinear | HQ").rect(); + let at = harness.get_by_label("Bilinear | HQ").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + + let option = harness.get_by_label("Nearest").rect(); + let list = option.expand(super::choice::LIST_BORDER); + assert_eq!(list.left(), button.left(), "the list starts at the button's left edge"); + assert_eq!(list.width(), button.width(), "the list is the button's width"); + assert!(option.top() > button.bottom(), "the list hangs below the button"); + + let at = harness.get_by_label("Nearest").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + assert_eq!(harness.state().filtering, Filtering::Nearest); +} + +/// Presses and lets go at `at` through the real pointer path, so a control drawn over another gets the click it would get from a person +fn click_at(harness: &mut Harness<'_, State>, at: egui::Pos2) { + let modifiers = egui::Modifiers::NONE; + harness.event(egui::Event::PointerMoved(at)); + harness.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(1); +} + +/// A reason too long for its caption's row is cut with "…", and hovering it shows it whole +#[test] +fn a_cut_unavailable_reason_reads_whole_in_its_tooltip() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + const REASON: &str = "Not available with this projection, for a reason far too long to fit beside the caption"; + const TOOLTIP_WAIT_FRAMES: usize = 60; + let mut harness = builder(Brightness::MediumDark).build_ui(|ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "unavailable", |sheet| sheet.section_unavailable("Symmetry", REASON)); + }); + harness.run_steps(2); + let reason = harness.get_by_label(REASON).rect(); + assert!(reason.right() <= PANEL_WIDTH + 1.0, "the reason is cut to fit the panel: {reason:?}"); + + harness.hover_at(reason.center()); + harness.run_steps(TOOLTIP_WAIT_FRAMES); + assert!(harness.get_all_by_label(REASON).count() > 1, "its tooltip reads it whole"); +} + +/// A number field held still until egui starts its drag, then moved, starts its own undo step with its first change +#[test] +fn a_number_field_held_still_then_dragged_starts_an_undo_step_with_its_first_change() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let field = harness.get_by_label("Position X").rect(); + harness.drag_at(field.center()); + + // Past egui's longest click, the press becomes a drag that has not moved + harness.run_steps(5); + harness.hover_at(field.center() + egui::vec2(10.0, 0.0)); + harness.run(); + harness.hover_at(field.center() + egui::vec2(20.0, 0.0)); + harness.run(); + harness.drop_at(field.center() + egui::vec2(20.0, 0.0)); + harness.run(); + + let merges = &harness.state().position_merges; + assert!(merges.len() >= 2, "the drag changes the value more than once: {merges:?}"); + assert_eq!(merges.first(), Some(&false), "the first move starts an undo step: {merges:?}"); + assert!(merges.iter().skip(1).all(|merge| *merge), "later moves continue it: {merges:?}"); +} + +#[test] +fn a_number_field_reads_zero_without_a_minus_sign() { + assert_eq!(shown_number(-0.0, 0), "0"); + assert_eq!(shown_number(-0.004, 2), "0.00"); + assert_eq!(shown_number(-0.3, 0), "0"); + assert_eq!(shown_number(-0.6, 0), "-1"); + assert_eq!(shown_number(-1.25, 2), "-1.25"); + assert_eq!(shown_number(2.5, 1), "2.5"); +} diff --git a/crates/ui-egui/src/property_sheet/tests/filtering.rs b/crates/ui-egui/src/property_sheet/tests/filtering.rs new file mode 100644 index 00000000..b37210ca --- /dev/null +++ b/crates/ui-egui/src/property_sheet/tests/filtering.rs @@ -0,0 +1,19 @@ +//! The gallery's Filtering choice + +#[derive(Clone, Copy, PartialEq, Debug)] +pub(super) enum Filtering { + BilinearHq, + BilinearSharp, + Nearest, +} + +impl Filtering { + pub(super) fn name(self) -> String { + match self { + Filtering::BilinearHq => "Bilinear | HQ", + Filtering::BilinearSharp => "Bilinear | Sharp", + Filtering::Nearest => "Nearest", + } + .to_owned() + } +} diff --git a/crates/ui-egui/src/property_sheet/tests/gallery.rs b/crates/ui-egui/src/property_sheet/tests/gallery.rs new file mode 100644 index 00000000..3a9e730a --- /dev/null +++ b/crates/ui-egui/src/property_sheet/tests/gallery.rs @@ -0,0 +1,15 @@ +//! What the gallery's controls last set + +use super::Filtering; + +pub(super) struct Gallery { + pub(super) filtering: Filtering, + pub(super) position: [f32; 3], + pub(super) position_merges: Vec, + pub(super) linked: bool, +} + +impl Default for Gallery { + fn default() -> Self { + } +} diff --git a/crates/ui-egui/src/property_sheet/tooltip.rs b/crates/ui-egui/src/property_sheet/tooltip.rs new file mode 100644 index 00000000..d9c37f65 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/tooltip.rs @@ -0,0 +1,32 @@ +use egui::{RectAlign, Response}; + +use super::PropertySheet; + +/// Where a tooltip goes when the window has no room above a control in the panel's right half: below it, then the other edge +const RIGHT_HALF_FALLBACKS: [RectAlign; 3] = [RectAlign::BOTTOM_END, RectAlign::TOP_START, RectAlign::BOTTOM_START]; + +/// The same for a control in the panel's left half +const LEFT_HALF_FALLBACKS: [RectAlign; 3] = [RectAlign::BOTTOM_START, RectAlign::TOP_END, RectAlign::BOTTOM_END]; + +impl PropertySheet<'_> { + /// A tooltip for `response` right next to it: above the control, flush with its edge nearer the panel's side so it grows toward the middle + pub(crate) fn tip(&self, response: Response, text: &str) -> Response { + let (align, fallbacks) = if response.rect.center().x > self.ui.max_rect().center().x { + (RectAlign::TOP_END, &RIGHT_HALF_FALLBACKS) + } else { + (RectAlign::TOP_START, &LEFT_HALF_FALLBACKS) + }; + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip.popup.anchor(&response).align(align).align_alternatives(fallbacks); + tooltip.show(|ui| ui.label(text)); + response + } + + /// A tooltip for a pad, outside the panel beside it, where it covers no value of the panel; under it when the panel has no room on its left + pub(crate) fn tip_beside(&self, response: Response, text: &str) -> Response { + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip.popup.anchor(&response).align(RectAlign::LEFT_START).align_alternatives(&[RectAlign::BOTTOM_START]); + tooltip.show(|ui| ui.label(text)); + response + } +} diff --git a/crates/ui-egui/src/property_sheet/track.rs b/crates/ui-egui/src/property_sheet/track.rs new file mode 100644 index 00000000..d4f2f91c --- /dev/null +++ b/crates/ui-egui/src/property_sheet/track.rs @@ -0,0 +1,13 @@ +//! The line a slider's knob runs along + +/// What a slider's knob runs along and shows +pub(super) struct Track { + pub(super) start: f32, + pub(super) end: f32, + pub(super) center_y: f32, + /// Where a two-sided range's fill starts and its tick sits (0 for signed ranges, 0.5 for a 0..1 range centred on "unchanged") + pub(super) zero: Option, + + /// The track is a picture of its range (a gray ramp) drawn by the caller: no line and no fill + pub(super) ramp: bool, +} diff --git a/crates/ui-egui/src/property_sheet/value_text.rs b/crates/ui-egui/src/property_sheet/value_text.rs new file mode 100644 index 00000000..b40ca7a4 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/value_text.rs @@ -0,0 +1,63 @@ +//! Where a slider's value sits and how it reads + +/// A value drawn right-aligned at `right` in a `width` wide box centred on `center_y`, reading `shown`; typing may end in `suffix`; it answers as `label`'s value +pub(super) struct ValueText<'a> { + pub(super) label: &'a dyn std::fmt::Display, + pub(super) right: f32, + pub(super) width: f32, + pub(super) center_y: f32, + pub(super) shown: &'a str, + pub(super) suffix: &'a str, +} + +/// How far below a value's centre its typing line runs +const LINE_DROP: f32 = 9.0; + +/// Where the field `field_id` keeps the text its typing opened with +fn opened_id(field_id: egui::Id) -> egui::Id { + field_id.with("opened") +} + +impl super::PropertySheet<'_> { + /// Starts typing `text` into the field `field_id`, all of it selected so the first key replaces it + pub(super) fn start_typing(&mut self, field_id: egui::Id, text: String) { + let mut state = egui::text_edit::TextEditState::load(self.ui.ctx(), field_id).unwrap_or_default(); + state.cursor.set_char_range(Some(egui::text::CCursorRange::select_all_str(&text))); + state.store(self.ui.ctx(), field_id); + self.ui.data_mut(|data| { + data.insert_temp(opened_id(field_id), text.clone()); + data.insert_temp(field_id, text); + }); + self.ui.memory_mut(|memory| memory.request_focus(field_id)); + } + + /// Ends typing into the field `field_id`; whether `typed` is still the text it opened with (left so, it changes nothing, even after the value changed meanwhile) + pub(super) fn end_typing(&mut self, field_id: egui::Id, typed: &str) -> bool { + let opened = self.ui.data_mut(|data| { + data.remove::(field_id); + data.remove_temp::(opened_id(field_id)) + }); + opened.is_some_and(|opened| opened.trim() == typed.trim()) + } + + /// Shows `edit` from `left` to `right` centred on `center_y` (an edit is never shorter than the theme's interact height), so its value sits where the shown value sat; leaves the sheet's rows where they are + pub(super) fn typing_edit(&mut self, left: f32, right: f32, center_y: f32, edit: egui::TextEdit<'_>) -> egui::Response { + let line = self.ui.painter().layout_no_wrap("0".to_owned(), crate::theme::semibold(super::TEXT_SIZE), self.tokens.text).size().y; + let height = line.max(self.ui.spacing().interact_size.y); + let rect = egui::Rect::from_min_max(egui::pos2(left, center_y - height / 2.0), egui::pos2(right, center_y + height / 2.0)); + let layout = egui::Layout::centered_and_justified(egui::Direction::TopDown); + let mut child = self.ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(layout)); + child.add(edit.frame(egui::Frame::NONE).margin(egui::vec2(0.0, 0.0))) + } + + /// Takes the one auto id [`Self::typing_edit`]'s child takes, for a value shown instead of typed: the controls after it keep their ids when typing starts or ends, so a click from one field to the next types into the one clicked + pub(super) fn skip_typing_edit(&mut self) { + self.ui.skip_ahead_auto_ids(1); + } + + /// The 1 px line under a typeable value centred on `center_y`, from `left` to `right`: grey on hover, accent while typing + pub(super) fn value_line(&self, left: f32, right: f32, center_y: f32, color: egui::Color32) { + let y = (center_y + LINE_DROP).round() + 0.5; + self.ui.painter().line_segment([egui::pos2(left, y), egui::pos2(right, y)], egui::Stroke::new(1.0, color)); + } +} From 9be079d6f8dcf770372861a094c93b35a9bc3f99 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:10 +0000 Subject: [PATCH 04/17] Fills: every projection samples with tiling, rotation and offset, Filtering, UV Wrap and Match per UV Tile --- crates/compose/src/axis_frame.rs | 158 +++++++++ crates/compose/src/fill_place.rs | 12 + crates/compose/src/mip_level.rs | 35 ++ crates/compose/src/pattern.rs | 454 +++++++++++++++++------- crates/compose/src/tile_length.rs | 155 ++++++++ crates/core/src/layer.rs | 231 +++++++++++- crates/engine/tests/it/fill_patterns.rs | 69 ++++ crates/engine/tests/it/fill_sampling.rs | 218 ++++++++++++ 8 files changed, 1188 insertions(+), 144 deletions(-) create mode 100644 crates/compose/src/axis_frame.rs create mode 100644 crates/compose/src/fill_place.rs create mode 100644 crates/compose/src/mip_level.rs create mode 100644 crates/compose/src/tile_length.rs create mode 100644 crates/engine/tests/it/fill_patterns.rs create mode 100644 crates/engine/tests/it/fill_sampling.rs diff --git a/crates/compose/src/axis_frame.rs b/crates/compose/src/axis_frame.rs new file mode 100644 index 00000000..a4daa864 --- /dev/null +++ b/crates/compose/src/axis_frame.rs @@ -0,0 +1,158 @@ +//! The frame an axis planar projection projects from: moving one on the model places it as that frame, so its images land where they did + +use texturecraft_core::{Decal, Projection, Projector, Source}; +use texturecraft_geom::glam::{EulerRot, Mat3, Vec3}; + +use crate::frame_placement::culling_folds; +use crate::pattern::{DEPTH_FADE_START, frame_uv_from_corner, mesh_frame, nonzero_stretch, projector_stretch}; + +/// The placed planar projection that reads images exactly as axis planar `proj` does on a mesh within `bounds` (None for other projections, placed ones included, and while backface culling cannot keep its facing in a frame: see [`culling_folds`]) +pub fn placed_from_axis(proj: &Projection, bounds: (Vec3, Vec3)) -> Option { + let Projection::Planar { scale, axis, offset, uv, projector, placed: None } = proj else { return None }; + + if !culling_folds(projector) { + return None; + } + + let frame = axis_frame(*scale, *axis, Vec3::from(*offset), projector, bounds)?; + + // The turn and per-axis scale are now in the frame; culling and crop stay + let projector = Projector { rotation: [0.0; 3], scale: [1.0; 3], ..*projector }; + + // An axis planar turns its image round the top left, a frame round its centre + let uv = frame_uv_from_corner(uv); + Some(Projection::Planar { scale: *scale, axis: *axis, offset: *offset, uv, projector, placed: Some(frame) }) +} + +/// Whether placing an axis planar that reads `sources` would move a pattern: a procedural reads an axis planar's plane but a placed frame's uv, so such a planar keeps its axis +pub fn placing_moves_pattern<'a>(mut sources: impl Iterator) -> bool { + sources.any(|source| matches!(source, Source::Procedural { .. })) +} + +/// The frame of an axis planar projection: its image's 0..1 square on the plane through the mesh, turned and sized by `projector` +pub fn axis_frame(scale: f32, axis: u8, offset: Vec3, projector: &Projector, bounds: (Vec3, Vec3)) -> Option { + let (center, radius) = mesh_frame(bounds); + let [x, y, z] = projector.rotation.map(f32::to_radians); + let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x); + let stretch = projector_stretch(projector); + let scale = nonzero_stretch(scale); + + // Where the image's centre sits, then its across, up and out directions with the stretch along each + let origin = center + turn * (stretch * -offset / scale) * radius; + let (across, up, out) = match axis { + 0 => (Vec3::Z, Vec3::Y, Vec3::NEG_X), + 1 => (Vec3::X, Vec3::NEG_Z, Vec3::Y), + _ => (Vec3::X, Vec3::Y, Vec3::Z), + }; + let side = |direction: Vec3| 2.0 * radius * direction.abs().dot(stretch) / scale; + + // A negative stretch or scale turns that side over + let flip = |direction: Vec3| direction * side(direction).signum(); + let (across, up) = (flip(across), flip(up)); + let size = [side(across).abs(), side(up).abs()]; + let out = turn * across.cross(up).normalize_or(out); + + // Deep enough never to crop the mesh by depth: the fade starts at three quarters of it + let reach = (radius + (origin - center).length()) / DEPTH_FADE_START * DEPTH_SPARE; + let frame = Decal { + center: origin.to_array(), + normal: out.to_array(), + up: (turn * up).to_array(), + size, + rotation: 0.0, + offset: [0.0; 2], + depth: reach, + symmetry: None, + flip: [false; 2], + }; + (origin.is_finite() && size.iter().all(|side| side.is_finite() && *side > 0.0) && reach.is_finite()).then_some(frame) +} + +/// Extra reach past the farthest mesh point +const DEPTH_SPARE: f32 = 1.01; + +#[cfg(test)] +mod tests { + use texturecraft_core::{Backface, ShapeCrop, UvTransform}; + use texturecraft_geom::glam::Vec2; + + use super::*; + use crate::pattern::{Coords, image_samples}; + use crate::projector_cover::{framed_cover, projector_cover}; + + /// Points spread through the box `lo`..`hi` with varied normals + fn points(lo: Vec3, hi: Vec3) -> Vec<(Vec3, Vec3)> { + (0..64) + .map(|i| { + let spread = |salt: u32| ((i * 37 + salt * 11) % 64) as f32 / 63.0; + let position = lo + (hi - lo) * Vec3::new(spread(1), spread(2), spread(3)); + let normal = Vec3::new(spread(4) - 0.4, spread(5) - 0.3, spread(6) - 0.2).normalize_or(Vec3::Z); + (position, normal) + }) + .collect() + } + + #[test] + fn a_placed_axis_planar_reads_images_where_it_did() { + let (lo, hi) = (Vec3::new(-1.0, -0.5, -2.0), Vec3::new(3.0, 1.5, 0.5)); + let center = (lo + hi) * 0.5; + let radius = (hi - lo).length() * 0.5; + for axis in 0..3 { + for (rotation, stretch) in [([0.0; 3], [1.0; 3]), ([20.0, -35.0, 50.0], [1.5, 0.7, 2.0])] { + for crop in [ShapeCrop::ExtendsOutside, ShapeCrop::Cropped] { + let projector = Projector { rotation, scale: stretch, crop, ..Projector::default() }; + let uv = UvTransform { tiling: [2.0, 3.0], rotation: 30.0, offset: [0.1, -0.2] }; + let axis_planar = Projection::Planar { scale: 1.7, axis, offset: [0.3, -0.4, 0.2], uv, projector, placed: None }; + let placed = placed_from_axis(&axis_planar, (lo, hi)).expect("an axis planar has a frame"); + for (position, normal) in points(lo, hi) { + let coords = Coords { uv: Vec2::ZERO, pos: (position - center) / radius, nrm: normal }; + let (before, _) = image_samples(&axis_planar, &coords)[0]; + let (uv_after, cover) = framed_cover(&placed, position, normal, center).expect("a placed frame covers"); + let (after, _) = image_samples(&placed, &Coords { uv: uv_after, ..coords })[0]; + assert!(before.distance(after) < 1e-3, "axis {axis} {rotation:?}: {before} became {after}"); + assert!((projector_cover(&axis_planar, &coords) - cover).abs() < 1e-3, "axis {axis} {crop:?}: cover changed at {position}"); + } + } + } + } + } + + #[test] + fn a_placed_axis_planar_keeps_what_backface_culling_hides() { + let (lo, hi) = (Vec3::new(-1.0, -0.5, -2.0), Vec3::new(3.0, 1.5, 0.5)); + let center = (lo + hi) * 0.5; + let radius = (hi - lo).length() * 0.5; + let backface = Backface { on: true, angle: 60.0, hardness: 1.0 }; + + // Half way between across and out: a stretch across tilts the culled normal past the angle, a negative one turns it round + let halfway = (center, Vec3::new(1.0, 0.0, 1.0).normalize()); + + for stretch in [[4.0, 1.0, 1.0], [1.5, -1.5, 1.5], [1.7; 3]] { + let projector = Projector { scale: stretch, backface, ..Projector::default() }; + let axis_planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None }; + let Some(placed) = placed_from_axis(&axis_planar, (lo, hi)) else { + assert!(!culling_folds(&projector), "{stretch:?}: only a stretch culling cannot keep stays unplaced"); + continue; + }; + + for (position, normal) in points(lo, hi).into_iter().chain([halfway]) { + let coords = Coords { uv: Vec2::ZERO, pos: (position - center) / radius, nrm: normal }; + let (_, cover) = framed_cover(&placed, position, normal, center).expect("a placed frame covers"); + assert!((projector_cover(&axis_planar, &coords) - cover).abs() < 1e-3, "{stretch:?}: culling changed at {normal}"); + } + } + + let even = Projector { scale: [1.7; 3], backface, ..Projector::default() }; + let axis_planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: even, placed: None }; + assert!(placed_from_axis(&axis_planar, (lo, hi)).is_some(), "an even stretch is still placed"); + } + + #[test] + fn only_axis_planars_are_placed() { + let bounds = (Vec3::NEG_ONE, Vec3::ONE); + assert!(placed_from_axis(&Projection::default(), bounds).is_none()); + let frame = axis_frame(1.0, 2, Vec3::ZERO, &Projector::default(), bounds).expect("a frame"); + assert!(placed_from_axis(&Projection::decal(frame), bounds).is_none()); + assert!(axis_frame(f32::NAN, 2, Vec3::ZERO, &Projector::default(), bounds).is_none()); + } +} diff --git a/crates/compose/src/fill_place.rs b/crates/compose/src/fill_place.rs new file mode 100644 index 00000000..2bad25f0 --- /dev/null +++ b/crates/compose/src/fill_place.rs @@ -0,0 +1,12 @@ +use texturecraft_core::Fill; + +use crate::projector_depth::ProjectorDepth; + +/// A fill as a texel samples it: the fill, its projector's depth map when it culls by depth, and whether it covers every texel +#[derive(Clone, Copy)] +pub(crate) struct FillPlace<'f> { + pub fill: &'f Fill, + pub depth: Option<&'f ProjectorDepth>, + /// Decided once per tile, so a texel never works its coverage out + pub covers_all: bool, +} diff --git a/crates/compose/src/mip_level.rs b/crates/compose/src/mip_level.rs new file mode 100644 index 00000000..4af44d24 --- /dev/null +++ b/crates/compose/src/mip_level.rs @@ -0,0 +1,35 @@ +//! One halved copy of an image resource, read by high-quality bilinear filtering when an image is shrunk + +use crate::store::texel_of; + +/// One halved copy of an image (box-filtered; see `halve` for its edges) +#[derive(Clone, Debug, PartialEq)] +pub struct MipLevel { + pub width: u32, + pub height: u32, + pub rgba: Vec<[f32; 4]>, +} + +/// Share of each of the 2 × 2 texels in a halved texel +const TEXEL_SHARE: f32 = 0.25; + +impl MipLevel { + /// `rgba` halved: each texel averages the 2 × 2 texels it covers (a size of 1 wraps; an odd size above leaves out its last row or column) + pub(crate) fn halve(rgba: &[[f32; 4]], width: u32, height: u32) -> MipLevel { + let (w, h) = ((width / 2).max(1), (height / 2).max(1)); + let mut halved = Vec::with_capacity(w as usize * h as usize); + for y in 0..i64::from(h) { + for x in 0..i64::from(w) { + let mut sum = [0.0f32; 4]; + for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + let texel = texel_of(rgba, width, height, x * 2 + dx, y * 2 + dy, (true, true)); + for (total, value) in sum.iter_mut().zip(texel) { + *total += value * TEXEL_SHARE; + } + } + halved.push(sum); + } + } + MipLevel { width: w, height: h, rgba: halved } + } +} diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs index 5634b3a1..f94b1d8b 100644 --- a/crates/compose/src/pattern.rs +++ b/crates/compose/src/pattern.rs @@ -1,7 +1,7 @@ //! Procedural patterns and projections. -use texturecraft_core::{Decal, DecalFlip, Procedural, ProceduralKind, Projection}; -use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_core::{Decal, FULL_TURN_DEGREES, Procedural, ProceduralKind, Projection, Projector, UvTransform}; +use texturecraft_geom::glam::{EulerRot, Mat3, Vec2, Vec3}; use texturecraft_texel::noise; use crate::pattern_context::PatternContext; @@ -381,7 +381,7 @@ const TRIPLANAR_SKIP: f32 = 1.0 / 131_072.0; /// to change a 0..1 value scaled by `gain` afterwards weigh 0 (see [`TRIPLANAR_SKIP`]). fn triplanar_weights(nrm: Vec3, sharpness: f32, gain: f32) -> Vec3 { let weights = sharpen(nrm.abs(), sharpness); - let weights = weights / (weights.x + weights.y + weights.z).max(1e-6); + let weights = weights / (weights.x + weights.y + weights.z).max(MIN_WEIGHT_SUM); let skip_threshold = TRIPLANAR_SKIP / gain.max(1.0); let retained = Vec3::select(weights.cmplt(Vec3::splat(skip_threshold)), Vec3::ZERO, weights); @@ -394,6 +394,132 @@ fn shape(pattern: &Procedural, value: f32) -> f32 { if pattern.invert { 1.0 - adjusted } else { adjusted } } +/// `point` turned by `rotation` degrees, scaled by `tiling` and moved by `offset`, as UV transformations place it +fn place(point: Vec2, tiling: Vec2, rotation: f32, offset: Vec2) -> Vec2 { + placement(tiling, rotation, offset)(point) +} + +/// [`place`] with its turn's sine and cosine worked out once, for a projection that places several points +fn placement(tiling: Vec2, rotation: f32, offset: Vec2) -> impl Fn(Vec2) -> Vec2 { + let (sin, cos) = rotation.to_radians().sin_cos(); + move |point| Vec2::new(point.x * cos - point.y * sin, point.x * sin + point.y * cos) * tiling + offset +} + +/// `point` placed as a 3D projection's UV transformation `uv` lays its image +fn place_uv(point: Vec2, uv: &UvTransform) -> Vec2 { + uv_placement(uv)(point) +} + +/// [`place_uv`] worked out once for every point a projection places +fn uv_placement(uv: &UvTransform) -> impl Fn(Vec2) -> Vec2 { + placement(Vec2::from(uv.tiling), uv.rotation, Vec2::from(uv.offset)) +} + +/// 0..1 around a cylindrical projection's axis (`depth` over `across`), over an arc of `angle` degrees centred on the front +fn around(across: f32, depth: f32, angle: f32) -> f32 { + let turn = depth.atan2(across) / std::f32::consts::TAU + 0.5; + + // A full turn reads the turn untouched, as projects saved before the angle existed did, bit for bit + if angle == FULL_TURN_DEGREES { turn } else { (turn - 0.5) * FULL_TURN_DEGREES / angle.max(MIN_CYLINDER_ANGLE) + 0.5 } +} + +/// Narrowest arc in degrees a cylindrical projection wraps its image round, so a zero angle never divides by zero +pub const MIN_CYLINDER_ANGLE: f32 = *Projection::CYLINDER_ANGLE_RANGE.start(); + +/// How many pattern tiles a procedural lays round and down a spherical projection, so its cells stay near square +const SPHERE_PATTERN_TILES: Vec2 = Vec2::new(4.0, 2.0); + +/// How many pattern tiles a procedural lays round a cylindrical projection's axis +const CYLINDER_PATTERN_TILES: f32 = 4.0; + +/// Smallest sum of tri-planar blend weights, so a zero normal never divides by zero +const MIN_WEIGHT_SUM: f32 = 1e-6; + +/// Smallest frame side or depth (world units), so a flat frame never divides by zero +const MIN_FRAME_EXTENT: f32 = 1e-6; + +/// Where `coords` lies round a spherical projection: 0..1 round its pole axis and down from its top +fn spherical_uv(projector: &Projector, offset: &[f32; 3], coords: &Coords) -> Vec2 { + let direction = (projector_local(projector, coords).pos + Vec3::from(*offset)).try_normalize().unwrap_or(Vec3::Y); + let u = direction.z.atan2(direction.x) / std::f32::consts::TAU + 0.5; + let v = direction.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI; + Vec2::new(u, v) +} + +/// The axis index (0 X, 1 Y, 2 Z) a cylindrical projection's stored `axis` wraps round: any value but X or Z reads as Y +pub fn cylinder_axis_index(axis: u8) -> usize { + match axis { + 0 => 0, + 2 => 2, + _ => 1, + } +} + +/// Where `coords` lies for a cylindrical projection round `axis`: 0..1 round the axis over `angle` degrees, and its height along the axis +fn cylinder_coords(axis: u8, projector: &Projector, offset: &[f32; 3], angle: f32, coords: &Coords) -> (f32, f32) { + let point = projector_local(projector, coords).pos + Vec3::from(*offset); + let (across, height, depth) = match cylinder_axis_index(axis) { + 0 => (point.y, point.x, point.z), + 2 => (point.x, point.z, point.y), + _ => (point.x, point.y, point.z), + }; + (around(across, depth, angle), height) +} + +/// Smallest mesh radius projections measure in, so a flat or empty mesh never divides by zero +const MIN_MESH_RADIUS: f32 = 1e-4; + +/// Nearest to zero a projection scale or stretch gets, so it never divides by zero +const MIN_STRETCH: f32 = 1e-6; + +/// The mesh's centre and its radius (half the diagonal) from its bounds +pub fn mesh_frame((lo, hi): (Vec3, Vec3)) -> (Vec3, f32) { + ((lo + hi) * 0.5, ((hi - lo).length() * 0.5).max(MIN_MESH_RADIUS)) +} + +/// `value` kept at least [`MIN_STRETCH`] from zero, on its own side +pub fn nonzero_stretch(value: f32) -> f32 { + value.signum() * value.abs().max(MIN_STRETCH) +} + +/// A projector's per-axis scale with no axis at zero, each keeping its sign +pub fn projector_stretch(projector: &Projector) -> Vec3 { + Vec3::from(projector.scale).map(nonzero_stretch) +} + +/// The middle of a frame's 0..1 texture coordinates: a frame's image turns round it +pub const FRAME_UV_CENTER: Vec2 = Vec2::splat(0.5); + +/// `point` (0..1 across and down a frame) placed as `uv` lays a frame's image: turned round the frame's centre, then tiled and moved from its top left +pub fn place_frame_uv(point: Vec2, uv: &UvTransform) -> Vec2 { + // An unplaced image reads `point` itself, bit for bit as decals saved before image placement did + if *uv == UvTransform::default() { + return point; + } + + let tiling = Vec2::from(uv.tiling); + place(point - FRAME_UV_CENTER, tiling, uv.rotation, Vec2::from(uv.offset)) + FRAME_UV_CENTER * tiling +} + +/// The image placement a frame needs to lay images exactly as `uv` does from the top left (a frame turns its image round its centre) +pub fn frame_uv_from_corner(uv: &UvTransform) -> UvTransform { + let offset = place_uv(FRAME_UV_CENTER, uv) - FRAME_UV_CENTER * Vec2::from(uv.tiling); + UvTransform { offset: offset.to_array(), ..*uv } +} + +/// `coords` inside a projector turned and scaled by `projector`; the default projector returns `coords` unchanged +pub fn projector_local(projector: &Projector, coords: &Coords) -> Coords { + if !projector.turns() { + return *coords; + } + + let [x, y, z] = projector.rotation.map(f32::to_radians); + let to_local = Mat3::from_euler(EulerRot::ZYX, z, y, x).transpose(); + let scale = projector_stretch(projector); + let nrm = (to_local * coords.nrm * scale).try_normalize().unwrap_or(coords.nrm); + Coords { pos: to_local * coords.pos / scale, nrm, ..*coords } +} + /// Evaluate a procedural through a projection, at full resolution and without images pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords) -> f32 { procedural_in(pattern, projection, coords, &PatternContext::default()) @@ -402,51 +528,41 @@ pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords /// Evaluate a procedural through a projection with what `context` gives it: its resolution and the images it reads pub fn procedural_in(pattern: &Procedural, projection: &Projection, coords: &Coords, context: &PatternContext) -> f32 { let pattern_scale = pattern.scale.max(MIN_PATTERN_SCALE); - let sample = |point: Vec3| plane_value(pattern, point, context); - let value = match projection { - Projection::Uv { scale, rotation, offset } => { - let (sn, cs) = rotation.to_radians().sin_cos(); - let uv = Vec2::new(coords.uv.x * cs - coords.uv.y * sn, coords.uv.x * sn + coords.uv.y * cs) * Vec2::from(*scale) + Vec2::from(*offset); - // Evaluate two-dimensional patterns on a slice of the volume - sample((uv * pattern_scale).extend(0.0)) - } - Projection::Triplanar { scale, sharpness, offset } => { - let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset); + // Evaluate two-dimensional patterns on a slice of the volume + let flat = |point: Vec2| plane_value(pattern, point.extend(0.0), context); + let value = match projection { + Projection::UvTile => flat((coords.uv - coords.uv.floor()) * pattern_scale), + Projection::Uv { scale, rotation, offset } => flat(place(coords.uv, Vec2::from(*scale), *rotation, Vec2::from(*offset)) * pattern_scale), + Projection::Triplanar { scale, sharpness, offset, uv, projector } => { + let coords = &projector_local(projector, coords); + let point = coords.pos * *scale * pattern_scale + Vec3::from(*offset); + let place_plane = uv_placement(uv); // Shape scales the blend by the contrast - let w = triplanar_weights(coords.nrm, *sharpness, pattern.contrast); - let planes = [(w.x, Vec3::new(p.z, p.y, 0.0)), (w.y, Vec3::new(p.x, p.z, 0.0)), (w.z, Vec3::new(p.x, p.y, 0.0))]; - planes.into_iter().filter(|(w, _)| *w > 0.0).map(|(w, q)| sample(q) * w).sum() + let weights = triplanar_weights(coords.nrm, *sharpness, pattern.contrast); + let planes = [(weights.x, Vec2::new(point.z, point.y)), (weights.y, Vec2::new(point.x, point.z)), (weights.z, Vec2::new(point.x, point.y))]; + planes.into_iter().filter(|(weight, _)| *weight > 0.0).map(|(weight, plane)| flat(place_plane(plane)) * weight).sum() } - Projection::Planar { scale, axis, offset } => { - let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset); - let q = match axis { - 0 => Vec3::new(p.z, p.y, 0.0), - 1 => Vec3::new(p.x, p.z, 0.0), - _ => Vec3::new(p.x, p.y, 0.0), + // The coordinates are already in the placed or warped frame (see [`placed_uv`] and [`crate::warp::warp_uv`]) + Projection::Planar { uv, placed: Some(_), .. } | Projection::Warp { uv, .. } => flat(place_frame_uv(coords.uv, uv) * pattern_scale), + Projection::Planar { scale, axis, offset, uv, projector, .. } => { + let point = projector_local(projector, coords).pos * *scale * pattern_scale + Vec3::from(*offset); + let plane = match axis { + 0 => Vec2::new(point.z, point.y), + 1 => Vec2::new(point.x, point.z), + _ => Vec2::new(point.x, point.y), }; - sample(q) + flat(place_uv(plane, uv)) } - Projection::Spherical { scale } => { - let d = coords.pos.try_normalize().unwrap_or(Vec3::Y); - let u = d.z.atan2(d.x) / std::f32::consts::TAU + 0.5; - let v = d.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI; - sample(Vec3::new(u * 4.0, v * 2.0, 0.0) * *scale * pattern_scale) + Projection::Spherical { scale, uv, offset, projector } => { + let sphere = spherical_uv(projector, offset, coords); + flat(place_uv(sphere * SPHERE_PATTERN_TILES * *scale * pattern_scale, uv)) } - Projection::Cylindrical { scale, axis } => { - let p = coords.pos; - let (a, h, b) = match axis { - 0 => (p.y, p.x, p.z), - 2 => (p.x, p.z, p.y), - _ => (p.x, p.y, p.z), - }; - let u = b.atan2(a) / std::f32::consts::TAU + 0.5; - sample(Vec3::new(u * 4.0, h, 0.0) * *scale * pattern_scale) + Projection::Cylindrical { scale, axis, uv, offset, projector, angle } => { + let (around_axis, height) = cylinder_coords(*axis, projector, offset, *angle, coords); + flat(place_uv(Vec2::new(around_axis * CYLINDER_PATTERN_TILES, height) * *scale * pattern_scale, uv)) } - - // The decal already supplied coordinates in its local frame - Projection::Decal(_) => sample((coords.uv * pattern_scale).extend(0.0)), }; shape(pattern, value) @@ -476,7 +592,7 @@ fn plane_value(pattern: &Procedural, point: Vec3, context: &PatternContext) -> f let base = grid.floor(); let fraction = grid - base; - let at = |dx: f32, dy: f32| pattern_value(pattern, ((base + Vec2::new(dx, dy) + 0.5) / cells).extend(point.z), context); + let at = |across: f32, down: f32| pattern_value(pattern, ((base + Vec2::new(across, down) + 0.5) / cells).extend(point.z), context); let top_left = at(0.0, 0.0); let bottom_left = at(0.0, 1.0); let top = top_left + (at(1.0, 0.0) - top_left) * fraction.x; @@ -497,45 +613,37 @@ fn pattern_value(pattern: &Procedural, point: Vec3, context: &PatternContext) -> pub fn image_samples(projection: &Projection, coords: &Coords) -> [(Vec2, f32); 3] { let one = |uv: Vec2| [(uv, 1.0), (Vec2::ZERO, 0.0), (Vec2::ZERO, 0.0)]; match projection { - Projection::Uv { scale, rotation, offset } => { - let (sn, cs) = rotation.to_radians().sin_cos(); - let uv = Vec2::new(coords.uv.x * cs - coords.uv.y * sn, coords.uv.x * sn + coords.uv.y * cs) * Vec2::from(*scale) + Vec2::from(*offset); - one(uv) - } - Projection::Triplanar { scale, sharpness, offset } => { - let p = coords.pos * *scale + Vec3::from(*offset); + Projection::UvTile => one(coords.uv - coords.uv.floor()), + Projection::Uv { scale, rotation, offset } => one(place(coords.uv, Vec2::from(*scale), *rotation, Vec2::from(*offset))), + Projection::Triplanar { scale, sharpness, offset, uv, projector } => { + let coords = &projector_local(projector, coords); + let point = coords.pos * *scale + Vec3::from(*offset); + let place_plane = uv_placement(uv); // Float images can exceed 1, so even a tiny plane weight can carry visible detail let weights = coords.nrm.abs().powf(sharpness.max(1.0)); - let weights = weights / (weights.x + weights.y + weights.z).max(1e-6); - [(Vec2::new(p.z, -p.y), weights.x), (Vec2::new(p.x, p.z), weights.y), (Vec2::new(p.x, -p.y), weights.z)] + let weights = weights / (weights.x + weights.y + weights.z).max(MIN_WEIGHT_SUM); + [ + (place_plane(Vec2::new(point.z, -point.y)), weights.x), + (place_plane(Vec2::new(point.x, point.z)), weights.y), + (place_plane(Vec2::new(point.x, -point.y)), weights.z), + ] } - Projection::Planar { scale, axis, offset } => { - let p = coords.pos * *scale + Vec3::from(*offset); - let q = match axis { - 0 => Vec2::new(p.z, -p.y), - 1 => Vec2::new(p.x, p.z), - _ => Vec2::new(p.x, -p.y), + Projection::Planar { uv, placed: Some(_), .. } | Projection::Warp { uv, .. } => one(place_frame_uv(coords.uv, uv)), + Projection::Planar { scale, axis, offset, uv, projector, .. } => { + let point = projector_local(projector, coords).pos * *scale + Vec3::from(*offset); + let plane = match axis { + 0 => Vec2::new(point.z, -point.y), + 1 => Vec2::new(point.x, point.z), + _ => Vec2::new(point.x, -point.y), }; - one(q * 0.5 + Vec2::splat(0.5)) + one(place_uv(plane * 0.5 + Vec2::splat(0.5), uv)) } - Projection::Spherical { scale } => { - let d = coords.pos.try_normalize().unwrap_or(Vec3::Y); - let u = d.z.atan2(d.x) / std::f32::consts::TAU + 0.5; - let v = d.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI; - one(Vec2::new(u, v) * *scale) + Projection::Spherical { scale, uv, offset, projector } => one(place_uv(spherical_uv(projector, offset, coords) * *scale, uv)), + Projection::Cylindrical { scale, axis, uv, offset, projector, angle } => { + let (around_axis, height) = cylinder_coords(*axis, projector, offset, *angle, coords); + one(place_uv(Vec2::new(around_axis, 0.5 - height * 0.5) * *scale, uv)) } - Projection::Cylindrical { scale, axis } => { - let p = coords.pos; - let (a, h, b) = match axis { - 0 => (p.y, p.x, p.z), - 2 => (p.x, p.z, p.y), - _ => (p.x, p.y, p.z), - }; - let u = b.atan2(a) / std::f32::consts::TAU + 0.5; - one(Vec2::new(u, 0.5 - h * 0.5) * *scale) - } - Projection::Decal(_) => one(coords.uv), } } @@ -561,50 +669,55 @@ pub fn decal_corners(d: &Decal) -> Option<[Vec3; 4]> { Some([o - r * hw + u * hh, o + r * hw + u * hh, o + r * hw - u * hh, o - r * hw - u * hh]) } -/// Where world point `p` with surface normal `nrm` falls in the decal: texture coordinates -/// (v down) and how much the decal covers it, None outside the frame, behind it, beyond its -/// depth or on faces turned away. Coverage fades on grazing faces and near the depth limit. -pub fn decal_uv(d: &Decal, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> { - let (o, r, u, n) = decal_axes(d)?; - let facing = nrm.dot(n); - let q = p - o; - let (lx, ly, lz) = (q.dot(r) / d.size[0].max(1e-6), q.dot(u) / d.size[1].max(1e-6), q.dot(n).abs()); - let depth = d.depth.max(1e-6); - if facing <= 0.0 || lx.abs() > 0.5 || ly.abs() > 0.5 || lz > depth || !(lx.is_finite() && ly.is_finite()) { - return None; +/// World point `point` in frame `frame` turned and scaled by `projector`: across and up in frame sizes, out along its normal in world units +pub fn frame_local(frame: &Decal, projector: &Projector, point: Vec3) -> Option { + let (origin, right, up, normal) = decal_axes(frame)?; + let from_origin = point - origin; + let mut local = Vec3::new(from_origin.dot(right), from_origin.dot(up), from_origin.dot(normal)); + if projector.turns() { + local = projector_local(projector, &Coords { uv: Vec2::ZERO, pos: local, nrm: Vec3::Z }).pos; } - let w = smoothstep(0.0, 0.3, facing) * (1.0 - smoothstep(0.75 * depth, depth, lz)); - Some((flip_uv(Vec2::new(lx + 0.5, 0.5 - ly), d.flip), w)) + let local = Vec3::new(local.x / frame.size[0].max(MIN_FRAME_EXTENT), local.y / frame.size[1].max(MIN_FRAME_EXTENT), local.z); + local.is_finite().then_some(local) } -/// `uv` with the image mirrored left to right (`flip[0]`) and/or top to bottom (`flip[1]`) inside the frame. -fn flip_uv(uv: Vec2, flip: [bool; 2]) -> Vec2 { - Vec2::new(if flip[0] { 1.0 - uv.x } else { uv.x }, if flip[1] { 1.0 - uv.y } else { uv.y }) -} - -/// [`decal_uv`] for a decal with a mirrored copy: whichever of the decal and its copy covers the -/// point more. The copy is the decal reflected through the plane across `center` (the mesh -/// center), so a point is looked up as its reflection (the plane is `offset` away from the center) and the image flipped as asked. -pub fn decal_uv_symmetric(d: &Decal, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> { - let direct = decal_uv(d, p, nrm); - let Some(symmetry) = d.symmetry else { return direct }; - let axis = usize::from(symmetry.axis.min(2)); - let (mut mirrored_position, mut mirrored_normal) = (p, nrm); - mirrored_position[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis]; - mirrored_normal[axis] = -nrm[axis]; - let mirrored = decal_uv(d, mirrored_position, mirrored_normal).map(|(uv, w)| { - let uv = match symmetry.flip { - DecalFlip::None => uv, - DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y), - DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y), - }; - (uv, w) - }); - match (direct, mirrored) { - (Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }), - (a, b) => a.or(b), +/// How squarely a surface with normal `nrm` faces frame `frame` turned by `projector` (the cosine of the turn) +pub fn frame_facing(frame: &Decal, projector: &Projector, nrm: Vec3) -> f32 { + let Some((_, right, up, normal)) = decal_axes(frame) else { return 0.0 }; + if !projector.turns() { + return nrm.dot(normal); } + + let turned = Vec3::new(nrm.dot(right), nrm.dot(up), nrm.dot(normal)); + projector_local(projector, &Coords { uv: Vec2::ZERO, pos: Vec3::ZERO, nrm: turned }).nrm.z +} + +/// Texture coordinates (v down) of a point at `local` in its frame (see [`frame_local`]) +pub fn placed_uv(local: Vec3) -> Vec2 { + Vec2::new(local.x + 0.5, 0.5 - local.y) +} + +/// How much frame `frame` covers a point at `local` when cropped to its shape: 0 outside the frame or past its depth, fading near the depth +pub fn frame_crop(frame: &Decal, local: Vec3) -> f32 { + if local.x.abs() > 0.5 || local.y.abs() > 0.5 { + return 0.0; + } + + depth_fade(local.z, frame.depth) +} + +/// Where a frame's depth fade starts, as a share of its depth +pub const DEPTH_FADE_START: f32 = 0.75; + +/// How much a frame reaching `depth` in front of and behind it covers a point `z` out from it: 0 past the depth, fading near it +pub fn depth_fade(z: f32, depth: f32) -> f32 { + let (distance, depth) = (z.abs(), depth.max(MIN_FRAME_EXTENT)); + if distance > depth { + return 0.0; + } + + 1.0 - smoothstep(DEPTH_FADE_START * depth, depth, distance) } /// World-space noise used by generators (seamless across UV islands). @@ -642,15 +755,98 @@ mod tests { assert!((at(0.25, &exact) - blended).abs() > 1e-3, "the exact pattern is not the blend, so the coarse read shows"); } + /// A stored cylinder axis past Z (only a hand-edited project holds one) wraps round Y + #[test] + fn a_cylinder_axis_past_z_reads_as_y() { + assert_eq!([0, 1, 2, 3, u8::MAX].map(cylinder_axis_index), [0, 1, 2, 1, 1]); + } + + /// A decal saved before image placement reads its frame coordinates bit for bit as it did: its image at them, its procedural at them times the pattern scale + #[test] + fn an_unplaced_decal_reads_its_frame_coordinates_bit_for_bit() { + let frame = Decal { + center: [0.0; 3], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [1.0; 2], + rotation: 0.0, + offset: [0.0; 2], + depth: 0.5, + symmetry: None, + flip: [false; 2], + }; + let decal = Projection::decal(frame); + let pattern = Procedural { scale: 3.0, ..Procedural::new(ProceduralKind::Gradient) }; + for across in 0..=1000 { + for down in [0.0, 0.1, 0.37, 1.0] { + let uv = Vec2::new(across as f32 / 1000.0, down); + let coords = Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Z }; + assert_eq!(image_samples(&decal, &coords)[0].0, uv, "image at {uv}"); + + let expected = shape(&pattern, raw(pattern.kind, (uv * pattern.scale).extend(0.0), pattern.seed)); + assert_eq!(procedural(&pattern, &decal, &coords).to_bits(), expected.to_bits(), "procedural at {uv}"); + } + } + } + + /// A frame's image turns round the frame's centre: the centre reads the same texel at any Rotation, and an unturned image reads exactly as before for any Tiling and Offset + #[test] + fn a_frame_image_turns_round_the_frame_centre() { + let frame = Decal { + center: [0.0; 3], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [1.0; 2], + rotation: 0.0, + offset: [0.0; 2], + depth: 0.5, + symmetry: None, + flip: [false; 2], + }; + let at = |uv: Vec2| Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Z }; + let sample = |rotation: f32, tiling: [f32; 2], offset: [f32; 2], uv: Vec2| { + image_samples( + &Projection::Warp { + frame, + corners: Projection::FRAME_CORNERS, + depth: 0.1, + uv: UvTransform { tiling, rotation, offset }, + projector: Projector::default(), + }, + &at(uv), + )[0] + .0 + }; + for rotation in [37.0, 90.0, 180.0] { + let center = sample(rotation, [1.0; 2], [0.0; 2], FRAME_UV_CENTER); + assert!((center - FRAME_UV_CENTER).length() < 1e-5, "{rotation}°: the centre stays put, not swung round the top left: {center}"); + } + let corner = sample(90.0, [1.0; 2], [0.0; 2], Vec2::ZERO); + assert!((corner - Vec2::new(1.0, 0.0)).length() < 1e-5, "a quarter turn brings the top left to the top right: {corner}"); + let placed = Projection::Planar { + scale: 1.0, + axis: 2, + offset: [0.0; 3], + uv: UvTransform { rotation: 90.0, ..UvTransform::default() }, + projector: Projector::default(), + placed: Some(frame), + }; + assert!((image_samples(&placed, &at(FRAME_UV_CENTER))[0].0 - FRAME_UV_CENTER).length() < 1e-5, "a placed planar frame turns the same way"); + for (tiling, offset, uv) in [([2.0, 3.0], [0.25, -0.5], Vec2::new(0.1, 0.8)), ([1.0, 1.0], [0.0, 0.0], Vec2::new(0.7, 0.2))] { + let before = uv * Vec2::from(tiling) + Vec2::from(offset); + assert!((sample(0.0, tiling, offset, uv) - before).length() < 1e-6, "unturned: as before"); + } + } + #[test] fn every_pattern_and_projection_stays_in_range() { let projections = [ Projection::default(), - Projection::Triplanar { scale: 1.0, sharpness: 4.0, offset: [0.0; 3] }, - Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3] }, - Projection::Spherical { scale: 1.0 }, - Projection::Cylindrical { scale: 1.0, axis: 1 }, - Projection::Decal(Decal { + Projection::Triplanar { scale: 1.0, sharpness: 4.0, offset: [0.0; 3], uv: Default::default(), projector: Default::default() }, + Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: Default::default(), projector: Default::default(), placed: None }, + Projection::Spherical { scale: 1.0, uv: Default::default(), offset: [0.0; 3], projector: Default::default() }, + Projection::Cylindrical { scale: 1.0, axis: 1, uv: Default::default(), offset: [0.0; 3], projector: Default::default(), angle: FULL_TURN_DEGREES }, + Projection::decal(Decal { center: [0.0; 3], normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], @@ -662,20 +858,17 @@ mod tests { flip: [false; 2], }), ]; - for kind in ProceduralKind::ALL { let pattern = Procedural::new(kind); for projection in &projections { - for i in 0..50 { - let t = i as f32 * 0.13; + for index in 0..50 { + let position = index as f32 * 0.13; let coords = Coords { - uv: Vec2::new(t.fract(), (t * 0.7).fract()), - pos: Vec3::new(t.sin(), t.cos(), t * 0.1), + uv: Vec2::new(position.fract(), (position * 0.7).fract()), + pos: Vec3::new(position.sin(), position.cos(), position * 0.1), nrm: Vec3::new(0.3, 0.9, 0.1).normalize(), }; - let value = procedural(&pattern, projection, &coords); - assert!((0.0..=1.0).contains(&value), "{kind:?} {projection:?} {value}"); } } @@ -702,7 +895,8 @@ mod tests { for contrast in [1.0, 4.0, 16.0] { let pattern = Procedural { contrast, ..Procedural::new(kind) }; for sharpness in [1.0, 4.0, 8.0, 16.0] { - let projection = Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3] }; + let projection = + Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default() }; for index in 0..400 { // Cover axis aligned and oblique normals at varied positions let position = index as f32 / 400.0; @@ -731,9 +925,9 @@ mod tests { #[test] fn triplanar_image_sampling_preserves_bright_float_pixels() { - let image = crate::ImageRes { width: 2, height: 2, rgba: vec![[0.0; 4], [0.0; 4], [0.0; 4], [100_000.0; 4]], srgb: false }; + let image = crate::ImageRes::new(2, 2, vec![[0.0; 4], [0.0; 4], [0.0; 4], [100_000.0; 4]], false); let coords = Coords { uv: Vec2::ZERO, pos: Vec3::new(0.25, 0.25, 0.75), nrm: Vec3::new(0.2, 1.0, 0.1).normalize() }; - let projection = Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] }; + let projection = Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default() }; let weights = coords.nrm.abs().powf(8.0); let expected = 100_000.0 * weights.x / (weights.x + weights.y + weights.z); @@ -761,6 +955,12 @@ mod tests { } } + /// Where frame `frame`'s planar projection lands at `point` facing `nrm`, None where it does not cover + fn decal_uv(frame: &Decal, point: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> { + let Projection::Planar { projector, .. } = Projection::decal(*frame) else { return None }; + crate::projector_cover::placed_cover(frame, &projector, point, nrm).filter(|(_, cover)| *cover > 0.0) + } + #[test] fn decals_cover_their_frame_facing_them() { let d = Decal { diff --git a/crates/compose/src/tile_length.rs b/crates/compose/src/tile_length.rs new file mode 100644 index 00000000..c08e668f --- /dev/null +++ b/crates/compose/src/tile_length.rs @@ -0,0 +1,155 @@ +//! How long one repeat of a fill's tile is on the mesh (mesh units): Physical size reads it from the tiling and writes tiling back + +use std::f32::consts::TAU; + +use texturecraft_core::{FULL_TURN_DEGREES, Projection}; + +use crate::pattern::{MIN_CYLINDER_ANGLE, cylinder_axis_index, projector_stretch}; + +/// The mesh's size as the projections see it: the bounds radius (3D projections) and the mesh units one UV unit covers (UV) +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MeshSize { + pub radius: f32, + pub uv_density: f32, +} + +/// Mesh units one tile covers across and down at a tiling of 1, the projector's stretch included; None without a physical size (per UV tile, spherical, or a stretch uneven across the planes a tile wraps round) +fn unit_tile(projection: &Projection, size: MeshSize) -> Option<[f32; 2]> { + let radius = size.radius; + match projection { + Projection::Uv { .. } => Some([size.uv_density; 2]), + Projection::Triplanar { scale, projector, .. } => { + // Every plane repeats in the one length only while the stretch is even + let stretch = projector_stretch(projector).abs(); + let even = stretch.x == stretch.y && stretch.y == stretch.z; + even.then_some([radius * stretch.x / scale; 2]) + } + Projection::Planar { placed: Some(frame), projector, .. } | Projection::Warp { frame, projector, .. } => { + let stretch = projector_stretch(projector).abs(); + Some([frame.size[0] * stretch.x, frame.size[1] * stretch.y]) + } + Projection::Planar { scale, axis, projector, .. } => { + let stretch = projector_stretch(projector).abs(); + let [across, down] = match axis { + 0 => [stretch.z, stretch.y], + 1 => [stretch.x, stretch.z], + _ => [stretch.x, stretch.y], + }; + Some([2.0 * radius * across / scale, 2.0 * radius * down / scale]) + } + Projection::Cylindrical { scale, axis, angle, projector, .. } => { + let stretch = projector_stretch(projector).abs(); + let ([across, depth], height) = match cylinder_axis_index(*axis) { + 0 => ([stretch.y, stretch.z], stretch.x), + 2 => ([stretch.x, stretch.y], stretch.z), + _ => ([stretch.x, stretch.z], stretch.y), + }; + + // Round an uneven cross-section the turn is no fixed length of surface + if across != depth { + return None; + } + + let around = TAU * radius * across * (angle.max(MIN_CYLINDER_ANGLE) / FULL_TURN_DEGREES); + Some([around / scale, 2.0 * radius * height / scale]) + } + Projection::UvTile | Projection::Spherical { .. } => None, + } +} + +/// The tiling a physical size reads and writes: UV's own tiling, a 3D projection's UV tiling +fn tiling(projection: &Projection) -> Option<[f32; 2]> { + match projection { + Projection::Uv { scale, .. } => Some(*scale), + Projection::Triplanar { uv, .. } | Projection::Planar { uv, .. } | Projection::Cylindrical { uv, .. } | Projection::Warp { uv, .. } => Some(uv.tiling), + Projection::UvTile | Projection::Spherical { .. } => None, + } +} + +/// Mesh units one repeat of the tile covers across and down +pub fn tile_length(projection: &Projection, size: MeshSize) -> Option<[f32; 2]> { + let unit = unit_tile(projection, size)?; + let tiling = tiling(projection)?; + Some([unit[0] / tiling[0].max(f32::EPSILON), unit[1] / tiling[1].max(f32::EPSILON)]) +} + +/// The tiling that makes one repeat `length` mesh units long across and down +pub fn tiling_for_length(projection: &Projection, size: MeshSize, length: [f32; 2]) -> Option<[f32; 2]> { + let unit = unit_tile(projection, size)?; + Some([unit[0] / length[0].max(f32::EPSILON), unit[1] / length[1].max(f32::EPSILON)]) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::pattern::{Coords, image_samples}; + use texturecraft_core::{Projector, UvTransform}; + use texturecraft_geom::glam::{Vec2, Vec3}; + + const SIZE: MeshSize = MeshSize { radius: 2.0, uv_density: 3.0 }; + + #[test] + fn uv_tile_length_is_the_uv_density_over_the_tiling() { + let uv = Projection::Uv { scale: [2.0, 4.0], rotation: 0.0, offset: [0.0; 2] }; + assert_eq!(tile_length(&uv, SIZE), Some([1.5, 0.75])); + } + + #[test] + fn a_length_read_back_gives_the_same_tiling() { + let uv = UvTransform { tiling: [3.0, 1.5], ..UvTransform::default() }; + for projection in [ + Projection::Uv { scale: [3.0, 1.5], rotation: 0.0, offset: [0.0; 2] }, + Projection::Triplanar { scale: 1.5, sharpness: Projection::TRIPLANAR_SHARPNESS, offset: [0.0; 3], uv, projector: Default::default() }, + Projection::Planar { scale: 0.5, axis: 2, offset: [0.0; 3], uv, projector: Default::default(), placed: None }, + Projection::Cylindrical { scale: 2.0, axis: 1, uv, offset: [0.0; 3], projector: Default::default(), angle: 360.0 }, + ] { + let length = tile_length(&projection, SIZE).unwrap(); + let tiling = tiling_for_length(&projection, SIZE, length).unwrap(); + assert!((tiling[0] - 3.0).abs() < 1e-5 && (tiling[1] - 1.5).abs() < 1e-5, "{projection:?}: {tiling:?}"); + } + } + + #[test] + fn a_written_length_is_the_repeat_on_the_mesh_through_a_stretched_projector() { + let projector = Projector { scale: [2.0, 1.0, 1.0], ..Projector::default() }; + let axis_planar = |uv| Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv, projector, placed: None }; + let length = 2.0; + + let tiling = tiling_for_length(&axis_planar(UvTransform::default()), SIZE, [length; 2]).unwrap(); + let planar = axis_planar(UvTransform { tiling, ..UvTransform::default() }); + let at = |x: f32, y: f32| image_samples(&planar, &Coords { uv: Vec2::ZERO, pos: Vec3::new(x, y, 0.0) / SIZE.radius, nrm: Vec3::Z })[0].0; + let across = at(0.3 + length, 0.1) - at(0.3, 0.1); + let down = at(0.3, 0.1 + length) - at(0.3, 0.1); + + assert_eq!(tile_length(&axis_planar(UvTransform::default()), SIZE), Some([8.0, 4.0]), "the stretch doubles the repeat across"); + assert!((across.x.abs() - 1.0).abs() < 1e-4 && across.y.abs() < 1e-4, "one length across is one tile: {across}"); + assert!(down.x.abs() < 1e-4 && (down.y.abs() - 1.0).abs() < 1e-4, "one length down is one tile: {down}"); + } + + #[test] + fn a_stretch_uneven_round_the_planes_has_no_physical_size() { + let projector = Projector { scale: [2.0, 1.0, 1.0], ..Projector::default() }; + let uv = UvTransform::default(); + + let triplanar = Projection::Triplanar { scale: 1.0, sharpness: Projection::TRIPLANAR_SHARPNESS, offset: [0.0; 3], uv, projector }; + let cylinder = Projection::Cylindrical { scale: 1.0, axis: 1, uv, offset: [0.0; 3], projector, angle: 360.0 }; + let along_axis = Projection::Cylindrical { scale: 1.0, axis: 0, uv, offset: [0.0; 3], projector, angle: 360.0 }; + + assert_eq!(tile_length(&triplanar, SIZE), None); + assert_eq!(tile_length(&cylinder, SIZE), None); + assert_eq!(tile_length(&along_axis, SIZE).map(|[_, down]| down), Some(8.0), "a stretch along the axis lengthens the repeat down it"); + } + + #[test] + fn a_cylinder_of_no_angle_still_has_a_length() { + let flat = Projection::Cylindrical { scale: 1.0, axis: 1, uv: UvTransform::default(), offset: [0.0; 3], projector: Default::default(), angle: 0.0 }; + let length = tile_length(&flat, SIZE).unwrap(); + assert!(length[0] > 0.0, "{length:?}"); + assert!(tiling_for_length(&flat, SIZE, length).unwrap()[0] > 0.0, "a written-back tiling is never 0"); + } + + #[test] + fn spherical_has_no_physical_size() { + assert_eq!(tile_length(&Projection::Spherical { scale: 1.0, uv: UvTransform::default(), offset: [0.0; 3], projector: Default::default() }, SIZE), None); + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index ebd2ae0d..b9677515 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -108,6 +108,10 @@ impl HeightMask { } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[expect( + clippy::large_enum_variant, + reason = "a fill holds its projection inline; boxing it would cost every fill read an indirection to save a few hundred bytes per paint layer or folder" +)] pub enum LayerKind { /// Painted pixels, stored per channel by the engine under the layer id. Paint, @@ -178,20 +182,90 @@ impl Layer { pub enum Projection { /// Texture coordinates of the mesh. Uv { scale: [f32; 2], rotation: f32, offset: [f32; 2] }, + /// The source stretched once over each UV tile (0..1 in every tile) + UvTile, /// World-space box projection blended by the normal. - Triplanar { scale: f32, sharpness: f32, offset: [f32; 3] }, - /// World-space planar projection along an axis (0 = X, 1 = Y, 2 = Z). - Planar { scale: f32, axis: u8, offset: [f32; 3] }, - /// Spherical projection around the mesh center. - Spherical { scale: f32 }, - /// Cylindrical projection around an axis. - Cylindrical { scale: f32, axis: u8 }, - /// A geometry decal: the image projected from a frame placed on the surface (outside the - /// frame, behind it or beyond its depth the fill does not cover). - Decal(Decal), + Triplanar { + scale: f32, + sharpness: f32, + offset: [f32; 3], + #[serde(default, skip_serializing_if = "UvTransform::is_default")] + uv: UvTransform, + #[serde(default, skip_serializing_if = "Projector::is_default")] + projector: Projector, + }, + /// World-space planar projection along an axis (0 = X, 1 = Y, 2 = Z), or from a frame placed on the surface + Planar { + scale: f32, + axis: u8, + offset: [f32; 3], + #[serde(default, skip_serializing_if = "UvTransform::is_default")] + uv: UvTransform, + #[serde(default, skip_serializing_if = "Projector::is_default")] + projector: Projector, + /// The frame it projects from when placed on the surface (scale, axis and offset then unused) + #[serde(default, skip_serializing_if = "Option::is_none")] + placed: Option, + }, + /// Spherical projection around the mesh center + Spherical { + scale: f32, + #[serde(default, skip_serializing_if = "UvTransform::is_default")] + uv: UvTransform, + #[serde(default, skip_serializing_if = "is_zero_offset")] + offset: [f32; 3], + #[serde(default, skip_serializing_if = "Projector::is_default")] + projector: Projector, + }, + /// Cylindrical projection around an axis + Cylindrical { + scale: f32, + axis: u8, + #[serde(default, skip_serializing_if = "UvTransform::is_default")] + uv: UvTransform, + #[serde(default, skip_serializing_if = "is_zero_offset")] + offset: [f32; 3], + #[serde(default, skip_serializing_if = "Projector::is_default")] + projector: Projector, + /// The arc one repeat of the source spans around the axis (degrees), centred on the front + #[serde(default = "full_turn", skip_serializing_if = "is_full_turn")] + angle: f32, + }, + /// A planar projection from a frame whose four corners are pulled freely, bending the image to the quad they make + Warp { + /// The frame it projects from (its depth is unused: `depth` sets the reach) + frame: Decal, + /// Where the frame's corners sit (top left, top right, bottom right, bottom left), across and up in frame sizes from its centre + corners: [[f32; 2]; 4], + /// Projection Depth: how far in front of and behind the frame it reaches when cropped to its shape, in lengths of the frame's longer side + depth: f32, + uv: UvTransform, + projector: Projector, + }, } -/// The frame a decal projects from (world space). +/// Tiling, rotation (degrees) and offset a 3D projection lays on the surface; the default changes nothing +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct UvTransform { + pub tiling: [f32; 2], + pub rotation: f32, + pub offset: [f32; 2], +} + +impl Default for UvTransform { + fn default() -> Self { + UvTransform { tiling: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] } + } +} + +impl UvTransform { + /// Whether it changes nothing, as projections saved before it existed did (not saved then) + pub fn is_default(&self) -> bool { + *self == UvTransform::default() + } +} + +/// The frame a planar projection placed on the surface (a decal) projects from, in world space #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub struct Decal { /// The surface point the decal was placed on. @@ -222,6 +296,21 @@ fn not_flipped(flip: &[bool; 2]) -> bool { !flip[0] && !flip[1] } +/// Serde default of a cylindrical projection's angle: the whole way round +fn full_turn() -> f32 { + crate::FULL_TURN_DEGREES +} + +/// Whether a cylindrical projection spans the whole way round, as ones saved before the angle did (not saved then) +fn is_full_turn(angle: &f32) -> bool { + *angle == full_turn() +} + +/// Whether a spherical or cylindrical projection sits unshifted, as ones saved before the offset did (not saved then) +fn is_zero_offset(offset: &[f32; 3]) -> bool { + *offset == [0.0; 3] +} + impl Default for Projection { fn default() -> Self { Projection::Uv { scale: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] } @@ -229,14 +318,88 @@ impl Default for Projection { } impl Projection { + /// A warp's corners before any is pulled: the frame's own + pub const FRAME_CORNERS: [[f32; 2]; 4] = [[-0.5, 0.5], [0.5, 0.5], [0.5, -0.5], [-0.5, -0.5]]; + + /// A new warp's Projection Depth + pub const WARP_DEPTH: f32 = 0.1; + + /// A new tri-planar projection's blend sharpness + pub const TRIPLANAR_SHARPNESS: f32 = 8.0; + + /// The blend sharpness a tri-planar projection takes: an exponent from soft (1) to near hard (64) + pub const TRIPLANAR_SHARPNESS_RANGE: std::ops::RangeInclusive = 1.0..=64.0; + + /// The arc in degrees a cylindrical projection wraps its image round; a zero arc would divide by zero + pub const CYLINDER_ANGLE_RANGE: std::ops::RangeInclusive = 1.0..=crate::FULL_TURN_DEGREES; + + /// A tri-planar projection with a new fill's settings + pub fn triplanar() -> Projection { + Projection::Triplanar { + scale: 1.0, + sharpness: Self::TRIPLANAR_SHARPNESS, + offset: [0.0; 3], + uv: UvTransform::default(), + projector: Projector::default(), + } + } + + /// A warp projection from `frame` with its corners where the frame's are + pub fn warp(frame: Decal) -> Projection { + Projection::Warp { + frame, + corners: Projection::FRAME_CORNERS, + depth: Projection::WARP_DEPTH, + uv: UvTransform::default(), + projector: Projector::depth_culled(), + } + } + + /// A planar projection from `frame` with a decal's look: cropped to its frame, depth and image alpha, off faces turned away + pub fn decal(frame: Decal) -> Projection { + let projector = Projector { crop: ShapeCrop::Cropped, backface: Backface { on: true, ..Backface::default() }, ..Projector::default() }; + Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: Some(frame) } + } + + /// The depth culling of a planar or warp projection that has it on + pub fn depth_culling(&self) -> Option { + match self { + Projection::Planar { projector, .. } | Projection::Warp { projector, .. } => Some(projector.depth).filter(|depth| depth.on), + _ => None, + } + } + + /// Whether the projection works in 3D, so a fill's symmetry can copy it (UV projections cannot) + pub fn takes_symmetry(&self) -> bool { + !matches!(self, Projection::Uv { .. } | Projection::UvTile) + } + + /// The frame on the surface a placed planar projection projects from + pub fn placed(&self) -> Option<&Decal> { + match self { + Projection::Planar { placed, .. } => placed.as_ref(), + _ => None, + } + } + + /// The frame on the surface a placed planar or a warp projection projects from + pub fn frame(&self) -> Option<&Decal> { + match self { + Projection::Planar { placed, .. } => placed.as_ref(), + Projection::Warp { frame, .. } => Some(frame), + _ => None, + } + } + pub fn label(&self) -> &'static str { match self { + Projection::UvTile => "Fill (Match per UV Tile)", Projection::Uv { .. } => "UV projection", Projection::Triplanar { .. } => "Tri-planar projection", Projection::Planar { .. } => "Planar projection", Projection::Spherical { .. } => "Spherical projection", Projection::Cylindrical { .. } => "Cylindrical projection", - Projection::Decal(_) => "Decal projection", + Projection::Warp { .. } => "Warp projection", } } } @@ -550,7 +713,10 @@ impl Source { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct Fill { pub sources: BTreeMap, + #[serde(serialize_with = "crate::saved_projection::save", deserialize_with = "crate::saved_projection::load")] pub projection: Projection, + #[serde(default = "Sampling::saved_before", skip_serializing_if = "Sampling::is_saved_before")] + pub sampling: Sampling, /// Set when the sources are maps cooked from a MaterialCraft material. #[serde(default, skip_serializing_if = "Option::is_none")] pub link: Option>, @@ -1179,7 +1345,10 @@ pub enum EffectKind { /// A uniform or procedural grayscale fill. Fill { source: Source, + #[serde(serialize_with = "crate::saved_projection::save", deserialize_with = "crate::saved_projection::load")] projection: Projection, + #[serde(default = "Sampling::saved_before", skip_serializing_if = "Sampling::is_saved_before")] + sampling: Sampling, }, Generator(Generator), Levels(Levels), @@ -1198,10 +1367,7 @@ pub enum EffectKind { /// Content only: a material fill (one source per channel; channels without a source are /// left as they are). Material(Fill), - /// Records the stack at its place so masks, fills and generators above can read it - /// ([`Source::Anchor`]). In a content stack it records the composited stack right after its - /// layer (that layer and everything below); in a mask, the mask value at that point (every - /// channel reads that gray). + /// Records the stack at its place so masks, fills and generators above can read it ([`Source::Anchor`]): in a content stack the composited stack right after its layer (that layer and everything below), in a mask the mask value there (every channel reads that gray) Anchor, } @@ -1547,21 +1713,27 @@ mod tests { assert_eq!(EffectKind::Anchor.content_only(), None, "anchors go on content and masks"); assert_eq!(EffectKind::Generator(Generator::new(GeneratorKind::Dirt)).content_only(), Some(false)); assert_eq!(EffectKind::Filter(Filter::Invert).content_only(), None); + let mut fill_layer = Layer::new(LayerId(1), "l", LayerKind::Paint, &[Channel::BaseColor]); assert!(!fill_layer.reads_anchor()); + let source = Source::Anchor { anchor: LayerId(9), channel: Channel::Height, ramp: Vec::new() }; fill_layer.mask = Some(Mask { - effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default() })], + effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })], ..Mask::new(MaskBackground::Black) }); + assert!(fill_layer.reads_anchor()); // A generator with micro detail reads its anchor too let mut generator_layer = Layer::new(LayerId(3), "g", LayerKind::Paint, &[Channel::BaseColor]); let mut generator = Generator::new(GeneratorKind::Dirt); generator.micro = Some(MicroDetail { anchor: LayerId(9), amount: 0.5 }); + assert_eq!(EffectKind::Generator(generator.clone()).anchors_read(), [(LayerId(9), Channel::Height)]); + generator_layer.mask = Some(Mask { effects: vec![Effect::new(LayerId(4), EffectKind::Generator(generator))], ..Mask::new(MaskBackground::Black) }); + assert!(generator_layer.reads_anchor()); } @@ -1605,6 +1777,31 @@ mod tests { } } + #[test] + fn fills_and_effects_in_the_shape_older_projects_saved_save_unchanged() { + let fills = [ + r#"{"sources":{"BaseColor":{"Uniform":[0.5,0.5,0.5]}},"projection":{"Uv":{"scale":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0]}}}"#, + r#"{"sources":{},"projection":{"Triplanar":{"scale":1.0,"sharpness":0.5,"offset":[0.0,0.0,0.0]}}}"#, + r#"{"sources":{},"projection":{"Planar":{"scale":2.0,"axis":2,"offset":[0.0,1.0,0.0]}}}"#, + r#"{"sources":{},"projection":{"Spherical":{"scale":1.0}}}"#, + r#"{"sources":{},"projection":{"Cylindrical":{"scale":1.0,"axis":1}}}"#, + r#"{"sources":{},"projection":{"Decal":{"center":[0.0,0.0,0.0],"normal":[0.0,0.0,1.0],"up":[0.0,1.0,0.0],"size":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0],"depth":1.0}}}"#, + ]; + for saved in fills { + let loaded: Fill = serde_json::from_str(saved).unwrap(); + assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "a fill saves as it was saved"); + } + + let effects = [ + r#"{"Fill":{"source":{"Uniform":[0.5,0.5,0.5]},"projection":{"Triplanar":{"scale":1.0,"sharpness":0.5,"offset":[0.0,0.0,0.0]}}}}"#, + r#"{"Material":{"sources":{},"projection":{"Spherical":{"scale":2.0}}}}"#, + ]; + for saved in effects { + let loaded: EffectKind = serde_json::from_str(saved).unwrap(); + assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "an effect saves as it was saved"); + } + } + #[test] fn procedural_kinds_parse_labels_and_saved_names() { for kind in ProceduralKind::ALL { diff --git a/crates/engine/tests/it/fill_patterns.rs b/crates/engine/tests/it/fill_patterns.rs new file mode 100644 index 00000000..c5d854ba --- /dev/null +++ b/crates/engine/tests/it/fill_patterns.rs @@ -0,0 +1,69 @@ +//! A fill's procedural pattern through `layer.fill.set`: a parameter given alone changes only itself + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerId, LayerKind, Procedural, ProceduralKind, Source}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// A fill layer whose roughness is a Clouds pattern with every parameter away from its default +fn clouds_fill() -> (Session, LayerId) { + let mut session = Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + let layer = LayerId(execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + let pattern = json!({ + "layer": layer.0, "channel": "roughness", "procedural": "Clouds", "scale": 9.0, "contrast": 1.5, "seed": 7, + "balance": 0.25, "invert": true, "low": [0.2, 0.2, 0.2], "high": [0.8, 0.8, 0.8], + }); + execute(&mut session, "layer.fill.set", &pattern).unwrap(); + (session, layer) +} + +/// The roughness pattern and its Low and High colours +type Roughness = (Procedural, [f32; 3], [f32; 3]); + +fn roughness(session: &Session, layer: LayerId) -> Roughness { + match &session.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(fill) => match fill.source(Channel::Roughness) { + Source::Procedural { pattern, low, high, .. } => (pattern, low, high), + other => panic!("not a procedural: {other:?}"), + }, + other => panic!("not a fill: {other:?}"), + } +} + +/// One parameter sent alone, its value, and what it changes in the stored pattern +type PatternEdit = (&'static str, Value, fn(&mut Roughness)); + +/// What the Scale, Contrast, Seed, Balance and Invert controls and the Low/High swatches send: one parameter each +#[test] +fn a_pattern_parameter_given_alone_keeps_every_other_one() { + let (mut session, layer) = clouds_fill(); + let edits: [PatternEdit; 7] = [ + ("scale", json!(3.0), |(pattern, ..)| pattern.scale = 3.0), + ("contrast", json!(0.5), |(pattern, ..)| pattern.contrast = 0.5), + ("seed", json!(42), |(pattern, ..)| pattern.seed = 42), + ("balance", json!(-0.5), |(pattern, ..)| pattern.balance = -0.5), + ("invert", json!(false), |(pattern, ..)| pattern.invert = false), + ("low", json!([0.1, 0.1, 0.1]), |(_, low, _)| *low = [0.1; 3]), + ("high", json!([0.9, 0.9, 0.9]), |(.., high)| *high = [0.9; 3]), + ]; + for (key, value, change) in edits { + let mut expected = roughness(&session, layer); + change(&mut expected); + let mut edit = json!({"layer": layer.0, "channel": "roughness", "procedural": "Clouds"}); + edit[key] = value; + execute(&mut session, "layer.fill.set", &edit).unwrap(); + + assert_eq!(roughness(&session, layer), expected, "`{key}` alone changes only itself"); + } + + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"balance\":-0.5") && inspected.contains("\"invert\":false"), "inspect shows the balance and invert"); +} + +/// Another kind is a new pattern: its defaults between black and white, as before +#[test] +fn another_pattern_kind_starts_from_its_defaults() { + let (mut session, layer) = clouds_fill(); + execute(&mut session, "layer.fill.set", &json!({"layer": layer.0, "channel": "roughness", "procedural": "Cells"})).unwrap(); + assert_eq!(roughness(&session, layer), (Procedural::new(ProceduralKind::Cells), [0.0; 3], [1.0; 3])); +} diff --git a/crates/engine/tests/it/fill_sampling.rs b/crates/engine/tests/it/fill_sampling.rs new file mode 100644 index 00000000..fd17f481 --- /dev/null +++ b/crates/engine/tests/it/fill_sampling.rs @@ -0,0 +1,218 @@ +//! How fills read their image sources (filtering), through engine commands + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, Fill, Filtering, LayerId, LayerKind, Projection, Sampling, ScaleMode}; +use texturecraft_engine::geom::NO_TRI; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + s.update(); + s +} + +fn png(w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 4]) -> Vec { + let mut out = Vec::new(); + image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +/// A fill layer whose base color is a one-texel black and white checker, tiled `tiling` times +fn checker_fill(s: &mut Session, tiling: f32) -> LayerId { + let name = s.import_resource_bytes("checker.png", png(64, 64, |x, y| if (x + y) % 2 == 0 { [255; 4] } else { [0, 0, 0, 255] })).unwrap(); + let layer = LayerId(execute(s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + execute(s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "image": name})).unwrap(); + execute(s, "layer.fill.projection", &json!({"layer": layer.0, "scale": tiling})).unwrap(); + layer +} + +/// Lowest and highest base color red across the covered texels of the set's middle band +fn spread(s: &mut Session) -> (f32, f32) { + s.update(); + let cache = &s.caches[0]; + let (w, h) = cache.size; + let mut range = (f32::MAX, f32::MIN); + for y in h * 3 / 8..h * 5 / 8 { + for x in w / 4..w * 3 / 4 { + if cache.gbuf.tri[(y * w + x) as usize] != NO_TRI { + let red = cache.composite.value(Channel::BaseColor, x, y)[0]; + range = (range.0.min(red), range.1.max(red)); + } + } + } + range +} + +fn filtering(s: &mut Session, layer: LayerId, id: &str) { + execute(s, "layer.fill.projection", &json!({"layer": layer.0, "filtering": id})).unwrap(); +} + +/// A checker shrunk to two image texels per texel: HQ averages it, Sharp aliases it, Nearest keeps black and white +#[test] +fn filtering_decides_how_a_shrunk_image_reads() { + let mut s = session(); + let layer = checker_fill(&mut s, 7.3); + let (lo, hi) = spread(&mut s); + assert!(hi - lo < 0.2, "a new fill reads with Bilinear | HQ: an even gray, got {lo}..{hi}"); + + filtering(&mut s, layer, "bilinearSharp"); + let (lo, hi) = spread(&mut s); + assert!(hi - lo > 0.5, "Bilinear | Sharp aliases a shrunk checker: {lo}..{hi}"); + + filtering(&mut s, layer, "nearest"); + s.update(); + let cache = &s.caches[0]; + let (w, h) = cache.size; + let pure = (h * 3 / 8..h * 5 / 8) + .flat_map(|y| (w / 4..w * 3 / 4).map(move |x| (x, y))) + .filter(|&(x, y)| cache.gbuf.tri[(y * w + x) as usize] != NO_TRI) + .all(|(x, y)| { + let red = cache.composite.value(Channel::BaseColor, x, y)[0]; + !(0.01..=0.99).contains(&red) + }); + assert!(pure, "Nearest reads one image texel: black or white only"); + + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["filtering"], json!("nearest")); + assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "filtering": "trilinear"})).is_err()); +} + +/// Fills saved before Filtering existed read images as before (plain bilinear); new fills start on Bilinear | HQ +#[test] +fn fills_saved_before_filtering_keep_their_look() { + let mut s = session(); + let layer = checker_fill(&mut s, 1.0); + let LayerKind::Fill(fill) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; + assert_eq!(fill.sampling.filtering, Filtering::BilinearHq); + + let mut saved = serde_json::to_value(fill).unwrap(); + saved.as_object_mut().unwrap().remove("sampling"); + let loaded: Fill = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.sampling, Sampling::SAVED_BEFORE); + assert_eq!(loaded.sampling.filtering, Filtering::BilinearSharp); +} + +/// Share of the middle band's covered texels where the white fill shows over the black layer below +fn shown(s: &mut Session) -> f32 { + s.update(); + let cache = &s.caches[0]; + let (w, h) = cache.size; + let (mut on, mut all) = (0usize, 0usize); + for y in h * 3 / 8..h * 5 / 8 { + for x in 0..w { + if cache.gbuf.tri[(y * w + x) as usize] != NO_TRI { + all += 1; + on += usize::from(cache.composite.value(Channel::BaseColor, x, y)[0] > 0.5); + } + } + } + on as f32 / all.max(1) as f32 +} + +/// UV Wrap on a white fill tiled 4 × 2: Repeat covers the band, None one tile, one-axis repeats in between +#[test] +fn uv_wrap_repeats_the_tile_or_stops_at_its_edge() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 0.0]})).unwrap(); + let layer = LayerId(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()["layer"].as_u64().unwrap()); + let set = |s: &mut Session, p: Value| { + let mut p = p; + p["layer"] = json!(layer.0); + execute(s, "layer.fill.projection", &p) + }; + set(&mut s, json!({"scale": [4, 2]})).unwrap(); + let near = |got: f32, want: f32| (got - want).abs() < 0.05; + let repeat = shown(&mut s); + assert!(near(repeat, 1.0), "Repeat covers the band: {repeat}"); + set(&mut s, json!({"wrap": "none"})).unwrap(); + let none = shown(&mut s); + assert!(near(none, 0.125), "None: a quarter across, half down: {none}"); + set(&mut s, json!({"wrap": "repeatHorizontally"})).unwrap(); + let across = shown(&mut s); + assert!(near(across, 0.5), "repeating across: the whole width, half down: {across}"); + set(&mut s, json!({"wrap": "repeatVertically"})).unwrap(); + let down = shown(&mut s); + assert!(near(down, 0.25), "repeating down: a quarter across, the whole height: {down}"); + + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["wrap"], json!("repeatVertically")); + assert!(set(&mut s, json!({"wrap": "mirror"})).is_err()); + + // Tri-planar has no tile: it covers whatever the wrap says + set(&mut s, json!({"projection": "triplanar", "wrap": "none"})).unwrap(); + let triplanar = shown(&mut s); + assert!(near(triplanar, 1.0), "{triplanar}"); +} + +/// 3D projections take UV transformations; older saves look as they did; world scale and offset stay separate +#[test] +fn three_d_projections_take_uv_transformations() { + use texturecraft_engine::core::{Projection, UvTransform}; + let mut s = session(); + let layer = LayerId(execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + let set = |s: &mut Session, p: Value| { + let mut p = p; + p["layer"] = json!(layer.0); + execute(s, "layer.fill.projection", &p) + }; + execute( + &mut s, + "layer.fill.set", + &json!({"layer": layer.0, "channel": "baseColor", "procedural": "Checker", "scale": 4, "low": [0, 0, 0], "high": [1, 1, 1]}), + ) + .unwrap(); + set(&mut s, json!({"projection": "triplanar"})).unwrap(); + let projection = |s: &Session| match &s.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(f) => f.projection.clone(), + _ => panic!("a fill layer"), + }; + let snapshot = |s: &mut Session| { + s.update(); + let cache = &s.caches[0]; + let (w, h) = cache.size; + (0..w * h).map(|i| cache.composite.value(Channel::BaseColor, i % w, i / w)[0]).collect::>() + }; + let plain = snapshot(&mut s); + + set(&mut s, json!({"tiling": [2, 3], "rotation": 45, "uvOffset": [0.25, 0.5]})).unwrap(); + let Projection::Triplanar { uv, scale, .. } = projection(&s) else { panic!("tri-planar") }; + assert_eq!(uv, UvTransform { tiling: [2.0, 3.0], rotation: 45.0, offset: [0.25, 0.5] }); + assert_eq!(scale, 1.0, "the world scale is its own param"); + assert_ne!(snapshot(&mut s), plain, "the UV transformations move the pattern"); + + // A fill saved before 3D projections had UV transformations loads them as nothing + let mut saved = serde_json::to_value(projection(&s)).unwrap(); + saved["Triplanar"].as_object_mut().unwrap().remove("uv"); + let loaded: Projection = serde_json::from_value(saved).unwrap(); + assert!(matches!(loaded, Projection::Triplanar { uv, .. } if uv == UvTransform::default())); + set(&mut s, json!({"tiling": 1, "rotation": 0, "uvOffset": [0, 0]})).unwrap(); + assert_eq!(snapshot(&mut s), plain, "the identity transform changes nothing"); + + // On a UV projection, tiling is its scale + set(&mut s, json!({"projection": "uv", "tiling": [2, 4]})).unwrap(); + assert!(matches!(projection(&s), Projection::Uv { scale, .. } if scale == [2.0, 4.0])); +} + +/// Physical size keeps the fill's tiling; inspect reports the mode and older fills open on Tiling +#[test] +fn scale_mode_is_stored_without_changing_the_tiling() { + let mut s = session(); + let layer = checker_fill(&mut s, 2.0); + execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "scaleMode": "physicalSize"})).unwrap(); + let LayerKind::Fill(fill) = s.doc.project.layer(layer).unwrap().kind.clone() else { panic!("a fill layer") }; + assert_eq!(fill.sampling.scale, ScaleMode::PhysicalSize); + assert!(matches!(fill.projection, Projection::Uv { scale: [2.0, 2.0], .. }), "{:?}", fill.projection); + + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["scaleMode"], json!("physicalSize")); + assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "scaleMode": "inches"})).is_err()); + + let mut saved = serde_json::to_value(&fill).unwrap(); + saved["sampling"].as_object_mut().unwrap().remove("scale"); + let loaded: Fill = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.sampling.scale, ScaleMode::Tiling); +} From 9958edaece10fca80473ea7259dda075418c5717 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:10 +0000 Subject: [PATCH 05/17] Fills: Shape crop, Backface culling and Depth culling on 3D projections --- crates/compose/src/projector_cover.rs | 281 +++++++++++++++++++++++++ crates/compose/src/projector_depth.rs | 287 ++++++++++++++++++++++++++ crates/compose/src/projector_view.rs | 62 ++++++ 3 files changed, 630 insertions(+) create mode 100644 crates/compose/src/projector_cover.rs create mode 100644 crates/compose/src/projector_depth.rs create mode 100644 crates/compose/src/projector_view.rs diff --git a/crates/compose/src/projector_cover.rs b/crates/compose/src/projector_cover.rs new file mode 100644 index 00000000..e19a6c73 --- /dev/null +++ b/crates/compose/src/projector_cover.rs @@ -0,0 +1,281 @@ +//! How much of a texel a 3D projection reaches: its shape crop and its backface culling + +use texturecraft_core::{Backface, Decal, DecalFlip, Projection, Projector, ShapeCrop}; +use texturecraft_geom::glam::{Vec2, Vec3}; + +use crate::frame_placement::warp_reach; +use crate::organic::smoothstep; +use crate::pattern::{Coords, depth_fade, frame_crop, frame_facing, frame_local, placed_uv, projector_local}; +use crate::warp::warp_uv; + +/// Nearer a cylinder's axis than this a texel has no outward direction, so it counts as facing out +const MIN_AXIS_DISTANCE: f32 = 1e-6; + +/// The turn (in cosine) over which backface culling fades at hardness 0 +const BACKFACE_FADE: f32 = 0.6; + +/// The shape crop and backface culling [`projector_cover`] applies, None where it lets every texel through +fn cropping_projector(proj: &Projection) -> Option<&Projector> { + let projector = match proj { + Projection::Triplanar { projector, .. } + | Projection::Planar { projector, .. } + | Projection::Spherical { projector, .. } + | Projection::Cylindrical { projector, .. } => projector, + // Framed on the surface: see [`framed_cover`] + Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => return None, + }; + Some(projector).filter(|projector| projector.crop != ShapeCrop::ExtendsOutside || projector.backface.on) +} + +/// Whether [`projector_cover`] is 1 on every texel, so it needs no texel's place +pub fn projector_covers_all(proj: &Projection) -> bool { + cropping_projector(proj).is_none() +} + +/// How much of the texel at `coords` the projection reaches through its shape crop and backface culling; not for placed planars or warps (see [`framed_cover`]) +pub fn projector_cover(proj: &Projection, coords: &Coords) -> f32 { + let Some(projector) = cropping_projector(proj) else { return 1.0 }; + + let local = projector_local(projector, coords); + let (inside, facing) = match proj { + Projection::Triplanar { .. } => (local.pos.abs().max_element() <= 1.0, None), + Projection::Planar { scale, axis, offset, .. } => { + let scaled = local.pos * *scale + Vec3::from(*offset); + + // The frame across the axis, and the side the image reads the right way round from + let (frame, facing) = match axis { + 0 => (scaled.z.abs().max(scaled.y.abs()), -local.nrm.x), + 1 => (scaled.x.abs().max(scaled.z.abs()), local.nrm.y), + _ => (scaled.x.abs().max(scaled.y.abs()), local.nrm.z), + }; + (frame <= 1.0, Some(facing)) + } + Projection::Spherical { offset, .. } => ((local.pos + Vec3::from(*offset)).length() <= 1.0, None), + Projection::Cylindrical { axis, offset, .. } => { + let position = local.pos + Vec3::from(*offset); + let normal = local.nrm; + let ((across, height, depth), (normal_across, normal_depth)) = match axis { + 0 => ((position.y, position.x, position.z), (normal.y, normal.z)), + 2 => ((position.x, position.z, position.y), (normal.x, normal.y)), + _ => ((position.x, position.y, position.z), (normal.x, normal.z)), + }; + let radius = across.hypot(depth); + let outward = if radius > MIN_AXIS_DISTANCE { (normal_across * across + normal_depth * depth) / radius } else { 1.0 }; + (radius <= 1.0 && height.abs() <= 1.0, Some(outward)) + } + Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => (true, None), + }; + if projector.crop == ShapeCrop::Cropped && !inside { + return 0.0; + } + + match facing { + Some(facing) if projector.backface.on => backface_cover(&projector.backface, facing), + _ => 1.0, + } +} + +/// How much a face turned `facing` (the cosine of its turn from the projection) keeps +pub fn backface_cover(backface: &Backface, facing: f32) -> f32 { + // A hand-edited NaN angle or hardness keeps the layer visible rather than making its texels NaN + if !(backface.angle.is_finite() && backface.hardness.is_finite()) { + return 1.0; + } + + // cos(angle) as sin(90 - angle): exactly 0 at 90 degrees + let threshold = (90.0 - backface.angle).to_radians().sin(); + let width = (1.0 - backface.hardness.clamp(0.0, 1.0)) * BACKFACE_FADE; + if width <= f32::EPSILON { + return f32::from(u8::from(facing > threshold)); + } + + smoothstep(threshold, threshold + width, facing) +} + +/// A planar projection placed on the surface at world point `p` with normal `nrm`: its texture coordinates and how much its backface culling and shape crop let through (None when the frame is degenerate) +pub fn placed_cover(frame: &Decal, projector: &Projector, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> { + let local = frame_local(frame, projector, p)?; + let mut cover = if projector.backface.on { backface_cover(&projector.backface, frame_facing(frame, projector, nrm)) } else { 1.0 }; + if projector.crop == ShapeCrop::Cropped { + cover *= frame_crop(frame, local); + } + Some((flip_uv(placed_uv(local), frame.flip), cover)) +} + +/// [`placed_cover`] for a frame with a mirrored copy: whichever of the frame and its copy covers the point more. The copy is the frame reflected through the plane `offset` away from `center` (the mesh center) on the symmetry axis, its image flipped as asked +pub fn placed_cover_symmetric(frame: &Decal, projector: &Projector, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> { + let direct = placed_cover(frame, projector, p, nrm); + let Some(symmetry) = frame.symmetry else { return direct }; + + let axis = usize::from(symmetry.axis.min(2)); + let (mut mirrored_position, mut mirrored_normal) = (p, nrm); + mirrored_position[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis]; + mirrored_normal[axis] = -nrm[axis]; + let mirrored = placed_cover(frame, projector, mirrored_position, mirrored_normal).map(|(uv, cover)| { + let uv = match symmetry.flip { + DecalFlip::None => uv, + DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y), + DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y), + }; + (uv, cover) + }); + match (direct, mirrored) { + (Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }), + (a, b) => a.or(b), + } +} + +/// `uv` with the image mirrored left to right (`flip[0]`) and/or top to bottom (`flip[1]`) inside the frame +fn flip_uv(uv: Vec2, flip: [bool; 2]) -> Vec2 { + Vec2::new(if flip[0] { 1.0 - uv.x } else { uv.x }, if flip[1] { 1.0 - uv.y } else { uv.y }) +} + +/// A projection from a frame on the surface (a placed planar or a warp) at world point `p` with normal `nrm`, `center` the mesh center a placed planar's mirrored copy reflects across: its texture coordinates and how much it covers there (None for other projections, a degenerate frame or where nothing lands) +pub fn framed_cover(proj: &Projection, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> { + match proj { + Projection::Planar { projector, placed: Some(frame), .. } => placed_cover_symmetric(frame, projector, p, nrm, center), + Projection::Warp { frame, corners, depth, projector, .. } => warp_cover(frame, corners, *depth, projector, p), + _ => None, + } +} + +/// A warp projection at world point `p`: its texture coordinates in the quad its corners make, and, cropped to its shape, how much of the quad and of its Projection Depth (in lengths of the frame's longer side) cover it +pub fn warp_cover(frame: &Decal, corners: &[[f32; 2]; 4], depth: f32, projector: &Projector, p: Vec3) -> Option<(Vec2, f32)> { + let local = frame_local(frame, projector, p)?; + let uv = warp_uv(corners, local.truncate())?; + if projector.crop == ShapeCrop::ExtendsOutside { + return Some((uv, 1.0)); + } + + let inside = (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y); + let reach = warp_reach(frame.size, depth); + Some((uv, if inside { depth_fade(local.z, reach) } else { 0.0 })) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The decal formula from before decals were placed planar projections, kept to check they still look the same + fn decal_before(frame: &Decal, point: Vec3, surface_normal: Vec3) -> Option<(Vec2, f32)> { + let (origin, right, up, normal) = crate::pattern::decal_axes(frame)?; + let facing = surface_normal.dot(normal); + let offset = point - origin; + let (local_x, local_y, local_z) = (offset.dot(right) / frame.size[0].max(1e-6), offset.dot(up) / frame.size[1].max(1e-6), offset.dot(normal).abs()); + let depth = frame.depth.max(1e-6); + if facing <= 0.0 || local_x.abs() > 0.5 || local_y.abs() > 0.5 || local_z > depth || !(local_x.is_finite() && local_y.is_finite()) { + return None; + } + + let cover = smoothstep(0.0, 0.3, facing) * (1.0 - smoothstep(0.75 * depth, depth, local_z)); + Some((Vec2::new(local_x + 0.5, 0.5 - local_y), cover)) + } + + #[test] + fn a_nan_backface_angle_or_hardness_culls_nothing() { + for backface in [Backface { on: true, angle: f32::NAN, hardness: 0.5 }, Backface { on: true, angle: 60.0, hardness: f32::NAN }] { + assert_eq!(backface_cover(&backface, -0.5), 1.0, "{backface:?}"); + } + } + + #[test] + fn saved_decals_cover_exactly_as_before() { + let frames = [ + Decal { + center: [0.0; 3], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [2.0, 1.0], + rotation: 0.0, + offset: [0.0; 2], + depth: 0.5, + symmetry: None, + flip: [false; 2], + }, + Decal { + center: [0.3, -0.2, 0.1], + normal: [0.4, 0.5, 0.7], + up: [0.0, 1.0, 0.0], + size: [0.7, 1.3], + rotation: 37.0, + offset: [0.2, -0.1], + depth: 0.4, + symmetry: None, + flip: [false; 2], + }, + ]; + for frame in frames { + let Projection::Planar { projector, placed: Some(placed), .. } = Projection::decal(frame) else { panic!("a placed planar projection") }; + for sample in 0..4000 { + let phase = sample as f32 * 0.137; + let point = Vec3::new(phase.sin() * 1.3, (phase * 0.71).cos() * 1.1, (phase * 0.33).sin() * 0.8); + let normal = Vec3::new((phase * 1.7).cos(), (phase * 0.9).sin(), (phase * 0.4).cos()).normalize(); + let now = placed_cover(&placed, &projector, point, normal).filter(|(_, cover)| *cover > 0.0); + match (decal_before(&frame, point, normal), now) { + (Some(before), Some(now)) => assert_eq!(before, now, "{point} {normal}"), + (None, None) => {} + (before, now) => panic!("{point} {normal}: {before:?} became {now:?}"), + } + } + } + } + + /// The mirrored copy's formula as the decal model before placed planar projections had it (flip and symmetry on a decal) + fn symmetric_before(d: &Decal, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> { + let flip = |uv: Vec2| flip_uv(uv, d.flip); + let direct = decal_before(d, p, nrm).map(|(uv, w)| (flip(uv), w)); + let Some(symmetry) = d.symmetry else { return direct }; + let axis = usize::from(symmetry.axis.min(2)); + let (mut q, mut m) = (p, nrm); + q[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis]; + m[axis] = -nrm[axis]; + let mirrored = decal_before(d, q, m).map(|(uv, w)| { + let uv = flip(uv); + let uv = match symmetry.flip { + DecalFlip::None => uv, + DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y), + DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y), + }; + (uv, w) + }); + match (direct, mirrored) { + (Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }), + (a, b) => a.or(b), + } + } + + #[test] + fn saved_mirrored_and_flipped_decals_cover_exactly_as_before() { + let base = Decal { + center: [0.3, -0.2, 0.1], + normal: [0.4, 0.5, 0.7], + up: [0.0, 1.0, 0.0], + size: [0.7, 1.3], + rotation: 37.0, + offset: [0.2, -0.1], + depth: 0.4, + symmetry: None, + flip: [false; 2], + }; + let center = Vec3::new(0.1, -0.05, 0.2); + let frames = [ + Decal { flip: [true, false], ..base }, + Decal { symmetry: Some(texturecraft_core::DecalSymmetry { axis: 0, flip: DecalFlip::None, offset: 0.0 }), ..base }, + Decal { symmetry: Some(texturecraft_core::DecalSymmetry { axis: 2, flip: DecalFlip::V, offset: -0.15 }), flip: [false, true], ..base }, + ]; + for frame in frames { + let Projection::Planar { projector, placed: Some(placed), .. } = Projection::decal(frame) else { panic!("a placed planar projection") }; + let mut mirrored = 0; + for i in 0..4000 { + let t = i as f32 * 0.137; + let p = Vec3::new(t.sin() * 1.3, (t * 0.71).cos() * 1.1, (t * 0.33).sin() * 0.8); + let nrm = Vec3::new((t * 1.7).cos(), (t * 0.9).sin(), (t * 0.4).cos()).normalize(); + let now = placed_cover_symmetric(&placed, &projector, p, nrm, center).filter(|(_, cover)| *cover > 0.0); + let before = symmetric_before(&frame, p, nrm, center); + mirrored += usize::from(before.is_some() && decal_before(&frame, p, nrm).is_none()); + assert_eq!(before, now, "{p} {nrm}"); + } + assert!(frame.symmetry.is_none() || mirrored > 0, "the mirrored copy covers points the frame does not"); + } + } +} diff --git a/crates/compose/src/projector_depth.rs b/crates/compose/src/projector_depth.rs new file mode 100644 index 00000000..bf0aafcd --- /dev/null +++ b/crates/compose/src/projector_depth.rs @@ -0,0 +1,287 @@ +//! The depth map of a planar or warp projection: the surface nearest its projector across its view, for depth culling + +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::{Arc, Mutex}; + +use texturecraft_core::Projection; +use texturecraft_geom::Mesh; +use texturecraft_geom::glam::{Vec2, Vec3}; + +use crate::organic::smoothstep; +use crate::projector_view::ProjectorView; + +/// The nearest surface in each cell of a grid across a projector's view +pub struct ProjectorDepth { + view: ProjectorView, + /// The view point at the grid's lower corner + origin: Vec2, + /// One cell's size across and up in the view + cell: Vec2, + /// Per cell: the nearness of the nearest surface at the cell centre and its slope across and up (nearness -inf where no surface is) + front: Vec<[f32; 3]>, +} + +/// Built maps by their view and the mesh they come from +type CacheEntry = (ProjectorView, u64, Arc); + +/// The smallest grid cell across and up, so a flat view still divides +const MIN_CELL_SIZE: f32 = 1e-6; + +/// A cell centre this close outside a triangle's edge (as a share of its area) still counts as inside, so shared edges leave no gaps +const EDGE_TOLERANCE: f32 = 1e-6; + +static CACHE: Mutex> = Mutex::new(Vec::new()); + +impl ProjectorDepth { + /// The depth map of `proj` over `mesh` within `bounds`, built once per view and mesh; None unless `proj` culls by depth + pub fn of(mesh: &Mesh, bounds: (Vec3, Vec3), proj: &Projection) -> Option> { + let view = ProjectorView::of(proj, bounds)?; + let mesh_key = fingerprint(mesh); + + // Built with the cache locked: the build runs no parallel work, and tiles asking for the same map wait for it instead of building it again + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(at) = cache.iter().position(|(cached_view, cached_mesh, _)| *cached_view == view && *cached_mesh == mesh_key) { + let (cached_view, cached_mesh, depth) = cache.remove(at); + cache.insert(0, (cached_view, cached_mesh, depth.clone())); + return Some(depth); + } + + let depth = Arc::new(ProjectorDepth::build(view, mesh)?); + cache.insert(0, (view, mesh_key, depth.clone())); + cache.truncate(CACHE_MAPS); + Some(depth) + } + + /// Drop every built map: a mesh replacing another (a reimport, another project) can share the old one's fingerprint + pub fn forget_all() { + CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clear(); + } + + /// Rasterize every triangle of `mesh` in `view`, keeping the nearest per cell (None when no vertex lands in the view) + pub fn build(view: ProjectorView, mesh: &Mesh) -> Option { + let local: Vec> = mesh.positions.iter().map(|position| view.local(*position)).collect(); + let (lo, hi) = local + .iter() + .flatten() + .fold((Vec2::splat(f32::MAX), Vec2::splat(f32::MIN)), |(lo, hi), view_point| (lo.min(view_point.truncate()), hi.max(view_point.truncate()))); + if lo.x > hi.x || lo.y > hi.y { + return None; + } + + let cell = ((hi - lo) / SIZE as f32).max(Vec2::splat(MIN_CELL_SIZE)); + let mut depth = ProjectorDepth { view, origin: lo, cell, front: vec![[f32::NEG_INFINITY, 0.0, 0.0]; SIZE * SIZE] }; + let mut budget = CELL_BUDGET; + for tri in mesh.indices.as_chunks::<3>().0 { + let corner = |i: u32| local.get(i as usize).copied().flatten(); + let (Some(a), Some(b), Some(c)) = (corner(tri[0]), corner(tri[1]), corner(tri[2])) else { continue }; + if !depth.raster([a, b, c], &mut budget) { + break; + } + } + Some(depth) + } + + /// Keep `triangle` where it is nearer than what a cell holds; false once the cell budget runs out + fn raster(&mut self, triangle: [Vec3; 3], budget: &mut usize) -> bool { + let [a, b, c] = triangle; + let (d1, d2) = (b - a, c - a); + let det = d1.x * d2.y - d1.y * d2.x; + if !det.is_finite() || det.abs() < MIN_SCREEN_AREA { + // Seen edge on, it covers nothing + return true; + } + + let slope = Vec2::new((d1.z * d2.y - d2.z * d1.y) / det, (d1.x * d2.z - d2.x * d1.z) / det).clamp(Vec2::splat(-MAX_SLOPE), Vec2::splat(MAX_SLOPE)); + + // Corners in cells: cell (i, j) has its centre at (i + 0.5, j + 0.5) + let [pa, pb, pc] = triangle.map(|corner| (corner.truncate() - self.origin) / self.cell); + let (lo, hi) = (pa.min(pb).min(pc), pa.max(pb).max(pc)); + let first = |v: f32| (v - 0.5).ceil().clamp(0.0, SIZE as f32) as usize; + let last = |v: f32| ((v - 0.5).floor() + 1.0).clamp(0.0, SIZE as f32) as usize; + let (x0, x1, y0, y1) = (first(lo.x), last(hi.x), first(lo.y), last(hi.y)); + let cells = x1.saturating_sub(x0).saturating_mul(y1.saturating_sub(y0)); + let Some(left) = budget.checked_sub(cells) else { return false }; + *budget = left; + + let area = edge(pa, pb, pc); + for y in y0..y1 { + for x in x0..x1 { + let cell_centre = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + let inside = [edge(pb, pc, cell_centre), edge(pc, pa, cell_centre), edge(pa, pb, cell_centre)] + .iter() + .all(|weight| weight * area.signum() >= -EDGE_TOLERANCE * area.abs()); + if !inside { + continue; + } + + let near = a.z + slope.dot(self.origin + cell_centre * self.cell - a.truncate()); + if let Some(cell) = self.front.get_mut(y * SIZE + x) + && near > cell[0] + { + *cell = [near, slope.x, slope.y]; + } + } + } + true + } + + /// How much depth culling with `hardness` leaves of a projection at world point `p`: 0 behind the surface nearest the projector, 1 on it or where nothing is in front + pub fn cover(&self, p: Vec3, hardness: f32) -> f32 { + // A hand-edited NaN hardness keeps the layer visible rather than making its texels NaN + if !hardness.is_finite() { + return 1.0; + } + + let Some(view_point) = self.view.local(p) else { return 1.0 }; + let at = (view_point.truncate() - self.origin) / self.cell; + if !(at.x >= 0.0 && at.y >= 0.0 && at.x < SIZE as f32 && at.y < SIZE as f32) { + return 1.0; + } + + let (x, y) = (at.x as usize, at.y as usize); + let Some(&[near, across, up]) = self.front.get(y * SIZE + x).filter(|cell| cell[0].is_finite()) else { return 1.0 }; + + // The nearest surface's plane carried from the cell centre to the point, so a surface is never behind itself + let centre = self.origin + (Vec2::new(x as f32, y as f32) + 0.5) * self.cell; + let slope = Vec2::new(across, up); + let behind = near + slope.dot(view_point.truncate() - centre) - view_point.z; + let unit = self.view.unit(); + + // Neighbouring triangles of a curved surface part from the carried plane by about one cell of its slope + let bias = BIAS * unit + (slope.abs() * self.cell).element_sum().min(MAX_SLOPE_BIAS * unit); + let width = (1.0 - hardness.clamp(0.0, 1.0)) * FADE * unit; + if width <= f32::EPSILON { + return f32::from(u8::from(behind <= bias)); + } + + 1.0 - smoothstep(bias, bias + width, behind) + } +} + +/// Twice the signed area of triangle `a`, `b`, `q` +fn edge(a: Vec2, b: Vec2, q: Vec2) -> f32 { + (b - a).perp_dot(q - a) +} + +/// Which mesh a map was built for: its sizes and a spread of its vertices and indices +fn fingerprint(mesh: &Mesh) -> u64 { + let mut hasher = DefaultHasher::new(); + (mesh.positions.len(), mesh.indices.len()).hash(&mut hasher); + for position in mesh.positions.iter().step_by((mesh.positions.len() / FINGERPRINT_SAMPLES).max(1)) { + position.to_array().map(f32::to_bits).hash(&mut hasher); + } + for index in mesh.indices.iter().step_by((mesh.indices.len() / FINGERPRINT_SAMPLES).max(1)) { + index.hash(&mut hasher); + } + hasher.finish() +} + +/// Cells across and up the grid +const SIZE: usize = 512; + +/// A triangle flatter than this on screen is seen edge on +const MIN_SCREEN_AREA: f32 = 1e-12; + +/// Most cells all triangles together may visit before the rest are left out (hostile meshes of huge overlapping triangles) +const CELL_BUDGET: usize = 256 * SIZE * SIZE; + +/// Steepest surface slope kept, in nearness per view unit +const MAX_SLOPE: f32 = 1e4; + +/// How far behind the nearest surface a point may sit and keep everything, in mesh radii +const BIAS: f32 = 0.002; + +/// Most the slope adds to the bias, in mesh radii +const MAX_SLOPE_BIAS: f32 = 0.05; + +/// How far behind the nearest surface culling fades out at hardness 0, in mesh radii +const FADE: f32 = 0.1; + +/// Maps kept built (each is about 3 MB) +const CACHE_MAPS: usize = 8; + +/// Vertices and indices the mesh fingerprint reads +const FINGERPRINT_SAMPLES: usize = 64; + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_core::{Projector, UvTransform}; + + /// Two squares facing +Z, one at z = `front` covering x 0..1, one at z = `back` covering x -1..1 + fn two_squares(front: f32, back: f32) -> Mesh { + let positions = vec![ + Vec3::new(0.0, -1.0, front), + Vec3::new(1.0, -1.0, front), + Vec3::new(1.0, 1.0, front), + Vec3::new(0.0, 1.0, front), + Vec3::new(-1.0, -1.0, back), + Vec3::new(1.0, -1.0, back), + Vec3::new(1.0, 1.0, back), + Vec3::new(-1.0, 1.0, back), + ]; + Mesh { positions, indices: vec![0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7], ..Mesh::default() } + } + + fn planar_z(on: bool, hardness: f32) -> Projection { + let mut projector = Projector::depth_culled(); + projector.depth.on = on; + projector.depth.hardness = hardness; + Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None } + } + + #[test] + fn surfaces_behind_others_are_culled_and_the_nearest_keeps_everything() { + let mesh = two_squares(0.5, -0.5); + let bounds = mesh.bounds(); + let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), bounds).unwrap(), &mesh).unwrap(); + assert_eq!(depth.cover(Vec3::new(0.5, 0.3, 0.5), 1.0), 1.0, "the front square"); + assert_eq!(depth.cover(Vec3::new(0.5, 0.3, -0.5), 1.0), 0.0, "the back square behind it"); + assert_eq!(depth.cover(Vec3::new(-0.5, 0.3, -0.5), 1.0), 1.0, "the back square where nothing is in front"); + let soft = depth.cover(Vec3::new(0.5, 0.3, 0.5 - 0.01), 0.0); + assert!(soft > 0.0 && soft < 1.0, "a soft cull fades just behind the front: {soft}"); + assert!(ProjectorView::of(&planar_z(false, 1.0), bounds).is_none(), "off, there is nothing to build"); + } + + #[test] + fn a_nan_hardness_culls_nothing() { + let mesh = two_squares(0.5, -0.5); + let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), mesh.bounds()).unwrap(), &mesh).unwrap(); + + let behind = depth.cover(Vec3::new(0.5, 0.3, -0.5), f32::NAN); + + assert_eq!(behind, 1.0, "a hand-edited NaN hardness keeps the back square visible"); + } + + #[test] + fn a_mesh_edited_where_its_fingerprint_does_not_look_is_rebuilt_once_forgotten() { + // Unused vertices spread the fingerprint's samples so the front square's right edge is not among them + let mut mesh = two_squares(0.5, -0.5); + mesh.positions.extend((0..FINGERPRINT_SAMPLES * 3).map(|_| Vec3::ZERO)); + let mut edited = mesh.clone(); + for right in [1, 2] { + edited.positions[right].x = 0.5; + } + assert_eq!(fingerprint(&mesh), fingerprint(&edited), "the edit is unseen by the fingerprint"); + let proj = planar_z(true, 1.0); + let behind_the_cut = Vec3::new(0.75, 0.3, -0.5); + let bounds = mesh.bounds(); + assert_eq!(ProjectorDepth::of(&mesh, bounds, &proj).unwrap().cover(behind_the_cut, 1.0), 0.0); + + ProjectorDepth::forget_all(); + + let rebuilt = ProjectorDepth::of(&edited, bounds, &proj).unwrap(); + assert_eq!(rebuilt.cover(behind_the_cut, 1.0), 1.0, "nothing is in front there any more"); + } + + #[test] + fn a_slanted_surface_is_never_behind_itself() { + let positions = vec![Vec3::new(-1.0, -1.0, -0.9), Vec3::new(1.0, -1.0, 0.9), Vec3::new(1.0, 1.0, 0.9), Vec3::new(-1.0, 1.0, -0.9)]; + let mesh = Mesh { positions, indices: vec![0, 1, 2, 0, 2, 3], ..Mesh::default() }; + let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), mesh.bounds()).unwrap(), &mesh).unwrap(); + for i in 0..1000 { + let (x, y) = ((i as f32 * 0.618).fract() * 1.98 - 0.99, (i as f32 * 0.377).fract() * 1.98 - 0.99); + assert_eq!(depth.cover(Vec3::new(x, y, x * 0.9), 1.0), 1.0, "{x} {y}"); + } + } +} diff --git a/crates/compose/src/projector_view.rs b/crates/compose/src/projector_view.rs new file mode 100644 index 00000000..982d0820 --- /dev/null +++ b/crates/compose/src/projector_view.rs @@ -0,0 +1,62 @@ +//! Where a planar or warp projection's projector looks from, for depth culling + +use texturecraft_core::{Decal, Projection, Projector}; +use texturecraft_geom::glam::{Vec2, Vec3}; + +use crate::pattern::{Coords, frame_local, mesh_frame, projector_local}; + +/// The view of a depth-culled planar or warp projection: points in it run across, up and towards the projector +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ProjectorView { + /// An axis planar projection, reading positions around the mesh centre in mesh radii + Axis { axis: u8, projector: Projector, center: Vec3, radius: f32 }, + /// A planar projection placed on the surface or a warp, from its frame + Frame { frame: Decal, projector: Projector, radius: f32 }, +} + +impl ProjectorView { + /// The view of `proj` over a mesh within `bounds`, None unless it is a planar or warp projection with depth culling on + pub fn of(proj: &Projection, bounds: (Vec3, Vec3)) -> Option { + proj.depth_culling()?; + let (center, radius) = mesh_frame(bounds); + match proj { + Projection::Planar { placed: Some(frame), projector, .. } | Projection::Warp { frame, projector, .. } => { + Some(ProjectorView::Frame { frame: *frame, projector: turn_only(projector), radius }) + } + Projection::Planar { axis, projector, .. } => Some(ProjectorView::Axis { axis: *axis, projector: turn_only(projector), center, radius }), + _ => None, + } + } + + /// World point `point` in the view: across, up and how near the projector (None where the view is degenerate) + pub fn local(&self, point: Vec3) -> Option { + let local = match self { + ProjectorView::Axis { axis, projector, center, radius } => { + let at = Coords { uv: Vec2::ZERO, pos: (point - *center) / *radius, nrm: Vec3::Z }; + let projected = projector_local(projector, &at).pos; + + // The side each axis projects from, as its backface culling reads it + match axis { + 0 => Vec3::new(projected.z, projected.y, -projected.x), + 1 => Vec3::new(projected.x, projected.z, projected.y), + _ => projected, + } + } + ProjectorView::Frame { frame, projector, .. } => frame_local(frame, projector, point)?, + }; + local.is_finite().then_some(local) + } + + /// The mesh radius in the view's nearness units + pub fn unit(&self) -> f32 { + match self { + ProjectorView::Axis { .. } => 1.0, + ProjectorView::Frame { radius, .. } => *radius, + } + } +} + +/// Only what moves the view: the turn and stretch, not the culling settings (changing those keeps the depth map) +fn turn_only(projector: &Projector) -> Projector { + Projector { rotation: projector.rotation, scale: projector.scale, ..Projector::default() } +} From 891247db6acea1e1f44c1140573f120687ff1736 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:10 +0000 Subject: [PATCH 06/17] Fills: decals are placed planars, and the Warp projection --- crates/compose/src/frame_placement.rs | 331 +++++++++++++++++++++++++ crates/compose/src/warp.rs | 96 ++++++++ crates/core/src/saved_decal.rs | 11 + crates/engine/src/decal_cmds.rs | 335 +++++++++++++++++++------- crates/engine/src/warp_cmds.rs | 68 ++++++ crates/ui-egui/src/warp_checker.rs | 169 +++++++++++++ 6 files changed, 921 insertions(+), 89 deletions(-) create mode 100644 crates/compose/src/frame_placement.rs create mode 100644 crates/compose/src/warp.rs create mode 100644 crates/core/src/saved_decal.rs create mode 100644 crates/engine/src/warp_cmds.rs create mode 100644 crates/ui-egui/src/warp_checker.rs diff --git a/crates/compose/src/frame_placement.rs b/crates/compose/src/frame_placement.rs new file mode 100644 index 00000000..0adac17b --- /dev/null +++ b/crates/compose/src/frame_placement.rs @@ -0,0 +1,331 @@ +//! A frame on the surface (a placed planar or a warp) as its 3D projection settings show it: where its centre is, how it is turned and how big it is + +use texturecraft_core::{Decal, Projection, Projector}; +use texturecraft_geom::glam::{EulerRot, Mat3, Quat, Vec3}; + +use crate::pattern::{decal_axes, mesh_frame, projector_stretch}; + +/// The shortest frame side a depth is divided by, so a collapsed frame keeps a finite depth +pub const MIN_FRAME_SIDE: f32 = 1e-6; + +/// Below this the frame faces nearly straight up or down, so world up gives no upright direction +const MIN_UP_CROSS_SQUARED: f32 = 1e-6; + +/// The longer side of a frame of `size`, at least [`MIN_FRAME_SIDE`]: a warp's Projection Depth counts in it +pub fn longer_side(size: [f32; 2]) -> f32 { + size[0].max(size[1]).max(MIN_FRAME_SIDE) +} + +/// How far a warp whose frame has `size` reaches in front of and behind it at Projection Depth `depth`, in world units +pub fn warp_reach(size: [f32; 2], depth: f32) -> f32 { + depth * longer_side(size) +} + +/// A frame's Offset (its centre in mesh radii from the mesh's centre), Rotation (degrees round X, Y and Z, as a projector turns) and Scale (its width and height, then how far it reaches in front of and behind it, in mesh diagonals) +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FramePlacement { + pub offset: [f32; 3], + pub rotation: [f32; 3], + pub scale: [f32; 3], +} + +/// Whether backface culling faces the same way once `projector`'s scale is moved into a frame: culling is off, or the scale is even and keeps the side the frame faces (culling reads the scaled normal, a frame its own) +pub fn culling_folds(projector: &Projector) -> bool { + let stretch = projector_stretch(projector); + let size = stretch.abs(); + let even = size.x == size.y && size.y == size.z; + !projector.backface.on || (even && stretch.x * stretch.y * stretch.z > 0.0) +} + +/// `proj` (a placed planar or a warp) with its projector's turn and scale moved into its frame, so the frame is where the projection lands; culling and crop stay. None for other projections, and while backface culling cannot keep its facing (see [`culling_folds`]) +pub fn folded(proj: &Projection) -> Option { + let (frame, projector) = match proj { + Projection::Planar { placed: Some(frame), projector, .. } | Projection::Warp { frame, projector, .. } => (frame, projector), + _ => return None, + }; + + if !projector.turns() { + return Some(proj.clone()); + } + + if !culling_folds(projector) { + return None; + } + + let (origin, across, up, _) = decal_axes(frame)?; + let [x, y, z] = projector.rotation.map(f32::to_radians); + let turn = Mat3::from_cols(across, up, across.cross(up)) * Mat3::from_euler(EulerRot::ZYX, z, y, x); + let stretch = projector_stretch(projector); + + // A negative scale turns that side over + let (across, up) = (turn.x_axis * stretch.x.signum(), turn.y_axis * stretch.y.signum()); + let size = [frame.size[0] * stretch.x.abs(), frame.size[1] * stretch.y.abs()]; + let reach = stretch.z.abs(); + let new_frame = Decal { + center: origin.to_array(), + normal: across.cross(up).to_array(), + up: up.to_array(), + size, + rotation: 0.0, + offset: [0.0; 2], + depth: frame.depth * reach, + symmetry: frame.symmetry, + flip: frame.flip, + }; + let unturned = Projector { rotation: [0.0; 3], scale: [1.0; 3], ..*projector }; + let mut out = proj.clone(); + match &mut out { + Projection::Planar { placed: Some(placed), projector, .. } => { + *placed = new_frame; + *projector = unturned; + } + Projection::Warp { frame: warp, projector, depth, .. } => { + // Its depth counts in lengths of the frame's longer side + *depth *= reach * longer_side(frame.size) / longer_side(size); + *warp = new_frame; + *projector = unturned; + } + _ => return None, + } + let finite = new_frame.center.iter().chain(&new_frame.normal).chain(&new_frame.up).chain(&new_frame.size).all(|v| v.is_finite()); + finite.then_some(out) +} + +/// How far frame projection `proj` reaches in front of and behind its frame, in world units (a warp counts its depth in lengths of the longer side) +fn reach(proj: &Projection) -> Option { + match proj { + Projection::Planar { placed: Some(frame), .. } => Some(frame.depth), + Projection::Warp { frame, depth, .. } => Some(warp_reach(frame.size, *depth)), + _ => None, + } +} + +/// Where frame projection `proj` (a placed planar or a warp) sits on a mesh with bounds `bounds`, its projector folded in (None for other projections) +pub fn placement(proj: &Projection, bounds: (Vec3, Vec3)) -> Option { + let proj = folded(proj)?; + let frame = proj.frame()?; + let (center, radius) = mesh_frame(bounds); + let (origin, across, up, out) = decal_axes(frame)?; + let (z, y, x) = Quat::from_mat3(&Mat3::from_cols(across, up, out)).to_euler(EulerRot::ZYX); + let diagonal = 2.0 * radius; + let placement = FramePlacement { + offset: ((origin - center) / radius).to_array(), + rotation: [x, y, z].map(f32::to_degrees), + scale: [frame.size[0] / diagonal, frame.size[1] / diagonal, reach(&proj)? / diagonal], + }; + let values = placement.offset.iter().chain(&placement.rotation).chain(&placement.scale); + values.copied().all(f32::is_finite).then_some(placement) +} + +/// Frame projection `proj` (a placed planar or a warp) moved to `placement`; its projector's turn and scale are folded in first, its other settings kept (None for other projections or a degenerate placement) +pub fn placed(proj: &Projection, placement: &FramePlacement, bounds: (Vec3, Vec3)) -> Option { + let values = placement.offset.iter().chain(&placement.rotation).chain(&placement.scale); + if !values.copied().all(f32::is_finite) || placement.scale.iter().any(|scale| *scale <= 0.0) { + return None; + } + + let mut proj = folded(proj)?; + let old = *proj.frame()?; + let (center, radius) = mesh_frame(bounds); + let diagonal = 2.0 * radius; + let [x, y, z] = placement.rotation.map(f32::to_radians); + let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x); + let [width, height, deep] = placement.scale.map(|scale| scale * diagonal); + let frame = Decal { + center: (center + Vec3::from(placement.offset) * radius).to_array(), + normal: turn.z_axis.to_array(), + up: turn.y_axis.to_array(), + size: [width, height], + rotation: 0.0, + offset: [0.0; 2], + depth: deep, + symmetry: old.symmetry, + flip: old.flip, + }; + match &mut proj { + Projection::Planar { placed: Some(placed), .. } => *placed = frame, + Projection::Warp { frame: warp, depth, .. } => { + *depth = deep / longer_side([width, height]); + + // The warp's own depth is what reaches; the frame's is unused + *warp = Decal { depth: warp.depth, ..frame }; + } + _ => return None, + } + Some(proj) +} + +/// A frame's turn round its own normal, as seen face on with the world's up (or, looking straight down, the far side) at the top: degrees +pub fn upright_turn(frame: &Decal) -> Option { + let (_, _, up, out) = decal_axes(frame)?; + let world_up = if out.cross(Vec3::Y).length_squared() > MIN_UP_CROSS_SQUARED { Vec3::Y } else { Vec3::NEG_Z }; + let upright = (world_up - out * out.dot(world_up)).try_normalize()?; + let upright_across = upright.cross(out); + let turn = (-up.dot(upright_across)).atan2(up.dot(upright)).to_degrees(); + turn.is_finite().then_some(turn) +} + +#[cfg(test)] +mod tests { + use texturecraft_core::{Backface, DecalFlip, DecalSymmetry, ShapeCrop, UvTransform}; + use texturecraft_geom::glam::Vec2; + + use super::*; + use crate::projector_cover::framed_cover; + + const BOUNDS: (Vec3, Vec3) = (Vec3::new(-1.0, -2.0, -0.5), Vec3::new(3.0, 1.0, 1.5)); + + fn frame() -> Decal { + Decal { + center: [0.4, -0.2, 1.3], + normal: [0.2, 0.1, 1.0], + up: [0.0, 1.0, 0.1], + size: [1.2, 0.8], + rotation: 25.0, + offset: [0.1, -0.2], + depth: 0.6, + symmetry: None, + flip: [false; 2], + } + } + + fn planar(projector: Projector) -> Projection { + Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: Some(frame()) } + } + + fn warp(projector: Projector) -> Projection { + Projection::Warp { frame: frame(), corners: [[-0.6, 0.5], [0.5, 0.4], [0.5, -0.5], [-0.4, -0.5]], depth: 0.7, uv: UvTransform::default(), projector } + } + + /// The projection's texture coordinates and cover at points through the frame's neighbourhood with varied normals + fn samples(proj: &Projection) -> Vec> { + let mut out = Vec::new(); + for across in 0..7 { + for up in 0..7 { + for out_of in 0..3 { + let position = Vec3::new(-0.5 + across as f32 * 0.25, -0.8 + up as f32 * 0.2, 0.7 + out_of as f32 * 0.3); + let normal = Vec3::new(0.1 * across as f32 - 0.3, 0.2, 1.0).normalize(); + out.push(framed_cover(proj, position, normal, (BOUNDS.0 + BOUNDS.1) * 0.5)); + } + } + } + out + } + + fn projector_of(proj: &Projection) -> Projector { + match proj { + Projection::Planar { projector, .. } | Projection::Warp { projector, .. } => *projector, + _ => panic!("a frame projection"), + } + } + + fn close(a: &[Option<(Vec2, f32)>], b: &[Option<(Vec2, f32)>]) { + assert_eq!(a.len(), b.len()); + for (index, (a, b)) in a.iter().zip(b).enumerate() { + match (a, b) { + (Some((uv_a, cover_a)), Some((uv_b, cover_b))) => { + assert!((cover_a - cover_b).abs() < 1e-3, "{index}: cover {cover_a} vs {cover_b}"); + assert!(uv_a.distance(*uv_b) < 1e-3, "{index}: {uv_a} vs {uv_b}"); + } + (None, None) => {} + _ => panic!("{index}: sampled on one side only: {a:?} vs {b:?}"), + } + } + } + + #[test] + fn folding_a_turned_and_evenly_scaled_projector_into_its_frame_lands_the_same() { + let projector = Projector { rotation: [20.0, -35.0, 50.0], scale: [1.7; 3], crop: ShapeCrop::Cropped, ..Projector::default() }; + for proj in [planar(projector), warp(projector)] { + let flat = folded(&proj).unwrap(); + let Projector { rotation, scale, crop, .. } = projector_of(&flat); + assert_eq!((rotation, scale, crop), ([0.0; 3], [1.0; 3], ShapeCrop::Cropped), "the turn and scale moved into the frame, the crop stayed"); + close(&samples(&proj), &samples(&flat)); + } + let unturned = planar(Projector::default()); + assert_eq!(folded(&unturned), Some(unturned), "nothing to fold: unchanged"); + assert_eq!(folded(&Projection::default()), None); + } + + #[test] + fn folding_keeps_what_backface_culling_hides() { + let backface = Backface { on: true, angle: 60.0, hardness: 1.0 }; + let square = Decal { center: [0.0; 3], normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], size: [1.0, 1.0], rotation: 0.0, offset: [0.0; 2], ..frame() }; + + // Half way between across and out: a scale across tilts the culled normal past the angle, a negative one turns it round + let normal = Vec3::new(1.0, 0.0, 1.0).normalize(); + let center = (BOUNDS.0 + BOUNDS.1) * 0.5; + let cover = |proj: &Projection| framed_cover(proj, Vec3::ZERO, normal, center).map(|(_, cover)| cover); + + for scale in [[4.0, 1.0, 1.0], [1.5, -1.5, 1.5], [1.7; 3]] { + let projector = Projector { scale, backface, ..Projector::default() }; + let proj = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: Some(square) }; + match folded(&proj) { + Some(flat) => { + assert_eq!(cover(&proj), cover(&flat), "{scale:?}: culling changed"); + close(&samples(&proj), &samples(&flat)); + } + None => assert!(!culling_folds(&projector), "{scale:?}: only a scale culling cannot keep stays unfolded"), + } + } + + assert!(folded(&planar(Projector { scale: [1.7; 3], backface, ..Projector::default() })).is_some(), "an even scale still folds"); + } + + #[test] + fn a_placement_read_and_written_back_lands_the_same_and_its_fields_move_the_frame() { + let projector = Projector { rotation: [10.0, 0.0, -30.0], scale: [1.2, 0.9, 1.3], ..Projector::default() }; + for proj in [planar(Projector::default()), warp(Projector::default()), planar(projector), warp(projector)] { + let place = placement(&proj, BOUNDS).unwrap(); + let back = placed(&proj, &place, BOUNDS).unwrap(); + close(&samples(&folded(&proj).unwrap()), &samples(&back)); + let again = placement(&back, BOUNDS).unwrap(); + for (a, b) in place.offset.iter().chain(&place.rotation).chain(&place.scale).zip(again.offset.iter().chain(&again.rotation).chain(&again.scale)) { + assert!((a - b).abs() < 1e-3, "{place:?} vs {again:?}"); + } + + let width = folded(&proj).unwrap().frame().unwrap().size[0]; + let bigger = placed(&proj, &FramePlacement { scale: [place.scale[0] * 2.0, place.scale[1], place.scale[2]], ..place }, BOUNDS).unwrap(); + assert!((bigger.frame().unwrap().size[0] - width * 2.0).abs() < 1e-4, "Scale X doubles the width"); + let moved = placed(&proj, &FramePlacement { offset: [0.0; 3], ..place }, BOUNDS).unwrap(); + assert!((Vec3::from(moved.frame().unwrap().center) - Vec3::new(1.0, -0.5, 0.5)).length() < 1e-4, "offset 0 = the mesh's centre"); + } + let place = placement(&planar(Projector::default()), BOUNDS).unwrap(); + assert_eq!(placed(&planar(Projector::default()), &FramePlacement { scale: [0.0, 1.0, 1.0], ..place }, BOUNDS), None, "no zero size"); + assert_eq!(placed(&planar(Projector::default()), &FramePlacement { rotation: [f32::NAN; 3], ..place }, BOUNDS), None); + assert_eq!(placement(&Projection::default(), BOUNDS), None); + } + + #[test] + fn a_frames_upright_turn_is_its_turn_round_its_normal() { + let mut flat = Decal { normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], rotation: 30.0, offset: [0.0; 2], ..frame() }; + assert!((upright_turn(&flat).unwrap() - 30.0).abs() < 1e-3); + flat.rotation = -100.0; + assert!((upright_turn(&flat).unwrap() + 100.0).abs() < 1e-3); + let top = Decal { normal: [0.0, 1.0, 0.0], up: [0.0, 0.0, -1.0], rotation: 0.0, ..frame() }; + assert!(upright_turn(&top).unwrap().abs() < 1e-3, "seen from above the far side is up"); + } + + #[test] + fn folding_and_placing_keep_a_frames_mirror_copy_and_image_flip() { + let symmetry = Some(DecalSymmetry { axis: 0, flip: DecalFlip::V, offset: 0.2 }); + let mirrored = Decal { symmetry, flip: [true, false], ..frame() }; + let turned = Projector { rotation: [10.0, 0.0, -30.0], scale: [1.2, 0.9, 1.3], ..Projector::default() }; + for proj in [ + Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: turned, placed: Some(mirrored) }, + Projection::Warp { + frame: mirrored, + corners: [[-0.6, 0.5], [0.5, 0.4], [0.5, -0.5], [-0.4, -0.5]], + depth: 0.7, + uv: UvTransform::default(), + projector: turned, + }, + ] { + let folded = folded(&proj).unwrap(); + let moved = placed(&proj, &placement(&proj, BOUNDS).unwrap(), BOUNDS).unwrap(); + for frame in [folded.frame().unwrap(), moved.frame().unwrap()] { + assert_eq!((frame.symmetry, frame.flip), (symmetry, [true, false])); + } + } + } +} diff --git a/crates/compose/src/warp.rs b/crates/compose/src/warp.rs new file mode 100644 index 00000000..29a1ec95 --- /dev/null +++ b/crates/compose/src/warp.rs @@ -0,0 +1,96 @@ +//! Where a point in a warp projection's frame lands in its image: the inverse of the bilinear quad its four corners make + +use texturecraft_geom::glam::Vec2; + +/// Texture coordinates (v down) of the point `p` (across and up in frame sizes) inside the quad `corners` makes (top left, top right, bottom right, bottom left); past the quad they run on, so the image can repeat. None where no texture coordinates land +pub fn warp_uv(corners: &[[f32; 2]; 4], p: Vec2) -> Option { + let [a, b, c, d] = corners.map(Vec2::from); + let (e, f, g, h) = (b - a, d - a, a - b + c - d, p - a); + let k2 = g.perp_dot(f); + let k1 = e.perp_dot(f) + h.perp_dot(g); + let k0 = h.perp_dot(e); + let uv = if k2.abs() < PARALLEL { + // Opposite edges parallel: the quad's equation is linear in v + let v = -k0 / k1; + Vec2::new(across(e, f, g, h, v)?, v) + } else { + let discriminant = k1 * k1 - 4.0 * k0 * k2; + if discriminant < 0.0 { + return None; + } + + let root = discriminant.sqrt(); + let near = |v: f32| across(e, f, g, h, v).map(|u| Vec2::new(u, v)); + + // Two solutions, neither found by subtracting near-equal values (which loses the answer when the quad is nearly a parallelogram): keep the one nearer the quad + let q = -0.5 * (k1 + root.copysign(k1)); + // q is 0 only for a double root at 0, which q / k2 still finds (k0 / q is then not finite, so no candidate) + let candidates = [near(q / k2), near(k0 / q)]; + candidates.into_iter().flatten().min_by(|x, y| outside(*x).total_cmp(&outside(*y)))? + }; + uv.is_finite().then_some(uv) +} + +/// How far across (u) a point lies at height `v`, solved on whichever axis the quad's edge spans most +fn across(e: Vec2, f: Vec2, g: Vec2, h: Vec2, v: f32) -> Option { + let span = e + g * v; + let u = if span.x.abs() >= span.y.abs() { (h.x - f.x * v) / span.x } else { (h.y - f.y * v) / span.y }; + u.is_finite().then_some(u) +} + +/// How far `uv` lies outside the image's 0..1 square (0 inside) +fn outside(uv: Vec2) -> f32 { + (uv - uv.clamp(Vec2::ZERO, Vec2::ONE)).length_squared() +} + +/// Below this, a quad's opposite edges count as parallel (frame sizes squared) +const PARALLEL: f32 = 1e-6; + +#[cfg(test)] +mod tests { + use super::*; + + const FRAME: [[f32; 2]; 4] = [[-0.5, 0.5], [0.5, 0.5], [0.5, -0.5], [-0.5, -0.5]]; + + /// The point at texture coordinates `uv` inside the quad `corners` + fn bilinear(corners: &[[f32; 2]; 4], uv: Vec2) -> Vec2 { + let [a, b, c, d] = corners.map(Vec2::from); + let top = a.lerp(b, uv.x); + let bottom = d.lerp(c, uv.x); + top.lerp(bottom, uv.y) + } + + #[test] + fn the_unpulled_frame_maps_like_a_planar_frame() { + for (x, y) in [(0.0, 0.0), (-0.5, 0.5), (0.25, -0.4), (1.3, 0.7), (-2.0, -1.5)] { + assert_eq!(warp_uv(&FRAME, Vec2::new(x, y)), Some(Vec2::new(x + 0.5, 0.5 - y)), "{x} {y}"); + } + } + + #[test] + fn pulled_corners_bend_the_image_to_their_quad() { + let quads = [ + [[-0.6, 0.4], [0.5, 0.7], [0.3, -0.5], [-0.4, -0.45]], + [[-0.5, 0.5], [0.9, 0.5], [0.5, -0.5], [-0.5, -0.5]], + [[-0.2, 0.6], [0.2, 0.6], [0.7, -0.6], [-0.7, -0.6]], + // Nearly a parallelogram: one corner a hair out + [[0.0, 0.0], [1.0, 0.0], [1.0 + 1.0 / 262_144.0, 1.0], [0.0, 1.0]], + ]; + for quad in quads { + for i in 0..=10 { + for j in 0..=10 { + let uv = Vec2::new(i as f32 / 10.0, j as f32 / 10.0); + let found = warp_uv(&quad, bilinear(&quad, uv)).unwrap_or(Vec2::NAN); + assert!((found - uv).length() < 1e-4, "{quad:?} {uv}: {found}"); + } + } + } + } + + #[test] + fn a_collapsed_quad_lands_nowhere_instead_of_failing() { + let point = [[0.0, 0.0]; 4]; + assert_eq!(warp_uv(&point, Vec2::new(0.3, 0.2)), None); + assert_eq!(warp_uv(&[[f32::NAN; 2]; 4], Vec2::ZERO), None); + } +} diff --git a/crates/core/src/saved_decal.rs b/crates/core/src/saved_decal.rs new file mode 100644 index 00000000..c8c7a0b6 --- /dev/null +++ b/crates/core/src/saved_decal.rs @@ -0,0 +1,11 @@ +//! A decal written in the shape saved before decals were planar projections + +use serde::Serialize; + +use crate::Decal; + +/// A decal in the shape saved before decals were planar projections +#[derive(Serialize)] +pub(crate) enum SavedDecal<'a> { + Decal(&'a Decal), +} diff --git a/crates/engine/src/decal_cmds.rs b/crates/engine/src/decal_cmds.rs index 392da975..d49e7afe 100644 --- a/crates/engine/src/decal_cmds.rs +++ b/crates/engine/src/decal_cmds.rs @@ -1,13 +1,17 @@ //! Geometry decals: an image resource projected onto the surface from a frame placed on it -//! (a decal fill with a planar projection), as a fill layer with a decal projection. +//! (a decal fill with a planar projection), as a fill layer with a decal projection, and moving +//! the frame of any planar or warp projection use serde_json::{Value, json}; +use texturecraft_compose::axis_frame::{placed_from_axis, placing_moves_pattern}; +use texturecraft_compose::frame_placement::{MIN_FRAME_SIDE, culling_folds, folded, longer_side, placed, placement as frame_placement}; use texturecraft_core::{ Channel, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Layer, LayerId, LayerKind, Mask, MaskBackground, Projection, Source, }; use texturecraft_geom::glam::{Quat, Vec2, Vec3}; use crate::commands::{CommandSpec, always, bad, boolp, channel_param, f32p, layer_param, strp, u64p, vec3}; +use crate::layer_cmds::{FULL_TURN_DEGREES, MAX_PROJECTION_DEPTH}; use crate::tool_cmds::viewport_of; use crate::{Result, Session, StackTarget, cmd}; @@ -27,7 +31,7 @@ pub fn specs() -> Vec { "Edit decal", [], None, - "{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer), x?, y?, viewport? | position?, normal? (re-place it on its own texture set), up?: [x,y,z] (default: the decal's up carried along when it moves onto a surface facing another way), size?: height | [w,h], keepProportions?: true keeps the image's aspect (the current ratio without an image): a height sets the width, a [w,h] pair or no size sets the height from the width, flipU?, flipV?: mirror the image left to right / top to bottom inside the frame, rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, symmetry?: x|y|z|off, symmetryFlip?: none|u|v, symmetryOffset? (the mirrored copy; the flip and offset alone keep the axis), image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags)}", + "{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer) — any fill with a planar or warp projection: moves the frame it projects from (an axis planar is first placed as the frame it projects from, reading images exactly as before; a warp keeps its corners), x?, y?, viewport? | position?, normal? (re-place it on its own texture set), up?: [x,y,z] (default: the decal's up carried along when it moves onto a surface facing another way), size?: height | [w,h], keepProportions?: true keeps the image's aspect (the current ratio without an image): a height sets the width, a [w,h] pair or no size sets the height from the width, flipU?, flipV?: mirror the image left to right / top to bottom inside the frame, rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?: world units (a warp: its Projection Depth becomes this over the frame's longer side), frameOffset?: [x, y, z] (the frame's centre in mesh radii from the mesh's centre), frameRotation?: [x, y, z] degrees (its turn: unturned it faces +Z with +Y up), frameScale?: [width, height, reach] (in mesh diagonals; reach = how far it projects in front of and behind it, a warp's Projection Depth times its longer side) — the frame as the 3D projection settings show it, applied before the other fields; any projector turn or scale is first folded into the frame (it lands the same); refused: an axis planar reading a procedural (placing it would move the pattern) and, under backface culling with an uneven or mirrored projector scale, placing an axis planar or the frame fields (even the scale out or turn culling off), symmetry?: x|y|z|off, symmetryFlip?: none|u|v, symmetryOffset? (the mirrored copy; the flip and offset alone keep the axis), image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags); a call that changes nothing adds no undo step}", always, set ), @@ -62,15 +66,24 @@ const MIN_SIZE: f32 = 1e-4; /// The largest decal side or depth, relative to the mesh diagonal const MAX_SIZE: f32 = 10.0; +/// The smallest mesh diagonal decal sizes count in, so a collapsed mesh still places one +const MIN_MESH_DIAGONAL: f32 = 1e-3; + +/// A given `up` this near the normal (squared sine of the angle between them) leaves no upright direction +const MIN_GIVEN_UP_CROSS_SQUARED: f32 = 1e-8; + +/// The camera's up this near the normal (squared sine) is a top face seen from the front: up is where the camera looks +const MIN_CAMERA_UP_CROSS_SQUARED: f32 = 1e-4; + /// The mesh's diagonal (decal sizes are relative to it). -fn mesh_size(s: &Session) -> f32 { - let (lo, hi) = s.mesh.bounds(); - (hi - lo).length().max(1e-3) +fn mesh_size(session: &Session) -> f32 { + let (lo, hi) = session.mesh.bounds(); + (hi - lo).length().max(MIN_MESH_DIAGONAL) } /// Width and height from a `size` param (a height keeping `aspect`, or `[w, h]`), within the decal size limits -fn size_param(p: &Value, aspect: f32, mesh_diagonal: f32) -> Option<[f32; 2]> { - let value = p.get("size")?; +fn size_param(params: &Value, aspect: f32, mesh_diagonal: f32) -> Option<[f32; 2]> { + let value = params.get("size")?; let size = match value.as_array() { Some(pair) => [pair.first()?.as_f64()? as f32, pair.get(1)?.as_f64()? as f32], None => { @@ -84,13 +97,16 @@ fn size_param(p: &Value, aspect: f32, mesh_diagonal: f32) -> Option<[f32; 2]> { /// The decal's up direction: `up` when given, else the camera's (decals are placed upright on /// screen), or where the camera looks when that is along `normal` (a top face seen from the /// front: its far edge is up, as on a table). -fn decal_up(s: &Session, cmd: &str, p: &Value, normal: Vec3) -> Result { - if p.get("up").is_some() { - return vec3(p, "up").filter(|u| u.cross(normal).length_squared() > 1e-8).ok_or_else(|| bad(cmd, "`up` must be [x, y, z], not along the normal")); +fn decal_up(session: &Session, command: &str, params: &Value, normal: Vec3) -> Result { + if params.get("up").is_some() { + return vec3(params, "up") + .filter(|up| up.cross(normal).length_squared() > MIN_GIVEN_UP_CROSS_SQUARED) + .ok_or_else(|| bad(command, "`up` must be [x, y, z], not along the normal")); } - let to_world = s.camera.view().inverse(); + + let to_world = session.camera.view().inverse(); let up = to_world.transform_vector3(Vec3::Y); - Ok(if up.normalize_or_zero().cross(normal).length_squared() > 1e-4 { up } else { to_world.transform_vector3(Vec3::NEG_Z) }) + Ok(if up.normalize_or_zero().cross(normal).length_squared() > MIN_CAMERA_UP_CROSS_SQUARED { up } else { to_world.transform_vector3(Vec3::NEG_Z) }) } /// The mirrored copy asked for by `symmetry` (x, y, z or off) and `symmetryFlip` (none, u or v), @@ -143,87 +159,197 @@ fn carried_up(s: &Session, from: (Vec3, Vec3), to: Vec3) -> Vec3 { Quat::from_rotation_arc(old_normal, new_normal) * old_up } -fn add(s: &mut Session, p: &Value) -> Result { - let cmd = "layer.add.decal"; - let image = strp(p, "image").ok_or_else(|| bad(cmd, "`image` is required"))?.to_string(); - let resource = s.images.get(&image).ok_or_else(|| bad(cmd, format!("no image resource `{image}` (import it first)")))?; +fn add(session: &mut Session, params: &Value) -> Result { + let command = "layer.add.decal"; + let image = strp(params, "image").ok_or_else(|| bad(command, "`image` is required"))?.to_string(); + let resource = session.images.get(&image).ok_or_else(|| bad(command, format!("no image resource `{image}` (import it first)")))?; let aspect = resource.width as f32 / resource.height.max(1) as f32; - let (center, normal, ts) = placement(s, cmd, p, s.ts(), false)?.ok_or_else(|| bad(cmd, "no placement"))?; + let (center, normal, texture_set) = placement(session, command, params, session.ts(), false)?.ok_or_else(|| bad(command, "no placement"))?; // None: the image masks a new fill layer - let target = match strp(p, "channel") { + let target = match strp(params, "channel") { Some("mask") => None, - _ => Some(channel_param(cmd, p, "channel")?.unwrap_or(Channel::BaseColor)), + _ => Some(channel_param(command, params, "channel")?.unwrap_or(Channel::BaseColor)), }; - let set_channels = s.doc.project.texture_set(ts)?.channel_list(); + let set_channels = session.doc.project.texture_set(texture_set)?.channel_list(); if let Some(channel) = target && !set_channels.contains(&channel) { - return Err(bad(cmd, format!("the texture set has no {} channel", channel.label()))); + return Err(bad(command, format!("the texture set has no {} channel", channel.label()))); } - let mesh_diagonal = mesh_size(s); + let mesh_diagonal = mesh_size(session); let default_height = mesh_diagonal * DEFAULT_HEIGHT; - let mut size = size_param(p, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]); - if boolp(p, "keepProportions") == Some(true) && p.get("size").is_some_and(Value::is_array) { + let mut size = size_param(params, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]); + if boolp(params, "keepProportions") == Some(true) && params.get("size").is_some_and(Value::is_array) { size[1] = (size[0] / aspect).clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE); } let decal = Decal { center: center.to_array(), normal: normal.to_array(), - up: decal_up(s, cmd, p, normal)?.to_array(), + up: decal_up(session, command, params, normal)?.to_array(), size, - rotation: f32p(p, "rotation").unwrap_or(0.0).rem_euclid(360.0), + rotation: f32p(params, "rotation").unwrap_or(0.0).rem_euclid(FULL_TURN_DEGREES), offset: [0.0; 2], - flip: [boolp(p, "flipU").unwrap_or(false), boolp(p, "flipV").unwrap_or(false)], + flip: [boolp(params, "flipU").unwrap_or(false), boolp(params, "flipV").unwrap_or(false)], // By default it reaches half its larger side into the surface - depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)), - symmetry: symmetry_param(cmd, p, None, s.mesh.bounds())?, + depth: f32p(params, "depth").map_or(size[0].max(size[1]) * 0.5, |depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)), + symmetry: symmetry_param(command, params, None, session.mesh.bounds())?, }; // A decal dropped on another texture set goes there and selects it, as a dropped material does - if ts != s.ts() { - crate::set_cmds::select_set(s, ts)?; + if texture_set != session.ts() { + crate::set_cmds::select_set(session, texture_set)?; } - let base = strp(p, "name") + let base = strp(params, "name") .map(str::to_string) .unwrap_or_else(|| std::path::Path::new(&image).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Decal").to_string()); - let name = s.doc.project.next_layer_name(ts, &base); - let (id, mask_effect) = s.edit("Add decal", |s| { - let id = s.doc.project.alloc_id(); + let name = session.doc.project.next_layer_name(texture_set, &base); + let (id, mask_effect) = session.edit("Add decal", |session| { + let id = session.doc.project.alloc_id(); let Some(channel) = target else { - let effect_id = s.doc.project.alloc_id(); + let effect_id = session.doc.project.alloc_id(); let mut layer = Layer::new(id, name, LayerKind::Fill(Fill::default()), &set_channels); let mut mask = Mask::new(MaskBackground::Black); - mask.effects.push(Effect::new(effect_id, EffectKind::Fill { source: Source::image(image.clone()), projection: Projection::Decal(decal) })); + mask.effects.push(Effect::new( + effect_id, + EffectKind::Fill { source: Source::image(image.clone()), projection: Projection::decal(decal), sampling: Default::default() }, + )); layer.mask = Some(mask); - crate::layer_cmds::insert_selected(s, layer)?; - s.target = StackTarget::Effect(effect_id); + crate::layer_cmds::insert_selected(session, layer)?; + session.target = StackTarget::Effect(effect_id); return Ok((id, Some(effect_id))); }; - let mut fill = Fill { projection: Projection::Decal(decal), ..Fill::default() }; + let mut fill = Fill { projection: Projection::decal(decal), ..Fill::default() }; fill.sources.insert(channel, Source::image(image.clone())); - crate::layer_cmds::insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &[channel]))?; + crate::layer_cmds::insert_selected(session, Layer::new(id, name, LayerKind::Fill(fill), &[channel]))?; Ok((id, None)) })?; Ok(json!({ "layer": id.0, "decal": decal, "maskEffect": mask_effect.map(|effect| effect.0) })) } -/// The decal of fill layer `id`, or of mask fill effect `effect` when given -fn decal_of(s: &Session, cmd: &str, id: LayerId, effect: Option) -> Result { - if let Some(effect) = effect { - return match s.doc.project.effect(effect).map(|(_, effect)| &effect.kind) { - Some(EffectKind::Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal), - _ => Err(bad(cmd, "the effect is not a decal (layer.add.decal with channel mask)")), - }; +/// The projection of fill layer `id`, or of mask fill effect `effect` when given, with the frame it projects from: an axis planar is placed as the frame it already projects from (it reads images exactly as before), a turned or scaled projector is folded into its frame +fn framed(session: &Session, command: &str, id: LayerId, effect: Option) -> Result<(Projection, Decal)> { + let projection = stored_projection(session, command, id, effect)?; + if matches!(projection, Projection::Planar { placed: None, .. }) && placing_moves_pattern(stored_sources(session, id, effect).into_iter()) { + return Err(bad(command, "an axis planar reading a procedural pattern keeps its axis: placing its frame would move the pattern")); } - match &s.doc.project.layer(id)?.kind { - LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal), - _ => Err(bad(cmd, "the layer is not a decal (layer.add.decal)")), + // A frame faces one way: culling read through an uneven or mirrored scale would hide other faces once the scale is in the frame (a placed frame keeps its edits that move no frame) + if matches!(projection, Projection::Planar { placed: None, .. }) && !culling_keeps_facing(projection) { + return Err(bad(command, UNFOLDABLE_CULLING)); + } + + let projection = placed_from_axis(projection, session.mesh.bounds()).unwrap_or_else(|| projection.clone()); + + // The frame moves as it lands: a projector's own turn and scale go into it first + let projection = folded(&projection).unwrap_or(projection); + let frame = projection + .frame() + .copied() + .ok_or_else(|| bad(command, "the projection has no frame: a planar or warp projection has one (layer.add.decal places one)"))?; + Ok((projection, frame)) +} + +/// Whether `projection`'s backface culling keeps its facing once its projector's turn and scale are in its frame +fn culling_keeps_facing(projection: &Projection) -> bool { + match projection { + Projection::Planar { projector, .. } | Projection::Warp { projector, .. } => culling_folds(projector), + _ => true, + } +} + +/// Why a projector whose backface culling cannot keep its facing in a frame is not moved, and the way out +const UNFOLDABLE_CULLING: &str = + "backface culling under an uneven or mirrored projector scale cannot move into a frame: even out the projector scale or turn backface culling off"; + +/// The projection fill layer `id`, or mask fill effect `effect` when given, holds +fn stored_projection<'a>(session: &'a Session, command: &str, id: LayerId, effect: Option) -> Result<&'a Projection> { + match effect { + Some(effect) => match session.doc.project.effect(effect).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Fill { projection, .. }) => Ok(projection), + _ => Err(bad(command, "the effect is not a mask fill effect")), + }, + None => match &session.doc.project.layer(id)?.kind { + LayerKind::Fill(fill) => Ok(&fill.projection), + _ => Err(bad(command, "the layer is not a fill layer")), + }, + } +} + +/// The sources fill layer `id`, or mask fill effect `effect` when given, reads +fn stored_sources(session: &Session, id: LayerId, effect: Option) -> Vec<&Source> { + match effect { + Some(effect) => match session.doc.project.effect(effect).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Fill { source, .. }) => vec![source], + _ => Vec::new(), + }, + None => match session.doc.project.layer(id).map(|layer| &layer.kind) { + Ok(LayerKind::Fill(fill)) => fill.sources.values().collect(), + _ => Vec::new(), + }, + } +} + +/// The image a decal projects: the mask fill effect's, or the fill layer's (the channel it was placed in) +fn placed_image(session: &Session, id: LayerId, effect: Option) -> Option { + let image_name = |source: &Source| match source { + Source::Image { name, .. } => Some(name.clone()), + _ => None, + }; + match effect { + Some(effect) => match session.doc.project.effect(effect).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Fill { source, .. }) => image_name(source), + _ => None, + }, + None => match &session.doc.project.layer(id).ok()?.kind { + LayerKind::Fill(fill) => fill.sources.values().find_map(image_name), + _ => None, + }, + } +} + +/// `projection` with its frame where `frameOffset`, `frameRotation` and `frameScale` put it (None when none is given) +fn placed_as_shown(session: &Session, command: &str, params: &Value, projection: &Projection) -> Result> { + let fields = ["frameOffset", "frameRotation", "frameScale"]; + if fields.iter().all(|key| params.get(*key).is_none()) { + return Ok(None); + } + + let read = |key: &str| match params.get(key) { + None => Ok(None), + Some(_) => vec3(params, key).map(Some).ok_or_else(|| bad(command, format!("`{key}` must be [x, y, z]"))), + }; + let bounds = session.mesh.bounds(); + if !culling_keeps_facing(projection) { + return Err(bad(command, UNFOLDABLE_CULLING)); + } + + let mut shown = frame_placement(projection, bounds).ok_or_else(|| bad(command, "the frame is degenerate"))?; + if let Some(offset) = read("frameOffset")? { + shown.offset = offset.clamp(Vec3::splat(-MAX_FRAME_OFFSET), Vec3::splat(MAX_FRAME_OFFSET)).to_array(); + } + if let Some(rotation) = read("frameRotation")? { + shown.rotation = rotation.clamp(Vec3::splat(-FULL_TURN_DEGREES), Vec3::splat(FULL_TURN_DEGREES)).to_array(); + } + if let Some(scale) = read("frameScale")? { + shown.scale = scale.clamp(Vec3::splat(MIN_SIZE), Vec3::splat(MAX_SIZE)).to_array(); + } + placed(projection, &shown, bounds).map(Some).ok_or_else(|| bad(command, "that frame is degenerate")) +} + +/// How far from the mesh's centre `frameOffset` may put a frame, in mesh radii +const MAX_FRAME_OFFSET: f32 = 100.0; + +/// `projection` projecting from `frame`, its other settings kept +fn move_frame(projection: &mut Projection, frame: Decal) { + match projection { + Projection::Planar { placed: Some(placed), .. } => *placed = frame, + Projection::Warp { frame: warp, .. } => *warp = frame, + _ => {} } } @@ -261,10 +387,19 @@ fn set(session: &mut Session, params: &Value) -> Result { return Err(bad(command, format!("effect {} is not in layer {layer}", effect.0))); } - let mut decal = decal_of(session, command, layer_id, effect)?; + let (mut projection, mut decal) = framed(session, command, layer_id, effect)?; let texture_set = session.doc.project.locate(layer_id).map(|(texture_set, _, _)| texture_set).ok_or_else(|| bad(command, "the decal has no texture set"))?; let mesh_diagonal = mesh_size(session); + if let Some(moved) = placed_as_shown(session, command, params, &projection)? { + projection = moved; + decal = projection.frame().copied().ok_or_else(|| bad(command, "the projection lost its frame"))?; + + // A reach from frameScale keeps the Projection Depth in the range every other path keeps + if let Projection::Warp { depth: warp_depth, .. } = &mut projection { + *warp_depth = warp_depth.clamp(0.0, MAX_PROJECTION_DEPTH); + } + } if let Some((center, normal, hit_set)) = placement(session, command, params, texture_set, true)? { // Selecting another set must not let this decal leave its layer's stack if hit_set != texture_set { @@ -282,7 +417,7 @@ fn set(session: &mut Session, params: &Value) -> Result { decal.up = decal_up(session, command, params, Vec3::from(decal.normal))?.to_array(); } let keep = boolp(params, "keepProportions") == Some(true); - let ratio = decal.size[0] / decal.size[1].max(1e-6); + let ratio = decal.size[0] / decal.size[1].max(MIN_FRAME_SIDE); let aspect = if keep { image_aspect(session, layer_id, effect, strp(params, "image")).unwrap_or(ratio) } else { ratio }; if let Some(mut size) = size_param(params, aspect, mesh_diagonal).or_else(|| keep.then_some(decal.size)) { // A height sets the width through `aspect`; a pair or the current size sets the height from the width @@ -298,7 +433,7 @@ fn set(session: &mut Session, params: &Value) -> Result { decal.flip[1] = flip; } if let Some(rotation) = f32p(params, "rotation") { - decal.rotation = rotation.rem_euclid(360.0); + decal.rotation = rotation.rem_euclid(FULL_TURN_DEGREES); } if let Some(offset) = params.get("offset").and_then(Value::as_array) { let values: Vec = offset.iter().filter_map(Value::as_f64).map(|value| value as f32).filter(|value| value.is_finite()).collect(); @@ -306,8 +441,13 @@ fn set(session: &mut Session, params: &Value) -> Result { decal.offset = [right.clamp(-mesh_diagonal, mesh_diagonal), up.clamp(-mesh_diagonal, mesh_diagonal)]; } - if let Some(depth) = f32p(params, "depth") { - decal.depth = depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE); + let depth = f32p(params, "depth").map(|depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)); + + // A warp reaches by its Projection Depth (set below); its frame's own depth is unused, so it stays + if let Some(depth) = depth + && !matches!(projection, Projection::Warp { .. }) + { + decal.depth = depth; } decal.symmetry = symmetry_param(command, params, decal.symmetry, session.mesh.bounds())?; @@ -318,39 +458,56 @@ fn set(session: &mut Session, params: &Value) -> Result { return Err(bad(command, format!("no image resource `{name}`"))); } - session.edit("Edit decal", |session| { - if let Some(effect) = effect { - if let Some(EffectKind::Fill { source, projection }) = session.doc.project.effect_mut(effect).map(|effect| &mut effect.kind) { - *projection = Projection::Decal(decal); - if let Some(image) = image { - *source = Source::image(image); - } - } - } else if let LayerKind::Fill(fill) = &mut session.doc.project.layer_mut(layer_id)?.kind { - fill.projection = Projection::Decal(decal); + move_frame(&mut projection, decal); - // The new image goes where the decal's image is (the channel it was placed in) - let placed = fill.sources.values().find_map(|source| match source { - Source::Image { name, .. } => Some(name.clone()), - _ => None, - }); - match (image, placed) { - (Some(image), Some(placed)) => { - for source in fill.sources.values_mut() { - if let Source::Image { name, .. } = source - && *name == placed - { - name.clone_from(&image); - } - } - } - (Some(image), None) => { - fill.sources.insert(Channel::BaseColor, Source::image(image)); - } - (None, _) => {} - } - } - Ok(()) - })?; + // A warp reaches by its own Projection Depth, in lengths of the frame's longer side + if let (Some(depth), Projection::Warp { depth: warp_depth, .. }) = (depth, &mut projection) { + *warp_depth = (depth / longer_side(decal.size)).clamp(0.0, MAX_PROJECTION_DEPTH); + } + + // Nothing moved and the image is the one it shows: no undo step + let unchanged = *stored_projection(session, command, layer_id, effect)? == projection + && image.as_ref().is_none_or(|image| placed_image(session, layer_id, effect).as_ref() == Some(image)); + if !unchanged { + session.edit("Edit decal", |session| store_decal(session, layer_id, effect, projection, image))?; + } Ok(json!({ "layer": layer_id.0, "decal": decal })) } + +/// Store `projection` (and `image`, in the channel or mask it was placed in) on fill layer `layer_id`, or on mask fill effect `effect` when given +fn store_decal(session: &mut Session, layer_id: LayerId, effect: Option, projection: Projection, image: Option) -> Result<()> { + if let Some(effect) = effect { + if let Some(EffectKind::Fill { source, projection: stored, .. }) = session.doc.project.effect_mut(effect).map(|effect| &mut effect.kind) { + *stored = projection; + if let Some(image) = image { + *source = Source::image(image); + } + } + return Ok(()); + } + + let LayerKind::Fill(fill) = &mut session.doc.project.layer_mut(layer_id)?.kind else { return Ok(()) }; + fill.projection = projection; + + // The new image goes where the decal's image is (the channel it was placed in) + let placed = fill.sources.values().find_map(|source| match source { + Source::Image { name, .. } => Some(name.clone()), + _ => None, + }); + match (image, placed) { + (Some(image), Some(placed)) => { + for source in fill.sources.values_mut() { + if let Source::Image { name, .. } = source + && *name == placed + { + name.clone_from(&image); + } + } + } + (Some(image), None) => { + fill.sources.insert(Channel::BaseColor, Source::image(image)); + } + (None, _) => {} + } + Ok(()) +} diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/warp_cmds.rs new file mode 100644 index 00000000..71d0f051 --- /dev/null +++ b/crates/engine/src/warp_cmds.rs @@ -0,0 +1,68 @@ +//! Warp projections: the frame a new warp starts from, and Reset frame, which puts a warp's frame and corners back there + +use serde_json::Value; +use texturecraft_core::{Decal, Projection}; +use texturecraft_geom::Mesh; + +use crate::commands::{CommandSpec, bad, has_layer}; +use crate::layer_cmds::{fill_target, placement_mut}; +use crate::{Result, Session, cmd}; + +/// Reset frame's command id, the prefix of its errors +const RESET_FRAME: &str = "layer.fill.resetFrame"; + +pub fn specs() -> Vec { + vec![cmd!( + "layer.fill.resetFrame", + "Reset frame", + [], + None, + has_layer, + reset_frame + )] +} + +/// The frame a new warp projection starts from: around the whole mesh, seen from the front (+Z), up along +Y +pub(crate) fn fitted_frame(mesh: &Mesh) -> Decal { + let (lo, hi) = mesh.bounds(); + let smallest = ((hi - lo).length() * SMALLEST_SIDE).max(f32::MIN_POSITIVE); + let size = [(hi.x - lo.x).max(smallest), (hi.y - lo.y).max(smallest)]; + Decal { + center: ((lo + hi) * 0.5).to_array(), + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size, + rotation: 0.0, + offset: [0.0; 2], + depth: 0.0, + symmetry: None, + flip: [false; 2], + } +} + +/// A fitted frame's smallest side, relative to the mesh diagonal (a flat mesh still gets a frame) +const SMALLEST_SIDE: f32 = 1e-3; + +fn reset_frame(s: &mut Session, p: &Value) -> Result { + let target = fill_target(s, p, RESET_FRAME)?; + let fitted = fitted_frame(&s.mesh); + let (Projection::Warp { frame, corners, .. }, _) = placement_mut(s, target)? else { + return Err(bad(RESET_FRAME, "the fill's projection is not a warp projection")); + }; + + // A frame already fitted with unpulled corners adds no undo step + if *frame == fitted && *corners == Projection::FRAME_CORNERS { + return Ok(Value::Null); + } + + s.edit("Reset frame", |s| { + let (Projection::Warp { frame, corners, .. }, _) = placement_mut(s, target)? else { + return Err(bad(RESET_FRAME, "the fill's projection is not a warp projection")); + }; + + *frame = fitted; + *corners = Projection::FRAME_CORNERS; + Ok(()) + })?; + Ok(Value::Null) +} diff --git a/crates/ui-egui/src/warp_checker.rs b/crates/ui-egui/src/warp_checker.rs new file mode 100644 index 00000000..70421b23 --- /dev/null +++ b/crates/ui-egui/src/warp_checker.rs @@ -0,0 +1,169 @@ +//! The checker a warp preview bends into its frame: laid on the frame as the fill's Tiling, Rotation and Offset lay the image, so turning or tiling the image shows + +use egui::Pos2; +use texturecraft_engine::compose::pattern::FRAME_UV_CENTER; +use texturecraft_engine::paint::FULL_TURN_DEGREES; + +use crate::fill_pictures::PREVIEW_MIN_TILES; +use crate::placement::Placement; +use crate::projection_preview::CHECKER_CELLS; + +/// Most repeats drawn across the frame: beyond this the checker is too fine to read and too many cells to draw each frame +const MAX_TILES: f32 = 6.0; + +/// The checker cells inside a frame whose corners land at `quad` (top left, top right, bottom right, bottom left), each with whether it is a light cell: a cell's corners in image coordinates go back to the frame (undo the offset, the tiling, the turn), are cut to the frame and bent with its corners +pub(crate) fn warp_checker(quad: [Pos2; 4], placement: Placement) -> Vec<(Vec, bool)> { + let [top_left, top_right, bottom_right, bottom_left] = quad; + let at = |[u, v]: [f32; 2]| -> Pos2 { + let top = top_left + (top_right - top_left) * u; + let bottom = bottom_left + (bottom_right - bottom_left) * u; + top + (bottom - top) * v + }; + let tiling = placement.tiling.map(|tiles| if tiles.is_finite() { tiles.clamp(PREVIEW_MIN_TILES, MAX_TILES) } else { 1.0 }); + + // The checker repeats every tile, so only the offset within one tile matters (and the cell numbers stay small) + let offset = placement.offset.map(|offset| if offset.is_finite() { offset.rem_euclid(1.0) } else { 0.0 }); + let rotation = if placement.rotation.is_finite() { placement.rotation.rem_euclid(FULL_TURN_DEGREES) } else { 0.0 }; + let (sin, cos) = rotation.to_radians().sin_cos(); + let [middle_u, middle_v] = FRAME_UV_CENTER.to_array(); + + // The frame (0..1 across and down) → image coordinates in cells: turn round the frame's centre, tile, offset, as the compositor places a warp's image + let to_cells = |[u, v]: [f32; 2]| -> [f32; 2] { + let (u, v) = (u - middle_u, v - middle_v); + let (x, y) = (u * cos - v * sin + middle_u, u * sin + v * cos + middle_v); + [(x * tiling[0] + offset[0]) * CHECKER_CELLS, (y * tiling[1] + offset[1]) * CHECKER_CELLS] + }; + let to_frame = |[x, y]: [f32; 2]| -> [f32; 2] { + let (x, y) = ((x / CHECKER_CELLS - offset[0]) / tiling[0] - middle_u, (y / CHECKER_CELLS - offset[1]) / tiling[1] - middle_v); + [x * cos + y * sin + middle_u, -x * sin + y * cos + middle_v] + }; + let corners = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]].map(to_cells); + let low = |axis: usize| corners.iter().map(|corner| corner[axis]).fold(f32::INFINITY, f32::min).floor() as i32; + let high = |axis: usize| corners.iter().map(|corner| corner[axis]).fold(f32::NEG_INFINITY, f32::max).ceil() as i32; + let mut cells = Vec::new(); + + // One outline and one cutting buffer for every cell: only the drawn outlines are kept + let mut outline = Vec::with_capacity(CLIPPED_CORNERS_MAX); + let mut scratch = Vec::with_capacity(CLIPPED_CORNERS_MAX); + for x in low(0)..high(0) { + for y in low(1)..high(1) { + let (x0, y0) = (x as f32, y as f32); + outline.clear(); + outline.extend([[x0, y0], [x0 + 1.0, y0], [x0 + 1.0, y0 + 1.0], [x0, y0 + 1.0]].map(to_frame)); + clip_to_frame(&mut outline, &mut scratch); + if area(&outline) > MIN_CELL_AREA { + cells.push((outline.iter().copied().map(at).collect(), (x + y).rem_euclid(2) == 0)); + } + } + } + cells +} + +/// Most corners a cell keeps once cut: its four, plus one for each side of the frame that cuts it +const CLIPPED_CORNERS_MAX: usize = 8; + +/// Least share of the frame a cut cell must cover to be drawn (slivers left by rounding at the frame's sides are not) +const MIN_CELL_AREA: f32 = 1e-6; + +/// The area of polygon `outline` (shoelace) +fn area(outline: &[[f32; 2]]) -> f32 { + let twice: f32 = outline.iter().zip(outline.iter().cycle().skip(1)).map(|(a, b)| a[0] * b[1] - b[0] * a[1]).sum(); + twice.abs() * 0.5 +} + +/// Cuts convex polygon `polygon` (frame coordinates) to the frame's 0..1 square in place (Sutherland–Hodgman, one side at a time), `scratch` holding each side's cut +fn clip_to_frame(polygon: &mut Vec<[f32; 2]>, scratch: &mut Vec<[f32; 2]>) { + // Each side of the square: the axis it bounds, and whether points must stay below (1) or above (0) it + for (axis, bound, below) in [(0, 0.0, false), (0, 1.0, true), (1, 0.0, false), (1, 1.0, true)] { + let inside = |p: &[f32; 2]| if below { p[axis] <= bound } else { p[axis] >= bound }; + scratch.clear(); + for (point, next) in polygon.iter().zip(polygon.iter().cycle().skip(1)) { + let next = *next; + if inside(point) { + scratch.push(*point); + } + if inside(point) != inside(&next) { + let t = (bound - point[axis]) / (next[axis] - point[axis]); + scratch.push([point[0] + (next[0] - point[0]) * t, point[1] + (next[1] - point[1]) * t]); + } + } + std::mem::swap(polygon, scratch); + if polygon.is_empty() { + break; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use egui::pos2; + + const QUAD: [Pos2; 4] = [pos2(0.0, 0.0), pos2(100.0, 0.0), pos2(100.0, 100.0), pos2(0.0, 100.0)]; + const STILL: Placement = Placement { tiling: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] }; + + fn rounded(cells: &[(Vec, bool)]) -> Vec<(Vec<[i32; 2]>, bool)> { + cells.iter().map(|(outline, light)| (outline.iter().map(|p| [p.x.round() as i32, p.y.round() as i32]).collect(), *light)).collect() + } + + #[test] + fn an_untouched_image_shows_four_by_four_cells_filling_the_frame() { + let cells = warp_checker(QUAD, STILL); + assert_eq!(cells.len(), 16); + assert!(cells.iter().all(|(outline, _)| outline.len() == 4), "whole cells"); + assert_eq!(cells.iter().filter(|(_, light)| *light).count(), 8, "a checker"); + let area: f32 = cells.iter().map(|(outline, _)| (outline[2].x - outline[0].x).abs() * (outline[2].y - outline[0].y).abs()).sum(); + assert!((area - 100.0 * 100.0).abs() < 1.0, "they fill the frame: {area}"); + } + + #[test] + fn rotation_turns_the_checker_inside_the_frame() { + let still = rounded(&warp_checker(QUAD, STILL)); + let turned = warp_checker(QUAD, Placement { rotation: 30.0, ..STILL }); + assert_ne!(rounded(&turned), still, "a turned image turns the checker"); + assert!(turned.iter().any(|(outline, _)| outline.len() != 4), "cells cut by the frame's sides"); + assert!( + turned.iter().flat_map(|(outline, _)| outline).all(|p| (-0.01..=100.01).contains(&p.x) && (-0.01..=100.01).contains(&p.y)), + "kept inside the frame" + ); + assert_eq!(rounded(&warp_checker(QUAD, Placement { rotation: 360.0, ..STILL })), still, "a full turn looks unturned"); + assert_ne!(rounded(&warp_checker(QUAD, Placement { tiling: [2.0, 2.0], ..STILL })), still, "tiling shows"); + assert_ne!(rounded(&warp_checker(QUAD, Placement { offset: [0.1, 0.0], ..STILL })), still, "offset shows"); + } + + /// The checker turns round the frame's centre, as the compositor turns a warp's image: a half turn maps the checker onto itself, mirrored through the centre + #[test] + fn rotation_turns_the_checker_round_the_frame_centre() { + // A tiling whose cells do not divide the frame evenly: a turn round the top left would cut it elsewhere + let off_center = Placement { tiling: [0.7, 0.7], offset: [0.1, 0.05], ..STILL }; + let still = rounded(&warp_checker(QUAD, off_center)); + let half_turn = Placement { rotation: 180.0, ..off_center }; + let turned: Vec<_> = rounded(&warp_checker(QUAD, half_turn)) + .into_iter() + .map(|(outline, light)| (outline.into_iter().map(|[x, y]| [100 - x, 100 - y]).collect::>(), light)) + .collect(); + let corners = |cells: &[(Vec<[i32; 2]>, bool)]| { + let mut points: Vec<[i32; 2]> = cells.iter().flat_map(|(outline, _)| outline.iter().copied()).collect(); + points.sort_unstable(); + points.dedup(); + points + }; + assert_eq!(corners(&turned), corners(&still), "half turned round the centre: the same cut lines, mirrored through it"); + } + + #[test] + fn hostile_placements_draw_a_bounded_checker() { + // The most cells a turned frame spans along an axis: its diagonal at the finest tiling, rounded out at both ends + let cells_per_axis = (MAX_TILES * CHECKER_CELLS * std::f32::consts::SQRT_2).ceil() + 1.0; + let most_cells = (cells_per_axis * cells_per_axis) as usize; + for placement in [ + Placement { tiling: [f32::NAN, 1e9], ..STILL }, + Placement { rotation: f32::INFINITY, ..STILL }, + Placement { offset: [f32::NAN, 1e30], ..STILL }, + Placement { tiling: [0.0, -5.0], ..STILL }, + ] { + let cells = warp_checker(QUAD, placement); + assert!(cells.len() <= most_cells, "{placement:?}: {} cells", cells.len()); + } + } +} From 80072b2b050d01991d2267d2a3534af2fc8a7155 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:28:49 +0000 Subject: [PATCH 07/17] Panels: one header bar per docked panel, its close button and the group tab boxes --- crates/ui-egui/src/docking.rs | 171 ++++++++++--- crates/ui-egui/src/docking/header_band.rs | 60 +++++ crates/ui-egui/src/docking/shown_group_tab.rs | 102 ++++++++ crates/ui-egui/src/property_sheet/mod.rs | 8 + .../src/property_sheet/section_tabs.rs | 19 ++ crates/ui-egui/tests/it/panel_header.rs | 235 ++++++++++++++++++ crates/ui-egui/tests/it/rail.rs | 33 +-- crates/ui-egui/tests/it/settings_window.rs | 4 +- crates/ui-egui/tests/it/split_divider.rs | 25 +- crates/ui-egui/tests/ui_snapshots.rs | 59 +++++ 10 files changed, 652 insertions(+), 64 deletions(-) create mode 100644 crates/ui-egui/src/docking/header_band.rs create mode 100644 crates/ui-egui/src/docking/shown_group_tab.rs create mode 100644 crates/ui-egui/src/property_sheet/mod.rs create mode 100644 crates/ui-egui/src/property_sheet/section_tabs.rs create mode 100644 crates/ui-egui/tests/it/panel_header.rs diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index d779bf77..b4f64ad4 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -12,7 +12,7 @@ use craft_ui::docking::{Action, DockArea, DockContent, DockStyle, Layout, Location, Node, PanelLimits, PanelState, Permissions, Placement}; use craft_ui::layout::{SplitAxis, SplitSize}; -use egui::{Id, Margin, RichText, Ui, vec2}; +use egui::{Id, Margin, RichText, Ui, Vec2, vec2}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -20,6 +20,11 @@ use crate::TextureCraftApp; use crate::i18n::tr; use crate::theme::Tokens; +mod header_band; +mod shown_group_tab; + +pub(crate) use shown_group_tab::HEADER_TITLE_LEFT; + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Panel { Viewport, @@ -160,7 +165,9 @@ pub fn default_workspace() -> Workspace { const ASSETS_SPLIT_RATIO: f32 = 0.16; const VIEWPORT_SPLIT_RATIO: f32 = 0.80; const TEXTURE_SET_SPLIT_RATIO: f32 = 0.125; - const LAYERS_SPLIT_RATIO: f32 = 0.57; + + // Layers' share under the texture sets: Properties' 69% shows a fill down to its channels, Layers keeps three rows + const LAYERS_SPLIT_RATIO: f32 = 0.31; let column = split( SplitAxis::Vertical, @@ -412,15 +419,17 @@ const TAB_TEXT_SIZE: f32 = 12.5; /// Narrowest panel tab, in points const MIN_TAB_WIDTH: f32 = 54.0; -/// The dock look: each panel group a card on the window's frame colour, tab strips without hard lines, the shown tab a pill +/// The dock look: every panel group is a card under one chrome-coloured header bar, names in capitals at the left, a close × at the right fn style(ui: &Ui, tokens: &Tokens) -> DockStyle { let mut dock_style = DockStyle::from_ui(ui); dock_style.gap = f32::from(crate::theme::GUTTER); dock_style.min_pane = MIN_PANE_EXTENT; dock_style.background = tokens.panel; - dock_style.tab_background = tokens.panel; - dock_style.active_background = tokens.button; + dock_style.tab_background = tokens.chrome; + + // The shown and the hovered tab keep the bar's colour; their names brighten instead + dock_style.active_background = tokens.chrome; dock_style.text = tokens.text_strong; dock_style.inactive_text = tokens.text_dim; dock_style.border = egui::Stroke::NONE; @@ -468,7 +477,7 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { if let Some(panel) = app.ui.dock.raise.take() { area = area.raise_panel(panel); } - let output = area.show_content(ui, &layout, &style, &mut Panels { app, tokens }); + let output = area.show_content(ui, &layout, &style, &mut Panels { app, tokens, style: style.clone() }); crate::rail_popup::hand_drag_to_dock(&context, area_id()); // After the dock, which records the viewport the popup reaches into, and before a changed layout returns early @@ -491,15 +500,51 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { } } +/// Size of the panel names on a header bar +const HEADER_TITLE_SIZE: f32 = 12.0; + +/// Side of the close × at the right end of a header bar +const HEADER_CLOSE_SIZE: f32 = 22.0; + +/// Room right of the close × button, so its glyph ends where the Properties controls end (side padding plus scroll bar gutter) +const HEADER_CLOSE_RIGHT_MARGIN: f32 = 18.0; + +/// Whether a docked group's header bar ends in a close × (floating windows have one on their title bar; the viewport never closes) +fn header_closes(active: &Panel, floating: bool) -> bool { + !floating && permissions(active).closable +} + /// The panels' contents, names and limits for the dock area struct Panels<'a> { app: &'a mut TextureCraftApp, tokens: Tokens, + style: DockStyle, } /// Room between a panel's edges and its contents const PANEL_BODY_MARGIN: Margin = Margin::symmetric(8, 4); +/// Narrowest Properties panel and so its dock column: the 300 point design width plus the solid scroll bar; narrower, the 3D projection settings' X, Y, Z fields (the widest row) overlap +pub const PROPERTIES_MIN_WIDTH: f32 = 310.0; + +/// Least size of a docked or floating panel other than the 3D view and Properties +const PANEL_MIN_SIZE: Vec2 = vec2(120.0, 60.0); + +/// Least size of the 3D view +const VIEWPORT_MIN_SIZE: Vec2 = vec2(200.0, 150.0); + +/// Size a panel opens at when it floats +const FLOATING_SIZE: Vec2 = vec2(300.0, 380.0); + +/// Least size of `panel`, docked or floating; a dock column or split stops shrinking at its panels' largest +fn min_size(panel: Panel) -> Vec2 { + match panel { + Panel::Viewport => VIEWPORT_MIN_SIZE, + Panel::Properties => vec2(PROPERTIES_MIN_WIDTH, PANEL_MIN_SIZE.y), + _ => PANEL_MIN_SIZE, + } +} + /// The body of every panel except the viewport, in the dock or on the rail pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { // No project open: the library and the log work, the other panels about a project stay empty @@ -508,7 +553,9 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { return; } - egui::Frame::new().inner_margin(PANEL_BODY_MARGIN).show(ui, |ui| match panel { + // Properties draws full-width bands and tabs, so it keeps its own margins + let margin = if panel == Panel::Properties { Margin::ZERO } else { PANEL_BODY_MARGIN }; + egui::Frame::new().inner_margin(margin).show(ui, |ui| match panel { Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui), Panel::Assets => crate::shelf::body(app, ui), Panel::CommonSettings => crate::bake_mode::common_settings_panel(app, ui), @@ -532,15 +579,16 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { impl DockContent for Panels<'_> { fn body(&mut self, ui: &mut Ui, panel: &Panel) { - let app = &mut *self.app; if *panel == Panel::Viewport { crate::rail_popup::remember_viewport(ui.ctx(), ui.max_rect()); ui.painter().rect_filled(ui.max_rect(), 0.0, self.tokens.viewport); - crate::viewport::central(app, ui); + crate::viewport::central(self.app, ui); return; } - panel_body(app, ui, *panel); + // Before the rows, which draw over the foot of the shown tab's box + self.paint_shown_group_tab(ui, *panel); + panel_body(self.app, ui, *panel); } fn logical_label(&self, panel: &Panel) -> String { @@ -550,8 +598,58 @@ impl DockContent for Panels<'_> { } } - fn label(&mut self, _ui: &Ui, _panel: &Panel, logical: &str, font: &egui::FontId, color: egui::Color32) -> egui::WidgetText { - RichText::new(logical).font(font.clone()).color(color).into() + fn label(&mut self, ui: &Ui, panel: &Panel, logical: &str, _font: &egui::FontId, color: egui::Color32) -> egui::WidgetText { + // Capitals on the bar only: menus and screen readers keep the logical name + let name = logical.to_uppercase(); + let font = crate::theme::semibold(HEADER_TITLE_SIZE); + + // Menus list the panels by these names too, in popups; only a header bar's names, docked or floating, centre on its band + if matches!(ui.layer_id().order, egui::Order::Foreground | egui::Order::Tooltip) { + return RichText::new(name).font(font).color(color).into(); + } + + header_band::header_name(ui, &name, font, color, self.header_lift(*panel)).into() + } + + fn group_header_width(&self, panels: &[Panel], active: &Panel, floating: bool, _strip_width: f32) -> f32 { + if header_closes(active, floating) { + HEADER_CLOSE_SIZE + HEADER_CLOSE_RIGHT_MARGIN + } else if redocks(panels, active, floating) { + DOCK_BUTTON_SIZE + DOCK_BUTTON_MARGIN + } else { + 0.0 + } + } + + /// A docked group's bar ends in its close ×; a rail panel floating on its own carries the Dock button that sends it back to the rail + fn group_header(&mut self, ui: &mut Ui, panels: &[Panel], active: &Panel, floating: bool) { + if redocks(panels, active, floating) { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::widgets::icon_button(ui, egui_phosphor::regular::ARROW_SQUARE_IN, tr("Dock"), false, DOCK_BUTTON_SIZE).clicked() { + self.app.ui.dock.close(*active); + } + }); + return; + } + + if !header_closes(active, floating) { + return; + } + + // On the names' line: the middle of the header band + let rect = ui.max_rect(); + let button = egui::Rect::from_center_size( + egui::pos2(rect.right() - HEADER_CLOSE_RIGHT_MARGIN - HEADER_CLOSE_SIZE / 2.0, rect.center().y - self.header_lift(*active)), + vec2(HEADER_CLOSE_SIZE, HEADER_CLOSE_SIZE), + ); + let clicked = ui + .scope_builder(egui::UiBuilder::new().max_rect(button), |ui| { + crate::widgets::icon_button(ui, egui_phosphor::regular::X, tr("Close Panel"), false, HEADER_CLOSE_SIZE).clicked() + }) + .inner; + if clicked { + self.app.ui.dock.close(*active); + } } fn permissions(&self, panel: &Panel) -> Permissions { @@ -559,29 +657,11 @@ impl DockContent for Panels<'_> { } fn limits(&self, panel: &Panel) -> PanelLimits { - let min = if *panel == Panel::Viewport { vec2(200.0, 150.0) } else { vec2(120.0, 60.0) }; - PanelLimits { min, ..PanelLimits::default() } + PanelLimits { min: min_size(*panel), ..PanelLimits::default() } } - fn floating_size(&self, _panel: &Panel) -> Option { - Some(vec2(300.0, 380.0)) - } - - fn group_header_width(&self, panels: &[Panel], active: &Panel, floating: bool, _strip_width: f32) -> f32 { - if redocks(panels, active, floating) { DOCK_BUTTON_SIZE + DOCK_BUTTON_MARGIN } else { 0.0 } - } - - /// A rail panel floating on its own carries the Dock button that sends it back to the rail - fn group_header(&mut self, ui: &mut Ui, panels: &[Panel], active: &Panel, floating: bool) { - if !redocks(panels, active, floating) { - return; - } - - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if crate::widgets::icon_button(ui, egui_phosphor::regular::ARROW_SQUARE_IN, tr("Dock"), false, DOCK_BUTTON_SIZE).clicked() { - self.app.ui.dock.close(*active); - } - }); + fn floating_size(&self, panel: &Panel) -> Option { + Some(FLOATING_SIZE.max(min_size(*panel))) } } @@ -614,6 +694,31 @@ mod tests { assert_eq!(panels_of(&w), [Panel::Assets, Panel::Viewport, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, Panel::Properties]); } + #[test] + fn the_default_right_column_gives_properties_about_two_thirds_under_the_texture_sets() { + let workspace = default_workspace(); + let Some(Node::Split { second: right, .. }) = workspace.layout.root.as_ref() else { panic!("assets | rest") }; + let Node::Split { second: column, .. } = right.as_ref() else { panic!("viewport | right column") }; + let Node::Split { second: below_sets, .. } = column.as_ref() else { panic!("texture sets | rest") }; + let Node::Split { size: SplitSize::Ratio(layers), first, second, .. } = below_sets.as_ref() else { panic!("layers | properties") }; + assert!(matches!(first.as_ref(), Node::Tabs { panels, .. } if panels.first() == Some(&Panel::Layers))); + assert!(matches!(second.as_ref(), Node::Tabs { panels, .. } if panels == &[Panel::Properties])); + let properties = 1.0 - layers; + assert!((2.0 / 3.0..0.7).contains(&properties), "Properties takes about 69% of the column, at least two thirds: {properties}"); + } + + #[test] + fn a_saved_split_keeps_its_own_share() { + let mut workspace = default_workspace(); + let Some(Node::Split { second: right, .. }) = workspace.layout.root.as_mut() else { panic!("assets | rest") }; + let Node::Split { second: column, .. } = right.as_mut() else { panic!("viewport | right column") }; + let Node::Split { second: below_sets, .. } = column.as_mut() else { panic!("texture sets | rest") }; + let Node::Split { size, .. } = below_sets.as_mut() else { panic!("layers | properties") }; + *size = SplitSize::Ratio(0.57); + let back = Dock::from_value(serde_json::to_value(&workspace).unwrap()); + assert_eq!(back.workspace(), &workspace, "a layout saved with the old split opens unchanged"); + } + #[test] fn default_dock_round_trips() { let dock = Dock::default(); diff --git a/crates/ui-egui/src/docking/header_band.rs b/crates/ui-egui/src/docking/header_band.rs new file mode 100644 index 00000000..95dcdeec --- /dev/null +++ b/crates/ui-egui/src/docking/header_band.rs @@ -0,0 +1,60 @@ +//! A docked header's band: the tab strip plus the gutter above it, less a hairline of separation, with the names' capitals centred on it + +use craft_ui::docking::{Layout, Node}; +use craft_ui::layout::SplitAxis; +use egui::text::{LayoutJob, TextFormat}; +use egui::{Align, Color32, FontId, Ui}; + +use super::Panel; + +/// Gutter between two stacked panels left showing between the upper panel and the header band under it, as the reference keeps a dark line there +const PANEL_SEPARATION: f32 = 2.0; + +/// How far a header under another panel reaches above its tab strip: the gutter between them, less the separation +pub(super) const HEADER_RISE: f32 = crate::theme::GUTTER as f32 - PANEL_SEPARATION; + +/// Whether `panel`'s docked group sits under another panel, a gutter above its header; floating groups and the top row have none +pub(super) fn under_a_panel(layout: &Layout, panel: Panel) -> bool { + let Some(root) = &layout.root else { return false }; + let mut nodes: Vec<(&Node, bool)> = vec![(root, false)]; + while let Some((node, below)) = nodes.pop() { + match node { + Node::Split { axis, first, second, .. } => { + nodes.push((first, below)); + nodes.push((second, below || *axis == SplitAxis::Vertical)); + } + Node::Tabs { panels, .. } if panels.contains(&panel) => return below, + Node::Dock { columns, .. } => { + for column in columns { + if let Some(index) = column.groups.iter().position(|group| group.panels.contains(&panel)) { + return below || index > 0; + } + } + } + _ => {} + } + } + + false +} + +/// `name` laid out so that, centred as the dock centres every name, its capitals' middle sits `lift` above the strip's (a galley's height counts descenders) +pub(super) fn header_name(ui: &Ui, name: &str, font: FontId, color: Color32, lift: f32) -> LayoutJob { + let format = TextFormat { font_id: font, color, valign: Align::TOP, ..Default::default() }; + let mut job = LayoutJob::single_section(name.to_owned(), format); + let galley = ui.painter().layout_job(job.clone()); + + // The first capital's ink; a name without one (a script without capitals) keeps the galley's middle + let capital = galley.rows.first().and_then(|row| row.glyphs.iter().find(|glyph| glyph.chr.is_uppercase()).map(|glyph| (row.pos.y, glyph))); + let ink_middle = capital.map_or(galley.size().y / 2.0, |(row_top, glyph)| row_top + glyph.pos.y + glyph.uv_rect.offset.y + glyph.uv_rect.size.y / 2.0); + + // Room below the name raises it when centred, room above lowers it + let shift = ink_middle - galley.size().y / 2.0 + lift; + if shift < 0.0 + && let Some(section) = job.sections.first_mut() + { + section.format.valign = Align::BOTTOM; + } + job.first_row_min_height = galley.size().y + 2.0 * shift.abs(); + job +} diff --git a/crates/ui-egui/src/docking/shown_group_tab.rs b/crates/ui-egui/src/docking/shown_group_tab.rs new file mode 100644 index 00000000..61f5d4e0 --- /dev/null +++ b/crates/ui-egui/src/docking/shown_group_tab.rs @@ -0,0 +1,102 @@ +//! The shown tab of a docked panel group, drawn as the Properties section tabs draw theirs: a raised box joined to the panel's body + +use craft_ui::docking::{DockContent, Layout, Node}; +use egui::text::TextWrapping; +use egui::{Rect, Ui, pos2}; + +use super::header_band::{HEADER_RISE, header_name, under_a_panel}; +use super::{HEADER_TITLE_SIZE, Panel, Panels}; +use crate::property_sheet::{full_height_tab_rect, shown_tab_box}; +use crate::theme::semibold; + +/// Room the dock leaves around a tab's name, half on each side (craft-ui's dock renderer keeps its own copy private) +const DOCK_TAB_PADDING: f32 = 24.0; + +/// From a panel's left edge to its header's name +pub(crate) const HEADER_TITLE_LEFT: f32 = DOCK_TAB_PADDING / 2.0; + +/// Width of the dock's "…" button for the tabs that do not fit (private in craft-ui's dock renderer as well) +const OVERFLOW_WIDTH: f32 = 22.0; + +/// Room between a tab's box and its neighbouring tabs; the first tab's box starts on the panel's left edge +const BOX_INSET: f32 = 4.0; + +/// The panels of the group holding `panel` and whether that group floats; a collapsed stack has no tabs +fn group_of(layout: &Layout, panel: Panel) -> Option<(&[Panel], bool)> { + let docked = layout.root.iter().map(|root| (root, false)); + let floating = layout.floating.iter().map(|window| (&window.root, true)); + let mut nodes: Vec<(&Node, bool)> = docked.chain(floating).collect(); + while let Some((node, floats)) = nodes.pop() { + match node { + Node::Split { first, second, .. } => { + nodes.push((first, floats)); + nodes.push((second, floats)); + } + Node::Tabs { panels, .. } if panels.contains(&panel) => return Some((panels, floats)), + Node::Dock { columns, .. } => { + let group = columns.iter().flat_map(|column| &column.groups).find(|group| group.panels.contains(&panel)); + if let Some(group) = group { + return Some((&group.panels, floats)); + } + } + _ => {} + } + } + None +} + +impl Panels<'_> { + /// How far `panel`'s header band reaches above its tab strip: the gutter above it, under another panel + fn header_rise(&self, panel: Panel) -> f32 { + if under_a_panel(&self.app.ui.dock.workspace.layout, panel) { HEADER_RISE } else { 0.0 } + } + + /// How far `panel`'s header name sits above its tab strip's middle: on its header band's middle + pub(super) fn header_lift(&self, panel: Panel) -> f32 { + self.header_rise(panel) / 2.0 + } + + /// Over the tab the dock drew for `panel`, the panel shown in its group, paints the section tabs' raised box and the name again; a panel alone keeps its plain header. `ui` is the panel's body, right under the strip + pub(super) fn paint_shown_group_tab(&self, ui: &Ui, panel: Panel) { + let Some((panels, floating)) = group_of(&self.app.ui.dock.workspace.layout, panel) else { return }; + if panels.len() < 2 { + return; + } + + let Some(shown) = panels.iter().position(|member| *member == panel) else { return }; + + // The dock's own tab layout: names at their natural width, shrunk or moved to "…" when the strip is short + let body = ui.max_rect(); + let strip = Rect::from_min_max(pos2(body.left(), body.top() - self.style.tab_height), pos2(body.right(), body.top())); + let band = Rect::from_x_y_ranges(strip.x_range(), strip.top() - self.header_rise(panel)..=strip.bottom()); + let font = semibold(HEADER_TITLE_SIZE); + let names: Vec = panels.iter().map(|member| self.logical_label(member).to_uppercase()).collect(); + let natural: Vec = + names.iter().map(|name| ui.painter().layout_no_wrap(name.clone(), font.clone(), self.style.text).size().x + DOCK_TAB_PADDING).collect(); + let header = self.group_header_width(panels, &panel, floating, strip.width()).clamp(0.0, strip.width()); + let available = (strip.width() - header - self.style.drag_bar_width).max(0.0); + let fit = craft_ui::tabs::fit(&natural, shown, available, self.style.min_tab_width, OVERFLOW_WIDTH); + let mut left = strip.left(); + for (index, width) in fit.shown { + if index != shown { + left += width; + continue; + } + + // The body's clip stops at the strip, which the box rises into up to the band's top + let clip = ui.clip_rect(); + let mut painter = ui.painter().clone(); + painter.set_clip_rect(Rect::from_x_y_ranges(clip.x_range(), band.top()..=clip.bottom())); + let box_left = if left > strip.left() { left + BOX_INSET } else { left }; + shown_tab_box(&painter, &self.tokens, full_height_tab_rect(band, box_left, left + width - BOX_INSET)); + + let Some(name) = names.get(index) else { return }; + let mut job = header_name(ui, name, font, self.style.text, self.header_lift(panel)); + job.wrap = TextWrapping::truncate_at_width((width - DOCK_TAB_PADDING).max(0.0)); + let galley = painter.layout_job(job); + let at = pos2(left + HEADER_TITLE_LEFT, strip.center().y - galley.size().y / 2.0); + painter.galley(at, galley, self.style.text); + return; + } + } +} diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs new file mode 100644 index 00000000..53afe419 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -0,0 +1,8 @@ +//! The Properties panel's rows, groups and controls, shared by every panel so they line up + +mod section_tabs; + +pub(crate) use section_tabs::{full_height_tab_rect, shown_tab_box}; + +/// Side padding: every row starts and ends this far inside the panel +pub(crate) const PAD: f32 = 12.0; diff --git a/crates/ui-egui/src/property_sheet/section_tabs.rs b/crates/ui-egui/src/property_sheet/section_tabs.rs new file mode 100644 index 00000000..5b7d6187 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/section_tabs.rs @@ -0,0 +1,19 @@ +use egui::{CornerRadius, Painter, Rect, pos2}; + +use crate::theme::Tokens; + +/// The chosen tab starts this far below the strip's top and reaches this far into the panel +const TAB_BELOW: f32 = 6.0; + +/// Corner rounding of the chosen tab +pub(crate) const TAB_ROUNDING: u8 = 5; + +/// A tab from `left` to `right` filling `strip`'s whole height and reaching as far into the panel as a section tab: a docked group's shown tab +pub(crate) fn full_height_tab_rect(strip: Rect, left: f32, right: f32) -> Rect { + Rect::from_min_max(pos2(left, strip.top()), pos2(right, strip.bottom() + TAB_BELOW)) +} + +/// The shown tab's box over `tab`: the panel's colour, rounded, so it rises from the panel below the strip +pub(crate) fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) { + painter.rect_filled(tab, CornerRadius::same(TAB_ROUNDING), tokens.panel); +} diff --git a/crates/ui-egui/tests/it/panel_header.rs b/crates/ui-egui/tests/it/panel_header.rs new file mode 100644 index 00000000..8a9caed5 --- /dev/null +++ b/crates/ui-egui/tests/it/panel_header.rs @@ -0,0 +1,235 @@ +//! Every docked panel group sits under one header bar: its names at the left, the shown one raised as a box when the group has several, a close × at the right + +use craft_ui::docking::{Action, Placement}; +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::{Dock, Panel, permissions}; + +use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_at, panel_close_button}; + +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// A floating window over the viewport, `[x, y, width, height]` +const FLOATING_RECT: [f32; 4] = [600.0, 200.0, 320.0, 400.0]; + +fn app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + + harness +} + +/// The rect of the tab whose name starts with `name` +fn tab_rect(harness: &Harness<'_, TextureCraftApp>, name: &str) -> egui::Rect { + harness + .get_all_by_role(Role::Tab) + .find(|tab| tab.accesskit_node().label().is_some_and(|label| label.starts_with(name))) + .map(|tab| tab.rect()) + .unwrap_or_else(|| panic!("a {name} tab")) +} + +#[test] +fn every_docked_panel_header_ends_in_its_own_close_button() { + let harness = app(); + let names = ["Assets", "Texture Sets", "Layers", "Properties - "]; + let tabs: Vec = names.iter().map(|name| tab_rect(&harness, name)).collect(); + for (name, tab) in names.iter().zip(&tabs) { + let close = panel_close_button(&harness, *tab); + + // No other group's tab between a tab and its close button: the button is on its own bar + let between = tabs.iter().any(|other| other.y_range().contains(close.center().y) && other.min.x > tab.max.x && other.max.x < close.min.x); + assert!(!between, "{name} has no close button on its own header"); + } +} + +#[test] +fn the_header_close_button_closes_its_panel() { + let mut harness = app(); + assert!(harness.state().ui.dock.is_visible(Panel::Properties)); + let close = panel_close_button(&harness, tab_rect(&harness, "Properties - ")); + click_at(&mut harness, close.center()); + + assert!(!harness.state().ui.dock.is_open(Panel::Properties)); + assert!(harness.state().ui.dock.is_visible(Panel::Layers), "only the panel under the bar closes"); +} + +/// With an effect selected the Properties header names its type, not the effect's own name (every filter reads "Filter") +#[test] +fn the_properties_header_names_the_selected_effects_type() { + let mut harness = app(); + let session = &mut harness.state_mut().session; + let layer = texturecraft_engine::execute(session, "layer.add.fill", &serde_json::Value::Null).unwrap()["layer"].as_u64().unwrap(); + let blur = texturecraft_engine::execute(session, "effect.add.filter", &serde_json::json!({"layer": layer, "target": "content", "filter": "blur"})).unwrap() + ["effect"] + .as_u64() + .unwrap(); + texturecraft_engine::execute(session, "effect.set", &serde_json::json!({"effect": blur, "name": "Soften edges"})).unwrap(); + texturecraft_engine::execute(session, "layer.select", &serde_json::json!({"layer": layer, "target": blur})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + + tab_rect(&harness, "Properties - Filter"); + + let level = texturecraft_engine::execute(&mut harness.state_mut().session, "effect.add.levels", &serde_json::json!({"layer": layer, "target": "content"})) + .unwrap()["effect"] + .as_u64() + .unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &serde_json::json!({"layer": layer, "target": level})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + tab_rect(&harness, "Properties - Levels"); +} + +/// How far a header under another panel reaches above its tab strip: the 6 px gutter less a 2 px separation (docking/header_band.rs) +const HEADER_RISE: f32 = 4.0; + +/// Room between a later tab's box and its tab's left edge (docking/shown_group_tab.rs, private to the crate) +const BOX_INSET: f32 = 4.0; + +/// Rounded boxes painted this frame over `tab` whose top is `rise` above it: the raised box of a shown tab +fn tab_boxes(harness: &Harness<'_, TextureCraftApp>, tab: egui::Rect, rise: f32) -> Vec { + harness + .output() + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Rect(rect) => { + let rises = (rect.rect.top() - (tab.top() - rise)).abs() < 0.5; + let raised = rises && rect.corner_radius != egui::CornerRadius::ZERO && tab.x_range().contains(rect.rect.center().x); + raised.then_some(rect.rect) + } + _ => None, + }) + .collect() +} + +#[test] +fn a_groups_shown_tab_rises_as_a_box_and_the_others_and_a_lone_panels_do_not() { + let mut harness = app(); + let layers = tab_rect(&harness, "Layers"); + let settings = tab_rect(&harness, "Texture Set Settings"); + + assert_eq!(tab_boxes(&harness, layers, HEADER_RISE).len(), 1, "the shown Layers tab has its box, from the top of its header band"); + assert_eq!(tab_boxes(&harness, settings, HEADER_RISE).len(), 0, "the hidden tab is its name only"); + assert_eq!(tab_boxes(&harness, tab_rect(&harness, "Properties - "), HEADER_RISE).len(), 0, "a panel alone keeps its plain header"); + + click_at(&mut harness, settings.center()); + harness.run_steps(SETTLE_FRAMES); + + assert_eq!(tab_boxes(&harness, tab_rect(&harness, "Texture Set Settings"), HEADER_RISE).len(), 1, "the box goes with the shown tab"); + assert_eq!(tab_boxes(&harness, tab_rect(&harness, "Layers"), HEADER_RISE).len(), 0); +} + +#[test] +fn the_first_tabs_box_starts_on_the_panels_edge_and_a_later_tabs_box_keeps_its_inset() { + let mut harness = app(); + let layers = tab_rect(&harness, "Layers"); + let boxes = tab_boxes(&harness, layers, HEADER_RISE); + assert!(!boxes.is_empty(), "the shown Layers tab has its box"); + assert!(boxes.iter().all(|shown| (shown.left() - layers.left()).abs() < 0.5), "{boxes:?} starts on the panel's left edge {}", layers.left()); + + let settings = tab_rect(&harness, "Texture Set Settings"); + + click_at(&mut harness, settings.center()); + harness.run_steps(SETTLE_FRAMES); + + let boxes = tab_boxes(&harness, settings, HEADER_RISE); + assert!(!boxes.is_empty(), "the shown Texture Set Settings tab has its box"); + assert!(boxes.iter().all(|shown| (shown.left() - (settings.left() + BOX_INSET)).abs() < 0.5), "{boxes:?} keeps its air from the Layers tab"); +} + +/// The middle of the first capital's ink in each painted text reading `name` +fn capital_middles(harness: &Harness<'_, TextureCraftApp>, name: &str) -> Vec { + harness + .output() + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == name => { + let row = text.galley.rows.first()?; + let glyph = row.glyphs.iter().find(|glyph| glyph.chr.is_uppercase())?; + Some(text.pos.y + row.pos.y + glyph.pos.y + glyph.uv_rect.offset.y + glyph.uv_rect.size.y / 2.0) + } + _ => None, + }) + .collect() +} + +/// Names' capitals and the close × share the header band's middle: the tab strip plus, under another panel, the gutter above it less the separation +#[test] +fn header_names_capitals_and_close_buttons_sit_on_the_header_bands_middle() { + let harness = app(); + let headers = [ + ("Texture Sets", "TEXTURE SETS", 0.0), + ("Layers", "LAYERS", HEADER_RISE), + ("Texture Set Settings", "TEXTURE SET SETTINGS", HEADER_RISE), + ("Properties - ", "PROPERTIES - PAINT", HEADER_RISE), + ]; + for (tab, name, rise) in headers { + let tab = tab_rect(&harness, tab); + let middle = (tab.top() - rise + tab.bottom()) / 2.0; + let capitals = capital_middles(&harness, name); + assert!(!capitals.is_empty(), "{name} is painted"); + assert!(capitals.iter().all(|capital| (capital - middle).abs() < 0.75), "{name}'s capitals at {capitals:?}, its band's middle at {middle}"); + } + + let properties = tab_rect(&harness, "Properties - "); + let close = panel_close_button(&harness, properties); + let middle = (properties.top() - HEADER_RISE + properties.bottom()) / 2.0; + assert!((close.center().y - middle).abs() < 0.5, "the close × at {}, the band's middle at {middle}", close.center().y); +} + +/// A floating group's names sit on one line: the shown name, painted again over its tab, and the dimmed one beside it (the dimmed one kept its galley's middle) +#[test] +fn a_floating_groups_names_share_one_line() { + let mut harness = app(); + let mut workspace = harness.state().ui.dock.workspace().clone(); + let actions = [ + Action::Float { panel: Panel::Properties, rect: FLOATING_RECT }, + Action::Move { panel: Panel::TextureSetSettings, anchor: Panel::Properties, placement: Placement::Tab { before: None } }, + Action::Activate { panel: Panel::Properties }, + ]; + workspace.apply_all(actions, permissions).unwrap(); + harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); + harness.run_steps(SETTLE_FRAMES); + + let shown = capital_middles(&harness, "PROPERTIES - PAINT"); + let dimmed = capital_middles(&harness, "TEXTURE SET SETTINGS"); + assert!(!shown.is_empty() && !dimmed.is_empty(), "both names are painted"); + assert!(shown.iter().chain(&dimmed).all(|capital| (capital - shown[0]).abs() < 0.5), "the shown name's capitals at {shown:?}, the other's at {dimmed:?}"); +} + +/// The tab menu's panel names keep their plain layout: only the header bar pads a name to centre its capitals on the band +#[test] +fn a_tab_menus_panel_names_keep_their_plain_layout() { + let mut harness = app(); + let properties = tab_rect(&harness, "Properties - "); + let button = egui::PointerButton::Secondary; + harness.hover_at(properties.center()); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: properties.center(), button, pressed, modifiers: egui::Modifiers::NONE }); + harness.run_steps(1); + } + harness.run_steps(SETTLE_FRAMES); + + let move_to = harness.get_by_role_and_label(Role::Button, "Move Panel to Group").rect(); + harness.hover_at(move_to.center()); + harness.run_steps(SETTLE_FRAMES); + + let entry = harness.get_by_role_and_label(Role::Button, "Layers").rect(); + let padded: Vec = harness + .output() + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == "LAYERS" && entry.contains(text.pos) => Some(text.galley.job.first_row_min_height), + _ => None, + }) + .collect(); + assert!(!padded.is_empty(), "the menu paints the Layers entry"); + assert!(padded.iter().all(|height| *height == 0.0), "the Layers entry is padded to {padded:?}"); +} diff --git a/crates/ui-egui/tests/it/rail.rs b/crates/ui-egui/tests/it/rail.rs index a994bcb3..30f3a153 100644 --- a/crates/ui-egui/tests/it/rail.rs +++ b/crates/ui-egui/tests/it/rail.rs @@ -7,18 +7,13 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; use texturecraft_ui_egui::state::ViewLayout; +use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_at}; + const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); /// The rail is the last 38 points of the window; the popup's own buttons sit left of it const RAIL_LEFT_EDGE: f32 = WINDOW_SIZE.x - 38.0; -// Small texture and bake sizes keep the sample session fast; the rail doesn't depend on them -const TEXTURE_RESOLUTION: u32 = 256; -const BAKE_RESOLUTION: u32 = 64; - -/// Frames for the first layout and fonts to settle -const STARTUP_FRAMES: usize = 4; - /// Where a drag out of the popup ends: in the viewport, clear of every panel const INTO_THE_VIEWPORT: egui::Vec2 = egui::vec2(-500.0, 100.0); @@ -28,9 +23,6 @@ const DRAG_STEPS: usize = 6; /// Frames between a drag's events: the press must land before the moves, and each move be seen const FRAMES_PER_DRAG_EVENT: usize = 2; -/// Frames for a click to reach the rail, the popup and the dock -const SETTLE_FRAMES: usize = 3; - // A setting only Shader Settings shows, and one only Display Settings shows const SHADER_SETTING: &str = "Index of refraction"; const DISPLAY_SETTING: &str = "Environment Opacity"; @@ -60,16 +52,8 @@ fn rail_icon<'h>(harness: &'h Harness<'_, TextureCraftApp>, name: &str) -> Optio } fn click_rail(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { - rail_icon(harness, name).expect("the panel's icon on the rail").click(); - harness.run_steps(SETTLE_FRAMES); -} - -fn click_at(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { - harness.hover_at(position); - harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - harness.run_steps(1); - harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - harness.run_steps(SETTLE_FRAMES); + let at = rail_icon(harness, name).expect("the panel's icon on the rail").rect().center(); + click_at(harness, at); } /// Drag with the primary button from `from` to `to` in a few moves @@ -197,9 +181,12 @@ fn dragging_the_title_onto_a_tab_strip_docks_the_panel_there() { let mut harness = app(); click_rail(&mut harness, "Log"); - let title = popup_title(&harness, "Log").center(); - let properties_tab = harness.get_by_label("Properties - Paint").rect().center(); - drag(&mut harness, title, properties_tab); + let title = popup_title(&harness, "Log"); + + // The popup covers the Properties strip and stays put while dragged: drop on the Texture Sets strip above it + let texture_sets_tab = harness.get_by_label("Texture Sets").rect(); + assert!(texture_sets_tab.bottom() < title.top(), "the Texture Sets strip {texture_sets_tab:?} is under the popup at {title:?}"); + drag(&mut harness, title.center(), texture_sets_tab.center()); let layout = &harness.state().ui.dock.workspace().layout; assert!(layout.contains(&Panel::Log) && !layout.floating.iter().any(|window| window.contains(&Panel::Log)), "the Log is docked"); diff --git a/crates/ui-egui/tests/it/settings_window.rs b/crates/ui-egui/tests/it/settings_window.rs index c2e31b66..477283c9 100644 --- a/crates/ui-egui/tests/it/settings_window.rs +++ b/crates/ui-egui/tests/it/settings_window.rs @@ -9,9 +9,7 @@ use texturecraft_ui_egui::state::{LibraryLocation, UiState}; use texturecraft_ui_egui::unavailable::NOT_AVAILABLE; use texturecraft_ui_egui::{TextureCraftApp, menus}; -#[path = "../../src/ui_state_store/memory_storage.rs"] -mod memory_storage; -use memory_storage::MemoryStorage; +use crate::memory_storage::MemoryStorage; /// The section captions of the General page, top to bottom. const SECTIONS: [&str; 13] = [ diff --git a/crates/ui-egui/tests/it/split_divider.rs b/crates/ui-egui/tests/it/split_divider.rs index 98a6c39c..075d4b80 100644 --- a/crates/ui-egui/tests/it/split_divider.rs +++ b/crates/ui-egui/tests/it/split_divider.rs @@ -1,10 +1,12 @@ //! The divider between the 3D and 2D views in the split layout resizes them and keeps the pointer from the views -use egui::{Event, Modifiers, PointerButton, Pos2, pos2}; +use egui::{Event, Modifiers, PointerButton, Pos2, Role, pos2}; use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::core::Channel; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::UiState; +use texturecraft_ui_egui::theme::GUTTER; use texturecraft_ui_egui::ui_state_store::UiStateStore; /// Narrowest a split view may get, as in `viewport.rs` @@ -37,6 +39,9 @@ impl eframe::Storage for MemoryStorage { fn split_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // The Layers tab is found by its English name, whatever the OS language is + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); harness } @@ -57,6 +62,17 @@ fn drag(harness: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: harness.run_steps(3); } +/// The views' right edge: a gutter left of the right column, whose Layers header starts at the column's left edge +fn views_right(harness: &Harness<'_, TextureCraftApp>) -> f32 { + let column_left = harness + .get_all_by_role(Role::Tab) + .filter(|tab| tab.accesskit_node().label().is_some_and(|label| label.starts_with("Layers"))) + .map(|tab| tab.rect().left()) + .next() + .expect("the right column's Layers header"); + column_left - f32::from(GUTTER) +} + /// The divider's x position: the 3D view ends 1 point left of it fn divider_x(harness: &Harness<'_, TextureCraftApp>) -> f32 { harness.state().viewport_rect.right() + 1.0 @@ -111,8 +127,8 @@ fn dragging_the_divider_resizes_the_views_within_their_minimum_width() { let mut harness = split_app(); let views_left = harness.state().viewport_rect.left(); let start_x = divider_x(&harness); - let views_width = (start_x - views_left) * 2.0; - let views_right = views_left + views_width; + let views_right = views_right(&harness); + let views_width = views_right - views_left; let y = harness.state().viewport_rect.center().y; assert_eq!(harness.state().ui.split_ratio, 0.5); @@ -204,9 +220,8 @@ fn dragging_the_divider_keeps_the_uv_texture_size_and_offset_on_screen() { harness.state_mut().ui.uv_pan = [0.2, 0.1]; harness.run_steps(2); - // The split starts centred, so the views end as far right of the divider as they start left of it let views_left = harness.state().viewport_rect.left(); - let views_right = views_left + (divider_x(&harness) - views_left) * 2.0; + let views_right = views_right(&harness); let y = harness.state().viewport_rect.center().y; let before = uv_texture_on_screen(&harness, views_right); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index b29ce0ed..7462516b 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -858,6 +858,35 @@ fn tile_generator_gradient_map_snapshot() { save(&mut harness, &output_dir, "tile-generator-gradient-map"); } +/// Every docked panel's header bar (names in capitals, a close × at the right), then the Properties × hovered +#[test] +#[ignore] +fn panel_header_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("panel-header-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + let close = harness + .get_all_by_label("Close Panel") + .map(|node| node.rect()) + .filter(|rect| rect.min.x > 1200.0) + .max_by(|a, b| a.min.y.total_cmp(&b.min.y)) + .expect("the Properties header's close button"); + harness.hover_at(close.center()); + save(&mut harness, &output_dir, "panel-header-close-hovered"); +} + /// Edit > Settings: the three pages and a compact window at 150% scale #[test] #[ignore] @@ -898,3 +927,33 @@ fn settings_pages_snapshot() { harness.state_mut().ui.windows.settings_draft.as_mut().unwrap().page = SettingsPage::General; save(&mut harness, &output_dir, "settings-compact"); } + +#[test] +#[ignore] +fn default_layout_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for color in [[0.2, 0.4, 0.7], [0.5, 0.5, 0.5], [0.8, 0.3, 0.1]] { + execute(&mut session, "layer.add.fill", &json!({ "color": color })).unwrap(); + } + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("default-layout-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + let properties_close = harness + .get_all_by_label("Close Panel") + .map(|node| node.rect()) + .filter(|rect| rect.min.x > 1200.0) + .max_by(|a, b| a.min.y.total_cmp(&b.min.y)) + .expect("the Properties header's close button"); + harness.hover_at(egui::pos2(properties_close.center().x - 120.0, properties_close.min.y - 6.0)); + save(&mut harness, &output_dir, "default-layout-split-hovered"); +} From 91310e5a734892d6a0e508407101b5af70789076 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:11 +0000 Subject: [PATCH 08/17] Fills: the Fill tab with its preview square, Move on model and section reset --- crates/engine/src/fill_reset_cmds.rs | 101 +++ crates/engine/tests/it/fill_projections.rs | 767 ++++++++++++++++ crates/ui-egui/src/fill_panel.rs | 484 ++++++++++ crates/ui-egui/src/fill_pictures.rs | 403 +++++++++ crates/ui-egui/src/move_hold.rs | 15 + crates/ui-egui/src/move_on_model.rs | 498 +++++++++++ crates/ui-egui/src/preview_dots.rs | 53 ++ crates/ui-egui/src/projection_kind.rs | 68 ++ crates/ui-egui/src/projection_preview.rs | 846 ++++++++++++++++++ .../src/projection_preview/preview_shape.rs | 24 + .../projection_preview/rendered_preview.rs | 11 + .../ui-egui/src/projection_preview/screen.rs | 30 + crates/ui-egui/src/projection_preview/view.rs | 25 + .../ui-egui/tests/it/fill_projection_rows.rs | 242 +++++ 14 files changed, 3567 insertions(+) create mode 100644 crates/engine/src/fill_reset_cmds.rs create mode 100644 crates/engine/tests/it/fill_projections.rs create mode 100644 crates/ui-egui/src/fill_panel.rs create mode 100644 crates/ui-egui/src/fill_pictures.rs create mode 100644 crates/ui-egui/src/move_hold.rs create mode 100644 crates/ui-egui/src/move_on_model.rs create mode 100644 crates/ui-egui/src/preview_dots.rs create mode 100644 crates/ui-egui/src/projection_kind.rs create mode 100644 crates/ui-egui/src/projection_preview.rs create mode 100644 crates/ui-egui/src/projection_preview/preview_shape.rs create mode 100644 crates/ui-egui/src/projection_preview/rendered_preview.rs create mode 100644 crates/ui-egui/src/projection_preview/screen.rs create mode 100644 crates/ui-egui/src/projection_preview/view.rs create mode 100644 crates/ui-egui/tests/it/fill_projection_rows.rs diff --git a/crates/engine/src/fill_reset_cmds.rs b/crates/engine/src/fill_reset_cmds.rs new file mode 100644 index 00000000..d5d1afa6 --- /dev/null +++ b/crates/engine/src/fill_reset_cmds.rs @@ -0,0 +1,101 @@ +//! Reset of a fill's Fill section: its projection's settings and its sampling back to a new fill's, its projection kind, symmetry and material kept + +use serde_json::Value; +use texturecraft_core::{Projection, Sampling}; + +use crate::commands::{CommandSpec, has_layer}; +use crate::layer_cmds::{UNFRAMED_PROJECTION_IDS, fill_target, new_unframed_projection, placement_mut}; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![cmd!( + "layer.fill.resetProjection", + "Reset fill settings", + [], + None, + has_layer, + reset_projection + )] +} + +/// The sampling a reset Fill section has: a new fill's, with `current`'s symmetry (it belongs to the Symmetry section) +pub fn reset_sampling(current: Sampling) -> Sampling { + Sampling { symmetry: current.symmetry, ..Sampling::default() } +} + +/// The defaults of `current`'s projection kind: a new fill's projection of that kind, with the frame a placed planar or a warp projects from kept +pub fn reset_projection_of(current: &Projection) -> Projection { + if let Projection::Warp { frame, .. } = current { + return Projection::warp(*frame); + } + + // The new projection of the same kind; one no id makes (none today) stays as it is + let same_kind = UNFRAMED_PROJECTION_IDS + .iter() + .filter_map(|id| new_unframed_projection(id)) + .find(|fresh| std::mem::discriminant(fresh) == std::mem::discriminant(current)); + let Some(mut fresh) = same_kind else { return current.clone() }; + + if let (Projection::Planar { placed, .. }, Projection::Planar { placed: Some(frame), .. }) = (&mut fresh, current) { + *placed = Some(*frame); + } + fresh +} + +/// Whether the Fill section of a fill projected by `projection` and sampled by `sampling` is already a new fill's (of the same projection kind) +pub fn at_defaults(projection: &Projection, sampling: Sampling) -> bool { + *projection == reset_projection_of(projection) && sampling == reset_sampling(sampling) +} + +fn reset_projection(s: &mut Session, p: &Value) -> Result { + let target = fill_target(s, p, "layer.fill.resetProjection")?; + let (projection, sampling) = placement_mut(s, target)?; + if at_defaults(projection, *sampling) { + return Ok(Value::Null); + } + + s.edit("Reset fill settings", |s| { + let (projection, sampling) = placement_mut(s, target)?; + *projection = reset_projection_of(projection); + *sampling = reset_sampling(*sampling); + Ok(()) + })?; + Ok(Value::Null) +} + +#[cfg(test)] +mod tests { + use texturecraft_core::{Decal, Projector}; + + use super::*; + + #[test] + fn every_projection_kind_resets_to_its_own_kind() { + let frame = Decal { + center: [0.0; 3], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [1.0, 1.0], + rotation: 0.0, + offset: [0.0; 2], + depth: 0.5, + symmetry: None, + flip: [false; 2], + }; + let mut kinds: Vec = UNFRAMED_PROJECTION_IDS.iter().filter_map(|id| new_unframed_projection(id)).collect(); + assert_eq!(kinds.len(), UNFRAMED_PROJECTION_IDS.len(), "every listed id makes a projection"); + + kinds.extend([Projection::warp(frame), Projection::decal(frame)]); + for kind in kinds { + let turned = match kind.clone() { + Projection::Planar { scale, axis, offset, uv, placed, .. } => { + Projection::Planar { scale: scale * 2.0, axis, offset, uv, placed, projector: Projector { rotation: [10.0; 3], ..Projector::default() } } + } + other => other, + }; + let reset = reset_projection_of(&turned); + assert_eq!(std::mem::discriminant(&reset), std::mem::discriminant(&kind), "{kind:?}"); + assert_eq!(reset.frame(), kind.frame(), "the frame stays where it is placed"); + } + } +} diff --git a/crates/engine/tests/it/fill_projections.rs b/crates/engine/tests/it/fill_projections.rs new file mode 100644 index 00000000..7d0ebc93 --- /dev/null +++ b/crates/engine/tests/it/fill_projections.rs @@ -0,0 +1,767 @@ +//! The 3D projection settings and the projection kinds of a fill, through engine commands + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, DepthCulling, FillSymmetry, LayerId, LayerKind, Projection, Projector, Sampling, UvTransform}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap(); + s.update(); + s +} + +/// A fill layer with a checker procedural in base color +fn checker_fill(s: &mut Session) -> LayerId { + let layer = LayerId(execute(s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + execute(s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "procedural": "Checker", "scale": 4, "low": [0, 0, 0], "high": [1, 1, 1]})) + .unwrap(); + layer +} + +fn set(s: &mut Session, layer: LayerId, mut p: Value) { + p["layer"] = json!(layer.0); + execute(s, "layer.fill.projection", &p).unwrap(); +} + +fn projection(s: &Session, layer: LayerId) -> Projection { + match &s.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(f) => f.projection.clone(), + _ => panic!("a fill layer"), + } +} + +/// Base color red of every texel +fn snapshot(s: &mut Session) -> Vec { + s.update(); + let cache = &s.caches[0]; + let (w, h) = cache.size; + (0..w * h).map(|i| cache.composite.value(Channel::BaseColor, i % w, i / w)[0]).collect() +} + +/// Rotation, per-axis scale and offset move every 3D projection; the defaults and older saves change nothing +#[test] +fn three_d_projection_settings_turn_stretch_and_move_every_3d_projection() { + let mut s = session(); + let layer = checker_fill(&mut s); + for kind in ["triplanar", "planar", "spherical", "cylindrical"] { + set(&mut s, layer, json!({"projection": kind})); + let plain = snapshot(&mut s); + + set(&mut s, layer, json!({"projectorRotation": [30, 45, 60]})); + assert_ne!(snapshot(&mut s), plain, "{kind}: rotation turns the pattern"); + set(&mut s, layer, json!({"projectorRotation": [0, 0, 0], "projectorScale": [2, 0.5, 1]})); + assert_ne!(snapshot(&mut s), plain, "{kind}: per-axis scale stretches the pattern"); + set(&mut s, layer, json!({"projectorScale": 1, "offset": [0.3, 0.2, 0.1]})); + assert_ne!(snapshot(&mut s), plain, "{kind}: offset moves the pattern"); + set(&mut s, layer, json!({"offset": 0})); + assert_eq!(snapshot(&mut s), plain, "{kind}: the defaults change nothing"); + + set(&mut s, layer, json!({"projectorRotation": [10, 20, 30], "projectorScale": [1, 2, 3]})); + let mut saved = serde_json::to_value(projection(&s, layer)).unwrap(); + let fields = saved.as_object_mut().unwrap().values_mut().next().unwrap().as_object_mut().unwrap(); + fields.remove("projector"); + let loaded: Projection = serde_json::from_value(saved).unwrap(); + let settings = match loaded { + Projection::Triplanar { projector, .. } + | Projection::Planar { projector, .. } + | Projection::Spherical { projector, .. } + | Projection::Cylindrical { projector, .. } => projector, + other => panic!("{kind}: loaded as {other:?}"), + }; + assert_eq!(settings, Projector::default(), "{kind}: an older save has no turn or stretch"); + set(&mut s, layer, json!({"projectorRotation": 0, "projectorScale": 1})); + } + + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + let cylindrical = &row["fill"]["projectionSettings"]["Cylindrical"]; + assert!( + cylindrical.is_object() && cylindrical.get("projector").is_none(), + "a reset projector is the default, left out as older projects saved it: {cylindrical}" + ); +} + +/// A negative projector scale mirrors that axis, as a project file's does: the command keeps its sign and limits only its size +#[test] +fn a_negative_projector_scale_keeps_its_mirror() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "spherical", "projectorScale": [-1.5, 0.0, 5000.0]})); + let Projection::Spherical { projector, .. } = projection(&s, layer) else { panic!("a spherical projection") }; + assert_eq!(projector.scale, [-1.5, 0.001, 1000.0], "the mirror kept, each axis's size within the scale limits"); + + set(&mut s, layer, json!({"projectorScale": -0.0001})); + let Projection::Spherical { projector, .. } = projection(&s, layer) else { panic!("a spherical projection") }; + assert_eq!(projector.scale, [-0.001; 3], "a tiny mirrored scale keeps the smallest size, still mirrored"); +} + +/// Fill (Match per UV Tile) shows the same pattern on both UDIM tiles, where UV runs on across them +#[test] +fn match_per_uv_tile_repeats_the_source_once_per_tile() { + let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + let layer = LayerId(execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + execute( + &mut s, + "layer.fill.set", + &json!({"layer": layer.0, "channel": "baseColor", "procedural": "Clouds", "scale": 3, "low": [0, 0, 0], "high": [1, 1, 1]}), + ) + .unwrap(); + let tiles = |s: &mut Session| { + s.update(); + let composite = &s.caches[0].composite; + let tile = |block: u32| (0..128 * 128).map(|i| composite.value(Channel::BaseColor, block * 128 + i % 128, i / 128)[0]).collect::>(); + (tile(0), tile(1)) + }; + let (left, right) = tiles(&mut s); + assert_ne!(left, right, "a UV projection runs on into the next tile"); + + set(&mut s, layer, json!({"projection": "uvTile"})); + assert_eq!(projection(&s, layer), Projection::UvTile); + let (left, right) = tiles(&mut s); + let worst = left.iter().zip(&right).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); + assert!(worst < 1e-4, "every tile shows the same pattern (worst difference {worst})"); +} + +/// Cylindrical Angle is the arc one repeat spans; older saves go the whole way round +#[test] +fn cylindrical_angle_is_the_arc_one_repeat_spans() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "cylindrical"})); + let plain = snapshot(&mut s); + set(&mut s, layer, json!({"angle": 120})); + assert!(matches!(projection(&s, layer), Projection::Cylindrical { angle: 120.0, .. })); + assert_ne!(snapshot(&mut s), plain, "a third of the way round repeats three times"); + set(&mut s, layer, json!({"angle": 360})); + assert_eq!(snapshot(&mut s), plain, "360 degrees is the whole way round"); + + let mut saved = serde_json::to_value(projection(&s, layer)).unwrap(); + saved["Cylindrical"].as_object_mut().unwrap().remove("angle"); + assert!(matches!(serde_json::from_value(saved).unwrap(), Projection::Cylindrical { angle: 360.0, .. })); +} + +/// Texel indices whose surface normal has a Z above `above` (and below `below`) +fn facing_z(s: &Session, above: f32, below: f32) -> Vec { + let cache = &s.caches[0]; + let (w, h) = cache.size; + (0..(w * h) as usize).filter(|&i| cache.gbuf.surface(&s.mesh, i).is_some_and(|surface| surface.nrm.z > above && surface.nrm.z < below)).collect() +} + +/// Cropped to Shape stops a shrunk tri-planar box short of the mesh; the default box holds it all +#[test] +fn shape_crop_stops_a_projection_at_its_shape() { + let mut s = session(); + let layer = checker_fill(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": false})).unwrap(); + let empty = snapshot(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": true})).unwrap(); + set(&mut s, layer, json!({"projection": "triplanar"})); + let plain = snapshot(&mut s); + set(&mut s, layer, json!({"shapeCrop": "cropped"})); + assert_eq!(snapshot(&mut s), plain, "the default box holds the whole mesh"); + + set(&mut s, layer, json!({"projectorScale": 0.5})); + let cropped = snapshot(&mut s); + let gone = cropped.iter().zip(&empty).filter(|(a, b)| a == b).count(); + set(&mut s, layer, json!({"shapeCrop": "extendsOutside"})); + let extends = snapshot(&mut s); + let gone_extending = extends.iter().zip(&empty).filter(|(a, b)| a == b).count(); + assert!(gone > gone_extending + 1000, "the half-size box leaves the rest of the mesh bare ({gone} vs {gone_extending} bare texels)"); + assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "shapeCrop": "clipped"})).is_err()); +} + +/// Backface culling leaves the far side of the sphere bare and the near side unchanged +#[test] +fn backface_culling_keeps_a_planar_projection_off_faces_turned_away() { + let mut s = session(); + let layer = checker_fill(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": false})).unwrap(); + let empty = snapshot(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": true})).unwrap(); + // Without depth culling the planar projection reaches the far side, so only backface culling can take it off + set(&mut s, layer, json!({"projection": "planar", "axis": 2, "depthCulling": false})); + let plain = snapshot(&mut s); + let (far, near) = (facing_z(&s, -1.1, -0.05), facing_z(&s, 0.05, 1.1)); + assert!(!far.is_empty() && !near.is_empty()); + assert!(far.iter().any(|&i| plain[i] != empty[i]), "without culling the projection reaches the far side"); + set(&mut s, layer, json!({"backfaceCulling": true, "backfaceAngle": 90, "backfaceHardness": 1})); + let culled = snapshot(&mut s); + assert!(far.iter().all(|&i| culled[i] == empty[i]), "faces turned away get none of the projection"); + assert!(near.iter().all(|&i| culled[i] == plain[i]), "faces turned towards it keep all of it"); + + set(&mut s, layer, json!({"backfaceAngle": 45})); + let narrow = snapshot(&mut s); + let sideways = facing_z(&s, 0.1, 0.6); + assert!(sideways.iter().all(|&i| narrow[i] == empty[i]), "past 45 degrees nothing is left"); +} + +/// A decal saved before decals were planar projections loads as a planar projection placed on its frame, cropped to it and off faces turned away +#[test] +fn saved_decals_load_as_planar_projections_placed_on_the_surface() { + use texturecraft_engine::core::{Backface, Decal, DecalFlip, DecalSymmetry, Fill, ShapeCrop}; + + // A decal saved with a mirrored copy and a flipped image keeps both + let frame = Decal { + center: [0.0, 0.0, 1.0], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [0.5, 0.4], + rotation: 10.0, + offset: [0.1, 0.0], + depth: 0.3, + symmetry: Some(DecalSymmetry { axis: 0, flip: DecalFlip::U, offset: 0.25 }), + flip: [true, false], + }; + let mut saved = serde_json::to_value(Fill::default()).unwrap(); + saved["projection"] = json!({ "Decal": frame }); + let fill: Fill = serde_json::from_value(saved).unwrap(); + let Projection::Planar { placed: Some(placed), projector, .. } = fill.projection else { panic!("{:?}", fill.projection) }; + assert_eq!(placed, frame); + assert_eq!(projector.crop, ShapeCrop::Cropped); + assert_eq!(projector.backface, Backface { on: true, angle: 90.0, hardness: 0.5 }); +} + +/// A planar projection with a decal's look saves as a decal, so versions from before planar decals still read a decal; changed in any way it saves as a planar projection +#[test] +fn placed_planars_with_a_decals_look_save_as_decals() { + use texturecraft_engine::core::{Decal, Fill}; + let frame = Decal { + center: [0.0, 0.0, 1.0], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [0.5, 0.4], + rotation: 10.0, + offset: [0.1, 0.0], + depth: 0.3, + symmetry: None, + flip: [false; 2], + }; + let fill = Fill { projection: Projection::decal(frame), ..Fill::default() }; + + let saved = serde_json::to_value(&fill).unwrap(); + assert_eq!(saved["projection"], json!({ "Decal": frame })); + assert_eq!(serde_json::from_value::(saved).unwrap(), fill, "and reads back the same"); + + let mut turned = fill; + let Projection::Planar { uv, .. } = &mut turned.projection else { panic!("{:?}", turned.projection) }; + uv.rotation = 30.0; + let saved = serde_json::to_value(&turned).unwrap(); + assert_eq!(saved["projection"]["Planar"]["placed"], json!(frame)); + assert_eq!(serde_json::from_value::(saved).unwrap(), turned); +} + +/// A warp projects from a frame around the mesh: pulling a corner bends the image, Projection Depth bounds it when cropped, and Reset frame unpulls the corners +#[test] +fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame() { + let mut s = session(); + let layer = checker_fill(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": false})).unwrap(); + let empty = snapshot(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": true})).unwrap(); + set(&mut s, layer, json!({"projection": "warp"})); + let Projection::Warp { frame, corners, depth, .. } = projection(&s, layer) else { panic!("{:?}", projection(&s, layer)) }; + assert_eq!((corners, depth), (Projection::FRAME_CORNERS, Projection::WARP_DEPTH)); + assert_eq!((frame.normal, frame.up), ([0.0, 0.0, 1.0], [0.0, 1.0, 0.0]), "seen from the front"); + assert!(frame.size.iter().all(|side| (side - 2.0).abs() < 1e-3) && frame.center.iter().all(|c| c.abs() < 1e-3), "around the unit sphere: {frame:?}"); + let unpulled = snapshot(&mut s); + assert_ne!(unpulled, empty); + + let pulled = json!([[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]]); + set(&mut s, layer, json!({"warpCorners": pulled})); + let bent = snapshot(&mut s); + assert_ne!(bent, unpulled, "a pulled corner bends the image"); + set(&mut s, layer, json!({"projection": "warp", "rotation": 0})); + assert_eq!(snapshot(&mut s), bent, "picking warp again keeps the corners"); + + set(&mut s, layer, json!({"shapeCrop": "cropped", "warpCorners": Projection::FRAME_CORNERS})); + let cropped = snapshot(&mut s); + + // Depth 0.1 of a frame 2 wide reaches 0.2 in front of and behind the frame through the sphere's middle + let (beyond, within) = (facing_z(&s, 0.35, 1.1), facing_z(&s, -0.05, 0.05)); + assert!(!beyond.is_empty() && !within.is_empty()); + assert!(beyond.iter().all(|&i| cropped[i] == empty[i]), "past its Projection Depth the warp does not reach"); + assert!(within.iter().all(|&i| cropped[i] == unpulled[i]), "within it the warp covers as before"); + set(&mut s, layer, json!({"projectionDepth": 1})); + let deep = snapshot(&mut s); + assert!(beyond.iter().all(|&i| deep[i] == unpulled[i]), "a deeper warp reaches the whole sphere"); + + set(&mut s, layer, json!({"warpCorners": pulled})); + execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).unwrap(); + let Projection::Warp { frame: reset, corners, depth, .. } = projection(&s, layer) else { panic!("still a warp") }; + assert_eq!((reset, corners, depth), (frame, Projection::FRAME_CORNERS, 1.0), "the frame and corners go back; the depth stays"); + let steps = s.history_labels().len(); + execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "resetting a frame already reset adds no undo step"); + + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["projection"], "Warp projection"); + assert_eq!(row["fill"]["projectionSettings"]["Warp"]["corners"], json!(Projection::FRAME_CORNERS)); + set(&mut s, layer, json!({"projection": "planar"})); + assert!(execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).is_err(), "only a warp has a frame to reset"); +} + +/// Depth culling keeps planar and warp projections off surfaces hidden behind others from the projector; new ones start with it on, older saves without it +#[test] +fn depth_culling_keeps_planar_and_warp_projections_off_hidden_surfaces() { + let mut s = session(); + let layer = checker_fill(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": false})).unwrap(); + let empty = snapshot(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": true})).unwrap(); + set(&mut s, layer, json!({"projection": "planar", "axis": 2})); + let Projection::Planar { projector, .. } = projection(&s, layer) else { panic!("{:?}", projection(&s, layer)) }; + assert_eq!(projector.depth, DepthCulling::NEW, "a new planar projection culls by depth"); + let culled = snapshot(&mut s); + set(&mut s, layer, json!({"depthCulling": false})); + let plain = snapshot(&mut s); + + // The sphere's far side sits behind its near side, seen from +Z + let (far, near) = (facing_z(&s, -1.1, -0.3), facing_z(&s, 0.3, 1.1)); + assert!(!far.is_empty() && !near.is_empty()); + assert!(far.iter().any(|&i| plain[i] != empty[i]), "without depth culling the far side gets the projection"); + assert!(far.iter().all(|&i| culled[i] == empty[i]), "hidden behind the near side, the far side gets none of it"); + assert!(near.iter().all(|&i| culled[i] == plain[i]), "the near side keeps all of it"); + + set(&mut s, layer, json!({"depthCulling": true, "depthCullingHardness": 0})); + assert_ne!(snapshot(&mut s), culled, "a softer cull fades further behind the near side"); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["projectionSettings"]["Planar"]["projector"]["depth"], json!({"on": true, "hardness": 0.0})); + + set(&mut s, layer, json!({"projection": "warp"})); + let Projection::Warp { projector, .. } = projection(&s, layer) else { panic!("{:?}", projection(&s, layer)) }; + assert_eq!(projector.depth, DepthCulling::NEW, "a new warp culls by depth"); + let warped = snapshot(&mut s); + assert!(far.iter().all(|&i| warped[i] == empty[i]), "a warp from the front leaves the far side bare"); + + let saved: Projector = serde_json::from_value(json!({"rotation": [0, 0, 0], "scale": [1, 1, 1]})).unwrap(); + assert_eq!(saved.depth, DepthCulling { on: false, hardness: 0.75 }, "an older save has no depth culling"); +} + +/// Texels of `far` that `values` gives something other than the bare `empty` +fn filled(far: &[usize], values: &[f32], empty: &[f32]) -> usize { + far.iter().filter(|&&i| values[i] != empty[i]).count() +} + +/// The symmetry axis is read from an index or from the letter tool.brush takes; any other value is refused, never ignored +#[test] +fn fill_symmetry_axis_reads_an_index_or_a_letter() { + let mut s = session(); + let layer = checker_fill(&mut s); + let axis = |s: &Session| match &s.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(fill) => fill.sampling.symmetry.axis, + _ => panic!("a fill layer"), + }; + + set(&mut s, layer, json!({"symmetryAxis": "Y"})); + assert_eq!(axis(&s), 1); + set(&mut s, layer, json!({"symmetryAxis": 2})); + assert_eq!(axis(&s), 2); + + for refused in [json!("w"), json!(true), json!(-1), json!(3)] { + assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryAxis": refused})).is_err(), "{refused}"); + } + assert_eq!(axis(&s), 2, "a refused axis changes nothing"); +} + +/// Mirror and radial symmetry copy a planar projection onto the sphere's far side and leave the near side as it was; Flip copy turns the copies' images over; UV projections and older saves have no copies +#[test] +fn fill_symmetry_mirrors_or_turns_copies_of_a_3d_projection() { + let mut s = session(); + let layer = checker_fill(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": false})).unwrap(); + let empty = snapshot(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": true})).unwrap(); + + // Depth culled from +Z, the planar projection reaches only the near side + set(&mut s, layer, json!({"projection": "planar", "axis": 2})); + let plain = snapshot(&mut s); + let (far, near) = (facing_z(&s, -1.1, -0.3), facing_z(&s, 0.3, 1.1)); + assert_eq!(filled(&far, &plain, &empty), 0); + + set(&mut s, layer, json!({"symmetry": true, "symmetryType": "mirror", "symmetryAxis": 2})); + let mirrored = snapshot(&mut s); + assert!(filled(&far, &mirrored, &empty) > far.len() / 2, "the mirror copy reaches the far side"); + assert!(near.iter().all(|&i| mirrored[i] == plain[i]), "the original keeps its own half"); + + set(&mut s, layer, json!({"symmetryType": "radial", "symmetryAxis": 1, "symmetryCount": 2})); + let turned = snapshot(&mut s); + assert!(filled(&far, &turned, &empty) > far.len() / 2, "the copy turned half round reaches the far side"); + assert!(near.iter().all(|&i| turned[i] == plain[i]), "the original keeps its own wedge"); + assert_ne!(turned, mirrored, "a turned copy is not a mirrored one"); + set(&mut s, layer, json!({"symmetry": false})); + assert_eq!(snapshot(&mut s), plain, "switched off, the copies go"); + + // A left to right ramp shows a copy's image turned over + let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "image": ramp})).unwrap(); + set(&mut s, layer, json!({"symmetry": true})); + let copied = snapshot(&mut s); + set(&mut s, layer, json!({"flipCopy": [true, false]})); + let flipped = snapshot(&mut s); + assert!(far.iter().filter(|&&i| (flipped[i] - copied[i]).abs() > 0.1).count() > far.len() / 4, "Flip copy U turns the copy's ramp round"); + assert!(near.iter().all(|&i| flipped[i] == copied[i]), "the original is never flipped"); + + set(&mut s, layer, json!({"projection": "uv"})); + let uv = snapshot(&mut s); + set(&mut s, layer, json!({"symmetry": false})); + assert_eq!(snapshot(&mut s), uv, "a UV projection has no copies"); + + assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryType": "spiral"})).is_err()); + assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryAxis": 3})).is_err()); + let saved: Sampling = serde_json::from_value(json!({"filtering": "BilinearHq", "wrap": "Repeat", "scale": "Tiling"})).unwrap(); + assert_eq!(saved.symmetry, FillSymmetry::OFF, "an older save has no symmetry"); +} + +/// Moving an axis planar on the model first places it as the frame it projects from: nothing moves until the frame does, and undo puts the axis planar back +#[test] +fn moving_an_axis_planar_places_it_as_its_frame_first() { + let mut s = session(); + let layer = checker_fill(&mut s); + let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "image": ramp})).unwrap(); + set(&mut s, layer, json!({"projection": "planar", "axis": 0, "scale": 1.5, "offset": [0.2, -0.1, 0.0], "projectorRotation": [0, 30, 10]})); + let axis = projection(&s, layer); + let before = snapshot(&mut s); + + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0})).unwrap(); + let placed = projection(&s, layer); + let Projection::Planar { placed: Some(frame), projector, .. } = &placed else { panic!("placed: {placed:?}") }; + assert_eq!((projector.rotation, projector.scale), ([0.0; 3], [1.0; 3]), "the turn is in the frame now"); + let after = snapshot(&mut s); + let moved = before.iter().zip(&after).filter(|(a, b)| (*a - *b).abs() > 2.0 / 255.0).count(); + assert!(moved * 200 < before.len(), "the image stays where it was: {moved} of {} texels changed", before.len()); + + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "offset": [0.4, 0.0], "merge": true})).unwrap(); + assert_ne!(snapshot(&mut s), after, "then the frame moves the image"); + let Projection::Planar { placed: Some(slid), .. } = projection(&s, layer) else { panic!("still placed") }; + assert_eq!((slid.offset, slid.size), ([0.4, 0.0], frame.size)); + + s.undo().unwrap(); + assert_eq!(projection(&s, layer), axis, "placing and moving is one step"); + + set(&mut s, layer, json!({"projection": "warp", "warpCorners": [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]]})); + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "rotation": 30})).unwrap(); + let Projection::Warp { frame, corners, .. } = projection(&s, layer) else { panic!("still a warp") }; + assert_eq!((frame.rotation, corners[1]), (30.0, [0.9, 0.9]), "a warp's frame turns and keeps its corners"); + set(&mut s, layer, json!({"projection": "spherical"})); + assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "rotation": 30})).is_err(), "a spherical projection has no frame"); +} + +/// An axis planar reading a procedural keeps its axis: a placed frame reads the pattern in its own uv, so placing it would move the pattern; a mask fill's pattern stays the same way +#[test] +fn an_axis_planar_reading_a_pattern_is_not_placed() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "planar", "axis": 0, "scale": 1.5})); + let axis = projection(&s, layer); + let before = snapshot(&mut s); + + assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0})).is_err(), "placing would move the pattern"); + assert_eq!(projection(&s, layer), axis, "the planar keeps its axis"); + assert_eq!(snapshot(&mut s), before, "and the pattern stays where it was"); + + let added = execute(&mut s, "effect.add.fill", &json!({"layer": layer.0, "target": "mask", "projection": "planar"})).unwrap(); + let effect = added["effect"].as_u64().unwrap(); + + assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "effect": effect})).is_err(), "a mask fill's pattern keeps its axis too"); +} + +/// Backface culling under an uneven or mirrored projector scale cannot keep its facing in a frame: moving it is refused with the way out, and nothing changes +#[test] +fn a_frame_under_uneven_culling_is_refused_with_the_way_out_and_changes_nothing() { + let mut s = session(); + let layer = checker_fill(&mut s); + let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "image": ramp})).unwrap(); + set(&mut s, layer, json!({"projection": "planar", "axis": 2, "backfaceCulling": true})); + + // An axis planar with an uneven then a mirrored scale, then a placed frame with an uneven one + for (scale, placed) in [(json!([2, 1, 1]), false), (json!([1.5, -1.5, 1.5]), false), (json!([2, 1, 1]), true)] { + let edit = if placed { json!({"layer": layer.0, "frameOffset": [0.1, 0, 0]}) } else { json!({"layer": layer.0}) }; + if placed { + set(&mut s, layer, json!({"projectorScale": 1})); + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0})).unwrap(); + assert!(projection(&s, layer).placed().is_some(), "an even scale places the frame"); + } + + set(&mut s, layer, json!({"projectorScale": scale})); + let before = projection(&s, layer); + let steps = s.history_labels().len(); + + let refused = execute(&mut s, "layer.decal.set", &edit).unwrap_err().to_string(); + + assert!(refused.contains("even out the projector scale or turn backface culling off"), "{scale} placed {placed}: {refused}"); + assert_eq!(projection(&s, layer), before, "{scale} placed {placed}: the projection is unchanged"); + assert_eq!(s.history_labels().len(), steps, "{scale} placed {placed}: no undo step"); + } + + // A placed frame's edit that moves no frame still lands + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "flipU": true})).unwrap(); + assert!(projection(&s, layer).frame().is_some_and(|frame| frame.flip[0]), "the flip lands on the placed frame"); +} + +/// A frame's 3D projection settings (Offset, Rotation, Scale as the panel and the gizmo share them) move it in one undo step, and a turned or scaled projector folds into the frame first, landing the same +#[test] +fn a_frame_takes_its_offset_rotation_and_scale_and_folds_its_projector_in_first() { + let mut s = session(); + let layer = checker_fill(&mut s); + let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "image": ramp})).unwrap(); + set(&mut s, layer, json!({"projection": "planar", "axis": 2})); + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0})).unwrap(); + + // Depth culling off: its depth map is drawn along the frame, so a folded turn re-draws it (a few silhouette texels differ) + set(&mut s, layer, json!({"projectorRotation": [0, 0, 30], "projectorScale": 1.25, "depthCulling": false})); + let turned = snapshot(&mut s); + let steps = s.history_labels().len(); + + // Moving the frame as shown: the turn and scale are in the frame now, the image where it was + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameOffset": [0.0, 0.0, 0.0]})).unwrap(); + let Projection::Planar { placed: Some(frame), projector, .. } = projection(&s, layer) else { panic!("still placed") }; + assert_eq!((projector.rotation, projector.scale), ([0.0; 3], [1.0; 3]), "folded into the frame"); + let (lo, hi) = s.mesh.bounds(); + assert!((Vec3::from(frame.center) - (lo + hi) * 0.5).length() < 1e-4, "offset 0 = the mesh's centre: {frame:?}"); + let shown = texturecraft_engine::compose::frame_placement::placement(&projection(&s, layer), (lo, hi)).unwrap(); + assert!((shown.rotation[2] - 30.0).abs() < 1e-3 && shown.rotation[0].abs() < 1e-3, "the projector's turn shows as the frame's: {shown:?}"); + let folded = snapshot(&mut s); + let changed = turned.iter().zip(&folded).filter(|(a, b)| (*a - *b).abs() > 2.0 / 255.0).count(); + assert!(changed * 200 < turned.len(), "the frame was already at the centre: the image stays, {changed} of {} texels changed", turned.len()); + + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameScale": [shown.scale[0] * 0.5, shown.scale[1], shown.scale[2]], "merge": true})) + .unwrap(); + let Projection::Planar { placed: Some(narrow), .. } = projection(&s, layer) else { panic!("still placed") }; + assert!((narrow.size[0] - frame.size[0] * 0.5).abs() < 1e-4 && (narrow.size[1] - frame.size[1]).abs() < 1e-4, "Scale X halves the width"); + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameRotation": [0, 0, 90], "merge": true})).unwrap(); + let again = texturecraft_engine::compose::frame_placement::placement(&projection(&s, layer), (lo, hi)).unwrap(); + assert!((again.rotation[2] - 90.0).abs() < 1e-3 && (again.scale[0] - shown.scale[0] * 0.5).abs() < 1e-4, "{again:?}"); + assert_eq!(s.history_labels().len(), steps + 1, "a drag is one undo step"); + s.undo().unwrap(); + assert_eq!(snapshot(&mut s), turned, "undo puts the turned projector back"); + + for bad in [json!({"frameScale": [1, 2]}), json!({"frameOffset": "x"}), json!({"frameScale": [0, -1, "deep"]})] { + let mut params = bad.clone(); + params["layer"] = json!(layer.0); + assert!(execute(&mut s, "layer.decal.set", ¶ms).is_err(), "{bad}"); + } + + // A collapsed or turned-over scale is clamped to the smallest frame, not refused + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameScale": [0, -1, 0]})).unwrap(); + let Projection::Planar { placed: Some(smallest), .. } = projection(&s, layer) else { panic!("still placed") }; + assert!(smallest.size.iter().chain([&smallest.depth]).all(|side| *side > 0.0 && side.is_finite()), "{smallest:?}"); + + // A warp's Scale Z is its reach: Projection Depth times the longer side + set(&mut s, layer, json!({"projection": "warp"})); + let Projection::Warp { frame, .. } = projection(&s, layer) else { panic!("a warp") }; + let diagonal = (hi - lo).length(); + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameScale": [frame.size[0] / diagonal, frame.size[1] / diagonal, 0.1]})).unwrap(); + let Projection::Warp { frame, depth, .. } = projection(&s, layer) else { panic!("a warp") }; + assert!((depth * frame.size[0].max(frame.size[1]) - 0.1 * diagonal).abs() < 1e-4, "reach {depth}"); +} + +/// A decal edit that moves nothing and keeps its image adds no undo step and leaves the project unmodified; one that moves it adds one +#[test] +fn a_decal_edit_that_changes_nothing_adds_no_undo_step() { + let mut s = session(); + let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap(); + let added = execute(&mut s, "layer.add.decal", &json!({"image": ramp, "position": [0, 0, 1], "normal": [0, 0, 1], "rotation": 30})).unwrap(); + let layer = added["layer"].as_u64().unwrap(); + let mask = execute(&mut s, "layer.add.decal", &json!({"image": ramp, "channel": "mask", "position": [0, 0, 1], "normal": [0, 0, 1]})).unwrap(); + let mask_effect = mask["maskEffect"].as_u64().unwrap(); + let steps = s.history_labels().len(); + + for unchanged in [ + json!({"layer": layer}), + json!({"layer": layer, "rotation": 30}), + json!({"layer": layer, "image": ramp}), + json!({"layer": layer, "offset": [0, 0]}), + json!({"effect": mask_effect}), + json!({"effect": mask_effect, "image": ramp}), + ] { + execute(&mut s, "layer.decal.set", &unchanged).unwrap(); + assert_eq!(s.history_labels().len(), steps, "{unchanged} changes nothing"); + } + + execute(&mut s, "layer.decal.set", &json!({"layer": layer, "rotation": 45})).unwrap(); + assert_eq!(s.history_labels().len(), steps + 1, "a turn is an edit"); +} + +/// Inspect shows the frame a decal was placed on, for a decal placed as a mask as for one placed as a layer +#[test] +fn inspect_shows_a_mask_decals_frame_as_a_layer_decals() { + let mut s = session(); + let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap(); + let placement = json!({"image": ramp, "position": [0, 0, 1], "normal": [0, 0, 1], "size": 0.5}); + let layer_decal = execute(&mut s, "layer.add.decal", &placement).unwrap(); + let mut mask_placement = placement.clone(); + mask_placement["channel"] = json!("mask"); + let mask_decal = execute(&mut s, "layer.add.decal", &mask_placement).unwrap(); + + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let layers = inspect["layers"].as_array().unwrap(); + let row = |id: &Value| layers.iter().find(|layer| &layer["id"] == id).unwrap().clone(); + let layer_frame = row(&layer_decal["layer"])["fill"]["decal"].clone(); + let mask_effects = row(&mask_decal["layer"])["mask"]["effects"].clone(); + let mask_effect = mask_effects.as_array().unwrap().iter().find(|effect| effect["id"] == mask_decal["maskEffect"]).unwrap().clone(); + + // Each side holds a frame on the requested point and normal, so two missing frames cannot match as nulls + let on_request = |frame: &Value| { + let near = |key: &str, want: [f64; 3]| { + frame[key] + .as_array() + .is_some_and(|got| got.len() == 3 && got.iter().zip(want).all(|(got, want)| got.as_f64().is_some_and(|got| (got - want).abs() < 1e-3))) + }; + near("center", [0.0, 0.0, 1.0]) && near("normal", [0.0, 0.0, 1.0]) + }; + for (name, frame) in [ + ("layer decal", &layer_frame), + ("layer decal reply", &layer_decal["decal"]), + ("mask decal", &mask_effect["decal"]), + ("mask decal reply", &mask_decal["decal"]), + ] { + assert!(on_request(frame), "the {name} shows its frame on the requested placement: {frame}"); + } + assert_eq!(layer_frame, layer_decal["decal"], "a layer decal's frame"); + assert_eq!(mask_effect["decal"], mask_decal["decal"], "a mask decal's frame"); +} + +/// `depth` on a warp sets how far it reaches: its Projection Depth becomes the depth over the frame's longer side +#[test] +fn a_warps_depth_sets_its_projection_depth() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "warp"})); + + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "depth": 0.5})).unwrap(); + let Projection::Warp { frame, depth, .. } = projection(&s, layer) else { panic!("a warp") }; + assert!((depth * frame.size[0].max(frame.size[1]) - 0.5).abs() < 1e-5, "reach {depth} × {:?}", frame.size); +} + +/// `depth` at a warp's current reach changes nothing, so it adds no undo step (its frame's unused depth is left alone) +#[test] +fn a_warps_current_reach_as_depth_adds_no_undo_step() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "warp", "projectionDepth": 0.5})); + let Projection::Warp { frame, depth, .. } = projection(&s, layer) else { panic!("a warp") }; + let steps = s.history_labels().len(); + + let reach = depth * frame.size[0].max(frame.size[1]); + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "depth": reach})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "reach {reach} is the one it has"); +} + +/// A frameScale reach on a warp keeps its Projection Depth within the range `projectionDepth` allows +#[test] +fn a_warps_frame_scale_keeps_its_projection_depth_in_range() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "warp"})); + + let deepest = checker_fill(&mut s); + set(&mut s, deepest, json!({"projection": "warp", "projectionDepth": 1e9})); + let Projection::Warp { depth: max_depth, .. } = projection(&s, deepest) else { panic!("a warp") }; + + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameScale": [0.0001, 0.0001, 10]})).unwrap(); + let Projection::Warp { depth, .. } = projection(&s, layer) else { panic!("a warp") }; + assert!(depth <= max_depth, "Projection Depth {depth} past {max_depth}"); +} + +/// A 64 × 8 PNG whose red climbs from left to right +fn ramp_png() -> Vec { + let mut out = Vec::new(); + let ramp = image::RgbaImage::from_fn(64, 8, |x, _| image::Rgba([(x * 4) as u8, 0, 0, 255])); + ramp.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +/// Reset fill settings puts the Fill section back to the defaults of the projection it uses, in one undo step, and leaves the projection kind, the symmetry and sources alone +#[test] +fn reset_fill_settings_keeps_the_projection_and_restores_its_defaults_in_one_undo_step() { + let mut s = session(); + let layer = checker_fill(&mut s); + let fresh = snapshot(&mut s); + set( + &mut s, + layer, + json!({"projection": "planar", "tiling": [3, 2], "rotation": 30, "axis": 0, "filtering": "nearest", "wrap": "none", "scaleMode": "physicalSize", "shapeCrop": "cropped", "symmetry": true, "symmetryAxis": 1}), + ); + let fill = |s: &Session| match &s.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(f) => f.clone(), + _ => panic!("a fill layer"), + }; + let changed = fill(&s); + assert!(!texturecraft_engine::fill_reset_cmds::at_defaults(&changed.projection, changed.sampling)); + + execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap(); + let reset = fill(&s); + let Projection::Planar { scale, axis, offset, uv, projector, placed } = reset.projection else { panic!("still planar, got {:?}", reset.projection) }; + assert_eq!((scale, axis, offset, uv, placed), (1.0, 2, [0.0; 3], UvTransform::default(), None), "a new planar's placement"); + assert_eq!(projector, Projector::depth_culled(), "a new planar's 3D settings and culling"); + assert_eq!(reset.sampling, Sampling { symmetry: changed.sampling.symmetry, ..Sampling::default() }, "the sampling is a new fill's; the symmetry stays"); + assert_eq!(reset.sources, changed.sources, "the material stays"); + assert!(texturecraft_engine::fill_reset_cmds::at_defaults(&reset.projection, reset.sampling)); + let steps = s.history_labels().len(); + execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "resetting a Fill section at its defaults adds no undo step"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(fill(&s), changed, "one undo brings every setting back"); + assert!(execute(&mut s, "layer.fill.resetProjection", &json!({"layer": 9999})).is_err(), "no such layer"); + + // A UV fill comes back to a UV projection at tiling 1 and renders like a new fill + set(&mut s, layer, json!({"projection": "uv", "tiling": [3, 2], "rotation": 30})); + execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap(); + assert_eq!(fill(&s).projection, Projection::default()); + assert_eq!(snapshot(&mut s), fresh, "it renders like the new fill"); +} + +/// A warp's reset keeps its frame where it is placed and restores its corners, Projection Depth, UV transform and projector settings +#[test] +fn reset_fill_settings_keeps_a_warp_frame_and_restores_its_settings() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "warp"})); + let Projection::Warp { frame: fitted, .. } = projection(&s, layer) else { panic!("a warp") }; + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "offset": [0.2, 0.1]})).unwrap(); + set( + &mut s, + layer, + json!({"warpCorners": [[-0.6, 0.5], [0.5, 0.6], [0.4, -0.5], [-0.5, -0.4]], "projectionDepth": 0.5, "tiling": [2, 2], "rotation": 45, "shapeCrop": "extendsOutside"}), + ); + let Projection::Warp { frame: moved, .. } = projection(&s, layer) else { panic!("a warp") }; + assert_ne!(moved, fitted, "the frame was moved"); + + execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap(); + assert_eq!(projection(&s, layer), Projection::warp(moved), "still a warp: its frame stays, every setting is a new warp's"); +} + +#[test] +fn malformed_warp_corners_copy_flips_and_a_warps_own_placement_are_rejected_and_change_nothing() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "warp"})); + let before = projection(&s, layer); + let steps = s.history_labels().len(); + + for bad in [ + json!({"warpCorners": [[1, 2]]}), + json!({"warpCorners": [[0, 0], [0, 0], [0, 0], ["x", 0]]}), + json!({"warpCorners": "pulled"}), + json!({"flipCopy": [true, "x"]}), + // A warp is placed by its frame (layer.decal.set): a scale or offset of its own would change nothing + json!({"scale": 2}), + json!({"offset": [1, 0, 0]}), + json!({"projection": "warp", "scale": 2, "offset": [1, 0, 0]}), + ] { + let mut p = bad.clone(); + p["layer"] = json!(layer.0); + assert!(execute(&mut s, "layer.fill.projection", &p).is_err(), "{bad}"); + } + + assert_eq!(projection(&s, layer), before); + assert_eq!(s.history_labels().len(), steps, "no undo step for a rejected edit"); +} diff --git a/crates/ui-egui/src/fill_panel.rs b/crates/ui-egui/src/fill_panel.rs new file mode 100644 index 00000000..b58dcde4 --- /dev/null +++ b/crates/ui-egui/src/fill_panel.rs @@ -0,0 +1,484 @@ +//! A fill's Properties: its projection, size, placement and edges, then its material + +use std::ops::RangeInclusive; + +use egui::{Painter, Rect}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::compose::frame_placement; +use texturecraft_engine::compose::tile_length::{MeshSize, tile_length, tiling_for_length}; +use texturecraft_engine::layer_cmds::{MAX_PLACEMENT, MIN_SCALE}; +use texturecraft_engine::paint::FULL_TURN_DEGREES; + +use crate::TextureCraftApp; +use crate::dock::with; +use crate::fill_pictures::{ + angle_picture, backface_picture, crop_picture, depth_picture, filtering_picture, projection_picture, warp_preview, window_preview, wrap_picture, +}; +use crate::i18n::{filtering_label, n_, tr, wrap_label}; +use crate::move_on_model::MoveOnModel; +use crate::placement::Placement; +use crate::projection_kind::ProjectionKind; +use crate::projection_preview::projection_preview; +use crate::property_sheet::{NumberField, PreviewLower, PreviewSize, PropertySheet, RowLead}; +use crate::theme::{AXIS_COLORS, AXIS_NAMES, Tokens}; + +/// Centimetres in one mesh unit: meshes are read in metres +const CM_PER_UNIT: f32 = 100.0; + +/// What the Tiling track spans +const TILING_TRACK: RangeInclusive = 0.01..=5.0; + +/// What a typed tiling may be: the command's own limits +const TILING_TYPED: RangeInclusive = MIN_SCALE..=MAX_PLACEMENT; + +/// What the Size (cm) track spans +const SIZE_CM_TRACK: RangeInclusive = 1.0..=500.0; + +/// What a typed size (cm) may be +const SIZE_CM_TYPED: RangeInclusive = 0.1..=100_000.0; + +/// What an Offset track spans (tiles, centred on zero) +const OFFSET_TRACK: RangeInclusive = -2.0..=2.0; + +/// What a typed offset may be (tiles): the command's own limits +const OFFSET_TYPED: RangeInclusive = -MAX_PLACEMENT..=MAX_PLACEMENT; + +/// Range of a fill's rotation, a full turn +const ROTATION_RANGE: RangeInclusive = 0.0..=FULL_TURN_DEGREES; + +/// Tri-planar blend's largest exponent: Hardness 1 (0 = exponent 1, 0.5 = 8) +const TRIPLANAR_SHARPNESS_MAX: f32 = *Projection::TRIPLANAR_SHARPNESS_RANGE.end(); + +/// Range of every Hardness the panel shows +const HARDNESS_RANGE: RangeInclusive = 0.0..=1.0; + +/// What a cylindrical projection's Angle may be: the arc one repeat spans, in degrees +const CYLINDER_ANGLE_RANGE: RangeInclusive = Projection::CYLINDER_ANGLE_RANGE; + +/// What Backface culling's Angle may be, in degrees from facing the projector +const BACKFACE_ANGLE_RANGE: RangeInclusive = Backface::ANGLE_RANGE; + +/// What the Projection Depth track spans, in lengths of the frame's longer side +const PROJECTION_DEPTH_TRACK: RangeInclusive = 0.0..=1.0; + +/// A degenerate warp frame's preview size: its side spans the preview's middle +const WARP_SPAN_FALLBACK: f32 = 1.7; + +/// Change per pixel dragged on a 3D offset field +pub(crate) const OFFSET_FIELD_SPEED: f32 = 0.01; + +/// Change per pixel dragged on a 3D rotation field, in degrees +const ROTATION_FIELD_SPEED: f32 = 0.5; + +/// Change per pixel dragged on a 3D scale field +const SCALE_FIELD_SPEED: f32 = 0.01; + +} + +/// Which fill a `base` addresses, (layer, effect), as the salt of its rows' widget state +pub(crate) type FillKey = (Option, Option); + +/// The [`FillKey`] of the fill at `base` +pub(crate) fn fill_key(base: &Value) -> FillKey { + (base.get("layer").and_then(Value::as_u64), base.get("effect").and_then(Value::as_u64)) +} + +/// The mesh's size for the texture set being painted, as the projections see it, measured once per mesh and material +fn mesh_size(app: &TextureCraftApp, ctx: &egui::Context) -> MeshSize { + let mesh = &app.session.mesh; + let material = app.session.doc.project.texture_set(app.session.ts()).map_or(0, |texture_set| texture_set.material); + let key = (app.session.mesh_id, material); + + // Both measures walk the whole mesh, too slow for every frame the sheet draws on a dense mesh + let cache_id = egui::Id::unique("tc_fill_mesh_size"); + if let Some((cached_key, size)) = ctx.data(|data| data.get_temp::<((u64, usize), MeshSize)>(cache_id)) + && cached_key == key + { + return size; + } + + let size = MeshSize { radius: mesh.radius(), uv_density: mesh.uv_density(material).unwrap_or(1.0) }; + ctx.data_mut(|data| data.insert_temp(cache_id, (key, size))); + size +} + +/// The Fill section (with its reset) and the Symmetry section of the fill at `base`: a fill layer's, a content fill effect's or a mask fill's +pub(crate) fn placement_sections(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value, reader: LayerId) { + // The section reset: projection, placement, sampling and culling back to a new fill's in one undo step + if sheet.section_reset(tr("Fill"), !texturecraft_engine::fill_reset_cmds::at_defaults(&fill.projection, fill.sampling)) { + app.run("layer.fill.resetProjection", base.clone()); + } + projection_rows(app, sheet, fill, base, fill_key(base), reader); + crate::fill_symmetry_panel::symmetry_section(app, sheet, &fill.projection, fill.sampling, base); +} + +/// Runs `layer.fill.projection` on the fill `base` names with `fields` +pub(crate) fn run_projection(app: &mut TextureCraftApp, base: &Value, fields: Value) { + app.run("layer.fill.projection", with(base, fields)); +} + +/// Projection, Scale, the preview with size and offset (held, it moves the projection on the model), Rotation, the culling rows, then the Filtering and edges and 3D projection settings bands +fn projection_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value, salt: FillKey, reader: LayerId) { + let tokens = Tokens::get(sheet.ui.ctx()); + let kind = ProjectionKind::of(&fill.projection); + let run = |app: &mut TextureCraftApp, fields: Value| run_projection(app, base, fields); + + let picture = |painter: &Painter, rect: Rect, kind: ProjectionKind| projection_picture(painter, rect, kind, &tokens); + + // A projection with a gizmo in the 3D view ends its row in the eye that shows or hides it (a view setting saved with the project) + let gizmos = app.session.doc.project.display.projection_gizmos; + let tip = if gizmos { tr("Hide projection gizmos") } else { tr("Show projection gizmos") }; + let name = |kind: ProjectionKind| tr(kind.label()).to_owned(); + let (picked, eye) = if matches!(kind, ProjectionKind::Uv | ProjectionKind::UvTile) { + (sheet.dropdown(tr("Projection"), kind, &ProjectionKind::ALL, name, Some(&picture)).0, false) + } else { + sheet.dropdown_with_eye(tr("Projection"), kind, &ProjectionKind::ALL, name, Some(&picture), (gizmos, tip)) + }; + if let Some(kind) = picked { + run(app, json!({"projection": kind.id()})); + } + if eye { + app.run("display.set", json!({"projectionGizmos": !gizmos})); + } + + // Per UV tile, the source fills each tile once: nothing to place + if kind == ProjectionKind::UvTile { + return; + } + + let size = mesh_size(app, sheet.ui.ctx()); + let length = tile_length(&fill.projection, size); + let physical = length.is_some() && fill.sampling.scale == ScaleMode::PhysicalSize; + if length.is_some() { + let modes = [tr("Tiling"), tr("Physical size")]; + if let Some(index) = sheet.switch(tr("Scale"), &modes, usize::from(physical)) + && let Some(mode) = ScaleMode::ALL.get(index) + { + run(app, json!({"scaleMode": mode.id()})); + } + } + + // Move on model: hold the preview square and drag to slide the projection + let target = match base.get("effect").and_then(Value::as_u64) { + Some(effect) => MoveOnModel { layer: reader, effect: Some(LayerId(effect)) }, + None => MoveOnModel::layer(reader), + }; + placement_rows(app, sheet, fill, base, length.filter(|_| physical), size, target); + frame_rows(app, sheet, fill, base); + culling_rows(app, sheet, fill, base); + + let crop = projector_of(&fill.projection).map(|projector| projector.crop); + let shows_wrap = kind != ProjectionKind::Triplanar; + let edges_changed = fill.sampling.filtering != Filtering::default() + || (shows_wrap && fill.sampling.wrap != UvWrap::default()) + || crop.is_some_and(|crop| crop != ShapeCrop::default()); + let band = sheet.band(tr("Filtering and edges"), true, Some(edges_changed), None); + if band.reset { + let mut fields = json!({"filtering": Filtering::default().id(), "wrap": UvWrap::default().id()}); + if crop.is_some() { + fields["shapeCrop"] = json!(ShapeCrop::default().id()); + } + run(app, fields); + } + if band.open { + let filtering = fill.sampling.filtering; + let picture = |painter: &Painter, rect: Rect, filtering: Filtering| filtering_picture(painter, rect, filtering, &tokens); + let (picked, _) = sheet.dropdown(tr("Filtering"), filtering, &Filtering::ALL, |filtering| tr(filtering_label(filtering)).to_owned(), Some(&picture)); + if let Some(filtering) = picked { + run(app, json!({"filtering": filtering.id()})); + } + + // Tri-planar has no tile to repeat + if shows_wrap { + let picture = |painter: &Painter, rect: Rect, wrap: UvWrap| wrap_picture(painter, rect, wrap, &tokens); + let (picked, _) = sheet.dropdown(tr("UV Wrap"), fill.sampling.wrap, &UvWrap::ALL, |wrap| tr(wrap_label(wrap)).to_owned(), Some(&picture)); + if let Some(wrap) = picked { + run(app, json!({"wrap": wrap.id()})); + } + } + if let Some(projector) = projector_of(&fill.projection) { + let picture = |painter: &Painter, rect: Rect, crop: ShapeCrop| crop_picture(painter, rect, crop, &tokens); + let (picked, _) = sheet.dropdown(tr("Shape crop"), projector.crop, &ShapeCrop::ALL, |crop| tr(crop_label(crop)).to_owned(), Some(&picture)); + if let Some(crop) = picked { + run(app, json!({"shapeCrop": crop.id()})); + } + } + } + + world_rows(app, sheet, fill, base, salt); +} + +/// The settings of the projector itself, shared by every 3D projection +fn projector_of(projection: &Projection) -> Option<&Projector> { + match projection { + Projection::Triplanar { projector, .. } + | Projection::Planar { projector, .. } + | Projection::Spherical { projector, .. } + | Projection::Cylindrical { projector, .. } + | Projection::Warp { projector, .. } => Some(projector), + Projection::Uv { .. } | Projection::UvTile => None, + } +} + +/// The name of a Shape crop choice; both fit beside the label at the default panel width +fn crop_label(crop: ShapeCrop) -> &'static str { + match crop { + ShapeCrop::Cropped => n_("Cropped to Shape"), + ShapeCrop::ExtendsOutside => n_("Extends Outside Shape"), + } +} + +/// Tri-planar Hardness as the panel shows it (0..1) from the blend's exponent (1..64): exponent = 64^hardness +fn triplanar_hardness(sharpness: f32) -> f32 { + (sharpness.max(1.0).ln() / TRIPLANAR_SHARPNESS_MAX.ln()).clamp(0.0, 1.0) +} + +/// The blend's exponent for a tri-planar Hardness the panel shows +fn triplanar_sharpness(hardness: f32) -> f32 { + TRIPLANAR_SHARPNESS_MAX.powf(hardness.clamp(0.0, 1.0)) +} + +/// A warp's Projection Depth and Reset frame +fn frame_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value) { + let Projection::Warp { depth, .. } = &fill.projection else { return }; + let mut depth = *depth; + + // Its i tells it apart from Depth culling; it keeps the column every projection shares + sheet.info(tr("How far the warp projection reaches into the mesh, in front of and behind its frame, in lengths of the frame's longer side. It bounds the fill only when cropped to its shape.")); + if let Some(merge) = sheet.slider_led(RowLead::Loose(tr("Depth")), &mut depth, PROJECTION_DEPTH_TRACK, 2, "") { + run_projection(app, base, json!({"projectionDepth": depth, "merge": merge})); + } + if sheet.button(ic::ARROW_CLOCKWISE, tr("Reset frame")).clicked() { + app.run("layer.fill.resetFrame", base.clone()); + } +} + +/// Cylindrical Angle, then Depth culling (planar, warp) and Backface culling (planar, cylindrical), each with its settings under it +fn culling_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value) { + let tokens = Tokens::get(sheet.ui.ctx()); + let run = |app: &mut TextureCraftApp, fields: Value| run_projection(app, base, fields); + let (projector, angle) = match &fill.projection { + Projection::Cylindrical { projector, angle, .. } => (projector, Some(*angle)), + Projection::Planar { projector, .. } | Projection::Warp { projector, .. } => (projector, None), + _ => return, + }; + + if let Some(mut angle) = angle { + let arc = angle; + let picture = |painter: &Painter, rect: Rect| angle_picture(painter, rect, arc, &tokens); + let lead = RowLead::Picture { picture: &picture, text: tr("Angle") }; + if let Some(merge) = sheet.slider_led(lead, &mut angle, CYLINDER_ANGLE_RANGE, 0, "°") { + run(app, json!({"angle": angle, "merge": merge})); + } + } + + if !matches!(fill.projection, Projection::Cylindrical { .. }) { + let mut culling = projector.depth; + let picture = |painter: &Painter, rect: Rect| depth_picture(painter, rect, &tokens); + sheet.info(tr("Paints only the surface the projector sees first; parts hidden behind it stay unpainted.")); + if sheet.picture_toggle(&picture, tr("Depth culling"), &mut culling.on) { + run(app, json!({"depthCulling": culling.on})); + } + if let Some(merge) = sheet.slider_led(RowLead::Child(tr("Hardness")), &mut culling.hardness, HARDNESS_RANGE, 2, "") { + run(app, json!({"depthCullingHardness": culling.hardness, "merge": merge})); + } + } + + if !matches!(fill.projection, Projection::Warp { .. }) { + let mut backface = projector.backface; + let culled = backface.on; + let picture = |painter: &Painter, rect: Rect| backface_picture(painter, rect, culled, &tokens); + sheet.info(tr("Leaves out faces turned away from the projector, so the fill doesn't run onto their back.")); + if sheet.picture_toggle(&picture, tr("Backface culling"), &mut backface.on) { + run(app, json!({"backfaceCulling": backface.on})); + } + + // Cylindrical culls by the angle to its axis's outward direction alone + if angle.is_none() + && let Some(merge) = sheet.angle_led(RowLead::Child(tr("Angle")), &mut backface.angle, BACKFACE_ANGLE_RANGE) + { + run(app, json!({"backfaceAngle": backface.angle, "merge": merge})); + } + if let Some(merge) = sheet.slider_led(RowLead::Child(tr("Hardness")), &mut backface.hardness, HARDNESS_RANGE, 2, "") { + run(app, json!({"backfaceHardness": backface.hardness, "merge": merge})); + } + } +} + +/// The preview square beside the size (tiling, or the tile's length while Physical size) and offset, held to move `target` on the model; Rotation under it +fn placement_rows( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + fill: &Fill, + base: &Value, + length: Option<[f32; 2]>, + size: MeshSize, + target: MoveOnModel, +) { + let tokens = Tokens::get(sheet.ui.ctx()); + let (tiling, rotation, offset, offset_key) = match &fill.projection { + Projection::Uv { scale, rotation, offset } => (*scale, *rotation, *offset, "offset"), + Projection::Triplanar { uv, .. } + | Projection::Planar { uv, .. } + | Projection::Spherical { uv, .. } + | Projection::Cylindrical { uv, .. } + | Projection::Warp { uv, .. } => (uv.tiling, uv.rotation, uv.offset, "uvOffset"), + Projection::UvTile => return, + }; + + let link_id = sheet.ui.make_persistent_id(("fill_tiling_link", fill_key(base))); + let mut linked = sheet.ui.data(|data| data.get_temp::(link_id)).unwrap_or(tiling[0] == tiling[1]); + let was_linked = linked; + let mut values = match length { + Some(length) => length.map(|units| (units * CM_PER_UNIT).round()), + None => tiling, + }; + let shown = values; + let (label, range, typed, decimals) = match length { + Some(_) => (tr("Size (cm)"), SIZE_CM_TRACK, SIZE_CM_TYPED, 0), + None => (tr("Tiling"), TILING_TRACK, TILING_TYPED, 2), + }; + let size_edit = PreviewSize { label, values: &mut values, range, typed, decimals, linked: &mut linked }; + + let mut lower_offset = offset; + let mut hardness = match &fill.projection { + Projection::Triplanar { sharpness, .. } => Some(triplanar_hardness(*sharpness)), + _ => None, + }; + let lower = match hardness.as_mut() { + Some(hardness) => PreviewLower::Slider { label: tr("Hardness"), value: hardness, range: HARDNESS_RANGE, decimals: 2 }, + None => PreviewLower::Offset { values: &mut lower_offset, range: OFFSET_TRACK, typed: OFFSET_TYPED }, + }; + let placement = Placement { tiling, rotation, offset }; + let bounds = app.session.mesh.bounds(); + + // A warp shows its frame's size and turn as its gizmo leaves them + let warp = match &fill.projection { + Projection::Warp { corners, .. } => { + let landed = frame_placement::folded(&fill.projection); + let frame = landed.as_ref().and_then(Projection::frame); + let diagonal = (bounds.1 - bounds.0).length().max(f32::EPSILON); + let size = frame.map_or([1.0 / WARP_SPAN_FALLBACK; 2], |frame| frame.size.map(|side| side / diagonal)); + let turn = frame.and_then(frame_placement::upright_turn).unwrap_or(0.0); + Some((*corners, size, turn)) + } + _ => None, + }; + let projection = &fill.projection; + let owner = sheet.ui.scope_id(); + let picture = |painter: &Painter, rect: Rect| match warp { + Some((corners, size, turn)) => warp_preview(painter, rect, corners, size, turn, placement, &tokens), + None => { + if projection_preview(painter, rect, projection, bounds, &tokens, owner).is_none() { + window_preview(painter, rect, placement, &tokens); + } + } + }; + let edit = sheet.preview_block(&picture, size_edit, lower); + crate::move_on_model::pad(app, sheet, edit.square, target); + + if linked != was_linked { + sheet.ui.data_mut(|data| data.insert_temp(link_id, linked)); + } + if let Some(merge) = edit.size + && values != shown + { + let tiling = match length { + Some(_) => tiling_for_length(&fill.projection, size, values.map(|cm| cm / CM_PER_UNIT)).unwrap_or(tiling), + None => values, + }; + run_projection(app, base, json!({"tiling": tiling, "merge": merge})); + } + if let Some(merge) = edit.lower { + let fields = match hardness { + Some(hardness) => json!({"sharpness": triplanar_sharpness(hardness), "merge": merge}), + None => json!({offset_key: lower_offset, "merge": merge}), + }; + run_projection(app, base, fields); + } + + let mut degrees = rotation; + if let Some(merge) = sheet.angle(tr("Rotation"), &mut degrees, ROTATION_RANGE) { + run_projection(app, base, json!({"rotation": degrees, "merge": merge})); + } +} + +/// One X, Y, Z row of the 3D projection settings +fn xyz_fields(values: [f32; 3], speed: f32, decimals: usize, suffix: &'static str) -> [NumberField<'static>; 3] { + std::array::from_fn(|axis| NumberField { tag: AXIS_NAMES[axis], tag_color: Some(AXIS_COLORS[axis]), value: values[axis], speed, decimals, suffix }) +} + +/// The 3D projection settings: the projector's Offset, Rotation and Scale in X, Y and Z; a frame on the surface shows its own (where its centre is, how it is turned, how big it is), the same values its gizmo drags +fn world_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value, salt: FillKey) { + let Some(projector) = projector_of(&fill.projection) else { return }; + if !sheet.band(tr("3D projection settings"), true, None, None).open { + return; + } + + let edited = |fields: &[NumberField]| -> Vec { fields.iter().map(|field| field.value).collect() }; + + // A placed planar or a warp: the frame, its projector folded in + if let Some(shown) = frame_placement::placement(&fill.projection, app.session.mesh.bounds()) { + let run = |app: &mut TextureCraftApp, key: &str, values: Vec, merge: bool| { + app.run("layer.decal.set", with(base, json!({key: values, "merge": merge}))); + }; + let mut fields = xyz_fields(shown.offset, OFFSET_FIELD_SPEED, 2, ""); + if let Some((_, merge)) = sheet.number_fields(tr("Offset"), &mut fields, None, true) { + run(app, "frameOffset", edited(&fields), merge); + } + let mut fields = xyz_fields(shown.rotation, ROTATION_FIELD_SPEED, 0, "°"); + if let Some((_, merge)) = sheet.number_fields(tr("Rotation"), &mut fields, None, true) { + run(app, "frameRotation", edited(&fields), merge); + } + if let Some((scale, merge)) = scale_row(sheet, shown.scale, salt) { + run(app, "frameScale", scale, merge); + } + return; + } + + let offset = match &fill.projection { + Projection::Triplanar { offset, .. } + | Projection::Planar { offset, .. } + | Projection::Spherical { offset, .. } + | Projection::Cylindrical { offset, .. } => Some(*offset), + Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => None, + }; + if let Some(offset) = offset { + let mut fields = xyz_fields(offset, OFFSET_FIELD_SPEED, 2, ""); + if let Some((_, merge)) = sheet.number_fields(tr("Offset"), &mut fields, None, true) { + run_projection(app, base, json!({"offset": edited(&fields), "merge": merge})); + } + } + let mut fields = xyz_fields(projector.rotation, ROTATION_FIELD_SPEED, 0, "°"); + if let Some((_, merge)) = sheet.number_fields(tr("Rotation"), &mut fields, None, true) { + run_projection(app, base, json!({"projectorRotation": edited(&fields), "merge": merge})); + } + if let Some((scale, merge)) = scale_row(sheet, projector.scale, salt) { + run_projection(app, base, json!({"projectorScale": scale, "merge": merge})); + } +} + +/// The least size of the edited axis's scale a linked edit scales the others from by a factor +const MIN_LINKED_SCALE_BASE: f32 = f32::EPSILON; + +/// The Scale X, Y, Z row with its link: the new scale and whether it continues the drag's undo step; linked, one field scales all three by the same factor +fn scale_row(sheet: &mut PropertySheet<'_>, scale: [f32; 3], salt: FillKey) -> Option<(Vec, bool)> { + let link_id = sheet.ui.make_persistent_id(("projector_scale_link", salt)); + let [x, y, z] = scale; + let mut linked = sheet.ui.data(|data| data.get_temp::(link_id)).unwrap_or(x == y && y == z); + let was_linked = linked; + let mut fields = xyz_fields(scale, SCALE_FIELD_SPEED, 2, ""); + let edit = sheet.number_fields(tr("Scale"), &mut fields, Some(&mut linked), false); + if linked != was_linked { + sheet.ui.data_mut(|data| data.insert_temp(link_id, linked)); + } + let (axis, merge) = edit?; + let mut values: Vec = fields.iter().map(|field| field.value).collect(); + if linked && let (Some(&value), Some(&before)) = (values.get(axis), scale.get(axis)) { + // From a scale of about zero no factor reaches the new value: all three take it instead + let factor = (before.abs() > MIN_LINKED_SCALE_BASE).then(|| value / before); + values = scale.iter().map(|old| factor.map_or(value, |factor| old * factor)).collect(); + } + Some((values, merge)) +} diff --git a/crates/ui-egui/src/fill_pictures.rs b/crates/ui-egui/src/fill_pictures.rs new file mode 100644 index 00000000..25c48d60 --- /dev/null +++ b/crates/ui-egui/src/fill_pictures.rs @@ -0,0 +1,403 @@ +//! Pictures of what a fill's settings do: one per projection, filtering and UV wrap choice, the window preview and the ring of radial copies + +use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke, pos2, vec2}; +use texturecraft_engine::core::{FillSymmetry, Filtering, ShapeCrop, UvWrap}; +use texturecraft_engine::paint::FULL_TURN_DEGREES; + +use crate::placement::Placement; +use crate::projection_kind::ProjectionKind; +use crate::projection_preview::{edge_markers, passed_sides}; +use crate::warp_checker::warp_checker; + +use crate::theme::{Tokens, lerp_color}; + +/// The projection glyph's height, as a share of its picture's +const PROJECTION_GLYPH_SHARE: f32 = 0.85; + +/// The shape a projection wraps around, as an icon in the accent colour +pub(crate) fn projection_picture(painter: &Painter, rect: Rect, kind: ProjectionKind, tokens: &Tokens) { + use egui_phosphor::regular as icon; + let glyph = match kind { + ProjectionKind::UvTile | ProjectionKind::Uv => icon::SQUARE, + ProjectionKind::Triplanar => icon::CUBE, + ProjectionKind::Planar | ProjectionKind::Warp => icon::SELECTION, + ProjectionKind::Spherical => icon::GLOBE, + ProjectionKind::Cylindrical => icon::CYLINDER, + }; + painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(rect.height() * PROJECTION_GLYPH_SHARE), tokens.accent); +} + +/// Cells across a magnified edge in the Filtering picture +const EDGE_CELLS: usize = 6; + +/// How steeply Bilinear Sharp ramps across the magnified edge: nearly a step +const SHARP_EDGE_RAMP: f32 = 3.0; + +/// How steeply Bilinear HQ ramps across the magnified edge: a soft blend +const HQ_EDGE_RAMP: f32 = 1.2; + +/// A magnified diagonal edge: smooth (HQ), crisp (Sharp) or stair-stepped (Nearest) +pub(crate) fn filtering_picture(painter: &Painter, rect: Rect, filtering: Filtering, tokens: &Tokens) { + let cell = rect.width() / EDGE_CELLS as f32; + for i in 0..EDGE_CELLS { + for j in 0..EDGE_CELLS { + let across = (i as f32 - j as f32) / EDGE_CELLS as f32; + let amount = match filtering { + Filtering::Nearest => f32::from(u8::from(i >= j)), + Filtering::BilinearSharp => (0.5 + across * SHARP_EDGE_RAMP).clamp(0.0, 1.0), + Filtering::BilinearHq => (0.5 + across * HQ_EDGE_RAMP).clamp(0.0, 1.0), + }; + let color = lerp_color(tokens.field, tokens.accent, amount); + let min = pos2(rect.left() + i as f32 * cell, rect.top() + j as f32 * cell); + painter.rect_filled(Rect::from_min_size(min, vec2(cell, cell)), 0, color); + } + } +} + +/// Cells of the UV Wrap picture's grid +const WRAP_CELLS: usize = 3; + +/// The gap kept around each Wrap tile, in points +const WRAP_TILE_INSET: f32 = 0.75; + +/// A repeated tile's accent strength beside the own tile's +const WRAP_REPEAT_SHADE: f32 = 0.55; + +/// A 3 × 3 grid: the middle tile is the image's own; filled tiles are where it repeats +pub(crate) fn wrap_picture(painter: &Painter, rect: Rect, wrap: UvWrap, tokens: &Tokens) { + let (across, down) = wrap.repeats(); + let cell = rect.width() / WRAP_CELLS as f32; + let middle = WRAP_CELLS / 2; + for i in 0..WRAP_CELLS { + for j in 0..WRAP_CELLS { + let own = i == middle && j == middle; + let repeated = own || (across && j == middle) || (down && i == middle) || (across && down); + let tile = Rect::from_min_size(pos2(rect.left() + i as f32 * cell, rect.top() + j as f32 * cell), vec2(cell, cell)).shrink(WRAP_TILE_INSET); + if own { + painter.rect_filled(tile, 1, tokens.accent); + } else if repeated { + painter.rect_filled(tile, 1, tokens.accent.gamma_multiply(WRAP_REPEAT_SHADE)); + } else { + painter.rect_stroke(tile, 1, Stroke::new(LINE_WIDTH, tokens.separator), egui::StrokeKind::Inside); + } + } + } +} + +/// Most tiles drawn across the window preview: beyond this the pattern is too fine to read +const PREVIEW_MAX_TILES: f32 = 24.0; + +/// The fewest tiles a preview shows, so a zero Tiling cannot divide by zero +pub(crate) const PREVIEW_MIN_TILES: f32 = 1e-3; + +/// Most tiles drawn along one direction of a lattice preview, whatever its map +const PREVIEW_MAX_SPAN: i32 = 64; + +/// The preview checker's dark cells, as a fraction of the way from `field` to `text` +const PREVIEW_DARK: f32 = 0.18; + +/// The preview checker's light cells, as a fraction of the way from `field` to `text` +const PREVIEW_LIGHT: f32 = 0.55; + +/// Where the mean of the checker's dark and light cells sits between them +const CHECKER_MEAN: f32 = 0.5; + +/// The width of every outline, border and ring line in these pictures +const LINE_WIDTH: f32 = 1.0; + +/// A lattice preview tile's checker cells, each half a tile wide, by the corner they start at in halves of a tile; even ones light +const TILE_CELLS: [(u8, u8); 4] = [(0, 0), (1, 0), (0, 1), (1, 1)]; + +/// A checker cell's side in tiles: two cells across a tile +const CELL_SIDE: f32 = 0.5; + +/// The window's centre (0..1) before any slide +const WINDOW_MIDDLE: f32 = 0.5; + +/// A flatter map shows nothing: the window could not be undone from it +const MIN_MAP_DETERMINANT: f32 = 1e-9; + +/// A window on the surface that never moves: a UV checker (2 × 2 cells per tile, accent tile borders) tiled, turned and slid as the fill is, the ring in the middle where Offset 0 puts the projection, the filled dot where its Offset carried that point +pub(crate) fn window_preview(painter: &Painter, rect: Rect, placement: Placement, tokens: &Tokens) { + let (columns, carried) = slid_window(placement); + lattice_preview(painter, rect, (columns, placement.offset), true, tokens); + let position = pos2(rect.left() + carried[0] * rect.width(), rect.top() + carried[1] * rect.height()); + let painter = painter.with_clip_rect(rect.intersect(painter.clip_rect())); + crate::preview_dots::preview_dots(&painter, rect.center(), position, tokens); + edge_markers(&painter, rect, passed_sides(std::iter::once(position), rect), tokens); +} + +/// The window preview's map, and where the Offset carried the window's middle (0..1): the checker slides with it, so a drag right moves both right +fn slid_window(placement: Placement) -> ([[f32; 2]; 2], [f32; 2]) { + let tiling = placement.tiling.map(|tiles| tiles.clamp(PREVIEW_MIN_TILES, PREVIEW_MAX_TILES)); + let (sin, cos) = placement.rotation.to_radians().sin_cos(); + + // Turn, scale, then offset: one step across the window moves (cos, sin) scaled in the texture + let columns = [[cos * tiling[0], sin * tiling[1]], [-sin * tiling[0], cos * tiling[1]]]; + let [[a, b], [c, d]] = columns; + let det = a * d - c * b; + let [x, y] = placement.offset; + + // The window step the Offset is worth: the map undone; the image moves against the Offset it samples at + let moved = [(d * x - c * y) / det, (a * y - b * x) / det]; + let carried = if moved.iter().all(|value| value.is_finite()) { [WINDOW_MIDDLE - moved[0], WINDOW_MIDDLE - moved[1]] } else { [WINDOW_MIDDLE; 2] }; + (columns, carried) +} + +/// The window preview for any linear map: window point (u, v) shows the texture at `columns[0] · u + columns[1] · v + shift`; without `repeat` only tile 0..1 +pub(crate) fn lattice_preview(painter: &Painter, rect: Rect, (columns, shift): ([[f32; 2]; 2], [f32; 2]), repeat: bool, tokens: &Tokens) { + let painter = painter.with_clip_rect(rect); + painter.rect_filled(rect, 0, tokens.field); + let [[a, b], [c, d]] = columns; + let det = a * d - c * b; + if det.abs() > MIN_MAP_DETERMINANT && det.is_finite() && shift.iter().all(|value| value.is_finite()) { + // Texture coordinates → the window: undo the shift, then the map + let to_window = |t: [f32; 2]| -> Pos2 { + let (x, y) = (t[0] - shift[0], t[1] - shift[1]); + let (u, v) = ((d * x - c * y) / det, (a * y - b * x) / det); + pos2(rect.left() + u * rect.width(), rect.top() + v * rect.height()) + }; + let to_texture = |u: f32, v: f32| -> [f32; 2] { [a * u + c * v + shift[0], b * u + d * v + shift[1]] }; + let corners = [to_texture(0.0, 0.0), to_texture(1.0, 0.0), to_texture(0.0, 1.0), to_texture(1.0, 1.0)]; + let low = |axis: usize| corners.iter().map(|corner| corner[axis]).fold(f32::INFINITY, f32::min).floor() as i32; + let high = |axis: usize| corners.iter().map(|corner| corner[axis]).fold(f32::NEG_INFINITY, f32::max).ceil() as i32; + let span = |first: i32, last: i32| if repeat { first..last.min(first.saturating_add(PREVIEW_MAX_SPAN)) } else { first.max(0)..last.min(1) }; + let (dark, light) = (lerp_color(tokens.field, tokens.text, PREVIEW_DARK), lerp_color(tokens.field, tokens.text, PREVIEW_LIGHT)); + let border = Stroke::new(LINE_WIDTH, tokens.accent); + + // Repeating past the most tiles drawn, a tile is about a pixel: the window reads as the checker's mean, so the undrawn tiles leave no bare field + if repeat && (0..2).any(|axis| high(axis).saturating_sub(low(axis)) > PREVIEW_MAX_SPAN) { + painter.rect_filled(rect, 0, lerp_color(dark, light, CHECKER_MEAN)); + } + for tile_x in span(low(0), high(0)) { + for tile_y in span(low(1), high(1)) { + for (cell_x, cell_y) in TILE_CELLS { + let (x0, y0) = (tile_x as f32 + f32::from(cell_x) * CELL_SIDE, tile_y as f32 + f32::from(cell_y) * CELL_SIDE); + let corners = [[x0, y0], [x0 + CELL_SIDE, y0], [x0 + CELL_SIDE, y0 + CELL_SIDE], [x0, y0 + CELL_SIDE]].map(to_window); + let color = if (cell_x + cell_y) % 2 == 0 { light } else { dark }; + painter.add(Shape::convex_polygon(corners.to_vec(), color, Stroke::NONE)); + } + let (x, y) = (tile_x as f32, tile_y as f32); + painter.add(Shape::closed_line([[x, y], [x + 1.0, y], [x + 1.0, y + 1.0], [x, y + 1.0]].map(to_window).to_vec(), border)); + } + } + } + painter.rect_stroke(rect, 0, Stroke::new(LINE_WIDTH, tokens.field_border), egui::StrokeKind::Inside); +} + +/// How far the darker accent sits from the accent towards black +const ACCENT_SHADE: f32 = 0.36; + +/// The darker accent pictures fill with, beside the accent itself +fn accent_shade(tokens: &Tokens) -> Color32 { + lerp_color(tokens.accent, Color32::BLACK, ACCENT_SHADE) +} + +/// The margin inside a small setting picture, in points +const PICTURE_INSET: f32 = 3.0; + +/// Depth culling's hidden part, as a share of its picture's height +const DEPTH_UNDER_SHARE: f32 = 0.45; + +/// The arrow glyph's size in the Depth picture +const DEPTH_ARROW_SIZE: f32 = 9.0; + +/// The Angle picture's radius, as a share of its width +const ANGLE_RADIUS_SHARE: f32 = 0.45; + +/// The warp preview's outline width +const WARP_EDGE_WIDTH: f32 = 1.5; + +/// Corner radius of the crop picture's shape +const CROP_SHAPE_CORNER_RADIUS: u8 = 3; + +/// Corner radius of a fill that reaches a picture's edges +const PICTURE_CORNER_RADIUS: u8 = 2; + +/// Where the depth picture's surface sits, as a share of its height from the top +const DEPTH_SURFACE_SHARE: f32 = 0.25; + +/// Points what lies under the surface reaches past its share, so it still reads at small sizes +const DEPTH_UNDER_EXTRA: f32 = 2.0; + +/// How far the backface picture's face stays inside the picture's sides +const BACKFACE_SIDE_INSET: f32 = 2.0; + +/// Shape crop: the projection inside its shape only, or past it too +pub(crate) fn crop_picture(painter: &Painter, rect: Rect, crop: ShapeCrop, tokens: &Tokens) { + let inner = rect.shrink(PICTURE_INSET); + match crop { + ShapeCrop::Cropped => { + painter.rect_filled(inner, CROP_SHAPE_CORNER_RADIUS, accent_shade(tokens)); + } + ShapeCrop::ExtendsOutside => { + painter.rect_filled(rect, PICTURE_CORNER_RADIUS, accent_shade(tokens)); + } + } + painter.rect_stroke(inner, CROP_SHAPE_CORNER_RADIUS, Stroke::new(LINE_WIDTH, tokens.text), egui::StrokeKind::Inside); +} + +/// Depth culling, seen from the side: the surface the projection lands on and what lies under it +pub(crate) fn depth_picture(painter: &Painter, rect: Rect, tokens: &Tokens) { + let top = rect.top() + rect.height() * DEPTH_SURFACE_SHARE; + let under = Rect::from_min_max(pos2(rect.left(), top), pos2(rect.right(), top + rect.height() * DEPTH_UNDER_SHARE + DEPTH_UNDER_EXTRA)); + painter.rect_filled(under, PICTURE_CORNER_RADIUS, accent_shade(tokens)); + painter.line_segment([pos2(rect.left(), top), pos2(rect.right(), top)], Stroke::new(LINE_WIDTH, tokens.text)); + painter.text( + pos2(rect.center().x, rect.top() + PICTURE_INSET), + egui::Align2::CENTER_CENTER, + egui_phosphor::regular::ARROW_DOWN, + egui::FontId::proportional(DEPTH_ARROW_SIZE), + tokens.accent, + ); +} + +/// Backface culling: a face turned away, darker while culled +pub(crate) fn backface_picture(painter: &Painter, rect: Rect, on: bool, tokens: &Tokens) { + let (left, apex, right) = ( + pos2(rect.left() + BACKFACE_SIDE_INSET, rect.bottom() - PICTURE_INSET), + pos2(rect.center().x, rect.top() + PICTURE_INSET), + pos2(rect.right() - BACKFACE_SIDE_INSET, rect.bottom() - PICTURE_INSET), + ); + painter.add(Shape::convex_polygon(vec![left, apex, right], if on { accent_shade(tokens) } else { tokens.accent }, Stroke::NONE)); + painter.line_segment([apex, right], Stroke::new(LINE_WIDTH, tokens.text)); +} + +/// Points around the Angle picture's arc per full turn +const ARC_POINTS: usize = 48; + +/// The angle and ring pictures start at the top: a quarter turn back from +x (egui's y points down), in turns +const TOP_START_TURNS: f32 = 0.25; + +/// A cylindrical projection's Angle seen from above: the slice of a turn one repeat spans +pub(crate) fn angle_picture(painter: &Painter, rect: Rect, degrees: f32, tokens: &Tokens) { + let center = rect.center(); + let radius = rect.width() * ANGLE_RADIUS_SHARE; + let sweep = degrees.clamp(0.0, FULL_TURN_DEGREES) / FULL_TURN_DEGREES; + if sweep >= 1.0 { + painter.circle_filled(center, radius, tokens.accent); + } else { + let steps = ((ARC_POINTS as f32 * sweep).ceil() as usize).max(1); + let mut points = vec![center]; + for step in 0..=steps { + let turn = (step as f32 / steps as f32 * sweep - TOP_START_TURNS) * std::f32::consts::TAU; + points.push(pos2(center.x + radius * turn.cos(), center.y + radius * turn.sin())); + } + + // A slice wider than half a turn is not convex: fill it as a fan from the centre + for pair in points[1..].windows(2) { + painter.add(Shape::convex_polygon(vec![center, pair[0], pair[1]], tokens.accent, Stroke::NONE)); + } + } + painter.circle_stroke(center, radius, Stroke::new(LINE_WIDTH, tokens.button_border)); +} + +/// How much of the preview an unpulled frame spans per mesh diagonal of its side (a new warp's frame round a ball spans about 0.62) +const WARP_SPAN_PER_DIAGONAL: f32 = 1.07; +/// The least and most of the preview a frame's side spans +const WARP_SPAN_RANGE: std::ops::RangeInclusive = 0.05..=0.95; + +/// Radius of a warp preview's corner handle +const WARP_HANDLE_RADIUS: f32 = 3.5; + +/// A warp's frame with its corners where they are pulled, the checker bending with them and laid as `placement` lays the image (tiling, rotation, offset); `size` is the frame's width and height in mesh diagonals, `turn` its turn round its normal (degrees), so resizing or turning the frame shows +pub(crate) fn warp_preview(painter: &Painter, rect: Rect, corners: [[f32; 2]; 4], size: [f32; 2], turn: f32, placement: Placement, tokens: &Tokens) { + let painter = painter.with_clip_rect(rect); + painter.rect_filled(rect, 0, tokens.field); + let span = size.map(|side| (side * WARP_SPAN_PER_DIAGONAL).clamp(*WARP_SPAN_RANGE.start(), *WARP_SPAN_RANGE.end())); + let (sin, cos) = turn.to_radians().sin_cos(); + + // Across and up in frame sizes from its centre -> turned -> the square + let [top_left, top_right, bottom_right, bottom_left] = corners.map(|[x, y]| { + let (x, y) = (x * span[0], y * span[1]); + let (x, y) = (x * cos - y * sin, x * sin + y * cos); + pos2(rect.center().x + x * rect.width(), rect.center().y - y * rect.height()) + }); + let (dark, light) = (lerp_color(tokens.field, tokens.text, PREVIEW_DARK), lerp_color(tokens.field, tokens.text, PREVIEW_LIGHT)); + for (outline, lit) in warp_checker([top_left, top_right, bottom_right, bottom_left], placement) { + painter.add(Shape::convex_polygon(outline, if lit { light } else { dark }, Stroke::NONE)); + } + let edge = [top_left, top_right, bottom_right, bottom_left]; + painter.add(Shape::closed_line(edge.to_vec(), Stroke::new(WARP_EDGE_WIDTH, tokens.accent))); + for corner in edge { + painter.circle(corner, WARP_HANDLE_RADIUS, tokens.text, Stroke::new(LINE_WIDTH, tokens.accent)); + } + painter.rect_stroke(rect, 0, Stroke::new(LINE_WIDTH, tokens.field_border), egui::StrokeKind::Inside); +} + +/// The ring's radius, in the picture's widths +const RING_RADIUS: f32 = 0.34; + +/// The radius of the axis's dot at the ring's centre +const RING_AXIS_DOT: f32 = 2.0; + +/// The radius of each copy's dot on the ring +const RING_COPY_DOT: f32 = 3.5; + +/// The straight pieces the ring is drawn with +const RING_SEGMENTS: usize = 64; + +/// Radial copies seen along their axis: the axis at the centre (its colour), the original (white) at the top and the other copies (accent) round the ring, spaced as the engine spaces them +pub(crate) fn ring_picture(painter: &Painter, rect: Rect, symmetry: &FillSymmetry, axis_color: Color32, tokens: &Tokens) { + painter.rect_filled(rect, 0, tokens.field); + let center = rect.center(); + let radius = rect.width() * RING_RADIUS; + let at = |degrees: f32| { + let turn = (degrees - TOP_START_TURNS * FULL_TURN_DEGREES).to_radians(); + center + vec2(turn.cos(), turn.sin()) * radius + }; + + // The ring runs over the span the engine spreads the copies over: a stored span past a full turn or below none reads as the engine reads it + let ring_end = symmetry.span.clamp(0.0, FULL_TURN_DEGREES); + let ring: Vec = (0..=RING_SEGMENTS).map(|k| at(ring_end * k as f32 / RING_SEGMENTS as f32)).collect(); + painter.add(Shape::line(ring, Stroke::new(LINE_WIDTH, tokens.separator))); + painter.circle_filled(center, RING_AXIS_DOT, axis_color); + for (k, degrees) in copy_angles(symmetry).enumerate() { + let color = if k == 0 { tokens.text } else { tokens.accent }; + painter.circle_filled(at(degrees), RING_COPY_DOT, color); + } +} + +/// The degrees each radial copy of `symmetry` turns, the original's 0 first, from the engine's count and spacing +fn copy_angles(symmetry: &FillSymmetry) -> impl Iterator { + let step = symmetry.step(); + (0..symmetry.copies()).map(move |k| k as f32 * step) +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::core::SymmetryKind; + + use super::*; + + /// A hand-edited span past a full turn spaces the ring's dots as the engine spaces the copies: six copies 60° apart, none on top of another + #[test] + fn the_ring_spaces_its_copies_as_the_engine_does() { + let symmetry = FillSymmetry { on: true, kind: SymmetryKind::Radial, count: 6, span: 720.0, ..FillSymmetry::OFF }; + + let angles: Vec = copy_angles(&symmetry).collect(); + + assert_eq!(angles, [0.0, 60.0, 120.0, 180.0, 240.0, 300.0]); + } + + /// The UV view stands still: the checker slides with the Offset as on the model, and the filled dot (the window's middle, carried) slides with it, the way a drag moves them + #[test] + fn the_uv_view_stands_still_and_the_dot_slides_with_the_checker() { + let placement = |offset: [f32; 2]| Placement { tiling: [2.0, 2.0], rotation: 30.0, offset }; + let (still, rest) = slid_window(placement([0.0, 0.0])); + assert_eq!(rest, [0.5, 0.5], "at Offset 0 the dot sits in the ring"); + let slid = placement([-0.25, 0.0]); + let (columns, dot) = slid_window(slid); + assert_eq!(columns, still, "the view never zooms or turns for the Offset"); + + // A pad drag right lowers the Offset: the dot goes right, an eighth of the window along the turned U + let expected = [0.5 + 0.125 * 30f32.to_radians().cos(), 0.5 - 0.125 * 30f32.to_radians().sin()]; + assert!((dot[0] - expected[0]).abs() < 1e-5 && (dot[1] - expected[1]).abs() < 1e-5, "{dot:?} vs {expected:?}"); + + // The checker point under the middle at Offset 0 shows under the dot now + let [[a, b], [c, d]] = columns; + let texture_at = |[u, v]: [f32; 2], offset: [f32; 2]| [a * u + c * v + offset[0], b * u + d * v + offset[1]]; + let (before, after) = (texture_at([0.5, 0.5], [0.0, 0.0]), texture_at(dot, slid.offset)); + assert!((before[0] - after[0]).abs() < 1e-5 && (before[1] - after[1]).abs() < 1e-5, "{before:?} vs {after:?}"); + } +} diff --git a/crates/ui-egui/src/move_hold.rs b/crates/ui-egui/src/move_hold.rs new file mode 100644 index 00000000..c07dc553 --- /dev/null +++ b/crates/ui-egui/src/move_hold.rs @@ -0,0 +1,15 @@ +//! A Move on model hold under way, kept in egui's memory between frames + +use egui::Pos2; + +use crate::move_on_model::MoveOnModel; + +/// The Move on model button held down: the fill it moves, where the pointer was on the last frame and the session revision its last edit left (its undo step, while the history is still there) +#[derive(Clone, Copy, Debug)] +pub(crate) struct MoveHold { + pub target: MoveOnModel, + pub last: Pos2, + pub edited_revision: Option, + /// The pass that last applied it: a sheet drawn twice in one frame moves the projection once + pub pass: u64, +} diff --git a/crates/ui-egui/src/move_on_model.rs b/crates/ui-egui/src/move_on_model.rs new file mode 100644 index 00000000..0871d95e --- /dev/null +++ b/crates/ui-egui/src/move_on_model.rs @@ -0,0 +1,498 @@ +//! Move on model: hold the preview square and drag to slide the selected fill's projection, with Shift or the right button held to turn it, and turn the wheel to scale it. The pointer is held while it lasts (hidden, no screen edge stops it, back where the press began when let go). Letting go ends it, as one undo step; the 3D view keeps its own drags and wheel + +use egui::{CursorIcon, Pos2, Rect}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, LayerId, LayerKind, Projection}; + +use crate::TextureCraftApp; +use crate::frame_gizmo::FrameGizmo; +use crate::i18n::tr; +use crate::move_hold::MoveHold; +use crate::property_sheet::PropertySheet; +use crate::round_gizmo::RoundGizmo; + +/// The fill whose projection Move on model moves: a fill layer, or a content fill effect in it +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MoveOnModel { + pub layer: LayerId, + pub effect: Option, +} + +impl MoveOnModel { + /// A fill layer's own projection + pub(crate) fn layer(layer: LayerId) -> MoveOnModel { + MoveOnModel { layer, effect: None } + } + + /// The `layer` or `effect` param of the fill commands + pub(crate) fn target(self) -> Value { + match self.effect { + Some(effect) => json!({"effect": effect.0}), + None => json!({"layer": self.layer.0}), + } + } + + /// The selected fill layer, or the selected fill effect in it (its content or its mask); its projector shows in the 3D view + pub(crate) fn selected(app: &TextureCraftApp) -> Option { + let layer = app.session.selected_layer()?; + let effect = match app.session.target { + texturecraft_engine::StackTarget::Content => None, + texturecraft_engine::StackTarget::Effect(effect) => Some(effect), + texturecraft_engine::StackTarget::Mask => return None, + }; + Some(MoveOnModel { layer, effect }) + } + + pub(crate) fn projection(self, app: &TextureCraftApp) -> Option { + let project = &app.session.doc.project; + match self.effect { + Some(effect) => match &project.effect(effect)?.1.kind { + EffectKind::Material(fill) => Some(fill.projection.clone()), + EffectKind::Fill { projection, .. } => Some(projection.clone()), + _ => None, + }, + None => match &project.layer(self.layer).ok()?.kind { + LayerKind::Fill(fill) => Some(fill.projection.clone()), + _ => None, + }, + } + } +} + +fn hold_id() -> egui::Id { + egui::Id::unique("tc_move_on_model_hold") +} + +/// Image repeats a drag across the view's height slides by +const SLIDE_PER_HEIGHT: f32 = 1.0; +/// Degrees a turning drag turns per point +const TURN_PER_POINT: f32 = 0.5; +/// Growth per wheel point (exponential) +const SCALE_PER_WHEEL_POINT: f32 = 0.0015; + +/// Move on model on `target`'s preview square: while it is held down it moves the projection +pub(crate) fn pad(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, square: Rect, target: MoveOnModel) { + let held = app.moving_on_model == Some(target); + let mut response = sheet.hold_pad(square, ic::HAND, tr("Move on model"), held); + if !held { + response = sheet.tip_beside(response, tr("Hold and drag to slide the projection; Shift or the right button turns it, the wheel scales it")); + } + let ctx = sheet.ui.ctx().clone(); + hold(app, &ctx, &response, target); +} + +/// Whether a Move on model hold is under way, or let go this frame (that release is no click in the view); the 3D view then keeps its camera, brush and gizmos still. Ends a hold whose window lost the focus +pub(crate) fn holding(app: &mut TextureCraftApp, ctx: &egui::Context) -> bool { + let held = app.moving_on_model.is_some(); + if held && !still_pressed(ctx) { + end(app, ctx); + } + held +} + +/// Ends a hold whose fill or pad went away, once a frame whichever views show +pub(crate) fn end_when_gone(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(target) = app.moving_on_model else { return }; + + if target.projection(app).is_none() || pad_gone(ctx) { + end(app, ctx); + } +} + +/// Whether the held pad was not drawn last pass nor this one (its layer was deselected, its panel hidden) +fn pad_gone(ctx: &egui::Context) -> bool { + let last_drawn = ctx.data(|data| data.get_temp::(hold_id())).map(|held| held.pass); + last_drawn.is_none_or(|pass| pass.saturating_add(1) < ctx.cumulative_pass_nr()) +} + +/// Whether the left button still holds: a window that lost the focus gets no release, so the hold ends there as on one +fn still_pressed(ctx: &egui::Context) -> bool { + ctx.input(|input| input.pointer.primary_down()) && !crate::viewport::focus_lost(ctx) +} + +/// Ends the hold where it is: its edits stay one undo step +fn end(app: &mut TextureCraftApp, ctx: &egui::Context) { + app.moving_on_model = None; + ctx.data_mut(|data| data.remove::(hold_id())); +} + +/// A press on the pad starts the hold; each frame until the left button lets go, pointer moves and wheel steps edit the projection +fn hold(app: &mut TextureCraftApp, ctx: &egui::Context, pad: &egui::Response, target: MoveOnModel) { + let primary = still_pressed(ctx); + let (pressed, turn, pointer) = + ctx.input(|input| (input.pointer.primary_pressed(), input.modifiers.shift || input.pointer.secondary_down(), input.pointer.latest_pos())); + let pass = ctx.cumulative_pass_nr(); + let mut held = ctx.data(|data| data.get_temp::(hold_id())).filter(|held| held.target == target); + + // Only a fresh press starts it: after a focus loss egui still has the left button down + if held.is_none() + && primary + && pressed + && pad.is_pointer_button_down_on() + && let Some(at) = pointer + { + held = Some(MoveHold { target, last: at, edited_revision: None, pass: pass.wrapping_sub(1) }); + } + + let Some(mut held) = held.filter(|_| primary && target.projection(app).is_some()) else { + if app.moving_on_model == Some(target) { + end(app, ctx); + } + if pad.hovered() { + ctx.set_cursor_icon(CursorIcon::Grab); + } + return; + }; + + app.moving_on_model = Some(target); + crate::pointer_lock::ask_for_hold(ctx); + if held.pass == pass { + return; + } + + held.pass = pass; + + let rect = app.viewport_rect; + if let Some(at) = pointer.filter(|at| *at != held.last) { + if let Some((command, params)) = dragged(app, target, held.last, at, turn, rect) { + step(app, &mut held, command, params); + } + held.last = at; + } + + // The wheel scales the projection instead of scrolling the panel or zooming the camera while the pad is held + let wheel = ctx.input_mut(|input| std::mem::take(&mut input.smooth_scroll_delta).y); + if wheel != 0.0 + && let Some((command, params)) = resized(app, target, (SCALE_PER_WHEEL_POINT * wheel).exp(), rect) + { + step(app, &mut held, command, params); + } + + ctx.data_mut(|data| data.insert_temp(hold_id(), held)); + + // The panel drew before this edit: one more frame shows its fields and preview where the projection is now + ctx.request_repaint(); +} + +/// Runs one edit of the hold; the edits after the first that changed something join its undo step +fn step(app: &mut TextureCraftApp, held: &mut MoveHold, command: &str, params: Value) { + crate::projection_gizmo::edit_in_one_step(&mut app.session, command, params, &mut held.edited_revision); +} + +/// The selected planar or warp frame of a fill layer or of a mask fill effect, which moves by its frame +fn frame_of(app: &TextureCraftApp, target: MoveOnModel, rect: Rect) -> Option { + FrameGizmo::of(app, rect).filter(|gizmo| match target.effect { + Some(effect) => gizmo.effect == Some(effect), + None => gizmo.layer == target.layer && gizmo.effect.is_none(), + }) +} + +/// The `layer` (and for a mask fill `effect`) params of `layer.decal.set` editing `gizmo`'s frame, added to `params` +fn frame_target(mut params: Value, gizmo: &FrameGizmo) -> Value { + params["layer"] = json!(gizmo.layer.0); + if let Some(effect) = gizmo.effect { + params["effect"] = json!(effect.0); + } + params +} + +/// A projection's UV tiling, rotation and offset (None for Fill (Match per UV Tile)) +fn placement(projection: &Projection) -> Option<([f32; 2], f32, [f32; 2])> { + match projection { + Projection::UvTile => None, + Projection::Uv { scale, rotation, offset } => Some((*scale, *rotation, *offset)), + Projection::Triplanar { uv, .. } + | Projection::Planar { uv, .. } + | Projection::Spherical { uv, .. } + | Projection::Cylindrical { uv, .. } + | Projection::Warp { uv, .. } => Some((uv.tiling, uv.rotation, uv.offset)), + } +} + +/// The edit a pointer move from `from` to `to` makes: a frame or projector slides by it, a UV image slides; with `turn` it turns instead +fn dragged(app: &TextureCraftApp, target: MoveOnModel, from: Pos2, to: Pos2, turn: bool, rect: Rect) -> Option<(&'static str, Value)> { + let delta = to - from; + if let Some(gizmo) = frame_of(app, target, rect) { + let params = if turn { json!({"rotation": gizmo.decal.rotation - delta.x * TURN_PER_POINT}) } else { json!({"offset": gizmo.slid_on_screen(delta)?}) }; + return Some(("layer.decal.set", frame_target(params, &gizmo))); + } + + if !turn && let Some(round) = RoundGizmo::of(app, rect).filter(|round| round.target == target) { + return Some(("layer.fill.projection", round.slid(app, rect, from, to)?)); + } + + let projection = target.projection(app)?; + let (_, rotation, offset) = placement(&projection)?; + let slide = delta * SLIDE_PER_HEIGHT / rect.height().max(1.0); + let offset = [offset[0] - slide.x, offset[1] - slide.y]; + let mut params = match (turn, projection) { + (true, _) => json!({"rotation": rotation + delta.x * TURN_PER_POINT}), + (false, Projection::Uv { .. }) => json!({"offset": offset}), + (false, _) => json!({"uvOffset": offset}), + }; + merge_target(&mut params, target); + Some(("layer.fill.projection", params)) +} + +/// The edit a wheel step growing the projection by `growth` makes: a frame grows, other projections' images repeat less +fn resized(app: &TextureCraftApp, target: MoveOnModel, growth: f32, rect: Rect) -> Option<(&'static str, Value)> { + if let Some(gizmo) = frame_of(app, target, rect) { + let [width, height] = gizmo.decal.size; + return Some(("layer.decal.set", frame_target(json!({"size": [width * growth, height * growth]}), &gizmo))); + } + + let (tiling, _, _) = placement(&target.projection(app)?)?; + let mut params = json!({"tiling": [tiling[0] / growth, tiling[1] / growth]}); + merge_target(&mut params, target); + Some(("layer.fill.projection", params)) +} + +/// Adds the `layer` or `effect` param naming `target` to `params` +fn merge_target(params: &mut Value, target: MoveOnModel) { + if let (Some(params), Value::Object(fields)) = (params.as_object_mut(), target.target()) { + params.extend(fields); + } +} + +#[cfg(test)] +mod tests { + use egui::{Modifiers, PointerButton, vec2}; + use egui_kittest::kittest::Queryable; + use texturecraft_engine::core::{Projection, UvTransform}; + + use super::*; + use crate::frame_gizmo::tests::{drag, fill_app, projection}; + use crate::pointer_lock::system_pointer::SystemPointer; + use crate::round_gizmo::tests::on_the_model_off_the_handles; + use crate::state::ViewLayout; + + type Harness = egui_kittest::Harness<'static, TextureCraftApp>; + + fn uv_of(projection: &Projection) -> UvTransform { + match projection { + Projection::Triplanar { uv, .. } => *uv, + other => panic!("tri-planar: {other:?}"), + } + } + + fn projector_offset(projection: &Projection) -> [f32; 3] { + match projection { + Projection::Triplanar { offset, .. } => *offset, + other => panic!("tri-planar: {other:?}"), + } + } + + /// Presses the left button on Move on model (the preview square) and holds it; returns the system's pointer, resting there + fn press_the_button(harness: &mut Harness) -> SystemPointer { + let at = harness.get_by_label("Move on model").rect().center(); + let mut pointer = SystemPointer::at(harness, at); + pointer.button(harness, PointerButton::Primary, true, Modifiers::NONE); + pointer + } + + /// A wheel step up where the pointer is, over a few frames as the wheel scrolls smoothly + fn wheel(harness: &mut Harness, pointer: &mut SystemPointer) { + harness.input_mut().events.push(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, 120.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: Modifiers::NONE, + }); + for _ in 0..6 { + pointer.frame(harness); + } + } + + /// Lets go of the left button, and lets a frame show where the pointer came back to + fn let_go(harness: &mut Harness, pointer: &mut SystemPointer) { + pointer.button(harness, PointerButton::Primary, false, Modifiers::NONE); + pointer.frame(harness); + } + + /// Holding the pad and dragging carries the projector with the mouse, the pointer hidden and kept on the pad; letting go ends it there + #[test] + fn holding_the_button_and_dragging_carries_the_projector_as_one_undo_step() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("triplanar"); + let rect = harness.state().viewport_rect; + let before = RoundGizmo::of(harness.state(), rect).unwrap(); + let (steps, camera) = (harness.state().session.history_labels().len(), harness.state().session.camera); + + let mut pointer = press_the_button(&mut harness); + let from = pointer.at; + assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "a press starts the hold"); + let moved = vec2(-300.0, -20.0); + pointer.drags(&mut harness, moved, 30, Modifiers::NONE); + let after = RoundGizmo::of(harness.state(), rect).unwrap(); + assert!((after.center - (before.center + moved)).length() < 2.0, "the projector follows the mouse: {:?} -> {:?}", before.center, after.center); + assert!(pointer.hidden, "the pointer hides while held"); + assert!(pointer.at.distance(from) < 1.0, "and stays on the pad, so no screen edge stops the drag: {:?}", pointer.at); + let slid = projection(&harness, layer); + assert_ne!(projector_offset(&slid), [0.0; 3], "the projector itself moved: {slid:?}"); + assert_eq!(uv_of(&slid), UvTransform::default(), "not only the image inside it"); + + let_go(&mut harness, &mut pointer); + assert_eq!(harness.state().moving_on_model, None, "letting go ends it"); + assert!(!pointer.hidden && pointer.at == from, "the pointer shows again where the press began: {:?}", pointer.at); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step per hold"); + assert_eq!(harness.state().session.camera, camera, "the camera kept still"); + + // The 3D view has its drags back: a drag on the model off the projector's handles moves nothing + let off = on_the_model_off_the_handles(&harness); + drag(&mut harness, off, off + vec2(60.0, 0.0), Modifiers::NONE); + assert_eq!(projection(&harness, layer), slid, "no mode is left on"); + } + + /// Losing the focus mid-hold (Alt+Tab) ends it as letting go does: one undo step, the pointer shown, and moves after it (egui still has the button down) leave the projection alone + #[test] + fn losing_the_window_focus_mid_hold_ends_it_as_letting_go_does() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("triplanar"); + let steps = harness.state().session.history_labels().len(); + let mut pointer = press_the_button(&mut harness); + pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE); + assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "the hold is under way"); + + harness.input_mut().events.push(egui::Event::WindowFocused(false)); + pointer.frame(&mut harness); + let left = projection(&harness, layer); + assert_eq!(harness.state().moving_on_model, None, "the focus loss ends the hold"); + assert!(!pointer.hidden, "the pointer shows again"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step, as letting go makes"); + + pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE); + assert_eq!(harness.state().moving_on_model, None, "the button still down in egui starts no new hold"); + assert_eq!(projection(&harness, layer), left, "moves after it leave the projection alone"); + } + + /// Removing the held fill mid-hold (its pad goes with it) ends the hold at once, the button still down, with or without the 3D view: the pointer shows + #[test] + fn removing_the_held_fill_ends_the_hold() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for layout in [ViewLayout::Split, ViewLayout::Only2D] { + let (mut harness, layer) = fill_app("triplanar"); + harness.state_mut().ui.layout = layout; + harness.run_steps(2); + let mut pointer = press_the_button(&mut harness); + pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE); + assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "{layout:?}: the hold is under way"); + + harness.state_mut().run("layer.remove", json!({"layer": layer.0})).unwrap(); + pointer.frame(&mut harness); + assert_eq!(harness.state().moving_on_model, None, "{layout:?}: the hold ended with its fill"); + assert!(!pointer.hidden, "{layout:?}: the pointer shows again"); + } + } + + /// The preview square is the pad: a press anywhere on it, its corner too, starts the hold and holds the pointer + #[test] + fn the_preview_square_is_the_pad_from_corner_to_corner() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("triplanar"); + let pad = harness.get_by_label("Move on model").rect(); + assert!((pad.width() - pad.height()).abs() < 1.0 && pad.width() > 60.0, "Move on model is the preview square, no row of its own: {pad:?}"); + let before = projection(&harness, layer); + let mut pointer = SystemPointer::at(&mut harness, pad.left_top() + vec2(4.0, 4.0)); + pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); + assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "a press at its corner starts the hold"); + pointer.drags(&mut harness, vec2(40.0, 0.0), 10, Modifiers::NONE); + assert!(pointer.hidden, "the pointer is held"); + let_go(&mut harness, &mut pointer); + assert_ne!(projection(&harness, layer), before, "the drag moved the projection"); + assert_eq!(harness.state().moving_on_model, None); + } + + /// While held, Shift or the right button turns the image and the wheel scales it, all in the hold's one undo step; the camera neither orbits nor zooms. Released, the wheel zooms again + #[test] + fn shift_or_the_right_button_turns_and_the_wheel_scales_while_held() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("triplanar"); + let rect = harness.state().viewport_rect; + let (steps, camera) = (harness.state().session.history_labels().len(), harness.state().session.camera); + let mut pointer = press_the_button(&mut harness); + let from = pointer.at; + + pointer.drags(&mut harness, vec2(-40.0, 0.0), 30, Modifiers::SHIFT); + let shifted = uv_of(&projection(&harness, layer)); + assert!(shifted.rotation > 0.0, "Shift turns the image: {shifted:?}"); + assert_eq!(projector_offset(&projection(&harness, layer)), [0.0; 3], "and does not slide it"); + + // The right button pressed once the drag has carried the held pointer over the 3D view, the left still holding the button + let over_view = rect.center() + vec2(-100.0, 80.0); + pointer.drags(&mut harness, over_view - (from + vec2(-40.0, 0.0)), 30, Modifiers::NONE); + let slid = projection(&harness, layer); + pointer.button(&mut harness, PointerButton::Secondary, true, Modifiers::NONE); + pointer.drags(&mut harness, vec2(-40.0, 0.0), 30, Modifiers::NONE); + let turned = projection(&harness, layer); + assert!(uv_of(&turned).rotation < shifted.rotation, "the right button turns it: {shifted:?} -> {turned:?}"); + assert_eq!(projector_offset(&turned), projector_offset(&slid), "without sliding"); + pointer.button(&mut harness, PointerButton::Secondary, false, Modifiers::NONE); + + wheel(&mut harness, &mut pointer); + let scaled = uv_of(&projection(&harness, layer)); + assert!(scaled.tiling[0] < uv_of(&turned).tiling[0] && scaled.tiling[0] == scaled.tiling[1], "the wheel up makes the image bigger: {scaled:?}"); + assert_eq!(harness.state().session.camera, camera, "the camera neither orbited nor zoomed"); + assert!(harness.state().properties_popup.is_none(), "the right click opened no Properties popup"); + + let_go(&mut harness, &mut pointer); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the whole hold is one undo step"); + let back = pointer.at; + pointer.moves(&mut harness, over_view - back, Modifiers::NONE); + wheel(&mut harness, &mut pointer); + assert_ne!(harness.state().session.camera, camera, "let go, the wheel zooms the camera"); + assert_eq!(uv_of(&projection(&harness, layer)), scaled, "and leaves the projection alone"); + } + + /// A hold whose first edit changes nothing (Shift with an up and down drag turns a frame by nothing) makes no undo step, so its later edits make the hold's own step instead of joining the edit before it + #[test] + fn a_hold_that_first_changes_nothing_keeps_its_own_undo_step() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "rotation": 30.0})).unwrap(); + harness.run_steps(2); + let turned = projection(&harness, layer); + let steps = harness.state().session.history_labels().len(); + + let mut pointer = press_the_button(&mut harness); + pointer.drags(&mut harness, vec2(0.0, -40.0), 10, Modifiers::SHIFT); + assert_eq!(projection(&harness, layer), turned, "an up and down turn changes nothing"); + pointer.drags(&mut harness, vec2(0.0, -40.0), 10, Modifiers::NONE); + let_go(&mut harness, &mut pointer); + assert_ne!(projection(&harness, layer), turned, "the slide moved the frame"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the hold made its own undo step"); + + harness.state_mut().session.undo().unwrap(); + assert_eq!(projection(&harness, layer), turned, "undo takes back the hold only"); + } + + /// A UV image slides as far as the mouse goes, past the window's edge; a warp's frame slides across its plane + #[test] + fn a_hold_slides_a_uv_image_and_a_frame_across_its_plane() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("uv"); + let height = harness.state().viewport_rect.height(); + let mut pointer = press_the_button(&mut harness); + let from = pointer.at; + wheel(&mut harness, &mut pointer); + assert_eq!(harness.get_by_label("Move on model").rect().center(), from, "a wheel step over the panel while held scales, it does not scroll the panel"); + let Projection::Uv { scale, .. } = projection(&harness, layer) else { panic!("still UV") }; + assert!(scale[0] < 1.0, "the wheel up makes the image bigger: {scale:?}"); + let far = vec2(-3.0 * from.x, 0.0); + pointer.drags(&mut harness, far, 60, Modifiers::NONE); + let_go(&mut harness, &mut pointer); + let Projection::Uv { offset, .. } = projection(&harness, layer) else { panic!("still UV") }; + assert!( + (offset[0] - (-far.x) * SLIDE_PER_HEIGHT / height).abs() < 0.01 && offset[1] == 0.0, + "a drag left slides the image left, all the way: {offset:?}" + ); + + let (mut harness, layer) = fill_app("warp"); + let mut pointer = press_the_button(&mut harness); + pointer.drags(&mut harness, vec2(0.0, -40.0), 30, Modifiers::NONE); + let_go(&mut harness, &mut pointer); + let Projection::Warp { frame, .. } = projection(&harness, layer) else { panic!("still a warp") }; + assert!(frame.offset[1] > 0.0 && frame.offset[0].abs() < frame.offset[1] * 0.2, "a drag up slides the frame up: {frame:?}"); + } +} diff --git a/crates/ui-egui/src/preview_dots.rs b/crates/ui-egui/src/preview_dots.rs new file mode 100644 index 00000000..09af91a8 --- /dev/null +++ b/crates/ui-egui/src/preview_dots.rs @@ -0,0 +1,53 @@ +//! The preview square's two dots: a ring where the projection sits with Offset 0, a filled dot where its Offset puts it, a dotted line between + +use egui::{Painter, Pos2, Stroke}; + +use crate::theme::Tokens; + +/// The ring's radius (points) +const RING_RADIUS: f32 = 5.5; + +/// The ring's line width (points) +const RING_LINE: f32 = 1.6; + +/// The width of the line under the ring that keeps it readable on the checker (points) +const RING_UNDER: f32 = 3.6; + +/// The filled dot's radius (points) +const DOT_RADIUS: f32 = 3.3; + +/// The width of the rim under the filled dot (points) +const DOT_RIM: f32 = 1.0; + +/// The dotted line's air between its dots (points) +const LINE_SPACING: f32 = 3.5; + +/// The radius of the dotted line's dots (points) +const LINE_DOT: f32 = 0.9; + +/// The width of the rim under the dotted line's dots (points) +const LINE_RIM: f32 = 0.6; + +/// Most dots the line draws: more than any preview square holds, the rest would be cut off anyway +const MAX_LINE_DOTS: usize = 256; + +/// Paints the two dots and the dotted line between them, from the filled dot out so a ring far past the square still gets its line +pub(crate) fn preview_dots(painter: &Painter, center: Pos2, position: Pos2, tokens: &Tokens) { + let span = center - position; + let length = span.length(); + let start = DOT_RADIUS + LINE_SPACING; + let end = length - RING_RADIUS - LINE_SPACING / 2.0; + if length.is_finite() && end > start { + let toward = span / length; + let count = (((end - start) / LINE_SPACING).floor() as usize).min(MAX_LINE_DOTS); + for step in 0..=count { + let at = position + toward * (start + step as f32 * LINE_SPACING); + painter.circle_filled(at, LINE_DOT + LINE_RIM, tokens.field); + painter.circle_filled(at, LINE_DOT, tokens.text); + } + } + painter.circle_stroke(center, RING_RADIUS, Stroke::new(RING_UNDER, tokens.field)); + painter.circle_stroke(center, RING_RADIUS, Stroke::new(RING_LINE, tokens.text)); + painter.circle_filled(position, DOT_RADIUS + DOT_RIM, tokens.field); + painter.circle_filled(position, DOT_RADIUS, tokens.text); +} diff --git a/crates/ui-egui/src/projection_kind.rs b/crates/ui-egui/src/projection_kind.rs new file mode 100644 index 00000000..4d3b676c --- /dev/null +++ b/crates/ui-egui/src/projection_kind.rs @@ -0,0 +1,68 @@ +//! The projections a fill's Projection dropdown offers + +use texturecraft_engine::core::Projection; + +use crate::i18n::n_; + +/// The projections a fill's Projection dropdown offers, with their command ids +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ProjectionKind { + UvTile, + Uv, + Triplanar, + Planar, + Spherical, + Cylindrical, + Warp, +} + +impl ProjectionKind { + pub(crate) const ALL: [ProjectionKind; 7] = [ + ProjectionKind::UvTile, + ProjectionKind::Uv, + ProjectionKind::Triplanar, + ProjectionKind::Planar, + ProjectionKind::Warp, + ProjectionKind::Spherical, + ProjectionKind::Cylindrical, + ]; + + /// The `projection` param of `layer.fill.projection` + pub(crate) fn id(self) -> &'static str { + match self { + ProjectionKind::UvTile => "uvTile", + ProjectionKind::Uv => "uv", + ProjectionKind::Triplanar => "triplanar", + ProjectionKind::Planar => "planar", + ProjectionKind::Spherical => "spherical", + ProjectionKind::Cylindrical => "cylindrical", + ProjectionKind::Warp => "warp", + } + } + + /// The kind `projection` is, as the Projection dropdown lists it + pub(crate) fn of(projection: &Projection) -> ProjectionKind { + match projection { + Projection::UvTile => ProjectionKind::UvTile, + Projection::Uv { .. } => ProjectionKind::Uv, + Projection::Triplanar { .. } => ProjectionKind::Triplanar, + Projection::Planar { .. } => ProjectionKind::Planar, + Projection::Spherical { .. } => ProjectionKind::Spherical, + Projection::Cylindrical { .. } => ProjectionKind::Cylindrical, + Projection::Warp { .. } => ProjectionKind::Warp, + } + } + + /// The dropdown's name for it + pub(crate) fn label(self) -> &'static str { + match self { + ProjectionKind::UvTile => n_("Fill (Match per UV Tile)"), + ProjectionKind::Uv => n_("UV projection"), + ProjectionKind::Triplanar => n_("Tri-planar projection"), + ProjectionKind::Planar => n_("Planar projection"), + ProjectionKind::Spherical => n_("Spherical projection"), + ProjectionKind::Cylindrical => n_("Cylindrical projection"), + ProjectionKind::Warp => n_("Warp projection"), + } + } +} diff --git a/crates/ui-egui/src/projection_preview.rs b/crates/ui-egui/src/projection_preview.rs new file mode 100644 index 00000000..fefc92d8 --- /dev/null +++ b/crates/ui-egui/src/projection_preview.rs @@ -0,0 +1,846 @@ +//! The preview square of a 3D projection: a checker laid on a sphere, cylinder or cube through the fill's own projection +//! +//! Each pixel casts a ray at the shape and samples the checker with the compositor's projection math +//! ([`image_samples`] and [`projector_cover`]), so tiling, offset, rotation, Hardness, Angle, the 3D projection +//! settings, Shape crop and Backface culling show as they will on the model. Depth culling needs the model's depth +//! map and is not previewed. The projector is drawn round the shape as the 3D view's gizmo draws it round the model, and the +//! view zooms out until both fit, down to half the shape's size; a projector bigger than that runs off the square, marked on +//! each side it passes + +use egui::{Color32, ColorImage, Painter, Pos2, Rect, Shape, Stroke, TextureOptions, pos2, vec2}; +use texturecraft_engine::compose::frame_placement::{folded, upright_turn}; +use texturecraft_engine::compose::pattern::{Coords, decal_axes, image_samples}; +use texturecraft_engine::compose::projector_cover::projector_cover; +use texturecraft_engine::core::{Projection, Projector, ShapeCrop}; +use texturecraft_engine::geom::glam::{Vec2, Vec3}; + +use rayon::prelude::*; + +use crate::projector_outline::ProjectorOutline; +use crate::theme::Tokens; + +mod preview_shape; +mod rendered_preview; +mod screen; +mod view; + +use preview_shape::PreviewShape; +use rendered_preview::RenderedPreview; +use screen::Screen; +use view::View; + + +/// Largest preview side in pixels; the square is never drawn bigger than this +const MAX_SIDE_PX: usize = 256; + +/// Rays per pixel along each axis (smooth outline) +const SUPERSAMPLE: usize = 2; + +/// Rays per pixel along each axis while a drag is held: a quarter of the rays, so the square keeps up with the pointer; the full picture follows on release +const DRAG_SUPERSAMPLE: usize = 1; + +/// Checker cells across one repeat of the source along each axis, in this square and in a warp's frame alike (an untiled, unturned image shows 4 × 4 cells), so a fill looks the same in both +pub(crate) const CHECKER_CELLS: f32 = 4.0; + +/// Half the view's width and height, in mesh radii: as near as the view comes +const VIEW_HALF: f32 = 1.0; + +/// Half the view's width and height as far as it zooms out, in mesh radii (the shape at half its size) +const MAX_VIEW_HALF: f32 = 2.0; + +/// Room left round the projector when the view zooms out to it +const FIT_MARGIN: f32 = 1.12; + +/// How far in front of the middle the rays start, in mesh radii (past every shape and every outline point tested for cover) +const CAMERA_DISTANCE: f32 = 3.0; + +/// Screen length of the pieces an outline is split into to find its hidden parts (points) +const OUTLINE_STEP: f32 = 3.0; + +/// The most pieces one outline segment is split into, however long it runs on screen +const MAX_OUTLINE_PIECES: f32 = 256.0; + +/// The outline's dashes where the shape hides it (points) +const HIDDEN_DASH: f32 = 3.0; + +/// The edge marker's dashes (points) +const EDGE_DASH: f32 = 6.0; + +/// The edge marker's inset from the square's side (points) +const EDGE_INSET: f32 = 2.0; + +/// The edge marker's chevron arm (points) +const CHEVRON_ARM: f32 = 5.0; + +/// The clear margin round the chevron, so the dashes and the shape stop short of it (points) +const CHEVRON_PATCH_MARGIN: f32 = 1.5; + +/// The dot at a planar's direction tip (points) +const TIP_DOT: f32 = 2.2; + +/// How far the field-coloured rim under the tip dot reaches past it (points) +const TIP_DOT_RIM: f32 = 0.8; + +/// The width of the field-coloured line under the outline, which keeps it readable on the checker (points) +const OUTLINE_UNDER_WIDTH: f32 = 2.5; + +/// The width of the outline itself (points) +const OUTLINE_WIDTH: f32 = 1.2; + +/// How strong the line under the outline and the outline show where the camera sees them +const SEEN_SHADES: (f32, f32) = (0.55, 1.0); + +/// How strong the line under the outline and the outline show where the shape hides them: fainter +const HIDDEN_SHADES: (f32, f32) = (0.35, 0.65); + +/// Points a point may lie past a side of the square and still count as inside it (a point on the side's pixel rounds either way) +const PAST_SIDE_SLACK: f32 = 0.5; + +/// Camera turn around the up axis (degrees): three faces of the cube and the cylinder's top show +const CAMERA_YAW: f32 = 35.0; + +/// Camera turn down from level (degrees) +const CAMERA_PITCH: f32 = 25.0; + +/// Where the light comes from, along the view's right, up and towards the eye: above and to the left of the camera +const LIGHT_FROM: [f32; 3] = [-0.5, 0.6, 0.6]; + +/// Light that reaches faces turned away from the light +const AMBIENT: f32 = 0.3; + +/// The sphere's radius, in mesh radii, inside the unit sphere the compositor's coordinates span +const SPHERE_RADIUS: f32 = 0.85; + +/// The cylinder's radius, in mesh radii +const CYLINDER_RADIUS: f32 = 0.55; + +/// Half the cylinder's height, in mesh radii +const CYLINDER_HALF_HEIGHT: f32 = 0.7; + +/// Half the cube's side, in mesh radii +const CUBE_HALF: f32 = 0.55; + +/// The checker's dark cells, as a fraction of the way from `field` to `text` +const CHECKER_DARK: f32 = 0.12; + +/// The checker's light cells, as a fraction of the way from `field` to `text` +const CHECKER_LIGHT: f32 = 1.0; + +/// The shape where the projection does not reach, as a fraction of the way from `field` to `text` +const UNCOVERED: f32 = 0.45; + +/// How much of the projection reaches a ray past which it counts as covered, for the edge of its reach +const HALF_COVERED: f32 = 0.5; + +/// How far a ray on the edge of the projection's reach is drawn from the accent towards the shape's colour +const EDGE_BLEND: f32 = 0.5; + +/// The smallest model radius and frame half size the preview divides by, in mesh units and mesh radii +const MIN_SIZE: f32 = 1e-4; + +/// A ray this close to parallel to a face or the cylinder's axis never meets it +const PARALLEL_TOLERANCE: f32 = 1e-6; + +/// Draw the preview of `projection` on a mesh within `bounds` into `rect`, rendered once per projection, size and theme, with a quarter of the rays while a drag is held (None for projections without one: UV, warp); each `owner` (the docked panel's square, the popup's) keeps its own picture +pub(crate) fn projection_preview(painter: &Painter, rect: Rect, projection: &Projection, bounds: (Vec3, Vec3), tokens: &Tokens, owner: egui::Id) -> Option<()> { + let shown = shown_projection(projection, bounds)?; + let ctx = painter.ctx(); + let side = ((rect.width() * ctx.pixels_per_point()).round() as usize).clamp(1, MAX_SIDE_PX); + let shape = shape_for(&shown); + let outline = ProjectorOutline::of(&shown, shape.half_size()); + let (resting, half) = resting_fit(&shown, shape); + let key = format!("{side}{half}{shown:?}{:?}{:?}{:?}", tokens.field, tokens.text, tokens.accent); + let held = ctx.input(|input| input.pointer.any_down()); + let id = slot(owner); + #[cfg(test)] + ctx.data_mut(|data| data.insert_temp(egui::Id::unique(LAST_OWNER), owner)); + + // The picture, the key and the rays per pixel it was rendered with; a drag's lighter picture is redone in full once the pointer is let go + let cached = ctx.data(|data| data.get_temp::(id)); + let up_to_date = cached.as_ref().is_some_and(|cached| cached.key == key && (held || cached.supersample == SUPERSAMPLE)); + let texture = match cached { + Some(cached) if up_to_date => cached.texture, + cached => { + let supersample = if held { DRAG_SUPERSAMPLE } else { SUPERSAMPLE }; + let image = render(&shown, side, half, supersample, tokens); + let texture = match cached { + Some(RenderedPreview { mut texture, .. }) => { + texture.set(image, TextureOptions::LINEAR); + texture + } + None => ctx.load_texture("projection-preview", image, TextureOptions::LINEAR), + }; + ctx.data_mut(|data| data.insert_temp(id, RenderedPreview { key, supersample, texture: texture.clone() })); + texture + } + }; + painter.image(texture.id(), rect, FULL_UV, Color32::WHITE); + if let Some(outline) = &outline { + let painter = painter.with_clip_rect(rect.intersect(painter.clip_rect())); + let screen = Screen { view: View::new(), rect, half }; + draw_outline(&painter, &screen, shape, outline, tokens); + let center = resting.as_ref().map_or(rect.center(), |resting| screen.at(resting.center)); + crate::preview_dots::preview_dots(&painter, center, screen.at(outline.center), tokens); + edge_markers(&painter, rect, passed_sides(outline.points().chain([outline.center]).map(|point| screen.at(point)), rect), tokens); + } + painter.rect_stroke(rect, 0, egui::Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); + Some(()) +} + +/// Where `owner`'s preview square keeps its picture +fn slot(owner: egui::Id) -> egui::Id { + egui::Id::unique(("projection_preview", owner)) +} + +/// Where tests find the owner of the square drawn last +#[cfg(test)] +const LAST_OWNER: &str = "projection_preview_last_owner"; + +/// The picture of the square drawn last (tests) +#[cfg(test)] +fn last_rendered(ctx: &egui::Context) -> Option { + let owner = ctx.data(|data| data.get_temp::(egui::Id::unique(LAST_OWNER)))?; + ctx.data(|data| data.get_temp::(slot(owner))) +} + +/// What the preview square last rendered (tests: a drag re-renders it) +#[cfg(test)] +pub(crate) fn shown_key(ctx: &egui::Context) -> Option { + last_rendered(ctx).map(|rendered| rendered.key) +} + +/// How the preview square was last rendered, with rays per pixel (tests: a drag renders it lighter, the release in full) +#[cfg(test)] +pub(crate) fn shown_supersample(ctx: &egui::Context) -> Option { + last_rendered(ctx).map(|rendered| rendered.supersample) +} + +/// The projection the preview renders: a planar placed on the model shows straight onto the sphere's front as big against the sphere as its frame is against the mesh, stretched, turned round its normal and slid across its plane as the frame is, cropped to its rectangle +fn shown_projection(projection: &Projection, bounds: (Vec3, Vec3)) -> Option { + match projection { + Projection::Planar { placed: Some(_), uv, .. } => { + let landed = folded(projection)?; + let Projection::Planar { placed: Some(frame), projector, .. } = &landed else { return None }; + + // The sphere stands for the model: its radius is the model's largest half size + let radius = ((bounds.1 - bounds.0) * 0.5).max_element().max(MIN_SIZE); + let half = frame.size.map(|side| (SPHERE_RADIUS * side / (2.0 * radius)).max(MIN_SIZE)); + let turn = upright_turn(frame).unwrap_or(0.0); + + // Slid across its own plane away from the mesh's centre: off the sphere's middle by as much + let (origin, across, up, _) = decal_axes(frame)?; + let from_center = (origin - (bounds.0 + bounds.1) * 0.5) / radius * SPHERE_RADIUS; + let offset = [-from_center.dot(across) / half[0], -from_center.dot(up) / half[1], 0.0]; + let projector = Projector { rotation: [0.0, 0.0, turn], scale: [half[0], half[1], 1.0], crop: ShapeCrop::Cropped, ..*projector }; + offset.iter().all(|value| value.is_finite()).then_some(Projection::Planar { scale: 1.0, axis: 2, offset, uv: *uv, projector, placed: None }) + } + Projection::Planar { .. } | Projection::Spherical { .. } | Projection::Cylindrical { .. } | Projection::Triplanar { .. } => Some(projection.clone()), + Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => None, + } +} + +/// The projector `shown` round `shape` back at Offset 0, and how far the view reaches to fit it there: sliding the projector never zooms +fn resting_fit(shown: &Projection, shape: PreviewShape) -> (Option, f32) { + let resting = ProjectorOutline::of(&at_rest(shown), shape.half_size()); + let half = view_half(resting.as_ref()); + (resting, half) +} + +/// `projection` with its projector back at Offset 0 (its turn and size kept) +fn at_rest(projection: &Projection) -> Projection { + let mut resting = projection.clone(); + match &mut resting { + Projection::Planar { offset, .. } + | Projection::Triplanar { offset, .. } + | Projection::Spherical { offset, .. } + | Projection::Cylindrical { offset, .. } => { + *offset = [0.0; 3]; + } + Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => {} + } + resting +} + +/// Which way the preview camera looks +pub(crate) fn view_direction() -> Vec3 { + View::new().forward +} + +/// How far the view reaches each way from the middle so the shape and the projector `outline` both fit: never nearer than today's framing, never so far the shape drops below half its size +fn view_half(outline: Option<&ProjectorOutline>) -> f32 { + let view = View::new(); + let reach = + outline.into_iter().flat_map(ProjectorOutline::points).map(|point| point.dot(view.right).abs().max(point.dot(view.up).abs())).fold(0.0, f32::max); + if reach.is_finite() { (reach * FIT_MARGIN).clamp(VIEW_HALF, MAX_VIEW_HALF) } else { MAX_VIEW_HALF } +} + +/// The outline's line in the text colour and the field-coloured line under it that keeps it readable on the checker, as the 3D view's gizmo draws its white outline on a dark shadow (the square's field is light in the light themes); fainter where the shape hides it +fn outline_strokes(hidden: bool, tokens: &Tokens) -> [Stroke; 2] { + let (under, over) = if hidden { HIDDEN_SHADES } else { SEEN_SHADES }; + [Stroke::new(OUTLINE_UNDER_WIDTH, tokens.field.gamma_multiply(under)), Stroke::new(OUTLINE_WIDTH, tokens.text.gamma_multiply(over))] +} + +/// The projector outline over the preview: solid where the camera sees it, dashed where the shape hides it, a dot where a planar's image travels to +fn draw_outline(painter: &Painter, screen: &Screen, shape: PreviewShape, outline: &ProjectorOutline, tokens: &Tokens) { + for line in &outline.lines { + // Runs of the line that are all seen or all hidden + let mut runs: Vec<(bool, Vec)> = Vec::new(); + for pair in line.windows(2) { + let [from, to] = [pair[0], pair[1]]; + let pieces = ((screen.at(to) - screen.at(from)).length() / OUTLINE_STEP).ceil().clamp(1.0, MAX_OUTLINE_PIECES) as usize; + for piece in 0..pieces { + let (start, end) = (from.lerp(to, piece as f32 / pieces as f32), from.lerp(to, (piece + 1) as f32 / pieces as f32)); + let hidden = screen.hidden(shape, start.lerp(end, 0.5)); + match runs.last_mut() { + Some((run_hidden, points)) if *run_hidden == hidden => points.push(screen.at(end)), + _ => runs.push((hidden, vec![screen.at(start), screen.at(end)])), + } + } + } + for (hidden, points) in runs { + for stroke in outline_strokes(hidden, tokens) { + if hidden { + painter.extend(Shape::dashed_line(&points, stroke, HIDDEN_DASH, HIDDEN_DASH)); + } else { + painter.add(Shape::line(points.clone(), stroke)); + } + } + } + } + if let Some(tip) = outline.tip { + let [under, over] = outline_strokes(false, tokens); + painter.circle_filled(screen.at(tip), TIP_DOT + TIP_DOT_RIM, under.color); + painter.circle_filled(screen.at(tip), TIP_DOT, over.color); + } +} + +/// The sides of `rect` some of `points` lie past: left, right, top, bottom +pub(crate) fn passed_sides(points: impl Iterator, rect: Rect) -> [bool; 4] { + let outer = rect.expand(PAST_SIDE_SLACK); + points.fold([false; 4], |[left, right, top, bottom], point| { + [left || point.x < outer.left(), right || point.x > outer.right(), top || point.y < outer.top(), bottom || point.y > outer.bottom()] + }) +} + +/// A dashed line just inside each side of `rect` the projector runs past, with a chevron pointing out at its middle +pub(crate) fn edge_markers(painter: &Painter, rect: Rect, sides: [bool; 4], tokens: &Tokens) { + let inner = rect.shrink(EDGE_INSET); + let center = rect.center(); + + // Per side: its two ends, the chevron's point and the way into the square + let edges = [ + ([inner.left_top(), inner.left_bottom()], pos2(inner.left(), center.y), vec2(1.0, 0.0)), + ([inner.right_top(), inner.right_bottom()], pos2(inner.right(), center.y), vec2(-1.0, 0.0)), + ([inner.left_top(), inner.right_top()], pos2(center.x, inner.top()), vec2(0.0, 1.0)), + ([inner.left_bottom(), inner.right_bottom()], pos2(center.x, inner.bottom()), vec2(0.0, -1.0)), + ]; + for (passed, (ends, point, inward)) in sides.into_iter().zip(edges) { + if !passed { + continue; + } + + let along = vec2(inward.y, inward.x); + let chevron = vec![point + (inward - along) * CHEVRON_ARM, point, point + (inward + along) * CHEVRON_ARM]; + for stroke in outline_strokes(false, tokens) { + painter.extend(Shape::dashed_line(&ends, stroke, EDGE_DASH, EDGE_DASH)); + } + + // The chevron on a clear patch, so the dashes and the shape do not run through it + let patch = Rect::from_points(&chevron).expand(CHEVRON_PATCH_MARGIN); + painter.rect_filled(patch, 0, tokens.field); + for stroke in outline_strokes(false, tokens) { + painter.add(Shape::line(chevron.clone(), stroke)); + } + } +} + +/// The shape the preview shows `projection` on: a cylinder for a cylindrical, a cube for a tri-planar, else a sphere +fn shape_for(projection: &Projection) -> PreviewShape { + match projection { + Projection::Cylindrical { .. } => PreviewShape::Cylinder, + Projection::Triplanar { .. } => PreviewShape::Cube, + _ => PreviewShape::Sphere, + } +} + +/// `side²` pixels of the checker on the projection's shape over the `field` background, the view `half` mesh radii across each way from the middle, `supersample²` rays per pixel cast on every core +fn render(projection: &Projection, side: usize, half: f32, supersample: usize, tokens: &Tokens) -> ColorImage { + let shape = shape_for(projection); + let View { eye, forward, right, up } = View::new(); + let [light_right, light_up, light_eye] = LIGHT_FROM; + let light = (light_right * right + light_up * up + light_eye * eye).normalize_or_zero(); + + let field = tokens.field; + let (background, text) = (linear(field), linear(tokens.text)); + let shades = [CHECKER_DARK, CHECKER_LIGHT, UNCOVERED].map(|t| background.lerp(text, t)); + let supersample = supersample.max(1); + let rays = side * supersample; + + // Per ray: the lit colour and how much of the projection lands there (None = the background) + let samples: Vec> = (0..rays * rays) + .into_par_iter() + .map(|ray| { + let (x, y) = (ray % rays, ray / rays); + let across = ((x as f32 + 0.5) / rays as f32 * 2.0 - 1.0) * half; + let down = ((y as f32 + 0.5) / rays as f32 * 2.0 - 1.0) * half; + let origin = right * across - up * down + eye * CAMERA_DISTANCE; + let hit = intersect(shape, origin, forward)?; + let shade = AMBIENT + (1.0 - AMBIENT) * hit.nrm.dot(light).max(0.0); + let (color, cover) = surface(projection, &hit, shades); + Some((color * shade, cover)) + }) + .collect(); + + let edge = linear(tokens.accent); + let mut image = ColorImage::new([side, side], vec![field; side * side]); + image.pixels.par_iter_mut().enumerate().for_each(|(pixel, out)| { + let (x, y) = (pixel % side, pixel / side); + let mut sum = Vec3::ZERO; + for sub in 0..supersample * supersample { + let (rx, ry) = (x * supersample + sub % supersample, y * supersample + sub / supersample); + let color = match samples.get(ry * rays + rx).copied().flatten() { + Some((color, cover)) if on_edge(&samples, rays, rx, ry, cover) => edge.lerp(color, EDGE_BLEND), + Some((color, _)) => color, + None => background, + }; + sum += color; + } + *out = from_linear(sum / (supersample * supersample) as f32); + }); + image +} + +/// Where the projection's reach ends on the shape: covered here, not on a neighbouring ray of the shape +fn on_edge(samples: &[Option<(Vec3, f32)>], rays: usize, x: usize, y: usize, cover: f32) -> bool { + if cover <= HALF_COVERED { + return false; + } + + let neighbours = [(x.wrapping_sub(1), y), (x + 1, y), (x, y.wrapping_sub(1)), (x, y + 1)]; + neighbours + .into_iter() + .any(|(nx, ny)| nx < rays && ny < rays && samples.get(ny * rays + nx).copied().flatten().is_some_and(|(_, cover)| cover <= HALF_COVERED)) +} + +/// The unlit colour at a hit and how much of the projection reaches it, from the dark and light checker and the uncovered shape `shades` in linear light +fn surface(projection: &Projection, hit: &Coords, shades: [Vec3; 3]) -> (Vec3, f32) { + let cover = projector_cover(projection, hit).clamp(0.0, 1.0); + let mut light = 0.0; + for (uv, weight) in image_samples(projection, hit) { + let cell = (uv * CHECKER_CELLS).floor(); + let even = (cell.x + cell.y).rem_euclid(2.0) < 0.5; + light += weight * f32::from(u8::from(even)); + } + let [dark, bright, uncovered] = shades; + (uncovered.lerp(dark.lerp(bright, light.clamp(0.0, 1.0)), cover), cover) +} + +/// The nearest hit of the ray from `origin` along unit `dir` on the preview shape +fn intersect(shape: PreviewShape, origin: Vec3, dir: Vec3) -> Option { + match shape { + PreviewShape::Sphere => intersect_sphere(origin, dir), + PreviewShape::Cube => intersect_cube(origin, dir), + PreviewShape::Cylinder => intersect_cylinder(origin, dir), + } +} + +/// The nearer hit of the ray from `ray_origin` along unit `ray_dir` on the sphere round the middle +fn intersect_sphere(ray_origin: Vec3, ray_dir: Vec3) -> Option { + // |origin + t·dir|² = r², with |dir| = 1: t² + 2·half_b·t + c = 0 + let half_b = ray_origin.dot(ray_dir); + let c = ray_origin.length_squared() - SPHERE_RADIUS * SPHERE_RADIUS; + let discriminant = half_b * half_b - c; + if discriminant < 0.0 { + return None; + } + + let point = ray_origin + ray_dir * (-half_b - discriminant.sqrt()); + Some(hit(point, point.normalize_or_zero())) +} + +/// Where the ray from `ray_origin` along `ray_dir` enters the cube round the middle: the latest of the three slabs' entries, before the earliest exit +fn intersect_cube(ray_origin: Vec3, ray_dir: Vec3) -> Option { + let (mut near, mut far, mut nrm) = (f32::NEG_INFINITY, f32::INFINITY, Vec3::ZERO); + for axis in 0..3 { + let (start, along) = (ray_origin[axis], ray_dir[axis]); + if along.abs() < PARALLEL_TOLERANCE { + if start.abs() > CUBE_HALF { + return None; + } + + continue; + } + + let (low_face, high_face) = ((-CUBE_HALF - start) / along, (CUBE_HALF - start) / along); + let (enter, exit) = (low_face.min(high_face), low_face.max(high_face)); + if enter > near { + near = enter; + nrm = Vec3::ZERO; + nrm[axis] = -along.signum(); + } + far = far.min(exit); + } + (near <= far && near.is_finite()).then(|| hit(ray_origin + ray_dir * near, nrm)) +} + +/// The nearest hit in front of `ray_origin` along `ray_dir` on the upright cylinder round the middle: its side or one of its caps +fn intersect_cylinder(ray_origin: Vec3, ray_dir: Vec3) -> Option { + let mut best: Option<(f32, Coords)> = None; + let mut keep = |distance: f32, hit: Coords| { + if distance > 0.0 && best.as_ref().is_none_or(|(best_distance, _)| distance < *best_distance) { + best = Some((distance, hit)); + } + }; + + // The side: x² + z² = r² within the height, a·t² + 2·half_b·t + c = 0 + let a = ray_dir.x * ray_dir.x + ray_dir.z * ray_dir.z; + let half_b = ray_origin.x * ray_dir.x + ray_origin.z * ray_dir.z; + let c = ray_origin.x * ray_origin.x + ray_origin.z * ray_origin.z - CYLINDER_RADIUS * CYLINDER_RADIUS; + let discriminant = half_b * half_b - a * c; + if a > PARALLEL_TOLERANCE && discriminant >= 0.0 { + let distance = (-half_b - discriminant.sqrt()) / a; + let point = ray_origin + ray_dir * distance; + if point.y.abs() <= CYLINDER_HALF_HEIGHT { + keep(distance, hit(point, Vec3::new(point.x, 0.0, point.z).normalize_or_zero())); + } + } + + // The caps + if ray_dir.y.abs() > PARALLEL_TOLERANCE { + for sign in [1.0, -1.0] { + let distance = (sign * CYLINDER_HALF_HEIGHT - ray_origin.y) / ray_dir.y; + let point = ray_origin + ray_dir * distance; + if point.x * point.x + point.z * point.z <= CYLINDER_RADIUS * CYLINDER_RADIUS { + keep(distance, hit(point, Vec3::Y * sign)); + } + } + } + best.map(|(_, hit)| hit) +} + +/// A shape point the camera sees, in the compositor's coordinates (no texture coordinates) +fn hit(pos: Vec3, nrm: Vec3) -> Coords { + Coords { uv: Vec2::ZERO, pos, nrm } +} + +/// `color` in linear light +fn linear(color: Color32) -> Vec3 { + let rgba = egui::Rgba::from(color); + Vec3::new(rgba.r(), rgba.g(), rgba.b()) +} + +/// A linear-light `color` back as a display colour +fn from_linear(color: Vec3) -> Color32 { + egui::Rgba::from_rgb(color.x, color.y, color.z).into() +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_engine::core::{Projector, UvTransform}; + + fn tokens() -> Tokens { + Tokens::for_brightness(crate::theme::Brightness::MediumDark) + } + + fn spherical(tiling: f32) -> Projection { + Projection::Spherical { + scale: 1.0, + uv: UvTransform { tiling: [tiling; 2], ..UvTransform::default() }, + offset: [0.0; 3], + projector: Projector::default(), + } + } + + fn cylindrical(projector: Projector) -> Projection { + Projection::Cylindrical { scale: 1.0, axis: 1, uv: UvTransform::default(), offset: [0.0; 3], projector, angle: 360.0 } + } + + #[test] + fn the_shape_fills_the_middle_and_leaves_the_corners_to_the_background() { + let tokens = tokens(); + for projection in [spherical(1.0), cylindrical(Projector::default()), Projection::triplanar()] { + let image = render(&projection, 32, VIEW_HALF, SUPERSAMPLE, &tokens); + assert_eq!(image.pixels[0], tokens.field, "{projection:?}: the corner is background"); + assert_ne!(image.pixels[16 * 32 + 16], tokens.field, "{projection:?}: the middle shows the shape"); + } + } + + #[test] + fn the_preview_follows_the_fill_settings() { + let tokens = tokens(); + assert_ne!( + render(&spherical(1.0), 32, VIEW_HALF, SUPERSAMPLE, &tokens).pixels, + render(&spherical(3.0), 32, VIEW_HALF, SUPERSAMPLE, &tokens).pixels, + "tiling changes the checker" + ); + + let culled = + Projector { backface: texturecraft_engine::core::Backface { on: true, ..Default::default() }, crop: ShapeCrop::Cropped, ..Projector::default() }; + assert_ne!( + render(&cylindrical(Projector::default()), 32, VIEW_HALF, SUPERSAMPLE, &tokens).pixels, + render(&cylindrical(culled), 32, VIEW_HALF, SUPERSAMPLE, &tokens).pixels, + "culling shows on the cylinder" + ); + } + + #[test] + fn projections_without_a_shape_have_no_preview() { + assert!(shown_projection(&Projection::UvTile, BOUNDS).is_none()); + assert!(shown_projection(&Projection::Uv { scale: [1.0; 2], rotation: 0.0, offset: [0.0; 2] }, BOUNDS).is_none()); + assert!(shown_projection(&spherical(1.0), BOUNDS).is_some()); + } + + const BOUNDS: (Vec3, Vec3) = (Vec3::NEG_ONE, Vec3::ONE); + + fn shown(projection: &Projection) -> Vec { + let shown = shown_projection(projection, BOUNDS).unwrap(); + let half = view_half(ProjectorOutline::of(&shown, shape_for(&shown).half_size()).as_ref()); + render(&shown, 32, half, SUPERSAMPLE, &tokens()).pixels + } + + /// What the 3D view's gizmo changes shows here too: a sphere's or cylinder's size, turn and centre, a placed frame's size, stretch and turn + #[test] + fn the_preview_shows_the_projectors_size_turn_and_place() { + let base = shown(&spherical(1.0)); + let bigger = Projector { scale: [1.15; 3], ..Projector::default() }; + let Projection::Spherical { uv, .. } = spherical(1.0) else { panic!("spherical() makes a spherical projection") }; + let sphere = |projector: Projector, offset: [f32; 3]| Projection::Spherical { scale: 1.0, uv, offset, projector }; + assert_ne!(shown(&sphere(bigger, [0.0; 3])), base, "a bigger sphere zooms the view out"); + assert_ne!(shown(&sphere(Projector { rotation: [0.0, 0.0, 40.0], ..Projector::default() }, [0.0; 3])), base, "a turned sphere turns its checker"); + assert_ne!(shown(&sphere(Projector::default(), [0.3, 0.0, 0.0])), base, "an offset moves it"); + assert_eq!(shown(&sphere(Projector::default(), [0.0; 3])), base, "unmoved: as before"); + assert_ne!( + shown(&cylindrical(Projector { scale: [1.3, 1.0, 1.3], ..Projector::default() })), + shown(&cylindrical(Projector::default())), + "a wider cylinder" + ); + + let frame = texturecraft_engine::core::Decal { + center: [0.0, 0.0, 1.0], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [1.0, 1.0], + rotation: 0.0, + offset: [0.0; 2], + depth: 1.0, + symmetry: None, + flip: [false; 2], + }; + let placed = |frame| Projection::decal(frame); + let square = shown(&placed(frame)); + assert_ne!(shown(&placed(texturecraft_engine::core::Decal { size: [0.5, 0.5], ..frame })), square, "a smaller frame"); + assert_ne!(shown(&placed(texturecraft_engine::core::Decal { size: [1.5, 1.0], ..frame })), square, "a stretched frame"); + assert_ne!(shown(&placed(texturecraft_engine::core::Decal { rotation: 30.0, ..frame })), square, "a turned frame"); + assert_ne!(shown(&placed(texturecraft_engine::core::Decal { offset: [0.3, 0.0], ..frame })), square, "a slid frame"); + } + + fn fitted_half(projection: &Projection) -> f32 { + let shown = shown_projection(projection, BOUNDS).unwrap(); + resting_fit(&shown, shape_for(&shown)).1 + } + + fn sized(scale: f32) -> Projection { + let Projection::Spherical { uv, .. } = spherical(1.0) else { panic!("spherical() makes a spherical projection") }; + Projection::Spherical { scale: 1.0, uv, offset: [0.0; 3], projector: Projector { scale: [scale; 3], ..Projector::default() } } + } + + /// The view zooms out until the projector fits, never nearer than the plain framing and never past half the shape's size; past that the projector runs off the square and each side it passes is marked + #[test] + fn the_view_fits_the_projector_down_to_half_the_shape() { + assert_eq!(fitted_half(&sized(0.4)), VIEW_HALF, "a small projector keeps the plain framing"); + let default = fitted_half(&sized(1.0)); + assert!(default > VIEW_HALF && default < MAX_VIEW_HALF, "{default}"); + assert_eq!(fitted_half(&sized(3.0)), MAX_VIEW_HALF, "x3 stops at half the shape's size"); + + let rect = Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)); + let sides = |scale: f32| { + let shown = sized(scale); + let outline = ProjectorOutline::of(&shown, PreviewShape::Sphere.half_size()).unwrap(); + let screen = Screen { view: View::new(), rect, half: fitted_half(&shown) }; + passed_sides(outline.points().map(|point| screen.at(point)), rect) + }; + assert_eq!(sides(1.0), [false; 4], "a fitted projector stays inside the square"); + assert_eq!(sides(3.0), [true; 4], "an x3 sphere runs past every side"); + + let triplanar = Projection::Triplanar { + scale: 1.0, + sharpness: Projection::TRIPLANAR_SHARPNESS, + offset: [0.0; 3], + uv: UvTransform::default(), + projector: Projector { scale: [10.0; 3], ..Projector::default() }, + }; + assert_eq!(fitted_half(&triplanar), MAX_VIEW_HALF, "every kind fits the same way"); + } + + /// Sliding a projector never zooms the view: it fits the projector at Offset 0, the ring stays in the middle and the projector's centre slides away from it + #[test] + fn the_offset_slides_the_projector_without_zooming_the_view() { + let rect = Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)); + let Projection::Spherical { scale, uv, projector, .. } = sized(1.0) else { panic!("sized() makes a spherical projection") }; + for offset in [[0.0, 0.0, 0.0], [0.3, 0.0, 0.0], [1.5, 0.8, 0.0]] { + let slid = Projection::Spherical { scale, uv, offset, projector }; + assert_eq!(fitted_half(&slid), fitted_half(&sized(1.0)), "Offset {offset:?} keeps the view"); + let (resting, half) = resting_fit(&slid, PreviewShape::Sphere); + let screen = Screen { view: View::new(), rect, half }; + let ring = screen.at(resting.unwrap().center); + let dot = screen.at(ProjectorOutline::of(&slid, PreviewShape::Sphere.half_size()).unwrap().center); + assert!(ring.distance(rect.center()) < 1e-3, "the ring marks the middle: {ring:?}"); + assert_eq!(dot.distance(ring) > 1.0, offset != [0.0; 3], "the filled dot leaves the ring only when slid: {dot:?}"); + } + } + + /// A huge spherical projector no longer fills the square with its own ball: the shape keeps half its size in the middle with background round it + #[test] + fn a_huge_sphere_keeps_the_shape_in_the_square() { + let tokens = tokens(); + let image = render(&sized(3.0), 32, fitted_half(&sized(3.0)), SUPERSAMPLE, &tokens); + assert_eq!(image.pixels[0], tokens.field, "the corner is background"); + assert_eq!(image.pixels[16 * 32 + 4], tokens.field, "the shape is half its size: its side is background"); + assert_ne!(image.pixels[16 * 32 + 16], tokens.field, "the shape is in the middle"); + } + + /// The outline is dashed where the shape hides it: the equator's back half runs behind the ball + #[test] + fn the_shape_hides_the_back_of_the_outline() { + let screen = Screen { view: View::new(), rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), half: 1.2 }; + let outline = ProjectorOutline::of(&sized(1.0), PreviewShape::Sphere.half_size()).unwrap(); + let hidden = |line: &Vec| line.iter().filter(|point| screen.hidden(PreviewShape::Sphere, **point)).count(); + assert_eq!(hidden(&outline.lines[0]), 0, "the rim is all seen"); + let equator = hidden(&outline.lines[1]); + assert!(equator > 0 && equator < outline.lines[1].len(), "the equator is half hidden: {equator}"); + } + + /// Every kind at x0.4, x1, x2, x3 and x10 (projector scale), as the panel's square draws it + #[test] + #[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] + fn preview_fit_snapshots() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + use crate::theme::Brightness; + let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { return }; + std::fs::create_dir_all(&directory).unwrap(); + const SIZES: [f32; 5] = [0.4, 1.0, 2.0, 3.0, 10.0]; + const SQUARE: f32 = 104.0; + const MARGIN: f32 = 4.0; + type Kind = (&'static str, fn(f32) -> Projection); + let kinds: [Kind; 4] = [ + ("planar", |s| Projection::Planar { + scale: 1.0, + axis: 2, + offset: [0.0; 3], + uv: UvTransform::default(), + projector: Projector { scale: [s, s, 1.0], ..Projector::default() }, + placed: None, + }), + ("spherical", sized), + ("cylindrical", |s| cylindrical(Projector { scale: [s; 3], ..Projector::default() })), + ("triplanar", |s| Projection::Triplanar { + scale: 1.0, + sharpness: Projection::TRIPLANAR_SHARPNESS, + offset: [0.0; 3], + uv: UvTransform::default(), + projector: Projector { scale: [s; 3], ..Projector::default() }, + }), + ]; + + // One square per picture: the preview keeps one rendered texture. The medium theme at every size, the others at two + let themes = [(Brightness::MediumDark, "", &SIZES[..]), (Brightness::Dark, "-dark", &[1.0, 3.0][..]), (Brightness::Light, "-light", &[1.0, 3.0][..])]; + for ((brightness, theme, sizes), (name, make)) in themes.into_iter().flat_map(|theme| kinds.map(|kind| (theme, kind))) { + for &scale in sizes { + let projection = make(scale); + let rect = Rect::from_min_size(pos2(MARGIN, MARGIN), vec2(SQUARE, SQUARE)); + let mut harness = + egui_kittest::Harness::builder().with_size(vec2(SQUARE + 2.0 * MARGIN, SQUARE + 2.0 * MARGIN)).with_pixels_per_point(2.0).wgpu().build_ui( + move |ui| { + let tokens = Tokens::for_brightness(brightness); + ui.painter().rect_filled(ui.ctx().content_rect(), 0, tokens.panel); + projection_preview(ui.painter(), rect, &projection, BOUNDS, &tokens, egui::Id::unique("square")); + }, + ); + harness.run_steps(2); + harness.render().unwrap().save(directory.join(format!("preview-fit-{name}-x{scale}{theme}.png"))).unwrap(); + } + } + + // In the panel: a x3 sphere zoomed out to its floor, marked on every side + let (mut harness, _) = crate::frame_gizmo::tests::fill_app_rendered(serde_json::json!({"projection": "spherical", "projectorScale": [3, 3, 3]}), true); + harness.run_steps(4); + harness.render().unwrap().save(directory.join("preview-fit-in-panel-spherical-x3.png")).unwrap(); + } + + /// One frame of `projection`'s preview square, with `events` as the frame's input + fn preview_frame(ctx: &egui::Context, projection: &Projection, events: Vec) { + let tokens = tokens(); + let input = egui::RawInput { events, ..Default::default() }; + let mut output = ctx.run_ui(input, |ui| { + projection_preview(ui.painter(), Rect::from_min_size(pos2(0.0, 0.0), vec2(64.0, 64.0)), projection, BOUNDS, &tokens, egui::Id::unique("square")); + }); + + // No renderer takes the uploads here + output.textures_delta.clear(); + } + + #[test] + fn a_drag_renders_the_square_lighter_and_the_release_renders_it_in_full() { + let ctx = egui::Context::default(); + let at = pos2(10.0, 10.0); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + preview_frame(&ctx, &spherical(1.0), Vec::new()); + assert_eq!(shown_supersample(&ctx), Some(SUPERSAMPLE), "at rest: in full"); + + preview_frame(&ctx, &spherical(1.0), vec![egui::Event::PointerMoved(at), button(true)]); + assert_eq!(shown_supersample(&ctx), Some(SUPERSAMPLE), "a press alone keeps the full picture: nothing changed"); + preview_frame(&ctx, &spherical(2.0), Vec::new()); + assert_eq!(shown_supersample(&ctx), Some(DRAG_SUPERSAMPLE), "a change while held renders lighter"); + let dragged = shown_key(&ctx); + + preview_frame(&ctx, &spherical(2.0), vec![button(false)]); + assert_eq!(shown_supersample(&ctx), Some(SUPERSAMPLE), "let go: the same picture in full"); + assert_eq!(shown_key(&ctx), dragged); + } + + /// Two squares of one projection at different sizes in one frame (the docked panel's and the popup's) keep their own pictures, so neither re-renders over the other + #[test] + fn two_squares_drawn_together_keep_their_own_pictures() { + let ctx = egui::Context::default(); + let tokens = tokens(); + let (docked, popup) = (egui::Id::unique("docked"), egui::Id::unique("popup")); + let rendered = |owner| ctx.data(|data| data.get_temp::(slot(owner))).expect("a picture"); + let mut shown = Vec::new(); + for _ in 0..2 { + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + projection_preview(ui.painter(), Rect::from_min_size(pos2(0.0, 0.0), vec2(64.0, 64.0)), &spherical(1.0), BOUNDS, &tokens, docked); + projection_preview(ui.painter(), Rect::from_min_size(pos2(100.0, 0.0), vec2(96.0, 96.0)), &spherical(1.0), BOUNDS, &tokens, popup); + }); + output.textures_delta.clear(); + shown.push([docked, popup].map(|owner| rendered(owner).texture.id())); + } + + let [docked_picture, popup_picture] = [rendered(docked), rendered(popup)]; + assert_ne!(docked_picture.texture.id(), popup_picture.texture.id(), "each square draws its own texture"); + assert!(docked_picture.key.starts_with("64") && popup_picture.key.starts_with("96"), "each picture is rendered at its own side"); + assert_eq!(shown[0], shown[1], "the next frame keeps both pictures"); + } + + /// Render times of the preview square (prints ms per render at its largest side; run with --ignored --nocapture) + #[test] + #[ignore] + fn preview_render_timings() { + let tokens = tokens(); + let kinds = [("sphere", spherical(2.0)), ("cylinder", cylindrical(Projector::default())), ("cube", Projection::triplanar())]; + for (name, projection) in kinds { + let start = std::time::Instant::now(); + const RUNS: u32 = 10; + for _ in 0..RUNS { + std::hint::black_box(render(&projection, MAX_SIDE_PX, VIEW_HALF, SUPERSAMPLE, &tokens)); + } + let full = start.elapsed().as_secs_f64() * 1000.0 / f64::from(RUNS); + let start = std::time::Instant::now(); + for _ in 0..RUNS { + std::hint::black_box(render(&projection, MAX_SIDE_PX, VIEW_HALF, DRAG_SUPERSAMPLE, &tokens)); + } + let dragged = start.elapsed().as_secs_f64() * 1000.0 / f64::from(RUNS); + println!("preview {name}: {full:.1} ms at rest, {dragged:.1} ms while dragged"); + } + } +} diff --git a/crates/ui-egui/src/projection_preview/preview_shape.rs b/crates/ui-egui/src/projection_preview/preview_shape.rs new file mode 100644 index 00000000..2865561b --- /dev/null +++ b/crates/ui-egui/src/projection_preview/preview_shape.rs @@ -0,0 +1,24 @@ +//! The shapes the projection preview wraps its checker around + +use texturecraft_engine::geom::glam::Vec3; + +use super::{CUBE_HALF, CYLINDER_HALF_HEIGHT, CYLINDER_RADIUS, SPHERE_RADIUS}; + +/// What the preview wraps the checker around +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum PreviewShape { + Sphere, + Cylinder, + Cube, +} + +impl PreviewShape { + /// Half the shape's size along X, Y and Z, in mesh radii + pub(super) fn half_size(self) -> Vec3 { + match self { + PreviewShape::Sphere => Vec3::splat(SPHERE_RADIUS), + PreviewShape::Cylinder => Vec3::new(CYLINDER_RADIUS, CYLINDER_HALF_HEIGHT, CYLINDER_RADIUS), + PreviewShape::Cube => Vec3::splat(CUBE_HALF), + } + } +} diff --git a/crates/ui-egui/src/projection_preview/rendered_preview.rs b/crates/ui-egui/src/projection_preview/rendered_preview.rs new file mode 100644 index 00000000..5e9bd7a0 --- /dev/null +++ b/crates/ui-egui/src/projection_preview/rendered_preview.rs @@ -0,0 +1,11 @@ +//! The projection preview's cached picture + +use egui::TextureHandle; + +/// The preview square's last picture: what it shows (`key`), how many rays per pixel along each axis it was cast with, and the texture holding it +#[derive(Clone)] +pub(super) struct RenderedPreview { + pub(super) key: String, + pub(super) supersample: usize, + pub(super) texture: TextureHandle, +} diff --git a/crates/ui-egui/src/projection_preview/screen.rs b/crates/ui-egui/src/projection_preview/screen.rs new file mode 100644 index 00000000..7935b2b4 --- /dev/null +++ b/crates/ui-egui/src/projection_preview/screen.rs @@ -0,0 +1,30 @@ +//! The preview camera laid on the square: where a point shows and whether the shape hides it + +use egui::{Pos2, Rect, vec2}; +use texturecraft_engine::geom::glam::Vec3; + +use super::{CAMERA_DISTANCE, PreviewShape, View, intersect}; + +/// The preview's view laid on the square `rect`, `half` mesh radii each way from its middle +pub(super) struct Screen { + pub(super) view: View, + pub(super) rect: Rect, + pub(super) half: f32, +} + +/// A hit this close in front of the point is the point's own surface +const OWN_SURFACE_DEPTH: f32 = 1e-3; + +impl Screen { + /// Where `point` shows on the square + pub(super) fn at(&self, point: Vec3) -> Pos2 { + let per_radius = self.rect.width() * 0.5 / self.half; + self.rect.center() + vec2(point.dot(self.view.right), -point.dot(self.view.up)) * per_radius + } + + /// Whether `shape` hides `point` from the camera + pub(super) fn hidden(&self, shape: PreviewShape, point: Vec3) -> bool { + let origin = point + self.view.eye * CAMERA_DISTANCE; + intersect(shape, origin, self.view.forward).is_some_and(|hit| (hit.pos - point).dot(self.view.eye) > OWN_SURFACE_DEPTH) + } +} diff --git a/crates/ui-egui/src/projection_preview/view.rs b/crates/ui-egui/src/projection_preview/view.rs new file mode 100644 index 00000000..7fe9a473 --- /dev/null +++ b/crates/ui-egui/src/projection_preview/view.rs @@ -0,0 +1,25 @@ +//! The projection preview's fixed camera + +use texturecraft_engine::geom::glam::Vec3; + +use super::{CAMERA_PITCH, CAMERA_YAW}; + +/// The preview camera's directions: towards the eye, the view direction, and the view's right and up +#[derive(Clone, Copy, Debug)] +pub(super) struct View { + pub(super) eye: Vec3, + pub(super) forward: Vec3, + pub(super) right: Vec3, + pub(super) up: Vec3, +} + +impl View { + /// The fixed preview camera, turned CAMERA_YAW round and CAMERA_PITCH down + pub(super) fn new() -> View { + let (yaw, pitch) = (CAMERA_YAW.to_radians(), CAMERA_PITCH.to_radians()); + let eye = Vec3::new(pitch.cos() * yaw.sin(), pitch.sin(), pitch.cos() * yaw.cos()); + let forward = -eye; + let right = forward.cross(Vec3::Y).normalize_or_zero(); + View { eye, forward, right, up: right.cross(forward) } + } +} diff --git a/crates/ui-egui/tests/it/fill_projection_rows.rs b/crates/ui-egui/tests/it/fill_projection_rows.rs new file mode 100644 index 00000000..8d0fbe71 --- /dev/null +++ b/crates/ui-egui/tests/it/fill_projection_rows.rs @@ -0,0 +1,242 @@ +//! A fill's Fill section shows the rows its projection has, and each new row changes the projection + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::core::{Fill, LayerId, Projection, ShapeCrop}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::fill_support::{click_label, fill_app, fill_of}; +use crate::filter_support::click_at; +use crate::{PROPERTIES_WINDOW, SETTLE_FRAMES}; + +/// The app with a new fill layer (projected as `projection`) selected in Properties, and its layer id +fn app_with_fill(projection: &str) -> (Harness<'static, TextureCraftApp>, u64) { + let (harness, LayerId(layer)) = fill_app(json!({}), Some(projection), None, PROPERTIES_WINDOW); + (harness, layer) +} + +/// The fill layer's projection as the document holds it +fn projection(harness: &Harness<'_, TextureCraftApp>, layer: u64) -> Projection { + fill(harness, layer).projection +} + +/// The fill layer as the document holds it +fn fill(harness: &Harness<'_, TextureCraftApp>, layer: u64) -> Fill { + fill_of(harness, LayerId(layer)) +} + +#[test] +fn each_projection_shows_its_own_rows() { + let shows = |harness: &Harness<'_, TextureCraftApp>, label: &str| harness.query_by_label(label).is_some(); + + let (harness, _) = app_with_fill("planar"); + for label in ["Depth culling", "Backface culling", "Angle", "Extends Outside Shape", "Offset X", "Rotation Y", "Scale Z"] { + assert!(shows(&harness, label), "planar: {label}"); + } + assert!(!shows(&harness, "Reset frame"), "planar has no frame to reset"); + + let (harness, _) = app_with_fill("warp"); + + // A warp's 3D projection settings are its frame's: where its centre is, its turn and its size + for label in ["Depth", "Reset frame", "Depth culling", "Offset X", "Rotation X", "Scale X"] { + assert!(shows(&harness, label), "warp: {label}"); + } + assert!(!shows(&harness, "Backface culling"), "a warp has no backface culling"); + + let (harness, _) = app_with_fill("cylindrical"); + for label in ["Angle", "Backface culling", "Extends Outside Shape", "Offset X"] { + assert!(shows(&harness, label), "cylindrical: {label}"); + } + assert!(!shows(&harness, "Depth culling")); + + let (harness, _) = app_with_fill("triplanar"); + assert!(shows(&harness, "Hardness") && !shows(&harness, "UV Wrap") && !shows(&harness, "Backface culling")); + + let (harness, _) = app_with_fill("uvTile"); + assert!(shows(&harness, "Fill (Match per UV Tile)")); + assert!(!shows(&harness, "Rotation") && !shows(&harness, "Filtering and edges"), "per UV tile there is nothing to place"); +} + +#[test] +fn culling_toggles_change_the_projection() { + let (mut harness, layer) = app_with_fill("planar"); + click_label(&mut harness, "Depth culling"); + click_label(&mut harness, "Backface culling"); + let Projection::Planar { projector, .. } = projection(&harness, layer) else { panic!("still planar") }; + assert!(!projector.depth.on, "a new planar starts depth culled; the toggle turns it off"); + assert!(projector.backface.on); +} + +/// What the Depth culling row's i says on hover +const DEPTH_CULLING_TIP: &str = "Paints only the surface the projector sees first; parts hidden behind it stay unpainted."; + +/// What the Backface culling row's i says on hover +const BACKFACE_CULLING_TIP: &str = "Leaves out faces turned away from the projector, so the fill doesn't run onto their back."; + +/// A point away from the Properties panel, where the pointer leaves no tooltip +const AWAY_FROM_PANEL: egui::Pos2 = egui::pos2(800.0, 500.0); + +/// Frames for the pointer to rest long enough for a tooltip +const TOOLTIP_FRAMES: usize = 60; + +/// Room the i's tooltip leaves at the panel's right edge for the values +const TIP_VALUE_ROOM: f32 = 70.0; + +#[test] +fn the_culling_rows_i_explains_the_row_on_hover_without_covering_its_values() { + let (mut harness, layer) = app_with_fill("planar"); + + // The i ends on the panel's right edge, where the values end + let panel_right = harness.get_by_label(DEPTH_CULLING_TIP).rect().right(); + for (tip, row) in [(DEPTH_CULLING_TIP, "Depth culling"), (BACKFACE_CULLING_TIP, "Backface culling")] { + let info = harness.get_by_label(tip).rect(); + let switch = harness.get_by_label(row).rect(); + assert!(info.left() >= switch.right() && (info.center().y - switch.center().y).abs() < 1.0, "{row}: the i sits at its row's end"); + assert_eq!(info.right(), panel_right, "{row}: on the panel's right edge"); + assert_eq!(harness.query_all_by_label(tip).count(), 1, "{row}: no tooltip before the hover"); + + harness.hover_at(info.center()); + harness.run_steps(TOOLTIP_FRAMES); + let shown = harness.query_all_by_label(tip).map(|node| node.rect()).find(|rect| *rect != info); + let Some(shown) = shown else { panic!("{row}: hovering the i shows its tooltip") }; + assert!(shown.top() >= info.bottom() - 2.0, "{row}: the tooltip hangs under the row"); + assert!(shown.right() <= panel_right - TIP_VALUE_ROOM, "{row}: the tooltip ends before the value column"); + + harness.hover_at(AWAY_FROM_PANEL); + harness.run_steps(SETTLE_FRAMES); + } + + // The i only explains: a click on it changes nothing + let before = projection(&harness, layer); + let info = harness.get_by_label(DEPTH_CULLING_TIP).rect().center(); + click_at(&mut harness, info); + assert_eq!(projection(&harness, layer), before); +} + +/// What a warp's Depth row says on its i +const WARP_DEPTH_TIP: &str = "How far the warp projection reaches into the mesh, in front of and behind its frame, in lengths of the frame's longer side. It bounds the fill only when cropped to its shape."; + +#[test] +fn shape_crop_sits_beside_its_label_and_a_warps_depth_explains_itself() { + let (harness, _) = app_with_fill("warp"); + + // Beside its label like Filtering, not under a stacked label at the panel's full width + let crop = harness.get_by_label("Extends Outside Shape").rect(); + let filtering = harness.get_by_label("Bilinear | HQ").rect(); + assert!((crop.left() - filtering.left()).abs() < 0.5, "Shape crop's list starts on the controls column: {crop:?} vs {filtering:?}"); + assert!((crop.width() - filtering.width()).abs() < 0.5, "and is as wide as Filtering's"); + + // Depth, not "Projection Depth": its i, on its row, tells it apart from Depth culling + let info = harness.get_by_label(WARP_DEPTH_TIP).rect(); + let depth = harness.get_by_label("Depth").rect(); + assert!((info.center().y - depth.center().y).abs() < 1.0 && info.right() <= depth.left() + 1.0, "the i sits left of Depth"); + assert!(harness.query_by_label("Projection Depth").is_none()); +} + +#[test] +fn shape_crop_is_picked_from_its_list() { + // Tri-planar's Shape crop sits highest in the panel, in view + let (mut harness, layer) = app_with_fill("triplanar"); + click_label(&mut harness, "Extends Outside Shape"); + click_label(&mut harness, "Cropped to Shape"); + let Projection::Triplanar { projector, .. } = projection(&harness, layer) else { panic!("still tri-planar") }; + assert_eq!(projector.crop, ShapeCrop::Cropped); +} + +#[test] +fn triplanar_hardness_runs_from_soft_to_the_hardest_blend() { + let (mut harness, layer) = app_with_fill("triplanar"); + let track = harness.get_by_label("Hardness").rect(); + click_at(&mut harness, egui::pos2(track.right() - 1.0, track.center().y)); + let Projection::Triplanar { sharpness, .. } = projection(&harness, layer) else { panic!("still tri-planar") }; + assert!(sharpness > 48.0, "Hardness 1 is the hardest blend, 64: {sharpness}"); + + click_at(&mut harness, egui::pos2(track.left() + 1.0, track.center().y)); + let Projection::Triplanar { sharpness, .. } = projection(&harness, layer) else { panic!("still tri-planar") }; + assert!(sharpness < 1.5, "Hardness 0 is the softest, 1: {sharpness}"); +} + +#[test] +fn reset_frame_puts_a_warps_corners_back() { + let (mut harness, layer) = app_with_fill("warp"); + let pulled = json!({"layer": layer, "warpCorners": [[-0.7, 0.6], [0.5, 0.5], [0.5, -0.5], [-0.5, -0.5]]}); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.fill.projection", &pulled).unwrap(); + harness.run_steps(SETTLE_FRAMES); + + click_label(&mut harness, "Reset frame"); + let Projection::Warp { corners, .. } = projection(&harness, layer) else { panic!("still a warp") }; + assert_eq!(corners, Projection::FRAME_CORNERS); +} + +#[test] +fn the_3d_projection_settings_fold_away() { + let (mut harness, _) = app_with_fill("spherical"); + assert!(harness.query_by_label("Scale X").is_some(), "the band starts open"); + click_label(&mut harness, "3D projection settings"); + assert!(harness.query_by_label("Scale X").is_none()); + assert!(harness.query_by_label("Spherical projection").is_some(), "the rows above it stay"); +} + +#[test] +fn the_fill_caption_resets_the_whole_fill_section_to_its_projections_defaults_in_one_undo_step() { + use texturecraft_engine::core::{Filtering, Sampling}; + let (mut harness, layer) = app_with_fill("planar"); + harness.state_mut().run("layer.fill.projection", json!({"layer": layer, "tiling": 3, "filtering": "nearest", "shapeCrop": "cropped", "symmetry": true})); + harness.run_steps(SETTLE_FRAMES); + let changed = fill(&harness, layer); + let reset = harness.get_by_label("Fill: Reset to defaults").rect().center(); + let edges = harness.get_by_label("Restore defaults").rect().center(); + + // The band's reset puts back only Filtering and edges, through a real pointer click + click_at(&mut harness, edges); + let after_band = fill(&harness, layer); + assert_eq!((after_band.sampling.filtering, crop(&after_band.projection)), (Filtering::default(), Some(ShapeCrop::default()))); + assert!(matches!(after_band.projection, Projection::Planar { .. }), "the projection stays planar"); + assert!(harness.get_by_label("Restore defaults").accesskit_node().is_disabled(), "at its defaults the band's reset is inert"); + + // The caption's reset puts back the whole section + click_at(&mut harness, reset); + let after = fill(&harness, layer); + assert!( + matches!(after.projection, Projection::Planar { scale, uv, placed: None, .. } if scale == 1.0 && uv == Default::default()), + "still planar, at a new planar's defaults: {:?}", + after.projection + ); + assert_eq!(after.sampling, Sampling { symmetry: changed.sampling.symmetry, ..Sampling::default() }, "the symmetry stays"); + assert!(harness.get_by_label("Fill: Reset to defaults").accesskit_node().is_disabled(), "at the defaults it is faint and inert"); + click_at(&mut harness, reset); + assert_eq!(fill(&harness, layer), after, "a click at the defaults changes nothing"); + + harness.state_mut().run("edit.undo", json!({})); + assert_eq!(fill(&harness, layer), after_band, "one undo step brings the whole section back"); +} + +/// A click from one typed number field to the next types into the one clicked: the field after it keeps its own value +#[test] +fn a_click_from_one_typed_field_to_the_next_types_into_the_one_clicked() { + let (mut harness, _) = app_with_fill("planar"); + let value = |harness: &Harness<'_, TextureCraftApp>, label: &str| harness.get_by_label(label).accesskit_node().numeric_value().unwrap(); + let untouched = value(&harness, "Offset Z"); + + click_label(&mut harness, "Offset X"); + harness.event(egui::Event::Text("0.1".into())); + harness.run_steps(SETTLE_FRAMES); + click_label(&mut harness, "Offset Y"); + harness.event(egui::Event::Text("0.2".into())); + harness.run_steps(SETTLE_FRAMES); + harness.key_press(egui::Key::Enter); + harness.run_steps(SETTLE_FRAMES); + + assert!((value(&harness, "Offset X") - 0.1).abs() < 1e-4, "the first field took its value"); + assert!((value(&harness, "Offset Y") - 0.2).abs() < 1e-4, "the clicked field took the typing"); + assert_eq!(value(&harness, "Offset Z"), untouched, "the field after it kept its value"); +} + +/// A projection's Shape crop, if it has a projector +fn crop(projection: &Projection) -> Option { + match projection { + Projection::Planar { projector, .. } | Projection::Triplanar { projector, .. } => Some(projector.crop), + _ => None, + } +} From c6ab3aa586517755794b6b6eaf6cb48728edf61d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:28:49 +0000 Subject: [PATCH 09/17] Popups: a press outside a popup closes it when it turns into a drag; Properties keeps a minimum width --- crates/ui-egui/src/decal_drop.rs | 4 +- crates/ui-egui/src/popup_drag.rs | 22 +++ crates/ui-egui/src/properties_popup.rs | 2 +- crates/ui-egui/src/symmetry/mod.rs | 12 +- crates/ui-egui/tests/it/popup_press_close.rs | 141 ++++++++++++++++++ .../ui-egui/tests/it/properties_min_width.rs | 108 ++++++++++++++ 6 files changed, 281 insertions(+), 8 deletions(-) create mode 100644 crates/ui-egui/src/popup_drag.rs create mode 100644 crates/ui-egui/tests/it/popup_press_close.rs create mode 100644 crates/ui-egui/tests/it/properties_min_width.rs diff --git a/crates/ui-egui/src/decal_drop.rs b/crates/ui-egui/src/decal_drop.rs index 2071ceb6..2d75dd83 100644 --- a/crates/ui-egui/src/decal_drop.rs +++ b/crates/ui-egui/src/decal_drop.rs @@ -71,7 +71,7 @@ impl DecalDrop { }); } - /// Show the waiting drop's menu over the 3D view `response`; a pick places the decal, a click elsewhere drops nothing + /// Show the waiting drop's menu over the 3D view `response`; a pick places the decal, a click or a drag elsewhere drops nothing pub fn show_menu(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) { let id = Self::menu_id(); let Some(drop) = Self::current(ui.ctx()) else { return }; @@ -110,7 +110,7 @@ impl DecalDrop { }); }); - if picked.is_some() || shown.is_none_or(|menu| menu.response.should_close()) { + if picked.is_some() || shown.is_none_or(|menu| menu.response.should_close()) || crate::popup_drag::drag_outside_popups(ui.ctx()) { Self::close(ui.ctx()); } diff --git a/crates/ui-egui/src/popup_drag.rs b/crates/ui-egui/src/popup_drag.rs new file mode 100644 index 00000000..b1bb14a2 --- /dev/null +++ b/crates/ui-egui/src/popup_drag.rs @@ -0,0 +1,22 @@ +//! A press outside the popups that turns into a drag closes them: egui closes a popup only on a click, so a paint stroke or slider drag left it open + +use egui::{Order, PointerButton}; + +/// Whether a primary press outside every popup has just been held or moved past a click: it starts a stroke, a slider drag or a panel move +pub(crate) fn drag_outside_popups(ctx: &egui::Context) -> bool { + let (dragging, origin, orbiting) = ctx.input(|input| { + let dragging = input.pointer.button_down(PointerButton::Primary) && input.pointer.is_decidedly_dragging(); + (dragging, input.pointer.press_origin(), input.modifiers.alt) + }); + + // Alt+drag orbits the camera, which keeps popups open like the colour picker; a drag in a popup or a dropdown it opened stays in it + let over_popup = |at| ctx.layer_id_at(at).is_some_and(|layer| matches!(layer.order, Order::Foreground | Order::Tooltip | Order::Debug)); + dragging && !orbiting && origin.is_some_and(|at| !over_popup(at)) +} + +/// Closes egui's open popup, menu or dropdown when [`drag_outside_popups`]; a plain click outside is egui's own close +pub(crate) fn close_on_drag_outside(ctx: &egui::Context) { + if egui::Popup::is_any_open(ctx) && drag_outside_popups(ctx) { + egui::Popup::close_all(ctx); + } +} diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs index 5c174cdd..305c8bb6 100644 --- a/crates/ui-egui/src/properties_popup.rs +++ b/crates/ui-egui/src/properties_popup.rs @@ -67,7 +67,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let Some(PropertiesPopup::Open { at, bounds }) = app.properties_popup else { return }; let tokens = Tokens::get(ctx); egui::Area::new(area_id()).order(egui::Order::Foreground).fixed_pos(at).constrain_to(bounds.shrink(PROPERTIES_POPUP_VIEW_MARGIN)).show(ctx, |ui| { - egui::Frame::popup(ui.style()).fill(tokens.panel).show(ui, |ui| { + egui::Frame::popup(ui.style()).fill(tokens.panel).inner_margin(egui::Margin::ZERO).show(ui, |ui| { ui.set_width(PROPERTIES_POPUP_WIDTH); // The area's remembered size would otherwise cap the scroll height ui.set_max_height(bounds.height() * PROPERTIES_POPUP_MAX_HEIGHT_SHARE); diff --git a/crates/ui-egui/src/symmetry/mod.rs b/crates/ui-egui/src/symmetry/mod.rs index 363ddd37..94eec7d8 100644 --- a/crates/ui-egui/src/symmetry/mod.rs +++ b/crates/ui-egui/src/symmetry/mod.rs @@ -102,14 +102,16 @@ pub(crate) fn toolbar_controls(app: &mut TextureCraftApp, ui: &mut Ui) { .close_behavior(egui::PopupCloseBehavior::IgnoreClicks) .show(|ui| settings_popup::show(app, ui)); - // A click outside the popup and the dropdowns it opens (foreground layers too) closes it + // A click outside the popup and the dropdowns it opens (foreground layers too) closes it, and so does a drag that starts outside them if let Some(shown) = shown && !response.clicked() - && ui.input(|input| input.pointer.any_click()) - && let Some(at) = ui.input(|input| input.pointer.interact_pos()) - && ui.ctx().layer_id_at(at).is_none_or(|layer| layer != shown.response.layer_id && layer.order != egui::Order::Foreground) { - open = false; + let clicked_at = ui.input(|input| input.pointer.interact_pos().filter(|_| input.pointer.any_click())); + let click_outside = clicked_at + .is_some_and(|at| ui.ctx().layer_id_at(at).is_none_or(|layer| layer != shown.response.layer_id && layer.order != egui::Order::Foreground)); + if click_outside || crate::popup_drag::drag_outside_popups(ui.ctx()) { + open = false; + } } ui.data_mut(|data| data.insert_temp(popup_id, open)); diff --git a/crates/ui-egui/tests/it/popup_press_close.rs b/crates/ui-egui/tests/it/popup_press_close.rs new file mode 100644 index 00000000..31e2d868 --- /dev/null +++ b/crates/ui-egui/tests/it/popup_press_close.rs @@ -0,0 +1,141 @@ +//! A press outside a popup closes it when it turns into a drag (a paint stroke on the model), as a click does: the tool's colour, the layer menus and the symmetry settings, in the default layout and in a rearranged one restored after a restart + +use eframe::App as _; +use egui::{Event, Modifiers, PointerButton, Pos2, Vec2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Dock; + +use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, PROPERTIES_WINDOW, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +use crate::memory_storage::MemoryStorage; + +/// Moves of a drag on the model, each a few points, so it is a drag well before its release +const DRAG_MOVES: usize = 6; + +/// A short stroke on the model +const STROKE: Vec2 = vec2(-60.0, 40.0); + +/// From the tool's Base color label to inside its swatch +const LABEL_TO_SWATCH: f32 = 60.0; + +/// The app started on `storage` (its saved arrangement, if any) with the paint tool's Properties showing +fn app(storage: &MemoryStorage) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + + // The view has no accessible name of its own; these tests drive it by position + let builder = Harness::builder().with_size(PROPERTIES_WINDOW).with_accessibility_check(false); + let mut harness = builder.build_eframe(|context| { + let mut creation = eframe::CreationContext::_new_kittest(context.egui_ctx.clone()); + creation.storage = Some(storage); + TextureCraftApp::new(&creation, session) + }); + + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + harness +} + +/// Properties swapped with Assets (now left of the view), saved and the app started again from that save +fn restarted_rearranged() -> Harness<'static, TextureCraftApp> { + let mut storage = MemoryStorage::default(); + let mut first = app(&storage); + let saved = serde_json::to_string(&first.state().ui.dock).unwrap(); + let swapped = saved.replace("\"Assets\"", "\"Swap\"").replace("\"Properties\"", "\"Assets\"").replace("\"Swap\"", "\"Properties\""); + first.state_mut().ui.dock = Dock::from_value(serde_json::from_str(&swapped).unwrap()); + first.run_steps(STARTUP_FRAMES); + first.state_mut().save(&mut storage); + + let restarted = app(&storage); + assert_eq!(restarted.state().ui.dock, first.state().ui.dock, "the rearranged layout comes back"); + restarted +} + +fn press(harness: &mut Harness<'_, TextureCraftApp>, at: Pos2, pressed: bool, modifiers: Modifiers) { + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers }); + harness.run_steps(DRAG_STEP_FRAMES); +} + +/// A primary press at `from` dragged by `by` in small moves, then released +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, by: Vec2, modifiers: Modifiers) { + harness.event(Event::ModifiersChanged(modifiers)); + harness.hover_at(from); + harness.run_steps(1); + press(harness, from, true, modifiers); + for step in 1..=DRAG_MOVES { + harness.hover_at(from + by * (step as f32 / DRAG_MOVES as f32)); + harness.run_steps(1); + } + press(harness, from + by, false, modifiers); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(SETTLE_FRAMES); +} + +/// A plain press and release at `at` +fn click(harness: &mut Harness<'_, TextureCraftApp>, at: Pos2) { + harness.hover_at(at); + harness.run_steps(1); + press(harness, at, true, Modifiers::NONE); + press(harness, at, false, Modifiers::NONE); + harness.run_steps(SETTLE_FRAMES); +} + +/// A stroke on the model, clear of the panels and the popups that open beside them +fn stroke_on_model(harness: &mut Harness<'_, TextureCraftApp>, modifiers: Modifiers) { + let view = harness.state().viewport_rect; + drag(harness, view.center(), STROKE, modifiers); +} + +/// Opens the paint tool's Base color swatch from its Properties' Material tab +fn open_tool_color(harness: &mut Harness<'_, TextureCraftApp>) { + let header = harness.get_by_label("Properties - Paint").rect(); + let in_properties = |rect: egui::Rect| header.x_range().contains(rect.center().x) && rect.top() > header.top(); + let material = harness.get_all_by_label("Material").find(|node| in_properties(node.rect())).unwrap(); + material.click(); + harness.run_steps(SETTLE_FRAMES); + + let label = harness.get_all_by_value("Base color").find(|node| in_properties(node.rect())).unwrap().rect(); + click(harness, label.right_center() + vec2(LABEL_TO_SWATCH, 0.0)); + assert!(egui::Popup::is_any_open(&harness.ctx), "the swatch opens its colour popup"); +} + +#[test] +fn a_stroke_on_the_model_closes_the_tool_colour_popup_in_the_default_and_a_restored_rearranged_layout() { + for (mut harness, layout) in [(app(&MemoryStorage::default()), "default"), (restarted_rearranged(), "restored rearranged")] { + open_tool_color(&mut harness); + let history = harness.state().session.history_labels().len(); + + stroke_on_model(&mut harness, Modifiers::NONE); + + assert!(!egui::Popup::is_any_open(&harness.ctx), "{layout}: the stroke closes the popup"); + assert!(harness.state().session.history_labels().len() > history, "{layout}: the stroke still paints"); + } +} + +#[test] +fn an_alt_orbit_keeps_the_tool_colour_popup_open() { + let mut harness = app(&MemoryStorage::default()); + open_tool_color(&mut harness); + + stroke_on_model(&mut harness, Modifiers::ALT); + + assert!(egui::Popup::is_any_open(&harness.ctx), "an Alt+drag orbits the camera and keeps the popup, like the colour picker"); +} + +#[test] +fn a_stroke_on_the_model_closes_the_symmetry_settings() { + let mut harness = app(&MemoryStorage::default()); + + // The paint controls overflow the bar at this width; its arrow brings the Symmetry buttons into view + harness.get_by_label("Scroll right").click(); + harness.run_steps(SETTLE_FRAMES); + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_label("Radial symmetry").is_some(), "the settings open"); + + stroke_on_model(&mut harness, Modifiers::NONE); + + assert!(harness.query_by_label("Radial symmetry").is_none(), "the stroke closes the settings"); +} diff --git a/crates/ui-egui/tests/it/properties_min_width.rs b/crates/ui-egui/tests/it/properties_min_width.rs new file mode 100644 index 00000000..79c39f5d --- /dev/null +++ b/crates/ui-egui/tests/it/properties_min_width.rs @@ -0,0 +1,108 @@ +//! The Properties panel never gets narrower than its rows need: the column it docks in stops shrinking there + +use craft_ui::docking::Node; +use craft_ui::layout::SplitSize; +use egui::{Event, Modifiers, PointerButton, Pos2, Role, pos2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::{Dock, PROPERTIES_MIN_WIDTH}; + +use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, panel_close_button}; + +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// A right column comfortably wider than the minimum, where a drag starts +const WIDE_COLUMN: f32 = 420.0; + +/// Half the gutter between the views and the right column, where its divider is grabbed +const DIVIDER_OFFSET: f32 = 3.0; + +/// How far under the Properties header the divider is grabbed: beside the panel's rows, clear of the header bar +const DIVIDER_GRAB_BELOW_HEADER: f32 = 100.0; + +/// How far right of the window's edge a drag aims, past any width the column could stop at +const WINDOW_RIGHT_INSET: f32 = 4.0; + +fn app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // The header names below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + harness +} + +/// Gives the right column (Layers over Properties) `width` points, as a layout saved at that width would +fn set_column_width(harness: &mut Harness<'_, TextureCraftApp>, width: f32) { + let mut workspace = harness.state().ui.dock.workspace().clone(); + let Some(Node::Split { second, .. }) = workspace.layout.root.as_mut() else { panic!("the assets column and the rest") }; + let Node::Split { size, .. } = second.as_mut() else { panic!("the 3D view and the right column") }; + *size = SplitSize::FixedSecond(width); + harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); + harness.run_steps(SETTLE_FRAMES); +} + +/// The Properties header's title, which starts at the column's left edge +fn properties_title(harness: &Harness<'_, TextureCraftApp>) -> egui::Rect { + harness + .get_all_by_role(Role::Tab) + .find(|tab| tab.accesskit_node().label().is_some_and(|label| label.starts_with("Properties - "))) + .map(|tab| tab.rect()) + .expect("the Properties header") +} + +/// Width of the Properties header bar, from its title's left edge to its close button's right edge +fn properties_header_width(harness: &Harness<'_, TextureCraftApp>) -> f32 { + let title = properties_title(harness); + panel_close_button(harness, title).max.x - title.min.x +} + +/// Moves of a divider drag, so the dock follows the pointer as it does by hand +const DRAG_MOVES: usize = 4; + +/// Drags with the primary button from `from` to `to` in [`DRAG_MOVES`] moves +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(DRAG_STEP_FRAMES); + + for step in 1..=DRAG_MOVES { + harness.hover_at(from + (to - from) * (step as f32 / DRAG_MOVES as f32)); + harness.run_steps(1); + } + + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn dragging_the_right_column_narrow_stops_at_the_properties_minimum_width() { + let mut harness = app(); + set_column_width(&mut harness, PROPERTIES_MIN_WIDTH); + let at_minimum = properties_header_width(&harness); + + set_column_width(&mut harness, WIDE_COLUMN); + let before = properties_title(&harness).min.x; + assert!(properties_header_width(&harness) > at_minimum, "a wide column gives Properties more than its minimum"); + + let y = properties_title(&harness).max.y + DIVIDER_GRAB_BELOW_HEADER; + drag(&mut harness, pos2(before - DIVIDER_OFFSET, y), pos2(WINDOW_SIZE.x - WINDOW_RIGHT_INSET, y)); + + assert!(properties_title(&harness).min.x > before, "the divider moved right"); + let width = properties_header_width(&harness); + assert!((width - at_minimum).abs() < 0.5, "Properties stopped at its minimum: header {width}, {at_minimum} at the minimum"); +} + +#[test] +fn a_layout_saved_narrower_draws_properties_at_its_minimum_width() { + let mut harness = app(); + set_column_width(&mut harness, PROPERTIES_MIN_WIDTH); + let at_minimum = properties_header_width(&harness); + + set_column_width(&mut harness, PROPERTIES_MIN_WIDTH * 0.5); + let width = properties_header_width(&harness); + assert!((width - at_minimum).abs() < 0.5, "a narrow saved column opens at the minimum: header {width}, {at_minimum} at the minimum"); +} From ed481a4a0109ffd99c87fd374a830b6c13266014 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:11 +0000 Subject: [PATCH 10/17] Fills: projection gizmos in the 3D view with a handle for every transform --- crates/ui-egui/src/frame_gizmo.rs | 988 ++++++++++++++++++ crates/ui-egui/src/frame_gizmo/frame_grab.rs | 29 + crates/ui-egui/src/projection_gizmo.rs | 77 ++ crates/ui-egui/src/projection_gizmo/gizmo.rs | 25 + .../src/projection_gizmo/gizmo_drag.rs | 14 + .../src/projection_gizmo/shown_gizmo.rs | 73 ++ crates/ui-egui/src/projector_outline.rs | 159 +++ crates/ui-egui/src/projector_outline/place.rs | 27 + crates/ui-egui/src/round_gizmo.rs | 885 ++++++++++++++++ crates/ui-egui/src/round_gizmo/round_grab.rs | 12 + crates/ui-egui/src/round_gizmo/shape.rs | 8 + crates/ui-egui/src/round_gizmo/size_handle.rs | 33 + 12 files changed, 2330 insertions(+) create mode 100644 crates/ui-egui/src/frame_gizmo.rs create mode 100644 crates/ui-egui/src/frame_gizmo/frame_grab.rs create mode 100644 crates/ui-egui/src/projection_gizmo.rs create mode 100644 crates/ui-egui/src/projection_gizmo/gizmo.rs create mode 100644 crates/ui-egui/src/projection_gizmo/gizmo_drag.rs create mode 100644 crates/ui-egui/src/projection_gizmo/shown_gizmo.rs create mode 100644 crates/ui-egui/src/projector_outline.rs create mode 100644 crates/ui-egui/src/projector_outline/place.rs create mode 100644 crates/ui-egui/src/round_gizmo.rs create mode 100644 crates/ui-egui/src/round_gizmo/round_grab.rs create mode 100644 crates/ui-egui/src/round_gizmo/shape.rs create mode 100644 crates/ui-egui/src/round_gizmo/size_handle.rs diff --git a/crates/ui-egui/src/frame_gizmo.rs b/crates/ui-egui/src/frame_gizmo.rs new file mode 100644 index 00000000..6b27767b --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo.rs @@ -0,0 +1,988 @@ +//! The frame of the selected planar or warp projection in the 3D view: the centre square slides it, the axis arrows move it along its across, up and out directions, the ring turns it round its normal, a planar's corners scale it, the edge dots stretch one side, a warp's corners pull freely + +use egui::{Color32, Pos2, Rect, Stroke, Ui, vec2}; +use serde_json::{Value, json}; +use texturecraft_engine::compose::axis_frame::{placed_from_axis, placing_moves_pattern}; +use texturecraft_engine::compose::frame_placement::folded; +use texturecraft_engine::compose::pattern::{decal_axes, decal_corners}; +use texturecraft_engine::core::{Decal, EffectKind, Fill, LayerId, LayerKind, Projection}; +use texturecraft_engine::geom::glam::Vec3; + +use crate::TextureCraftApp; +use crate::projection_gizmo::{Gizmo, dragging}; +use crate::theme::{AXIS_COLORS, SHAFT_HALO, SHAFT_HALO_EXTRA_WIDTH, SHAFT_WIDTH, Tokens}; +use crate::viewport::{project, view_ray}; + +mod frame_grab; + +pub(crate) use frame_grab::FrameGrab; + +/// The selected fill's frame as the 3D view shows it +#[derive(Clone, Copy, Debug)] +pub(crate) struct FrameGizmo { + pub layer: LayerId, + /// The selected mask fill effect projecting from the frame, when it is in a mask + pub effect: Option, + /// The frame; an axis planar shows the frame it is placed as on its first drag + pub decal: Decal, + /// A warp's corners, across and up in frame sizes from its centre + pub warp: Option<[[f32; 2]; 4]>, + /// On screen: the corners (a warp's pulled ones), the edge dots and the centre + pub corners: [Pos2; 4], + pub sides: [Pos2; 4], + pub center: Pos2, + /// On screen, the tips of the across, up and out arrows (None when one points at the camera) + pub arrows: [Option; 3], + /// On screen, the turn ring round the centre in the frame's plane (None when it is edge on) + pub ring: Option<[Pos2; TURN_RING_POINTS]>, + /// In the world: the frame's centre, and its across, up and out directions + origin: Vec3, + axes: [Vec3; 3], + /// Screen movement per world unit along each direction at the centre + steps: [Option; 3], +} + +/// Screen length of the axis arrows, and their heads (points): long enough to grab each one apart from the others +pub(crate) const ARROW: f32 = 56.0; +const ARROW_HEAD: f32 = 14.0; +/// The centre square's side, the corner and edge dot radii, a warp corner's radius (points) +pub(crate) const CENTER_SQUARE: f32 = 16.0; +const CORNER_DOT: f32 = 6.5; +const SIDE_DOT: f32 = 5.5; +const WARP_DOT: f32 = 8.0; +/// How near a handle or arrow a press grabs it (points) +pub(crate) const GRAB: f32 = 11.0; +/// Screen radius of the turn rings (frames and round projectors alike): past the arrow heads, so a ring is grabbed apart from the arrows +pub(crate) const TURN_RING: f32 = 84.0; +/// Points on a frame's turn ring, the first repeated at the end to close it +pub(crate) const TURN_RING_POINTS: usize = 49; +/// The smallest share of its size a dragged side keeps +const MIN_SIDE_STRETCH: f32 = 0.02; +/// The least distance from the centre a resize drag measures from, so a press on the centre never divides by zero (points) +pub(crate) const MIN_HANDLE_REACH: f32 = 1.0; + +impl FrameGizmo { + /// The frame as the 3D view shows it: none while the Projection row's eye hides the projection gizmos + pub(crate) fn shown(app: &TextureCraftApp, rect: Rect) -> Option { + FrameGizmo::of(app, rect).filter(|_| app.session.doc.project.display.projection_gizmos) + } + + /// The frame of the selected fill layer, or of the selected mask fill effect, with a planar or warp projection + pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option { + use texturecraft_engine::StackTarget; + + if app.ui.mode != crate::state::Mode::Painting { + return None; + } + + let layers = &app.session.doc.project; + let selected = app.session.selected_layer()?; + let (layer, effect, projection, sources) = match app.session.target { + StackTarget::Content => { + let layer = layers.content_layer(selected)?; + let LayerKind::Fill(Fill { projection, sources, .. }) = &layer.kind else { return None }; + + (layer.id, None, projection, sources.values().collect::>()) + } + StackTarget::Effect(effect) => { + // Only the selected layer's effective mask may supply a frame, including an instance's inherited mask + let owner = layers.mask_owner(selected); + let mask = layers.layer(owner).ok()?.mask.as_ref()?; + let mask_effect = mask.effects.iter().find(|candidate| candidate.id == effect)?; + let EffectKind::Fill { projection, source, .. } = &mask_effect.kind else { return None }; + + (owner, Some(effect), projection, vec![source]) + } + StackTarget::Mask => return None, + }; + + // An axis planar reading a pattern keeps its axis (see [`placing_moves_pattern`]): it has no frame to move + let unplaced = matches!(projection, Projection::Planar { placed: None, .. }); + if unplaced && placing_moves_pattern(sources.into_iter()) { + return None; + } + let placed = placed_from_axis(projection, app.session.mesh.bounds()); + + // Where the projection lands: a projector's own turn and scale moved into the frame, as the panel's 3D projection settings show it + let landed = folded(placed.as_ref().unwrap_or(projection))?; + let decal = *landed.frame()?; + let warp = match projection { + Projection::Warp { corners, .. } => Some(*corners), + _ => None, + }; + let (origin, across, up, out) = decal_axes(&decal)?; + + // The corners on screen: a warp's pulled ones, or the frame's own + let at = |[x, y]: [f32; 2]| project(app, rect, origin + across * x * decal.size[0] + up * y * decal.size[1]); + let corners = match warp { + Some([top_left, top_right, bottom_right, bottom_left]) => [at(top_left)?, at(top_right)?, at(bottom_right)?, at(bottom_left)?], + None => { + let [top_left, top_right, bottom_right, bottom_left] = decal_corners(&decal)?.map(|corner| project(app, rect, corner)); + [top_left?, top_right?, bottom_right?, bottom_left?] + } + }; + + let sides = [0, 1, 2, 3].map(|side| corners[side].lerp(corners[(side + 1) % 4], 0.5)); + let center = project(app, rect, origin)?; + + // Screen movement per world unit along each direction, and an arrow along each one not pointing at the camera + let reach = decal.size[0].max(decal.size[1]); + let axes = [across, up, out]; + let steps = axes.map(|axis| Some((project(app, rect, origin + axis * reach)? - center) / reach.max(f32::MIN_POSITIVE))); + let arrows = steps.map(|step| step.filter(|step| step.length() * reach > MIN_SCREEN_SPAN).map(|step| center + step.normalized() * ARROW)); + + // The turn ring, unless the frame is seen too near edge on to grab it + let ring = steps[0] + .zip(steps[1]) + .filter(|(across_step, up_step)| { + across_step.length() > f32::EPSILON && solve(*across_step, *up_step, egui::Vec2::X).is_some() && ring_open(app, rect, center, out) + }) + .and_then(|(step, _)| { + let radius = TURN_RING / step.length(); + let last = (TURN_RING_POINTS - 1) as f32; + let points = (0..TURN_RING_POINTS).map(|index| { + let (sin, cos) = (index as f32 / last * std::f32::consts::TAU).sin_cos(); + project(app, rect, origin + (across * cos + up * sin) * radius) + }); + points.collect::>>()?.try_into().ok() + }); + + Some(FrameGizmo { layer, effect, decal, warp, corners, sides, center, arrows, ring, origin, axes, steps }) + } + + /// The frame's offset after sliding it across its plane by screen movement `delta` (None when the frame is edge-on) + pub(crate) fn slid_on_screen(&self, delta: egui::Vec2) -> Option<[f32; 2]> { + let [across, up] = solve(self.steps[0]?, self.steps[1]?, delta)?; + Some(self.slid(across, up)) + } + + /// Where screen point `p` meets the frame's plane, across and up in frame sizes from its centre + fn on_plane(&self, app: &TextureCraftApp, rect: Rect, p: Pos2) -> Option<[f32; 2]> { + let ray = view_ray(app, rect, p); + let [across, up, out] = self.axes; + let facing = ray.dir.dot(out); + if facing.abs() < EDGE_ON_FACING { + return None; + } + + let hit = ray.origin + ray.dir * ((self.origin - ray.origin).dot(out) / facing); + let local = [(hit - self.origin).dot(across) / self.decal.size[0], (hit - self.origin).dot(up) / self.decal.size[1]]; + local.iter().all(|value| value.is_finite()).then_some(local) + } + + /// The frame's offset after moving `across` and `up` world units along its turned directions, unturned as `layer.decal.set` stores it + fn slid(&self, across: f32, up: f32) -> [f32; 2] { + let (sin, cos) = self.decal.rotation.to_radians().sin_cos(); + [self.decal.offset[0] + across * cos - up * sin, self.decal.offset[1] + across * sin + up * cos] + } +} + +/// Half a turn in degrees: a ring drag's sweep is kept within one either way +const HALF_TURN: f32 = 180.0; + +/// The smallest determinant of two screen steps (points² per world unit²) that still tells them apart: below it they run parallel on screen +const PARALLEL_DETERMINANT: f32 = 1e-6; + +/// The smallest cosine between a view ray and a plane's normal for the ray to meet the plane: nearer edge on, the hit runs off far away +pub(crate) const EDGE_ON_FACING: f32 = 1e-4; + +/// The smallest length a direction spans on screen to point somewhere (points): shorter, it points at the camera +pub(crate) const MIN_SCREEN_SPAN: f32 = 1.0; + +/// The smallest cosine between the view ray and a turn ring's axis for the ring to show: flatter, its half height on screen is under its drawn line's width, it reads as a line and a drag along it turns half a turn at once across the centre +const MIN_RING_FACING: f32 = (SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH) / TURN_RING; + +/// Whether a turn ring round `axis`, centred on screen at `center`, is seen open enough to show and grab +pub(crate) fn ring_open(app: &TextureCraftApp, rect: Rect, center: Pos2, axis: Vec3) -> bool { + view_ray(app, rect, center).dir.dot(axis).abs() >= MIN_RING_FACING +} + +/// `delta` as a mix of screen steps `across_step` and `up_step` (None when they are parallel on screen) +fn solve(across_step: egui::Vec2, up_step: egui::Vec2, delta: egui::Vec2) -> Option<[f32; 2]> { + let determinant = across_step.x * up_step.y - across_step.y * up_step.x; + if determinant.abs() < PARALLEL_DETERMINANT { + return None; + } + + Some([(delta.x * up_step.y - delta.y * up_step.x) / determinant, (across_step.x * delta.y - across_step.y * delta.x) / determinant]) +} + +/// How far `p` is from the centre square (0 inside it) +pub(crate) fn center_distance(center: Pos2, p: Pos2) -> f32 { + Rect::from_center_size(center, egui::Vec2::splat(CENTER_SQUARE)).distance_to_pos(p) +} + +/// How far `p` is from the arrow from `center` to `tip`, its head included +pub(crate) fn arrow_distance(p: Pos2, center: Pos2, tip: Pos2) -> f32 { + distance_to_segment(p, center, tip + (tip - center).normalized() * ARROW_HEAD) +} + +/// The handle nearest its distance, if one is within `GRAB` (the first listed wins a tie) +pub(crate) fn nearest(handles: impl IntoIterator) -> Option { + let mut best: Option<(T, f32)> = None; + for (handle, distance) in handles { + if distance <= GRAB && best.is_none_or(|(_, nearest)| distance < nearest) { + best = Some((handle, distance)); + } + } + best.map(|(handle, _)| handle) +} + +pub(crate) fn distance_to_segment(p: Pos2, a: Pos2, b: Pos2) -> f32 { + let ab = b - a; + let t = ((p - a).dot(ab) / ab.length_sq().max(f32::MIN_POSITIVE)).clamp(0.0, 1.0); + p.distance(a + ab * t) +} + +impl Gizmo for FrameGizmo { + type Grab = FrameGrab; + + fn drag_id() -> egui::Id { + egui::Id::unique("tc_frame_drag") + } + + /// The handle under screen point `p`: the nearest one within reach, so a small frame's corners stay grabbable beside its arrows + fn grab(&self, at: Pos2) -> Option { + let mut handles = vec![(FrameGrab::Slide, center_distance(self.center, at))]; + handles.extend((0..3).filter_map(|axis| Some((FrameGrab::Axis(axis), arrow_distance(at, self.center, self.arrows[axis]?))))); + let near = |points: [Pos2; 4], grab: fn(usize) -> FrameGrab| (0..4).map(move |index| (grab(index), points[index].distance(at))); + match self.warp { + // A mask effect's warp corners have no command to pull them + Some(_) if self.effect.is_none() => handles.extend(near(self.corners, FrameGrab::Corner)), + Some(_) => {} + None => handles.extend(near(self.corners, |_| FrameGrab::Scale)), + } + handles.extend(near(self.sides, FrameGrab::Side)); + if let Some(ring) = &self.ring { + handles.push((FrameGrab::Turn, ring.windows(2).map(|pair| distance_to_segment(at, pair[0], pair[1])).fold(f32::INFINITY, f32::min))); + } + nearest(handles) + } + + fn same_projection(&self, other: &FrameGizmo) -> bool { + self.layer == other.layer && self.effect == other.effect + } + + /// The command and params a drag of `grab` from `from` to `to` runs + fn edit(&self, app: &TextureCraftApp, rect: Rect, grab: FrameGrab, from: Pos2, to: Pos2) -> Option<(&'static str, Value)> { + let delta = to - from; + let center = self.center; + let mut params = match grab { + FrameGrab::Slide => json!({"offset": self.slid_on_screen(delta)?}), + FrameGrab::Axis(axis) => { + let step = (*self.steps.get(axis)?)?; + let distance = delta.dot(step) / step.length_sq().max(f32::MIN_POSITIVE); + match axis { + 0 => json!({"offset": self.slid(distance, 0.0)}), + 1 => json!({"offset": self.slid(0.0, distance)}), + _ => json!({"position": (self.origin + self.axes[2] * distance).to_array(), "normal": self.axes[2].to_array()}), + } + } + FrameGrab::Scale => { + let scale = (to - center).length() / (from - center).length().max(MIN_HANDLE_REACH); + json!({"size": [self.decal.size[0] * scale, self.decal.size[1] * scale]}) + } + FrameGrab::Side(side) => { + let direction = (*self.sides.get(side)? - center).normalized(); + let stretch = ((to - center).dot(direction) / (from - center).dot(direction).max(MIN_HANDLE_REACH)).max(MIN_SIDE_STRETCH); + let mut size = self.decal.size; + size[1 - side % 2] *= stretch; + json!({"size": size}) + } + FrameGrab::Turn => { + // The sweep round the centre on the frame's own plane (across turning towards up is a positive turn), so a tilted or off-centre frame follows the pointer too + let angle = |p: Pos2| self.on_plane(app, rect, p).map(|[across, up]| (up * self.decal.size[1]).atan2(across * self.decal.size[0]).to_degrees()); + let swept = angle(to)? - angle(from)?; + let swept = (swept + HALF_TURN).rem_euclid(2.0 * HALF_TURN) - HALF_TURN; + json!({"rotation": self.decal.rotation + swept}) + } + FrameGrab::Corner(corner) => { + let mut corners = self.warp?; + *corners.get_mut(corner)? = self.on_plane(app, rect, to)?; + return Some(("layer.fill.projection", json!({"layer": self.layer.0, "warpCorners": corners}))); + } + }; + params["layer"] = json!(self.layer.0); + if let Some(effect) = self.effect { + params["effect"] = json!(effect.0); + } + Some(("layer.decal.set", params)) + } + + fn cursor(&self, grab: FrameGrab, dragging: bool) -> egui::CursorIcon { + grab.cursor(dragging) + } +} + +/// The selected frame over the 3D view: dashed outline, corner and edge dots, and the centre square with its axis arrows +pub(crate) fn overlay(ui: &Ui, rect: Rect, gizmo: &FrameGizmo) { + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter_at(rect); + let active = dragging::(ui.ctx()).map(|drag| drag.grab); + let hovered = ui.ctx().pointer_hover_pos().filter(|hover| rect.contains(*hover)).and_then(|hover| gizmo.grab(hover)); + let lit = |grab: FrameGrab| active == Some(grab) || (active.is_none() && hovered == Some(grab)); + let dot_fill = |grab: FrameGrab| if lit(grab) { tokens.viewport_accent } else { Color32::WHITE }; + + let mut outline = gizmo.corners.to_vec(); + outline.push(gizmo.corners[0]); + dashed_outline(&painter, &outline); + if let Some(ring) = &gizmo.ring { + let color = if lit(FrameGrab::Turn) { tokens.viewport_accent } else { AXIS_COLORS[2] }; + painter.add(egui::Shape::line(ring.to_vec(), Stroke::new(SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH, SHAFT_HALO))); + painter.add(egui::Shape::line(ring.to_vec(), Stroke::new(SHAFT_WIDTH, color))); + } + match gizmo.warp { + Some(_) => { + for (index, corner) in gizmo.corners.into_iter().enumerate() { + handle_dot(&painter, corner, WARP_DOT, dot_fill(FrameGrab::Corner(index))); + } + } + None => { + for corner in gizmo.corners { + handle_dot(&painter, corner, CORNER_DOT, dot_fill(FrameGrab::Scale)); + } + } + } + for (index, side) in gizmo.sides.into_iter().enumerate() { + handle_dot(&painter, side, SIDE_DOT, dot_fill(FrameGrab::Side(index))); + } + + let arrow_color = |axis: usize| if lit(FrameGrab::Axis(axis)) { tokens.viewport_accent } else { AXIS_COLORS[axis] }; + move_handles(&painter, gizmo.center, gizmo.arrows, arrow_color, dot_fill(FrameGrab::Slide)); +} + +/// The centre square (filled `square`) with its X/Y/Z arrows to `arrows`, coloured by `arrow_color`; shafts and heads over a dark halo like the symmetry manipulator's +pub(crate) fn move_handles(painter: &egui::Painter, center: Pos2, arrows: [Option; 3], arrow_color: impl Fn(usize) -> Color32, square: Color32) { + for (axis, tip) in arrows.into_iter().enumerate() { + let Some(tip) = tip else { continue }; + + let color = arrow_color(axis); + let direction = (tip - center).normalized(); + let side = direction.rot90() * ARROW_HEAD * ARROW_HEAD_HALF_WIDTH; + let start = center + direction * CENTER_SQUARE * 0.5; + painter.line_segment([start, tip], Stroke::new(SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH, SHAFT_HALO)); + painter.line_segment([start, tip], Stroke::new(SHAFT_WIDTH, color)); + painter.add(egui::Shape::convex_polygon(vec![tip + direction * ARROW_HEAD, tip + side, tip - side], color, HANDLE_EDGE)); + } + let square_rect = Rect::from_center_size(center, vec2(CENTER_SQUARE, CENTER_SQUARE)); + painter.rect(square_rect, CENTER_SQUARE_CORNER_RADIUS, square, HANDLE_EDGE, egui::StrokeKind::Middle); +} + +/// The dashed outline: the dark shadow's width and colour, the light dashes' width and colour over it (white at 230 alpha, premultiplied), the dash and gap lengths +const OUTLINE_SHADOW_WIDTH: f32 = 3.0; +const OUTLINE_SHADOW: Color32 = Color32::from_black_alpha(140); +const OUTLINE_WIDTH: f32 = 1.2; +const OUTLINE_COLOR: Color32 = Color32::from_rgba_premultiplied(230, 230, 230, 230); +const OUTLINE_DASH: f32 = 6.0; +const OUTLINE_GAP: f32 = 4.0; + +/// A gizmo's dashed outline through `points`, light over a dark shadow so it reads on any model +pub(crate) fn dashed_outline(painter: &egui::Painter, points: &[Pos2]) { + for stroke in [Stroke::new(OUTLINE_SHADOW_WIDTH, OUTLINE_SHADOW), Stroke::new(OUTLINE_WIDTH, OUTLINE_COLOR)] { + painter.add(egui::Shape::dashed_line(points, stroke, OUTLINE_DASH, OUTLINE_GAP)); + } +} + +/// An arrow head's half width, as a share of its length +const ARROW_HEAD_HALF_WIDTH: f32 = 0.45; + +/// The dark rim around a handle dot +const DOT_RIM: f32 = 1.5; +/// The thin dark edge round handle dots, arrow heads and the centre square +pub(crate) const HANDLE_EDGE: Stroke = Stroke { width: 1.0, color: Color32::from_black_alpha(200) }; +/// The centre square's corner radius (points) +const CENTER_SQUARE_CORNER_RADIUS: f32 = 2.0; + +/// A handle dot of `radius`: `fill` over a dark rim, so it reads on a light or dark model +pub(crate) fn handle_dot(painter: &egui::Painter, at: Pos2, radius: f32, fill: Color32) { + painter.circle_filled(at, radius + DOT_RIM, SHAFT_HALO); + painter.circle(at, radius, fill, HANDLE_EDGE); +} + +#[cfg(test)] +pub(crate) mod tests { + use egui::{Modifiers, PointerButton, Pos2, vec2}; + use egui_kittest::kittest::Queryable; + use serde_json::json; + use texturecraft_engine::Session; + use texturecraft_engine::core::{LayerId, LayerKind, Projection}; + + use super::*; + + /// The test window: big enough that the docked panels leave the 3D view room for the ball with every gizmo handle round it + const TEST_WINDOW: egui::Vec2 = vec2(1600.0, 960.0); + + /// The ball in a new project, its first frames run; with `render` the views render through wgpu + pub(crate) fn ball_app(render: bool) -> egui_kittest::Harness<'static, TextureCraftApp> { + let session = Session::new_project("Gizmo", texturecraft_engine::geom::primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap(); + let builder = egui_kittest::Harness::builder().with_size(TEST_WINDOW); + let builder = if render { builder.wgpu() } else { builder }; + let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + harness + } + + /// The ball with a selected fill layer projecting `projection` + pub(crate) fn fill_app(projection: &str) -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) { + fill_app_with(json!({"projection": projection})) + } + + /// The ball with a selected fill layer set up by `fields` of layer.fill.projection + pub(crate) fn fill_app_with(fields: serde_json::Value) -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) { + fill_app_rendered(fields, false) + } + + /// As [`fill_app_with`]; with `render` the views render through wgpu + pub(crate) fn fill_app_rendered(mut fields: serde_json::Value, render: bool) -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) { + let mut harness = ball_app(render); + let layer = harness.state_mut().run("layer.add.fill", json!({})).unwrap()["layer"].as_u64().unwrap(); + fields["layer"] = json!(layer); + harness.state_mut().run("layer.fill.projection", fields).unwrap(); + harness.run_steps(2); + (harness, LayerId(layer)) + } + + pub(crate) fn projection(harness: &egui_kittest::Harness<'_, TextureCraftApp>, layer: LayerId) -> Projection { + match &harness.state().session.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(fill) => fill.projection.clone(), + _ => panic!("a fill layer"), + } + } + + /// A primary-button drag from `from` to `to` over a few frames, with `modifiers` held + pub(crate) fn drag(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2, modifiers: Modifiers) { + press_and_move(harness, from, to, modifiers); + harness.event_modifiers(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers }, modifiers); + harness.run_steps(2); + } + + /// The press and moves of [`drag`], the button still down at `to` + pub(crate) fn press_and_move(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2, modifiers: Modifiers) { + harness.event_modifiers(egui::Event::PointerMoved(from), modifiers); + harness.event_modifiers(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers }, modifiers); + harness.run_steps(2); + for step in 1..=4 { + harness.event_modifiers(egui::Event::PointerMoved(from.lerp(to, step as f32 / 4.0)), modifiers); + harness.run_steps(1); + } + } + + /// Whether a frame drag is under way + fn frame_dragging(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> bool { + crate::projection_gizmo::dragging::(&harness.ctx).is_some() + } + + /// A drag as a mouse sends it, one small move per frame; after each frame `check` looks at the app and (with `preview`) the 3D preview square must have re-rendered + #[track_caller] + pub(crate) fn drag_frames( + harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, + layer: LayerId, + from: Pos2, + to: Pos2, + modifiers: Modifiers, + preview: bool, + mut check: impl FnMut(&egui_kittest::Harness<'_, TextureCraftApp>), + ) { + harness.event_modifiers(egui::Event::PointerMoved(from), modifiers); + harness.event_modifiers(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers }, modifiers); + harness.run_steps(2); + let mut shown = crate::projection_preview::shown_key(&harness.ctx); + let mut was = projection(harness, layer); + let mut moved = 0; + for step in 1..=6 { + harness.event_modifiers(egui::Event::PointerMoved(from.lerp(to, step as f32 / 6.0)), modifiers); + harness.step(); + let now = projection(harness, layer); + + // Until the pointer passes the drag threshold nothing moves + if now == was { + assert_eq!(moved, 0, "frame {step}: once started, every frame of the drag moves it"); + continue; + } + + moved += 1; + check(harness); + let key = crate::projection_preview::shown_key(&harness.ctx); + assert!(!preview || (key.is_some() && key != shown), "frame {step}: the preview square re-rendered for the new values"); + (shown, was) = (key, now); + } + assert!(moved >= 4, "the drag moved it on {moved} frames"); + harness.event_modifiers(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers }, modifiers); + harness.run_steps(2); + check(harness); + } + + /// The panel's X, Y and Z fields of a 3D projection settings row + pub(crate) fn panel_xyz(harness: &egui_kittest::Harness<'_, TextureCraftApp>, row: &str) -> [f32; 3] { + use egui_kittest::kittest::NodeT; + ["X", "Y", "Z"].map(|tag| harness.get_by_label(&format!("{row} {tag}")).accesskit_node().numeric_value().unwrap() as f32) + } + + fn gizmo(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> FrameGizmo { + FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap() + } + + #[test] + fn an_axis_planar_is_placed_on_its_first_drag_and_its_handles_move_size_and_stretch_it() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + + // Repeating three times across the mesh, the frame is smaller than the ball + let (mut harness, layer) = fill_app_with(json!({"projection": "planar", "scale": 3})); + let axis = gizmo(&harness); + assert!(matches!(projection(&harness, layer), Projection::Planar { placed: None, .. }), "a new planar projects along its axis"); + assert!(axis.warp.is_none() && axis.arrows.iter().all(Option::is_some), "a planar frame with its three arrows: {axis:?}"); + + drag(&mut harness, axis.center, axis.center + vec2(30.0, 0.0), Modifiers::NONE); + let Projection::Planar { placed: Some(slid), .. } = projection(&harness, layer) else { panic!("placed on the first drag") }; + assert!(slid.offset[0] > 0.0 && slid.offset[1].abs() < slid.offset[0] * 0.2, "the centre square slides it right: {slid:?}"); + assert_eq!(slid.size, axis.decal.size, "sliding keeps its size"); + assert_eq!(harness.state().session.history_labels().last().map(String::as_str), Some("Edit decal")); + let steps = harness.state().session.history_labels().len(); + + let placed = gizmo(&harness); + drag(&mut harness, placed.sides[1], placed.center + (placed.sides[1] - placed.center) * 0.5, Modifiers::NONE); + let Projection::Planar { placed: Some(stretched), .. } = projection(&harness, layer) else { panic!("still placed") }; + assert!(stretched.size[0] < slid.size[0] * 0.75 && stretched.size[1] == slid.size[1], "the right edge dot narrows it only: {stretched:?}"); + + let narrowed = gizmo(&harness); + drag(&mut harness, narrowed.corners[2], narrowed.center + (narrowed.corners[2] - narrowed.center) * 1.5, Modifiers::NONE); + let Projection::Planar { placed: Some(scaled), .. } = projection(&harness, layer) else { panic!("still placed") }; + assert!(scaled.size[1] > stretched.size[1] * 1.2, "a corner scales it: {scaled:?}"); + assert_eq!(harness.state().session.history_labels().len(), steps + 2, "one undo step per drag"); + } + + #[test] + fn a_warp_corner_follows_the_pointer_on_the_frame_plane() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + let warp = gizmo(&harness); + assert_eq!(warp.warp, Some(Projection::FRAME_CORNERS)); + let to = warp.corners[1] + vec2(-40.0, 30.0); + drag(&mut harness, warp.corners[1], to, Modifiers::NONE); + let Projection::Warp { corners, frame, .. } = projection(&harness, layer) else { panic!("still a warp") }; + assert_eq!((frame, corners[0], corners[2], corners[3]), (warp.decal, [-0.5, 0.5], [0.5, -0.5], [-0.5, -0.5]), "only that corner moves"); + assert!(corners[1][0] < 0.45 && corners[1][1] < 0.45, "top right pulled in: {corners:?}"); + assert!(gizmo(&harness).corners[1].distance(to) < 1.5, "the corner sits under the pointer"); + } + + /// A move that arrives in the same frame as the release still moves the corner: it ends under the pointer, not one step short + #[test] + fn a_move_in_the_release_frame_still_moves_the_corner() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = fill_app("warp"); + let warp = gizmo(&harness); + let to = warp.corners[1] + vec2(-40.0, 30.0); + press_and_move(&mut harness, warp.corners[1], warp.corners[1].lerp(to, 0.5), Modifiers::NONE); + + // Straight into the next frame's input: the harness's queued events would each get a frame of their own + let release = egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }; + harness.input_mut().events.extend([egui::Event::PointerMoved(to), release]); + harness.run_steps(2); + + assert!(crate::projection_gizmo::dragging::(&harness.ctx).is_none(), "the release ends the drag"); + assert!(gizmo(&harness).corners[1].distance(to) < 1.5, "the corner sits under the release point: {:?} {to:?}", gizmo(&harness).corners[1]); + } + + /// The across and up arrows slide a frame on its own plane and the out arrow moves it along its normal, each following the pointer; one undo step per drag + #[test] + fn the_arrows_move_a_frame_along_its_directions() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + let steps = harness.state().session.history_labels().len(); + let frame = |harness: &egui_kittest::Harness<'_, TextureCraftApp>| match projection(harness, layer) { + Projection::Warp { frame, .. } => frame, + other => panic!("still a warp: {other:?}"), + }; + + for axis in 0..3 { + let start = gizmo(&harness); + let tip = start.arrows[axis].unwrap_or_else(|| panic!("arrow {axis} shows")); + let along = (tip - start.center).normalized(); + let before = frame(&harness); + drag(&mut harness, tip, tip + along * 25.0, Modifiers::NONE); + + let moved = gizmo(&harness); + assert!( + (moved.center - start.center).dot(along) > 15.0, + "arrow {axis}: the centre follows the pointer along it: {:?} -> {:?}", + start.center, + moved.center + ); + assert_eq!(frame(&harness).normal, before.normal, "arrow {axis}: moving never turns the frame"); + + // Across and up slide it on its own plane, out moves it along its normal + let shift = moved.origin - start.origin; + assert!(shift.normalize().dot(start.axes[axis]) > 0.99, "arrow {axis} moves it along its own direction: {shift:?}"); + assert_eq!(harness.state().session.history_labels().len(), steps + axis + 1, "arrow {axis}: one undo step per drag"); + } + } + + /// The panel's Rotation turns a frame and its Scale sizes it, so the gizmo does both: the ring turns a planar or warp frame round its normal, following the pointer round the centre; a warp's edge dots size its frame as a planar's do + #[test] + fn the_ring_turns_a_frame_and_a_warps_edge_dots_size_it() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for kind in ["warp", "planar"] { + let (mut harness, _) = fill_app(kind); + let start = gizmo(&harness); + let ring = start.ring.unwrap_or_else(|| panic!("{kind}: a frame facing the camera shows its ring")); + let on_ring = *ring + .iter() + .filter(|at| start.grab(**at) == Some(FrameGrab::Turn)) + .max_by(|a, b| a.y.total_cmp(&b.y)) + .expect("a ring point clear of the other handles"); + let steps = harness.state().session.history_labels().len(); + let quarter = start.center + (on_ring - start.center).rot90(); + drag(&mut harness, on_ring, quarter, Modifiers::NONE); + let turned = gizmo(&harness); + let sweep = |from: egui::Vec2, to: egui::Vec2| (to.angle() - from.angle()).to_degrees(); + let pointer = sweep(on_ring - start.center, quarter - start.center); + let corner = sweep(start.corners[1] - start.center, turned.corners[1] - turned.center); + let off = (corner - pointer + 180.0).rem_euclid(360.0) - 180.0; + assert!(off.abs() < 6.0, "{kind}: the frame turns a quarter with the pointer: corner {corner}°, pointer {pointer}°"); + assert!(turned.center.distance(start.center) < 1.0, "{kind}: round its centre"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "{kind}: one undo step"); + } + + let (mut harness, layer) = fill_app("warp"); + let warp = gizmo(&harness); + assert_eq!(warp.grab(warp.sides[1]), Some(FrameGrab::Side(1))); + drag(&mut harness, warp.sides[1], warp.center + (warp.sides[1] - warp.center) * 0.5, Modifiers::NONE); + let Projection::Warp { frame, corners, .. } = projection(&harness, layer) else { panic!("still a warp") }; + assert!(frame.size[0] < warp.decal.size[0] * 0.75 && (frame.size[1] - warp.decal.size[1]).abs() < 1e-4, "the right edge dot narrows it: {frame:?}"); + assert_eq!(corners, Projection::FRAME_CORNERS, "its corners stay where they are on the frame"); + } + + /// Losing the focus mid-drag (Alt+Tab) ends a frame drag as a release does: one undo step, and moves after it (egui still has the button down) leave the frame alone + #[test] + fn losing_the_window_focus_ends_a_frame_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("planar"); + let steps = harness.state().session.history_labels().len(); + let center = gizmo(&harness).center; + let to = center + vec2(40.0, 0.0); + press_and_move(&mut harness, center, to, Modifiers::NONE); + assert!(frame_dragging(&harness), "the centre square is held"); + + harness.event(egui::Event::WindowFocused(false)); + harness.run_steps(1); + let left = projection(&harness, layer); + assert!(!frame_dragging(&harness), "the focus loss ends the drag"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "as one undo step"); + + for step in 1..=3 { + harness.event(egui::Event::PointerMoved(to + vec2(20.0, 10.0) * step as f32)); + harness.run_steps(1); + } + assert_eq!(projection(&harness, layer), left, "moves after it leave the frame where it was"); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "and add no step"); + } + + /// Alt pressed mid-drag hands the pointer to the camera and ends the frame drag where it is: let go of Alt with the button still down, the drag does not resume from where it began; one undo step + #[test] + fn alt_mid_drag_ends_a_frame_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("planar"); + let steps = harness.state().session.history_labels().len(); + let center = gizmo(&harness).center; + let to = center + vec2(40.0, 0.0); + press_and_move(&mut harness, center, to, Modifiers::NONE); + let slid = projection(&harness, layer); + let camera = harness.state().session.camera; + + harness.event_modifiers(egui::Event::PointerMoved(to + vec2(20.0, 0.0)), Modifiers::ALT); + harness.run_steps(1); + assert_ne!(harness.state().session.camera, camera, "Alt turns the camera"); + assert!(!frame_dragging(&harness), "and ends the frame drag"); + + for step in 2..=4 { + harness.event(egui::Event::PointerMoved(to + vec2(20.0, 5.0) * step as f32)); + harness.run_steps(1); + } + assert_eq!(projection(&harness, layer), slid, "Alt let go, the frame stays where the drag left it"); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step"); + } + + /// The rest of a drag held at `from`: moves to `to` over a few frames and lets go there + fn move_and_let_go(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + for step in 1..=4 { + harness.event(egui::Event::PointerMoved(from.lerp(to, step as f32 / 4.0))); + harness.run_steps(1); + } + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + } + + /// A drag whose first edit changes nothing (its arrow pulled further past the offset limit) makes no undo step, so its later edits make the drag's own step instead of joining the edit before it + #[test] + fn a_drag_that_first_changes_nothing_keeps_its_own_undo_step() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + + // The frame waits at its left limit, a mesh diagonal off the ball's centre, clear of the panels on the right; the camera backs off so it shows with its arrows + harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "offset": [-100.0, 0.0]})).unwrap(); + harness.state_mut().session.camera.distance *= 3.0; + harness.run_steps(2); + let at_limit = projection(&harness, layer); + let steps = harness.state().session.history_labels().len(); + let start = gizmo(&harness); + let tip = start.arrows[0].expect("the across arrow shows"); + let inward = (tip - start.center).normalized(); + + press_and_move(&mut harness, tip, tip - inward * 25.0, Modifiers::NONE); + + assert_eq!(projection(&harness, layer), at_limit, "past the limit the frame stays where it is"); + move_and_let_go(&mut harness, tip - inward * 25.0, tip + inward * 25.0); + + assert_ne!(projection(&harness, layer), at_limit, "back inside the frame moves"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the drag made its own undo step"); + + harness.state_mut().session.undo().unwrap(); + assert_eq!(projection(&harness, layer), at_limit, "undo takes back the drag only"); + } + + /// An axis planar reading a pattern keeps its axis, so it shows no frame to drag; reading an image it shows one + #[test] + fn an_axis_planar_reading_a_pattern_has_no_frame() { + let (mut harness, layer) = fill_app("planar"); + assert!(FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_some(), "a uniform fill places as its frame"); + + harness.state_mut().run("layer.fill.set", json!({"layer": layer.0, "channel": "roughness", "procedural": "Checker"})).unwrap(); + harness.run_steps(2); + assert!(FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "placing would move the pattern"); + } + + /// An Undo mid-drag takes the drag's step away: the drag's next edits make a step of their own instead of joining the drag before it + #[test] + fn undo_mid_drag_leaves_the_drag_before_its_own_step() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + let center = gizmo(&harness).center; + drag(&mut harness, center, center + vec2(30.0, 0.0), Modifiers::NONE); + let first = projection(&harness, layer); + let steps = harness.state().session.history_labels().len(); + + let center = gizmo(&harness).center; + press_and_move(&mut harness, center, center + vec2(0.0, 30.0), Modifiers::NONE); + harness.key_press_modifiers(Modifiers::COMMAND, egui::Key::Z); + harness.run_steps(1); + assert_eq!(projection(&harness, layer), first, "Ctrl+Z undid the drag so far"); + move_and_let_go(&mut harness, center + vec2(0.0, 30.0), center + vec2(0.0, 40.0)); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the drag's later edits made a step of their own"); + + harness.state_mut().session.undo().unwrap(); + assert_eq!(projection(&harness, layer), first, "undo goes back to where the first drag left the frame"); + } + + /// A click as a mouse sends it: move there, press, release + fn click(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, at: Pos2) { + harness.event(egui::Event::PointerMoved(at)); + harness.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + } + + /// The Projection row's eye hides the gizmo: not drawn, a press on where its handle was moves nothing, and the eye brings it back + #[test] + fn the_projection_rows_eye_hides_and_shows_the_gizmo() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app_with(json!({"projection": "planar", "scale": 3})); + let shown = gizmo(&harness); + let eye = harness.get_by_label("Hide projection gizmos").rect(); + let projection_row = harness.get_by_label("Planar projection").rect(); + assert!(eye.left() > projection_row.right() && (eye.center().y - projection_row.center().y).abs() < 0.5, "the eye ends the Projection row"); + + click(&mut harness, eye.center()); + assert!(!harness.state().session.doc.project.display.projection_gizmos, "the eye hides the gizmos"); + assert!(FrameGizmo::shown(harness.state(), harness.state().viewport_rect).is_none(), "the 3D view has no frame to draw or grab"); + let before = projection(&harness, layer); + drag(&mut harness, shown.center, shown.center + vec2(30.0, 0.0), Modifiers::NONE); + assert_eq!(projection(&harness, layer), before, "a drag where the centre square was moves nothing"); + + let eye = harness.get_by_label("Show projection gizmos").rect(); + click(&mut harness, eye.center()); + assert!(harness.state().session.doc.project.display.projection_gizmos, "the eye shows them again"); + drag(&mut harness, shown.center, shown.center + vec2(30.0, 0.0), Modifiers::NONE); + assert_ne!(projection(&harness, layer), before, "shown, the centre square slides it again"); + + // A UV projection has no gizmo: its row keeps the whole width for the dropdown + harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "projection": "uv"})).unwrap(); + harness.run_steps(2); + assert!(harness.query_by_label("Hide projection gizmos").is_none(), "no eye without a gizmo"); + } + + #[test] + fn round_projections_have_no_frame() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for projection in ["uv", "triplanar", "spherical", "cylindrical"] { + let (harness, _) = fill_app(projection); + assert!(FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "{projection}"); + } + } + + /// The planar and warp frames over the ball, a handle hovered, Move on model lit, and the round projectors + #[test] + #[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] + fn frame_gizmo_snapshots() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { return }; + + std::fs::create_dir_all(&directory).unwrap(); + let checker = |harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, layer: LayerId| { + let fields = + json!({"layer": layer.0, "channel": "baseColor", "procedural": "Checker", "scale": 4, "low": [0.2, 0.2, 0.2], "high": [0.6, 0.6, 0.6]}); + harness.state_mut().run("layer.fill.set", fields).unwrap(); + harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "shapeCrop": "cropped"})).unwrap(); + }; + let (mut harness, layer) = fill_app_rendered(json!({"projection": "planar", "scale": 3}), true); + checker(&mut harness, layer); + harness.run_steps(4); + let planar = gizmo(&harness); + harness.hover_at(planar.sides[1]); + harness.run_steps(4); + harness.render().unwrap().save(directory.join("move-planar-side-hover.png")).unwrap(); + + // Move on model held down and dragged into the 3D view: the button stays lit and the frame follows + let button = harness.get_by_label("Move on model").rect().center(); + harness.event(egui::Event::PointerMoved(button)); + harness.event(egui::Event::PointerButton { pos: button, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + for step in 1..=6 { + harness.event(egui::Event::PointerMoved(button + vec2(-40.0, 10.0) * step as f32)); + harness.run_steps(1); + } + harness.run_steps(3); + harness.render().unwrap().save(directory.join("move-planar-held.png")).unwrap(); + harness.event(egui::Event::PointerButton { + pos: button + vec2(-240.0, 60.0), + button: PointerButton::Primary, + pressed: false, + modifiers: Modifiers::NONE, + }); + harness.run_steps(2); + + let (mut harness, layer) = fill_app_rendered(json!({"projection": "warp"}), true); + checker(&mut harness, layer); + let pulled = json!([[-0.35, 0.3], [0.4, 0.42], [0.42, -0.4], [-0.3, -0.32]]); + harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "warpCorners": pulled, "projectionDepth": 1})).unwrap(); + harness.run_steps(4); + harness.hover_at(gizmo(&harness).corners[1]); + harness.run_steps(4); + harness.render().unwrap().save(directory.join("move-warp-corner-hover.png")).unwrap(); + + // Mid drag: the panel's 3D projection settings and the preview square hold the frame the gizmo is dragging + let (mut harness, layer) = fill_app_rendered(json!({"projection": "planar", "scale": 3}), true); + checker(&mut harness, layer); + harness.run_steps(4); + let held = gizmo(&harness); + let (from, to) = (held.sides[0], held.center + (held.sides[0] - held.center) * 0.6 + vec2(30.0, 0.0)); + harness.event(egui::Event::PointerMoved(from)); + harness.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + for step in 1..=6 { + harness.event(egui::Event::PointerMoved(from.lerp(to, step as f32 / 6.0))); + harness.run_steps(1); + } + harness.run_steps(3); + harness.render().unwrap().save(directory.join("sync-planar-mid-drag.png")).unwrap(); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + let (mut harness, layer) = fill_app_rendered(json!({"projection": "spherical"}), true); + checker(&mut harness, layer); + harness.run_steps(4); + let round = crate::round_gizmo::RoundGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); + let dot = round.sizes.iter().find(|size| size.axes == [true; 3]).expect("the even-scale dot").at; + let to = round.center + (dot - round.center) * 0.6; + harness.event(egui::Event::PointerMoved(dot)); + harness.event(egui::Event::PointerButton { pos: dot, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + for step in 1..=6 { + harness.event(egui::Event::PointerMoved(dot.lerp(to, step as f32 / 6.0))); + harness.run_steps(1); + } + harness.run_steps(3); + harness.render().unwrap().save(directory.join("sync-sphere-mid-drag.png")).unwrap(); + + // The round projections with their fill selected: the shape round it, a ring hovered (a sphere: its one dot; a cylinder: its height arrow) + for kind in ["triplanar", "spherical", "cylindrical"] { + let (mut harness, layer) = fill_app_rendered(json!({"projection": kind}), true); + checker(&mut harness, layer); + harness.run_steps(4); + let round = crate::round_gizmo::RoundGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); + let size_at = |axes: [bool; 3]| round.sizes.iter().find(|size| size.axes == axes).expect("the size handle").at; + let hover = match kind { + "triplanar" => round.rings[2][crate::round_gizmo::CIRCLE_POINTS / 8], + "spherical" => size_at([true; 3]), + _ => size_at([false, true, false]), + }; + harness.hover_at(hover); + harness.run_steps(4); + harness.render().unwrap().save(directory.join(format!("move-{kind}.png"))).unwrap(); + } + } + + /// The panel's 3D projection settings show the frame the gizmo drags (its centre, turn and size), and the preview square follows, every frame of every drag: resize, stretch, slide, turn, a warp's slide and corners; one undo step per drag + #[test] + fn the_panel_and_its_preview_follow_every_frame_of_a_frame_drag() { + // Dolly exponent stepping the camera back before the corner drag + const CORNER_ZOOM_OUT: f32 = 0.4; + + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + use texturecraft_engine::compose::frame_placement::placement; + + let check = |layer: LayerId| { + move |harness: &egui_kittest::Harness<'_, TextureCraftApp>| { + let Some(shown) = placement(&projection(harness, layer), harness.state().session.mesh.bounds()) else { panic!("placed on its first drag") }; + for (row, value) in [("Offset", shown.offset), ("Rotation", shown.rotation), ("Scale", shown.scale)] { + let field = panel_xyz(harness, row); + for axis in 0..3 { + assert!((field[axis] - value[axis]).abs() < 1e-3, "the panel's {row} shows the frame's {value:?}, not {field:?}"); + } + } + } + }; + + let (mut harness, layer) = fill_app("planar"); + let steps = harness.state().session.history_labels().len(); + let center = gizmo(&harness).center; + drag_frames(&mut harness, layer, center, center + vec2(30.0, -10.0), Modifiers::NONE, true, check(layer)); + let slid = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + + // The top edge dot and a corner inside the view (the frame starts bigger than the model) + let side = gizmo(&harness); + drag_frames(&mut harness, layer, side.sides[0], side.center + (side.sides[0] - side.center) * 0.5, Modifiers::NONE, true, check(layer)); + let narrowed = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + assert!(narrowed.scale[1] < slid.scale[1] * 0.75 && (narrowed.scale[0] - slid.scale[0]).abs() < 1e-4, "{slid:?} -> {narrowed:?}"); + + // The view steps back so a corner shows beside the panels + harness.state_mut().session.camera.zoom(-CORNER_ZOOM_OUT); + harness.run_steps(2); + let corner = gizmo(&harness); + let view = harness.state().viewport_rect.shrink(10.0); + let inside = *corner.corners.iter().find(|at| view.contains(**at)).expect("a corner in the view"); + drag_frames(&mut harness, layer, inside, corner.center + (inside - corner.center) * 0.6, Modifiers::NONE, true, check(layer)); + let scaled = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + assert!(scaled.scale[1] < narrowed.scale[1] * 0.8 && scaled.scale[0] < narrowed.scale[0] * 0.8, "a corner scales it: {scaled:?}"); + + // Move on model held with Shift turns the frame round its normal + let before = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + let button = harness.get_by_label("Move on model").rect().center(); + drag_frames(&mut harness, layer, button, button + vec2(-60.0, 0.0), Modifiers::SHIFT, true, check(layer)); + let turned = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + assert!((turned.rotation[2] - before.rotation[2]).abs() > 10.0, "turned: {before:?} -> {turned:?}"); + assert_eq!(harness.state().session.history_labels().len(), steps + 4, "one undo step per drag"); + + let (mut harness, layer) = fill_app("warp"); + let warp = gizmo(&harness); + drag_frames(&mut harness, layer, warp.center, warp.center + vec2(30.0, 25.0), Modifiers::NONE, false, check(layer)); + let warp = gizmo(&harness); + drag_frames(&mut harness, layer, warp.corners[0], warp.corners[0] + vec2(-25.0, -15.0), Modifiers::NONE, false, check(layer)); + let Projection::Warp { corners, .. } = projection(&harness, layer) else { panic!("a warp") }; + assert_ne!(corners[0], Projection::FRAME_CORNERS[0], "the corner was pulled"); + } +} diff --git a/crates/ui-egui/src/frame_gizmo/frame_grab.rs b/crates/ui-egui/src/frame_gizmo/frame_grab.rs new file mode 100644 index 00000000..a0733168 --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo/frame_grab.rs @@ -0,0 +1,29 @@ +/// What a drag on the frame does +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum FrameGrab { + /// The centre square: slide the frame across its own plane + Slide, + /// Along the frame's across (0), up (1) or out (2) direction + Axis(usize), + /// A planar's corner: scale it about its centre + Scale, + /// A planar's edge dot (top, right, bottom, left): stretch that side + Side(usize), + /// A warp's corner (top left, top right, bottom right, bottom left): pull it + Corner(usize), + /// The ring: turn it round its normal + Turn, +} + +impl FrameGrab { + pub(super) fn cursor(self, dragging: bool) -> egui::CursorIcon { + match self { + FrameGrab::Slide if dragging => egui::CursorIcon::Grabbing, + FrameGrab::Slide => egui::CursorIcon::Grab, + FrameGrab::Axis(_) | FrameGrab::Corner(_) | FrameGrab::Turn => egui::CursorIcon::Move, + FrameGrab::Scale => egui::CursorIcon::ResizeNwSe, + FrameGrab::Side(side) if side % 2 == 0 => egui::CursorIcon::ResizeVertical, + FrameGrab::Side(_) => egui::CursorIcon::ResizeHorizontal, + } + } +} diff --git a/crates/ui-egui/src/projection_gizmo.rs b/crates/ui-egui/src/projection_gizmo.rs new file mode 100644 index 00000000..06b1c199 --- /dev/null +++ b/crates/ui-egui/src/projection_gizmo.rs @@ -0,0 +1,77 @@ +//! A drag on a handle of the selected fill's projection gizmo, a planar or warp frame or a round projector: one undo step per drag, the projection updating live + +mod gizmo; +mod gizmo_drag; +mod shown_gizmo; + +use egui::{PointerButton, Rect}; +use serde_json::{Value, json}; +use texturecraft_engine::Session; + +use crate::TextureCraftApp; +use crate::viewport::focus_lost; + +pub(crate) use gizmo::Gizmo; +pub(crate) use gizmo_drag::GizmoDrag; +pub(crate) use shown_gizmo::ShownGizmo; + +/// The drag under way on a handle of a `G` gizmo +pub(crate) fn dragging(ctx: &egui::Context) -> Option> { + ctx.data(|data| data.get_temp::>(G::drag_id())) +} + +/// Ends a drag under way on a `G` gizmo where it is: its undo step stays one step +pub(crate) fn let_go(ctx: &egui::Context) { + ctx.data_mut(|data| data.remove::>(G::drag_id())); +} + +/// Drags on `gizmo`'s handles (one undo step per drag, the projection updates live); returns whether a drag owns the pointer. The cursor shows what the handle under it, or the one dragged, does (only while the gizmo takes input: an Alt orbit or a held Move on model keeps its own) +pub(crate) fn input(app: &mut TextureCraftApp, ctx: &egui::Context, response: &egui::Response, rect: Rect, gizmo: Option<&G>) -> bool { + let mut drag = dragging::(ctx).filter(|drag| gizmo.is_some_and(|gizmo| gizmo.same_projection(&drag.start))); + if response.drag_started_by(PointerButton::Primary) + && let (Some(gizmo), Some(from)) = (gizmo, ctx.input(|input| input.pointer.press_origin())) + && let Some(grab) = gizmo.grab(from) + { + drag = Some(GizmoDrag { grab, from, start: gizmo.clone(), edited_revision: None }); + } + + // A window that lost the focus gets no release: the drag ends there. A release still applies a move that came in the same frame + let released = response.drag_stopped_by(PointerButton::Primary); + let pressed = response.dragged_by(PointerButton::Primary) || response.drag_started_by(PointerButton::Primary) || released; + let Some(mut drag) = drag.filter(|_| pressed && !focus_lost(ctx)) else { + let_go::(ctx); + if let Some((gizmo, grab)) = gizmo.and_then(|gizmo| Some((gizmo, gizmo.grab(response.hover_pos()?)?))) { + ctx.set_cursor_icon(gizmo.cursor(grab, false)); + } + return false; + }; + + // A drag lives only while its gizmo shows, so the gizmo drawn this frame names the cursor + ctx.set_cursor_icon(gizmo.unwrap_or(&drag.start).cursor(drag.grab, true)); + + if let Some(pointer) = response.interact_pointer_pos().filter(|_| ctx.input(|input| input.pointer.delta() != egui::Vec2::ZERO)) + && let Some((command, params)) = drag.start.edit(app, rect, drag.grab, drag.from, pointer) + { + edit_in_one_step(&mut app.session, command, params, &mut drag.edited_revision); + + // The panel drew before this edit: one more frame shows its fields and preview where the projection is now + ctx.request_repaint(); + } + if released { + let_go::(ctx); + } else { + ctx.data_mut(|data| data.insert_temp(G::drag_id(), drag)); + } + true +} + +/// Runs one edit of a drag or hold, joining the undo step its last edit (at `edited_revision`) made while the history is still where that edit left it: an edit that changed nothing made no step to join, and an Undo took the step away +pub(crate) fn edit_in_one_step(session: &mut Session, command: &str, mut params: Value, edited_revision: &mut Option) { + params["merge"] = json!(*edited_revision == Some(session.revision)); + let before = session.revision; + + // Off the plane or past the size limits: the projection waits where it is + if texturecraft_engine::execute(session, command, ¶ms).is_ok() && session.revision != before { + *edited_revision = Some(session.revision); + } +} diff --git a/crates/ui-egui/src/projection_gizmo/gizmo.rs b/crates/ui-egui/src/projection_gizmo/gizmo.rs new file mode 100644 index 00000000..e95c8270 --- /dev/null +++ b/crates/ui-egui/src/projection_gizmo/gizmo.rs @@ -0,0 +1,25 @@ +use egui::{Pos2, Rect}; +use serde_json::Value; + +use crate::TextureCraftApp; + +/// A projection gizmo whose handles a drag edits +pub(crate) trait Gizmo: Clone + Send + Sync + 'static { + /// What a drag on one of its handles does + type Grab: Copy + PartialEq + Send + Sync + 'static; + + /// Where a drag on it is kept in egui's memory + fn drag_id() -> egui::Id; + + /// The handle under screen point `at` + fn grab(&self, at: Pos2) -> Option; + + /// Whether `other` shows the same projection: a drag goes on only while the projection it began on shows + fn same_projection(&self, other: &Self) -> bool; + + /// The command and params a drag of `grab` from `from` to `to` runs + fn edit(&self, app: &TextureCraftApp, rect: Rect, grab: Self::Grab, from: Pos2, to: Pos2) -> Option<(&'static str, Value)>; + + /// The cursor over `grab`, or dragging it + fn cursor(&self, grab: Self::Grab, dragging: bool) -> egui::CursorIcon; +} diff --git a/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs b/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs new file mode 100644 index 00000000..bf8221b5 --- /dev/null +++ b/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs @@ -0,0 +1,14 @@ +use egui::Pos2; + +use super::Gizmo; + +/// A handle of a projection gizmo being dragged (kept in egui's memory between frames) +#[derive(Clone, Debug)] +pub(crate) struct GizmoDrag { + pub(crate) grab: G::Grab, + /// Where the drag started and the gizmo then + pub(crate) from: Pos2, + pub(crate) start: G, + /// The session revision the drag's last edit left: later updates merge into its undo step while the history is still there + pub(crate) edited_revision: Option, +} diff --git a/crates/ui-egui/src/projection_gizmo/shown_gizmo.rs b/crates/ui-egui/src/projection_gizmo/shown_gizmo.rs new file mode 100644 index 00000000..cd2a7e26 --- /dev/null +++ b/crates/ui-egui/src/projection_gizmo/shown_gizmo.rs @@ -0,0 +1,73 @@ +use egui::{Pos2, Rect, Ui}; + +use super::{Gizmo, dragging, let_go}; +use crate::TextureCraftApp; +use crate::frame_gizmo::FrameGizmo; +use crate::round_gizmo::RoundGizmo; + +/// The selected fill's projection gizmo the 3D view shows, built once a frame: a planar or warp frame, or a round projector +pub(crate) enum ShownGizmo { + // Both boxed: each gizmo is hundreds of bytes and of a different size + Frame(Box), + Round(Box), +} + +impl ShownGizmo { + /// The gizmo of the selected fill's projection: none while the Projection row's eye hides it + pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option { + FrameGizmo::shown(app, rect) + .map(|frame| ShownGizmo::Frame(Box::new(frame))) + .or_else(|| RoundGizmo::shown(app, rect).map(|round| ShownGizmo::Round(Box::new(round)))) + } + + fn frame(gizmo: Option<&ShownGizmo>) -> Option<&FrameGizmo> { + match gizmo? { + ShownGizmo::Frame(frame) => Some(frame), + ShownGizmo::Round(_) => None, + } + } + + fn round(gizmo: Option<&ShownGizmo>) -> Option<&RoundGizmo> { + match gizmo? { + ShownGizmo::Round(round) => Some(round), + ShownGizmo::Frame(_) => None, + } + } + + /// Drags on `gizmo`'s handles; returns whether a drag owns the pointer + pub(crate) fn input(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, rect: Rect, gizmo: Option<&ShownGizmo>) -> bool { + let ctx = ui.ctx(); + super::input(app, ctx, response, rect, ShownGizmo::frame(gizmo)) || super::input(app, ctx, response, rect, ShownGizmo::round(gizmo)) + } + + /// Ends a drag under way on either gizmo where it is + pub(crate) fn let_go(ctx: &egui::Context) { + let_go::(ctx); + let_go::(ctx); + } + + /// Whether screen point `at` is on one of its handles + pub(crate) fn on_handle(&self, rect: Rect, at: Pos2) -> bool { + rect.contains(at) + && match self { + ShownGizmo::Frame(frame) => frame.grab(at).is_some(), + ShownGizmo::Round(round) => round.grab(at).is_some(), + } + } + + /// Whether the pointer is over one of `gizmo`'s handles or dragging one (the brush cursor hides there) + pub(crate) fn hovered(ui: &Ui, rect: Rect, gizmo: Option<&ShownGizmo>) -> bool { + let ctx = ui.ctx(); + dragging::(ctx).is_some() + || dragging::(ctx).is_some() + || ctx.pointer_hover_pos().is_some_and(|hover| gizmo.is_some_and(|gizmo| gizmo.on_handle(rect, hover))) + } + + /// The gizmo over the 3D view + pub(crate) fn overlay(&self, app: &TextureCraftApp, ui: &Ui, rect: Rect) { + match self { + ShownGizmo::Frame(frame) => crate::frame_gizmo::overlay(ui, rect, frame), + ShownGizmo::Round(round) => crate::round_gizmo::overlay(app, ui, rect, round), + } + } +} diff --git a/crates/ui-egui/src/projector_outline.rs b/crates/ui-egui/src/projector_outline.rs new file mode 100644 index 00000000..ddd40e64 --- /dev/null +++ b/crates/ui-egui/src/projector_outline.rs @@ -0,0 +1,159 @@ +//! The projector a 3D projection's preview square draws round its object, as the 3D view's gizmo shows it round the model: a planar's frame with the dot its image travels to, a sphere's rim, equator and meridian, a tri-planar box or a cylinder + +use texturecraft_engine::compose::axis_frame::axis_frame; +use texturecraft_engine::compose::pattern::{cylinder_axis_index, decal_axes}; +use texturecraft_engine::core::Projection; +use texturecraft_engine::geom::glam::{Vec2, Vec3}; + +use crate::round_gizmo::{BOX_REACH, CIRCLE_POINTS, CYLINDER_HEIGHT, CYLINDER_REACH, SPHERE_REACH, box_corner, box_edges}; + +mod place; + +use place::Place; + +/// How far in front of the object a planar's frame stands (preview units) +const FRAME_GAP: f32 = 0.15; + +/// How far a planar's direction line reaches back from its frame (preview units) +const DIRECTION_LENGTH: f32 = 0.35; + +/// The projector's outline in the preview's coordinates (the compositor's: the mesh's centre at the origin, its half diagonal 1) +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct ProjectorOutline { + /// Polylines; a closed one repeats its first point at its end + pub lines: Vec>, + /// Where a planar's image travels to from its frame: the direction dot + pub tip: Option, + /// The projector's centre: a frame's middle, a round projector's centre + pub center: Vec3, +} + +impl ProjectorOutline { + /// The outline of `projection`'s projector round an object with half sizes `object` (None for projections without one: UV, warp, placed planars, which the preview shows as axis planars) + pub(crate) fn of(projection: &Projection, object: Vec3) -> Option { + let outline = match projection { + Projection::Planar { scale, axis, offset, projector, placed: None, .. } => { + // The compositor's coordinates as a mesh: centred, half diagonal 1, so each corner sits 1/√3 out along every axis + let corner = Vec3::splat(1.0 / 3f32.sqrt()); + let frame = axis_frame(*scale, *axis, Vec3::from(*offset), projector, (-corner, corner))?; + planar(frame.size, decal_axes(&frame)?, object) + } + Projection::Triplanar { scale, offset, projector, .. } => { + let place = Place::new(projector.rotation, projector.scale, Vec3::from(*offset), *scale); + let size = object * BOX_REACH; + let corner = |index: usize| place.world(place.local + size * box_corner(index)); + let lines = box_edges().map(|(first, second)| vec![corner(first), corner(second)]).collect(); + + ProjectorOutline { lines, tip: None, center: place.world(place.local) } + } + Projection::Spherical { offset, projector, .. } => { + let place = Place::new(projector.rotation, projector.scale, Vec3::from(*offset), 1.0); + let radius = object.max_element() * SPHERE_REACH; + let (u, v) = place.facing().any_orthonormal_pair(); + let ring = |a: Vec3, b: Vec3| circle(|t| place.world(place.local + (a * t.x + b * t.y) * radius)); + ProjectorOutline { lines: vec![ring(u, v), ring(Vec3::X, Vec3::Z), ring(Vec3::Y, Vec3::Z)], tip: None, center: place.world(place.local) } + } + Projection::Cylindrical { axis, offset, projector, .. } => { + let place = Place::new(projector.rotation, projector.scale, Vec3::from(*offset), 1.0); + let axis = cylinder_axis_index(*axis); + let along = Vec3::AXES[axis]; + let (u, v) = (Vec3::AXES[(axis + 1) % Vec3::AXES.len()], Vec3::AXES[(axis + 2) % Vec3::AXES.len()]); + let radius = (object * (Vec3::ONE - along)).max_element() * CYLINDER_REACH; + let half_height = object[axis] * CYLINDER_HEIGHT; + let cap = |height: f32| circle(|t| place.world(place.local + along * height + (u * t.x + v * t.y) * radius)); + let mut lines = vec![cap(half_height), cap(-half_height)]; + + // The two side lines, where the round side turns away from the camera + let facing = place.facing(); + if let Some(side) = along.cross(facing - along * facing.dot(along)).try_normalize() { + for edge in [side, -side] { + lines.push(vec![ + place.world(place.local + edge * radius + along * half_height), + place.world(place.local + edge * radius - along * half_height), + ]); + } + } + ProjectorOutline { lines, tip: None, center: place.world(place.local) } + } + Projection::Planar { placed: Some(_), .. } | Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => return None, + }; + let finite = outline.points().all(|point| point.is_finite()) && outline.center.is_finite(); + finite.then_some(outline) + } + + /// Every point the outline draws, the direction dot included + pub(crate) fn points(&self) -> impl Iterator + '_ { + self.lines.iter().flatten().copied().chain(self.tip) + } +} + +/// A planar's frame, `size` across and up on the frame `axes` (origin, across, up, out), stood just in front of the object on the side its image reads from, and the line its image travels along into the object +fn planar(size: [f32; 2], (origin, across, up, out): (Vec3, Vec3, Vec3, Vec3), object: Vec3) -> ProjectorOutline { + let center = origin + out * (object.max_element() + FRAME_GAP - origin.dot(out)); + let (across, up) = (across * size[0] / 2.0, up * size[1] / 2.0); + let corners = [center - across - up, center + across - up, center + across + up, center - across + up, center - across - up]; + let tip = center - out * DIRECTION_LENGTH; + ProjectorOutline { lines: vec![corners.to_vec(), vec![center, tip]], tip: Some(tip), center } +} + +/// A closed circle through `at` of the unit circle's points +fn circle(at: impl Fn(Vec2) -> Vec3) -> Vec { + (0..=CIRCLE_POINTS) + .map(|index| { + let angle = index as f32 / CIRCLE_POINTS as f32 * std::f32::consts::TAU; + at(Vec2::new(angle.cos(), angle.sin())) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_engine::core::{Projector, UvTransform}; + + const BALL: Vec3 = Vec3::splat(0.85); + + fn spherical(projector: Projector, offset: [f32; 3]) -> Projection { + Projection::Spherical { scale: 1.0, uv: UvTransform::default(), offset, projector } + } + + #[test] + fn every_3d_projection_has_its_projector_outline() { + let planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default(), placed: None }; + let outline = ProjectorOutline::of(&planar, BALL).unwrap(); + assert_eq!(outline.lines.len(), 2, "a frame and its direction line"); + let tip = outline.tip.unwrap(); + assert!(tip.z < BALL.z + FRAME_GAP && outline.lines[0][0].z > BALL.z, "the frame stands in front of the ball, the dot points into it"); + + assert_eq!(ProjectorOutline::of(&spherical(Projector::default(), [0.0; 3]), BALL).unwrap().lines.len(), 3, "rim, equator, meridian"); + let cylinder = + Projection::Cylindrical { scale: 1.0, axis: 1, uv: UvTransform::default(), offset: [0.0; 3], projector: Projector::default(), angle: 360.0 }; + assert_eq!(ProjectorOutline::of(&cylinder, Vec3::new(0.55, 0.7, 0.55)).unwrap().lines.len(), 4, "two caps, two side lines"); + let triplanar = Projection::triplanar(); + assert_eq!(ProjectorOutline::of(&triplanar, Vec3::splat(0.55)).unwrap().lines.len(), 12, "a box's edges"); + assert!(ProjectorOutline::of(&Projection::UvTile, BALL).is_none()); + } + + #[test] + fn a_cylinder_axis_past_z_wraps_round_y_as_the_compositor_reads_it() { + let cylinder = |axis: u8| Projection::Cylindrical { + scale: 1.0, + axis, + uv: UvTransform::default(), + offset: [0.0; 3], + projector: Projector::default(), + angle: 360.0, + }; + let object = Vec3::new(0.55, 0.7, 0.4); + assert_eq!(ProjectorOutline::of(&cylinder(3), object), ProjectorOutline::of(&cylinder(1), object)); + } + + #[test] + fn the_outline_follows_the_projectors_size_and_centre() { + let reach = |projection: &Projection| ProjectorOutline::of(projection, BALL).unwrap().points().map(Vec3::length).fold(0.0, f32::max); + let plain = reach(&spherical(Projector::default(), [0.0; 3])); + assert!((plain - 0.85 * SPHERE_REACH).abs() < 1e-4, "{plain}"); + assert!((reach(&spherical(Projector { scale: [3.0; 3], ..Projector::default() }, [0.0; 3])) - 3.0 * plain).abs() < 1e-3, "x3 is three times as far"); + assert!(reach(&spherical(Projector::default(), [0.5, 0.0, 0.0])) > plain + 0.4, "an offset moves it"); + } +} diff --git a/crates/ui-egui/src/projector_outline/place.rs b/crates/ui-egui/src/projector_outline/place.rs new file mode 100644 index 00000000..9cf1d79a --- /dev/null +++ b/crates/ui-egui/src/projector_outline/place.rs @@ -0,0 +1,27 @@ +use texturecraft_engine::compose::pattern::nonzero_stretch; +use texturecraft_engine::geom::glam::{EulerRot, Mat3, Vec3}; + +/// A round projector's turn, stretch and centre: a point in its own units lands at `turn × (stretch × point)` (the gizmo's placement) +pub(super) struct Place { + pub(super) turn: Mat3, + pub(super) stretch: Vec3, + /// Its centre in its own units + pub(super) local: Vec3, +} + +impl Place { + /// `offset` moves the centre by `-offset / per_local` of its own units + pub(super) fn new(rotation: [f32; 3], scale: [f32; 3], offset: Vec3, per_local: f32) -> Place { + let [x, y, z] = rotation.map(f32::to_radians); + Place { turn: Mat3::from_euler(EulerRot::ZYX, z, y, x), stretch: Vec3::from(scale).map(nonzero_stretch), local: -offset / nonzero_stretch(per_local) } + } + + pub(super) fn world(&self, local: Vec3) -> Vec3 { + self.turn * (self.stretch * local) + } + + /// The preview camera's view direction in the projector's own units: the rim is the circle across it + pub(super) fn facing(&self) -> Vec3 { + (self.turn.transpose() * crate::projection_preview::view_direction() / self.stretch).try_normalize().unwrap_or(Vec3::Z) + } +} diff --git a/crates/ui-egui/src/round_gizmo.rs b/crates/ui-egui/src/round_gizmo.rs new file mode 100644 index 00000000..146cd50f --- /dev/null +++ b/crates/ui-egui/src/round_gizmo.rs @@ -0,0 +1,885 @@ +//! The selected tri-planar, spherical or cylindrical fill shows its projector round the whole model: a dashed box, sphere or cylinder with the centre square, X/Y/Z arrows and turn rings, and size handles: a dot scales it evenly (or a cylinder across its axis), a double arrow stretches it along one direction. Only a press on one of those handles moves it: any other drag paints or turns the camera + +use egui::{Color32, Pos2, Rect, Stroke, Ui}; +use serde_json::{Value, json}; +use texturecraft_engine::compose::pattern::{cylinder_axis_index, mesh_frame, nonzero_stretch, projector_stretch}; +use texturecraft_engine::core::Projection; +use texturecraft_engine::geom::glam::{EulerRot, Mat3, Quat, Vec2, Vec3}; +use texturecraft_engine::layer_cmds::signed_scale; + +use crate::TextureCraftApp; +use crate::frame_gizmo::{ + ARROW, EDGE_ON_FACING, HANDLE_EDGE, MIN_HANDLE_REACH, MIN_SCREEN_SPAN, TURN_RING, arrow_distance, center_distance, dashed_outline, distance_to_segment, + handle_dot, move_handles, nearest, ring_open, +}; +use crate::move_on_model::MoveOnModel; +use crate::projection_gizmo::{Gizmo, dragging}; +use crate::theme::{AXIS_COLORS, SHAFT_HALO, SHAFT_HALO_EXTRA_WIDTH, SHAFT_WIDTH, Tokens}; +use crate::viewport::{project, view_ray}; + +mod round_grab; +mod shape; +mod size_handle; + +pub(crate) use round_grab::RoundGrab; +use shape::Shape; +pub(crate) use size_handle::SizeHandle; + +/// The projector of the fill Move on model moves, as the 3D view shows it +#[derive(Clone, Debug)] +pub(crate) struct RoundGizmo { + pub(crate) target: MoveOnModel, + /// Mesh centre and radius: the projector reads positions around it in radii + mesh_center: Vec3, + radius: f32, + /// The projector's turn and per-axis scale (a mirrored axis keeps its sign, as the projection reads it) + turn: Mat3, + stretch: Vec3, + /// The projection's centre in the projector's units, and what offset puts it there (offset = -local × this) + local: Vec3, + offset_per_local: f32, + /// On screen: the centre, the arrow tips, the turn rings, the dashed outline and the size handles + pub center: Pos2, + pub arrows: [Option; 3], + pub rings: [Vec; 3], + outline: Vec>, + pub sizes: Vec, + /// Screen movement per world unit along each projector direction at the centre + steps: [Option; 3], +} + +/// How far round the model each shape reaches, in the mesh's half sizes: the box, the sphere, the cylinder's radius and half height +pub(crate) const BOX_REACH: f32 = 1.08; +pub(crate) const SPHERE_REACH: f32 = 1.2; +pub(crate) const CYLINDER_REACH: f32 = 1.1; +pub(crate) const CYLINDER_HEIGHT: f32 = 1.15; +/// The size dots' radius (points) +const SIZE_DOT: f32 = 7.0; +/// A size double arrow's half length, tip to middle, and its heads' length and half width (points) +const SIZE_ARROW: f32 = 12.0; +const SIZE_ARROW_HEAD: f32 = 7.0; +const SIZE_ARROW_HEAD_HALF_WIDTH: f32 = 5.0; +/// How far from the centre a box face's double arrow must land on screen to show: nearer, the face is seen head on and its arrow would sit on the centre square +const FACE_CLEARANCE: f32 = 40.0; +/// Points on a drawn circle +pub(crate) const CIRCLE_POINTS: usize = 48; +/// A box's corners, and the bit of a corner's index that flips it along each axis +const BOX_CORNERS: usize = 8; +const BOX_AXIS_BITS: [usize; 3] = [1, 2, 4]; +/// How far along each direction its screen step is measured, in mesh radii: half way out, inside the model, where perspective bends it little +const STEP_PROBE_RADII: f32 = 0.5; + +impl RoundGizmo { + /// The projector as the 3D view shows it: none while the Projection row's eye hides the projection gizmos + pub(crate) fn shown(app: &TextureCraftApp, rect: Rect) -> Option { + RoundGizmo::of(app, rect).filter(|_| app.session.doc.project.display.projection_gizmos) + } + + /// The projector of the selected tri-planar, spherical or cylindrical fill + pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option { + if app.ui.mode != crate::state::Mode::Painting { + return None; + } + + let target = MoveOnModel::selected(app)?; + let (shape, offset, projector, offset_per_local) = match target.projection(app)? { + Projection::Triplanar { scale, offset, projector, .. } => (Shape::Box, offset, projector, scale), + Projection::Spherical { offset, projector, .. } => (Shape::Sphere, offset, projector, 1.0), + Projection::Cylindrical { axis, offset, projector, .. } => (Shape::Cylinder(cylinder_axis_index(axis)), offset, projector, 1.0), + _ => return None, + }; + + let (lower, upper) = app.session.mesh.bounds(); + let (mesh_center, radius) = mesh_frame((lower, upper)); + let [x, y, z] = projector.rotation.map(f32::to_radians); + let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x); + let stretch = projector_stretch(&projector); + let offset_per_local = nonzero_stretch(offset_per_local); + let local = -Vec3::from(offset) / offset_per_local; + let mut gizmo = RoundGizmo { + target, + mesh_center, + radius, + turn, + stretch, + local, + offset_per_local, + center: Pos2::ZERO, + arrows: [None; 3], + rings: Default::default(), + outline: Vec::new(), + sizes: Vec::new(), + steps: [None; 3], + }; + let origin = gizmo.world(local); + if !origin.is_finite() { + return None; + } + + gizmo.center = project(app, rect, origin)?; + gizmo.move_and_turn_handles(app, rect, origin)?; + + // The shape, sized round the mesh in the projector's units; a size handle past the view's edge waits at the edge, where it can be grabbed + let at = |point: Vec3| project(app, rect, mesh_center + turn * (stretch * point) * radius); + let view = rect.shrink(SIZE_ARROW); + let half = (upper - lower) * 0.5 / radius; + let forward = app.session.camera.forward(); + + // The view direction in the projector's units: what faces the camera there + let facing = (turn.transpose() * forward / stretch).try_normalize().unwrap_or(Vec3::Z); + match shape { + Shape::Box => gizmo.box_handles(at, half * BOX_REACH, forward, view), + Shape::Sphere => gizmo.sphere_handles(at, half.max_element() * SPHERE_REACH, facing, view), + Shape::Cylinder(axis) => gizmo.cylinder_handles(at, axis, half, facing, view), + } + Some(gizmo) + } + + /// The arrows along the projector's turned directions and the rings that turn round them, each ring seen too near edge on left out (empty: neither drawn nor grabbed) + fn move_and_turn_handles(&mut self, app: &TextureCraftApp, rect: Rect, origin: Vec3) -> Option<()> { + let center = self.center; + let directions = self.directions(); + let reach = self.radius * STEP_PROBE_RADII; + self.steps = directions.map(|direction| Some((project(app, rect, origin + direction * reach)? - center) / reach)); + self.arrows = self.steps.map(|step| step.filter(|step| step.length() * reach > MIN_SCREEN_SPAN).map(|step| center + step.normalized() * ARROW)); + + let right = app.session.camera.forward().cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); + let pixels = (project(app, rect, origin + right * reach)? - center).length() / reach; + let ring = TURN_RING / pixels.max(f32::MIN_POSITIVE); + self.rings = directions.map(|direction| { + if !ring_open(app, rect, center, direction) { + return Vec::new(); + } + + let (tangent, bitangent) = direction.any_orthonormal_pair(); + circle(|unit| project(app, rect, origin + (tangent * unit.x + bitangent * unit.y) * ring)) + }); + Some(()) + } + + /// A box of half size `size`: its edges, a dot on the corner up and right on screen that scales it evenly, and a double arrow on each face turned towards the camera that stretches it along that direction + fn box_handles(&mut self, at: impl Fn(Vec3) -> Option, size: Vec3, forward: Vec3, view: Rect) { + let local = self.local; + let corner = |index: usize| local + size * box_corner(index); + for (first_corner, second_corner) in box_edges() { + if let (Some(from), Some(to)) = (at(corner(first_corner)), at(corner(second_corner))) { + self.outline.push(vec![from, to]); + } + } + + let corners = (0..BOX_CORNERS).filter_map(|index| at(corner(index))); + if let Some(top_right) = corners.max_by(|first, second| (first.x - first.y).total_cmp(&(second.x - second.y))) { + self.sizes.push(SizeHandle { at: kept_in(view, top_right), axes: [true; 3], along: None }); + } + for (axis, direction) in self.directions().iter().enumerate() { + // The face toward the camera, on the other side in the projector's units when a mirrored axis flips it + let facing_side = if direction.dot(forward) > 0.0 { -1.0 } else { 1.0 }; + let toward = facing_side * self.stretch[axis].signum(); + let Some(face) = at(local + Vec3::AXES[axis] * size * toward) else { continue }; + let out = face - self.center; + if out.length() >= FACE_CLEARANCE { + self.sizes.push(SizeHandle { at: kept_in(view, face), axes: only_axis(axis), along: Some(out.normalized()) }); + } + } + } + + /// A sphere of `radius`: its silhouette across `facing` and its equator, and one dot on its right side (a sphere only scales evenly) + fn sphere_handles(&mut self, at: impl Fn(Vec3) -> Option, radius: f32, facing: Vec3, view: Rect) { + let local = self.local; + let (tangent, bitangent) = facing.any_orthonormal_pair(); + let silhouette = circle(|unit| at(local + (tangent * unit.x + bitangent * unit.y) * radius)); + if let Some(side) = silhouette.iter().copied().max_by(|first, second| first.x.total_cmp(&second.x)) { + self.sizes.push(SizeHandle { at: kept_in(view, side), axes: [true; 3], along: None }); + } + self.outline.push(silhouette); + self.outline.push(circle(|unit| at(local + Vec3::new(unit.x, 0.0, unit.y) * radius))); + } + + /// A cylinder round `axis` over a mesh of half sizes `half`: its caps and side lines, a double arrow on the top rim that stretches its height (seen end on, a dot) and a dot on its right side that scales it across (seen end on, on the rim's right) + fn cylinder_handles(&mut self, at: impl Fn(Vec3) -> Option, axis: usize, half: Vec3, facing: Vec3, view: Rect) { + let local = self.local; + let along = Vec3::AXES[axis]; + let (tangent, bitangent) = (Vec3::AXES[(axis + 1) % 3], Vec3::AXES[(axis + 2) % 3]); + let radius = (half * (Vec3::ONE - along)).max_element() * CYLINDER_REACH; + let half_height = half[axis] * CYLINDER_HEIGHT; + let cap = |height: f32| circle(|unit| at(local + along * height + (tangent * unit.x + bitangent * unit.y) * radius)); + let top = cap(half_height); + let along_axis = match (at(local + along * half_height), at(local - along * half_height)) { + (Some(top), Some(bottom)) => Some(top - bottom).filter(|span| span.length() > MIN_SCREEN_SPAN).map(egui::Vec2::normalized), + _ => None, + }; + if let Some(rim) = top.iter().copied().min_by(|first, second| first.y.total_cmp(&second.y)) { + self.sizes.push(SizeHandle { at: kept_in(view, rim), axes: only_axis(axis), along: along_axis }); + } + let right_of_rim = top.iter().copied().max_by(|first, second| first.x.total_cmp(&second.x)); + self.outline.extend([top, cap(-half_height)]); + + // The two side lines, where the round side turns away from the camera; seen end on there are none, and the dot sits on the rim's right + let side = along.cross(facing - along * facing.dot(along)).try_normalize(); + let mut sides = Vec::new(); + for edge in side.into_iter().flat_map(|side| [side, -side]) { + if let (Some(top), Some(bottom)) = (at(local + edge * radius + along * half_height), at(local + edge * radius - along * half_height)) { + self.outline.push(vec![top, bottom]); + sides.push(top.lerp(bottom, 0.5)); + } + } + let across_at = match side { + Some(_) => sides.into_iter().max_by(|first, second| first.x.total_cmp(&second.x)), + None => right_of_rim, + }; + if let Some(side) = across_at { + let mut across = [true; 3]; + across[axis] = false; + self.sizes.push(SizeHandle { at: kept_in(view, side), axes: across, along: None }); + } + } + + /// A point in the projector's units, in the world + fn world(&self, local: Vec3) -> Vec3 { + self.mesh_center + self.turn * (self.stretch * local) * self.radius + } + + /// The projector's turned X, Y and Z directions in the world + fn directions(&self) -> [Vec3; 3] { + Vec3::AXES.map(|axis| self.turn * axis) + } + + /// The `layer.fill.projection` params that slide the projector across the view from `from` to `to`, as its centre square does + pub(crate) fn slid(&self, app: &TextureCraftApp, rect: Rect, from: Pos2, to: Pos2) -> Option { + self.params(app, rect, RoundGrab::Slide, from, to) + } + + /// The `layer.fill.projection` params a drag of `grab` from `from` to `to` sets; only a size handle sets the scale, so a mirrored axis keeps its sign through a slide or turn + fn params(&self, app: &TextureCraftApp, rect: Rect, grab: RoundGrab, from: Pos2, to: Pos2) -> Option { + let origin = self.world(self.local); + let (turn, stretch, center) = match grab { + RoundGrab::Slide => { + let forward = app.session.camera.forward(); + let moved = on_view_plane(app, rect, origin, forward, to)? - on_view_plane(app, rect, origin, forward, from)?; + (self.turn, self.stretch, origin + moved) + } + RoundGrab::Axis(axis) => { + let step = (*self.steps.get(axis)?)?; + let distance = (to - from).dot(step) / step.length_sq().max(f32::MIN_POSITIVE); + (self.turn, self.stretch, origin + self.directions()[axis] * distance) + } + RoundGrab::Ring(axis) => { + let angle = (to - self.center).angle() - (from - self.center).angle(); + + // Seen from the side its direction points to, a turn runs the other way round on screen + let facing = self.directions()[axis].dot(app.session.camera.forward()); + let angle = if facing < 0.0 { -angle } else { angle }; + let turn = self.turn * Mat3::from_axis_angle(Vec3::AXES[axis], angle); + (turn, self.stretch, origin) + } + RoundGrab::Size(axes) => { + // How far the pointer went along the line from the centre through where the handle was grabbed (past the centre, none: a drag never flips it); the command keeps each axis's size in its limits on its own side, so does the offset worked out here + let reach = from - self.center; + let factor = ((to - self.center).dot(reach) / reach.length().max(MIN_HANDLE_REACH).powi(2)).max(0.0); + let stretch = Vec3::from(axes.map(|on| if on { factor } else { 1.0 })) * self.stretch; + (self.turn, stretch.map(signed_scale), origin) + } + }; + + // The centre stays where it was put: the offset follows the turn and scale + let local = turn.transpose() * ((center - self.mesh_center) / self.radius) / stretch; + let offset = -local * self.offset_per_local; + let (z, y, x) = Quat::from_mat3(&turn).to_euler(EulerRot::ZYX); + let rotation = [x, y, z].map(f32::to_degrees); + let values = [offset.to_array(), rotation, stretch.to_array()]; + if !values.iter().flatten().all(|value| value.is_finite()) { + return None; + } + + let mut params = self.target.target(); + params["offset"] = json!(offset.to_array()); + params["projectorRotation"] = json!(rotation); + if matches!(grab, RoundGrab::Size(_)) { + params["projectorScale"] = json!(stretch.to_array()); + } + Some(params) + } +} + +impl Gizmo for RoundGizmo { + type Grab = RoundGrab; + + fn drag_id() -> egui::Id { + egui::Id::unique("tc_round_drag") + } + + /// The handle under screen point `p`: the nearest one within reach (where rings cross, the nearest ring) + fn grab(&self, at: Pos2) -> Option { + let mut handles = vec![(RoundGrab::Slide, center_distance(self.center, at))]; + handles.extend((0..3).filter_map(|axis| Some((RoundGrab::Axis(axis), arrow_distance(at, self.center, self.arrows[axis]?))))); + handles.extend(self.sizes.iter().map(|size| (RoundGrab::Size(size.axes), size.distance(at)))); + let distance = |ring: &Vec| ring.windows(2).map(|pair| distance_to_segment(at, pair[0], pair[1])).fold(f32::INFINITY, f32::min); + handles.extend((0..3).map(|axis| (RoundGrab::Ring(axis), distance(&self.rings[axis])))); + nearest(handles) + } + + fn same_projection(&self, other: &RoundGizmo) -> bool { + self.target == other.target + } + + fn edit(&self, app: &TextureCraftApp, rect: Rect, grab: RoundGrab, from: Pos2, to: Pos2) -> Option<(&'static str, Value)> { + Some(("layer.fill.projection", self.params(app, rect, grab, from, to)?)) + } + + /// A size handle's resize cursor runs along its arrow + fn cursor(&self, grab: RoundGrab, dragging: bool) -> egui::CursorIcon { + match grab { + RoundGrab::Slide if dragging => egui::CursorIcon::Grabbing, + RoundGrab::Slide => egui::CursorIcon::Grab, + RoundGrab::Axis(_) | RoundGrab::Ring(_) => egui::CursorIcon::Move, + RoundGrab::Size(axes) => self.sizes.iter().find(|size| size.axes == axes).map_or(egui::CursorIcon::ResizeNeSw, SizeHandle::cursor), + } + } +} + +/// A size handle that stretches one way: a double arrow through `at` along `along`, `fill` over a dark halo like the axis arrows +fn size_arrow(painter: &egui::Painter, at: Pos2, along: egui::Vec2, fill: Color32) { + let side = along.rot90() * SIZE_ARROW_HEAD_HALF_WIDTH; + let shaft = [at - along * (SIZE_ARROW - SIZE_ARROW_HEAD), at + along * (SIZE_ARROW - SIZE_ARROW_HEAD)]; + painter.line_segment(shaft, Stroke::new(SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH, SHAFT_HALO)); + painter.line_segment(shaft, Stroke::new(SHAFT_WIDTH, fill)); + for direction in [along, -along] { + let base = at + direction * (SIZE_ARROW - SIZE_ARROW_HEAD); + painter.add(egui::Shape::convex_polygon(vec![at + direction * SIZE_ARROW, base + side, base - side], fill, HANDLE_EDGE)); + } +} + +/// Corner `index` of a box from -1 to 1: the index's three low bits pick its low (0) or high (1) side along X, Y and Z +pub(crate) fn box_corner(index: usize) -> Vec3 { + let side = |bit: usize| if index & bit == 0 { -1.0 } else { 1.0 }; + Vec3::new(side(BOX_AXIS_BITS[0]), side(BOX_AXIS_BITS[1]), side(BOX_AXIS_BITS[2])) +} + +/// A box's twelve edges as pairs of corner indices, each once: from a corner on an axis's low side to the corner across that axis +pub(crate) fn box_edges() -> impl Iterator { + (0..BOX_CORNERS).flat_map(|corner| BOX_AXIS_BITS.into_iter().filter(move |bit| corner & bit == 0).map(move |bit| (corner, corner | bit))) +} + +/// Which projector directions a handle along `axis` alone works on +fn only_axis(axis: usize) -> [bool; 3] { + let mut axes = [false; 3]; + axes[axis] = true; + axes +} + +/// `point` kept inside `view`, where a handle past its edge can still be grabbed +fn kept_in(view: Rect, point: Pos2) -> Pos2 { + point.clamp(view.min, view.max) +} + +/// A closed circle of screen points from `at` (given the unit circle's points); empty when a point is off screen +fn circle(at: impl Fn(Vec2) -> Option) -> Vec { + (0..=CIRCLE_POINTS) + .map(|index| { + let angle = index as f32 / CIRCLE_POINTS as f32 * std::f32::consts::TAU; + at(Vec2::new(angle.cos(), angle.sin())) + }) + .collect::>>() + .unwrap_or_default() +} + +/// Where screen point `p` meets the plane facing the camera through `origin` +fn on_view_plane(app: &TextureCraftApp, rect: Rect, origin: Vec3, forward: Vec3, p: Pos2) -> Option { + let ray = view_ray(app, rect, p); + let facing = ray.dir.dot(forward); + if facing.abs() < EDGE_ON_FACING { + return None; + } + + let hit = ray.origin + ray.dir * ((origin - ray.origin).dot(forward) / facing); + hit.is_finite().then_some(hit) +} + +/// The projector over the 3D view: dashed shape, rings, arrows, centre square and dots, the handle under the pointer lit +pub(crate) fn overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, gizmo: &RoundGizmo) { + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter_at(rect); + let active = dragging::(ui.ctx()).map(|drag| drag.grab); + + // A held Move on model button lights none + let hovered = ui.ctx().pointer_hover_pos().filter(|hover| rect.contains(*hover) && app.moving_on_model.is_none()).and_then(|hover| gizmo.grab(hover)); + let lit = |grab: RoundGrab| active == Some(grab) || (active.is_none() && hovered == Some(grab)); + let fill = |grab: RoundGrab| if lit(grab) { tokens.viewport_accent } else { Color32::WHITE }; + let axis_color = |axis: usize, grab: RoundGrab| if lit(grab) { tokens.viewport_accent } else { AXIS_COLORS[axis] }; + for line in &gizmo.outline { + dashed_outline(&painter, line); + } + for (axis, ring) in gizmo.rings.iter().enumerate() { + painter.add(egui::Shape::line(ring.clone(), Stroke::new(SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH, SHAFT_HALO))); + painter.add(egui::Shape::line(ring.clone(), Stroke::new(SHAFT_WIDTH, axis_color(axis, RoundGrab::Ring(axis))))); + } + for size in &gizmo.sizes { + let color = fill(RoundGrab::Size(size.axes)); + match size.along { + Some(along) => size_arrow(&painter, size.at, along, color), + None => handle_dot(&painter, size.at, SIZE_DOT, color), + } + } + move_handles(&painter, gizmo.center, gizmo.arrows, |axis| axis_color(axis, RoundGrab::Axis(axis)), fill(RoundGrab::Slide)); +} + +#[cfg(test)] +pub(crate) mod tests { + use egui::{Modifiers, PointerButton, vec2}; + use texturecraft_engine::core::{Fill, LayerId, LayerKind, Projection, Projector}; + + use super::*; + + fn gizmo(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> RoundGizmo { + RoundGizmo::of(harness.state(), harness.state().viewport_rect).unwrap() + } + + fn projector_and_offset(projection: &Projection) -> (Projector, [f32; 3]) { + match projection { + Projection::Triplanar { projector, offset, .. } + | Projection::Spherical { projector, offset, .. } + | Projection::Cylindrical { projector, offset, .. } => (*projector, *offset), + other => panic!("a round projection: {other:?}"), + } + } + + #[test] + fn round_projections_show_their_projector_while_their_fill_is_selected() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for kind in ["triplanar", "spherical", "cylindrical"] { + let (mut harness, _) = fill_app(kind); + harness.run_steps(2); + let shown = gizmo(&harness); + assert!(shown.arrows.iter().all(Option::is_some) && shown.rings.iter().all(|ring| ring.len() > 8), "{kind}: arrows and rings {shown:?}"); + assert!(!shown.outline.is_empty(), "{kind}: its shape is drawn"); + + // A box's corner and a double arrow per face (the ball is seen from above and aside, no face head on); a sphere's one dot; a cylinder's top rim and side + let size_handles = match kind { + "triplanar" => 4, + "spherical" => 1, + _ => 2, + }; + assert_eq!(shown.sizes.len(), size_handles, "{kind}: size handles {:?}", shown.sizes); + } + let (harness, _) = fill_app("planar"); + assert!(RoundGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "planar projections show their frame instead"); + } + + #[test] + fn a_cylinder_axis_past_z_shows_round_y_as_the_compositor_wraps_it() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app_with(json!({"projection": "cylindrical", "axis": 1})); + let round_y = gizmo(&harness).outline; + + // A hand-edited project can store an axis past Z: no command writes one + let stored = &mut harness.state_mut().session.doc.project.layer_mut(layer).unwrap().kind; + let LayerKind::Fill(Fill { projection: Projection::Cylindrical { axis, .. }, .. }) = stored else { panic!("a cylindrical fill") }; + *axis = 3; + assert_eq!(gizmo(&harness).outline, round_y); + } + + #[test] + fn the_arrows_move_the_rings_turn_and_the_dots_scale_the_projector_one_step_per_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("spherical"); + let steps = harness.state().session.history_labels().len(); + + let start = gizmo(&harness); + let tip = start.arrows[0].unwrap(); + drag(&mut harness, tip, tip + (tip - start.center).normalized() * 30.0, Modifiers::NONE); + let (projector, offset) = projector_and_offset(&projection(&harness, layer)); + assert!(offset[0] < -0.05 && offset[1].abs() < 1e-3 && offset[2].abs() < 1e-3, "the X arrow moves the centre along X: {offset:?}"); + assert_eq!(projector.rotation, [0.0; 3]); + let moved = gizmo(&harness); + assert!(moved.center.x > start.center.x + 20.0, "the centre follows: {moved:?}"); + + // The Z ring (seen face on) turns it round Z; the centre stays where it is + let clear = |p: &&Pos2| moved.rings[..2].iter().flatten().map(|other| other.distance(**p)).fold(f32::INFINITY, f32::min); + let on_ring = *moved.rings[2].iter().max_by(|a, b| clear(a).total_cmp(&clear(b))).unwrap(); + assert_eq!(moved.grab(on_ring), Some(RoundGrab::Ring(2))); + drag(&mut harness, on_ring, moved.center + (on_ring - moved.center).rot90(), Modifiers::NONE); + let (turned, _) = projector_and_offset(&projection(&harness, layer)); + assert!(turned.rotation[2].abs() > 30.0 && turned.rotation[0].abs() < 1e-2, "{:?}", turned.rotation); + assert!(gizmo(&harness).center.distance(moved.center) < 1.0, "turning keeps the centre"); + + let scaling = gizmo(&harness); + let dot = scaling.sizes.iter().find(|size| size.axes == [true; 3]).expect("the even-scale dot").at; + let center = scaling.center; + assert_eq!(gizmo(&harness).grab(dot), Some(RoundGrab::Size([true; 3]))); + drag(&mut harness, dot, center + (dot - center) * 1.5, Modifiers::NONE); + let (scaled, _) = projector_and_offset(&projection(&harness, layer)); + assert!(scaled.scale.iter().all(|scale| (scale - 1.5).abs() < 0.05), "the side dot scales it evenly: {:?}", scaled.scale); + assert!(gizmo(&harness).center.distance(center) < 1.0, "scaling keeps the centre"); + assert_eq!(harness.state().session.history_labels().len(), steps + 3, "one undo step per drag"); + } + + #[test] + fn a_cylinders_top_dot_stretches_its_height_and_a_tri_planar_box_moves_by_its_texture_offset() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("cylindrical"); + let cylinder = gizmo(&harness); + let height = cylinder.sizes.iter().find(|size| size.axes == [false, true, false]).expect("the height handle"); + let SizeHandle { at: top, axes, along } = *height; + assert_eq!(axes, [false, true, false], "the top handle works along the axis"); + let along = along.expect("the height handle is a double arrow"); + assert!(along.y.abs() > 0.99, "drawn upright, along the upright axis: {along:?}"); + assert_eq!(cylinder.cursor(RoundGrab::Size(axes), false), egui::CursorIcon::ResizeVertical); + drag(&mut harness, top, cylinder.center + (top - cylinder.center) * 0.5, Modifiers::NONE); + let (projector, _) = projector_and_offset(&projection(&harness, layer)); + assert!(projector.scale[1] < 0.7 && projector.scale[0] == 1.0 && projector.scale[2] == 1.0, "{:?}", projector.scale); + + let (mut harness, layer) = fill_app("triplanar"); + harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "scale": 4})).unwrap(); + harness.run_steps(2); + let box_gizmo = gizmo(&harness); + drag(&mut harness, box_gizmo.center, box_gizmo.center + vec2(0.0, -30.0), Modifiers::NONE); + let (_, offset) = projector_and_offset(&projection(&harness, layer)); + assert!(offset[1] < -0.1 && offset[0].abs() < 0.05, "sliding up shifts the texture by the tiling: {offset:?}"); + assert!(gizmo(&harness).center.distance(box_gizmo.center + vec2(0.0, -30.0)) < 1.5, "the centre sits under the pointer"); + } + + /// Every drag on the projector shows in the panel the same frame: its Offset, Rotation and Scale fields hold the projector's values and the preview square re-renders, every frame of the drag; one undo step per drag + #[test] + fn the_panel_and_its_preview_follow_every_frame_of_a_projector_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for kind in ["spherical", "cylindrical"] { + let (mut harness, layer) = fill_app(kind); + let steps = harness.state().session.history_labels().len(); + let read = |harness: &egui_kittest::Harness<'_, TextureCraftApp>| { + let (projector, offset) = projector_and_offset(&projection(harness, layer)); + let (row_offset, row_rotation, row_scale) = (panel_xyz(harness, "Offset"), panel_xyz(harness, "Rotation"), panel_xyz(harness, "Scale")); + for (row, field, value) in + [("Offset", row_offset, offset), ("Rotation", row_rotation, projector.rotation), ("Scale", row_scale, projector.scale)] + { + for axis in 0..3 { + assert!((field[axis] - value[axis]).abs() < 1e-3, "{kind}: the panel's {row} shows the projector's {value:?}, not {field:?}"); + } + } + }; + + // A sphere's one dot scales it evenly, a cylinder's height arrow stretches it along its axis + let start = gizmo(&harness); + let axes = if kind == "spherical" { [true; 3] } else { [false, true, false] }; + let dot = start.sizes.iter().find(|size| size.axes == axes).unwrap_or_else(|| panic!("{kind}: its size handle {axes:?}")).at; + drag_frames(&mut harness, layer, dot, start.center + (dot - start.center) * 1.5, Modifiers::NONE, true, read); + let tip = gizmo(&harness).arrows[0].unwrap(); + let center = gizmo(&harness).center; + drag_frames(&mut harness, layer, tip, tip + (tip - center).normalized() * 30.0, Modifiers::NONE, true, read); + let turned = gizmo(&harness); + let clear = |p: &&Pos2| turned.rings[..2].iter().flatten().map(|other| other.distance(**p)).fold(f32::INFINITY, f32::min); + let on_ring = *turned.rings[2].iter().max_by(|a, b| clear(a).total_cmp(&clear(b))).unwrap(); + drag_frames(&mut harness, layer, on_ring, turned.center + (on_ring - turned.center).rot90(), Modifiers::NONE, true, read); + let (projector, _) = projector_and_offset(&projection(&harness, layer)); + assert!( + projector.scale.iter().copied().fold(0.0, f32::max) > 1.3 && projector.rotation[2].abs() > 30.0, + "{kind}: resized and turned: {projector:?}" + ); + assert_eq!(harness.state().session.history_labels().len(), steps + 3, "{kind}: one undo step per drag"); + } + } + + /// Whether a projector drag is under way + fn round_dragging(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> bool { + dragging::(&harness.ctx).is_some() + } + + /// Losing the focus mid-drag (Alt+Tab) ends a projector drag as a release does: one undo step, and moves after it (egui still has the button down) leave the projector alone + #[test] + fn losing_the_window_focus_ends_a_projector_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("spherical"); + let steps = harness.state().session.history_labels().len(); + let center = gizmo(&harness).center; + let to = center + vec2(40.0, 0.0); + press_and_move(&mut harness, center, to, Modifiers::NONE); + assert!(round_dragging(&harness), "the centre square is held"); + + harness.event(egui::Event::WindowFocused(false)); + harness.run_steps(1); + let left = projection(&harness, layer); + assert!(!round_dragging(&harness), "the focus loss ends the drag"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "as one undo step"); + + for step in 1..=3 { + harness.event(egui::Event::PointerMoved(to + vec2(20.0, 10.0) * step as f32)); + harness.run_steps(1); + } + assert_eq!(projection(&harness, layer), left, "moves after it leave the projector where it was"); + } + + /// Alt pressed mid-drag hands the pointer to the camera and ends the projector drag where it is: let go of Alt with the button still down, the drag does not resume; one undo step + #[test] + fn alt_mid_drag_ends_a_projector_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("spherical"); + let steps = harness.state().session.history_labels().len(); + let center = gizmo(&harness).center; + let to = center + vec2(40.0, 0.0); + press_and_move(&mut harness, center, to, Modifiers::NONE); + let slid = projection(&harness, layer); + let camera = harness.state().session.camera; + + harness.event_modifiers(egui::Event::PointerMoved(to + vec2(20.0, 0.0)), Modifiers::ALT); + harness.run_steps(1); + assert_ne!(harness.state().session.camera, camera, "Alt turns the camera"); + assert!(!round_dragging(&harness), "and ends the projector drag"); + + for step in 2..=4 { + harness.event(egui::Event::PointerMoved(to + vec2(20.0, 5.0) * step as f32)); + harness.run_steps(1); + } + assert_eq!(projection(&harness, layer), slid, "Alt let go, the projector stays where the drag left it"); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step"); + } + + /// Seen edge on a ring is a line, whose screen-angle turn would jump half a turn across the centre: from straight in front (no yaw) the X ring is neither drawn nor grabbed while the Y and Z rings stay; turned aside, it opens and shows again + #[test] + fn a_ring_seen_edge_on_is_neither_drawn_nor_grabbed() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = fill_app("spherical"); + harness.state_mut().session.camera.yaw = 0.0; + harness.run_steps(2); + + let front = gizmo(&harness); + assert!(front.rings[0].is_empty(), "the X ring seen edge on is left out: {:?}", front.rings[0]); + assert!(front.rings[1..].iter().all(|ring| !ring.is_empty()), "the Y and Z rings show"); + let on_the_line = front.center + vec2(0.0, 40.0); + assert_ne!(front.grab(on_the_line), Some(RoundGrab::Ring(0)), "a press where its line would be does not grab it"); + + harness.state_mut().session.camera.yaw = 0.5; + harness.run_steps(2); + assert!(gizmo(&harness).rings.iter().all(|ring| !ring.is_empty()), "turned aside, every ring shows"); + } + + /// A point on the model clear of every handle of the shown gizmo + pub(crate) fn on_the_model_off_the_handles(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> Pos2 { + let app = harness.state(); + let rect = app.viewport_rect; + let round = RoundGizmo::of(app, rect); + let frame = crate::frame_gizmo::FrameGizmo::of(app, rect); + let clear = |p: Pos2| { + round.as_ref().is_none_or(|gizmo| gizmo.grab(p).is_none()) + && frame.as_ref().is_none_or(|gizmo| gizmo.grab(p).is_none()) + && app.session.pick(texturecraft_engine::geom::glam::Vec2::new(p.x - rect.left(), p.y - rect.top()), app.session.viewport).is_some() + }; + (1..12) + .flat_map(|ring| (0..16).map(move |step| rect.center() + egui::Vec2::angled(step as f32 / 16.0 * std::f32::consts::TAU) * (ring as f32 * 14.0))) + .find(|p| clear(*p) && clear(*p + vec2(30.0, 0.0))) + .expect("the model shows past the handles") + } + + /// A sphere has one size handle (it only scales evenly); a tri-planar box scales evenly from its corner and along one direction from a face's double arrow + #[test] + fn a_sphere_scales_from_one_dot_and_a_tri_planar_box_from_its_corner_and_faces() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("spherical"); + let start = gizmo(&harness); + assert_eq!(start.sizes.len(), 1, "one dot: {:?}", start.sizes); + let dot = start.sizes[0].at; + assert_eq!(start.grab(dot), Some(RoundGrab::Size([true; 3]))); + drag(&mut harness, dot, start.center + (dot - start.center) * 1.4, Modifiers::NONE); + let (scaled, _) = projector_and_offset(&projection(&harness, layer)); + assert!(scaled.scale.iter().all(|scale| (scale - 1.4).abs() < 0.08), "it scales evenly: {:?}", scaled.scale); + + let (mut harness, layer) = fill_app("triplanar"); + let start = gizmo(&harness); + let corner = start.sizes.iter().find(|size| size.axes == [true; 3]).expect("a corner dot").at; + drag(&mut harness, corner, start.center + (corner - start.center) * 1.25, Modifiers::NONE); + let (scaled, _) = projector_and_offset(&projection(&harness, layer)); + assert!(scaled.scale.iter().all(|scale| (scale - 1.25).abs() < 0.05), "the corner scales it evenly: {:?}", scaled.scale); + assert!(gizmo(&harness).center.distance(start.center) < 1.0, "scaling keeps the centre"); + + let box_gizmo = gizmo(&harness); + let across = *box_gizmo.sizes.iter().find(|size| size.axes == [true, false, false]).expect("an X face arrow"); + assert!(across.along.is_some_and(|along| along.x.abs() > 0.95), "it points across: {across:?}"); + assert_eq!( + box_gizmo.grab(across.at + across.along.unwrap_or_default() * (SIZE_ARROW - 1.0)), + Some(RoundGrab::Size([true, false, false])), + "grabbed from its tip" + ); + drag(&mut harness, across.at, box_gizmo.center + (across.at - box_gizmo.center) * 0.5, Modifiers::NONE); + let (stretched, _) = projector_and_offset(&projection(&harness, layer)); + assert!((stretched.scale[0] - scaled.scale[0] * 0.5).abs() < 0.05, "the X face halves it across: {:?}", stretched.scale); + assert!( + (stretched.scale[1] - scaled.scale[1]).abs() < 1e-4 && (stretched.scale[2] - scaled.scale[2]).abs() < 1e-4, + "and only across: {:?}", + stretched.scale + ); + } + + /// A projector a project file mirrors along X (a negative scale, as the projection reads it) reads mirrored in the gizmo and stays mirrored through a slide, a move along an arrow, a turn and a resize + #[test] + fn a_mirrored_projector_keeps_its_mirror_through_every_handle() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("spherical"); + let mirrored = [-1.0, 1.0, 1.0]; + match &mut harness.state_mut().session.doc.project.layer_mut(layer).unwrap().kind { + texturecraft_engine::core::LayerKind::Fill(fill) => match &mut fill.projection { + Projection::Spherical { projector, .. } => projector.scale = mirrored, + other => panic!("a spherical projection: {other:?}"), + }, + other => panic!("a fill layer: {other:?}"), + } + harness.run_steps(2); + + let start = gizmo(&harness); + assert_eq!(start.stretch, Vec3::from(mirrored), "the gizmo reads the mirror as the projection does"); + drag(&mut harness, start.center, start.center + vec2(30.0, -20.0), Modifiers::NONE); + let (slid, offset) = projector_and_offset(&projection(&harness, layer)); + assert_eq!(slid.scale, mirrored, "a slide keeps the mirror"); + assert!(offset.iter().any(|axis| axis.abs() > 0.05), "and slides it: {offset:?}"); + + let tip = gizmo(&harness).arrows[1].unwrap(); + let center = gizmo(&harness).center; + drag(&mut harness, tip, tip + (tip - center).normalized() * 20.0, Modifiers::NONE); + assert_eq!(projector_and_offset(&projection(&harness, layer)).0.scale, mirrored, "so does a move along an arrow"); + + let before_turn = projector_and_offset(&projection(&harness, layer)).0; + let ring = gizmo(&harness).rings[2].clone(); + drag(&mut harness, ring[CIRCLE_POINTS / 8], ring[CIRCLE_POINTS / 8 + 3], Modifiers::NONE); + let turned = projector_and_offset(&projection(&harness, layer)).0; + assert_ne!(turned.rotation, before_turn.rotation, "the ring turns it"); + assert_eq!(turned.scale, mirrored, "and keeps the mirror"); + + let resized = gizmo(&harness); + let dot = resized.sizes.iter().find(|size| size.axes == [true; 3]).expect("the even-scale dot").at; + drag(&mut harness, dot, resized.center + (dot - resized.center) * 1.5, Modifiers::NONE); + let scale = projector_and_offset(&projection(&harness, layer)).0.scale; + let expected = [-1.5, 1.5, 1.5]; + assert!(scale.iter().zip(expected).all(|(axis, wanted)| (axis - wanted).abs() < 1e-3), "a resize scales it evenly, still mirrored: {scale:?}"); + } + + /// A box mirrored along X (a negative scale from a project file) keeps its X double arrow on the face toward the camera, where the unmirrored box shows it + #[test] + fn a_mirrored_box_keeps_its_face_arrow_toward_the_camera() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("triplanar"); + let x_face_arrow = |harness: &egui_kittest::Harness<'_, TextureCraftApp>| { + gizmo(harness).sizes.iter().find(|size| size.axes == [true, false, false]).map(|size| size.at) + }; + let unmirrored = x_face_arrow(&harness).expect("an X face arrow"); + match &mut harness.state_mut().session.doc.project.layer_mut(layer).unwrap().kind { + LayerKind::Fill(fill) => match &mut fill.projection { + Projection::Triplanar { projector, .. } => projector.scale = [-1.0, 1.0, 1.0], + other => panic!("a tri-planar projection: {other:?}"), + }, + other => panic!("a fill layer: {other:?}"), + } + harness.run_steps(2); + + let mirrored = x_face_arrow(&harness).expect("the mirrored box's X face arrow"); + assert!(mirrored.distance(unmirrored) < 0.5, "the arrow stays on the near face: {mirrored:?}, unmirrored {unmirrored:?}"); + } + + /// The pointer over a handle shows what it does only while the gizmo takes input: with Alt held the camera orbits, and the handle's cursor is not shown + #[test] + fn alt_over_a_handle_shows_no_handle_cursor() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = fill_app("triplanar"); + let center = gizmo(&harness).center; + harness.hover_at(center); + harness.run_steps(2); + assert_eq!(harness.output().platform_output.cursor_icon, egui::CursorIcon::Grab, "the centre square shows it slides"); + + harness.event(egui::Event::ModifiersChanged(Modifiers::ALT)); + harness.event(egui::Event::PointerMoved(center + vec2(1.0, 0.0))); + harness.run_steps(2); + assert_ne!(harness.output().platform_output.cursor_icon, egui::CursorIcon::Grab, "with Alt held it does not"); + harness.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(2); + } + + /// A tri-planar fill selected while the quick mask is edited with the Paint tool: brushes act and the projector shows + fn quick_mask_paint_app() -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) { + let (mut harness, layer) = fill_app("triplanar"); + harness.state_mut().run("viewport.quickMask", json!({"enabled": true})).unwrap(); + harness.state_mut().run("viewport.quickMask.edit", json!({"editing": true})).unwrap(); + harness.state_mut().session.tool.tool = texturecraft_engine::Tool::Paint; + harness.run_steps(2); + assert!(gizmo(&harness).sizes.len() > 1, "the projector shows"); + (harness, layer) + } + + /// A Ctrl+drag that starts on a handle changes the brush only: the projector stays where it is + #[test] + fn a_ctrl_drag_on_a_handle_changes_the_brush_and_not_the_projection() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = quick_mask_paint_app(); + let before = projection(&harness, layer); + let flow = harness.state().session.tool.brush.flow; + let center = gizmo(&harness).center; + + harness.event(egui::Event::ModifiersChanged(Modifiers::COMMAND)); + drag(&mut harness, center, center + vec2(-40.0, 0.0), Modifiers::COMMAND); + harness.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(2); + assert_ne!(harness.state().session.tool.brush.flow, flow, "the drag changes the brush"); + assert_eq!(projection(&harness, layer), before, "and leaves the projection"); + } + + /// A press on a handle's edge that drifts just off it before release (still a click) is the handle's: it paints no dab + #[test] + fn a_click_that_drifts_off_a_handle_paints_nothing() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = quick_mask_paint_app(); + let shown = gizmo(&harness); + let rect = harness.state().viewport_rect; + let on_model = |p: Pos2| { + harness + .state() + .session + .pick(texturecraft_engine::geom::glam::Vec2::new(p.x - rect.left(), p.y - rect.top()), harness.state().session.viewport) + .is_some() + }; + let drift = 2.0; + + // The centre square's last point along some direction whose point a drift further is off every handle and on the model + let (edge, off) = (0..16) + .filter_map(|step| { + let toward = egui::Vec2::angled(step as f32 / 16.0 * std::f32::consts::TAU); + let edge = (0..200).map(|half| shown.center + toward * (half as f32 * 0.5)).take_while(|p| shown.grab(*p).is_some()).last()?; + let off = edge + toward * drift; + (shown.grab(off).is_none() && on_model(off)).then_some((edge, off)) + }) + .next() + .expect("a handle edge on the model"); + let click = |harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2| { + harness.hover_at(from); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(egui::Event::PointerMoved(to)); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + }; + + let painted = harness.state().session.quick_mask.revision; + click(&mut harness, edge, off); + assert_eq!(harness.state().session.quick_mask.revision, painted, "a press that began on the handle paints no dab"); + + // The same click a little past the handle paints + click(&mut harness, off, off + (off - edge)); + assert_ne!(harness.state().session.quick_mask.revision, painted, "a press off the handle paints"); + } + + /// A cylinder seen straight down its axis keeps the dot that scales it across, on its rim's right + #[test] + fn a_cylinder_seen_end_on_keeps_its_across_dot() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app_with(json!({"projection": "cylindrical", "axis": 2})); + harness.state_mut().session.camera.yaw = 0.0; + harness.state_mut().session.camera.pitch = 0.0; + harness.run_steps(2); + + let end_on = gizmo(&harness); + let across = [true, true, false]; + let dot = end_on.sizes.iter().find(|size| size.axes == across).unwrap_or_else(|| panic!("the across dot: {:?}", end_on.sizes)).at; + assert_eq!(end_on.grab(dot), Some(RoundGrab::Size(across))); + drag(&mut harness, dot, end_on.center + (dot - end_on.center) * 1.5, Modifiers::NONE); + let (projector, _) = projector_and_offset(&projection(&harness, layer)); + assert!(projector.scale[0] > 1.2 && projector.scale[1] > 1.2 && projector.scale[2] == 1.0, "it scales across only: {:?}", projector.scale); + } +} diff --git a/crates/ui-egui/src/round_gizmo/round_grab.rs b/crates/ui-egui/src/round_gizmo/round_grab.rs new file mode 100644 index 00000000..321c7b20 --- /dev/null +++ b/crates/ui-egui/src/round_gizmo/round_grab.rs @@ -0,0 +1,12 @@ +/// What a drag on the projector does +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum RoundGrab { + /// The centre square: slide it across the view + Slide, + /// Along the projector's X (0), Y (1) or Z (2) direction + Axis(usize), + /// Turn it round its X, Y or Z direction + Ring(usize), + /// A size dot: scale it along the directions marked + Size([bool; 3]), +} diff --git a/crates/ui-egui/src/round_gizmo/shape.rs b/crates/ui-egui/src/round_gizmo/shape.rs new file mode 100644 index 00000000..3cd4ebd8 --- /dev/null +++ b/crates/ui-egui/src/round_gizmo/shape.rs @@ -0,0 +1,8 @@ +/// Which shape the projector shows +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Shape { + Box, + Sphere, + /// Round the axis 0, 1 or 2 + Cylinder(usize), +} diff --git a/crates/ui-egui/src/round_gizmo/size_handle.rs b/crates/ui-egui/src/round_gizmo/size_handle.rs new file mode 100644 index 00000000..f2f3c57f --- /dev/null +++ b/crates/ui-egui/src/round_gizmo/size_handle.rs @@ -0,0 +1,33 @@ +use egui::Pos2; + +use super::SIZE_ARROW; +use crate::frame_gizmo::distance_to_segment; + +/// A handle that resizes the projector +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct SizeHandle { + pub at: Pos2, + /// The projector directions it scales + pub axes: [bool; 3], + /// A double arrow's direction on screen; None for a dot + pub along: Option, +} + +impl SizeHandle { + /// How far screen point `p` is from the handle (a double arrow: from anywhere along it) + pub(super) fn distance(&self, p: Pos2) -> f32 { + match self.along { + Some(along) => distance_to_segment(p, self.at - along * SIZE_ARROW, self.at + along * SIZE_ARROW), + None => self.at.distance(p), + } + } + + /// The resize cursor along its arrow, or a diagonal one for a dot + pub(super) fn cursor(&self) -> egui::CursorIcon { + match self.along { + Some(along) if along.y.abs() >= along.x.abs() => egui::CursorIcon::ResizeVertical, + Some(_) => egui::CursorIcon::ResizeHorizontal, + None => egui::CursorIcon::ResizeNeSw, + } + } +} From d31604cc97b9e0d191f3b1a167fccdefbcb8a057 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:28:49 +0000 Subject: [PATCH 11/17] Properties: the panel keeps its scroll place per layer, titles an effect by its type, and an empty panel shows its note --- crates/engine/src/session.rs | 2 +- crates/ui-egui/src/dock.rs | 57 ++++++++++++++----- crates/ui-egui/src/lib.rs | 5 ++ crates/ui-egui/src/widgets.rs | 16 ++++++ crates/ui-egui/tests/it/empty_start.rs | 13 ++++- crates/ui-egui/tests/it/layer_multi_select.rs | 11 ++++ crates/ui-egui/tests/it/layers_panel.rs | 10 +++- crates/ui-egui/tests/it/main.rs | 49 ++++++++++++++++ crates/ui-egui/tests/it/tool_availability.rs | 2 +- 9 files changed, 145 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 10dc72df..b493a8b6 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -328,7 +328,7 @@ impl Default for ToolState { } /// What is selected in the layer stack. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)] pub enum StackTarget { #[default] Content, diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index d831213d..6256973b 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1798,7 +1798,8 @@ pub(crate) fn properties_title(app: &TextureCraftApp) -> String { let what = match (app.session.selected_layer().and_then(|id| project.layers.get(&id)), app.session.target) { // Polygon fill keeps its own properties wherever it can fill _ if tool == Tool::PolygonFill && tool_usable => tr(tool.label()).to_string(), - (Some(_), StackTarget::Effect(effect)) => project.effect(effect).map(|(_, found)| found.name.clone()).unwrap_or_default(), + // The effect's type, not its own name (every filter reads "Filter") + (Some(_), StackTarget::Effect(effect)) => project.effect(effect).map(|(_, found)| tr(effect_type_label(&found.kind)).to_string()).unwrap_or_default(), (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => tr("Fill").to_string(), (Some(layer), StackTarget::Content) if layer.is_group() => tr("Folder").to_string(), (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => tr("Instance").to_string(), @@ -1809,44 +1810,70 @@ pub(crate) fn properties_title(app: &TextureCraftApp) -> String { format!("{} - {what}", tr("Properties")) } +/// The name of effect type `kind` in the Properties title +fn effect_type_label(kind: &EffectKind) -> &'static str { + match kind { + EffectKind::Filter(_) => n_("Filter"), + other => other.name(), + } +} + pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { // A floating scroll bar would cover the right-aligned slider values and section reset icons ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); - egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); + egui::ScrollArea::vertical().id_salt(("props", properties_place(app))).auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); +} + +/// What the docked Properties list keeps its own scroll place for: the selected layer and the part of it edited, none for the tool +fn properties_place(app: &TextureCraftApp) -> Option<(LayerId, StackTarget)> { + // A short panel in between would clamp a shared place back to the top; a greyed tool shows the layer's own sheet + if app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { + return None; + } + + app.session.selected_layer().map(|layer| (layer, app.session.target)) +} + +/// Room around the Properties rows not yet laid out by the property sheet: the sheet's side padding, so both start under the panel's name +const LEGACY_BODY_MARGIN: egui::Margin = egui::Margin::symmetric(crate::property_sheet::PAD as i8, 4); + +/// Lays out `body` with the other panels' margin +fn legacy_body(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { + egui::Frame::new().inner_margin(LEGACY_BODY_MARGIN).show(ui, body); } /// What the Properties panel edits: polygon fill's own settings, the selected effect, fill, folder, instance or mask, else the tool (or a hint to select a layer when it can't act) pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { - let tokens = Tokens::get(ui.ctx()); if !app.session.project_open { - ui.label(RichText::new(tr("No properties found")).color(tokens.text_dim)); + crate::widgets::empty_note(ui, tr("No properties found")); return; } let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned()); let tool = app.session.tool.tool; let tool_usable = app.session.tool_usable(tool); + let tokens = Tokens::get(ui.ctx()); match (&selected, app.session.target) { // Polygon fill shows its own settings and says what it fills into, wherever it can fill - _ if tool == Tool::PolygonFill && tool_usable => polygon_fill_properties(app, ui), - (Some(layer), StackTarget::Effect(effect)) => effect_properties(app, ui, layer, effect), - (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => fill_properties(app, ui, layer), - (Some(layer), StackTarget::Content) if layer.is_group() => { + _ if tool == Tool::PolygonFill && tool_usable => legacy_body(ui, |ui| polygon_fill_properties(app, ui)), + (Some(layer), StackTarget::Effect(effect)) => legacy_body(ui, |ui| effect_properties(app, ui, layer, effect)), + (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => legacy_body(ui, |ui| fill_properties(app, ui, layer)), + (Some(layer), StackTarget::Content) if layer.is_group() => legacy_body(ui, |ui| { ui.label(RichText::new(tr("A folder blends its children (pass-through). Set per-channel opacity in the layer rows.")).color(tokens.text_dim)); - } - (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => instance_properties(app, ui, layer), - (Some(layer), StackTarget::Mask) => { + }), + (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => legacy_body(ui, |ui| instance_properties(app, ui, layer)), + (Some(layer), StackTarget::Mask) => legacy_body(ui, |ui| { height_mask_section(app, ui, layer); if tool_usable { ui.separator(); tool_properties(app, ui); } - } - (None, _) if !tool_usable => { + }), + (None, _) if !tool_usable => legacy_body(ui, |ui| { ui.label(RichText::new(tr("Select a layer to paint on")).color(tokens.text_dim)); - } - _ => tool_properties(app, ui), + }), + _ => legacy_body(ui, |ui| tool_properties(app, ui)), } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3df3eb31..90519b44 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -68,6 +68,7 @@ mod path_surface_cache; mod pattern_panel; mod pattern_target; pub mod pbr_import; +mod popup_drag; mod preview_image; mod preview_request; mod preview_worker; @@ -76,6 +77,7 @@ pub mod profile; mod project_config; pub mod project_form; pub mod properties_popup; +mod property_sheet; mod query_field; mod rail_popup; pub mod render_mode; @@ -1053,6 +1055,9 @@ impl eframe::App for TextureCraftApp { self.ui.mode = state::Mode::Painting; } + // Before any popup draws, so one a drag closes is gone from this frame + popup_drag::close_on_drag_outside(&ctx); + if !self.ui.hide_ui { titlebar::show(self, ui); banner(self, ui); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index fa5ecd4c..ef2455a1 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -495,6 +495,22 @@ fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> painter.add(mesh); } +/// From a panel body's top to its empty note's lettering: the reference's gap under the header's name +const EMPTY_NOTE_TOP: f32 = 9.0; + +/// The line an empty panel shows instead of its contents ("No properties found"): under the header at its name's left edge, greyed as the disabled toolbar icons are +pub(crate) fn empty_note(ui: &mut Ui, text: &str) { + let tokens = Tokens::get(ui.ctx()); + ui.add_enabled_ui(false, |ui| { + let font = egui::TextStyle::Body.resolve(ui.style()); + let galley = ui.painter().layout_no_wrap(text.to_owned(), font, tokens.text); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), EMPTY_NOTE_TOP + galley.size().y), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, false, text)); + let at = egui::pos2(rect.left() + crate::docking::HEADER_TITLE_LEFT, rect.top() + EMPTY_NOTE_TOP); + ui.painter().galley(at, galley, tokens.text); + }); +} + /// Panel title row with optional trailing content. pub fn panel_header(ui: &mut Ui, title: &str, trailing: impl FnOnce(&mut Ui)) { ui.horizontal(|ui| { diff --git a/crates/ui-egui/tests/it/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs index 54f4e925..3ca2f721 100644 --- a/crates/ui-egui/tests/it/empty_start.rs +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -105,8 +105,8 @@ fn the_empty_views_keep_the_view_picker_and_drop_the_camera_picker() { assert!(!has_camera_picker(&empty), "no camera picker"); - // The picker shows "Material" right of the tool shelf and the Assets panel: one per view in the split layout - let pickers = painted(&empty).iter().filter(|(text, x)| text == "Material" && *x > 400.0).count(); + // The picker shows "Material" right of the tool shelf and the Assets panel and left of the right column: one per view in the split layout + let pickers = painted(&empty).iter().filter(|(text, x)| text == "Material" && (300.0..1200.0).contains(x)).count(); assert_eq!(pickers, 2, "each of the two views keeps its view picker"); @@ -393,3 +393,12 @@ fn close_releases_the_layer_thumbnail_snapshot() { ); } } + +#[test] +fn the_empty_properties_note_starts_at_its_header_names_left_edge() { + let harness = empty(); + let texts = painted(&harness); + let left_of = |wanted: &str| texts.iter().find(|(text, _)| text == wanted).map(|(_, left)| *left).unwrap_or_else(|| panic!("{wanted} is painted")); + + assert_eq!(left_of("No properties found"), left_of("PROPERTIES")); +} diff --git a/crates/ui-egui/tests/it/layer_multi_select.rs b/crates/ui-egui/tests/it/layer_multi_select.rs index 92201b7c..5dab5e1d 100644 --- a/crates/ui-egui/tests/it/layer_multi_select.rs +++ b/crates/ui-egui/tests/it/layer_multi_select.rs @@ -20,8 +20,18 @@ fn harness() -> (Harness<'static, TextureCraftApp>, [LayerId; 4]) { (h, rows) } +/// Frames for a scroll to bring a row into view (it animates) +const SCROLL_FRAMES: usize = 25; + +/// Scrolls the row `name` into view: six rows overflow the Layers panel +fn show_row(h: &mut Harness<'_, TextureCraftApp>, name: &str) { + h.get_by_label(name).scroll_to_me(); + h.run_steps(SCROLL_FRAMES); +} + /// Click the row `name` while `modifiers` are held (pressed before and released after the click). fn click(h: &mut Harness<'_, TextureCraftApp>, name: &str, modifiers: Modifiers) { + show_row(h, name); let at: Pos2 = h.get_by_label(name).rect().center(); h.event(Event::PointerMoved(at)); h.event(Event::ModifiersChanged(modifiers)); @@ -161,6 +171,7 @@ fn ctrl_a_leaves_text_fields_and_other_panels_alone() { /// Right-click the row `name` and choose the menu item whose label starts with `item`. fn row_menu(h: &mut Harness<'_, TextureCraftApp>, name: &str, item: &str) { + show_row(h, name); h.get_by_label(name).click_secondary(); h.run_steps(3); h.get_by(|node| node.label().is_some_and(|label| label.starts_with(item))).click(); diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index ccbd9074..6b2b6a3e 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -107,9 +107,17 @@ fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() { } let mut workspace = h.state().ui.dock.workspace().clone(); let Some(Node::Split { second, .. }) = workspace.layout.root.as_mut() else { panic!("default columns") }; - let Node::Split { size, .. } = second.as_mut() else { panic!("viewport and right column") }; + let Node::Split { size, second: column, .. } = second.as_mut() else { panic!("viewport and right column") }; *size = SplitSize::Ratio(0.99); + + // Layers tall enough for the whole nested stack: the default gives most of the column to Properties + let Node::Split { second: below_sets, .. } = column.as_mut() else { panic!("texture sets and the rest") }; + let Node::Split { size: layers_share, .. } = below_sets.as_mut() else { panic!("layers and properties") }; + *layers_share = SplitSize::Ratio(0.9); h.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); + + // Properties holds its column at its minimum width: without it the column narrows as far as Layers allows + h.state_mut().ui.dock.close(texturecraft_ui_egui::docking::Panel::Properties); h.run_steps(4); let row = h.get_by_label("Effect A").rect(); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 914bb830..2b938e89 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -52,11 +52,14 @@ mod nav_buttons; mod new_project_baked_maps; mod new_project_window; mod output_templates; +mod panel_header; mod path_in_view; mod path_list; mod pen_pressure; mod polygon_fill; +mod popup_press_close; mod project_config; +mod properties_min_width; mod properties_popup; mod rail; mod reference_order; @@ -93,3 +96,49 @@ mod stencil; mod symmetry; mod symmetry_2d; mod tile_generator_panel; + +/// eframe's in-memory storage, shared by the tests that save and restore the UI state +#[path = "../../src/ui_state_store/memory_storage.rs"] +mod memory_storage; + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_ui_egui::TextureCraftApp; + +/// Window of the Properties tests: tall enough that a whole sheet shows without scrolling +const PROPERTIES_WINDOW: egui::Vec2 = egui::vec2(1600.0, 1400.0); + +// Small texture and bake sizes keep the sample session fast; the panels don't depend on them +const TEXTURE_RESOLUTION: u32 = 256; +const BAKE_RESOLUTION: u32 = 64; + +/// Frames for the first layout and fonts to settle +const STARTUP_FRAMES: usize = 4; + +/// Frames for a click or key to reach the panels and its change to show +const SETTLE_FRAMES: usize = 3; + +/// Frames between the moves of a drag, and between a press and its release +const DRAG_STEP_FRAMES: usize = 2; + +/// Presses and releases the primary button at `at` without moving, as a pointer click does +fn click_at(harness: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { + harness.hover_at(at); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + harness.run_steps(1); + } + + harness.run_steps(SETTLE_FRAMES); +} + +/// The close button nearest the right of a docked panel's `title` (its tab or header title), on the same row +fn panel_close_button(harness: &Harness<'_, TextureCraftApp>, title: egui::Rect) -> egui::Rect { + harness + .get_all_by_role(egui::Role::Button) + .filter(|button| button.accesskit_node().label().as_deref() == Some("Close Panel")) + .map(|button| button.rect()) + .filter(|close| close.min.x > title.max.x && title.y_range().contains(close.center().y)) + .min_by(|a, b| a.min.x.total_cmp(&b.min.x)) + .expect("a close button right of the title") +} diff --git a/crates/ui-egui/tests/it/tool_availability.rs b/crates/ui-egui/tests/it/tool_availability.rs index cc6d97ff..2d55e09f 100644 --- a/crates/ui-egui/tests/it/tool_availability.rs +++ b/crates/ui-egui/tests/it/tool_availability.rs @@ -68,7 +68,7 @@ fn a_fill_layer_greys_the_paint_tools_and_shows_its_own_properties() { assert!(shelf_button_disabled(&harness, "Polygon fill (4)")); assert!(!shelf_button_selected(&harness, "Polygon fill (4)"), "the equipped tool doesn't show as selected while greyed"); assert!(!shelf_button_disabled(&harness, "Geometry mask (8)")); - assert!(shows_text(&harness, "Properties - Fill"), "a fill layer shows its fill whatever the tool"); + assert!(shows_text(&harness, "PROPERTIES - FILL"), "a fill layer shows its fill whatever the tool"); assert!(!shows_text(&harness, "Size"), "a tool that can't act leaves the top bar"); } From e131e826b1b52b86f23e490c8622ddf159877c9f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:11 +0000 Subject: [PATCH 12/17] Fills: Symmetry, mirrored or radial copies of a 3D projection --- crates/compose/src/fill_copies.rs | 154 ++++++++++++++++++ crates/core/src/fill_symmetry.rs | 93 +++++++++++ crates/core/src/symmetry_kind.rs | 31 ++++ crates/ui-egui/src/fill_symmetry_panel.rs | 113 +++++++++++++ crates/ui-egui/src/symmetry/settings_popup.rs | 3 +- crates/ui-egui/src/symmetry/view_overlay.rs | 9 +- crates/ui-egui/tests/it/fill_symmetry_rows.rs | 111 +++++++++++++ 7 files changed, 504 insertions(+), 10 deletions(-) create mode 100644 crates/compose/src/fill_copies.rs create mode 100644 crates/core/src/fill_symmetry.rs create mode 100644 crates/core/src/symmetry_kind.rs create mode 100644 crates/ui-egui/src/fill_symmetry_panel.rs create mode 100644 crates/ui-egui/tests/it/fill_symmetry_rows.rs diff --git a/crates/compose/src/fill_copies.rs b/crates/compose/src/fill_copies.rs new file mode 100644 index 00000000..cd4fc02a --- /dev/null +++ b/crates/compose/src/fill_copies.rs @@ -0,0 +1,154 @@ +//! The copies a symmetric fill makes of its projection, as mirrors and turns of the surface point each copy samples + +use texturecraft_core::{FULL_TURN_DEGREES, FillSymmetry, SymmetryKind}; +use texturecraft_geom::glam::{Mat3, Vec3}; + +use crate::fill_copy::FillCopy; + +/// The copies of a fill's projection one texel shows, the original among them: the one whose half (mirror) or wedge (radial) holds the texel comes first, so it lies on top where copies overlap +pub struct FillCopies { + symmetry: FillSymmetry, + pivot: Vec3, + axis: usize, + step: f32, + first: u32, + count: u32, + next: u32, +} + +impl FillCopies { + /// The copies `symmetry` makes for a texel at world point `point`, on a mesh whose bounds have centre `center` and radius `radius` + pub fn new(symmetry: &FillSymmetry, point: Vec3, center: Vec3, radius: f32) -> FillCopies { + let reach = FillSymmetry::REACH; + let position = Vec3::from(symmetry.position.map(|coordinate| if coordinate.is_finite() { coordinate.clamp(-reach, reach) } else { 0.0 })); + let pivot = center + position * radius; + let axis = symmetry.axis_index(); + let count = symmetry.copies(); + let step = symmetry.step(); + + let from_pivot = point - pivot; + let first = match symmetry.kind { + // The original keeps the half on the axis's positive side + SymmetryKind::Mirror => u32::from(from_pivot[axis] < 0.0), + SymmetryKind::Radial => { + let turned = from_pivot[(axis + 2) % 3].atan2(from_pivot[(axis + 1) % 3]).to_degrees().rem_euclid(FULL_TURN_DEGREES); + nearest_copy(turned, step, count, symmetry.span) + } + }; + + FillCopies { symmetry: *symmetry, pivot, axis, step, first, count, next: 0 } + } + + /// Copy `index`: the original at 0, then the mirror or the radial copies in turn + fn copy(&self, index: u32) -> FillCopy { + let flip = if index == 0 { [false; 2] } else { self.symmetry.flip }; + let turn = match self.symmetry.kind { + _ if index == 0 => Mat3::IDENTITY, + SymmetryKind::Mirror => { + let mut scale = Vec3::ONE; + scale[self.axis] = -1.0; + Mat3::from_diagonal(scale) + } + + // Copy `index` is the original turned by `index` steps, so a texel samples the original turned back + SymmetryKind::Radial => Mat3::from_axis_angle(Vec3::AXES[self.axis], -(index as f32 * self.step).to_radians()), + }; + FillCopy::new(turn, self.pivot, flip) + } +} + +/// The radial copy nearest a texel `turned` degrees round the axis, of `count` copies `step` degrees apart over `span` degrees: copy 0 across the gap a span under a full turn leaves, else the nearest by its step +fn nearest_copy(turned: f32, step: f32, count: u32, span: f32) -> u32 { + // A span of nothing (or no step at all) stacks every copy on the original + if step.is_nan() || step <= 0.0 { + return 0; + } + + let by_step = (turned / step).round() as u32; + if span >= FULL_TURN_DEGREES || span.is_nan() { + return by_step % count; + } + + let last = by_step.min(count - 1); + let past_last = (turned - last as f32 * step).abs(); + let before_first = FULL_TURN_DEGREES - turned; + if before_first <= past_last { 0 } else { last } +} + +impl Iterator for FillCopies { + type Item = FillCopy; + + fn next(&mut self) -> Option { + if self.next >= self.count { + return None; + } + + let index = (self.first + self.next) % self.count; + self.next += 1; + Some(self.copy(index)) + } +} + +#[cfg(test)] +mod tests { + use texturecraft_geom::glam::Vec2; + + use super::*; + + fn symmetry(kind: SymmetryKind, axis: u8) -> FillSymmetry { + FillSymmetry { on: true, kind, axis, ..FillSymmetry::OFF } + } + + #[test] + fn a_mirror_puts_the_texels_own_half_first_and_reflects_across_the_axis_position() { + let mut mirror = symmetry(SymmetryKind::Mirror, 0); + mirror.position = [0.5, 0.0, 0.0]; + let left: Vec = FillCopies::new(&mirror, Vec3::new(-1.0, 0.0, 0.0), Vec3::ZERO, 2.0).collect(); + assert_eq!(left.len(), 2); + + // The plane passes at x = 1 (half a radius of 2): a point at -1 sees the original at 3 first + assert!(left[0].point(Vec3::new(-1.0, 0.2, 0.0)).abs_diff_eq(Vec3::new(3.0, 0.2, 0.0), 1e-5)); + assert!(left[1].point(Vec3::new(-1.0, 0.2, 0.0)).abs_diff_eq(Vec3::new(-1.0, 0.2, 0.0), 1e-5)); + assert!(left[0].normal(Vec3::X).abs_diff_eq(-Vec3::X, 1e-5)); + let right: Vec = FillCopies::new(&mirror, Vec3::new(2.0, 0.0, 0.0), Vec3::ZERO, 2.0).collect(); + assert!(right[0].point(Vec3::new(2.0, 0.3, 0.0)).abs_diff_eq(Vec3::new(2.0, 0.3, 0.0), 1e-5)); + } + + #[test] + fn radial_copies_turn_by_their_step_and_flip_only_the_copies() { + let mut radial = symmetry(SymmetryKind::Radial, 2); + radial.count = 4; + radial.flip = [true, false]; + let copies: Vec = FillCopies::new(&radial, Vec3::X, Vec3::ZERO, 1.0).collect(); + assert_eq!(copies.len(), 4); + assert_eq!(copies[0].uv(Vec2::new(0.25, 0.5)), Vec2::new(0.25, 0.5)); + assert_eq!(copies[1].uv(Vec2::new(0.25, 0.5)), Vec2::new(0.75, 0.5)); + + // Copy 1 sits a quarter turn on: a texel on +Y samples the original on +X + assert!(copies[1].point(Vec3::Y).abs_diff_eq(Vec3::X, 1e-5)); + + // A texel on +Y lies in copy 1's wedge, so copy 1 comes first there + let on_y: Vec = FillCopies::new(&radial, Vec3::Y, Vec3::ZERO, 1.0).collect(); + assert!(on_y[0].point(Vec3::Y).abs_diff_eq(Vec3::X, 1e-5)); + } + + #[test] + fn the_nearest_copy_is_found_by_its_step_as_a_search_of_every_copy_finds_it() { + for (count, span) in [(6, 360.0), (5, 360.0), (4, 180.0), (3, 90.0), (64, 300.0), (2, 1.0)] { + let step = radial_step(count, span); + for tenth in 0..3600 { + let turned = tenth as f32 / 10.0 + 0.05; + let gap = |index: u32| { + let past_copy = (turned - index as f32 * step).rem_euclid(FULL_TURN_DEGREES); + past_copy.min(FULL_TURN_DEGREES - past_copy) + }; + let searched = (0..count).min_by(|a, b| gap(*a).total_cmp(&gap(*b))).unwrap_or(0); + assert_eq!(nearest_copy(turned, step, count, span), searched, "{count} copies over {span} at {turned}"); + } + } + } + + fn radial_step(count: u32, span: f32) -> f32 { + FillSymmetry { count, span, ..symmetry(SymmetryKind::Radial, 2) }.step() + } +} diff --git a/crates/core/src/fill_symmetry.rs b/crates/core/src/fill_symmetry.rs new file mode 100644 index 00000000..be0ebc40 --- /dev/null +++ b/crates/core/src/fill_symmetry.rs @@ -0,0 +1,93 @@ +//! Symmetry of a fill's 3D projection: mirrored or radial copies of it on the model + +use serde::{Deserialize, Serialize}; + +use crate::{FULL_TURN_DEGREES, SymmetryKind}; + +/// Copies of a fill's projection: off for every fill saved before symmetry existed +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct FillSymmetry { + pub on: bool, + pub kind: SymmetryKind, + /// 0 = X, 1 = Y, 2 = Z: the mirror plane's normal, or the axis radial copies turn round + pub axis: u8, + /// Whether the copies' images are turned over across (U) and down (V) + pub flip: [bool; 2], + /// Where the mirror plane or the turning axis passes, in mesh radii from the mesh's centre + pub position: [f32; 3], + /// How many radial copies, the original included + pub count: u32, + /// The degrees the radial copies spread over; a full turn spaces them evenly round it + pub span: f32, +} + +impl FillSymmetry { + /// Off; switched on, a mirror across X through the mesh's centre, or six radial copies over a full turn + pub const OFF: FillSymmetry = + FillSymmetry { on: false, kind: SymmetryKind::Mirror, axis: 0, flip: [false; 2], position: [0.0; 3], count: 6, span: FULL_TURN_DEGREES }; + /// The fewest and most radial copies + pub const COUNTS: std::ops::RangeInclusive = 2..=64; + /// The degrees an Angle span may be set to: at least one, at most a full turn + pub const SPANS: std::ops::RangeInclusive = 1.0..=FULL_TURN_DEGREES; + /// How far the axis position reaches from the mesh's centre, in mesh radii + pub const REACH: f32 = 1.0; + /// [`FillSymmetry::axis`] of the last axis, Z + pub const LAST_AXIS: u8 = 2; + + /// The degrees between radial copies: a full turn spaces `count` copies evenly, a smaller span puts the first and last at its ends (a span that is not a number is a full turn) + pub fn step(&self) -> f32 { + let count = self.radial_count() as f32; + let span = if self.span.is_nan() { FULL_TURN_DEGREES } else { self.span.clamp(0.0, FULL_TURN_DEGREES) }; + if span >= FULL_TURN_DEGREES { span / count } else { span / (count - 1.0) } + } + + /// The copies there are, the original included: two for a mirror + pub fn copies(&self) -> u32 { + match self.kind { + SymmetryKind::Mirror => 2, + SymmetryKind::Radial => self.radial_count(), + } + } + + /// The axis the copies mirror across or turn round, the last one for an axis past it + pub fn axis_index(&self) -> usize { + usize::from(self.axis.min(Self::LAST_AXIS)) + } + + /// How many radial copies, kept within [`FillSymmetry::COUNTS`] + fn radial_count(&self) -> u32 { + self.count.clamp(*Self::COUNTS.start(), *Self::COUNTS.end()) + } + + /// Whether this is the symmetry a new fill starts with, so saves leave it out + pub fn is_default(&self) -> bool { + *self == FillSymmetry::default() + } +} + +impl Default for FillSymmetry { + fn default() -> Self { + FillSymmetry::OFF + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn radial(count: u32, span: f32) -> FillSymmetry { + FillSymmetry { on: true, kind: SymmetryKind::Radial, count, span, ..FillSymmetry::OFF } + } + + #[test] + fn a_span_under_a_full_turn_puts_the_last_copy_at_its_end() { + assert_eq!(radial(4, 180.0).step(), 60.0); + assert_eq!(radial(4, 360.0).step(), 90.0); + } + + #[test] + fn a_span_that_is_not_a_number_spaces_the_copies_round_a_full_turn() { + assert_eq!(radial(4, f32::NAN).step(), 90.0); + } +} diff --git a/crates/core/src/symmetry_kind.rs b/crates/core/src/symmetry_kind.rs new file mode 100644 index 00000000..01b5c407 --- /dev/null +++ b/crates/core/src/symmetry_kind.rs @@ -0,0 +1,31 @@ +//! The kind of copies a symmetric fill makes: mirrored or turned round an axis + +use serde::{Deserialize, Serialize}; + +/// How a symmetric fill copies its projection +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SymmetryKind { + /// One copy mirrored across the plane through the axis position, square to the axis + #[default] + Mirror, + /// Copies turned round the axis through the axis position + Radial, +} + +impl SymmetryKind { + /// Every kind, in the order the Type list shows them + pub const ALL: [SymmetryKind; 2] = [SymmetryKind::Mirror, SymmetryKind::Radial]; + + /// The id commands use + pub fn id(self) -> &'static str { + match self { + SymmetryKind::Mirror => "mirror", + SymmetryKind::Radial => "radial", + } + } + + /// The kind with command id `id` + pub fn from_id(id: &str) -> Option { + SymmetryKind::ALL.into_iter().find(|kind| kind.id() == id) + } +} diff --git a/crates/ui-egui/src/fill_symmetry_panel.rs b/crates/ui-egui/src/fill_symmetry_panel.rs new file mode 100644 index 00000000..0a95f428 --- /dev/null +++ b/crates/ui-egui/src/fill_symmetry_panel.rs @@ -0,0 +1,113 @@ +//! A fill's Symmetry section: mirrored or radial copies of its 3D projection + +use std::ops::RangeInclusive; + +use egui::{Painter, Rect}; +use serde_json::{Value, json}; +use texturecraft_engine::core::{FillSymmetry, Projection, Sampling, SymmetryKind}; + +use crate::TextureCraftApp; +use crate::fill_panel::run_projection; +use crate::fill_pictures::ring_picture; +use crate::i18n::{n_, tr}; +use crate::property_sheet::{PropertySheet, StackSlider}; +use crate::theme::{AXIS_COLORS, AXIS_NAMES, Tokens}; +use crate::widgets::press_edit; + +/// What the Axis position track spans, in mesh radii from the mesh's centre +const POSITION_RANGE: RangeInclusive = -FillSymmetry::REACH..=FillSymmetry::REACH; + +/// What the Count track spans; a typed count reaches the engine's fewest and most copies, as the symmetry popup's Count does +const COUNT_TRACK: RangeInclusive = *FillSymmetry::COUNTS.start() as f32..=16.0; + +/// What a typed Count may reach +const COUNT_TYPED: RangeInclusive = *FillSymmetry::COUNTS.start() as f32..=*FillSymmetry::COUNTS.end() as f32; + +/// The Angle span slider's place in the stack beside the ring, under Count +const SPAN_SLIDER: usize = 1; + +/// The Symmetry section under the Fill section: its switch on the caption, then Type, Axis, the radial copies beside their picture, Flip copy and Axis position +pub(crate) fn symmetry_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, projection: &Projection, sampling: Sampling, base: &Value) { + let symmetry = sampling.symmetry; + let run = |app: &mut TextureCraftApp, fields: Value| run_projection(app, base, fields); + if !projection.takes_symmetry() { + let reason = match projection { + Projection::UvTile => tr("Not available with Fill (Match per UV Tile)"), + _ => tr("Not available with UV projection"), + }; + sheet.section_unavailable(tr("Symmetry"), reason); + return; + } + + let switch = sheet.section_switch(tr("Symmetry"), symmetry.on); + if switch.clicked() { + run(app, json!({"symmetry": !symmetry.on})); + } + if !symmetry.on { + return; + } + + let (picked, _) = sheet.dropdown(tr("Type"), symmetry.kind, &SymmetryKind::ALL, |kind| tr(kind_label(kind)).to_owned(), None); + if let Some(kind) = picked { + run(app, json!({"symmetryType": kind.id()})); + } + let axis = symmetry.axis_index(); + if let Some(picked) = sheet.switch_tinted(tr("Axis"), &AXIS_NAMES, axis, &AXIS_COLORS) { + run(app, json!({"symmetryAxis": picked})); + } + if symmetry.kind == SymmetryKind::Radial { + radial_rows(app, sheet, &symmetry, base); + } + + let mut flip = symmetry.flip; + if sheet.toggle_pair(tr("Flip copy"), ["U", "V"], &mut flip).is_some() { + run(app, json!({"flipCopy": flip})); + } + + // A mirror moves its plane along its axis; radial copies turn round an axis that moves across it + let moving: Vec = match symmetry.kind { + SymmetryKind::Mirror => vec![axis], + SymmetryKind::Radial => (0..AXIS_NAMES.len()).filter(|other| *other != axis).collect(), + }; + let mut parts: Vec<(&str, egui::Color32, f32)> = moving.iter().map(|&moved| (AXIS_NAMES[moved], AXIS_COLORS[moved], symmetry.position[moved])).collect(); + if let Some((index, merge)) = sheet.lettered_sliders(tr("Axis position"), &mut parts, POSITION_RANGE, 2) + && let (Some(&moved), Some((_, _, value))) = (moving.get(index), parts.get(index)) + { + let mut position = symmetry.position; + position[moved] = *value; + run(app, json!({"axisPosition": position, "merge": merge})); + } +} + +/// Count and Angle span beside the ring of copies, seen along the axis +fn radial_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, symmetry: &FillSymmetry, base: &Value) { + let tokens = Tokens::get(sheet.ui.ctx()); + let axis_color = AXIS_COLORS[symmetry.axis_index()]; + let picture = |painter: &Painter, rect: Rect| ring_picture(painter, rect, symmetry, axis_color, &tokens); + let count = symmetry.copies(); + let (mut count_value, mut span_value) = (count as f32, symmetry.span); + let mut sliders = [ + StackSlider { label: tr("Count"), value: &mut count_value, range: COUNT_TRACK, typed: COUNT_TYPED, decimals: 0, suffix: "" }, + StackSlider { label: tr("Angle span"), value: &mut span_value, range: FillSymmetry::SPANS, typed: FillSymmetry::SPANS, decimals: 0, suffix: "°" }, + ]; + let edited = sheet.picture_sliders(&picture, &mut sliders); + if let Some((SPAN_SLIDER, merge)) = edited { + run_projection(app, base, json!({"angleSpan": span_value, "merge": merge})); + return; + } + + // Whole counts: a press's first whole-number change starts its undo step, changes that round to the count it has apply nothing + let counted = count_value.round(); + let press = sheet.ui.make_persistent_id("symmetry_count_press"); + if let Some(merge) = press_edit(sheet.ui, press, edited.is_some() && counted as u32 != count) { + run_projection(app, base, json!({"symmetryCount": counted, "merge": merge})); + } +} + +/// The Type dropdown's name for `kind` +fn kind_label(kind: SymmetryKind) -> &'static str { + match kind { + SymmetryKind::Mirror => n_("Mirror symmetry"), + SymmetryKind::Radial => n_("Radial symmetry"), + } +} diff --git a/crates/ui-egui/src/symmetry/settings_popup.rs b/crates/ui-egui/src/symmetry/settings_popup.rs index b92e37cd..8e072d9e 100644 --- a/crates/ui-egui/src/symmetry/settings_popup.rs +++ b/crates/ui-egui/src/symmetry/settings_popup.rs @@ -6,6 +6,7 @@ use texturecraft_engine::paint::{FULL_TURN_DEGREES, MAX_RADIAL_COPIES, Symmetry} use super::{DEFAULT_RADIAL_COUNT, movable_axes}; use crate::TextureCraftApp; use crate::i18n::tr; +use crate::theme::AXIS_NAMES; use crate::widgets::{color_swatch, section, slider}; /// The popup's width (points) @@ -14,8 +15,6 @@ const POPUP_WIDTH: f32 = 340.0; /// Width of the radial Axis row's label column const LABEL_WIDTH: f32 = 64.0; -const AXIS_NAMES: [&str; 3] = ["X", "Y", "Z"]; - /// Space between the mirror section and the radial toggle const SECTIONS_GAP: f32 = 4.0; diff --git a/crates/ui-egui/src/symmetry/view_overlay.rs b/crates/ui-egui/src/symmetry/view_overlay.rs index 3ceb5be6..4f805951 100644 --- a/crates/ui-egui/src/symmetry/view_overlay.rs +++ b/crates/ui-egui/src/symmetry/view_overlay.rs @@ -11,6 +11,7 @@ use super::symmetry_intersection::SymmetryIntersection; use super::symmetry_manipulator::SymmetryManipulator; use super::symmetry_manipulator_arrow::SymmetryManipulatorArrow; use crate::TextureCraftApp; +use crate::theme::{AXIS_COLORS, SHAFT_HALO, SHAFT_HALO_EXTRA_WIDTH, SHAFT_WIDTH}; /// The plane reaches this far past the mesh, as a fraction of its size const PLANE_MARGIN: f32 = 0.05; @@ -30,14 +31,6 @@ const VISIBILITY_TOLERANCE: f32 = 2e-3; const INTERSECTION_WIDTH: f32 = 1.5; const INTERSECTION_POINT_RADIUS: f32 = 3.0; -/// Manipulator arrows along X, Y and Z (the view-corner axis colors, a little softer) -const AXIS_COLORS: [Color32; 3] = [Color32::from_rgb(0xd8, 0x60, 0x4f), Color32::from_rgb(0x6c, 0xbc, 0x5a), Color32::from_rgb(0x5a, 0x8c, 0xe0)]; - -/// Arrow shaft width, its dark halo and the halo's extra width (points at the default size) -const SHAFT_WIDTH: f32 = 2.2; -const SHAFT_HALO: Color32 = Color32::from_black_alpha(128); -const SHAFT_HALO_EXTRA_WIDTH: f32 = 3.0; - /// Faces around a cone const CONE_SEGMENTS: usize = 20; diff --git a/crates/ui-egui/tests/it/fill_symmetry_rows.rs b/crates/ui-egui/tests/it/fill_symmetry_rows.rs new file mode 100644 index 00000000..466f07f5 --- /dev/null +++ b/crates/ui-egui/tests/it/fill_symmetry_rows.rs @@ -0,0 +1,111 @@ +//! A fill's Symmetry section: its switch, Type, Axis, Flip copy and the radial rows each change the fill's symmetry + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{FillSymmetry, LayerId, SymmetryKind}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::fill_support::{click_label, click_node, fill_app, fill_of}; +use crate::filter_support::{along, click_at, drag, undo_depth}; +use crate::{PROPERTIES_WINDOW, SETTLE_FRAMES}; + +/// The app with a new fill layer (projected as `projection`) selected, its Symmetry tab clicked, and its layer id +fn app_with_fill(projection: &str) -> (Harness<'static, TextureCraftApp>, u64) { + let (harness, LayerId(layer)) = fill_app(json!({}), Some(projection), Some("Symmetry"), PROPERTIES_WINDOW); + (harness, layer) +} + +/// The fill layer's symmetry as the document holds it +fn symmetry(harness: &Harness<'_, TextureCraftApp>, layer: u64) -> FillSymmetry { + fill_of(harness, LayerId(layer)).sampling.symmetry +} + +/// The app with a planar fill's radial symmetry on (six copies over a full turn) and its radial rows showing +fn app_with_radial() -> (Harness<'static, TextureCraftApp>, u64) { + let (mut harness, layer) = app_with_fill("planar"); + harness.state_mut().run("layer.fill.projection", json!({"layer": layer, "symmetry": true, "symmetryType": "radial"})); + harness.run_steps(SETTLE_FRAMES); + (harness, layer) +} + +/// The Count track's start: the fewest copies +const COUNT_TRACK_FEWEST: f32 = *FillSymmetry::COUNTS.start() as f32; + +/// The Count track's end; a typed count reaches further +const COUNT_TRACK_MOST: f32 = 16.0; + +/// Where the Count track shows `count` copies +fn count_at(harness: &Harness<'_, TextureCraftApp>, count: f32) -> egui::Pos2 { + let track = harness.get_by_role_and_label(Role::Slider, "Count").rect(); + along(track, (count - COUNT_TRACK_FEWEST) / (COUNT_TRACK_MOST - COUNT_TRACK_FEWEST)) +} + +#[test] +fn the_symmetry_switch_shows_its_rows_and_each_row_changes_the_symmetry() { + let (mut harness, layer) = app_with_fill("planar"); + assert!(harness.query_by_label("Mirror symmetry").is_none(), "off, the section is the caption alone"); + + click_node(&mut harness, Role::CheckBox, "Symmetry"); + assert!(symmetry(&harness, layer).on); + assert!(harness.query_by_label("Axis position X").is_some(), "a mirror across X moves along X"); + assert!(harness.query_by_label("Count").is_none(), "a mirror has no radial rows"); + + click_node(&mut harness, Role::RadioButton, "Y"); + assert_eq!(symmetry(&harness, layer).axis, 1); + click_node(&mut harness, Role::CheckBox, "Flip copy U"); + assert_eq!(symmetry(&harness, layer).flip, [true, false]); + + click_node(&mut harness, Role::ComboBox, "Mirror symmetry"); + click_node(&mut harness, Role::ListBoxOption, "Radial symmetry"); + assert_eq!(symmetry(&harness, layer).kind, SymmetryKind::Radial); + for label in ["Count", "Angle span", "Axis position X", "Axis position Z"] { + assert!(harness.query_by_label(label).is_some(), "radial round Y: {label}"); + } + assert!(harness.query_by_label("Axis position Y").is_none(), "the turning axis does not move along itself"); + + click_node(&mut harness, Role::CheckBox, "Symmetry"); + assert!(!symmetry(&harness, layer).on); + assert_eq!(symmetry(&harness, layer).kind, SymmetryKind::Radial, "switched off, the settings stay"); +} + +#[test] +fn a_uv_fill_says_why_in_place_of_the_symmetry_switch() { + let (mut harness, layer) = app_with_fill("uv"); + assert!(harness.query_by_role_and_label(Role::CheckBox, "Symmetry").is_none(), "no switch to click"); + click_label(&mut harness, "Not available with UV projection"); + assert!(!symmetry(&harness, layer).on, "a UV projection has no symmetry to switch on"); + assert!(harness.query_by_label("Type").is_none(), "its settings stay hidden, not greyed"); +} + +/// A click on the Count track that rounds to the count it has changes nothing and adds no undo step; a drag to the next whole count is one step +#[test] +fn a_count_click_that_keeps_the_count_adds_no_undo_step_and_a_drag_to_the_next_adds_one() { + let (mut harness, layer) = app_with_radial(); + let steps = undo_depth(&harness); + + let inside = count_at(&harness, 6.2); + click_at(&mut harness, inside); + assert_eq!(symmetry(&harness, layer).count, 6); + assert_eq!(undo_depth(&harness), steps, "a count that stays six is no edit"); + + let (from, to) = (count_at(&harness, 6.0), count_at(&harness, 7.3)); + drag(&mut harness, from, to); + assert_eq!(symmetry(&harness, layer).count, 7); + assert_eq!(undo_depth(&harness), steps + 1, "the drag's frames merge into one step"); +} + +/// A typed count reaches past the track's end, up to the engine's most copies, as the symmetry popup's Count does +#[test] +fn a_typed_count_reaches_past_the_track_to_the_engines_most() { + let (mut harness, layer) = app_with_radial(); + + click_node(&mut harness, Role::Label, "Count value"); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.event(egui::Event::Text("40".into())); + harness.key_press(egui::Key::Enter); + harness.run_steps(SETTLE_FRAMES); + + assert_eq!(symmetry(&harness, layer).count, 40); +} From eb362a790ec41ad915582d270b77a4bbddd496a2 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 22 Nov 2026 05:28:49 +0000 Subject: [PATCH 13/17] Panel shell: review repairs from #698 Chasse's repairs to the panel shell, carried over from the #698 head (5644b7d3). --- crates/ui-egui/src/docking.rs | 4 ++++ crates/ui-egui/src/docking/header_band.rs | 2 ++ crates/ui-egui/src/docking/shown_group_tab.rs | 4 ++++ crates/ui-egui/src/symmetry/mod.rs | 2 +- crates/ui-egui/tests/it/empty_start.rs | 1 + crates/ui-egui/tests/it/layers_panel.rs | 1 + crates/ui-egui/tests/it/panel_header.rs | 2 ++ crates/ui-egui/tests/it/popup_press_close.rs | 1 + crates/ui-egui/tests/it/properties_min_width.rs | 4 ++++ crates/ui-egui/tests/it/rail.rs | 1 + crates/ui-egui/tests/it/split_divider.rs | 3 +++ 11 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index b4f64ad4..16164aa4 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -688,9 +688,11 @@ mod tests { fn default_workspace_has_every_panel_and_is_valid() { let w = default_workspace(); assert!(validate(&w).is_ok()); + for panel in Panel::ALL { assert!(w.layout.contains(&panel) || w.hidden.iter().any(|(p, _)| *p == panel), "{panel:?} is neither shown nor hidden"); } + assert_eq!(panels_of(&w), [Panel::Assets, Panel::Viewport, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, Panel::Properties]); } @@ -703,6 +705,7 @@ mod tests { let Node::Split { size: SplitSize::Ratio(layers), first, second, .. } = below_sets.as_ref() else { panic!("layers | properties") }; assert!(matches!(first.as_ref(), Node::Tabs { panels, .. } if panels.first() == Some(&Panel::Layers))); assert!(matches!(second.as_ref(), Node::Tabs { panels, .. } if panels == &[Panel::Properties])); + let properties = 1.0 - layers; assert!((2.0 / 3.0..0.7).contains(&properties), "Properties takes about 69% of the column, at least two thirds: {properties}"); } @@ -716,6 +719,7 @@ mod tests { let Node::Split { size, .. } = below_sets.as_mut() else { panic!("layers | properties") }; *size = SplitSize::Ratio(0.57); let back = Dock::from_value(serde_json::to_value(&workspace).unwrap()); + assert_eq!(back.workspace(), &workspace, "a layout saved with the old split opens unchanged"); } diff --git a/crates/ui-egui/src/docking/header_band.rs b/crates/ui-egui/src/docking/header_band.rs index 95dcdeec..3c00cd31 100644 --- a/crates/ui-egui/src/docking/header_band.rs +++ b/crates/ui-egui/src/docking/header_band.rs @@ -16,6 +16,7 @@ pub(super) const HEADER_RISE: f32 = crate::theme::GUTTER as f32 - PANEL_SEPARATI /// Whether `panel`'s docked group sits under another panel, a gutter above its header; floating groups and the top row have none pub(super) fn under_a_panel(layout: &Layout, panel: Panel) -> bool { let Some(root) = &layout.root else { return false }; + let mut nodes: Vec<(&Node, bool)> = vec![(root, false)]; while let Some((node, below)) = nodes.pop() { match node { @@ -55,6 +56,7 @@ pub(super) fn header_name(ui: &Ui, name: &str, font: FontId, color: Color32, lif { section.format.valign = Align::BOTTOM; } + job.first_row_min_height = galley.size().y + 2.0 * shift.abs(); job } diff --git a/crates/ui-egui/src/docking/shown_group_tab.rs b/crates/ui-egui/src/docking/shown_group_tab.rs index 61f5d4e0..c9c500cb 100644 --- a/crates/ui-egui/src/docking/shown_group_tab.rs +++ b/crates/ui-egui/src/docking/shown_group_tab.rs @@ -26,6 +26,7 @@ fn group_of(layout: &Layout, panel: Panel) -> Option<(&[Panel], bool)> { let docked = layout.root.iter().map(|root| (root, false)); let floating = layout.floating.iter().map(|window| (&window.root, true)); let mut nodes: Vec<(&Node, bool)> = docked.chain(floating).collect(); + while let Some((node, floats)) = nodes.pop() { match node { Node::Split { first, second, .. } => { @@ -42,6 +43,7 @@ fn group_of(layout: &Layout, panel: Panel) -> Option<(&[Panel], bool)> { _ => {} } } + None } @@ -59,6 +61,7 @@ impl Panels<'_> { /// Over the tab the dock drew for `panel`, the panel shown in its group, paints the section tabs' raised box and the name again; a panel alone keeps its plain header. `ui` is the panel's body, right under the strip pub(super) fn paint_shown_group_tab(&self, ui: &Ui, panel: Panel) { let Some((panels, floating)) = group_of(&self.app.ui.dock.workspace.layout, panel) else { return }; + if panels.len() < 2 { return; } @@ -76,6 +79,7 @@ impl Panels<'_> { let header = self.group_header_width(panels, &panel, floating, strip.width()).clamp(0.0, strip.width()); let available = (strip.width() - header - self.style.drag_bar_width).max(0.0); let fit = craft_ui::tabs::fit(&natural, shown, available, self.style.min_tab_width, OVERFLOW_WIDTH); + let mut left = strip.left(); for (index, width) in fit.shown { if index != shown { diff --git a/crates/ui-egui/src/symmetry/mod.rs b/crates/ui-egui/src/symmetry/mod.rs index 94eec7d8..081387c3 100644 --- a/crates/ui-egui/src/symmetry/mod.rs +++ b/crates/ui-egui/src/symmetry/mod.rs @@ -102,7 +102,7 @@ pub(crate) fn toolbar_controls(app: &mut TextureCraftApp, ui: &mut Ui) { .close_behavior(egui::PopupCloseBehavior::IgnoreClicks) .show(|ui| settings_popup::show(app, ui)); - // A click outside the popup and the dropdowns it opens (foreground layers too) closes it, and so does a drag that starts outside them + // Outside clicks and drags dismiss the menu unless they belong to a child popup if let Some(shown) = shown && !response.clicked() { diff --git a/crates/ui-egui/tests/it/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs index 3ca2f721..eedbb9c2 100644 --- a/crates/ui-egui/tests/it/empty_start.rs +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -381,6 +381,7 @@ fn close_releases_the_layer_thumbnail_snapshot() { invoke(&mut harness, "file.close"); assert!(!harness.state().session.project_open); + assert_eventually_released(&old_mesh); for (pixels, _) in &old_maps { assert_eventually_released(pixels); diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 6b2b6a3e..e346617a 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -122,6 +122,7 @@ fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() { let row = h.get_by_label("Effect A").rect(); assert!(row.width() < 180.0, "the test must use a compact panel: {row:?}"); + let indent = (row.width() - 7.0 - 22.0 - 21.6 - 8.0 - 20.0 - 6.0).max(0.0); click(&mut h, egui::pos2(row.left() + 15.0 + indent, row.center().y)); diff --git a/crates/ui-egui/tests/it/panel_header.rs b/crates/ui-egui/tests/it/panel_header.rs index 8a9caed5..6485f50a 100644 --- a/crates/ui-egui/tests/it/panel_header.rs +++ b/crates/ui-egui/tests/it/panel_header.rs @@ -52,6 +52,7 @@ fn every_docked_panel_header_ends_in_its_own_close_button() { fn the_header_close_button_closes_its_panel() { let mut harness = app(); assert!(harness.state().ui.dock.is_visible(Panel::Properties)); + let close = panel_close_button(&harness, tab_rect(&harness, "Properties - ")); click_at(&mut harness, close.center()); @@ -230,6 +231,7 @@ fn a_tab_menus_panel_names_keep_their_plain_layout() { _ => None, }) .collect(); + assert!(!padded.is_empty(), "the menu paints the Layers entry"); assert!(padded.iter().all(|height| *height == 0.0), "the Layers entry is padded to {padded:?}"); } diff --git a/crates/ui-egui/tests/it/popup_press_close.rs b/crates/ui-egui/tests/it/popup_press_close.rs index 31e2d868..b56d3c91 100644 --- a/crates/ui-egui/tests/it/popup_press_close.rs +++ b/crates/ui-egui/tests/it/popup_press_close.rs @@ -133,6 +133,7 @@ fn a_stroke_on_the_model_closes_the_symmetry_settings() { harness.run_steps(SETTLE_FRAMES); harness.get_by_label("Symmetry settings").click(); harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_label("Radial symmetry").is_some(), "the settings open"); stroke_on_model(&mut harness, Modifiers::NONE); diff --git a/crates/ui-egui/tests/it/properties_min_width.rs b/crates/ui-egui/tests/it/properties_min_width.rs index 79c39f5d..f9d5fd68 100644 --- a/crates/ui-egui/tests/it/properties_min_width.rs +++ b/crates/ui-egui/tests/it/properties_min_width.rs @@ -39,6 +39,7 @@ fn set_column_width(harness: &mut Harness<'_, TextureCraftApp>, width: f32) { let mut workspace = harness.state().ui.dock.workspace().clone(); let Some(Node::Split { second, .. }) = workspace.layout.root.as_mut() else { panic!("the assets column and the rest") }; let Node::Split { size, .. } = second.as_mut() else { panic!("the 3D view and the right column") }; + *size = SplitSize::FixedSecond(width); harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); harness.run_steps(SETTLE_FRAMES); @@ -86,12 +87,14 @@ fn dragging_the_right_column_narrow_stops_at_the_properties_minimum_width() { set_column_width(&mut harness, WIDE_COLUMN); let before = properties_title(&harness).min.x; + assert!(properties_header_width(&harness) > at_minimum, "a wide column gives Properties more than its minimum"); let y = properties_title(&harness).max.y + DIVIDER_GRAB_BELOW_HEADER; drag(&mut harness, pos2(before - DIVIDER_OFFSET, y), pos2(WINDOW_SIZE.x - WINDOW_RIGHT_INSET, y)); assert!(properties_title(&harness).min.x > before, "the divider moved right"); + let width = properties_header_width(&harness); assert!((width - at_minimum).abs() < 0.5, "Properties stopped at its minimum: header {width}, {at_minimum} at the minimum"); } @@ -104,5 +107,6 @@ fn a_layout_saved_narrower_draws_properties_at_its_minimum_width() { set_column_width(&mut harness, PROPERTIES_MIN_WIDTH * 0.5); let width = properties_header_width(&harness); + assert!((width - at_minimum).abs() < 0.5, "a narrow saved column opens at the minimum: header {width}, {at_minimum} at the minimum"); } diff --git a/crates/ui-egui/tests/it/rail.rs b/crates/ui-egui/tests/it/rail.rs index 30f3a153..b6b3617b 100644 --- a/crates/ui-egui/tests/it/rail.rs +++ b/crates/ui-egui/tests/it/rail.rs @@ -186,6 +186,7 @@ fn dragging_the_title_onto_a_tab_strip_docks_the_panel_there() { // The popup covers the Properties strip and stays put while dragged: drop on the Texture Sets strip above it let texture_sets_tab = harness.get_by_label("Texture Sets").rect(); assert!(texture_sets_tab.bottom() < title.top(), "the Texture Sets strip {texture_sets_tab:?} is under the popup at {title:?}"); + drag(&mut harness, title.center(), texture_sets_tab.center()); let layout = &harness.state().ui.dock.workspace().layout; diff --git a/crates/ui-egui/tests/it/split_divider.rs b/crates/ui-egui/tests/it/split_divider.rs index 075d4b80..63ce4ee7 100644 --- a/crates/ui-egui/tests/it/split_divider.rs +++ b/crates/ui-egui/tests/it/split_divider.rs @@ -133,15 +133,18 @@ fn dragging_the_divider_resizes_the_views_within_their_minimum_width() { assert_eq!(harness.state().ui.split_ratio, 0.5); drag(&mut harness, PointerButton::Primary, pos2(start_x, y), pos2(start_x - 200.0, y)); + assert!((divider_x(&harness) - (start_x - 200.0)).abs() < 0.5, "follows the pointer: {}", divider_x(&harness)); assert!((harness.state().ui.split_ratio - (start_x - 200.0 - views_left) / views_width).abs() < 1e-3); let x = divider_x(&harness); drag(&mut harness, PointerButton::Primary, pos2(x, y), pos2(views_left + 10.0, y)); + assert!((divider_x(&harness) - views_left - MIN_VIEW_WIDTH).abs() < 0.5, "clamped on the left: {}", divider_x(&harness)); let x = divider_x(&harness); drag(&mut harness, PointerButton::Primary, pos2(x, y), pos2(views_right - 10.0, y)); + assert!((views_right - divider_x(&harness) - MIN_VIEW_WIDTH).abs() < 0.5, "clamped on the right: {}", divider_x(&harness)); } From 32f848c7c59e6de6f794b971ff49cb1cf72f05e5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:12 +0000 Subject: [PATCH 14/17] Fills: engine evaluation, commands and the remaining tests for the Fill tab --- Cargo.lock | 1 + apps/texturecraft/Cargo.toml | 4 + apps/texturecraft/src/main.rs | 55 +- crates/automation/src/render.rs | 2 +- crates/compose/src/eval.rs | 802 +++++++++++++----- crates/compose/src/fill_copy.rs | 34 + crates/compose/src/lib.rs | 14 +- crates/compose/src/store.rs | 200 ++++- crates/compose/src/tile_pattern.rs | 2 +- crates/compose/tests/cache_and_instances.rs | 33 +- crates/core/src/backface.rs | 23 + crates/core/src/depth_culling.rs | 23 + crates/core/src/lib.rs | 23 +- crates/core/src/project.rs | 12 +- crates/core/src/projector.rs | 40 + crates/core/src/saved_projection.rs | 30 + crates/core/src/shape_crop.rs | 27 + crates/engine/src/commands.rs | 2 + crates/engine/src/filter_lib.rs | 2 +- crates/engine/src/inspect.rs | 65 +- crates/engine/src/layer_cmds.rs | 343 ++++++-- crates/engine/src/lib.rs | 2 + crates/engine/src/mask_cmds.rs | 26 +- crates/engine/src/materials.rs | 12 +- crates/engine/src/pbr_cmds.rs | 13 +- crates/engine/src/resource_cmds.rs | 4 +- crates/engine/src/session.rs | 4 + crates/engine/src/smart_masks.rs | 3 +- crates/engine/src/thumbs.rs | 29 +- crates/engine/src/view_cmds.rs | 121 +-- crates/engine/tests/it/main.rs | 6 +- crates/engine/tests/it/painter_gaps.rs | 55 +- crates/engine/tests/it/tile_generator.rs | 4 +- crates/engine/tests/it/user_smart_mask.rs | 5 +- crates/geom/src/mesh.rs | 20 + crates/paint/src/brush.rs | 15 +- crates/paint/src/pickup.rs | 7 +- crates/render/tests/headless.rs | 4 +- crates/ui-egui/src/dock.rs | 680 ++++++++------- crates/ui-egui/src/exact_entry_open.rs | 5 + crates/ui-egui/src/gpu.rs | 2 +- crates/ui-egui/src/gray_slider.rs | 5 +- crates/ui-egui/src/i18n.rs | 21 + crates/ui-egui/src/lib.rs | 79 +- crates/ui-egui/src/past_end.rs | 10 + crates/ui-egui/src/placement.rs | 9 + crates/ui-egui/src/properties_popup.rs | 16 +- crates/ui-egui/src/render_mode/tests.rs | 4 +- crates/ui-egui/src/resolution_band.rs | 138 +++ crates/ui-egui/src/shelf_preview.rs | 4 +- crates/ui-egui/src/theme.rs | 20 + crates/ui-egui/src/thumbs.rs | 14 +- crates/ui-egui/src/viewport.rs | 384 ++------- crates/ui-egui/src/widgets.rs | 78 +- crates/ui-egui/tests/it/decal_proportions.rs | 113 --- crates/ui-egui/tests/it/decal_symmetry.rs | 106 --- crates/ui-egui/tests/it/effect_decal.rs | 65 -- .../tests/it/fill_projection_section.rs | 102 --- crates/ui-egui/tests/it/fill_support.rs | 52 ++ crates/ui-egui/tests/it/filter_support.rs | 51 ++ crates/ui-egui/tests/it/main.rs | 8 +- crates/ui-egui/tests/it/panel_header.rs | 25 + crates/ui-egui/tests/it/polygon_fill.rs | 19 + crates/ui-egui/tests/it/project_config.rs | 8 +- crates/ui-egui/tests/it/properties_popup.rs | 83 +- crates/ui-egui/tests/it/shelf_drop.rs | 6 +- crates/ui-egui/tests/it/symmetry.rs | 6 +- crates/ui-egui/tests/ui_snapshots.rs | 472 ++++++++++- 68 files changed, 3111 insertions(+), 1541 deletions(-) create mode 100644 crates/compose/src/fill_copy.rs create mode 100644 crates/core/src/backface.rs create mode 100644 crates/core/src/depth_culling.rs create mode 100644 crates/core/src/projector.rs create mode 100644 crates/core/src/saved_projection.rs create mode 100644 crates/core/src/shape_crop.rs create mode 100644 crates/ui-egui/src/exact_entry_open.rs create mode 100644 crates/ui-egui/src/past_end.rs create mode 100644 crates/ui-egui/src/placement.rs create mode 100644 crates/ui-egui/src/resolution_band.rs delete mode 100644 crates/ui-egui/tests/it/decal_proportions.rs delete mode 100644 crates/ui-egui/tests/it/decal_symmetry.rs delete mode 100644 crates/ui-egui/tests/it/effect_decal.rs delete mode 100644 crates/ui-egui/tests/it/fill_projection_section.rs create mode 100644 crates/ui-egui/tests/it/fill_support.rs create mode 100644 crates/ui-egui/tests/it/filter_support.rs diff --git a/Cargo.lock b/Cargo.lock index a06f2619..f9292a97 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4604,6 +4604,7 @@ dependencies = [ "craft-update", "eframe", "egui", + "egui_kittest", "image", "log", "rfd", diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index e3fb936a..cab8493e 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -38,5 +38,9 @@ craft-update = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] craft-menu = { workspace = true } +[dev-dependencies] +# The pointer-hold test drives the windowed app's frames (src/main.rs) +egui_kittest = { version = "0.37", features = ["eframe"] } + [build-dependencies] winresource = "0.1" diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index ec60c58c..3a768c2b 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -164,12 +164,15 @@ impl eframe::App for Shell { self.app.save(storage); } - fn raw_input_hook(&mut self, _ctx: &egui::Context, _raw: &mut egui::RawInput) { + fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { // winit gives the window its caption back when it changes the window's flags (maximize, // restore, …): take it off again before the frame is laid out. if let Some(guard) = self.window_frame.as_mut() { guard(); } + + // The app's own hook: a drag holding the pointer reads its moves from it + self.app.raw_input_hook(ctx, raw); } fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { @@ -388,4 +391,54 @@ mod tests { std::fs::remove_file(&ron_path).unwrap(); assert_eq!(saved_prefs(Some(&json_path), Some(&ron_path)), texturecraft_ui_egui::state::Prefs::default()); } + + /// How far the test's drag moves the mouse in one frame, in points + const DRAG_STEP: egui::Vec2 = egui::vec2(80.0, 0.0); + + /// Points within which a put-back lands on the press point (the system rounds it to whole pixels) + const PUT_BACK_REACH: f32 = 1.0; + + /// One frame of the window: the system's events go through the window's raw input hook, as eframe sends them; returns what the app asked of the window + fn window_frame(harness: &mut egui_kittest::Harness<'static, Shell>, events: Vec) -> Vec { + let ctx = harness.ctx.clone(); + let mut raw = harness.input_mut().clone(); + raw.events.extend(events); + eframe::App::raw_input_hook(harness.state_mut(), &ctx, &mut raw); + *harness.input_mut() = raw; + harness.step(); + harness.output().viewport_output.get(&egui::ViewportId::ROOT).map(|viewport| viewport.commands.clone()).unwrap_or_default() + } + + /// Holding the fill's preview square in the window holds the system's pointer: put back to the press point every frame, or locked where the system locks it + #[test] + fn the_window_holds_the_pointer_while_the_preview_square_is_held() { + let session = Session::new_project("Hold", texturecraft_engine::geom::primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap(); + let builder = egui_kittest::Harness::builder().with_size(egui::vec2(DEFAULT_SIZE[0], DEFAULT_SIZE[1])); + let mut harness = builder.build_eframe(|cc| Shell { + app: TextureCraftApp::new(cc, session), + window_frame: None, + #[cfg(target_os = "macos")] + movable: None, + }); + harness.run_steps(4); + let layer = harness.state_mut().app.run("layer.add.fill", serde_json::json!({})).unwrap()["layer"].clone(); + harness.state_mut().app.run("layer.fill.projection", serde_json::json!({"layer": layer, "projection": "triplanar"})).unwrap(); + harness.run_steps(2); + + let pad = egui_kittest::kittest::Queryable::get_by_label(&harness, "Move on model").rect().center(); + let press = egui::Event::PointerButton { pos: pad, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; + let pressed = window_frame(&mut harness, vec![egui::Event::PointerMoved(pad), press]); + let locked = pressed.contains(&egui::ViewportCommand::CursorGrab(egui::CursorGrab::Locked)); + + // A locked pointer stays still and the system reports only its raw motion + let mut moves = vec![egui::Event::MouseMoved(DRAG_STEP)]; + if !locked { + moves.push(egui::Event::PointerMoved(pad + DRAG_STEP)); + } + let moved = window_frame(&mut harness, moves); + let put_back = moved.iter().any(|command| matches!(command, egui::ViewportCommand::CursorPosition(to) if to.distance(pad) <= PUT_BACK_REACH)); + assert!(locked || put_back, "the window puts the pointer back where the press began, so it never leaves: {moved:?}"); + let seen = harness.ctx.input(|input| input.pointer.latest_pos()); + assert!(seen.is_some_and(|seen| seen.distance(pad + DRAG_STEP) <= PUT_BACK_REACH), "the app reads the whole move: {seen:?}"); + } } diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index 8e809021..588f1752 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -285,7 +285,7 @@ mod tests { mesh.append(&texturecraft_engine::geom::primitives::plane(2.0, 1)); let mut session = Session::new_project("Test", mesh, "two-planes", None, 128).unwrap(); assert_eq!(session.caches.len(), 2); - session.images.insert("red".into(), Arc::new(ImageRes { width: 1, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0]], srgb: true })); + session.images.insert("red".into(), Arc::new(ImageRes::new(1, 1, vec![[1.0, 0.0, 0.0, 1.0]], true))); execute(&mut session, "viewport.view", &json!({"mode": "image", "image": "red"})).unwrap(); let camera = session.camera; let uv = |ts| ViewKind::Uv { ts, zoom: 1.0, pan: [0.0, 0.0], rotation: 0.0 }; diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 8bb323e9..adbf91ae 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -15,18 +15,29 @@ use texturecraft_core::{ blend1, blend3, lum, mix3, per_unit, }; use texturecraft_geom::glam::{Vec2, Vec3}; -use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; +use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; use crate::below::{Band, BelowCache, Level, StackKey}; use crate::curvature_sizes::CurvatureSizes; +use crate::fill_copies::FillCopies; +use crate::fill_copy::FillCopy; +use crate::fill_place::FillPlace; use crate::held_fields::HeldFields; -use crate::pattern::{Coords, decal_uv_symmetric, image_samples, pattern_pixels, procedural_in, world_noise}; +use crate::pattern::{Coords, image_samples, mesh_frame, pattern_pixels, procedural_in, world_noise}; use crate::pattern_context::PatternContext; -use crate::store::{BakedMaps, ImageStore, PixelStore, decode}; +use crate::projector_cover::{framed_cover, projector_cover, projector_covers_all}; +use crate::projector_depth::ProjectorDepth; +use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; const NCH: usize = Channel::ALL.len(); +/// Coverage past which a symmetric fill's remaining copies would not show under the ones above +const COVERED: f32 = 0.9999; + +/// Share of an image's longer side a step to the next texel may jump before it counts as a UV seam +const SEAM_JUMP_SHARE: f32 = 0.25; + /// Stack values being composited, per channel. type Acc = [[f32; 3]; NCH]; @@ -211,8 +222,16 @@ struct ChanPlan<'a> { } enum Content<'a> { - Paint { preview: bool }, - Fill(&'a Fill), + Paint { + preview: bool, + }, + Fill { + fill: Box>, + /// Its projector's depth map when it culls by depth + depth: Option>, + /// Whether it covers every texel (see [`covers_every_texel`]), so no texel asks + covers_all: bool, + }, Group(Vec>), } @@ -228,6 +247,10 @@ struct EffectPlan<'a> { curvature_sizes: Option>, /// A filtered mask stage retained because an anchor above it records that stage. filtered_mask: Option<&'a Field>, + /// The projector's depth map of a fill or material effect that culls by depth + depth: Option>, + /// Whether a fill or material effect covers every texel (see [`covers_every_texel`]), so no texel asks + covers_all: bool, } struct MaskPlan<'a> { @@ -969,7 +992,7 @@ fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, .collect() } -/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset. +/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset fn finish_generator(generator: &Generator, ramp: f32) -> f32 { let value = generator.global.apply(ramp); let value = if generator.invert { 1.0 - value } else { value }; @@ -1063,10 +1086,9 @@ struct Node<'a> { content: Content<'a>, chans: Vec>, mask: Option>, - /// Visible anchor points of the layer: recorded after it is applied, or (`Some(k)`, an - /// anchor with visible effects above it) with its content cut after `k` visible effects. + /// Visible anchor points of the layer: recorded after it is applied, or (`Some(k)`, an anchor with visible effects above it) with its content cut after `k` visible effects anchors: Vec<(LayerId, Option)>, - /// The node or one of its children records an anchor. + /// The node or one of its children records an anchor has_anchor: bool, height_mask: HeightMask, /// Geometry mask: whether the layer shows on each mesh submesh (None: everywhere). @@ -1088,6 +1110,12 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y EffectKind::Generator(Generator { detail: Some(detail), .. }) => CurvatureSizes::of(inp, &detail.blurred_sizes_in_use()), _ => None, }; + let (depth, covers_all) = match &effect.kind { + EffectKind::Fill { projection, sampling, .. } | EffectKind::Material(Fill { projection, sampling, .. }) => { + fill_coverage(inp, projection, *sampling) + } + _ => (None, false), + }; EffectPlan { id: effect.id, kind: &effect.kind, @@ -1097,6 +1125,8 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y preview: previews(inp, target), curvature_sizes, filtered_mask: None, + depth, + covers_all, } }) .collect() @@ -1145,6 +1175,7 @@ fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, t if depth > texturecraft_core::project::MAX_DEPTH { return Vec::new(); } + list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true)).collect() } @@ -1188,7 +1219,9 @@ fn plan_node<'a>( .collect::>(); let content = match &layer.kind { LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) }, - LayerKind::Fill(f) => Content::Fill(f), + LayerKind::Fill(f) => { + let (depth, covers_all) = fill_coverage(inp, &f.projection, f.sampling); + } LayerKind::Group { children, .. } => Content::Group(if kids { plan(inp, children, channels, tx, ty, depth + 1, fields) } else { Vec::new() }), // `content_layer` already followed instance links @@ -1256,7 +1289,7 @@ fn blend_chan(c: &ChanPlan, mode: BlendMode, a: [f32; 3], b: [f32; 3]) -> [f32; if c.comps == 3 { blend3(mode, a, b) } else { [blend1(mode, a[0], b[0]); 3] } } -/// Lay value `p` with weight `a` over a straight value and coverage (premultiplied "over"). +/// Lay value `p` with weight `a` over a straight value and coverage (premultiplied "over") fn over(c: &ChanPlan, mode: BlendMode, v: [f32; 3], cov: f32, p: [f32; 3], a: f32) -> ([f32; 3], f32) { if a <= 0.0 { return (v, cov); @@ -1266,8 +1299,29 @@ fn over(c: &ChanPlan, mode: BlendMode, v: [f32; 3], cov: f32, p: [f32; 3], a: f3 (mix3(v, b, a / nc.max(1e-5)), nc) } -/// The plain UV projection a decal's frame coordinates are sampled through. -const DECAL_UV: Projection = Projection::Uv { scale: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] }; +/// Whether a fill placed by `proj` repeats past its tile both ways, so no texel falls outside it (tri-planar never ends) +fn repeats_everywhere(proj: &Projection, sampling: Sampling) -> bool { + sampling.wrap.repeats() == (true, true) || matches!(proj, Projection::Triplanar { .. }) +} + +/// Whether a fill placed by `proj` covers every texel: it repeats, nothing crops or culls it and it is not framed on the surface +fn covers_every_texel(proj: &Projection, sampling: Sampling, depth: Option<&ProjectorDepth>) -> bool { + let framed = matches!(proj, Projection::Planar { placed: Some(_), .. } | Projection::Warp { .. }); + let depth_culled = depth.is_some() && proj.depth_culling().is_some(); + !framed && !depth_culled && repeats_everywhere(proj, sampling) && projector_covers_all(proj) +} + +/// A fill's projector depth (None: not culled by depth) and whether it covers every texel +fn fill_coverage(inp: &Inputs, projection: &Projection, sampling: Sampling) -> (Option>, bool) { + let depth = ProjectorDepth::of(inp.mesh, inp.bounds, projection); + let covers_all = covers_every_texel(projection, sampling, depth.as_deref()); + (depth, covers_all) +} + +/// Whether a fill placed by `proj` is sampled once per copy of `sampling`'s symmetry +fn takes_symmetry(proj: &Projection, sampling: Sampling) -> bool { + sampling.symmetry.on && proj.takes_symmetry() +} /// Per-texel context. struct Texel<'a, 'b> { @@ -1285,6 +1339,8 @@ struct Texel<'a, 'b> { anchors: Vec<(LayerId, Acc, bool)>, /// Where `eval` takes layer masks and content from. tape: Tape<'b>, + /// The copy of a symmetric fill being sampled: the surface point and normal it sees, and its image's flip + copy: Option, } /// What a layer contributes (its mask, its content value and coverage per channel): evaluated @@ -1369,29 +1425,142 @@ impl<'a, 'b> Texel<'a, 'b> { if let Some(c) = self.coords { return c; } + + #[cfg(test)] + tests::COORDS_LOOKUPS.with(|count| count.set(count.get() + 1)); + let g = self.inp.gbuf; - let i = (self.y * g.width + self.x) as usize; - let (lo, hi) = self.inp.bounds; - let center = (lo + hi) * 0.5; - let r = ((hi - lo).length() * 0.5).max(1e-4); - let mut c = match g.surface(self.inp.mesh, i) { - Some(s) => Coords { uv: s.uv, pos: (s.pos - center) / r, nrm: s.nrm }, - None => Coords { uv: Vec2::new((self.x as f32 + 0.5) / g.width as f32, (self.y as f32 + 0.5) / g.height as f32), pos: Vec3::ZERO, nrm: Vec3::Y }, + let c = match self.surface((self.y * g.width + self.x) as usize) { + Some(s) => self.coords_of(s), + None => self.tile_uv(Coords { + uv: Vec2::new((self.x as f32 + 0.5) / g.width as f32, (self.y as f32 + 0.5) / g.height as f32), + pos: Vec3::ZERO, + nrm: Vec3::Y, + }), }; - // UV-tiled sets: projections see the mesh's own UVs (patterns repeat per tile). + self.coords = Some(c); + c + } + + /// The coordinates projections see at surface `s`: its UV, and its position in mesh radii from the mesh's centre + #[inline(always)] + fn coords_of(&self, s: Surface) -> Coords { + let (center, radius) = mesh_frame(self.inp.bounds); + self.tile_uv(Coords { uv: s.uv, pos: (s.pos - center) / radius, nrm: s.nrm }) + } + + /// `c` with its UV moved out of the atlas on a UV-tiled set, so projections see the mesh's own UVs (patterns repeat per tile) + #[inline(always)] + fn tile_uv(&self, mut c: Coords) -> Coords { if let Ok(set) = self.inp.project.texture_set(self.inp.ts) && let Some(grid) = set.tile_grid() { c.uv = Vec2::from(set.from_atlas(&grid, c.uv.to_array())); } - self.coords = Some(c); c } - /// World position of this texel (None when uncovered). + /// The coordinates of texel (`x`, `y`) through `proj`, uncached (None when uncovered) + fn projected_at(&self, proj: &Projection, x: u32, y: u32) -> Option { + let g = self.inp.gbuf; + if x >= g.width || y >= g.height { + return None; + } + + let s = self.surface((y * g.width + x) as usize)?; + let c = self.coords_of(s); + if proj.frame().is_none() { + return Some(c); + } + + let (center, _) = mesh_frame(self.inp.bounds); + framed_cover(proj, s.pos, s.nrm, center).map(|(uv, _)| Coords { uv, ..c }) + } + + /// Image texels one surface texel spans at each of `samples`, from the next texel across and down (1 at a seam) + fn footprints(&self, proj: &Projection, samples: &[(Vec2, f32); 3], image: &ImageRes) -> [f32; 3] { + let size = Vec2::new(image.width as f32, image.height as f32); + let mut out = [1.0f32; 3]; + for (dx, dy) in [(1, 0), (0, 1)] { + let Some(next) = self.projected_at(proj, self.x + dx, self.y + dy) else { continue }; + for ((footprint, (uv, _)), (next_uv, _)) in out.iter_mut().zip(samples).zip(self.image_uvs(proj, &next)) { + let span = ((next_uv - *uv) * size).length(); + + // A jump across more of the image than this is a UV seam, not the texel's size + if span.is_finite() && span < size.max_element() * SEAM_JUMP_SHARE { + *footprint = footprint.max(span); + } + } + } + out + } + + /// World position of this texel as the fill copy being sampled sees it (None when uncovered) fn world(&self) -> Option { - let i = (self.y * self.inp.gbuf.width + self.x) as usize; - self.inp.gbuf.surface(self.inp.mesh, i).map(|s| s.pos) + self.surface((self.y * self.inp.gbuf.width + self.x) as usize).map(|s| s.pos) + } + + /// The surface at G-buffer index `i`, as the fill copy being sampled sees it + #[inline(always)] + fn surface(&self, i: usize) -> Option { + let mut s = self.inp.gbuf.surface(self.inp.mesh, i)?; + if let Some(copy) = self.copy { + s.pos = copy.point(s.pos); + s.nrm = copy.normal(s.nrm); + s.geo_nrm = copy.normal(s.geo_nrm); + } + Some(s) + } + + /// Where `proj` reads images at `coords`, turned over as the fill copy being sampled says + fn image_uvs(&self, proj: &Projection, coords: &Coords) -> [(Vec2, f32); 3] { + let samples = image_samples(proj, coords); + match self.copy { + Some(copy) => samples.map(|(uv, weight)| (copy.uv(uv), weight)), + None => samples, + } + } + + /// A fill's value and coverage through `proj`, from `one` (which samples it once): with `sampling`'s symmetry on, every copy of the projection is sampled and the copies are laid over each other, the texel's own copy on top + fn symmetric(&mut self, proj: &Projection, sampling: Sampling, mut one: impl FnMut(&mut Self) -> ([f32; 3], f32)) -> ([f32; 3], f32) { + // Most fills have no symmetry: they are sampled directly and never pay for the surface lookup + if !takes_symmetry(proj, sampling) { + return one(self); + } + + self.symmetric_copies(sampling, one) + } + + /// [`Texel::symmetric`] with symmetry on: every copy sampled and laid over the others + fn symmetric_copies(&mut self, sampling: Sampling, mut one: impl FnMut(&mut Self) -> ([f32; 3], f32)) -> ([f32; 3], f32) { + let Some(world) = self.inp.gbuf.surface(self.inp.mesh, (self.y * self.inp.gbuf.width + self.x) as usize).map(|surface| surface.pos) else { + return one(self); + }; + + let (center, radius) = mesh_frame(self.inp.bounds); + let cached = self.coords.take(); + let mut value = [0.0f32; 3]; + let mut cover = 0.0f32; + for copy in FillCopies::new(&sampling.symmetry, world, center, radius) { + self.copy = Some(copy); + self.coords = None; + let (copy_value, copy_cover) = one(self); + let weight = copy_cover.clamp(0.0, 1.0) * (1.0 - cover); + for (total, part) in value.iter_mut().zip(copy_value) { + *total += part * weight; + } + cover += weight; + if cover >= COVERED { + break; + } + } + self.copy = None; + self.coords = cached; + if cover <= 0.0 { + return ([0.0; 3], 0.0); + } + + (value.map(|v| v / cover), cover) } fn baked(&self, m: BakedMap) -> Option { @@ -1402,33 +1571,90 @@ impl<'a, 'b> Texel<'a, 'b> { self.inp.baked.sample_working(map, self.x, self.y, (self.res, self.inp.gbuf.height), &self.inp.block_scales) } - /// Where projection `proj` samples this texel: the texel's coordinates, or for a decal its - /// position in the decal's frame (then sampled as UVs) and the decal's coverage. - fn projected<'p>(&mut self, proj: &'p Projection) -> (Coords, &'p Projection, f32) { + /// Where `proj` samples this texel: its coordinates, or for a projection from a frame on the surface (placed planar, warp) its place in the frame, and how much backface culling and the shape crop let through + fn projected(&mut self, proj: &Projection) -> (Coords, f32) { let c = self.coords(); - let (lo, hi) = self.inp.bounds; - let center = (lo + hi) * 0.5; - match proj { - Projection::Decal(d) => match self.world().and_then(|p| decal_uv_symmetric(d, p, c.nrm, center)) { - Some((uv, w)) => (Coords { uv, ..c }, &DECAL_UV, w), - None => (c, &DECAL_UV, 0.0), - }, - _ => (c, proj, 1.0), + if proj.frame().is_none() { + return (c, 1.0); + } + + let (center, _) = mesh_frame(self.inp.bounds); + + match self.world().and_then(|p| framed_cover(proj, p, c.nrm, center)) { + Some((uv, cover)) => (Coords { uv, ..c }, cover), + None => (c, 0.0), } } - /// How much a fill projected by `proj` covers this texel: 1, or for a decal its frame - /// coverage times the alpha of its first image source. - fn cover<'s>(&mut self, mut sources: impl Iterator, proj: &Projection) -> f32 { - if !matches!(proj, Projection::Decal(_)) { - return 1.0; + /// `place`'s fill at this texel in channel `ch`, every symmetric copy laid over each other when its symmetry is on + #[inline(always)] + fn fill_place_texel(&mut self, place: FillPlace, source: Option<&Source>, ch: Channel) -> ([f32; 3], f32) { + // Without symmetry the fill is sampled directly: through `symmetric`'s closure a plain fill composites about 8% slower + if takes_symmetry(&place.fill.projection, place.fill.sampling) { + self.symmetric(&place.fill.projection, place.fill.sampling, |texel| texel.fill_texel(place, source, ch)) + } else { + self.fill_texel(place, source, ch) } - let (c, _, w) = self.projected(proj); + } + + /// `place`'s fill sampled once at this texel: its value in channel `ch` (`source`, else the channel's default) and its coverage + #[inline(always)] + fn fill_texel(&mut self, place: FillPlace, source: Option<&Source>, ch: Channel) -> ([f32; 3], f32) { + let FillPlace { fill, depth, covers_all } = place; + let value = match source { + Some(source) => self.source(source, &fill.projection, fill.sampling, ch.kind()), + None => ch.default_value(), + }; + let cover = if covers_all { 1.0 } else { self.cover(fill.sources.values(), &fill.projection, fill.sampling, depth) }; + (value, cover) + } + + /// How much a fill projected by `proj` covers this texel: [`Texel::shape_cover`], then depth culling through the projector's `depth` map + fn cover<'s>(&mut self, sources: impl Iterator, proj: &Projection, sampling: Sampling, depth: Option<&ProjectorDepth>) -> f32 { + #[cfg(test)] + tests::COVER_CALLS.with(|count| count.set(count.get() + 1)); + + let cover = self.shape_cover(sources, proj, sampling); + match depth.zip(proj.depth_culling()) { + Some((depth, culling)) if cover > 0.0 => cover * self.world().map_or(1.0, |p| depth.cover(p, culling.hardness)), + _ => cover, + } + } + + /// How much a fill projected by `proj` covers this texel: wrap, shape crop and backface culling, and a cropped framed projection's image alpha + fn shape_cover<'s>(&mut self, mut sources: impl Iterator, proj: &Projection, sampling: Sampling) -> f32 { + let (Projection::Planar { projector, placed: Some(_), .. } | Projection::Warp { projector, .. }) = proj else { + // Repeating with nothing cropped or culled, a fill covers every texel without looking up where the texel is + if repeats_everywhere(proj, sampling) && projector_covers_all(proj) { + return 1.0; + } + + let coords = self.coords(); + return self.tile_cover(proj, &coords, sampling) * projector_cover(proj, &coords); + }; + + let (c, cover) = self.projected(proj); + if projector.crop == ShapeCrop::ExtendsOutside { + return cover * self.tile_cover(proj, &c, sampling); + } + + // Cropped to its shape, a framed projection takes the shape of its image too let image = sources.find_map(|s| match s { Source::Image { name, .. } => self.inp.images.get(name), _ => None, }); - w * image.map_or(1.0, |img| img.sample(c.uv.x, c.uv.y)[3].clamp(0.0, 1.0)) + let samples = self.image_uvs(proj, &c); + let [(uv, _), ..] = samples; + + // The shape is read over the footprint the image's colour is, so a shrunk image's coverage matches its averaged colour + let alpha = image.map_or(1.0, |img| { + let [footprint, ..] = match sampling.filtering { + Filtering::BilinearHq => self.footprints(proj, &samples, img), + Filtering::BilinearSharp | Filtering::Nearest => [1.0; 3], + }; + img.sample_filtered(uv.x, uv.y, sampling, footprint)[3].clamp(0.0, 1.0) + }); + cover * alpha * self.tile_cover(proj, &c, sampling) } /// The stack value anchor point `anchor` recorded for `channel` (the channel default for an @@ -1443,8 +1669,20 @@ impl<'a, 'b> Texel<'a, 'b> { self.anchors.iter().rev().find(|(id, ..)| *id == anchor).is_some_and(|(_, _, mask)| *mask) } + /// 1 where a fill placed by `proj` at `coords` lands inside its 0..1 tile on every axis `sampling.wrap` does not repeat, else 0 + fn tile_cover(&self, proj: &Projection, coords: &Coords, sampling: Sampling) -> f32 { + if repeats_everywhere(proj, sampling) { + return 1.0; + } + + let (across, down) = sampling.wrap.repeats(); + let [(uv, _), ..] = self.image_uvs(proj, coords); + let inside = |t: f32, repeats: bool| repeats || (0.0..1.0).contains(&t); + if inside(uv.x, across) && inside(uv.y, down) { 1.0 } else { 0.0 } + } + /// The value `source` gives this texel through `projection`, read as a channel of `kind` - fn source(&mut self, source: &Source, projection: &Projection, kind: ChannelKind) -> [f32; 3] { + fn source(&mut self, source: &Source, projection: &Projection, sampling: Sampling, kind: ChannelKind) -> [f32; 3] { match source { Source::Uniform(value) => *value, @@ -1457,7 +1695,7 @@ impl<'a, 'b> Texel<'a, 'b> { texturecraft_core::gradient(ramp, lightness).unwrap_or_default() } Source::Procedural { pattern, low, high, ramp } => { - let (coords, projection, _) = self.projected(projection); + let (coords, _) = self.projected(projection); let pixels = if pattern.resolution.can_reduce() { let uv_tile = self.inp.tile_res_at(self.x, self.y); let texture_set = self.inp.project.texture_set(self.inp.ts).map_or(uv_tile, |set| set.resolution); @@ -1476,10 +1714,15 @@ impl<'a, 'b> Texel<'a, 'b> { Source::Image { name, normal_format } => { let Some(image) = self.inp.images.get(name) else { return [0.5; 3] }; - let (coords, projection, _) = self.projected(projection); + let (coords, _) = self.projected(projection); + let samples = self.image_uvs(projection, &coords); + let footprints = match sampling.filtering { + Filtering::BilinearHq => self.footprints(projection, &samples, image), + Filtering::BilinearSharp | Filtering::Nearest => [1.0; 3], + }; let mut sum = [0.0f32; 4]; - for (uv, weight) in image_samples(projection, &coords).into_iter().filter(|(_, weight)| *weight > 0.0) { - for (total, value) in sum.iter_mut().zip(image.sample(uv.x, uv.y)) { + for ((uv, weight), footprint) in samples.into_iter().zip(footprints).filter(|((_, weight), _)| *weight > 0.0) { + for (total, value) in sum.iter_mut().zip(image.sample_filtered(uv.x, uv.y, sampling, footprint)) { *total += value * weight; } } @@ -1575,7 +1818,8 @@ impl<'a, 'b> Texel<'a, 'b> { /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). fn generator_input(&mut self, generator: &Generator, map: BakedMap) -> Option { match generator.inputs.get(&map) { - Some(source) => Some(self.source(source, &Projection::default(), ChannelKind::Scalar)[0]), + // Generator inputs have no sampling setting: they read as projects saved before sampling choices did + Some(source) => Some(self.source(source, &Projection::default(), Sampling::SAVED_BEFORE, ChannelKind::Scalar)[0]), None => self.baked(map), } } @@ -1672,9 +1916,15 @@ impl<'a, 'b> Texel<'a, 'b> { value += (blend1(effect.blend, value, layer_value) - value) * coverage * opacity; } } - EffectKind::Fill { source, projection } => { - let fill = self.source(source, projection, ChannelKind::Scalar)[0]; - value += (blend1(effect.blend, value, fill) - value) * opacity * self.cover(std::iter::once(source), projection); + EffectKind::Fill { source, projection, sampling } => { + let once = |texel: &mut Self| { + let fill = texel.source(source, projection, *sampling, ChannelKind::Scalar); + let cover = if effect.covers_all { 1.0 } else { texel.cover(std::iter::once(source), projection, *sampling, effect.depth.as_deref()) }; + (fill, cover) + }; + // Sampled directly without symmetry, as `Texel::fill_place_texel` is + let ([fill, ..], cover) = if takes_symmetry(projection, *sampling) { self.symmetric(projection, *sampling, once) } else { once(self) }; + value += (blend1(effect.blend, value, fill) - value) * opacity * cover; } EffectKind::Generator(generator) => { let generated = self.generator(generator, effect.curvature_sizes.as_deref()); @@ -1712,56 +1962,55 @@ impl<'a, 'b> Texel<'a, 'b> { value.clamp(0.0, 1.0) } - /// Composite `nodes` over `acc`, recording anchors. Returns true when it reached the `stop` - /// layer (`acc` then holds the stack below it). + /// Composite `nodes` over `acc`, recording anchors; true when it reached the `stop` layer (`acc` then holds the stack below it) fn eval(&mut self, nodes: &[Node], acc: &mut Acc) -> bool { - for n in nodes { - if self.stop == Some(n.id) { + for node in nodes { + if self.stop == Some(node.id) { return true; } - let m = self.tape_mask(n); - match &n.content { + let mask = self.tape_mask(node); + match &node.content { // Masked-out groups still run when they record anchors or hold the stop layer - Content::Group(children) if m > 0.0 || n.has_anchor || self.stop.is_some() => { + Content::Group(children) if mask > 0.0 || node.has_anchor || self.stop.is_some() => { let mut inner = *acc; if self.eval(children, &mut inner) { return true; } - if m > 0.0 { - mix_group(acc, &inner, &n.chans, m); + if mask > 0.0 { + mix_group(acc, &inner, &node.chans, mask); } } - Content::Fill(_) | Content::Paint { .. } if m > 0.0 => { - let before = if n.anchors.iter().any(|a| a.1.is_some()) { Some(*acc) } else { None }; - for c in &n.chans { - if let Some((v, cov)) = self.tape_content(&n.content, c) { - apply(acc, c, v, cov, m); + Content::Fill { .. } | Content::Paint { .. } if mask > 0.0 => { + let before = if node.anchors.iter().any(|(_, cut)| cut.is_some()) { Some(*acc) } else { None }; + for chan_plan in &node.chans { + if let Some((value, coverage)) = self.tape_content(&node.content, chan_plan) { + apply(acc, chan_plan, value, coverage, mask); } } // Anchors inside the content stack read the stack cut at that point - for (a, cut) in &n.anchors { - let rec = match (cut, before) { - (Some(k), Some(mut b)) => { - for c in &n.chans { - if let Some((v, cov)) = self.content_to(&n.content, c, *k) { - apply(&mut b, c, v, cov, m); + for (anchor, cut) in &node.anchors { + let recorded = match (cut, before) { + (Some(cut), Some(mut cut_acc)) => { + for chan_plan in &node.chans { + if let Some((value, coverage)) = self.content_to(&node.content, chan_plan, *cut) { + apply(&mut cut_acc, chan_plan, value, coverage, mask); } } - b + cut_acc } _ => *acc, }; - self.anchors.push((*a, rec, false)); + self.anchors.push((*anchor, recorded, false)); } continue; } _ => {} } - for (a, _) in &n.anchors { - self.anchors.push((*a, *acc, false)); + for (anchor, _) in &node.anchors { + self.anchors.push((*anchor, *acc, false)); } } false @@ -1859,8 +2108,7 @@ impl<'a, 'b> Texel<'a, 'b> { k.and_then(|k| allowed.get(k).copied()).unwrap_or(true) } - /// Record the anchors of the stack below layer `id` (`full` is the planned stack), to - /// evaluate that layer on its own. + /// Record the anchors of the stack below layer `id` (`full` is the planned stack), to evaluate that layer on its own fn anchors_below(&mut self, full: &[Node], id: LayerId) { self.anchors.clear(); self.stop = Some(id); @@ -1869,41 +2117,36 @@ impl<'a, 'b> Texel<'a, 'b> { self.stop = None; } - /// Straight value and coverage of one channel of a paint or fill layer at this texel - /// (content effects and live stroke preview included). None where the layer is empty. + /// Straight value and coverage of one channel of a paint or fill layer at this texel (content effects and live stroke preview included); None where the layer is empty fn content(&mut self, content: &Content, c: &ChanPlan) -> Option<([f32; 3], f32)> { self.content_to(content, c, usize::MAX) } - /// [`Texel::content`] with only the first `end` visible content effects. - fn content_to(&mut self, content: &Content, c: &ChanPlan, end: usize) -> Option<([f32; 3], f32)> { - let start = c.start.filter(|(k, _)| *k < end); - let (mut v, mut cov, skip) = match start.and_then(|(k, f)| f.get(self.x, self.y).map(|d| (k, d))) { - Some((k, d)) => { - let px = |i: usize| d.get(i).copied().unwrap_or(0.0); - ([px(0), px(1), px(2)], px(3), k + 1) + /// [`Texel::content`] with only the first `end` visible content effects + fn content_to(&mut self, content: &Content, chan_plan: &ChanPlan, end: usize) -> Option<([f32; 3], f32)> { + let start = chan_plan.start.filter(|(stage, _)| *stage < end); + let (mut value, mut coverage, skip) = match start.and_then(|(stage, field)| field.get(self.x, self.y).map(|texel| (stage, texel))) { + Some((stage, texel)) => { + let component = |i: usize| texel.get(i).copied().unwrap_or(0.0); + ([component(0), component(1), component(2)], component(3), stage + 1) } None => { - let (v, cov) = match content { - Content::Fill(f) => { - let ch = Channel::ALL.get(c.ch).copied()?; - // A channel without a source fills with its default (no clone per texel). - let v = match f.sources.get(&ch) { - Some(s) => self.source(s, &f.projection, ch.kind()), - None => ch.default_value(), - }; - (v, self.cover(f.sources.values(), &f.projection)) + let (value, coverage) = match content { + Content::Fill { fill, depth, covers_all } => { + let ch = Channel::ALL.get(chan_plan.ch).copied()?; + let source = fill.sources.get(&ch); + self.fill_place_texel(FillPlace { fill, depth: depth.as_deref(), covers_all: *covers_all }, source, ch) } - Content::Paint { preview } => self.painted(c.data.as_deref(), c, *preview), + Content::Paint { preview } => self.painted(chan_plan.data.as_deref(), chan_plan, *preview), Content::Group(_) => return None, }; - (v, cov, 0) + (value, coverage, 0) } }; - for e in c.effects.iter().take(end).skip(skip) { - (v, cov) = self.content_effect(e, c, v, cov); + for effect in chan_plan.effects.iter().take(end).skip(skip) { + (value, coverage) = self.content_effect(effect, chan_plan, value, coverage); } - (cov > 0.0).then_some((v, cov.min(1.0))) + (coverage > 0.0).then_some((value, coverage.min(1.0))) } /// Straight value and coverage of painted data of one channel (premultiplied values plus @@ -1962,37 +2205,36 @@ impl<'a, 'b> Texel<'a, 'b> { (v, cov.min(1.0)) } - /// Apply one content effect to a channel's straight value and coverage. - fn content_effect(&mut self, e: &EffectPlan, c: &ChanPlan, v: [f32; 3], cov: f32) -> ([f32; 3], f32) { - let o = e.opacity.clamp(0.0, 1.0); - match e.kind { + /// Apply one content effect to a channel's straight value and coverage + fn content_effect(&mut self, effect: &EffectPlan, chan_plan: &ChanPlan, value: [f32; 3], coverage: f32) -> ([f32; 3], f32) { + let opacity = effect.opacity.clamp(0.0, 1.0); + match effect.kind { EffectKind::Paint | EffectKind::Path(_) => { - let (p, pc) = self.painted(e.data.as_deref(), c, e.preview); - over(c, e.blend, v, cov, p, pc * o) + let (painted, painted_coverage) = self.painted(effect.data.as_deref(), chan_plan, effect.preview); + over(chan_plan, effect.blend, value, coverage, painted, painted_coverage * opacity) } - EffectKind::Material(f) => match Channel::ALL.get(c.ch).and_then(|ch| f.sources.get(ch).map(|s| (*ch, s))) { - Some((ch, s)) => { - let p = self.source(s, &f.projection, ch.kind()); - let w = o * self.cover(f.sources.values(), &f.projection); - over(c, e.blend, v, cov, p, w) + EffectKind::Material(fill) => match Channel::ALL.get(chan_plan.ch).and_then(|ch| fill.sources.get(ch).map(|source| (*ch, source))) { + Some((ch, source)) => { + let place = FillPlace { fill, depth: effect.depth.as_deref(), covers_all: effect.covers_all }; + let (material_value, weight) = self.fill_place_texel(place, Some(source), ch); + over(chan_plan, effect.blend, value, coverage, material_value, weight * opacity) } - None => (v, cov), + None => (value, coverage), }, - EffectKind::Levels(l) => (mix3(v, per_unit(c.kind, v, |x| l.apply(x)), o), cov), - // Baked lighting reads the texel's normal and occlusion, and lights the base color only. - EffectKind::Filter(f @ Filter::BakedLighting { .. }) => match Channel::ALL.get(c.ch) { + // Baked lighting reads the texel's normal and occlusion, and lights the base color only + EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => match Channel::ALL.get(chan_plan.ch) { Some(Channel::BaseColor) => { let nrm = self.coords().nrm.to_array(); let k = f.baked_light(nrm, self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0)).unwrap_or(1.0); (mix3(v, v.map(|x| (x * k).clamp(0.0, 1.0)), o), cov) } - _ => (v, cov), + _ => (value, coverage), }, - // Neighbourhood filters come precomputed through `ChanPlan::start`. - EffectKind::Filter(f) => (f.point(c.kind, v).map_or(v, |out| mix3(v, out, o)), cov), - // Anchors are recorded by `eval`; mask-only effects leave content as it is. + // Neighbourhood filters come precomputed through `ChanPlan::start` + EffectKind::Filter(filter) => (filter.point(chan_plan.kind, value).map_or(value, |out| mix3(value, out, opacity)), coverage), + // Anchors are recorded by `eval`; mask-only effects leave content as it is EffectKind::Anchor | EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection { .. } | EffectKind::Compare { .. } => { - (v, cov) + (value, coverage) } } } @@ -2625,12 +2867,10 @@ fn mask_tile<'a>( }) } -/// Tiles [`effect_histogram`] samples at most (a million texels). +/// Tiles [`effect_histogram`] samples at most (a million texels) const HISTOGRAM_TILES: usize = 256; -/// The tiles [`effect_histogram`] reads: an even sample of at most [`HISTOGRAM_TILES`], which -/// keeps the cost flat up to 8K. The stride is odd: a power of two would divide the row length -/// and sample the same few columns. +/// The tiles [`effect_histogram`] reads: an even sample of at most [`HISTOGRAM_TILES`], which keeps the cost flat up to 8K; the stride is odd, as a power of two would divide the row length and sample the same few columns fn histogram_tiles(width: u32, height: u32) -> Vec<(u32, u32)> { let all = all_tiles(width, height); let stride = all.len().div_ceil(HISTOGRAM_TILES).max(1) | 1; @@ -2812,9 +3052,8 @@ mod tests { Fixture { project, mesh, gbuf, pixels: PixelStore::default(), baked: BakedMaps::default() } } - fn run(f: &Fixture, preview: Option<&StrokePreview>) -> Composite { - let images = Default::default(); - let inp = Inputs { + fn inputs<'a>(f: &'a Fixture, images: &'a ImageStore, preview: Option<&'a StrokePreview>) -> Inputs<'a> { + Inputs { project: &f.project, ts: 0, mesh: &f.mesh, @@ -2823,14 +3062,21 @@ mod tests { baked: &f.baked, block_scales: f.project.texture_sets[0].block_scales(), preview, - images: &images, + images, bounds: f.mesh.bounds(), - }; + } + } + + fn run_with_images(f: &Fixture, preview: Option<&StrokePreview>, images: &ImageStore) -> Composite { let mut out = Composite::new(&f.project.texture_sets[0].channel_list(), 64); - composite_tiles(&inp, &mut out, &all_tiles(64, 64)); + composite_tiles(&inputs(f, images, preview), &mut out, &all_tiles(64, 64)); out } + fn run(f: &Fixture, preview: Option<&StrokePreview>) -> Composite { + run_with_images(f, preview, &ImageStore::default()) + } + #[test] fn procedural_resolution_uses_each_uv_tiles_scale() { let mut fixture = fixture(); @@ -2877,6 +3123,58 @@ mod tests { (0..3).all(|i| (a[i] - b[i]).abs() < 2e-4) } + thread_local! { + /// How many times a texel looked up its place on the surface on this thread + pub(super) static COORDS_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many times a texel worked out how much of it a fill covers on this thread + pub(super) static COVER_CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + /// What `counter` counts while `fixture` composites, on one thread so the count sees every texel + fn count_while_compositing(counter: &'static std::thread::LocalKey>, fixture: &Fixture) -> usize { + let pool = rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap(); + pool.install(|| { + counter.with(|count| count.set(0)); + run(fixture, None); + counter.with(std::cell::Cell::get) + }) + } + + /// How many texels looked up their place on the surface while `fixture` composites + fn coords_lookups(fixture: &Fixture) -> usize { + count_while_compositing(&COORDS_LOOKUPS, fixture) + } + + #[test] + fn a_repeating_uniform_fill_covers_every_texel_without_looking_up_where_it_is() { + let mut f = fixture(); + let id = fill_layer(&mut f.project, [1.0, 0.0, 0.0], 0.2); + assert_eq!(coords_lookups(&f), 0, "a uniform fill that repeats needs no texel's place, as before fills could crop"); + + // Not repeating, it crops to its tile, so it has to know where each texel lands + let Ok(LayerKind::Fill(fill)) = f.project.layer_mut(id).map(|layer| &mut layer.kind) else { panic!("fill layer") }; + fill.sampling.wrap = texturecraft_core::UvWrap::None; + assert!(coords_lookups(&f) > 0); + } + + /// How many times a texel worked out a fill's coverage while `fixture` composites + fn cover_calls(fixture: &Fixture) -> usize { + count_while_compositing(&COVER_CALLS, fixture) + } + + #[test] + fn a_fill_covering_every_texel_is_decided_once_per_tile_not_per_texel() { + let mut f = fixture(); + let id = fill_layer(&mut f.project, [1.0, 0.0, 0.0], 0.2); + assert_eq!(cover_calls(&f), 0, "a repeating fill with nothing cropped or culled covers every texel, so no texel asks"); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [1.0, 0.0, 0.0])); + + // Not repeating, it crops to its tile, so each texel works its coverage out + let Ok(LayerKind::Fill(fill)) = f.project.layer_mut(id).map(|layer| &mut layer.kind) else { panic!("fill layer") }; + fill.sampling.wrap = texturecraft_core::UvWrap::None; + assert!(cover_calls(&f) > 0); + } + #[test] fn retained_filter_buffers_release_after_the_last_tile() { for resolution in [128, 512] { @@ -3026,7 +3324,11 @@ mod tests { let pattern = Procedural::new(ProceduralKind::Checker); mask.effects.push(Effect::new( eid, - EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, projection: Projection::default() }, + EffectKind::Fill { + source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, + projection: Projection::default(), + sampling: Default::default(), + }, )); f.project.layer_mut(id).unwrap().mask = Some(mask); let out = run(&f, None); @@ -3076,7 +3378,11 @@ mod tests { let pattern = Procedural::new(ProceduralKind::Checker); mask.effects.push(Effect::new( effect, - EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, projection: Projection::default() }, + EffectKind::Fill { + source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, + projection: Projection::default(), + sampling: Default::default(), + }, )); fixture.project.layer_mut(layer).unwrap().mask = Some(mask); @@ -3106,6 +3412,7 @@ mod tests { EffectKind::Fill { source: Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, projection: Projection::default(), + sampling: Default::default(), }, )); fixture.project.layer_mut(layer).unwrap().mask = Some(mask); @@ -3172,11 +3479,16 @@ mod tests { let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new( fixture.project.alloc_id(), - EffectKind::Fill { source: Source::Anchor { anchor, channel: Channel::BaseColor, ramp: Vec::new() }, projection: Projection::default() }, + EffectKind::Fill { + source: Source::Anchor { anchor, channel: Channel::BaseColor, ramp: Vec::new() }, + projection: Projection::default(), + sampling: Default::default(), + }, )); fixture.project.layer_mut(upper).unwrap().mask = Some(mask.clone()); let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); let original = assert_sparse_mask_matches_image(&fixture, upper, &texels).unwrap(); + assert!(original.iter().any(|value| *value > 0.99) && original.iter().any(|value| *value < 0.01), "the anchor supplies the checker"); for filter in [Filter::Blur { radius: 64.0 }, Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 }] { @@ -3199,7 +3511,10 @@ mod tests { let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); let mut masked = |filters: &[Filter]| { let mut mask = Mask::new(MaskBackground::Black); - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker.clone(), projection: Projection::default() })); + mask.effects.push(Effect::new( + fixture.project.alloc_id(), + EffectKind::Fill { source: checker.clone(), projection: Projection::default(), sampling: Default::default() }, + )); for filter in filters { mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(filter.clone()))); } @@ -3318,7 +3633,8 @@ mod tests { let (mut fixture, layer) = ridge_fixture(100); let mut row_with = |blur: f32| { let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }; - let below = Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default() }); + let below = + Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default(), sampling: Default::default() }); let mut generator = ridge_generator(); generator.global.blur = blur; let mut lighten = generator_effect(&mut fixture, generator); @@ -3390,6 +3706,22 @@ mod tests { assert!(black > 0.99 && baked < black - 0.2, "baked {baked}, black input {black}"); } + #[test] + fn a_generator_input_image_reads_plain_bilinear_as_saved_projects_did() { + // Every fourth column white: a texel centre reads between two black columns, a mip level a quarter gray + const SIZE: u32 = 256; + let striped = (0..SIZE * SIZE).map(|i| if (i % SIZE).is_multiple_of(4) { [1.0; 4] } else { [0.0, 0.0, 0.0, 1.0] }).collect(); + let images: ImageStore = [("ao".to_string(), Arc::new(crate::store::ImageRes::new(SIZE, SIZE, striped, false)))].into_iter().collect(); + let mut generator = Generator::new(GeneratorKind::Dirt); + generator.inputs.insert(BakedMap::AmbientOcclusion, Source::image("ao")); + let fixture = fixture(); + let inp = inputs(&fixture, &images, None); + + let read = Texel::new(&inp, 20, 20, 0, 0.0).generator_input(&generator, BakedMap::AmbientOcclusion); + + assert_eq!(read, Some(0.0)); + } + #[test] fn curvature_detail_noise_keeps_flat_areas_neutral() { let mut fixture = fixture(); @@ -3431,14 +3763,20 @@ mod tests { let mut f = fixture(); let id = fill_layer(&mut f.project, [1.0; 3], 1.0); assert!(!stack_reads_neighbours(&f.project, 0)); + let mut mask = Mask::new(MaskBackground::White); let eid = f.project.alloc_id(); mask.effects.push(Effect::new(eid, EffectKind::Filter(Filter::Blur { radius: 8.0 }))); f.project.layer_mut(id).unwrap().mask = Some(mask); + assert!(stack_reads_neighbours(&f.project, 0)); + f.project.layer_mut(id).unwrap().mask = None; + assert!(!stack_reads_neighbours(&f.project, 0)); + content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 8.0 })); + assert!(stack_reads_neighbours(&f.project, 0)); } @@ -3451,7 +3789,11 @@ mod tests { let (e1, e2) = (f.project.alloc_id(), f.project.alloc_id()); mask.effects.push(Effect::new( e1, - EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, projection: Projection::default() }, + EffectKind::Fill { + source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, + projection: Projection::default(), + sampling: Default::default(), + }, )); f.project.layer_mut(id).unwrap().mask = Some(mask.clone()); let hard: Vec = (0..64).map(|x| run(&f, None).value(Channel::BaseColor, x, 20)[0]).collect(); @@ -3513,7 +3855,7 @@ soft {soft:?}" let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 5, 5), [1.0, 0.0, 1.0])); assert!(close(out.value(Channel::Roughness, 5, 5), [0.8; 3])); - // Hidden effects are skipped and opacity fades an effect. + // Hidden effects are skipped and opacity fades an effect let fx = &mut f.project.layer_mut(id).unwrap().content_effects; fx[0].visible = false; fx[1].opacity = 0.5; @@ -3529,6 +3871,7 @@ soft {soft:?}" let mut mask = Mask::new(MaskBackground::White); mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Hsl { hue: 0.3, saturation: 1.0, lightness: -0.5 }))); f.project.layer_mut(id).unwrap().mask = Some(mask); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.75; 3])); } @@ -3580,12 +3923,15 @@ soft {soft:?}" let edges = content_fx(&mut f, id, EffectKind::Filter(Filter::EdgeDetect { width: 32.0 })); let out = run(&f, None); let vals: Vec = (0..64).flat_map(|y| (0..64).map(move |x| (x, y))).map(|(x, y)| out.value(Channel::Roughness, x, y)[0]).collect(); + assert!(vals.iter().all(|v| (0.0..=1.0).contains(v))); assert!(vals.iter().filter(|v| **v > 0.5).count() > 64 && vals.iter().filter(|v| **v < 0.01).count() > 64, "{vals:?}"); + f.project.layer_mut(id).unwrap().content_effects.retain(|e| e.id != edges); content_fx(&mut f, id, EffectKind::Filter(Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 })); let warped = run(&f, None); let differs = (0..64).any(|y| (0..64).any(|x| (warped.value(Channel::Roughness, x, y)[0] - plain.value(Channel::Roughness, x, y)[0]).abs() > 0.2)); + assert!(differs, "the warp moves the checker"); // Point filters @@ -3661,8 +4007,10 @@ soft {soft:?}" // Facing the light adds illumination; facing away keeps ambient only let (toward, rough) = lit(if n.y > 0.0 { 90.0 } else { -90.0 }); assert!(close(toward, [0.5; 3]) && close(rough, [0.3; 3]), "{toward:?} {rough:?}"); + let (away, _) = lit(if n.y > 0.0 { -90.0 } else { 90.0 }); assert!(close(away, [0.2; 3]), "{away:?}"); + let f = Filter::BakedLighting { azimuth: 0.0, elevation: 0.0, light: 0.0, ambient: 1.0, occlusion: 0.5 }; assert_eq!(f.baked_light([0.0, 1.0, 0.0], 0.2), Some(0.6), "half the occlusion"); assert_eq!(Filter::Invert.baked_light([0.0; 3], 1.0), None); @@ -3711,19 +4059,8 @@ soft {soft:?}" assert!(close(out.value(Channel::BaseColor, 3, 3), [0.5; 3]), "channels without a source stay untouched"); // Flattening bakes in the content effects - let images = Default::default(); - let inp = Inputs { - project: &f.project, - ts: 0, - mesh: &f.mesh, - gbuf: &f.gbuf, - pixels: &f.pixels, - baked: &f.baked, - block_scales: f.project.texture_sets[0].block_scales(), - preview: None, - images: &images, - bounds: f.mesh.bounds(), - }; + let images = ImageStore::default(); + let inp = inputs(&f, &images, None); let flat = flatten_layer(&inp, id, &all_tiles(64, 64)).unwrap(); assert!(flat.iter().all(|(c, _, _)| *c == Channel::Roughness)); let (_, _, data) = flat.iter().find(|(_, t, _)| *t == (0, 0)).unwrap(); @@ -3742,26 +4079,30 @@ soft {soft:?}" let top = fill_layer(&mut f.project, [1.0; 3], 0.5); let mut mask = Mask::new(MaskBackground::Black); let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() }; - mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })); + mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })); f.project.layer_mut(top).unwrap().mask = Some(mask.clone()); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.7; 3])); // The field pre-pass reads anchors under blur, preserving flat height mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0 }))); f.project.layer_mut(top).unwrap().mask = Some(mask); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.7; 3])); // An anchor above its reader is not evaluated yet, so it reads the channel default f.project.move_layer(low, 1).unwrap(); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.5; 3])); } - /// A white fill layer on top whose mask reads `anchor` (any channel: a mask anchor is gray). + /// A white fill layer on top whose mask reads `anchor` (any channel: a mask anchor is gray) fn anchor_reader(fixture: &mut Fixture, anchor: LayerId) -> LayerId { let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5); let mut mask = Mask::new(MaskBackground::Black); let source = Source::Anchor { anchor, channel: Channel::Roughness, ramp: Vec::new() }; - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })); + mask.effects + .push(Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })); fixture.project.layer_mut(top).unwrap().mask = Some(mask); top } @@ -3772,9 +4113,11 @@ soft {soft:?}" let low = fill_layer(&mut fixture.project, [0.0; 3], 0.5); let (gray, anchor, full) = (fixture.project.alloc_id(), fixture.project.alloc_id(), fixture.project.alloc_id()); let mut mask = Mask::new(MaskBackground::Black); - mask.effects.push(Effect::new(gray, EffectKind::Fill { source: Source::Uniform([0.4; 3]), projection: Projection::default() })); + mask.effects + .push(Effect::new(gray, EffectKind::Fill { source: Source::Uniform([0.4; 3]), projection: Projection::default(), sampling: Default::default() })); mask.effects.push(Effect::new(anchor, EffectKind::Anchor)); - mask.effects.push(Effect::new(full, EffectKind::Fill { source: Source::Uniform([1.0; 3]), projection: Projection::default() })); + mask.effects + .push(Effect::new(full, EffectKind::Fill { source: Source::Uniform([1.0; 3]), projection: Projection::default(), sampling: Default::default() })); fixture.project.layer_mut(low).unwrap().mask = Some(mask.clone()); anchor_reader(&mut fixture, anchor); @@ -3785,11 +4128,13 @@ soft {soft:?}" mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0 }))); fixture.project.layer_mut(low).unwrap().mask = Some(mask.clone()); let color = run(&fixture, None).value(Channel::BaseColor, 5, 5); + assert!(close(color, [0.4; 3]), "{color:?}"); // An empty paint layer still records its mask anchor for the layer above fixture.project.layer_mut(low).unwrap().kind = LayerKind::Paint; let color = run(&fixture, None).value(Channel::BaseColor, 5, 5); + assert!(close(color, [0.7; 3]), "{color:?}"); } @@ -3802,13 +4147,17 @@ soft {soft:?}" let anchor = fixture.project.alloc_id(); let mut mask = Mask::new(MaskBackground::Black); let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }; - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default() })); + mask.effects.push(Effect::new( + fixture.project.alloc_id(), + EffectKind::Fill { source: checker, projection: Projection::default(), sampling: Default::default() }, + )); mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 64.0 }))); mask.effects.push(Effect::new(anchor, EffectKind::Anchor)); fixture.project.layer_mut(lower).unwrap().mask = Some(mask.clone()); let reader = anchor_reader(&mut fixture, anchor); let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); let expected = assert_sparse_mask_matches_image(&fixture, reader, &texels).unwrap(); + assert!(expected.iter().any(|value| *value > 0.1 && *value < 0.9), "the anchor records a softened checker"); mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 128.0 }))); @@ -3901,14 +4250,14 @@ soft {soft:?}" } } - #[test] - fn decal_fills_cover_only_their_frame_and_image_alpha() { - let mut f = fixture(); - let s = f.gbuf.surface(&f.mesh, 32 * 64 + 32).unwrap(); - let d = texturecraft_core::Decal { - center: s.pos.to_array(), - normal: s.nrm.to_array(), - up: s.nrm.any_orthonormal_vector().to_array(), + /// A fixture under a decal fill of image "decal" framed on the plane's middle, its projection changed by `change` + fn decal_fixture(change: impl FnOnce(&mut Fill)) -> Fixture { + let mut fixture = fixture(); + let surface = fixture.gbuf.surface(&fixture.mesh, 32 * 64 + 32).unwrap(); + let frame = texturecraft_core::Decal { + center: surface.pos.to_array(), + normal: surface.nrm.to_array(), + up: surface.nrm.any_orthonormal_vector().to_array(), size: [1.0, 1.0], rotation: 0.0, offset: [0.0; 2], @@ -3916,33 +4265,35 @@ soft {soft:?}" symmetry: None, flip: [false; 2], }; - let id = f.project.alloc_id(); - let mut fill = Fill { projection: Projection::Decal(d), ..Fill::default() }; + let id = fixture.project.alloc_id(); + let mut fill = Fill { projection: Projection::decal(frame), ..Fill::default() }; fill.sources.insert(Channel::BaseColor, Source::image("decal")); - f.project.insert_layer(0, Layer::new(id, "Decal", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); - let composite = |alpha: f32| { - let img = crate::store::ImageRes { width: 2, height: 2, rgba: vec![[1.0, 0.0, 0.0, alpha]; 4], srgb: false }; - let images: ImageStore = [("decal".to_string(), std::sync::Arc::new(img))].into_iter().collect(); - let inp = Inputs { - project: &f.project, - ts: 0, - mesh: &f.mesh, - gbuf: &f.gbuf, - pixels: &f.pixels, - baked: &f.baked, - block_scales: f.project.texture_sets[0].block_scales(), - preview: None, - images: &images, - bounds: f.mesh.bounds(), - }; - let mut out = Composite::new(&f.project.texture_sets[0].channel_list(), 64); - composite_tiles(&inp, &mut out, &all_tiles(64, 64)); - out - }; - let out = composite(1.0); - assert!(close(out.value(Channel::BaseColor, 32, 32), [1.0, 0.0, 0.0]), "{:?}", out.value(Channel::BaseColor, 32, 32)); - assert!(close(out.value(Channel::BaseColor, 2, 2), [0.5; 3]), "outside the frame"); + change(&mut fill); + fixture.project.insert_layer(0, Layer::new(id, "Decal", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + fixture + } + + /// `f` composited with `image` as its "decal" image + fn composite_with_decal(f: &Fixture, image: crate::store::ImageRes) -> Composite { + let images: ImageStore = [("decal".to_string(), std::sync::Arc::new(image))].into_iter().collect(); + run_with_images(f, None, &images) + } + + /// Texels of a 64 x 64 composite whose base colour is not the fixture's grey + fn decal_texels(out: &Composite) -> Vec<[f32; 3]> { + (0..64 * 64).map(|i| out.value(Channel::BaseColor, i % 64, i / 64)).filter(|v| !close(*v, [0.5; 3])).collect() + } + + #[test] + fn decal_fills_cover_only_their_frame_and_image_alpha() { + let fixture = decal_fixture(|_| {}); + let composite = |alpha: f32| composite_with_decal(&fixture, crate::store::ImageRes::new(2, 2, vec![[1.0, 0.0, 0.0, alpha]; 4], false)); + + let opaque = composite(1.0); let half = composite(0.5); + + assert!(close(opaque.value(Channel::BaseColor, 32, 32), [1.0, 0.0, 0.0]), "{:?}", opaque.value(Channel::BaseColor, 32, 32)); + assert!(close(opaque.value(Channel::BaseColor, 2, 2), [0.5; 3]), "outside the frame"); assert!(close(half.value(Channel::BaseColor, 32, 32), [0.75, 0.25, 0.25]), "the image alpha shapes the decal"); } @@ -3955,17 +4306,12 @@ soft {soft:?}" let mut project = Project::new("t", "builtin:cube"); project.texture_sets.push(TextureSet::new("Cube", 0, 64)); let id = project.alloc_id(); - let mut fill = Fill { projection: Projection::Decal(d), ..Fill::default() }; + let mut fill = Fill { projection: Projection::decal(d), ..Fill::default() }; fill.sources.insert(Channel::BaseColor, Source::image("decal")); project.insert_layer(0, Layer::new(id, "Decal", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); // Top left red, top right blue, bottom left green, bottom right yellow - let img = crate::store::ImageRes { - width: 2, - height: 2, - rgba: vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.0, 1.0, 0.0, 1.0], [1.0, 1.0, 0.0, 1.0]], - srgb: false, - }; + let img = crate::store::ImageRes::new(2, 2, vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.0, 1.0, 0.0, 1.0], [1.0, 1.0, 0.0, 1.0]], false); let images: ImageStore = [("decal".to_string(), std::sync::Arc::new(img.clone()))].into_iter().collect(); let pixels = PixelStore::default(); let baked = BakedMaps::default(); @@ -4131,19 +4477,19 @@ soft {soft:?}" flip: [false; 2], }; let id = f.project.alloc_id(); - let mut fill = Fill { projection: Projection::Decal(d), ..Fill::default() }; + let mut fill = Fill { projection: Projection::decal(d), ..Fill::default() }; fill.sources.insert(Channel::BaseColor, Source::image("decal")); f.project.insert_layer(0, Layer::new(id, "Decal", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); // Left half red, right half blue - let img = crate::store::ImageRes { width: 2, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]], srgb: false }; + let img = crate::store::ImageRes::new(2, 1, vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]], false); let images: ImageStore = [("decal".to_string(), std::sync::Arc::new(img))].into_iter().collect(); let texel = |f: &Fixture, flip: [bool; 2]| { let mut project = f.project.clone(); if let Ok(layer) = project.layer_mut(id) && let LayerKind::Fill(fill) = &mut layer.kind { - fill.projection = Projection::Decal(texturecraft_core::Decal { flip, ..d }); + fill.projection = Projection::decal(texturecraft_core::Decal { flip, ..d }); } let inp = Inputs { project: &project, @@ -4166,6 +4512,56 @@ soft {soft:?}" assert!(close(texel(&f, [false, true]), [1.0, 0.0, 0.0]), "Flip V leaves the left half"); } + #[test] + fn a_cropped_frames_image_alpha_turns_with_its_image() { + let f = decal_fixture(|fill| { + if let Projection::Planar { uv, .. } = &mut fill.projection { + uv.rotation = 180.0; + } + }); + + // Opaque red on the left half, see-through green on the right + let half = (0..8 * 8).map(|i| if i % 8 < 4 { [1.0, 0.0, 0.0, 1.0] } else { [0.0, 1.0, 0.0, 0.0] }).collect(); + let shown = decal_texels(&composite_with_decal(&f, crate::store::ImageRes::new(8, 8, half, false))); + + assert!(!shown.is_empty(), "the red half shows"); + assert!(shown.iter().all(|v| v[1] < 0.75), "the see-through green half stays hidden once turned (a seam texel blends some in): {shown:?}"); + } + + #[test] + fn a_shrunk_cropped_frames_coverage_averages_its_image_alpha_as_its_colour_does() { + let f = decal_fixture(|fill| fill.sampling.filtering = Filtering::BilinearHq); + + // Red columns a texel wide, opaque and see-through in turn, far finer than the frame's texels; not a power of two, so a full-size read lands anywhere between two columns + const SIZE: u32 = 1000; + let stripes = (0..SIZE * SIZE).map(|i| [1.0, 0.0, 0.0, if i % 2 == 0 { 1.0 } else { 0.0 }]).collect(); + let shown = decal_texels(&composite_with_decal(&f, crate::store::ImageRes::new(SIZE, SIZE, stripes, false))); + + assert!(!shown.is_empty(), "the frame shows"); + let half = [0.75, 0.25, 0.25]; + assert!( + shown.iter().all(|v| v.iter().zip(half).all(|(got, want)| (got - want).abs() < 0.05)), + "every texel is half covered, as its averaged stripes are: {shown:?}" + ); + } + + #[test] + fn a_cropped_frame_with_wrap_none_shows_one_image_however_it_tiles() { + let opaque = || crate::store::ImageRes::new(2, 2, vec![[1.0, 0.0, 0.0, 1.0]; 4], false); + let once = decal_texels(&composite_with_decal(&decal_fixture(|_| {}), opaque())).len(); + let tiled = decal_fixture(|fill| { + fill.sampling.wrap = texturecraft_core::UvWrap::None; + if let Projection::Planar { uv, .. } = &mut fill.projection { + uv.tiling = [2.0, 2.0]; + } + }); + + let quarter = decal_texels(&composite_with_decal(&tiled, opaque())).len(); + + assert!(once > 0, "the frame shows"); + assert!(quarter.abs_diff(once / 4) <= once / 16, "tiled twice with no wrap, one image fills a quarter of the frame: {quarter} of {once}"); + } + #[test] fn anchors_read_colors_as_gray_in_fill_layers() { let mut f = fixture(); @@ -4230,8 +4626,10 @@ soft {soft:?}" let low = fill_layer(&mut f.project, [0.0; 3], 0.5); let anchor = f.project.alloc_id(); let mut mask = Mask::new(MaskBackground::Black); - mask.effects - .push(Effect::new(f.project.alloc_id(), EffectKind::Fill { source: Source::Uniform([gray; 3]), projection: Projection::default() })); + mask.effects.push(Effect::new( + f.project.alloc_id(), + EffectKind::Fill { source: Source::Uniform([gray; 3]), projection: Projection::default(), sampling: Default::default() }, + )); mask.effects.push(Effect::new(anchor, EffectKind::Anchor)); f.project.layer_mut(low).unwrap().mask = Some(mask); let id = f.project.alloc_id(); diff --git a/crates/compose/src/fill_copy.rs b/crates/compose/src/fill_copy.rs new file mode 100644 index 00000000..12753d28 --- /dev/null +++ b/crates/compose/src/fill_copy.rs @@ -0,0 +1,34 @@ +//! One copy of a symmetric fill's projection: the mirror or turn a texel samples it through + +use texturecraft_geom::glam::{Mat3, Vec2, Vec3}; + +/// One copy of a fill's projection: a texel at a point shows what the projection gives at [`FillCopy::point`] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FillCopy { + turn: Mat3, + pivot: Vec3, + flip: [bool; 2], +} + +impl FillCopy { + /// A copy sampling the projection at `pivot + turn * (point - pivot)`, its image turned over across and down as `flip` says + pub fn new(turn: Mat3, pivot: Vec3, flip: [bool; 2]) -> FillCopy { + FillCopy { turn, pivot, flip } + } + + /// The surface point the projection is sampled at for a texel at world point `point` + pub fn point(&self, point: Vec3) -> Vec3 { + self.pivot + self.turn * (point - self.pivot) + } + + /// The normal the projection sees for a texel whose normal is `normal` + pub fn normal(&self, normal: Vec3) -> Vec3 { + self.turn * normal + } + + /// `uv` in the copy's image, turned over across and down as its Flip copy says + pub fn uv(&self, uv: Vec2) -> Vec2 { + let [across, down] = self.flip; + Vec2::new(if across { 1.0 - uv.x } else { uv.x }, if down { 1.0 - uv.y } else { uv.y }) + } +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 39b00656..25548ab5 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -7,6 +7,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod axis_frame; mod baked_maps; pub mod below; mod curvature_size_level; @@ -14,24 +15,33 @@ pub mod curvature_sizes; pub mod display; pub mod eval; mod fabric; +pub mod fill_copies; +pub mod fill_copy; +mod fill_place; +pub mod frame_placement; mod fur_lock; mod held_fields; mod image_identity; +pub mod mip_level; mod organic; pub mod pattern; mod pattern_context; +pub mod projector_cover; +pub mod projector_depth; +pub mod projector_view; pub mod solo; pub mod store; pub mod thumb; +pub mod tile_length; mod tile_pattern; mod tile_random_stream; mod timber; +pub mod warp; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, kinds_for, tile_bytes}; pub use eval::{ - BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, - effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours, + covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours, }; pub use pattern_context::PatternContext; pub use solo::solo_project; diff --git a/crates/compose/src/store.rs b/crates/compose/src/store.rs index 1370c0c0..43d9b19a 100644 --- a/crates/compose/src/store.rs +++ b/crates/compose/src/store.rs @@ -2,10 +2,13 @@ //! maps. Everything is copy-on-write, so cloning the store for undo is cheap. use std::collections::HashMap; +use std::sync::OnceLock; -use texturecraft_core::{Channel, ChannelKind, LayerId}; +use texturecraft_core::{Channel, ChannelKind, Filtering, LayerId, Sampling}; use texturecraft_texel::{TileImage, from_u16, from_u16_signed}; +use crate::mip_level::MipLevel; + /// Painted data of one paint layer channel: premultiplied value(s) plus coverage, u16 per /// component (height stored signed). #[derive(Clone, Debug, Default)] @@ -66,16 +69,54 @@ pub struct ImageRes { pub rgba: Vec<[f32; 4]>, /// 8/16-bit images are sRGB-encoded; color channels linearize them. pub srgb: bool, + /// Halved copies of the image, built on first use by [`Filtering::BilinearHq`] + pub mips: OnceLock>, } /// Image resources by name. pub type ImageStore = HashMap>; +/// Image levels below the full image at most: a 64k image halves 16 times to 1 texel +const MAX_MIP_LEVELS: usize = 16; + +/// Texel (`x`, `y`) of `rgba`; an axis that does not `repeat` (across, down) stops at its edge +pub(crate) fn texel_of(rgba: &[[f32; 4]], width: u32, height: u32, x: i64, y: i64, repeat: (bool, bool)) -> [f32; 4] { + let (w, h) = (width.max(1) as i64, height.max(1) as i64); + let x = if repeat.0 { x.rem_euclid(w) } else { x.clamp(0, w - 1) }; + let y = if repeat.1 { y.rem_euclid(h) } else { y.clamp(0, h - 1) }; + let i = (y * w + x) as usize; + rgba.get(i).copied().unwrap_or([0.0; 4]) +} + +/// Bilinear sample of `rgba` (texture coordinates, v down), wrapping around on the axes that `repeat` +fn bilinear(rgba: &[[f32; 4]], width: u32, height: u32, u: f32, v: f32, repeat: (bool, bool)) -> [f32; 4] { + // Texel centres sit half a texel in from the texel's corner + let texel_x = u * width as f32 - 0.5; + let texel_y = v * height as f32 - 0.5; + let (left, top) = (texel_x.floor() as i64, texel_y.floor() as i64); + let (across, down) = (texel_x - texel_x.floor(), texel_y - texel_y.floor()); + + // A huge coordinate saturates to the last texel instead of overflowing past it + let (right, bottom) = (left.saturating_add(1), top.saturating_add(1)); + let texel = |x, y| texel_of(rgba, width, height, x, y, repeat); + let (top_left, top_right) = (texel(left, top), texel(right, top)); + let (bottom_left, bottom_right) = (texel(left, bottom), texel(right, bottom)); + let mut blended = [0.0; 4]; + for k in 0..4 { + let upper = top_left[k] + (top_right[k] - top_left[k]) * across; + let lower = bottom_left[k] + (bottom_right[k] - bottom_left[k]) * across; + blended[k] = upper + (lower - upper) * down; + } + blended +} + impl ImageRes { - fn texel(&self, x: i64, y: i64) -> [f32; 4] { - let (w, h) = (self.width.max(1) as i64, self.height.max(1) as i64); - let i = (y.rem_euclid(h) * w + x.rem_euclid(w)) as usize; - self.rgba.get(i).copied().unwrap_or([0.0; 4]) + pub fn new(width: u32, height: u32, rgba: Vec<[f32; 4]>, srgb: bool) -> ImageRes { + ImageRes { width, height, rgba, srgb, mips: OnceLock::new() } + } + + fn texel(&self, x: i64, y: i64, repeat: (bool, bool)) -> [f32; 4] { + texel_of(&self.rgba, self.width, self.height, x, y, repeat) } /// Bilinear sample with wrap-around (texture coordinates, v down). @@ -83,17 +124,144 @@ impl ImageRes { if !u.is_finite() || !v.is_finite() { return [0.0; 4]; } - let fx = u * self.width as f32 - 0.5; - let fy = v * self.height as f32 - 0.5; - let (x0, y0) = (fx.floor() as i64, fy.floor() as i64); - let (tx, ty) = (fx - fx.floor(), fy - fy.floor()); - let (a, b, c, d) = (self.texel(x0, y0), self.texel(x0 + 1, y0), self.texel(x0, y0 + 1), self.texel(x0 + 1, y0 + 1)); - let mut out = [0.0; 4]; - for k in 0..4 { - let top = a[k] + (b[k] - a[k]) * tx; - let bot = c[k] + (d[k] - c[k]) * tx; - out[k] = top + (bot - top) * ty; + bilinear(&self.rgba, self.width, self.height, u, v, (true, true)) + } + + /// The texel under (`u`, `v`), on the axes that do not `repeat` the edge texel past the edge + fn nearest(&self, u: f32, v: f32, repeat: (bool, bool)) -> [f32; 4] { + self.texel((u * self.width as f32).floor() as i64, (v * self.height as f32).floor() as i64, repeat) + } + + /// The halved levels, built the first time they are asked for + fn mips(&self) -> &[MipLevel] { + self.mips.get_or_init(|| { + let mut levels: Vec = Vec::new(); + let (mut w, mut h) = (self.width, self.height); + while (w > 1 || h > 1) && levels.len() < MAX_MIP_LEVELS { + let next = match levels.last() { + Some(level) => MipLevel::halve(&level.rgba, level.width, level.height), + None => MipLevel::halve(&self.rgba, w, h), + }; + (w, h) = (next.width, next.height); + levels.push(next); + } + levels + }) + } + + /// Sample at (`u`, `v`) with `sampling`; `footprint` = image texels per surface texel (1 or less = not shrunk) + pub fn sample_filtered(&self, u: f32, v: f32, sampling: Sampling, footprint: f32) -> [f32; 4] { + if !u.is_finite() || !v.is_finite() { + return [0.0; 4]; + } + + let repeat = sampling.wrap.repeats(); + let full = |u: f32, v: f32| bilinear(&self.rgba, self.width, self.height, u, v, repeat); + match sampling.filtering { + Filtering::Nearest => self.nearest(u, v, repeat), + Filtering::BilinearSharp => full(u, v), + Filtering::BilinearHq => { + // Not shrunk: the full image alone, without building mips it does not read + if !(footprint.is_finite() && footprint > 1.0) { + return full(u, v); + } + + let lod = footprint.log2(); + + // Level 0 is the full image, level n the nth mip (the smallest past the last) + let mips = self.mips(); + let level = |index: usize| match index.checked_sub(1) { + None => full(u, v), + Some(mip_index) => { + mips.get(mip_index).or(mips.last()).map_or_else(|| full(u, v), |mip| bilinear(&mip.rgba, mip.width, mip.height, u, v, repeat)) + } + }; + let finer_level = lod.floor() as usize; + let toward_coarser = lod - lod.floor(); + let finer = level(finer_level); + if toward_coarser <= 0.0 { + return finer; + } + + let coarser = level(finer_level + 1); + [0, 1, 2, 3].map(|component| finer[component] + (coarser[component] - finer[component]) * toward_coarser) + } } - out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_core::UvWrap; + + #[test] + fn a_huge_texture_coordinate_samples_without_overflowing() { + let image = ImageRes::new(2, 2, vec![[0.5; 4]; 4], false); + + let sampled = image.sample(1e30, -1e30); + + assert_eq!(sampled, [0.5; 4]); + } + + /// A 4 × 1 image of columns 0, 1, 2, 3 + fn ramp() -> ImageRes { + ImageRes::new(4, 1, (0..4).map(|column| [column as f32; 4]).collect(), false) + } + + fn sampling(filtering: Filtering, wrap: UvWrap) -> Sampling { + Sampling { filtering, wrap, ..Sampling::default() } + } + + #[test] + fn nearest_reads_the_texel_under_the_point_and_wraps_or_stops_at_the_edge() { + let image = ramp(); + + let inside = image.sample_filtered(0.6, 0.5, sampling(Filtering::Nearest, UvWrap::Repeat), 1.0); + let wrapped = image.sample_filtered(1.1, 0.5, sampling(Filtering::Nearest, UvWrap::Repeat), 1.0); + let stopped = image.sample_filtered(1.1, 0.5, sampling(Filtering::Nearest, UvWrap::None), 1.0); + + assert_eq!(inside, [2.0; 4]); + assert_eq!(wrapped, [0.0; 4], "past the right edge a repeating image starts again"); + assert_eq!(stopped, [3.0; 4], "past the right edge a single image keeps its last column"); + } + + #[test] + fn a_bilinear_read_past_a_single_images_edge_blends_no_far_side_texel() { + let image = ramp(); + + let repeating = image.sample_filtered(0.99, 0.5, sampling(Filtering::BilinearSharp, UvWrap::Repeat), 1.0); + let single = image.sample_filtered(0.99, 0.5, sampling(Filtering::BilinearSharp, UvWrap::None), 1.0); + + assert!(repeating[0] < 3.0, "the far side's 0 blends in: {repeating:?}"); + assert_eq!(single, [3.0; 4]); + } + + #[test] + fn high_quality_bilinear_reads_the_mip_the_footprint_asks_for() { + let image = ramp(); + let hq = sampling(Filtering::BilinearHq, UvWrap::Repeat); + + let full = image.sample_filtered(0.375, 0.5, hq, 1.0); + let halved = image.sample_filtered(0.25, 0.5, hq, 2.0); + let quartered = image.sample_filtered(0.375, 0.5, hq, 4.0); + let past_the_last = image.sample_filtered(0.375, 0.5, hq, 64.0); + let between = image.sample_filtered(0.875, 0.5, hq, 2.0_f32.sqrt()); + + assert_eq!(full, [1.0; 4], "a footprint of 1 reads the full image at column 1's centre"); + assert_eq!(halved, [0.5; 4], "level 1's first texel averages columns 0 and 1"); + assert_eq!(quartered, [1.5; 4], "a 1-texel level holds the mean"); + assert_eq!(past_the_last, quartered, "a footprint past the last level reads the last one"); + assert!(between[0] > 2.0 && between[0] < 3.0, "half a level blends the full image's 3 and level 1's 2: {between:?}"); + } + + #[test] + fn an_unshrunk_high_quality_read_builds_no_mips() { + let image = ramp(); + + let full = image.sample_filtered(0.375, 0.5, sampling(Filtering::BilinearHq, UvWrap::Repeat), 1.0); + + assert_eq!(full, [1.0; 4]); + assert!(image.mips.get().is_none(), "a footprint of 1 reads only the full image"); } } diff --git a/crates/compose/src/tile_pattern.rs b/crates/compose/src/tile_pattern.rs index c756072f..2fcaf208 100644 --- a/crates/compose/src/tile_pattern.rs +++ b/crates/compose/src/tile_pattern.rs @@ -599,7 +599,7 @@ mod tests { fn halves(left: f32, right: f32) -> std::sync::Arc { let size = 8; let rgba = (0..size * size).map(|texel| if texel % size < size / 2 { [left, left, left, 1.0] } else { [right, right, right, 1.0] }).collect(); - std::sync::Arc::new(ImageRes { width: size as u32, height: size as u32, rgba, srgb: false }) + std::sync::Arc::new(ImageRes::new(size as u32, size as u32, rgba, false)) } #[test] diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 08f971be..406d8480 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -77,7 +77,10 @@ fn heavy_stack(f: &mut Fixture) -> LayerId { let l = Layer::new(inner, "inner", fill(&[(Channel::Metallic, procedural(ProceduralKind::Scratches, 0.0, 1.0))]), &Channel::DEFAULT_SET); f.project.insert_layer(0, l, Some(group), true).unwrap(); let mut blurred = Mask::new(MaskBackground::Black); - blurred.effects.push(effect(f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() })); + blurred.effects.push(effect( + f, + EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() }, + )); blurred.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 24.0 }))); let top = add(f, 0, LayerKind::Paint, Some(blurred)); let img = f.pixels.layer_mut(top, Channel::BaseColor, (RES, RES)); @@ -203,7 +206,7 @@ fn mask_with_height_follows_the_layer_height() { let height = Source::Procedural { pattern: ramp, low: [0.25; 3], high: [-0.25; 3], ramp: Vec::new() }; let id = add(&mut f, 0, fill(&[(Channel::BaseColor, Source::Uniform([1.0; 3])), (Channel::Height, height)]), None); let mut mask = Mask::new(MaskBackground::Black); - mask.effects.push(effect(&mut f, EffectKind::Fill { source: Source::Uniform([0.5; 3]), projection: Projection::default() })); + mask.effects.push(effect(&mut f, EffectKind::Fill { source: Source::Uniform([0.5; 3]), projection: Projection::default(), sampling: Default::default() })); f.project.layer_mut(id).unwrap().mask = Some(mask); let plain = reference(&f, 0); f.project.layer_mut(id).unwrap().height_mask = HeightMask { enabled: true, contrast: 1.0, offset: 0.0 }; @@ -290,7 +293,10 @@ fn nested_stack(f: &mut Fixture) -> Nested { let inner = put(f, 0, Some(g1), fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0)), (Channel::Metallic, Source::Uniform([0.3; 3]))]), None); let mut checker = Mask::new(MaskBackground::Black); - checker.effects.push(effect(f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.2, 1.0), projection: Projection::default() })); + checker.effects.push(effect( + f, + EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.2, 1.0), projection: Projection::default(), sampling: Default::default() }, + )); let g2 = group(f, Some(g1), BlendMode::Passthrough, 1.0, Some(checker)); let mask = generator_mask(f, GeneratorKind::Direction, Some(16.0)); put(f, 0, Some(g2), fill(&[(Channel::BaseColor, procedural(ProceduralKind::Scratches, 0.0, 1.0))]), Some(mask)); @@ -412,7 +418,7 @@ fn anchor_readers_fall_back_to_full_evaluation() { f.project.layer_mut(n.base).unwrap().content_effects.push(anchor); // A mask above the hot layer reads the stack below it - let reader = effect(&mut f, EffectKind::Fill { source, projection: Projection::default() }); + let reader = effect(&mut f, EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() }); f.project.layer_mut(n.g2_above).unwrap().mask.as_mut().unwrap().effects.push(reader); for hot in [n.deep, n.top] { assert!(check_cached(&f, 0, hot).is_empty(), "anchors read the stack: nothing cached"); @@ -556,7 +562,10 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() { None, ); let mut slope = Mask::new(MaskBackground::Black); - slope.effects.push(effect(&mut f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() })); + slope.effects.push(effect( + &mut f, + EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() }, + )); slope.effects.push(effect(&mut f, EffectKind::Filter(Filter::SlopeBlur { radius: 24.0, scale: 3.0, seed: 1 }))); let streaks = add(&mut f, 0, fill(&[(Channel::Metallic, procedural(ProceduralKind::Stripes, 0.0, 1.0))]), Some(slope)); let top = add(&mut f, 0, LayerKind::Paint, None); @@ -685,7 +694,10 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() { // Pattern detail exposes any missing blur field let mut blurred = Mask::new(MaskBackground::Black); - blurred.effects.push(effect(&mut fixture, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() })); + blurred.effects.push(effect( + &mut fixture, + EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() }, + )); blurred.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 40.0 }))); add(&mut fixture, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(blurred)); @@ -762,7 +774,7 @@ fn cached_stack_tracks_the_images_a_tile_generator_reads() { pattern.tile.get_or_insert_with(Box::default).background_image = Some("plate".into()); fill.sources.insert(Channel::Roughness, Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }); - let image_with_value = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false }); + let image_with_value = |value| Arc::new(ImageRes::new(RES, RES, vec![[value; 4]; (RES * RES) as usize], false)); let mut images = ImageStore::default(); let baked = Default::default(); let tiles = all_tiles(RES, RES); @@ -800,7 +812,7 @@ fn cached_stack_tracks_referenced_images_only() { let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(bottom_layer).unwrap().kind else { panic!("expected fill") }; fill.sources.insert(Channel::Roughness, Source::Image { name: "used".into(), normal_format: Default::default() }); - let image_with_value = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false }); + let image_with_value = |value| Arc::new(ImageRes::new(RES, RES, vec![[value; 4]; (RES * RES) as usize], false)); let mut images = ImageStore::default(); let baked = Default::default(); let tiles = all_tiles(RES, RES); @@ -860,7 +872,7 @@ fn generator_input_image_changes_invalidate_stack_key() { *generator = Generator::new(GeneratorKind::Dirt); generator.inputs.insert(BakedMap::AmbientOcclusion, Source::image("used")); - let image = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false }); + let image = |value| Arc::new(ImageRes::new(RES, RES, vec![[value; 4]; (RES * RES) as usize], false)); let mut images = ImageStore::default(); images.insert("used".into(), image(0.1)); let baked = Default::default(); @@ -869,13 +881,16 @@ fn generator_input_image_changes_invalidate_stack_key() { let original = key(&images); images.insert("unrelated".into(), image(0.5)); + assert_eq!(key(&images), original, "an unrelated image leaves the key unchanged"); let old_image = Arc::downgrade(&images["used"]); images.insert("used".into(), image(0.9)); + assert!(old_image.upgrade().is_none(), "the cache must not retain the old image pixels"); assert!(key(&images) != original, "replacing a generator input must invalidate the cache"); images.remove("used"); + assert!(key(&images) != original, "removing a generator input must invalidate the cache"); } diff --git a/crates/core/src/backface.rs b/crates/core/src/backface.rs new file mode 100644 index 00000000..7e312fca --- /dev/null +++ b/crates/core/src/backface.rs @@ -0,0 +1,23 @@ +//! Backface culling of planar and cylindrical projections + +use serde::{Deserialize, Serialize}; + +/// Faces turned more than `angle` degrees from the projection get none of it, faded softer as `hardness` drops +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Backface { + pub on: bool, + pub angle: f32, + pub hardness: f32, +} + +impl Backface { + /// The angle culling may take, in degrees from facing the projector + pub const ANGLE_RANGE: std::ops::RangeInclusive = 0.0..=180.0; +} + +impl Default for Backface { + fn default() -> Self { + Backface { on: false, angle: 90.0, hardness: 0.5 } + } +} diff --git a/crates/core/src/depth_culling.rs b/crates/core/src/depth_culling.rs new file mode 100644 index 00000000..31038f83 --- /dev/null +++ b/crates/core/src/depth_culling.rs @@ -0,0 +1,23 @@ +//! Depth culling of planar and warp projections + +use serde::{Deserialize, Serialize}; + +/// Surfaces hidden from the projector behind other surfaces get none of the projection, faded softer as `hardness` drops +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct DepthCulling { + pub on: bool, + pub hardness: f32, +} + +impl DepthCulling { + /// What a new planar or warp projection starts with + pub const NEW: DepthCulling = DepthCulling { on: true, hardness: 0.75 }; +} + +impl Default for DepthCulling { + /// Off, as for every projection saved before depth culling existed + fn default() -> Self { + DepthCulling { on: false, ..DepthCulling::NEW } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index ec27f3cb..3797e2a5 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -7,15 +7,27 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod backface; pub mod bake; pub mod blend; mod block_scales; pub mod channel; +pub mod depth_culling; mod env_alignment; +pub mod fill_symmetry; pub mod layer; pub mod project; +pub mod projector; +mod saved_decal; +mod saved_projection; mod shadow_mode; +pub mod shape_crop; +pub mod symmetry_kind; +/// A full turn, in degrees +pub const FULL_TURN_DEGREES: f32 = 360.0; + +pub use backface::Backface; pub use bake::{ AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakedMap, BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings, HeightNormalization, @@ -25,16 +37,19 @@ pub use bake::{ }; pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; +pub use depth_culling::DepthCulling; +pub use fill_symmetry::FillSymmetry; pub use layer::{ - ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Generator, GeneratorGlobal, - GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, - PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, - TileSymmetry, gradient, hsl_adjust, per_unit, + ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, + GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, }; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, ShadowMode, TANGENT_BENT_NORMAL_VERSION, TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at, }; +pub use projector::Projector; +pub use shape_crop::ShapeCrop; +pub use symmetry_kind::SymmetryKind; #[derive(Debug, thiserror::Error, Clone, PartialEq)] pub enum CoreError { diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index ce14606b..7bbb1aa5 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -314,6 +314,14 @@ pub struct DisplaySettings { pub ior: f32, /// Depth of field of the viewport and the path tracer (thin lens). pub dof: DepthOfField, + /// The selected fill's projection gizmos show in the 3D view (the Projection row's eye) + #[serde(skip_serializing_if = "is_shown")] + pub projection_gizmos: bool, +} + +/// Whether a view flag is at its default, shown (saved projects then stay as they were) +fn is_shown(shown: &bool) -> bool { + *shown } /// A thin-lens camera's depth of field (Display settings: focus distance and aperture). @@ -403,6 +411,7 @@ impl Default for DisplaySettings { scatter_radius: 0.1, ior: 1.5, dof: DepthOfField::default(), + projection_gizmos: true, } } } @@ -816,12 +825,13 @@ mod tests { let mut top = paint(&mut p, "y"); let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() }; top.mask = Some(Mask { - effects: vec![Effect::new(p.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })], + effects: vec![Effect::new(p.alloc_id(), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::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(); + assert_eq!(back, p); assert_eq!(back.effect(anchor).map(|(owner, _)| owner), Some(id)); diff --git a/crates/core/src/projector.rs b/crates/core/src/projector.rs new file mode 100644 index 00000000..ba0b5459 --- /dev/null +++ b/crates/core/src/projector.rs @@ -0,0 +1,40 @@ +//! The 3D projection settings shared by tri-planar, planar, spherical and cylindrical projections + +use serde::{Deserialize, Serialize}; + +use crate::{Backface, DepthCulling, ShapeCrop}; + +/// Rotation (degrees about X, then Y, then Z) and per-axis scale of a 3D projection's shape; default = unchanged +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Projector { + pub rotation: [f32; 3], + pub scale: [f32; 3], + pub crop: ShapeCrop, + pub backface: Backface, + /// Planar and warp projections only + pub depth: DepthCulling, +} + +impl Default for Projector { + fn default() -> Self { + Projector { rotation: [0.0; 3], scale: [1.0; 3], crop: ShapeCrop::default(), backface: Backface::default(), depth: DepthCulling::default() } + } +} + +impl Projector { + /// The settings a new planar or warp projection starts with: depth culled + pub fn depth_culled() -> Projector { + Projector { depth: DepthCulling::NEW, ..Projector::default() } + } + + /// Whether it is the default, which projections saved before it existed load as (not saved then) + pub fn is_default(&self) -> bool { + *self == Projector::default() + } + + /// Whether it turns or stretches the projection at all + pub fn turns(&self) -> bool { + self.rotation != [0.0; 3] || self.scale != [1.0; 3] + } +} diff --git a/crates/core/src/saved_projection.rs b/crates/core/src/saved_projection.rs new file mode 100644 index 00000000..d748ed02 --- /dev/null +++ b/crates/core/src/saved_projection.rs @@ -0,0 +1,30 @@ +//! Reading and writing saved projections, including decals in the shape saved before they were planar projections placed on the surface + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +use crate::saved_decal::SavedDecal; +use crate::{Decal, Projection}; + +/// A projection as saved: today's, or a decal from before decals were planar projections +#[derive(Deserialize)] +enum SavedProjection { + Decal(Decal), + #[serde(untagged)] + Current(Projection), +} + +/// Serde hook for projection fields: an older decal loads as the planar projection that looks the same +pub(crate) fn load<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + Ok(match SavedProjection::deserialize(deserializer)? { + SavedProjection::Decal(frame) => Projection::decal(frame), + SavedProjection::Current(projection) => projection, + }) +} + +/// Serde hook for projection fields: a planar projection with a decal's look saves as a decal, so earlier versions still read a decal +pub(crate) fn save(projection: &Projection, serializer: S) -> Result { + match projection { + Projection::Planar { placed: Some(frame), .. } if *projection == Projection::decal(*frame) => SavedDecal::Decal(frame).serialize(serializer), + _ => projection.serialize(serializer), + } +} diff --git a/crates/core/src/shape_crop.rs b/crates/core/src/shape_crop.rs new file mode 100644 index 00000000..d0be4dd2 --- /dev/null +++ b/crates/core/src/shape_crop.rs @@ -0,0 +1,27 @@ +//! How far a 3D projection reaches past its shape + +use serde::{Deserialize, Serialize}; + +/// Whether a projection reaches past its shape (planar frame, tri-planar box, sphere, cylinder) +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] +pub enum ShapeCrop { + #[default] + ExtendsOutside, + Cropped, +} + +impl ShapeCrop { + pub const ALL: [ShapeCrop; 2] = [ShapeCrop::Cropped, ShapeCrop::ExtendsOutside]; + + /// Command id + pub fn id(self) -> &'static str { + match self { + ShapeCrop::ExtendsOutside => "extendsOutside", + ShapeCrop::Cropped => "cropped", + } + } + + pub fn from_id(id: &str) -> Option { + ShapeCrop::ALL.into_iter().find(|crop| crop.id() == id) + } +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index b0e5332f..32451af5 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -111,6 +111,7 @@ pub fn command_specs() -> &'static [CommandSpec] { let mut v = Vec::new(); v.extend(crate::view_cmds::edit_specs()); v.extend(crate::layer_cmds::specs()); + v.extend(crate::fill_reset_cmds::specs()); v.extend(crate::layer_ops::specs()); v.extend(crate::instance_cmds::specs()); v.extend(crate::mask_cmds::specs()); @@ -142,6 +143,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::smart_masks::specs()); v.extend(crate::filter_lib::specs()); v.extend(crate::decal_cmds::specs()); + v.extend(crate::warp_cmds::specs()); v.extend(crate::text_cmds::specs()); v }) diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index 45aace1c..2430b0dd 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -151,7 +151,7 @@ fn mat_finish(id: &str) -> Option { }; let pattern = Procedural { scale, ..Procedural::new(kind) }; - let mut fill = Fill { projection: Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] }, ..Fill::default() }; + let mut fill = Fill { projection: Projection::triplanar(), ..Fill::default() }; fill.sources.insert(Channel::Roughness, Source::Procedural { pattern: pattern.clone(), low: [rough[0]; 3], high: [rough[1]; 3], ramp: Vec::new() }); fill.sources.insert(Channel::Height, Source::Procedural { pattern, low: [-height; 3], high: [height; 3], ramp: Vec::new() }); Some(fill) diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 8fb0a3d8..f1c82a32 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -2,7 +2,7 @@ //! without a screenshot. use serde_json::{Value, json}; -use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, LayerKind, NormalFormat, Projection, Source}; +use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, LayerKind, NormalFormat, Projection, Sampling, Source}; use crate::Session; use crate::session::StackTarget; @@ -11,19 +11,20 @@ fn source_json(source: &Source) -> Value { match source { Source::Uniform(value) => json!({ "uniform": value }), Source::Procedural { pattern, low, high, ramp } => { - let mut report = json!({ - "procedural": pattern.kind.label(), "scale": pattern.scale, "seed": pattern.seed, "contrast": pattern.contrast, "low": low, "high": high + let mut out = json!({ + "procedural": pattern.kind.label(), "scale": pattern.scale, "seed": pattern.seed, "contrast": pattern.contrast, + "balance": pattern.balance, "invert": pattern.invert, "low": low, "high": high }); if !pattern.resolution.is_default() { - report["resolution"] = + out["resolution"] = json!({ "mode": format!("{:?}", pattern.resolution.mode), "custom": pattern.resolution.custom, "factor": pattern.resolution.factor }); } if let Some(tile) = &pattern.tile { - report["tile"] = crate::procedural_params::tile_report(tile); + out["tile"] = crate::procedural_params::tile_report(tile); } - with_ramp(report, ramp) + with_ramp(out, ramp) } Source::Image { name, normal_format: NormalFormat::OpenGl } => json!({ "image": name }), Source::Image { name, normal_format: NormalFormat::DirectX } => json!({ "image": name, "normalFormat": "directX" }), @@ -31,29 +32,38 @@ fn source_json(source: &Source) -> Value { } } -/// `v` with the gradient map stops of its source as `colors`, when it has any. -fn with_ramp(mut v: Value, ramp: &[[f32; 3]]) -> Value { +/// `out` with the gradient map stops of its source as `colors`, when it has any +fn with_ramp(mut out: Value, ramp: &[[f32; 3]]) -> Value { if !ramp.is_empty() { - v["colors"] = json!(ramp); + out["colors"] = json!(ramp); } - v + out } -fn fill_json(f: &Fill) -> Value { - let mut v = json!({ - "projection": f.projection.label(), - "sources": f.sources.iter().map(|(c, s)| (c.id().to_string(), source_json(s))).collect::>(), - }); - if let Projection::Decal(d) = &f.projection { - v["decal"] = json!(d); +fn fill_json(fill: &Fill) -> Value { + let sources = fill.sources.iter().map(|(channel, source)| (channel.id().to_string(), source_json(source))); + let mut out = json!({ "sources": sources.collect::>() }); + placement_json(&fill.projection, &fill.sampling, &mut out); + if let Some(link) = &fill.link { + out["link"] = json!(link); } - if let Some(link) = &f.link { - v["link"] = json!(link); - } - v + out } -/// A mask or content (`content`) effect. +/// Where a fill lands and how it reads its sources: the projection, its frame when placed on the surface, and the sampling +fn placement_json(projection: &Projection, sampling: &Sampling, out: &mut Value) { + out["projection"] = json!(projection.label()); + out["projectionSettings"] = json!(projection); + out["filtering"] = json!(sampling.filtering.id()); + out["wrap"] = json!(sampling.wrap.id()); + out["scaleMode"] = json!(sampling.scale.id()); + out["symmetry"] = json!(sampling.symmetry); + if let Some(frame) = projection.placed() { + out["decal"] = json!(frame); + } +} + +/// A mask or content (`content`) effect fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { let mut out = json!({ "id": effect.id.0, "name": effect.name, "kind": effect.kind.name(), "visible": effect.visible, "blend": effect.blend.label(), "opacity": effect.opacity }); let mask_tiles = || session.doc.pixels.masks.get(&effect.id).map_or(0, |image| image.allocated_count()); @@ -74,7 +84,10 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { } EffectKind::Paint if content => out["tiles"] = json!(content_tiles()), EffectKind::Paint => out["tiles"] = json!(mask_tiles()), - EffectKind::Fill { source, .. } => out["source"] = source_json(source), + EffectKind::Fill { source, projection, sampling } => { + out["source"] = source_json(source); + placement_json(projection, sampling, &mut out); + } EffectKind::Material(fill) => out["fill"] = fill_json(fill), EffectKind::Filter(filter) => { out["filter"] = json!(filter); @@ -89,7 +102,7 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { out } -/// A generator's settings: global adjustments, then its resolution, replaced inputs and curvature detail when it has them. +/// A generator's settings: global adjustments, then its resolution, replaced inputs and curvature detail when it has them fn generator_json(generator: &Generator) -> Value { let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "offset": generator.offset, "invert": generator.invert, "blur": generator.global.blur, "balance": generator.global.balance, "contrast": generator.global.contrast }); if !generator.resolution.is_default() { @@ -160,7 +173,7 @@ fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value { v } -/// The layer stack of texture set `ts`, top → bottom (as displayed). +/// The layer stack of texture set `ts`, top → bottom (as displayed) pub fn stack(s: &Session, ts: usize) -> Value { let Some(set) = s.doc.project.texture_sets.get(ts) else { return Value::Null }; json!(set.stack.iter().rev().filter_map(|id| s.doc.project.layers.get(id)).map(|l| layer_json(s, l, 0)).collect::>()) @@ -201,7 +214,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value { }) } -/// The whole session. +/// The whole session pub fn session(session: &Session) -> Value { let texture_set = session.ts(); json!({ diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 56d2fc2e..4c8b209f 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -13,6 +13,23 @@ use crate::commands::{ use crate::layer_selection::{batch_param, ids_json}; use crate::{EngineError, Result, Session, cmd, session::StackTarget}; +/// One full turn, in degrees (the brush's, so every angle wraps on the same turn) +pub(crate) use texturecraft_paint::FULL_TURN_DEGREES; + +/// The smallest scale or tiling a fill's placement takes +pub const MIN_SCALE: f32 = 0.001; +/// The largest scale, tiling or offset a fill's placement takes +pub const MAX_PLACEMENT: f32 = 1000.0; + +/// The command [`fill_set`] runs as +const FILL_SET: &str = "layer.fill.set"; + +/// How far a warp's corner may be pulled from the frame's centre, in frame sizes +const MAX_CORNER_REACH: f32 = 100.0; + +/// The largest Projection Depth, in lengths of the frame's longer side +pub(crate) const MAX_PROJECTION_DEPTH: f32 = 100.0; + pub fn specs() -> Vec { vec![ cmd!("layer.add.paint", "Add paint layer", ["Layers"], None, "{name?}", always, add_paint), @@ -491,15 +508,7 @@ fn blending_set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } -/// Which fill `layer.fill.*` edits: a fill layer's (`layer`) or a content fill effect's -/// (`effect`). -#[derive(Clone, Copy)] -enum FillTarget { - Layer(LayerId), - Effect(LayerId), -} - -fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result { +pub(crate) fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result { match u64p(p, "effect").map(LayerId) { Some(e) => match s.doc.project.effect(e) { Some((_, x)) if matches!(x.kind, EffectKind::Material(_)) => Ok(FillTarget::Effect(e)), @@ -509,44 +518,49 @@ fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result { } } -fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> { +pub(crate) fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> { match target { FillTarget::Layer(id) => match &mut s.doc.project.layer_mut(id)?.kind { LayerKind::Fill(f) => Ok(f), _ => Err(EngineError::Other("not a fill layer".into())), }, - FillTarget::Effect(e) => match s.doc.project.effect_mut(e).map(|x| &mut x.kind) { + FillTarget::Effect(effect) => match s.doc.project.effect_mut(effect).map(|found| &mut found.kind) { Some(EffectKind::Material(f)) => Ok(f), _ => Err(EngineError::Other("not a content fill effect".into())), }, } } +/// How the fill at `target` is projected and sampled: every fill has both +pub(crate) fn placement_mut(s: &mut Session, target: FillTarget) -> Result<(&mut Projection, &mut Sampling)> { + let fill = fill_mut(s, target)?; + Ok((&mut fill.projection, &mut fill.sampling)) +} + fn fill_set(session: &mut Session, params: &Value) -> Result { - const CMD: &str = "layer.fill.set"; - let target = fill_target(session, params, CMD)?; - let channel = channel_param(CMD, params, "channel")?.ok_or_else(|| bad(CMD, "`channel` is required"))?; + let target = fill_target(session, params, FILL_SET)?; + let channel = channel_param(FILL_SET, params, "channel")?.ok_or_else(|| bad(FILL_SET, "`channel` is required"))?; // `solo`: this channel on, every other one off let solo = boolp(params, "solo") == Some(true); let enabled = if solo { Some(true) } else { boolp(params, "enabled") }; - let normal_format = normal_format_param(CMD, params)?; + let normal_format = normal_format_param(FILL_SET, params)?; let colors = ramp_param(params, channel)?; let init_ramp = boolp(params, "gradientMap") == Some(true); if init_ramp && colors.is_some() { - return Err(bad(CMD, "give `gradientMap` or `colors`, not both")); + return Err(bad(FILL_SET, "give `gradientMap` or `colors`, not both")); } let source = fill_source_from(session, params, (target, channel), normal_format)?; if source.is_none() && enabled.is_none() && normal_format.is_none() && colors.is_none() && !init_ramp { return Err(bad( - CMD, + FILL_SET, "give `color`, `value`, `procedural`, `image`, `anchor`, pattern settings (`tile`, `resolution`…), `colors`, `gradientMap`, `normalFormat`, `enabled` or `solo`", )); } if normal_format.is_some() && source.as_ref().is_some_and(|source| !matches!(source, Source::Image { .. })) { - return Err(bad(CMD, "`normalFormat` goes with `image` or alone")); + return Err(bad(FILL_SET, "`normalFormat` goes with `image` or alone")); } // Changing only the normal format or gradient stops leaves the layer channel on or off @@ -558,7 +572,7 @@ fn fill_set(session: &mut Session, params: &Value) -> Result { if let (None, Some(format)) = (&source, normal_format) { match fill.sources.get_mut(&channel) { Some(Source::Image { normal_format, .. }) => *normal_format = format, - _ => return Err(bad(CMD, "`normalFormat` needs an image on the channel")), + _ => return Err(bad(FILL_SET, "`normalFormat` needs an image on the channel")), } } @@ -601,6 +615,18 @@ fn fill_set(session: &mut Session, params: &Value) -> Result { Ok(Value::Null) } +/// The procedural source `params` ask for with `low`/`high` already parsed: a pattern of the same kind as `current` keeps what `params` do not give; another kind starts from its defaults +fn procedural_from(params: &Value, kind: ProceduralKind, current: Option<&Source>, [low, high]: [Option<[f32; 3]>; 2]) -> Result { + let (mut pattern, current_low, current_high) = match current { + Some(Source::Procedural { pattern, low, high, .. }) if pattern.kind == kind => (pattern.clone(), *low, *high), + _ => (Procedural::new(kind), [0.0; 3], [1.0; 3]), + }; + + crate::procedural_params::pattern_basics_from(params, &mut pattern); + crate::procedural_params::pattern_settings_from(FILL_SET, params, &mut pattern)?; + Ok(Source::Procedural { pattern, low: low.unwrap_or(current_low), high: high.unwrap_or(current_high), ramp: Vec::new() }) +} + /// The source `params` give fill channel `channel` of `target`, or None when they only switch it or set its image's normal format fn fill_source_from( session: &mut Session, @@ -608,27 +634,15 @@ fn fill_source_from( (target, channel): (FillTarget, Channel), normal_format: Option, ) -> Result> { - const CMD: &str = "layer.fill.set"; - let low = color_param(CMD, params, "low")?.unwrap_or([0.0; 3]); - let high = color_param(CMD, params, "high")?.unwrap_or([1.0; 3]); - let uniform = color_param(CMD, params, "color")?.or(color_param(CMD, params, "value")?); + let low = color_param(FILL_SET, params, "low")?; + let high = color_param(FILL_SET, params, "high")?; + let uniform = color_param(FILL_SET, params, "color")?.or(color_param(FILL_SET, params, "value")?); if let Some(name) = strp(params, "procedural") { - let kind = ProceduralKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown procedural `{name}`")))?; - let mut pattern = Procedural::new(kind); - crate::procedural_params::pattern_basics_from(params, &mut pattern); - - // A pattern of the same kind keeps its resolution and Tile Generator settings - let current = fill_mut(session, target)?.sources.get(&channel); - if let Some(Source::Procedural { pattern: current, .. }) = current - && current.kind == kind - { - pattern.resolution = current.resolution; - pattern.tile = current.tile.clone(); - } - - crate::procedural_params::pattern_settings_from(CMD, params, &mut pattern)?; - return Ok(Some(Source::Procedural { pattern, low, high, ramp: Vec::new() })); + let kind = ProceduralKind::parse(name).ok_or_else(|| bad(FILL_SET, format!("unknown procedural `{name}`")))?; + // A pattern of the same kind keeps what `params` do not give; another kind starts from its defaults + let current = fill_mut(session, target)?.sources.get(&channel).cloned(); + return Ok(Some(procedural_from(params, kind, current.as_ref(), [low, high])?)); } if let Some(color) = uniform { @@ -644,9 +658,9 @@ fn fill_source_from( FillTarget::Layer(id) => Some(id), FillTarget::Effect(effect) => session.doc.project.effect(effect).map(|(owner, _)| owner), }; - let reader = reader.ok_or_else(|| bad(CMD, "the fill is not in a layer"))?; - let anchor_channel = channel_param(CMD, params, "anchorChannel")?.unwrap_or(channel); - return Ok(Some(crate::mask_cmds::anchor_source(session, CMD, reader, LayerId(anchor), anchor_channel)?)); + let reader = reader.ok_or_else(|| bad(FILL_SET, "the fill is not in a layer"))?; + let anchor_channel = channel_param(FILL_SET, params, "anchorChannel")?.unwrap_or(channel); + return Ok(Some(crate::mask_cmds::anchor_source(session, FILL_SET, reader, LayerId(anchor), anchor_channel)?)); } if !crate::procedural_params::has_pattern_settings(params) { @@ -655,12 +669,12 @@ fn fill_source_from( // Pattern settings alone edit the channel's current pattern let Some(Source::Procedural { pattern, low, high, .. }) = fill_mut(session, target)?.sources.get(&channel) else { - return Err(bad(CMD, "the channel has no pattern: give `procedural` with its settings")); + return Err(bad(FILL_SET, "the channel has no pattern: give `procedural` with its settings")); }; let mut pattern = pattern.clone(); crate::procedural_params::pattern_basics_from(params, &mut pattern); - crate::procedural_params::pattern_settings_from(CMD, params, &mut pattern)?; + crate::procedural_params::pattern_settings_from(FILL_SET, params, &mut pattern)?; Ok(Some(Source::Procedural { pattern, low: *low, high: *high, ramp: Vec::new() })) } @@ -731,83 +745,236 @@ fn with_ramp(channel: Channel, current: Option<&Source>, source: Option, Ok(Some(source)) } -/// Parse projection settings, retaining unspecified fields when the projection kind stays the same. -pub(crate) fn projection_from(params: &Value, command: &str, current: Option<&Projection>) -> Result { - projection_from_fields(params, command, current, true) +/// A new fill's projection of kind `id` (`uv`, `uvTile`, `triplanar`, `planar`, `spherical`, `cylindrical`, or a `warp` from frame `fit`) +pub(crate) fn new_projection(id: &str, fit: impl FnOnce() -> Decal) -> Option { + match id { + "warp" => Some(Projection::warp(fit())), + _ => new_unframed_projection(id), + } } -/// A procedural mask can assign the command's scale to its pattern instead of its projection. -pub(crate) fn projection_from_fields(params: &Value, command: &str, current: Option<&Projection>, read_scale: bool) -> Result { - const MIN_SCALE: f32 = 0.001; - const MAX_SCALE: f32 = 1000.0; - const MAX_OFFSET: f32 = 1000.0; - const DEFAULT_SHARPNESS: f32 = 8.0; - const MAX_SHARPNESS: f32 = 64.0; +/// The ids [`new_unframed_projection`] takes, one per kind +pub(crate) const UNFRAMED_PROJECTION_IDS: [&str; 6] = ["uv", "uvTile", "triplanar", "planar", "spherical", "cylindrical"]; - let named = match strp(params, "projection") { +/// A new fill's projection of kind `id`, any kind but a warp (which needs a frame) +pub(crate) fn new_unframed_projection(id: &str) -> Option { + let projection = match id { + "uv" => Projection::default(), + "uvTile" => Projection::UvTile, + "triplanar" | "tri-planar" => Projection::triplanar(), + "planar" => Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: Default::default(), projector: Projector::depth_culled(), placed: None }, + "spherical" => Projection::Spherical { scale: 1.0, uv: Default::default(), offset: [0.0; 3], projector: Default::default() }, + "cylindrical" => { + Projection::Cylindrical { scale: 1.0, axis: 1, uv: Default::default(), offset: [0.0; 3], projector: Default::default(), angle: FULL_TURN_DEGREES } + } + _ => return None, + }; + Some(projection) +} + +/// The projection `p` asks for: fields it does not give keep their values from `current` when that is of the same kind (or `p` names no kind), and the kind's defaults otherwise; a new warp starts from frame `fit` +pub(crate) fn projection_from(p: &Value, cmd: &str, current: Option<&Projection>, fit: impl FnOnce() -> Decal) -> Result { + let named = match strp(p, "projection") { None => None, - Some("uv") => Some(Projection::default()), - Some("triplanar" | "tri-planar") => Some(Projection::Triplanar { scale: 1.0, sharpness: DEFAULT_SHARPNESS, offset: [0.0; 3] }), - Some("planar") => Some(Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3] }), - Some("spherical") => Some(Projection::Spherical { scale: 1.0 }), - Some("cylindrical") => Some(Projection::Cylindrical { scale: 1.0, axis: 1 }), - Some(other) => return Err(bad(command, format!("unknown projection `{other}`"))), + Some("warp") if matches!(current, Some(Projection::Warp { .. })) => current.cloned(), + Some(id) => Some(new_projection(id, fit).ok_or_else(|| bad(cmd, format!("unknown projection `{id}`")))?), }; let mut projection = match (named, current) { (Some(named), Some(current)) if std::mem::discriminant(&named) == std::mem::discriminant(current) => current.clone(), (Some(named), _) => named, (None, current) => current.cloned().unwrap_or_default(), }; + let scale = floats::<2>(p, "scale", MIN_SCALE, MAX_PLACEMENT); + let tiling = floats::<2>(p, "tiling", MIN_SCALE, MAX_PLACEMENT); + let rotation = f32p(p, "rotation").map(|degrees| degrees.rem_euclid(FULL_TURN_DEGREES)); + let axis = u64p(p, "axis").map(|axis| axis.min(2) as u8); - let new_scale = if read_scale { floats::<2>(params, "scale", MIN_SCALE, MAX_SCALE) } else { None }; - let new_axis = u64p(params, "axis").map(|axis| axis.min(2) as u8); + // The UV transformations of a 3D projection: tiling, rotation and an offset across the surface + let place = |uv: &mut UvTransform| { + uv.tiling = tiling.unwrap_or(uv.tiling); + uv.rotation = rotation.unwrap_or(uv.rotation); + uv.offset = floats(p, "uvOffset", -MAX_PLACEMENT, MAX_PLACEMENT).unwrap_or(uv.offset); + }; + + // The 3D projection settings: the projector's offset, turn and per-axis scale + let projector_offset = floats::<3>(p, "offset", -MAX_PLACEMENT, MAX_PLACEMENT); + let crop = match strp(p, "shapeCrop") { + None => None, + Some(id) => Some(ShapeCrop::from_id(id).ok_or_else(|| bad(cmd, format!("unknown shapeCrop `{id}`: cropped or extendsOutside")))?), + }; + let turn = |projector: &mut Projector| { + projector.rotation = floats(p, "projectorRotation", -FULL_TURN_DEGREES, FULL_TURN_DEGREES).unwrap_or(projector.rotation); + projector.scale = floats(p, "projectorScale", -MAX_PLACEMENT, MAX_PLACEMENT).map_or(projector.scale, |scale| scale.map(signed_scale)); + projector.crop = crop.unwrap_or(projector.crop); + projector.backface.on = p.get("backfaceCulling").and_then(Value::as_bool).unwrap_or(projector.backface.on); + projector.backface.angle = f32p(p, "backfaceAngle").map_or(projector.backface.angle, |angle| clamp_to(angle, &Backface::ANGLE_RANGE)); + projector.backface.hardness = f32p(p, "backfaceHardness").map_or(projector.backface.hardness, |hardness| hardness.clamp(0.0, 1.0)); + projector.depth.on = p.get("depthCulling").and_then(Value::as_bool).unwrap_or(projector.depth.on); + projector.depth.hardness = f32p(p, "depthCullingHardness").map_or(projector.depth.hardness, |hardness| hardness.clamp(0.0, 1.0)); + }; match &mut projection { - Projection::Uv { scale, rotation, offset } => { - *scale = new_scale.unwrap_or(*scale); - *rotation = f32p(params, "rotation").map_or(*rotation, |degrees| degrees.rem_euclid(360.0)); - *offset = floats(params, "offset", -MAX_OFFSET, MAX_OFFSET).unwrap_or(*offset); + Projection::Uv { scale: uv_scale, rotation: uv_rotation, offset } => { + // A UV projection's scale is its tiling + *uv_scale = tiling.or(scale).unwrap_or(*uv_scale); + *uv_rotation = rotation.unwrap_or(*uv_rotation); + *offset = floats(p, "offset", -MAX_PLACEMENT, MAX_PLACEMENT).unwrap_or(*offset); } - Projection::Triplanar { scale, sharpness, offset } => { - *scale = new_scale.map_or(*scale, |axes| axes[0]); - *sharpness = f32p(params, "sharpness").map_or(*sharpness, |value| value.clamp(1.0, MAX_SHARPNESS)); - *offset = floats(params, "offset", -MAX_OFFSET, MAX_OFFSET).unwrap_or(*offset); + Projection::UvTile => {} + Projection::Triplanar { scale: projection_scale, sharpness, offset, uv, projector } => { + *projection_scale = scale.map_or(*projection_scale, |across| across[0]); + *sharpness = f32p(p, "sharpness").map_or(*sharpness, |given| clamp_to(given, &Projection::TRIPLANAR_SHARPNESS_RANGE)); + *offset = projector_offset.unwrap_or(*offset); + place(uv); + turn(projector); } - Projection::Planar { scale, axis, offset } => { - *scale = new_scale.map_or(*scale, |axes| axes[0]); - *axis = new_axis.unwrap_or(*axis); - *offset = floats(params, "offset", -MAX_OFFSET, MAX_OFFSET).unwrap_or(*offset); + Projection::Planar { scale: projection_scale, axis: projection_axis, offset, uv, projector, .. } => { + *projection_scale = scale.map_or(*projection_scale, |across| across[0]); + *projection_axis = axis.unwrap_or(*projection_axis); + *offset = projector_offset.unwrap_or(*offset); + place(uv); + turn(projector); } - Projection::Spherical { scale } => *scale = new_scale.map_or(*scale, |axes| axes[0]), - Projection::Cylindrical { scale, axis } => { - *scale = new_scale.map_or(*scale, |axes| axes[0]); - *axis = new_axis.unwrap_or(*axis); + Projection::Spherical { scale: projection_scale, uv, offset, projector } => { + *projection_scale = scale.map_or(*projection_scale, |across| across[0]); + *offset = projector_offset.unwrap_or(*offset); + place(uv); + turn(projector); } - Projection::Decal(_) => {} - } + Projection::Cylindrical { scale: projection_scale, axis: projection_axis, uv, offset, projector, angle } => { + *projection_scale = scale.map_or(*projection_scale, |across| across[0]); + *angle = f32p(p, "angle").map_or(*angle, |given| clamp_to(given, &Projection::CYLINDER_ANGLE_RANGE)); + *projection_axis = axis.unwrap_or(*projection_axis); + *offset = projector_offset.unwrap_or(*offset); + place(uv); + turn(projector); + } + Projection::Warp { corners, depth, uv, projector, .. } => { + // A warp has no scale or offset of its own: its frame places it, so they would change nothing + if p.get("scale").is_some() || p.get("offset").is_some() { + return Err(bad(cmd, "a warp is placed by its frame: set frameOffset or frameScale with layer.decal.set")); + } + *corners = warp_corners(p, cmd)?.unwrap_or(*corners); + *depth = f32p(p, "projectionDepth").map_or(*depth, |given| given.clamp(0.0, MAX_PROJECTION_DEPTH)); + place(uv); + turn(projector); + } + } Ok(projection) } -/// `key` as `N` finite numbers clamped to `lo..=hi`: an array of `N`, or one number for all. +/// `value` held within `range` +fn clamp_to(value: f32, range: &std::ops::RangeInclusive) -> f32 { + value.clamp(*range.start(), *range.end()) +} + +/// The projection `params` asks for, as [`projection_from`]; without `read_scale` its `scale` is left out (a procedural mask's scale is its pattern's) +pub(crate) fn projection_from_fields( + params: &Value, + command: &str, + current: Option<&Projection>, + read_scale: bool, + fit: impl FnOnce() -> Decal, +) -> Result { + let mut placement = params.clone(); + if !read_scale && let Some(fields) = placement.as_object_mut() { + fields.remove("scale"); + } + projection_from(&placement, command, current, fit) +} + +/// The `warpCorners` param: four [across, up] corners in frame sizes from the frame's centre, finite and within reach of the frame (None when not given) +fn warp_corners(p: &Value, cmd: &str) -> Result> { + let Some(given) = p.get("warpCorners") else { return Ok(None) }; + + let malformed = || bad(cmd, "warpCorners is four [across, up] pairs of finite numbers"); + let list = given.as_array().filter(|list| list.len() == 4).ok_or_else(malformed)?; + let mut corners = Projection::FRAME_CORNERS; + for (corner, value) in corners.iter_mut().zip(list) { + let pair = value.as_array().filter(|pair| pair.len() == 2).ok_or_else(malformed)?; + for (axis, number) in corner.iter_mut().zip(pair) { + let reach = number.as_f64().map(|number| number as f32).filter(|number| number.is_finite()).ok_or_else(malformed)?; + *axis = reach.clamp(-MAX_CORNER_REACH, MAX_CORNER_REACH); + } + } + Ok(Some(corners)) +} + +/// `current` with the `filtering`, `wrap`, `scaleMode` and symmetry params applied +pub(crate) fn sampling_from(p: &Value, cmd: &str, current: Sampling) -> Result { + let mut sampling = current; + if let Some(id) = strp(p, "filtering") { + sampling.filtering = Filtering::from_id(id).ok_or_else(|| bad(cmd, format!("unknown filtering `{id}`: bilinearHq, bilinearSharp or nearest")))?; + } + if let Some(id) = strp(p, "wrap") { + sampling.wrap = UvWrap::from_id(id).ok_or_else(|| bad(cmd, format!("unknown wrap `{id}`: repeat, repeatHorizontally, repeatVertically or none")))?; + } + if let Some(id) = strp(p, "scaleMode") { + sampling.scale = ScaleMode::from_id(id).ok_or_else(|| bad(cmd, format!("unknown scaleMode `{id}`: tiling or physicalSize")))?; + } + sampling.symmetry = symmetry_from(p, cmd, sampling.symmetry)?; + Ok(sampling) +} + +/// `current` with the `symmetry`, `symmetryType`, `symmetryAxis`, `flipCopy`, `axisPosition`, `symmetryCount` and `angleSpan` params applied +fn symmetry_from(p: &Value, cmd: &str, current: FillSymmetry) -> Result { + let mut symmetry = current; + symmetry.on = boolp(p, "symmetry").unwrap_or(symmetry.on); + if let Some(id) = strp(p, "symmetryType") { + symmetry.kind = SymmetryKind::from_id(id).ok_or_else(|| bad(cmd, format!("unknown symmetryType `{id}`: mirror or radial")))?; + } + if let Some(given) = p.get("symmetryAxis").filter(|given| !given.is_null()) { + // An index or the letter tool.brush takes for its own symmetry axis + let axis = match given { + Value::String(letter) => ["x", "y", "z"].iter().position(|name| letter.eq_ignore_ascii_case(name)).and_then(|index| u8::try_from(index).ok()), + index => index.as_u64().and_then(|index| u8::try_from(index).ok()).filter(|index| *index <= FillSymmetry::LAST_AXIS), + }; + symmetry.axis = axis.ok_or_else(|| bad(cmd, "symmetryAxis is 0 (X), 1 (Y) or 2 (Z), or \"x\", \"y\" or \"z\""))?; + } + if let Some(flips) = p.get("flipCopy") { + let [Some(across), Some(down)] = flips.as_array().map(Vec::as_slice).unwrap_or_default().iter().map(Value::as_bool).collect::>()[..] else { + return Err(bad(cmd, "flipCopy is [u, v], two booleans")); + }; + + symmetry.flip = [across, down]; + } + let reach = FillSymmetry::REACH; + symmetry.position = floats(p, "axisPosition", -reach, reach).unwrap_or(symmetry.position); + if let Some(count) = u64p(p, "symmetryCount") { + let (fewest, most) = (u64::from(*FillSymmetry::COUNTS.start()), u64::from(*FillSymmetry::COUNTS.end())); + symmetry.count = u32::try_from(count.clamp(fewest, most)).unwrap_or(*FillSymmetry::COUNTS.start()); + } + symmetry.span = f32p(p, "angleSpan").map_or(symmetry.span, |span| clamp_to(span, &FillSymmetry::SPANS)); + Ok(symmetry) +} + +/// `value` as one axis of a projector's scale: its size kept within [`MIN_SCALE`]..[`MAX_PLACEMENT`] on its own side, so a mirrored axis stays mirrored +pub fn signed_scale(value: f32) -> f32 { + value.signum() * value.abs().clamp(MIN_SCALE, MAX_PLACEMENT) +} + +/// `key` as `N` finite numbers clamped to `lo..=hi`: an array of `N`, or one number for all fn floats(p: &Value, key: &str, lo: f32, hi: f32) -> Option<[f32; N]> { - let one = |x: &Value| x.as_f64().map(|f| f as f32).filter(|f| f.is_finite()).map(|f| f.clamp(lo, hi)); + let number = |value: &Value| value.as_f64().map(|given| given as f32).filter(|given| given.is_finite()).map(|given| given.clamp(lo, hi)); match p.get(key)? { - Value::Array(a) if a.len() == N => { + Value::Array(list) if list.len() == N => { let mut out = [0.0; N]; - for (o, x) in out.iter_mut().zip(a) { - *o = one(x)?; + for (slot, value) in out.iter_mut().zip(list) { + *slot = number(value)?; } Some(out) } - v => one(v).map(|f| [f; N]), + value => number(value).map(|given| [given; N]), } } fn fill_projection(s: &mut Session, p: &Value) -> Result { let target = fill_target(s, p, "layer.fill.projection")?; + let mesh = s.mesh.clone(); s.edit("Fill projection", |s| { - let fill = fill_mut(s, target)?; - fill.projection = projection_from(p, "layer.fill.projection", Some(&fill.projection))?; + let (projection, sampling) = placement_mut(s, target)?; + *projection = projection_from(p, "layer.fill.projection", Some(projection), || crate::warp_cmds::fitted_frame(&mesh))?; + *sampling = sampling_from(p, "layer.fill.projection", *sampling)?; Ok(()) })?; Ok(Value::Null) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c1c8f9ab..4d25b237 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -19,6 +19,7 @@ pub mod effect_clipboard; pub mod file_cmds; pub mod fill_hit_test; pub mod fill_mode; +pub mod fill_reset_cmds; pub mod filter_lib; mod frame_target; pub mod inspect; @@ -76,6 +77,7 @@ mod uv_stroke_state; mod uv_symmetry; pub mod uv_tile_cmds; pub mod view_cmds; +pub mod warp_cmds; pub use bake::{BakeMesh, BakeMeshes, BakeTask, StreamedBake, StreamedMap}; pub use bake_preview::{BakePreview, PreviewShow}; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index adc124f8..ac1db3f5 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Add fill", ["Layers", "Effects"], None, - "{layer?, target?: mask|content, name?, mask: value?: 0..1 | image?: resource name | procedural?: kind, scale?, seed?, contrast?, balance?, invert?, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true | anchor?: anchor effect id, anchorChannel?: channel (height); content: color? ([r,g,b] linear or \"#rrggbb\" sRGB), roughness?, metallic?, height?, opacity? (default: every layer channel); projection?}", + "{layer?, target?: mask|content, name?, mask: value?: 0..1 | image?: resource name | procedural?: kind, scale?, seed?, contrast?, balance?, invert?, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true | anchor?: anchor effect id, anchorChannel?: channel (height); content: color? ([r,g,b] linear or \"#rrggbb\" sRGB), roughness?, metallic?, height?, opacity? (default: every layer channel); projection?; filtering?: bilinearHq|bilinearSharp|nearest; wrap?: repeat|repeatHorizontally|repeatVertically|none}", has_layer, add_fill ), @@ -295,16 +295,18 @@ fn image_source(session: &Session, command: &str, name: &str) -> Result fn add_fill(session: &mut Session, params: &Value) -> Result { const CMD: &str = "effect.add.fill"; + let sampling = crate::layer_cmds::sampling_from(params, CMD, Sampling::default())?; let blend = blend_param(CMD, params, "blend")?.unwrap_or(BlendMode::Normal); let layer = layer_param(session, CMD, params)?; if content_target(params, CMD)? { let mut fill = crate::layer_cmds::fill_from(CMD, params)?; + fill.sampling = sampling; if fill.sources.is_empty() { fill.sources = session.doc.project.layer(layer)?.channels.keys().map(|channel| (*channel, Source::uniform_of(*channel))).collect(); } - fill.projection = projection_from(params, CMD, None)?; + fill.projection = projection_from(params, CMD, None, || crate::warp_cmds::fitted_frame(&session.mesh))?; return push_effect(session, params, EffectKind::Material(fill), blend); } @@ -327,9 +329,9 @@ fn add_fill(session: &mut Session, params: &Value) -> Result { // A scalar controls pattern frequency, while a two-axis scale places the new mask let pattern_scale = matches!(source, Source::Procedural { .. }) && params.get("scale").is_some_and(Value::is_number); - let projection = projection_from_fields(params, CMD, None, !pattern_scale)?; + let projection = projection_from_fields(params, CMD, None, !pattern_scale, || crate::warp_cmds::fitted_frame(&session.mesh))?; - push_effect(session, params, EffectKind::Fill { source, projection }, blend) + push_effect(session, params, EffectKind::Fill { source, projection, sampling }, blend) } /// Apply `params` to `generator`, using `command` in errors @@ -613,6 +615,7 @@ fn set(session: &mut Session, params: &Value) -> Result { }; let swaps_filter = swapped.is_some(); + let mesh = session.mesh.clone(); session.edit("Edit effect", |session| { let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; if let Some((kind, label)) = swapped { @@ -667,7 +670,7 @@ fn set(session: &mut Session, params: &Value) -> Result { // The swapped filter was built with the parameters already EffectKind::Filter(_) if swaps_filter => {} EffectKind::Filter(filter) => crate::filter_lib::apply(params, filter, CMD)?, - EffectKind::Fill { source, projection } => { + EffectKind::Fill { source, projection, .. } => { // `uniform` picks the source, so it outranks settings that would edit the current pattern let uniform = f32p(params, "uniform").filter(|_| strp(params, "procedural").is_none()); if let Some(anchor) = anchor { @@ -684,9 +687,16 @@ fn set(session: &mut Session, params: &Value) -> Result { *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); } - // Pattern edits keep the mask's existing projection scale - let read_scale = !matches!(source, Source::Procedural { .. }); - *projection = projection_from_fields(params, CMD, Some(projection), read_scale)?; + // While the fill reads a pattern, `scale` is the pattern's and leaves the projection alone + let mut placement = params.clone(); + if matches!(source, Source::Procedural { .. }) + && let Some(fields) = placement.as_object_mut() + { + fields.remove("scale"); + } + + // Preserve projection fields that the edit does not supply + *projection = projection_from(&placement, CMD, Some(&*projection), || crate::warp_cmds::fitted_frame(&mesh))?; } EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_cmds::apply_params(params, colors, tolerance)?, EffectKind::Compare { tolerance, .. } => { diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index f91efe86..62c36dd2 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -210,8 +210,8 @@ impl Builder<'_> { fn fill(&mut self, name: &str, sources: Sources) -> Layer { let id = self.p.alloc_id(); let enabled: Vec = sources.iter().map(|(c, _)| *c).filter(|c| self.channels.contains(c)).collect(); - let projection = Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] }; - Layer::new(id, name, LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, link: None }), &enabled) + let projection = Projection::triplanar(); + Layer::new(id, name, LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, ..Fill::default() }), &enabled) } /// A fill masked by smart mask preset `mask` (inverted: present where the preset is not). @@ -782,8 +782,12 @@ pub fn brush_values(id: &str) -> Option> { /// `scale` (the same fill evaluation a layer with that material uses). pub(crate) fn brush_fill(id: LayerId, sources: Vec<(Channel, Source)>, scale: f32) -> Layer { let channels: Vec = sources.iter().map(|(channel, _)| *channel).collect(); - let projection = Projection::Triplanar { scale, sharpness: 8.0, offset: [0.0; 3] }; - Layer::new(id, "Brush material", LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, link: None }), &channels) + let projection = Projection::Triplanar { scale, sharpness: 8.0, offset: [0.0; 3], uv: Default::default(), projector: Default::default() }; + Layer::new( + id, + "Brush material", + &channels, + ) } /// Where [`apply_at`] puts a material. diff --git a/crates/engine/src/pbr_cmds.rs b/crates/engine/src/pbr_cmds.rs index a9635f49..d5b3d4aa 100644 --- a/crates/engine/src/pbr_cmds.rs +++ b/crates/engine/src/pbr_cmds.rs @@ -358,7 +358,8 @@ pub fn common_name(files: &[String]) -> Option { // Parameters and sources (native) -fn options(cmd: &str, p: &Value) -> Result { +/// The import options in `p`; a warp projection is fitted to `mesh` +fn options(cmd: &str, p: &Value, mesh: &texturecraft_geom::Mesh) -> Result { let normal_format = match strp(p, "normalFormat") { None | Some("auto") => None, Some("openGl" | "opengl") => Some(NormalFormat::OpenGl), @@ -377,7 +378,7 @@ fn options(cmd: &str, p: &Value) -> Result { Ok(PbrOptions { name: strp(p, "name").filter(|name| !name.trim().is_empty()).map(str::to_string), normal_format, - projection: crate::layer_cmds::projection_from(p, cmd, None)?, + projection: crate::layer_cmds::projection_from(p, cmd, None, || crate::warp_cmds::fitted_frame(mesh))?, choose, }) } @@ -414,7 +415,7 @@ mod native; #[cfg(not(target_arch = "wasm32"))] fn import(s: &mut Session, p: &Value) -> Result { let cmd = "file.importPbrFolder"; - let mut options = options(cmd, p)?; + let mut options = options(cmd, p, &s.mesh)?; let found = native::find(cmd, p)?; if options.name.is_none() { options.name = found.name.clone(); @@ -425,7 +426,7 @@ fn import(s: &mut Session, p: &Value) -> Result { #[cfg(not(target_arch = "wasm32"))] fn scan(s: &mut Session, p: &Value) -> Result { let cmd = "file.scanPbrFolder"; - let options = options(cmd, p)?; + let options = options(cmd, p, &s.mesh)?; let found = native::find(cmd, p)?; let set = detect_with(&found.files, &options.choose)?; let mut reply = report(&set, options.normal_format); @@ -440,8 +441,8 @@ fn scan(s: &mut Session, p: &Value) -> Result { } #[cfg(target_arch = "wasm32")] -fn import(_: &mut Session, p: &Value) -> Result { - let _ = options("file.importPbrFolder", p)?; +fn import(s: &mut Session, p: &Value) -> Result { + let _ = options("file.importPbrFolder", p, &s.mesh)?; Err(EngineError::Other("file paths are not available in the browser".into())) } diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 3cdc0d5e..d20a81e5 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -42,7 +42,7 @@ pub(crate) const MAX_BYTES: usize = 512 << 20; pub(crate) const EXR_SIGNATURE: &[u8] = &[0x76, 0x2f, 0x31, 0x01]; pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { - Arc::new(ImageRes { width: d.width, height: d.height, rgba: d.rgba, srgb: d.srgb }) + Arc::new(ImageRes::new(d.width, d.height, d.rgba, d.srgb)) } impl Session { @@ -307,7 +307,7 @@ fn add_image_fill(s: &mut Session, p: &Value) -> Result { let raw_name = strp(p, "name").ok_or_else(|| bad("layer.add.image", "`name` is required"))?; let name = resolve_resource_name(s, raw_name)?; let ch = channel_param("layer.add.image", p, "channel")?.unwrap_or(Channel::BaseColor); - let projection = crate::layer_cmds::projection_from(p, "layer.add.image", None)?; + let projection = crate::layer_cmds::projection_from(p, "layer.add.image", None, || crate::warp_cmds::fitted_frame(&s.mesh))?; let ts = s.ts(); let label = std::path::Path::new(&name).file_stem().and_then(|n| n.to_str()).unwrap_or("Image").to_string(); let layer_name = s.doc.project.next_layer_name(ts, &label); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index b493a8b6..8a036f72 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -496,6 +496,10 @@ impl Session { let source = Arc::new(mesh); let mesh = tiled_mesh(&source, &doc.project); + + // Depth maps built for the mesh this one replaces must not be taken for its own + texturecraft_compose::projector_depth::ProjectorDepth::forget_all(); + let bvh = Bvh::new(&mesh); let mut camera = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() }; let (bounds_min, bounds_max) = mesh.bounds(); diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index 0529b0b8..8c7a2791 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -93,7 +93,8 @@ pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, pub(crate) fn pattern(kind: ProceduralKind, scale: f32, seed: u32, contrast: f32) -> EffectKind { EffectKind::Fill { source: Source::Procedural { pattern: Procedural { scale, seed, contrast, ..Procedural::new(kind) }, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, - projection: Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] }, + projection: Projection::triplanar(), + sampling: Default::default(), } } diff --git a/crates/engine/src/thumbs.rs b/crates/engine/src/thumbs.rs index 811a742f..bd6bdd13 100644 --- a/crates/engine/src/thumbs.rs +++ b/crates/engine/src/thumbs.rs @@ -203,6 +203,10 @@ pub struct ThumbService { queue: VecDeque, in_flight: HashSet<(u64, ThumbTarget)>, wanted: HashSet, + /// Asked for after this frame's poll (a panel drawn after the Layers panel): wanted again next frame + late: HashSet, + /// Whether this frame's poll has run + polled: bool, gbufs: GbufCache, #[cfg(not(target_arch = "wasm32"))] worker: Option, @@ -227,6 +231,8 @@ impl Default for ThumbService { queue: VecDeque::new(), in_flight: HashSet::new(), wanted: HashSet::new(), + late: HashSet::new(), + polled: false, gbufs: GbufCache::default(), #[cfg(not(target_arch = "wasm32"))] worker: None, @@ -243,9 +249,10 @@ impl ThumbService { ThumbService::default() } - /// Start of a frame: forget what the last frame asked for and notice document changes. + /// Start of a frame: forget what the last frame asked for (but what it asked for after its poll) and notice document changes pub fn begin_frame(&mut self, session: &Session, now: f64) { - self.wanted.clear(); + self.wanted = std::mem::take(&mut self.late); + self.polled = false; let texture_set = session.ts(); if self.seen == Some(session.revision) && self.snapshot.as_ref().is_some_and(|snapshot| snapshot.ts == texture_set && snapshot.mesh_id == session.mesh_id) @@ -290,6 +297,9 @@ impl ThumbService { /// picture is missing or out of date. pub fn get(&mut self, session: &Session, target: ThumbTarget) -> ThumbView { self.wanted.insert(target); + if self.polled { + self.late.insert(target); + } self.tick = self.tick.wrapping_add(1); let fresh = self.cache.get(&target).is_some_and(|entry| entry.generation == self.generation); let checked = self.checked(session); @@ -316,6 +326,7 @@ impl ThumbService { /// End of a frame: collect results, discard unrequested rows, and dispatch new work. /// Returns whether another frame is needed, including to display newly collected pictures. pub fn poll(&mut self, session: &Session) -> bool { + self.polled = true; let changed = self.collect(); self.queue.retain(|target| self.wanted.contains(target)); self.dispatch(); @@ -517,6 +528,20 @@ mod tests { assert!(!service.poll(&session), "an idle cache must stop repainting"); } + #[test] + fn a_picture_asked_for_after_the_poll_renders_at_the_next_one() { + let session = test_session().unwrap(); + let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor }; + let (mut service, jobs, _results) = held_worker(); + service.begin_frame(&session, 0.0); + service.poll(&session); + service.get(&session, target); + + service.begin_frame(&session, 0.1); + service.poll(&session); + assert_eq!(jobs.try_recv().map(|job| job.target).ok(), Some(target), "the late request is dispatched, not dropped"); + } + #[test] fn a_stopped_worker_retries_visible_targets_inline() { let session = test_session().unwrap(); diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index e8161c8e..fc85fd59 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -10,6 +10,9 @@ use crate::frame_target::FrameTarget; use crate::session::ViewMode; use crate::{Result, Session, cmd}; +/// The farthest depth-of-field focus distance, in world units +const MAX_FOCUS_DISTANCE: f32 = 1e6; + pub fn specs() -> Vec { vec![ cmd!( @@ -68,7 +71,7 @@ pub fn specs() -> Vec { "Display settings", [], None, - "{environment?: |resource:, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, shadowMode? (intensive|average|lightweight: the shadow map resolution), shadowOpacity? (0..1: how dark the shadows are), alignment? (world|camera: what the environment turns with), soloUnlit? (single-channel views flat; off: lit), aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, displacement? (the viewport moves the surface by the height channel), scatterColor?: [r,g,b] linear or \"#rrggbb\" sRGB, scatterRadius? (0..1 of the mesh radius), ior? (1..3, transmission), dof?: {enabled?, focusDistance? (view depth, world units; 0 = the orbit target), aperture? (lens radius, 0..1 of the mesh radius)}}", + "{environment?: |resource:, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, shadowMode? (intensive|average|lightweight: the shadow map resolution), shadowOpacity? (0..1: how dark the shadows are), alignment? (world|camera: what the environment turns with), soloUnlit? (single-channel views flat; off: lit), aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, displacement? (the viewport moves the surface by the height channel), scatterColor?: [r,g,b] linear or \"#rrggbb\" sRGB, scatterRadius? (0..1 of the mesh radius), ior? (1..3, transmission), dof?: {enabled?, focusDistance? (view depth, world units; 0 = the orbit target), aperture? (lens radius, 0..1 of the mesh radius)}, projectionGizmos? (the selected fill's projection gizmos show in the 3D view)}", always, display ), @@ -270,10 +273,10 @@ fn orbit(s: &mut Session, p: &Value) -> Result { } fn display(s: &mut Session, p: &Value) -> Result { - let tm = match strp(p, "toneMapping") { + let tone_mapping = match strp(p, "toneMapping") { Some("linear") => Some(ToneMapping::Linear), Some("aces") | Some("acesFilmic") => Some(ToneMapping::AcesFilmic), - Some(o) => return Err(bad("display.set", format!("unknown tone mapping `{o}`"))), + Some(other) => return Err(bad("display.set", format!("unknown tone mapping `{other}`"))), None => None, }; let shadow_mode = match strp(p, "shadowMode") { @@ -284,77 +287,80 @@ fn display(s: &mut Session, p: &Value) -> Result { Some(id) => Some(EnvAlignment::parse(id).ok_or_else(|| bad("display.set", format!("unknown environment alignment `{id}` (world or camera)")))?), None => None, }; - let env = strp(p, "environment").map(str::to_string); - if let Some(name) = env.as_deref().and_then(|e| e.strip_prefix(texturecraft_core::project::ENV_RESOURCE_PREFIX)) + let environment = strp(p, "environment").map(str::to_string); + if let Some(name) = environment.as_deref().and_then(|picked| picked.strip_prefix(texturecraft_core::project::ENV_RESOURCE_PREFIX)) && !s.images.contains_key(name) { return Err(bad("display.set", format!("no image resource `{name}` (import it with resource.import)"))); } - if let Some(e) = env.as_deref().filter(|e| !e.starts_with(texturecraft_core::project::ENV_RESOURCE_PREFIX) && !ENVIRONMENTS.contains(e)) { - return Err(bad("display.set", format!("unknown environment `{e}`: one of {}, or resource:", ENVIRONMENTS.join(", ")))); + if let Some(unknown) = + environment.as_deref().filter(|picked| !picked.starts_with(texturecraft_core::project::ENV_RESOURCE_PREFIX) && !ENVIRONMENTS.contains(picked)) + { + return Err(bad("display.set", format!("unknown environment `{unknown}`: one of {}, or resource:", ENVIRONMENTS.join(", ")))); } let scatter_color = color_param("display.set", p, "scatterColor")?; - let d = &mut s.doc.project.display; - if let Some(e) = env { - d.environment = e; + let settings = &mut s.doc.project.display; + if let Some(picked) = environment { + settings.environment = picked; } - for (k, slot, lo, hi) in [ - ("exposure", &mut d.env_exposure, -10.0, 10.0), - ("blur", &mut d.env_blur, 0.0, 1.0), - ("rotation", &mut d.env_rotation, -360.0, 360.0), - ("opacity", &mut d.env_opacity, 0.0, 1.0), - ("fov", &mut d.fov, 5.0, 150.0), - ("aoIntensity", &mut d.ao_intensity, 0.0, 1.0), - ("bloom", &mut d.bloom, 0.0, 1.0), - ("vignette", &mut d.vignette, 0.0, 1.0), - ("sharpen", &mut d.sharpen, 0.0, 1.0), - ("grain", &mut d.grain, 0.0, 1.0), - ("scatterRadius", &mut d.scatter_radius, 0.0, 1.0), - ("ior", &mut d.ior, 1.0, 3.0), - ("shadowOpacity", &mut d.shadow_opacity, 0.0, 1.0), + for (key, slot, lowest, highest) in [ + ("exposure", &mut settings.env_exposure, -10.0, 10.0), + ("blur", &mut settings.env_blur, 0.0, 1.0), + ("rotation", &mut settings.env_rotation, -360.0, 360.0), + ("opacity", &mut settings.env_opacity, 0.0, 1.0), + ("fov", &mut settings.fov, 5.0, 150.0), + ("aoIntensity", &mut settings.ao_intensity, 0.0, 1.0), + ("bloom", &mut settings.bloom, 0.0, 1.0), + ("vignette", &mut settings.vignette, 0.0, 1.0), + ("sharpen", &mut settings.sharpen, 0.0, 1.0), + ("grain", &mut settings.grain, 0.0, 1.0), + ("scatterRadius", &mut settings.scatter_radius, 0.0, 1.0), + ("ior", &mut settings.ior, 1.0, 3.0), + ("shadowOpacity", &mut settings.shadow_opacity, 0.0, 1.0), ] { - if let Some(v) = f32p(p, k) { - *slot = v.clamp(lo, hi); + if let Some(value) = f32p(p, key) { + *slot = value.clamp(lowest, highest); } } - if let Some(t) = tm { - d.tone_mapping = t; + if let Some(picked) = tone_mapping { + settings.tone_mapping = picked; } - if let Some(c) = scatter_color { - d.scatter_color = c.map(|v| v.clamp(0.0, 1.0)); + if let Some(color) = scatter_color { + settings.scatter_color = color.map(|component| component.clamp(0.0, 1.0)); } - if let Some(b) = boolp(p, "shadows") { - d.shadows = b; + if let Some(on) = boolp(p, "shadows") { + settings.shadows = on; } if let Some(mode) = shadow_mode { - d.shadow_mode = mode; + settings.shadow_mode = mode; } if let Some(alignment) = alignment { - d.env_alignment = alignment; + settings.env_alignment = alignment; } if let Some(dof) = p.get("dof") { - if let Some(b) = boolp(dof, "enabled") { - d.dof.enabled = b; + if let Some(on) = boolp(dof, "enabled") { + settings.dof.enabled = on; } - if let Some(v) = f32p(dof, "focusDistance") { - d.dof.focus_distance = v.clamp(0.0, 1e6); + if let Some(distance) = f32p(dof, "focusDistance") { + settings.dof.focus_distance = distance.clamp(0.0, MAX_FOCUS_DISTANCE); } - if let Some(v) = f32p(dof, "aperture") { - d.dof.aperture = v.clamp(0.0, 1.0); + if let Some(aperture) = f32p(dof, "aperture") { + settings.dof.aperture = aperture.clamp(0.0, 1.0); } } - for (k, slot) in [ - ("postEffects", &mut d.post_effects), - ("taa", &mut d.taa), - ("specGloss", &mut d.spec_gloss), - ("parallax", &mut d.parallax), - ("displacement", &mut d.displacement), - ("soloUnlit", &mut d.solo_unlit), + for (key, slot) in [ + ("postEffects", &mut settings.post_effects), + ("taa", &mut settings.taa), + ("specGloss", &mut settings.spec_gloss), + ("parallax", &mut settings.parallax), + ("displacement", &mut settings.displacement), + ("soloUnlit", &mut settings.solo_unlit), + ("projectionGizmos", &mut settings.projection_gizmos), ] { - if let Some(b) = boolp(p, k) { - *slot = b; + if let Some(on) = boolp(p, key) { + *slot = on; } } @@ -519,4 +525,21 @@ mod tests { execute(&mut s, "file.removeUnused", &Value::Null).unwrap(); assert!(s.doc.resources.contains_key(&name), "the environment's image counts as used"); } + + #[test] + fn the_projection_gizmos_hide_per_project_and_old_projects_show_them() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + let shown = serde_json::to_value(&s.doc.project.display).unwrap(); + assert!(s.doc.project.display.projection_gizmos && shown.get("projection_gizmos").is_none(), "shown by default and saved as before: {shown}"); + + let hidden = execute(&mut s, "display.set", &json!({"projectionGizmos": false})).unwrap(); + assert!(!s.doc.project.display.projection_gizmos); + assert_eq!(hidden["projection_gizmos"], json!(false), "hidden is saved with the project"); + assert!(s.history_labels().is_empty(), "a view flag is no undo step"); + + let reopened: texturecraft_core::project::DisplaySettings = serde_json::from_value(hidden).unwrap(); + assert!(!reopened.projection_gizmos, "a saved project opens with its gizmos hidden"); + let old: texturecraft_core::project::DisplaySettings = serde_json::from_value(shown).unwrap(); + assert!(old.projection_gizmos, "a project saved before the flag shows them"); + } } diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index d88166e5..11a5b7f0 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -13,6 +13,9 @@ mod content_effects; mod export_colour_space; mod export_file_types; mod export_maps; +mod fill_patterns; +mod fill_projections; +mod fill_sampling; mod filter_swap; mod filters; mod frame_selection; @@ -36,6 +39,7 @@ mod polygon_fill; mod project_recovery; mod sample; mod solo; +mod symmetry; mod thumbs; mod tile_generator; mod tool_availability; @@ -44,5 +48,3 @@ mod tools; mod udim; mod user_smart_mask; mod uv_strokes; - -mod symmetry; diff --git a/crates/engine/tests/it/painter_gaps.rs b/crates/engine/tests/it/painter_gaps.rs index 37b8e601..4ad6c736 100644 --- a/crates/engine/tests/it/painter_gaps.rs +++ b/crates/engine/tests/it/painter_gaps.rs @@ -3,7 +3,7 @@ //! maps from images and fill projection transforms, through engine commands. use serde_json::{Value, json}; -use texturecraft_engine::core::{Channel, Decal, EffectKind, Filter, LayerId, LayerKind, Projection, Source}; +use texturecraft_engine::core::{Channel, Decal, EffectKind, Filter, LayerId, LayerKind, Projection, Projector, Source}; use texturecraft_engine::geom::NO_TRI; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; @@ -80,33 +80,44 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() { let fid = f["id"].as_str().unwrap(); let eid = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": fid, "target": "content"})).unwrap(), "effect"); let (owner, e) = s.doc.project.effect(eid).unwrap(); + assert_eq!(owner, layer); assert_eq!(e.name, f["label"].as_str().unwrap(), "named after the shelf entry"); assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|x| x.id == eid)); + execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap(); } - // A gradient map recolors the content; effect.set edits it and inspect shows it. + // A gradient map recolors the content; effect.set edits it and inspect shows it let gm = id(execute(&mut s, "effect.add.filter", &json!({"filter": "gradientMap", "target": "content", "colors": [[0, 0, 1], [0, 0, 1]]})).unwrap(), "effect"); let blue = at(&mut s, Channel::BaseColor, 200.0, 200.0); assert!(blue[2] > 0.95 && blue[0] < 0.05, "{before:?} -> {blue:?}"); + execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": ["#00ff00"]})).unwrap(); + assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0)[1] > 0.95); assert!(execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": []})).is_err()); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains("GradientMap"), "inspect shows filter parameters"); + execute(&mut s, "effect.remove", &json!({"effect": gm.0})).unwrap(); - // Posterize on the mask; its steps are clamped. + // Posterize on the mask; its steps are clamped let post = id(execute(&mut s, "effect.add.filter", &json!({"filter": "posterize", "levels": 3})).unwrap(), "effect"); execute(&mut s, "effect.set", &json!({"effect": post.0, "levels": 500})).unwrap(); + assert!(s.doc.project.layer(layer).unwrap().mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == post))); assert!(matches!(s.doc.project.effect(post).unwrap().1.kind, EffectKind::Filter(Filter::Posterize { levels }) if levels == 64.0)); - // Material finishes fill the content's roughness and height. + + // Material finishes fill the content's roughness and height let fin = id(execute(&mut s, "effect.add.filter", &json!({"filter": "MatFinish Hammered"})).unwrap(), "effect"); + assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|e| e.id == fin)); assert!(matches!(&s.doc.project.effect(fin).unwrap().1.kind, EffectKind::Material(f) if f.sources.contains_key(&Channel::Height))); assert!(execute(&mut s, "effect.add.filter", &json!({"filter": "nope"})).is_err()); - // A directional blur, slope blur and warp composite without trouble on a sphere. + + // A directional blur, slope blur and warp composite without trouble on a sphere for (fid, extra) in [ ("blurDirectional", json!({"radius": 40, "angle": 45})), ("slopeBlur", json!({"radius": 30})), @@ -182,7 +193,7 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() { let layer = id(r.clone(), "layer"); assert!((r["decal"]["size"][1].as_f64().unwrap() - 0.5).abs() < 1e-6); let LayerKind::Fill(f) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; - assert!(matches!(f.projection, Projection::Decal(_))); + assert!(matches!(f.projection, Projection::Planar { placed: Some(_), .. })); assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the decal shows where it was placed"); assert!(!red(at(&mut s, Channel::BaseColor, 120.0, 200.0)), "and only there"); @@ -198,8 +209,7 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() { assert_eq!(r["decal"]["offset"], json!([0.0, 0.0]), "re-placing resets the offset"); assert!(red(at(&mut s, Channel::BaseColor, 170.0, 180.0))); let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); - assert!(inspect.contains("Decal projection") && inspect.contains("\"rotation\":45"), "inspect shows the decal"); - + assert!(inspect.contains("Planar projection") && inspect.contains("\"decal\"") && inspect.contains("\"rotation\":45"), "inspect shows the decal"); // Not a decal; one undo step per edit let plain = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer"); assert!(execute(&mut s, "layer.decal.set", &json!({"layer": plain.0, "size": 1})).is_err()); @@ -210,7 +220,10 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() { /// The decal of mask fill effect `effect` fn effect_decal(s: &Session, effect: LayerId) -> Decal { - let EffectKind::Fill { projection: Projection::Decal(decal), .. } = &s.doc.project.effect(effect).unwrap().1.kind else { panic!("a decal fill effect") }; + let EffectKind::Fill { projection: Projection::Planar { placed: Some(decal), .. }, .. } = &s.doc.project.effect(effect).unwrap().1.kind else { + panic!("a decal fill effect") + }; + *decal } @@ -244,7 +257,7 @@ fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() { // The layer decal is untouched by all of it let LayerKind::Fill(f) = &s.doc.project.layer(layer_decal).unwrap().kind else { panic!("a fill layer") }; - assert!(matches!(&f.projection, Projection::Decal(d) if d.size[1] == 0.5 && d.rotation == 0.0)); + assert!(matches!(&f.projection, Projection::Planar { placed: Some(d), .. } if d.size[1] == 0.5 && d.rotation == 0.0)); // Errors: unknown effect, an effect that is not a decal, an effect of another layer assert!(execute(&mut s, "layer.decal.set", &json!({"effect": 999_999, "size": 1})).is_err()); @@ -272,7 +285,7 @@ fn decals_keep_the_image_aspect_and_flip_their_image() { assert!(r["decal"].get("flip").is_none(), "nothing flipped saves nothing extra"); let size = |s: &mut Session| { let LayerKind::Fill(f) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; - let Projection::Decal(d) = &f.projection else { panic!("a decal") }; + let Projection::Planar { placed: Some(d), .. } = &f.projection else { panic!("a decal") }; (d.size, d.flip) }; @@ -501,7 +514,9 @@ fn a_decal_image_fills_a_chosen_channel_or_a_mask() { let added = execute(&mut s, "layer.add.decal", &place("mask")).unwrap(); let masked = id(added.clone(), "layer"); let mask = s.doc.project.layer(masked).unwrap().mask.as_ref().unwrap(); - assert!(matches!(mask.effects.as_slice(), [effect] if matches!(effect.kind, EffectKind::Fill { projection: Projection::Decal(_), .. }))); + assert!( + matches!(mask.effects.as_slice(), [effect] if matches!(effect.kind, EffectKind::Fill { projection: Projection::Planar { placed: Some(_), .. }, .. })) + ); assert_eq!(added["maskEffect"], json!(mask.effects[0].id.0)); execute(&mut s, "layer.fill.set", &json!({"layer": masked.0, "channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the mask shows the layer under the decal"); @@ -676,9 +691,17 @@ fn fill_projection_edits_keep_what_they_do_not_change() { assert_eq!(proj(&s), Projection::Uv { scale: [2.0, 3.0], rotation: 30.0, offset: [0.25, 0.5] }, "the same kind keeps its fields; a bad offset is ignored"); set(&mut s, json!({"projection": "triplanar", "offset": [1, 2, 3]})).unwrap(); set(&mut s, json!({"sharpness": 100})).unwrap(); - assert_eq!(proj(&s), Projection::Triplanar { scale: 1.0, sharpness: 64.0, offset: [1.0, 2.0, 3.0] }, "a new kind starts from its defaults"); + assert_eq!( + proj(&s), + Projection::Triplanar { scale: 1.0, sharpness: 64.0, offset: [1.0, 2.0, 3.0], uv: Default::default(), projector: Default::default() }, + "a new kind starts from its defaults" + ); set(&mut s, json!({"projection": "planar", "axis": 7, "offset": [1e9, 0, 0]})).unwrap(); - assert_eq!(proj(&s), Projection::Planar { scale: 1.0, axis: 2, offset: [1000.0, 0.0, 0.0] }, "hostile values are clamped"); + assert_eq!( + proj(&s), + Projection::Planar { scale: 1.0, axis: 2, offset: [1000.0, 0.0, 0.0], uv: Default::default(), projector: Projector::depth_culled(), placed: None }, + "hostile values are clamped" + ); assert!(set(&mut s, json!({"projection": "hexagonal"})).is_err()); // The offset moves the pattern: a UV offset changes what the composite shows. set(&mut s, json!({"projection": "uv", "scale": 1})).unwrap(); @@ -747,7 +770,7 @@ fn red_on_minus_x(s: &mut Session, inside: impl Fn(f32, f32) -> bool) -> usize { fn decal_of(s: &Session, layer: LayerId) -> texturecraft_engine::core::Decal { let LayerKind::Fill(fill) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; - let Projection::Decal(decal) = fill.projection else { panic!("a decal") }; + let Projection::Planar { placed: Some(decal), .. } = fill.projection else { panic!("a decal") }; decal } @@ -906,7 +929,7 @@ fn a_saved_decal_with_an_out_of_range_axis_is_repaired_on_load_and_can_be_edited let image = session.import_resource_bytes("decal.png", png(4, 4, |_, _| [255; 4])).unwrap(); let layer = id(execute(&mut session, "layer.add.decal", &json!({"image": image, "symmetry": "x"})).unwrap(), "layer"); let LayerKind::Fill(fill) = &mut session.doc.project.layer_mut(layer).unwrap().kind else { panic!("expected fill") }; - let Projection::Decal(decal) = &mut fill.projection else { panic!("expected decal") }; + let Projection::Planar { placed: Some(decal), .. } = &mut fill.projection else { panic!("expected decal") }; decal.symmetry.as_mut().unwrap().axis = u8::MAX; let bytes = session.to_project_bytes().unwrap(); diff --git a/crates/engine/tests/it/tile_generator.rs b/crates/engine/tests/it/tile_generator.rs index 3a027e96..445facdf 100644 --- a/crates/engine/tests/it/tile_generator.rs +++ b/crates/engine/tests/it/tile_generator.rs @@ -177,7 +177,7 @@ fn a_pattern_scale_edit_leaves_the_mask_fills_projection_alone() { execute(&mut session, "effect.set", &json!({"effect": effect, "scale": 3.0})).unwrap(); let Some((_, edited)) = session.doc.project.effect(LayerId(effect)) else { panic!("the mask fill is gone") }; - let EffectKind::Fill { source: Source::Procedural { pattern, .. }, projection } = &edited.kind else { panic!("the fill reads a pattern") }; + let EffectKind::Fill { source: Source::Procedural { pattern, .. }, projection, .. } = &edited.kind else { panic!("the fill reads a pattern") }; assert_eq!(pattern.scale, 3.0); assert_eq!(*projection, Projection::default(), "the projection keeps its scale"); } @@ -205,7 +205,7 @@ fn a_new_procedural_mask_uses_scalar_scale_only_for_the_pattern() { let effect = LayerId(added["effect"].as_u64().unwrap()); let (_, effect) = session.doc.project.effect(effect).unwrap(); - let EffectKind::Fill { source: Source::Procedural { pattern, .. }, projection } = &effect.kind else { panic!("expected a procedural mask fill") }; + let EffectKind::Fill { source: Source::Procedural { pattern, .. }, projection, .. } = &effect.kind else { panic!("expected a procedural mask fill") }; assert_eq!(pattern.scale, 3.0); assert_eq!(*projection, Projection::default(), "UV placement must not multiply pattern frequency a second time"); } diff --git a/crates/engine/tests/it/user_smart_mask.rs b/crates/engine/tests/it/user_smart_mask.rs index 04fce3a6..72916dcb 100644 --- a/crates/engine/tests/it/user_smart_mask.rs +++ b/crates/engine/tests/it/user_smart_mask.rs @@ -33,7 +33,7 @@ fn multi_effect_mask(s: &mut Session) -> (LayerId, String) { let mask = s.doc.project.layer_mut(id).unwrap().mask.as_mut().unwrap(); for effect in &mut mask.effects { if effect.id.0 == fill { - effect.kind = EffectKind::Fill { source: Source::image(&name), projection: Default::default() }; + effect.kind = EffectKind::Fill { source: Source::image(&name), projection: Default::default(), sampling: Default::default() }; } } let size = s.doc.project.texture_set(0).unwrap().resolution; @@ -169,6 +169,7 @@ fn effects_reading_an_anchor_of_the_mask_follow_it() { effect.kind = EffectKind::Fill { source: Source::Anchor { anchor: LayerId(anchor), channel: texturecraft_engine::core::Channel::Height, ramp: Vec::new() }, projection: Default::default(), + sampling: Default::default(), }; } } @@ -197,7 +198,7 @@ fn an_external_anchor_cannot_be_saved_or_rebound_in_another_project() { for (project, id) in [(&mut file.project, holder), (&mut s.doc.project, source)] { let mask = project.layer_mut(id).unwrap().mask.as_mut().unwrap(); let fill = mask.effects.iter_mut().find(|effect| matches!(effect.kind, EffectKind::Fill { .. })).unwrap(); - fill.kind = EffectKind::Fill { source: source_ref.clone(), projection: Default::default() }; + fill.kind = EffectKind::Fill { source: source_ref.clone(), projection: Default::default(), sampling: Default::default() }; } assert!(s.smart_mask_bytes(source, "Preset").unwrap_err().to_string().contains("outside this mask")); diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 1d01fe6c..bf68e50b 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -369,6 +369,18 @@ impl Mesh { .collect() } + /// Mesh units one UV unit covers on material `m`'s triangles: sqrt(surface area / UV area), None without UV area + pub fn uv_density(&self, m: usize) -> Option { + let (mut surface, mut uv_area) = (0.0_f32, 0.0_f32); + for [a, b, c] in self.triangles_of(m).filter_map(|t| self.tri(t)) { + let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; + let (Some(ua), Some(ub), Some(uc)) = (self.uvs.get(a), self.uvs.get(b), self.uvs.get(c)) else { continue }; + surface += (*pb - *pa).cross(*pc - *pa).length() * 0.5; + uv_area += (*ub - *ua).perp_dot(*uc - *ua).abs() * 0.5; + } + (uv_area > f32::EPSILON && surface.is_finite()).then(|| (surface / uv_area).sqrt()) + } + /// Remap the UVs of material `m`'s triangles with `f`. Vertices they share with other /// materials are duplicated first, so the other triangles keep their UVs. pub fn map_material_uvs(&mut self, m: usize, f: impl Fn(Vec2) -> Vec2) { @@ -595,6 +607,14 @@ mod tests { assert_eq!(m.bounds_of_material(1), None); } + #[test] + fn uv_density_is_mesh_units_per_uv_unit() { + assert_eq!(quad().uv_density(0), Some(1.0)); + let plane = crate::primitives::plane(3.0, 4).uv_density(0).unwrap(); + assert!((plane - 3.0).abs() < 1e-4, "{plane}"); + assert_eq!(quad().uv_density(1), None, "no triangles of that material"); + } + #[test] fn wire_edges_leave_out_polygon_diagonals() { let mut m = quad(); diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index dd55d182..2cb62488 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -181,8 +181,8 @@ fn full_turn() -> f32 { FULL_TURN_DEGREES } -/// [`Symmetry::angle_span`] of a full turn -pub const FULL_TURN_DEGREES: f32 = 360.0; +// A full turn is the angle span every crate measures turns against +pub use texturecraft_core::FULL_TURN_DEGREES; /// Most radial copies a brush paints pub const MAX_RADIAL_COPIES: u8 = 32; @@ -445,7 +445,7 @@ mod tests { #[test] fn image_alpha_follows_the_image_and_is_zero_outside() { // Left half white, right half black (2×1 image, sampled at texel centers) - let img = ImageRes { width: 2, height: 1, rgba: vec![[1.0; 4], [0.0, 0.0, 0.0, 1.0]], srgb: true }; + let img = ImageRes::new(2, 1, vec![[1.0; 4], [0.0, 0.0, 0.0, 1.0]], true); let shape = Shape { alpha: BrushAlpha::Round, image: Some(&img), library: None, params: AlphaParams::default(), level: 0 }; assert!(shape.sample(-0.5, 0.0, 0.5, 0) > 0.99); assert!(shape.sample(0.5, 0.0, 0.5, 0) < 0.01); @@ -483,12 +483,7 @@ mod tests { #[test] fn default_parameters_reproduce_every_alpha_exactly() { - let img = ImageRes { - width: 3, - height: 2, - rgba: vec![[1.0; 4], [0.3, 0.3, 0.3, 1.0], [0.0, 0.0, 0.0, 1.0], [0.6, 0.6, 0.6, 1.0], [0.9; 4], [0.1, 0.1, 0.1, 1.0]], - srgb: true, - }; + let img = ImageRes::new(3, 2, vec![[1.0; 4], [0.3, 0.3, 0.3, 1.0], [0.0, 0.0, 0.0, 1.0], [0.6, 0.6, 0.6, 1.0], [0.9; 4], [0.1, 0.1, 0.1, 1.0]], true); let library = crate::alphas::library().first().map(|alpha| alpha.image()); let kinds = BrushAlpha::ALL.map(|alpha| Shape { alpha, image: None, library: None, params: AlphaParams::default(), level: 0 }); for shape in kinds.into_iter().chain([ @@ -522,7 +517,7 @@ mod tests { #[test] fn sizes_apply_to_image_and_library_alphas_too() { - let img = ImageRes { width: 1, height: 1, rgba: vec![[1.0; 4]], srgb: true }; + let img = ImageRes::new(1, 1, vec![[1.0; 4]], true); let params = AlphaParams { size_x: 0.5, ..AlphaParams::default() }; let image = Shape { alpha: BrushAlpha::Round, image: Some(&img), library: None, params, level: 0 }; assert_eq!((image.sample(0.4, 0.0, 0.5, 0) > 0.99, image.sample(0.6, 0.0, 0.5, 0)), (true, 0.0)); diff --git a/crates/paint/src/pickup.rs b/crates/paint/src/pickup.rs index c70c1f92..6d61b073 100644 --- a/crates/paint/src/pickup.rs +++ b/crates/paint/src/pickup.rs @@ -366,7 +366,12 @@ mod tests { let mut project = Project::new("test", "builtin:plane"); project.texture_sets.push(TextureSet::new("Set", 0, size)); let id = project.alloc_id(); - let fill = Fill { sources: [(Channel::Roughness, Source::Uniform([0.25; 3]))].into(), projection: Default::default(), link: None }; + let fill = Fill { + sources: [(Channel::Roughness, Source::Uniform([0.25; 3]))].into(), + projection: Default::default(), + sampling: Default::default(), + link: None, + }; let mut layer = Layer::new(id, "fill", LayerKind::Fill(fill), &[Channel::Roughness]); layer.mask = Some(Mask::new(MaskBackground::White)); project.insert_layer(0, layer, None, false).unwrap(); diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index e4ddad39..39ab2e2b 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -765,7 +765,7 @@ fn imported_hdr_environment_lights_the_ball() { // A procedural HDR: a hot orange sky over a dim blue ground (values far above 1). let (w, hh) = (256u32, 128u32); let rgba = (0..w * hh).map(|i| if i / w < hh / 2 { [12.0, 4.0, 1.0, 1.0] } else { [0.02, 0.05, 0.2, 1.0] }).collect(); - let sky = ImageRes { width: w, height: hh, rgba, srgb: false }; + let sky = ImageRes::new(w, hh, rgba, false); h.renderer.set_environment(&h.device, &h.queue, "resource:sky.hdr", Some(&sky)); let lit = render(&mut h, &frame, "env_hdr_resource"); assert_ne!(lit.px, base.px, "the imported environment changes the lighting"); @@ -1081,7 +1081,7 @@ fn spot_environment(dir: texturecraft_geom::glam::Vec3) -> ImageRes { if d.dot(dir) > 0.5 { [6.0, 6.0, 6.0, 1.0] } else { [0.02, 0.02, 0.02, 1.0] } }) .collect(); - ImageRes { width: w, height: hh, rgba, srgb: false } + ImageRes::new(w, hh, rgba, false) } #[test] diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 6256973b..70c4f246 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -18,6 +18,8 @@ use crate::TextureCraftApp; use crate::filter_slot::SLOT_HEIGHT; use crate::i18n::{n_, tr, trf}; use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_size, layer_row_height}; +use crate::past_end::PastEnd; +use crate::property_sheet::{PropertySheet, SectionScope}; use crate::shelf::{Asset, ShelfDrag}; use crate::state::PropsTab; use crate::theme::{Tokens, caption}; @@ -147,6 +149,12 @@ fn add_mask_menu(app: &mut TextureCraftApp, ui: &mut Ui, row: Option) { } } +/// Gap between the layer toolbar and the layer rows +const LAYER_TOOLBAR_GAP: f32 = 2.0; + +/// Least height of the drop space under the layer rows, so a drop to the bottom always has a target +const BOTTOM_DROP_MIN_HEIGHT: f32 = 24.0; + pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); @@ -204,10 +212,11 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { return; } - ui.add_space(2.0); - let ts = app.session.ts(); - let stack: Vec = app.session.doc.project.texture_sets.get(ts).map(|t| t.stack.iter().rev().copied().collect()).unwrap_or_default(); - let now = ui.input(|i| i.time); + ui.add_space(LAYER_TOOLBAR_GAP); + let set = app.session.ts(); + let stack: Vec = + app.session.doc.project.texture_sets.get(set).map(|texture_set| texture_set.stack.iter().rev().copied().collect()).unwrap_or_default(); + let now = ui.input(|input| input.time); app.layer_panel.begin(&app.session, now); egui::ScrollArea::vertical().id_salt("layers_scroll").auto_shrink([false, false]).show(ui, |ui| { let mut count = 0; @@ -217,27 +226,28 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { // Empty space keeps the selection and drops below the rows let free = ui.available_height(); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), if free.is_finite() { free.max(24.0) } else { 24.0 }), Sense::hover()); - if let Some(dragged) = dnd_release::(&resp) { - let bottom = app.session.doc.project.texture_sets.get(ts).and_then(|t| t.stack.first().copied()); + let drop_height = if free.is_finite() { free.max(BOTTOM_DROP_MIN_HEIGHT) } else { BOTTOM_DROP_MIN_HEIGHT }; + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), drop_height), Sense::hover()); + if let Some(dragged) = dnd_release::(&response) { + let bottom = app.session.doc.project.texture_sets.get(set).and_then(|texture_set| texture_set.stack.first().copied()); if let Some(layers) = selection_with(app, LayerId(*dragged)) { app.run("layer.move", json!({"layers": layers, "index": 0})); - } else if bottom.map(|b| b.0) != Some(*dragged) { + } else if bottom.map(|bottom| bottom.0) != Some(*dragged) { app.run("layer.move", json!({"layer": *dragged, "index": 0})); } } - match dnd_release::(&resp).map(|d| d.asset.clone()) { - Some(Asset::Material(m)) => { - app.run("material.apply", json!({"material": m, "index": 0})); + match dnd_release::(&response).map(|drag| drag.asset.clone()) { + Some(Asset::Material(material)) => { + app.run("material.apply", json!({"material": material, "index": 0})); } Some(Asset::Library(path)) => { app.run("material.load", json!({"path": path, "index": 0})); } _ => {} } - let material = resp.dnd_hover_payload::().is_some_and(|d| d.asset.is_material()); - if resp.dnd_hover_payload::().is_some() || material { - ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, tokens.accent)); + let material = response.dnd_hover_payload::().is_some_and(|drag| drag.asset.is_material()); + if response.dnd_hover_payload::().is_some() || material { + ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(DROP_STROKE, tokens.accent)); } }); select_all_layers(app, ui); @@ -455,6 +465,9 @@ const GROUP_HEADER_LABEL_FONT_SIZE: f32 = 10.5; const ALTERNATE_LAYER_SHADE: f32 = 0.45; /// Maximum layer-tree nesting shown by the dock const MAX_LAYER_TREE_DEPTH: usize = 12; + +/// Width of the drop indicators: the line above a row and the outline round it or its mask +const DROP_STROKE: f32 = 2.0; /// Checkerboard cells along each thumbnail edge const THUMB_CHECKER_CELLS: usize = 4; /// Keep the group label and count readable when the panel is narrow @@ -671,18 +684,20 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let set = project.locate(source).and_then(|(set, _, _)| project.texture_sets.get(set)).map(|set| set.name.as_str()).unwrap_or("?"); project.layers.get(&source).map_or_else(|| tr("missing source").to_string(), |source_layer| format!("{} · {set}", source_layer.name)) }); - let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.clone()); + // Only what the row draws of the mask (whether it is on, its background, its effect count): no clone per row per frame + let mask = + project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.as_ref()).map(|mask| (mask.enabled, mask.background, mask.effects.len())); let blend = project.content_layer(layer.id).and_then(|content| content.blend(channel)); // Mask thumbnail, selectable on its own; or the slot that adds one let mask_rect; - if let Some(mask) = &mask { + if let Some((mask_enabled, mask_background, mask_effect_count)) = mask { let mask_target = selected && !targets_content(app); mask_rect = Rect::from_min_size(pos2(x, rect.center().y - thumbnail_size * 0.5), vec2(thumbnail_size, thumbnail_size)); - if !thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !mask.enabled) { - let white = mask.background == texturecraft_engine::core::MaskBackground::White; + if !thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !mask_enabled) { + let white = mask_background == texturecraft_engine::core::MaskBackground::White; painter.rect_filled(mask_rect, THUMBNAIL_ROUNDING, Color32::from_gray(if white { WHITE_MASK_GRAY } else { BLACK_MASK_GRAY })); - if !mask.effects.is_empty() { + if mask_effect_count > 0 { painter.text( mask_rect.center(), egui::Align2::CENTER_CENTER, @@ -693,7 +708,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } } painter.rect_stroke(mask_rect, THUMBNAIL_ROUNDING, target_stroke(&tokens, mask_target), egui::StrokeKind::Outside); - if !mask.enabled { + if !mask_enabled { painter.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.danger)); } let mask_response = ui @@ -769,7 +784,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize LayerKind::Group { .. } => "Folder", LayerKind::Instance { .. } => "Instance", }); - let effects = layer.content_effects.len() + mask.as_ref().map_or(0, |mask| mask.effects.len()); + let effects = layer.content_effects.len() + mask.map_or(0, |(_, _, count)| count); let subtitle = match (source, effects) { (Some(source), _) => format!("{kind} · {} {source}", ic::LINK_SIMPLE), (None, 0) => kind.to_string(), @@ -1378,27 +1393,33 @@ fn blending_options_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) } }); } +/// Least width of a layer row's right-click menu, wide enough for its longest item and shortcut +const CONTEXT_MENU_MIN_WIDTH: f32 = 230.0; + +/// Side and corner radius of a colour tag square in the layer row's right-click menu +const TAG_SWATCH_SIZE: f32 = 16.0; +const TAG_SWATCH_RADIUS: f32 = 2.0; fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { - let tk = Tokens::get(ui.ctx()); - ui.set_min_width(230.0); - let lid = layer.id.0; + let tokens = Tokens::get(ui.ctx()); + ui.set_min_width(CONTEXT_MENU_MIN_WIDTH); + let layer_id = layer.id.0; let keymap = app.ui.keymap.clone(); // On one of several selected layers, remove, duplicate and group act on all of them let several = selection_with(app, layer.id); - let run = |app: &mut TextureCraftApp, ui: &mut Ui, label: &str, id: &str, p: Value, enabled: bool| { - let mut b = egui::Button::new(label); - if let Some(sc) = crate::keymap::shortcut_of(&keymap, id) { - b = b.shortcut_text(sc); + let run = |app: &mut TextureCraftApp, ui: &mut Ui, label: &str, id: &str, params: Value, enabled: bool| { + let mut button = egui::Button::new(label); + if let Some(shortcut) = crate::keymap::shortcut_of(&keymap, id) { + button = button.shortcut_text(shortcut); } - if ui.add_enabled(enabled, b).clicked() { + if ui.add_enabled(enabled, button).clicked() { let batch = matches!(id, "layer.remove" | "layer.duplicate" | "layer.group"); match several.as_ref().filter(|_| batch) { Some(layers) => app.run(id, json!({"layers": layers})), None => { - app.run("layer.select", json!({"layer": lid})); - app.run(id, p) + app.run("layer.select", json!({"layer": layer_id})); + app.run(id, params) } }; ui.close(); @@ -1407,19 +1428,19 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { // An instance edits its source mask until it gets its own let project = &app.session.doc.project; - let has_mask = project.layers.get(&project.mask_owner(layer.id)).is_some_and(|l| l.mask.is_some()); + let has_mask = project.layers.get(&project.mask_owner(layer.id)).is_some_and(|owner| owner.mask.is_some()); // A switched-off mask has no values to export - let mask_on = project.layers.get(&project.mask_owner(layer.id)).is_some_and(|l| l.mask.as_ref().is_some_and(|m| m.enabled)); - run(app, ui, tr("Add white mask"), "mask.add.white", json!({"layer": lid}), layer.mask.is_none()); - run(app, ui, tr("Add black mask"), "mask.add.black", json!({"layer": lid}), layer.mask.is_none()); - run(app, ui, tr("Add mask with color selection"), "mask.add.colorSelection", json!({"layer": lid}), true); + let mask_on = project.layers.get(&project.mask_owner(layer.id)).is_some_and(|owner| owner.mask.as_ref().is_some_and(|mask| mask.enabled)); + run(app, ui, tr("Add white mask"), "mask.add.white", json!({"layer": layer_id}), layer.mask.is_none()); + run(app, ui, tr("Add black mask"), "mask.add.black", json!({"layer": layer_id}), layer.mask.is_none()); + run(app, ui, tr("Add mask with color selection"), "mask.add.colorSelection", json!({"layer": layer_id}), true); ui.separator(); - run(app, ui, tr("Toggle mask"), "mask.toggle", json!({"layer": lid}), has_mask); - run(app, ui, tr("Invert mask background"), "mask.invertBackground", json!({"layer": lid}), has_mask); - run(app, ui, tr("Invert mask"), "mask.invert", json!({"layer": lid}), has_mask); - run(app, ui, tr("Clear mask"), "mask.clear", json!({"layer": lid}), has_mask); - run(app, ui, tr("Remove mask"), "mask.remove", json!({"layer": lid}), has_mask); + run(app, ui, tr("Toggle mask"), "mask.toggle", json!({"layer": layer_id}), has_mask); + run(app, ui, tr("Invert mask background"), "mask.invertBackground", json!({"layer": layer_id}), has_mask); + run(app, ui, tr("Invert mask"), "mask.invert", json!({"layer": layer_id}), has_mask); + run(app, ui, tr("Clear mask"), "mask.clear", json!({"layer": layer_id}), has_mask); + run(app, ui, tr("Remove mask"), "mask.remove", json!({"layer": layer_id}), has_mask); #[cfg(not(target_arch = "wasm32"))] if ui.add_enabled(mask_on, egui::Button::new(tr("Export mask to file..."))).clicked() { export_mask_file(app, layer); @@ -1430,57 +1451,63 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { ui.close(); } geometry_mask_menu(app, ui, layer); + ui.separator(); solo_menu(app, ui, layer.id); ui.separator(); - run(app, ui, tr("Flatten layer"), "layer.flatten", json!({"layer": lid}), !layer.is_group()); + run(app, ui, tr("Flatten layer"), "layer.flatten", json!({"layer": layer_id}), !layer.is_group()); #[cfg(not(target_arch = "wasm32"))] if ui.button(tr("Create smart material")).clicked() { let file = crate::library_dir().join(format!("{}.tcmat", texturecraft_engine::formats::sanitize_resource_name(&layer.name))); - if let Some(r) = app.run("material.save", json!({"layer": lid, "path": file.display().to_string(), "name": layer.name})) { - let p = r.get("path").and_then(|p| p.as_str()).unwrap_or_default().to_string(); - app.toast(trf("Smart material saved to {path}", &[("path", &p)]), false); + if let Some(saved) = app.run("material.save", json!({"layer": layer_id, "path": file.display().to_string(), "name": layer.name})) { + let path = saved.get("path").and_then(|path| path.as_str()).unwrap_or_default().to_string(); + app.toast(trf("Smart material saved to {path}", &[("path", &path)]), false); app.library = None; } ui.close(); } #[cfg(not(target_arch = "wasm32"))] if ui.add_enabled(has_mask, egui::Button::new(tr("Create smart mask"))).clicked() { - app.run("layer.select", json!({"layer": lid})); + app.run("layer.select", json!({"layer": layer_id})); crate::smart_mask_menu::save(app, layer, &crate::library_dir()); ui.close(); } 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); + run(app, ui, tr("Cut layer(s)"), "layer.cut", json!({"layer": layer_id}), true); + run(app, ui, tr("Copy layer(s)"), "layer.copy", json!({"layer": layer_id}), true); 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"); run(app, ui, tr("Paste as instance"), "layer.pasteInstance", json!({}), paste_instance); - run(app, ui, tr("Duplicate layer(s)"), "layer.duplicate", json!({"layer": lid}), true); - run(app, ui, tr("Instantiate across texture sets"), "layer.instantiateAll", json!({"layer": lid}), app.session.set_count() > 1); - run(app, ui, tr("Copy to all texture sets"), "layer.instantiateAll", json!({"layer": lid, "copy": true}), app.session.set_count() > 1); - run(app, ui, tr("Remove layer(s)"), "layer.remove", json!({"layer": lid}), true); - run(app, ui, tr("Group layer(s)"), "layer.group", json!({"layer": lid}), true); + run(app, ui, tr("Duplicate layer(s)"), "layer.duplicate", json!({"layer": layer_id}), true); + let many_sets = app.session.set_count() > 1; + run(app, ui, tr("Instantiate across texture sets"), "layer.instantiateAll", json!({"layer": layer_id}), many_sets); + run(app, ui, tr("Copy to all texture sets"), "layer.instantiateAll", json!({"layer": layer_id, "copy": true}), many_sets); + run(app, ui, tr("Remove layer(s)"), "layer.remove", json!({"layer": layer_id}), true); + run(app, ui, tr("Group layer(s)"), "layer.group", json!({"layer": layer_id}), true); blending_options_menu(app, ui, layer); + + // Colour tags: none (crossed out), then each tag colour ui.separator(); ui.horizontal(|ui| { - let (r, resp) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::click()); - ui.painter().rect_stroke(r, 2.0, Stroke::new(1.0, tk.text_dim), egui::StrokeKind::Inside); - ui.painter().line_segment([r.left_bottom(), r.right_top()], Stroke::new(1.0, tk.danger)); - if resp.clicked() { - app.run("layer.colorTag", json!({"layer": lid})); + let swatch_size = vec2(TAG_SWATCH_SIZE, TAG_SWATCH_SIZE); + let (swatch, response) = ui.allocate_exact_size(swatch_size, Sense::click()); + ui.painter().rect_stroke(swatch, TAG_SWATCH_RADIUS, Stroke::new(1.0, tokens.text_dim), egui::StrokeKind::Inside); + ui.painter().line_segment([swatch.left_bottom(), swatch.right_top()], Stroke::new(1.0, tokens.danger)); + if response.clicked() { + app.run("layer.colorTag", json!({"layer": layer_id})); } - for (i, c) in TAG_COLORS.iter().enumerate() { - let (r, resp) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::click()); - ui.painter().rect_filled(r, 2.0, *c); - if resp.clicked() { - app.run("layer.colorTag", json!({"layer": lid, "tag": i})); + for (tag, color) in TAG_COLORS.iter().enumerate() { + let (swatch, response) = ui.allocate_exact_size(swatch_size, Sense::click()); + ui.painter().rect_filled(swatch, TAG_SWATCH_RADIUS, *color); + if response.clicked() { + app.run("layer.colorTag", json!({"layer": layer_id, "tag": tag})); } } }); + ui.separator(); effect_menu(app, ui, layer); } @@ -1488,90 +1515,126 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { // --------------------------------------------------------------------------------------------- // Texture set settings +/// Size of a channel's remove button, and of the room Base color keeps for one +const CHANNEL_REMOVE_SIZE: f32 = 18.0; + +/// The sizes a texture set and each of its UV tiles can take +const TEXTURE_SET_RESOLUTIONS: [u32; 6] = [256, 512, 1024, 2048, 4096, 8192]; + +/// Air between the General properties grid's columns and rows +const GENERAL_GRID_SPACING: egui::Vec2 = vec2(8.0, 6.0); + +/// Air above the Channels and Mesh maps captions +const SECTION_GAP: f32 = 8.0; + +/// Air between the channel list and the height and normal settings +const CHANNEL_SETTINGS_GAP: f32 = 6.0; + +/// Range of the Height to normal strength slider +const HEIGHT_STRENGTH_RANGE: std::ops::RangeInclusive = 0.0..=10.0; + +/// A mesh map row's colour square, its corner radius, the size of its file name and of its menu's dots +const MESH_MAP_SWATCH_SIZE: f32 = 26.0; +const MESH_MAP_SWATCH_RADIUS: f32 = 2.0; +const MESH_MAP_FILE_TEXT_SIZE: f32 = 10.5; +const MESH_MAP_MENU_ICON_SIZE: f32 = 13.0; + pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let ts = app.session.ts(); - let Some(set) = app.session.doc.project.texture_sets.get(ts).cloned() else { return }; + let tokens = Tokens::get(ui.ctx()); + let set_index = app.session.ts(); + let Some(set) = app.session.doc.project.texture_sets.get(set_index).cloned() else { return }; egui::ScrollArea::vertical().id_salt("tss").show(ui, |ui| { ui.label(caption(tr("General properties"))); - egui::Grid::new("tss_grid").num_columns(2).spacing(vec2(8.0, 6.0)).show(ui, |ui| { + egui::Grid::new("tss_grid").num_columns(2).spacing(GENERAL_GRID_SPACING).show(ui, |ui| { ui.label(tr("Name")); - ui.label(RichText::new(&set.name).color(tk.text_strong)); + ui.label(RichText::new(&set.name).color(tokens.text_strong)); ui.end_row(); + ui.label(tr("Size")); egui::ComboBox::from_id_salt("ts_size").selected_text(format!("{}", set.resolution)).show_ui(ui, |ui| { - for r in [256u32, 512, 1024, 2048, 4096, 8192] { - if ui.selectable_label(r == set.resolution, format!("{r}")).clicked() { - app.start_resize(ts, r); + for resolution in TEXTURE_SET_RESOLUTIONS { + if ui.selectable_label(resolution == set.resolution, format!("{resolution}")).clicked() { + app.start_resize(set_index, resolution); } } }); ui.end_row(); + ui.label(tr("UV tiles (UDIM)")); let mut tiled = !set.uv_tiles.is_empty(); if ui.checkbox(&mut tiled, "").changed() { - app.run("textureSet.uvTiles", json!({"ts": ts, "enabled": tiled})); + app.run("textureSet.uvTiles", json!({"ts": set_index, "enabled": tiled})); } ui.end_row(); - // Each tile's own size (per-tile resolution). + + // Each tile's own size for &udim in &set.uv_tiles { - let r = set.tile_resolution(udim); - ui.label(RichText::new(format!(" {udim}")).color(tk.text_dim)); - egui::ComboBox::from_id_salt(("ts_tile", udim)).selected_text(format!("{r}")).show_ui(ui, |ui| { - for v in [256u32, 512, 1024, 2048, 4096, 8192] { - if ui.selectable_label(v == r, format!("{v}")).clicked() { - app.run("textureSet.tile.resolution", json!({"ts": ts, "tile": udim, "resolution": v})); + let tile_resolution = set.tile_resolution(udim); + ui.label(RichText::new(format!(" {udim}")).color(tokens.text_dim)); + egui::ComboBox::from_id_salt(("ts_tile", udim)).selected_text(format!("{tile_resolution}")).show_ui(ui, |ui| { + for resolution in TEXTURE_SET_RESOLUTIONS { + if ui.selectable_label(resolution == tile_resolution, format!("{resolution}")).clicked() { + app.run("textureSet.tile.resolution", json!({"ts": set_index, "tile": udim, "resolution": resolution})); } } }); ui.end_row(); } + ui.label(tr("Shader instance")); ui.label(tr("Main shader")); ui.end_row(); }); - ui.add_space(8.0); + + ui.add_space(SECTION_GAP); ui.horizontal(|ui| { ui.label(caption(tr("Channels"))); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.menu_button(tr("Add channel"), |ui| { - for c in Channel::ALL { - if !set.has_channel(c) && ui.button(tr(c.label())).clicked() { - app.run("textureSet.channel.add", json!({"ts": ts, "channel": c.id()})); + for channel in Channel::ALL { + if !set.has_channel(channel) && ui.button(tr(channel.label())).clicked() { + app.run("textureSet.channel.add", json!({"ts": set_index, "channel": channel.id()})); ui.close(); } } }); }); }); - for (c, f) in &set.channels { + + for (channel, format) in &set.channels { ui.horizontal(|ui| { - ui.label(RichText::new(tr(c.label())).strong()); + ui.label(RichText::new(tr(channel.label())).strong()); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if *c != Channel::BaseColor && icon_button(ui, ic::X, tr("Remove channel"), false, 18.0).clicked() { - app.run("textureSet.channel.remove", json!({"ts": ts, "channel": c.id()})); + // Base color can't be removed: its × room stays, so every format ends on one column + if *channel == Channel::BaseColor { + ui.allocate_exact_size(vec2(CHANNEL_REMOVE_SIZE, CHANNEL_REMOVE_SIZE), Sense::hover()); + } else if icon_button(ui, ic::X, tr("Remove channel"), false, CHANNEL_REMOVE_SIZE).clicked() { + app.run("textureSet.channel.remove", json!({"ts": set_index, "channel": channel.id()})); } - ui.label(RichText::new(f.label()).color(tk.text_dim)); + ui.label(RichText::new(format.label()).color(tokens.text_dim)); }); }); } - ui.add_space(6.0); - let mut hs = set.height_strength; - if let Some(merge) = slider_edit(ui, tr("Height to normal strength"), &mut hs, 0.0..=10.0, 2) { - app.run("textureSet.settings", json!({"ts": ts, "heightStrength": hs, "merge": merge})); + + ui.add_space(CHANNEL_SETTINGS_GAP); + let mut height_strength = set.height_strength; + if let Some(merge) = slider_edit(ui, tr("Height to normal strength"), &mut height_strength, HEIGHT_STRENGTH_RANGE, 2) { + app.run("textureSet.settings", json!({"ts": set_index, "heightStrength": height_strength, "merge": merge})); } + let directx = app.session.doc.project.normal_format == texturecraft_engine::core::NormalFormat::DirectX; combo(ui, tr("Normal map format"), if directx { "DirectX" } else { "OpenGL" }, |ui| { for (id, label, on) in [("openGl", "OpenGL", !directx), ("directX", "DirectX", directx)] { if ui.selectable_label(on, label).clicked() && !on { - app.run("textureSet.settings", json!({"ts": ts, "normalFormat": id})); + app.run("textureSet.settings", json!({"ts": set_index, "normalFormat": id})); } } }) .on_hover_text(tr( "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", )); - ui.add_space(8.0); + + ui.add_space(SECTION_GAP); ui.horizontal(|ui| { ui.label(caption(tr("Mesh maps"))); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -1580,37 +1643,39 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { } }); }); - for m in BakedMap::ALL { - let present = app.session.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&m)); + for map in BakedMap::ALL { + let present = app.session.doc.baked.get(&set_index).is_some_and(|baked| baked.maps.contains_key(&map)); 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 }); + let (swatch, _) = ui.allocate_exact_size(vec2(MESH_MAP_SWATCH_SIZE, MESH_MAP_SWATCH_SIZE), Sense::hover()); + ui.painter().rect_filled(swatch, MESH_MAP_SWATCH_RADIUS, if present { mesh_map_color(map) } else { tokens.button }); ui.vertical(|ui| { - ui.label(RichText::new(tr(crate::i18n::baked_map_label(m))).strong()); + ui.label(RichText::new(tr(crate::i18n::baked_map_label(map))).strong()); ui.label( - RichText::new(if present { format!("{}_{}", set.name, m.id()) } else { tr("Missing (bake to create)").into() }) - .size(10.5) - .color(tk.text_dim), + RichText::new(if present { format!("{}_{}", set.name, map.id()) } else { tr("Missing (bake to create)").into() }) + .size(MESH_MAP_FILE_TEXT_SIZE) + .color(tokens.text_dim), ); }); - // An image resource instead of a bake, or no map. + + // 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.menu_button(RichText::new(ic::DOTS_THREE).size(MESH_MAP_MENU_ICON_SIZE), |ui| { if let Some(name) = image_menu(app, ui) { - app.run("textureSet.meshMap.set", json!({"ts": ts, "map": m.id(), "image": name})); + app.run("textureSet.meshMap.set", json!({"ts": set_index, "map": map.id(), "image": name})); } ui.separator(); if ui.add_enabled(present, egui::Button::new(tr("Clear"))).clicked() { - app.run("textureSet.meshMap.clear", json!({"ts": ts, "map": m.id()})); + app.run("textureSet.meshMap.clear", json!({"ts": set_index, "map": map.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 let Some(name) = image_drop(ui, &resp) { - app.run("textureSet.meshMap.set", json!({"ts": ts, "map": m.id(), "image": name})); + + // A shelf image dropped on the row becomes this mesh map + let response = 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 let Some(name) = image_drop(ui, &response) { + app.run("textureSet.meshMap.set", json!({"ts": set_index, "map": map.id(), "image": name})); } } }); @@ -1696,7 +1761,7 @@ mod image_menu_tests { // The menu reads decoded images; fixture bytes are never imported or decoded for index in 0..image_count { let name = format!("image-{index:04}.png"); - let image = ImageRes { width: 32, height: 32, rgba: vec![[index as f32 / image_count as f32, 0.5, 0.25, 1.0]; 32 * 32], srgb: false }; + let image = ImageRes::new(32, 32, vec![[index as f32 / image_count as f32, 0.5, 0.25, 1.0]; 32 * 32], false); session.doc.resources.insert(name.clone(), Arc::new(vec![0])); session.images.insert(name, Arc::new(image)); } @@ -1754,10 +1819,9 @@ mod image_menu_tests { } } -/// An image from the Assets panel dropped on `resp`, outlined while one hovers it. Other assets -/// are left for the drop targets around it. +/// An image from the Assets panel dropped on `resp`, outlined while one hovers it; other assets are left for the drop targets around it pub(crate) fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { - if !resp.dnd_hover_payload::().is_some_and(|d| matches!(d.asset, Asset::Texture(_))) { + if !resp.dnd_hover_payload::().is_some_and(|drag| matches!(drag.asset, Asset::Texture(_))) { return None; } @@ -1822,6 +1886,12 @@ pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { // A floating scroll bar would cover the right-aligned slider values and section reset icons ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); egui::ScrollArea::vertical().id_salt(("props", properties_place(app))).auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); + let scope = SectionScope::Docked; + if let Some(tabs) = properties_fill_tabs(app) { + crate::property_sheet::section_tabs(ui, scope, 0, &tabs); + } + let area = egui::ScrollArea::vertical().id_salt(("props", properties_place(app))).auto_shrink([false, false]); + crate::property_sheet::in_scope(ui, scope, |ui| properties_scrolled(app, ui, area, PastEnd::Always)); } /// What the docked Properties list keeps its own scroll place for: the selected layer and the part of it edited, none for the tool @@ -1834,6 +1904,35 @@ fn properties_place(app: &TextureCraftApp) -> Option<(LayerId, StackTarget)> { app.session.selected_layer().map(|layer| (layer, app.session.target)) } +/// The sections in `area`, leaving the solid bar's room even without it, so the bar coming in refits no row (flipped it every frame) +pub(crate) fn properties_scrolled(app: &mut TextureCraftApp, ui: &mut Ui, area: egui::ScrollArea, past_end: PastEnd) { + let sheet_width = (ui.available_width() - ui.spacing().scroll.allocated_width()).max(0.0); + area.show(ui, |ui| { + ui.set_max_width(sheet_width); + crate::property_sheet::forget_sections(ui); + properties_contents(app, ui); + + // Blank space under the rows lets the last section's top reach the top of the list, as the reference panel scrolls + let scrolls = ui.min_rect().height() > ui.clip_rect().height(); + if past_end == PastEnd::Always || scrolls { + ui.add_space(crate::property_sheet::room_past_end(ui)); + } + }); +} + + if app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { + return None; + } + + let project = &app.session.doc.project; + match app.session.target { + StackTarget::Content => { + let layer = app.session.selected_layer().and_then(|id| project.layers.get(&id))?; + } + _ => None, + } +} + /// Room around the Properties rows not yet laid out by the property sheet: the sheet's side padding, so both start under the panel's name const LEGACY_BODY_MARGIN: egui::Margin = egui::Margin::symmetric(crate::property_sheet::PAD as i8, 4); @@ -1859,6 +1958,8 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { _ if tool == Tool::PolygonFill && tool_usable => legacy_body(ui, |ui| polygon_fill_properties(app, ui)), (Some(layer), StackTarget::Effect(effect)) => legacy_body(ui, |ui| effect_properties(app, ui, layer, effect)), (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => legacy_body(ui, |ui| fill_properties(app, ui, layer)), + (Some(layer), StackTarget::Effect(effect)) => effect_properties(app, ui, layer, effect), + (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => fill_properties(app, ui, layer), (Some(layer), StackTarget::Content) if layer.is_group() => legacy_body(ui, |ui| { ui.label(RichText::new(tr("A folder blends its children (pass-through). Set per-channel opacity in the layer rows.")).color(tokens.text_dim)); }), @@ -1923,26 +2024,51 @@ fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { }); } +/// Height of the brush preview over the tool's properties, and its corner radius +const BRUSH_PREVIEW_HEIGHT: f32 = 88.0; +const BRUSH_PREVIEW_CORNER_RADIUS: f32 = 2.0; + +/// The preview stroke: its segments, its margin from the preview's left (each side of its half), its wave's phase span in radians and its swing +const PREVIEW_STROKE_STEPS: usize = 40; +const PREVIEW_STROKE_MARGIN: f32 = 14.0; +const PREVIEW_STROKE_WAVE: f32 = 9.0; +const PREVIEW_STROKE_SWING: f32 = 18.0; + +/// The preview stroke's width: [`PREVIEW_STROKE_WIDTH_SCALE`] points for each [`PREVIEW_SIZE_UNIT`] of brush size, kept inside [`PREVIEW_STROKE_WIDTH`] +const PREVIEW_SIZE_UNIT: f32 = 0.25; +const PREVIEW_STROKE_WIDTH_SCALE: f32 = 60.0; +const PREVIEW_STROKE_WIDTH: std::ops::RangeInclusive = 2.0..=30.0; + +/// Faintest the preview stroke draws, so a low flow or opacity still shows +const PREVIEW_STROKE_MIN_ALPHA: u8 = 30; + +/// Radius of the preview's material sphere, and the colour it shows when the tool has no base colour +const PREVIEW_SPHERE_RADIUS: f32 = 36.0; +const PREVIEW_FALLBACK_BASE_COLOR: [f32; 3] = [0.8; 3]; + +/// Gap between the brush preview and the tab buttons +const BRUSH_PREVIEW_GAP: f32 = 4.0; + fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); // Brush preview: a stroke and a sphere with the tool's material - let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 88.0), Sense::hover()); + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), BRUSH_PREVIEW_HEIGHT), Sense::hover()); let painter = ui.painter(); - painter.rect_filled(rect, 2.0, tokens.viewport); + painter.rect_filled(rect, BRUSH_PREVIEW_CORNER_RADIUS, tokens.viewport); let half_width = rect.width() * 0.5; let brush = &app.session.tool.brush; let mut points = Vec::new(); - for step in 0..=40 { - let fraction = step as f32 / 40.0; - points.push(pos2(rect.left() + 14.0 + fraction * (half_width - 28.0), rect.center().y + (fraction * 9.0).sin() * 18.0)); + for step in 0..=PREVIEW_STROKE_STEPS { + let fraction = step as f32 / PREVIEW_STROKE_STEPS as f32; + let x = rect.left() + PREVIEW_STROKE_MARGIN + fraction * (half_width - 2.0 * PREVIEW_STROKE_MARGIN); + points.push(pos2(x, rect.center().y + (fraction * PREVIEW_STROKE_WAVE).sin() * PREVIEW_STROKE_SWING)); } - let stroke_width = (brush.size / 0.25 * 60.0).clamp(2.0, 30.0); + let stroke_width = (brush.size / PREVIEW_SIZE_UNIT * PREVIEW_STROKE_WIDTH_SCALE).clamp(*PREVIEW_STROKE_WIDTH.start(), *PREVIEW_STROKE_WIDTH.end()); let alpha = (brush.flow * brush.opacity * 255.0) as u8; - painter.add(egui::Shape::line(points, Stroke::new(stroke_width, Color32::from_white_alpha(alpha.max(30))))); - let base_color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([0.8; 3]); - crate::thumbs::paint_sphere(painter, pos2(rect.left() + half_width * 1.5, rect.center().y), 36.0, base_color); - ui.add_space(4.0); + let base_color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or(PREVIEW_FALLBACK_BASE_COLOR); + crate::thumbs::paint_sphere(painter, pos2(rect.left() + half_width * 1.5, rect.center().y), PREVIEW_SPHERE_RADIUS, base_color); + ui.add_space(BRUSH_PREVIEW_GAP); ui.horizontal(|ui| { let button_size = ui.spacing().interact_size.y; @@ -2517,6 +2643,9 @@ fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) { material_controls(app, ui); } +/// Space between the tool's channel chips and the first channel value +const CHIPS_GAP: f32 = 4.0; + /// One chip per channel of the texture set, on while the tool's material has it enabled; returns the channels. /// The Material tab and the Smudge panel both draw these, so they share one set of flags. fn material_channel_chips(app: &mut TextureCraftApp, ui: &mut Ui) -> Vec { @@ -2539,7 +2668,7 @@ fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let channels = material_channel_chips(app, ui); - ui.add_space(4.0); + ui.add_space(CHIPS_GAP); if !targets_content(app) { let mut gray = app.session.tool.mask_value; @@ -2582,6 +2711,7 @@ fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { } } } + if app.session.tool.tool == Tool::Eraser { ui.label(RichText::new(tr("The eraser removes paint from the enabled channels.")).color(tokens.text_dim)); } @@ -2589,13 +2719,16 @@ fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { fn fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { let LayerKind::Fill(fill) = &layer.kind else { return }; - if let Some(link) = &fill.link { - link_properties(app, ui, layer.id, link); - ui.add_space(6.0); - } let on: Vec = layer.channels.keys().copied().collect(); - ui.label(caption(tr("Fill"))); - fill_editor(app, ui, fill, &json!({"layer": layer.id.0}), &on, layer.id); + PropertySheet::show(ui, ("fill_sheet", layer.id.0), |sheet| { + }); + legacy_body(ui, |ui| { + if let Some(link) = &fill.link { + link_properties(app, ui, layer.id, link); + ui.add_space(6.0); + } + fill_editor(app, ui, fill, &json!({"layer": layer.id.0}), &on, layer.id); + }); } /// A MaterialCraft material's presets and exposed inputs; edits store the value and re-cook the @@ -2719,11 +2852,11 @@ fn link_param_editor(ui: &mut Ui, layer: LayerId, p: &LinkParam) -> Option Value { - let mut params = base.clone(); - if let (Some(fields), Value::Object(extra)) = (params.as_object_mut(), extra) { - fields.extend(extra); + let mut merged = base.clone(); + if let (Some(fields), Value::Object(extra_fields)) = (merged.as_object_mut(), extra) { + fields.extend(extra_fields); } - params + merged } /// Anchor points below layer `reader` in its texture set: (effect id, "layer / anchor" label). @@ -2815,12 +2948,6 @@ const FILL_CHANNELS_GAP: f32 = 4.0; /// Projection and sources of a fill layer or fill effect (`base`) for its enabled channels; `reader` owns it fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, enabled_channels: &[Channel], reader: LayerId) { let salt = base.to_string(); - if let Projection::Decal(decal) = &fill.projection { - decal_editor(app, ui, decal, base, reader); - } else { - projection_editor(app, ui, &fill.projection, "layer.fill.projection", base, &salt); - } - ui.add_space(FILL_MATERIAL_GAP); ui.label(caption(tr("Material"))); let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); @@ -2849,6 +2976,9 @@ const FILL_SCALE_RANGE: std::ops::RangeInclusive = 0.01..=20.0; /// Slider range of a UV fill's rotation, a full turn const FILL_ROTATION_DEGREES_RANGE: std::ops::RangeInclusive = 0.0..=360.0; +/// Slider range of a fill's UV offset and world offset, one texture or mesh width either way +const FILL_OFFSET_RANGE: std::ops::RangeInclusive = -1.0..=1.0; + /// Tri-planar hardness, the exponent weighting the three projections; `layer.fill.projection` clamps to the same range const TRIPLANAR_HARDNESS_RANGE: std::ops::RangeInclusive = 1.0..=64.0; @@ -2887,53 +3017,135 @@ fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, projection: &Projec // One id per fill so each keeps its own open or closed state section(ui, &format!("sec_fill_transform{salt}"), tr("UV transformations"), true, |ui| { - projection_transform(ui, projection, &mut edit); + projection_transform(ui, projection, salt, &mut edit); }); } -/// Scale plus what the projection kind adds: UV rotation and offset, or a world offset -fn projection_transform(ui: &mut Ui, projection: &Projection, edit: &mut impl FnMut(Value)) { - let mut scale = match projection { - Projection::Uv { scale, .. } => scale[0], - Projection::Triplanar { scale, .. } | Projection::Planar { scale, .. } | Projection::Spherical { scale } | Projection::Cylindrical { scale, .. } => { - *scale +/// Width of the lock button between a pair of sliders +const PAIR_LOCK_WIDTH: f32 = 22.0; + +/// Height of the lock button, which sits level with the sliders' tracks at the bottom of the pair +const PAIR_LOCK_HEIGHT: f32 = 18.0; + +/// Size of the lock button's icon +const PAIR_LOCK_ICON_SIZE: f32 = 14.0; + +/// Height of one slider: its value row over its track +const PAIR_SLIDER_HEIGHT: f32 = 34.0; + +/// Two sliders side by side under `label` (across and down), locked together while `lock` is given and set (the second greyed); the pair once one is edited, with [`slider_edit`]'s `merge` +fn pair_sliders( + ui: &mut Ui, + label: &str, + mut values: [f32; 2], + range: std::ops::RangeInclusive, + decimals: usize, + lock: Option<&mut bool>, +) -> Option<([f32; 2], bool)> { + let mut edited = None; + ui.label(label); + + let locked = lock.as_deref().copied().unwrap_or(false); + let lock_width = if lock.is_some() { PAIR_LOCK_WIDTH } else { ui.spacing().item_spacing.x }; + let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), PAIR_SLIDER_HEIGHT), Sense::hover()); + let half = ((rect.width() - lock_width) / 2.0).max(1.0); + let left = egui::Rect::from_min_size(rect.min, egui::vec2(half, rect.height())); + let right = egui::Rect::from_min_size(egui::pos2(rect.right() - half, rect.top()), egui::vec2(half, rect.height())); + let slot = |ui: &mut Ui, area: egui::Rect| ui.new_child(egui::UiBuilder::new().max_rect(area).layout(egui::Layout::top_down(egui::Align::Min))); + + if let Some(merge) = slider_edit(&mut slot(ui, left), "", &mut values[0], range.clone(), decimals) { + if locked { + values[1] = values[0]; } - Projection::Decal(_) => return, + edited = Some(merge); + } + + if let Some(lock) = lock { + let middle = + egui::Rect::from_center_size(egui::pos2(rect.center().x, rect.bottom() - PAIR_LOCK_HEIGHT / 2.0), egui::vec2(PAIR_LOCK_WIDTH, PAIR_LOCK_HEIGHT)); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(middle).layout(egui::Layout::centered_and_justified(egui::Direction::LeftToRight))); + let icon = if *lock { ic::LOCK_SIMPLE } else { ic::LOCK_SIMPLE_OPEN }; + if icon_button(&mut child, icon, tr("Lock the two values together"), *lock, PAIR_LOCK_ICON_SIZE).clicked() { + *lock = !*lock; + if *lock && values[1] != values[0] { + values[1] = values[0]; + edited = Some(false); + } + } + } + + let mut second = slot(ui, right); + second.add_enabled_ui(!locked, |ui| { + if let Some(merge) = slider_edit(ui, "", &mut values[1], range.clone(), decimals) { + edited = Some(merge); + } + }); + + edited.map(|merge| (values, merge)) +} + +/// A projection's UV transformations: tiling across and down (locked together until unlocked), rotation and offset; a 3D projection's scale and world offset too +fn projection_transform(ui: &mut Ui, projection: &Projection, salt: &str, edit: &mut impl FnMut(Value)) { + let (tiling, rotation, offset, offset_key) = match projection { + Projection::Uv { scale, rotation, offset } => (*scale, *rotation, *offset, "offset"), + Projection::Triplanar { uv, .. } + | Projection::Planar { uv, .. } + | Projection::Spherical { uv, .. } + | Projection::Cylindrical { uv, .. } + | Projection::Warp { uv, .. } => (uv.tiling, uv.rotation, uv.offset, "uvOffset"), + Projection::UvTile => return, }; - if let Some(merge) = slider_edit(ui, tr("Scale / tiling"), &mut scale, FILL_SCALE_RANGE, 2) { - edit(json!({"scale": scale, "merge": merge})); + + let lock_id = ui.make_persistent_id(("fill_tiling_lock", salt)); + let mut locked = ui.data(|data| data.get_temp::(lock_id)).unwrap_or(tiling[0] == tiling[1]); + let was_locked = locked; + if let Some((edited, merge)) = pair_sliders(ui, tr("Tiling"), tiling, FILL_SCALE_RANGE, 2, Some(&mut locked)) { + edit(json!({"tiling": edited, "merge": merge})); + } + if locked != was_locked { + ui.data_mut(|data| data.insert_temp(lock_id, locked)); + } + + let mut rotation_degrees = rotation; + if let Some(merge) = slider_edit(ui, tr("Rotation"), &mut rotation_degrees, FILL_ROTATION_DEGREES_RANGE, 0) { + edit(json!({"rotation": rotation_degrees, "merge": merge})); + } + + if let Some((edited, merge)) = pair_sliders(ui, tr("Offset"), offset, FILL_OFFSET_RANGE, 2, None) { + edit(json!({offset_key: edited, "merge": merge})); } match projection { - Projection::Uv { rotation, offset, .. } => { - let mut rotation_degrees = *rotation; - if let Some(merge) = slider_edit(ui, tr("Rotation"), &mut rotation_degrees, FILL_ROTATION_DEGREES_RANGE, 0) { - edit(json!({"rotation": rotation_degrees, "merge": merge})); - } - if let Some((edited_offset, merge)) = offset_sliders(ui, ["U", "V"], *offset) { - edit(json!({"offset": edited_offset, "merge": merge})); - } - } - Projection::Triplanar { offset, .. } | Projection::Planar { offset, .. } => { + Projection::Triplanar { scale, offset, .. } | Projection::Planar { scale, offset, .. } => { + world_scale(ui, *scale, edit); if let Some((edited_offset, merge)) = offset_sliders(ui, ["X", "Y", "Z"], *offset) { edit(json!({"offset": edited_offset, "merge": merge})); } } - Projection::Spherical { .. } | Projection::Cylindrical { .. } | Projection::Decal(_) => {} + Projection::Spherical { scale, .. } | Projection::Cylindrical { scale, .. } => world_scale(ui, *scale, edit), + Projection::Uv { .. } | Projection::UvTile | Projection::Warp { .. } => {} } } -/// A slider per offset component ("Offset U", …): the whole offset once one is edited, with -/// [`slider_edit`]'s `merge`. -fn offset_sliders(ui: &mut Ui, axes: [&str; N], mut v: [f32; N]) -> Option<([f32; N], bool)> { +/// A 3D projection's scale: how many times its pattern fits across the mesh +fn world_scale(ui: &mut Ui, scale: f32, edit: &mut impl FnMut(Value)) { + let mut scale = scale; + if let Some(merge) = slider_edit(ui, tr("Scale"), &mut scale, FILL_SCALE_RANGE, 2) { + edit(json!({"scale": scale, "merge": merge})); + } +} + +/// A slider per offset component ("Offset U", …): the whole offset once one is edited, with [`slider_edit`]'s `merge` +fn offset_sliders(ui: &mut Ui, axes: [&str; N], mut values: [f32; N]) -> Option<([f32; N], bool)> { let mut edit = None; - for (axis, x) in axes.iter().zip(v.iter_mut()) { - edit = edit.or(slider_edit(ui, &trf("Offset {axis}", &[("axis", axis)]), x, -1.0..=1.0, 2)); + for (axis, value) in axes.iter().zip(values.iter_mut()) { + edit = edit.or(slider_edit(ui, &trf("Offset {axis}", &[("axis", axis)]), value, FILL_OFFSET_RANGE, 2)); } - edit.map(|merge| (v, merge)) + + edit.map(|merge| (values, merge)) } -/// The axis a planar or cylindrical projection runs along: the one picked, if any. +/// The axis a planar or cylindrical projection runs along: the one picked, if any fn axis_combo(ui: &mut Ui, axis: u8) -> Option { let mut picked = None; combo(ui, tr("Axis"), ["X", "Y", "Z"].get(usize::from(axis)).copied().unwrap_or("Z"), |ui| { @@ -2946,107 +3158,6 @@ fn axis_combo(ui: &mut Ui, axis: u8) -> Option { picked } -/// A decal's frame: place it with a click in the 3D view, then size, turn and shift it. `base` is the -/// `{layer}` or `{effect}` holding it (a mask fill effect's decal edits like a layer's); `layer` is the reader. -fn decal_editor(app: &mut TextureCraftApp, ui: &mut Ui, d: &Decal, base: &Value, layer: LayerId) { - // What a placing click or the stack selection names: the effect when the decal is a mask effect's - let holder = base.get("effect").and_then(Value::as_u64).map_or(layer, LayerId); - let tk = Tokens::get(ui.ctx()); - ui.label(caption(tr("Decal"))); - let placing = app.placing_decal == Some(holder); - let label = format!("{} {}", ic::CROSSHAIR, if placing { tr("Click the mesh to place the decal") } else { tr("Place on the surface") }); - if ui.selectable_label(placing, label).on_hover_text(tr("The next click in the 3D view moves the decal there")).clicked() { - app.placing_decal = if placing { None } else { Some(holder) }; - } - let (lo, hi) = app.session.mesh.bounds(); - let diag = (hi - lo).length().max(1e-3); - let mut v = [d.size[0], d.size[1], d.rotation, d.offset[0], d.offset[1], d.depth]; - let rows = [ - (tr("Width"), diag * 0.01..=diag * 2.0), - (tr("Height"), diag * 0.01..=diag * 2.0), - (tr("Rotation (degrees)"), 0.0..=360.0), - (tr("Offset right"), -diag..=diag), - (tr("Offset up"), -diag..=diag), - (tr("Depth"), diag * 0.005..=diag), - ]; - let mut edit = None; - for (row, ((label, range), x)) in rows.into_iter().zip(v.iter_mut()).enumerate() { - edit = edit.or(slider_edit(ui, label, x, range, 3).map(|merge| (row, merge))); - } - - // The lock is a setting of the editor, not of the decal: every decal starts locked - let keep_id = ui.scope_id().with(("decal_keep_proportions", holder.0)); - let mut keep = ui.ctx().data(|data| data.get_temp::(keep_id)).unwrap_or(true); - if ui.checkbox(&mut keep, tr("Keep proportions")).on_hover_text(tr("Width and height follow each other by the image's aspect")).changed() { - ui.ctx().data_mut(|data| data.insert_temp(keep_id, keep)); - if keep { - app.run("layer.decal.set", with(base, json!({"keepProportions": true}))); - } - } - let mut flip = d.flip; - let flipped = ui.horizontal(|ui| ui.checkbox(&mut flip[0], tr("Flip U")).changed() | ui.checkbox(&mut flip[1], tr("Flip V")).changed()).inner; - if flipped { - app.run("layer.decal.set", with(base, json!({"flipU": flip[0], "flipV": flip[1]}))); - } - if let Some((row, merge)) = edit { - // Locked: the edited side sets the other (a height sets the width, anything else the height) - let size = if keep && row == 1 { json!(v[1]) } else { json!([v[0], v[1]]) }; - app.run( - "layer.decal.set", - with(base, json!({"size": size, "keepProportions": keep && row < 2, "rotation": v[2], "offset": [v[3], v[4]], "depth": v[5], "merge": merge})), - ); - } - decal_symmetry_editor(app, ui, d, base); - ui.label( - RichText::new(tr("The image's alpha cuts the decal's shape; faces turned away and surfaces beyond its depth stay clear.")) - .size(10.5) - .color(tk.text_dim), - ); -} - -/// The decal's mirrored copy on the other side of the mesh: the axis it is mirrored across and how its image is flipped -fn decal_symmetry_editor(app: &mut TextureCraftApp, ui: &mut Ui, decal: &Decal, base: &Value) { - let axes = ["X", "Y", "Z"]; - let axis = decal.symmetry.map(|symmetry| usize::from(symmetry.axis)); - let mut picked = None; - combo(ui, tr("Mirror across"), axis.and_then(|axis| axes.get(axis).copied()).unwrap_or_else(|| tr("Off")), |ui| { - if ui.selectable_label(axis.is_none(), tr("Off")).clicked() && axis.is_some() { - picked = Some(json!({"symmetry": "off"})); - } - for (i, name) in axes.into_iter().enumerate() { - if ui.selectable_label(axis == Some(i), name).clicked() && axis != Some(i) { - picked = Some(json!({"symmetry": name.to_ascii_lowercase()})); - } - } - }); - - if let Some(symmetry) = decal.symmetry { - let flips = [(DecalFlip::None, tr("None"), "none"), (DecalFlip::U, "U", "u"), (DecalFlip::V, "V", "v")]; - let current = flips.iter().find(|flip| flip.0 == symmetry.flip).map_or("", |flip| flip.1); - combo(ui, tr("Flip the copy's image"), current, |ui| { - for (flip, name, id) in flips { - if ui.selectable_label(flip == symmetry.flip, name).clicked() && flip != symmetry.flip { - picked = Some(json!({"symmetryFlip": id})); - } - } - }); - } - - if let Some(symmetry) = decal.symmetry { - // The plane moves within the mesh, as the symmetry popup's axis position does - let (lo, hi) = app.session.mesh.bounds(); - let limit = ((hi - lo) * 0.5)[usize::from(symmetry.axis.min(2))]; - let mut offset = symmetry.offset; - if let Some(merge) = slider_edit(ui, tr("Axis position"), &mut offset, -limit..=limit, 2) { - picked = Some(json!({"symmetryOffset": offset, "merge": merge})); - } - } - - if let Some(change) = picked { - app.run("layer.decal.set", with(base, change)); - } -} - /// Space a fill channel's color swatch leaves at the group's right edge const CHANNEL_SWATCH_MARGIN: f32 = 4.0; /// Width of a pattern's low and high swatches @@ -3191,10 +3302,10 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe let id = effect_id.0; + // Property sheets keep the panel's own edges; only the rows not yet laid out by one get the legacy margin match &effect.kind { - EffectKind::Generator(generator) => crate::generator_panel::generator_properties(app, ui, layer.id, id, generator), - EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels), - EffectKind::Fill { source, projection } => { + EffectKind::Generator(generator) => legacy_body(ui, |ui| crate::generator_panel::generator_properties(app, ui, layer.id, id, generator)), + EffectKind::Fill { source, projection, .. } => legacy_body(ui, |ui| { ui.label(caption(tr("Fill"))); let anchors = effect_anchors_below(app, layer.id, effect_id); let target = crate::fill_source_target::FillSourceTarget::Mask { effect: id }; @@ -3232,21 +3343,17 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe ui.label(RichText::new(tr("Colors read as gray. Add a levels or blur effect above to shape the result.")).color(tokens.text_dim)); } Source::Image { .. } => { - if let Projection::Decal(decal) = projection { - decal_editor(app, ui, decal, &json!({"effect": id}), layer.id); - } else { - projection_editor(app, ui, projection, "effect.set", &json!({"effect": id}), &format!("maskfill{id}")); - } + projection_editor(app, ui, projection, "effect.set", &json!({"effect": id}), &format!("maskfill{id}")); } } if anchors.is_empty() { ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tokens.text_dim)); } - } + }), EffectKind::Material(fill) => { - ui.label(caption(tr("Fill"))); let enabled: Vec = fill.sources.keys().copied().collect(); - fill_editor(app, ui, fill, &json!({"effect": id}), &enabled, layer.id); + PropertySheet::show(ui, ("fill_effect_sheet", id), |sheet| { + }); } EffectKind::Anchor => { ui.label(caption(tr("Anchor point"))); @@ -3256,8 +3363,8 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe tr("Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.") }; ui.label(RichText::new(text).color(tokens.text_dim)); - } - EffectKind::Paint => { + }), + EffectKind::Paint => legacy_body(ui, |ui| { let hint = if layer.content_effects.iter().any(|content| content.id == effect_id) { tr("Paint on the mesh to edit the layer content.") } else { @@ -3267,8 +3374,8 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe if app.session.tool_usable(app.session.tool.tool) { tool_properties(app, ui); } - } - EffectKind::Path(paths) => { + }), + EffectKind::Path(paths) => legacy_body(ui, |ui| { ui.label( RichText::new(tr("Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.")) .color(tokens.text_dim), @@ -3292,12 +3399,13 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe if app.session.tool_usable(app.session.tool.tool) { tool_properties(app, ui); } + }), } EffectKind::Filter(filter) => filter_properties(app, ui, id, filter), EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, colors, *tolerance), other => { ui.label(RichText::new(tr(other.name())).color(tokens.text_dim)); - } + }), } } diff --git a/crates/ui-egui/src/exact_entry_open.rs b/crates/ui-egui/src/exact_entry_open.rs new file mode 100644 index 00000000..67abc1b5 --- /dev/null +++ b/crates/ui-egui/src/exact_entry_open.rs @@ -0,0 +1,5 @@ +//! The Levels editor's mark that its exact-entry fields are shown + +/// Marks the exact-entry fields as shown; they appear on a handle's double-click or Enter and close when typing ends +#[derive(Clone, Copy)] +pub(crate) struct ExactEntryOpen; diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 51464449..60e5a7b4 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -640,7 +640,7 @@ mod tests { assert!(gpu.sync(&mut s, None, None, 0, 0.0).image_aux.is_empty()); assert!(gpu.aux_image.is_none()); - let replacement = Arc::new(ImageRes { width: 1, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0]], srgb: true }); + let replacement = Arc::new(ImageRes::new(1, 1, vec![[1.0, 0.0, 0.0, 1.0]], true)); s.images.insert(name.clone(), replacement); execute(&mut s, "viewport.view", &json!({"mode": "image", "image": name})).unwrap(); let updated = gpu.sync(&mut s, Some(AuxView::Image), None, 0, 0.0); diff --git a/crates/ui-egui/src/gray_slider.rs b/crates/ui-egui/src/gray_slider.rs index 0ea4dfd2..eac04af1 100644 --- a/crates/ui-egui/src/gray_slider.rs +++ b/crates/ui-egui/src/gray_slider.rs @@ -21,7 +21,10 @@ pub(crate) fn gray_slider(ui: &mut Ui, label: &str, value: &mut f32) -> Option &'static str { + use texturecraft_engine::core::Filtering; + match filtering { + Filtering::BilinearHq => n_("Bilinear | HQ"), + Filtering::BilinearSharp => n_("Bilinear | Sharp"), + Filtering::Nearest => n_("Nearest"), + } +} + +/// Whether a fill repeats past its tile, as the UV Wrap combo names it +pub(crate) fn wrap_label(wrap: texturecraft_engine::core::UvWrap) -> &'static str { + use texturecraft_engine::core::UvWrap; + match wrap { + UvWrap::None => n_("None"), + UvWrap::RepeatHorizontally => n_("Repeat horizontally"), + UvWrap::RepeatVertically => n_("Repeat vertically"), + UvWrap::Repeat => n_("Repeat"), + } +} + /// Display labels belong to the UI; the model exposes only map identities pub(crate) fn baked_map_label(map: texturecraft_engine::core::BakedMap) -> &'static str { use texturecraft_engine::core::BakedMap; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 90519b44..0a9ad4d2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -28,10 +28,14 @@ pub mod export_templates; mod export_window; #[cfg(not(target_arch = "wasm32"))] pub mod file_dialogs; +mod fill_panel; +mod fill_pictures; mod fill_source_slot; mod fill_source_target; +mod fill_symmetry_panel; mod filter_slot; pub mod fonts; +mod frame_gizmo; mod generator_panel; pub mod gpu; mod gray_slider; @@ -54,6 +58,8 @@ mod mask_preview_image; mod material_preview_image; pub mod menus; mod mesh_export_options; +mod move_hold; +pub mod move_on_model; mod name_error; mod named_layout; pub mod named_layouts; @@ -63,12 +69,16 @@ mod nav_view; pub mod new_project_advanced; mod orb_shape; pub mod parity; +mod past_end; mod path_hit; mod path_surface_cache; mod pattern_panel; mod pattern_target; pub mod pbr_import; +mod placement; +mod pointer_lock; mod popup_drag; +mod preview_dots; mod preview_image; mod preview_request; mod preview_worker; @@ -76,6 +86,10 @@ pub mod profile; #[cfg(not(target_arch = "wasm32"))] mod project_config; pub mod project_form; +mod projection_gizmo; +mod projection_kind; +mod projection_preview; +mod projector_outline; pub mod properties_popup; mod property_sheet; mod query_field; @@ -88,6 +102,7 @@ mod resource_picker_choice; mod resource_picker_item; mod resource_picker_tab; mod resource_picker_tile; +mod round_gizmo; mod running_bake; pub mod saved_search; mod screen_color_pick; @@ -122,6 +137,7 @@ mod uv_tile_grid; mod uv_view_map; mod view_mode_picker; pub mod viewport; +mod warp_checker; pub mod web_files; pub mod widgets; pub mod windows; @@ -236,8 +252,8 @@ pub struct TextureCraftApp { pub last_paint_point: Option, /// The last finished 2D stroke's endpoint, scoped to its mesh and texture set for Shift+click lines pub last_paint_uv: Option, - /// The decal layer the next click in the 3D view places. - pub placing_decal: Option, + /// The fill whose Move on model button is held down: dragging slides its projection, Shift or the right button turns it, the wheel scales it + pub moving_on_model: Option, /// The Properties popup a right click in a view opens. pub properties_popup: Option, /// The color selection the next click in the 3D or 2D view picks an ID color for @@ -344,7 +360,7 @@ impl TextureCraftApp { render: render_mode::RenderView::default(), last_paint_point: None, last_paint_uv: None, - placing_decal: None, + moving_on_model: None, properties_popup: None, picking_id_color: None, picking_symmetry_plane: false, @@ -925,6 +941,13 @@ struct CameraGlide { const GLIDE_SECONDS: f64 = 0.35; +/// The share of the running frame rate and frame time averages each frame keeps (an average over about ten frames) +const FRAME_AVERAGE_KEEP: f32 = 0.9; +/// The interface scale applied: wider than the Settings slider, so a scale set elsewhere still applies within reason +const UI_SCALE_APPLIED: std::ops::RangeInclusive = 0.5..=3.0; +/// Zoom factors closer than this are the same zoom (float noise), so the zoom is not set again each frame +const SAME_ZOOM_TOLERANCE: f32 = 1e-3; + impl TextureCraftApp { /// Advance the camera glide by one frame. fn step_camera_glide(&mut self, ctx: &egui::Context) { @@ -953,6 +976,11 @@ impl TextureCraftApp { } impl eframe::App for TextureCraftApp { + /// A drag that holds the pointer reads the pointer's moves as moves of a pointer no screen edge stops + fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) { + pointer_lock::rewrite(ctx, raw_input); + } + /// The browser never tells eframe the page is closing, so save often there. fn auto_save_interval(&self) -> std::time::Duration { std::time::Duration::from_secs(if cfg!(target_arch = "wasm32") { 5 } else { 30 }) @@ -966,13 +994,14 @@ impl eframe::App for TextureCraftApp { } fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { - let t0 = now_ms(); - let now = ctx.input(|i| i.time); - let dt = (now - self.last_time) as f32; - if dt > 0.0 { - self.fps = self.fps * 0.9 + (1.0 / dt) * 0.1; + let logic_start_ms = now_ms(); + let now = ctx.input(|input| input.time); + let frame_seconds = (now - self.last_time) as f32; + if frame_seconds > 0.0 { + self.fps = self.fps * FRAME_AVERAGE_KEEP + (1.0 / frame_seconds) * (1.0 - FRAME_AVERAGE_KEEP); } self.last_time = now; + let style = (self.ui.prefs.brightness, self.ui.prefs.accent); if self.styled != Some(style) { theme::apply(ctx, style.0, style.1); @@ -980,16 +1009,17 @@ impl eframe::App for TextureCraftApp { } self.step_camera_glide(ctx); self.ui.prefs.apply_resource_limits(); + control::poll(self, ctx); #[cfg(not(target_arch = "wasm32"))] self.run_file_dialog_answers(); web_files::poll(self); - let dropped = ctx.input(|i| i.raw.dropped_files.clone()); + let dropped = ctx.input(|input| input.raw.dropped_files.clone()); // A folder, a zip or several PBR maps dropped together open the PBR import dialog #[cfg(not(target_arch = "wasm32"))] let consumed = if !dropped.is_empty() { - let paths: Vec = dropped.iter().map(|f| f.path().to_path_buf()).collect(); + let paths: Vec = dropped.iter().map(|file| file.path().to_path_buf()).collect(); pbr_import::dropped(self, &paths) } else { Vec::new() @@ -1009,13 +1039,14 @@ impl eframe::App for TextureCraftApp { self.thumbs.sync_images(&self.session.images, self.session.revision); // The library shelf rescans when the window comes back (MaterialCraft may have sent a material) - let focused = ctx.input(|i| i.viewport().focused).unwrap_or(true); + let focused = ctx.input(|input| input.viewport().focused).unwrap_or(true); if focused && !self.focused { self.library = None; } self.focused = focused; - let scale = self.ui.prefs.ui_scale.clamp(0.5, 3.0); - if (ctx.zoom_factor() - scale).abs() > 1e-3 { + + let scale = self.ui.prefs.ui_scale.clamp(*UI_SCALE_APPLIED.start(), *UI_SCALE_APPLIED.end()); + if (ctx.zoom_factor() - scale).abs() > SAME_ZOOM_TOLERANCE { ctx.set_zoom_factor(scale); } #[cfg(not(target_arch = "wasm32"))] @@ -1029,17 +1060,19 @@ impl eframe::App for TextureCraftApp { self.fonts.update(ctx, i18n::current().code, self.ui.windows.settings); #[cfg(not(target_arch = "wasm32"))] updates_ui::tick(self, ctx); + self.bindings.sync(&self.ui.keymap, craft_keymap::egui::platform(ctx)); menus::shortcuts(self, ctx); + move_on_model::end_when_gone(self, ctx); // The Path tool's curve repaints (a preview while placed) as its points, brush or material change - if let Err(e) = self.session.path_live() { + if let Err(error) = self.session.path_live() { self.session.cancel_path(); - self.toast(e.to_string(), true); + self.toast(error.to_string(), true); } profile::drive(self, ctx); - self.toasts.retain(|t| t.until > now); - self.profiler.logic_ms = (now_ms() - t0) as f32; + self.toasts.retain(|toast| toast.until > now); + self.profiler.logic_ms = (now_ms() - logic_start_ms) as f32; // Last, so it sees every close request this frame's work made windows::close_request(self, ctx); @@ -1048,7 +1081,7 @@ impl eframe::App for TextureCraftApp { #[cfg_attr(target_arch = "wasm32", allow(unused_variables))] fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { let ctx = ui.ctx().clone(); - let started_ms = now_ms(); + let ui_start_ms = now_ms(); // Baking and rendering need a project (a saved layout may start in one of them) if !self.session.project_open { @@ -1088,10 +1121,12 @@ impl eframe::App for TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] self.file_dialogs.show_pending(frame); - let ended_ms = now_ms(); - let elapsed_ms = (ended_ms - started_ms) as f32; - self.ui_ms = if self.ui_ms == 0.0 { elapsed_ms } else { self.ui_ms * 0.9 + elapsed_ms * 0.1 }; - self.profiler.end_frame(ended_ms, elapsed_ms); + pointer_lock::settle(&ctx); + + let end_ms = now_ms(); + let ui_frame_ms = (end_ms - ui_start_ms) as f32; + self.ui_ms = if self.ui_ms == 0.0 { ui_frame_ms } else { self.ui_ms * FRAME_AVERAGE_KEEP + ui_frame_ms * (1.0 - FRAME_AVERAGE_KEEP) }; + self.profiler.end_frame(end_ms, ui_frame_ms); } } diff --git a/crates/ui-egui/src/past_end.rs b/crates/ui-egui/src/past_end.rs new file mode 100644 index 00000000..22851ad6 --- /dev/null +++ b/crates/ui-egui/src/past_end.rs @@ -0,0 +1,10 @@ +//! How far a Properties list scrolls past its last row + +/// When a Properties list leaves blank space under its rows so its last section's top can reach the top of the list +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum PastEnd { + /// Always, as the docked panel: even when every section fits + Always, + /// Only once the rows no longer fit, as a popup sized to its rows + WhenScrolling, +} diff --git a/crates/ui-egui/src/placement.rs b/crates/ui-egui/src/placement.rs new file mode 100644 index 00000000..925e616b --- /dev/null +++ b/crates/ui-egui/src/placement.rs @@ -0,0 +1,9 @@ +//! Where a fill's tiles land, as the window preview draws them + +/// How the fill's image is laid on its tile: tiles across and down, rotation in degrees, offset in tiles (rotate, scale, then offset) +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Placement { + pub tiling: [f32; 2], + pub rotation: f32, + pub offset: [f32; 2], +} diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs index 305c8bb6..341fda86 100644 --- a/crates/ui-egui/src/properties_popup.rs +++ b/crates/ui-egui/src/properties_popup.rs @@ -3,6 +3,7 @@ use egui::{PointerButton, Pos2, Rect, Ui}; use crate::TextureCraftApp; +use crate::property_sheet::SectionScope; use crate::state::Mode; use crate::theme::Tokens; @@ -34,7 +35,7 @@ pub(crate) fn open_on_right_click(app: &mut TextureCraftApp, ui: &Ui, response: let free = app.ui.mode == Mode::Painting && app.properties_popup.is_none() && !app.session.stroke_active() - && app.placing_decal.is_none() + && app.moving_on_model.is_none() && !gesture_key_held && !crate::viewport::focus_picking(ui.ctx()) && ui.input(|input| input.modifiers.is_none()); @@ -50,6 +51,7 @@ pub(crate) fn open_on_right_click(app: &mut TextureCraftApp, ui: &Ui, response: /// Draws the open popup and closes it on a press outside it or when the app leaves Painting pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let (any_down, pressed_at) = ctx.input(|input| (input.pointer.any_down(), input.pointer.press_origin().filter(|_| input.pointer.any_pressed()))); + match app.properties_popup { _ if app.ui.mode != Mode::Painting => app.properties_popup = None, Some(PropertiesPopup::Closing) if !any_down => app.properties_popup = None, @@ -73,7 +75,17 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.set_max_height(bounds.height() * PROPERTIES_POPUP_MAX_HEIGHT_SHARE); // A floating bar would cover the sliders' right-aligned values ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); - egui::ScrollArea::vertical().id_salt("properties_popup_scroll").show(ui, |ui| crate::dock::properties_contents(app, ui)); + + // The docked panel's jump tabs on the top edge stay put while the sections scroll under them + let scope = SectionScope::Popup; + if let Some(tabs) = crate::dock::properties_fill_tabs(app) { + crate::property_sheet::section_tabs(ui, scope, ui.style().visuals.menu_corner_radius.nw, &tabs); + } + crate::property_sheet::in_scope(ui, scope, |ui| { + // A popup that fits its rows keeps its size; one that scrolls goes on until its last section's top + let area = egui::ScrollArea::vertical().id_salt("properties_popup_scroll"); + crate::dock::properties_scrolled(app, ui, area, crate::past_end::PastEnd::WhenScrolling); + }); }); }); } diff --git a/crates/ui-egui/src/render_mode/tests.rs b/crates/ui-egui/src/render_mode/tests.rs index d7145208..d8f7ada3 100644 --- a/crates/ui-egui/src/render_mode/tests.rs +++ b/crates/ui-egui/src/render_mode/tests.rs @@ -41,14 +41,14 @@ fn environment_cache_retains_source_identity_until_replaced() { let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let mut app = egui_kittest::Harness::builder().build_eframe(|context| crate::TextureCraftApp::new(context, session())).into_state(); app.session.doc.project.display.environment = "resource:environment".into(); - let source = Arc::new(ImageRes { width: 2, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0]; 2], srgb: false }); + let source = Arc::new(ImageRes::new(2, 1, vec![[1.0, 0.0, 0.0, 1.0]; 2], false)); let original_source = Arc::downgrade(&source); app.session.images.insert("environment".into(), source); let first_key = gpu_scene_key(&app.session); let first = super::trace_scene(&app).env; assert!(Arc::ptr_eq(&first, &super::trace_scene(&app).env), "unchanged images reuse the decoded environment"); - let replacement = Arc::new(ImageRes { width: 2, height: 1, rgba: vec![[0.0, 1.0, 0.0, 1.0]; 2], srgb: false }); + let replacement = Arc::new(ImageRes::new(2, 1, vec![[0.0, 1.0, 0.0, 1.0]; 2], false)); app.session.images.insert("environment".into(), replacement.clone()); assert!(original_source.upgrade().is_none(), "replacing the resource releases its decoded pixels immediately"); diff --git a/crates/ui-egui/src/resolution_band.rs b/crates/ui-egui/src/resolution_band.rs new file mode 100644 index 00000000..c2794eb1 --- /dev/null +++ b/crates/ui-egui/src/resolution_band.rs @@ -0,0 +1,138 @@ +//! The Resolution of a cooked source, Relative (follows the texture set) or Fixed, each size pictured against the texture set's: a material's band, a procedural slot's row + +use egui::{CornerRadius, Painter, Rect, Stroke, StrokeKind, vec2}; +use texturecraft_engine::core::{CookResolution, MAX_RESOLUTION}; + +use crate::i18n::tr; +use crate::property_sheet::PropertySheet; +use crate::theme::Tokens; + +/// Side of the grey square (this source) for factors 1/8 … ×8, as a share of the picture's side +const RATIO_SIDES: [f32; 7] = [0.12, 0.22, 0.32, 0.46, 0.66, 0.84, 1.0]; + +/// Side of the accent outline (the texture set) as a share of the picture's side +const TEXTURE_SET_SIDE: f32 = 0.42; + +/// The smallest fixed size the list offers +const SMALLEST_FIXED: u32 = 256; + +/// The Relative side of the Relative | Fixed switch +const RELATIVE_MODE: usize = 0; + +/// The Fixed side of the Relative | Fixed switch +const FIXED_MODE: usize = 1; + +/// The Resolution band (folded: picture and size); returns the resolution picked +pub(crate) fn resolution_band(sheet: &mut PropertySheet<'_>, current: CookResolution, texture_set: u32) -> Option { + let tokens = Tokens::get(sheet.ui.ctx()); + let size = current.size(texture_set); + let relative = matches!(current, CookResolution::Relative(_)); + let picture = |painter: &Painter, rect: Rect| ratio_picture(painter, rect, factor_of(size, texture_set), relative, &tokens); + if !sheet.band_pictured(tr("Resolution"), false, &format!("{size} × {size}"), &picture).open { + return None; + } + + let modes = [tr("Relative"), tr("Fixed")]; + let mode_picture = |painter: &Painter, rect: Rect, index: usize| ratio_picture(painter, rect, 0, index == RELATIVE_MODE, &tokens); + let switched = sheet.picture_switch(&modes, if relative { RELATIVE_MODE } else { FIXED_MODE }, &mode_picture).map(|mode| { + if mode == RELATIVE_MODE { + // Fixed → Relative keeps the nearest factor the texture set can cook at + let factor = factor_of(size, texture_set); + if fits(texture_set, factor) { CookResolution::Relative(factor) } else { CookResolution::TEXTURE_SET } + } else { + CookResolution::Fixed(size) + } + }); + + let picked = if let CookResolution::Relative(factor) = current { + let factors = || fitting_factors(texture_set); + let name = |factor: i8| format!("{} · {}", factor_name(factor), CookResolution::Relative(factor).size(texture_set)); + let draw = |painter: &Painter, rect: Rect, factor: i8| ratio_picture(painter, rect, factor, true, &tokens); + sheet.dropdown_built(tr("Size"), factor, factors, name, Some(&draw)).0.map(CookResolution::Relative) + } else { + let draw = |painter: &Painter, rect: Rect, size: u32| ratio_picture(painter, rect, factor_of(size, texture_set), false, &tokens); + sheet.dropdown_built(tr("Size"), size, fixed_sizes, |size| format!("{size} × {size}"), Some(&draw)).0.map(CookResolution::Fixed) + }; + switched.or(picked) +} + +/// The Resolution row of a procedural slot's card: one list with the texture set's factors under Relative and fixed sizes under Fixed; returns the resolution picked +pub(crate) fn resolution_row(sheet: &mut PropertySheet<'_>, current: CookResolution, texture_set: u32) -> Option { + let tokens = Tokens::get(sheet.ui.ctx()); + let name = |resolution: CookResolution| match resolution { + CookResolution::Relative(factor) => format!("{} · {}", factor_name(factor), resolution.size(texture_set)), + CookResolution::Fixed(size) => format!("{size} × {size}"), + }; + let draw = |painter: &Painter, rect: Rect, resolution: CookResolution| { + let related = matches!(resolution, CookResolution::Relative(_)); + ratio_picture(painter, rect, factor_of(resolution.size(texture_set), texture_set), related, &tokens); + }; + let groups = || { + let relative: Vec = fitting_factors(texture_set).map(CookResolution::Relative).collect(); + let fixed: Vec = fixed_sizes().map(CookResolution::Fixed).collect(); + [(tr("Relative"), relative), (tr("Fixed"), fixed)] + }; + sheet.grouped_dropdown(tr("Resolution"), current, groups, name, &draw) +} + +/// The factors the texture set can cook at, smallest first +fn fitting_factors(texture_set: u32) -> impl Iterator { + CookResolution::FACTORS.filter(move |factor| fits(texture_set, *factor)) +} + +/// The sizes a fixed resolution offers, smallest first +fn fixed_sizes() -> impl Iterator { + std::iter::successors(Some(SMALLEST_FIXED), |size| size.checked_mul(2)).take_while(|size| *size <= MAX_RESOLUTION) +} + +/// Whether the texture set's size times 2^`factor` can be cooked +fn fits(texture_set: u32, factor: i8) -> bool { + let shift = u32::from(factor.unsigned_abs()); + let size = if factor >= 0 { 1u32.checked_shl(shift).and_then(|scale| texture_set.checked_mul(scale)) } else { texture_set.checked_shr(shift) }; + size.is_some_and(CookResolution::cookable) +} + +/// The factor (a power of two, within the list's) from the texture set's size to `size` +fn factor_of(size: u32, texture_set: u32) -> i8 { + let steps = i64::from(size.max(1).ilog2()) - i64::from(texture_set.max(1).ilog2()); + let (low, high) = (CookResolution::FACTORS.start(), CookResolution::FACTORS.end()); + i8::try_from(steps.clamp(i64::from(*low), i64::from(*high))).unwrap_or_default() +} + +/// A factor's name in the list: 1/8 … Texture set … ×8 (a factor outside the list, from a loaded project, is named as its nearest end) +fn factor_name(factor: i8) -> String { + match factor.clamp(*CookResolution::FACTORS.start(), *CookResolution::FACTORS.end()) { + 0 => tr("Texture set").to_owned(), + negative if negative < 0 => format!("1/{}", 1u32 << negative.unsigned_abs()), + positive => format!("×{}", 1u32 << positive), + } +} + +/// This source (grey square) against the texture set (accent outline, when the size follows it) +fn ratio_picture(painter: &Painter, rect: Rect, factor: i8, related: bool, tokens: &Tokens) { + painter.rect_filled(rect, CornerRadius::ZERO, tokens.field); + let step = usize::try_from(i32::from(factor) - i32::from(*CookResolution::FACTORS.start())).unwrap_or_default(); + let side = RATIO_SIDES.get(step).copied().unwrap_or(1.0) * rect.width(); + painter.rect_filled(Rect::from_center_size(rect.center(), vec2(side, side)), CornerRadius::ZERO, tokens.text_dim); + if related { + let side = TEXTURE_SET_SIDE * rect.width(); + painter.rect_stroke(Rect::from_center_size(rect.center(), vec2(side, side)), CornerRadius::ZERO, Stroke::new(1.0, tokens.accent), StrokeKind::Inside); + } +} + +#[cfg(test)] +mod tests { + use super::{factor_name, factor_of, fits}; + + #[test] + fn factors_name_and_fit_the_texture_set() { + assert_eq!([-3, -1, 1, 3].map(factor_name), ["1/8", "1/2", "×2", "×8"]); + assert_eq!((factor_of(1024, 2048), factor_of(8192, 128), factor_of(0, 2048)), (-1, 3, -3)); + assert!(fits(2048, 2) && !fits(2048, 3) && !fits(256, -2)); + } + + #[test] + fn a_factor_outside_the_list_is_named_as_its_nearest_end() { + assert_eq!([i8::MIN, i8::MAX].map(factor_name), ["1/8", "×8"]); + } +} diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index a2ae0528..3f3b75e2 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -164,7 +164,7 @@ mod tests { #[test] fn every_tab_renders_a_big_preview() { - let image = ImageRes { width: 4, height: 2, rgba: vec![[0.8, 0.4, 0.2, 1.0]; 8], srgb: true }; + let image = ImageRes::new(4, 2, vec![[0.8, 0.4, 0.2, 1.0]; 8], true); let previews = [ ShelfPreview::Material(MATERIALS[0].id), ShelfPreview::Filter(FILTERS[0].id), @@ -201,7 +201,7 @@ mod tests { #[test] fn saved_brush_preview_uses_its_project_image_alpha() { let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; - let transparent = Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[1.0, 1.0, 1.0, 0.0]; 4], srgb: false }); + let transparent = Arc::new(ImageRes::new(2, 2, vec![[1.0, 1.0, 1.0, 0.0]; 4], false)); let preview = ShelfPreview::SavedBrush { path: PathBuf::from("brush.tcbrush"), settings: Some(settings.clone()), image: Some(transparent) }; assert!(preview.image(64).is_some_and(|image| image.pixels.iter().all(|pixel| pixel.r() == 0))); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 41b14eb7..2c2b045d 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -293,6 +293,9 @@ pub fn semibold(size: f32) -> FontId { /// The semibold family: Inter SemiBold, the regular font without it. pub(crate) const SEMIBOLD: &str = "ui-semibold"; +/// Colour of the hard, unblurred shadow under the panel's own popups (pickers, menus, tips) +pub(crate) const HARD_SHADOW: Color32 = Color32::from_rgb(12, 14, 18); + /// The app's fonts: Inter (regular and semibold) when built with craft-fonts, egui's defaults /// otherwise, egui's monospace face for values, and the Phosphor icon font (`fonts::UiFonts` /// adds CJK). @@ -384,6 +387,23 @@ pub fn apply(ctx: &egui::Context, b: Brightness, accent: Accent) { }); } +/// X, Y and Z as the view corner, the symmetry manipulator and the 3D fields show them +pub const AXIS_COLORS: [Color32; 3] = [Color32::from_rgb(0xd8, 0x60, 0x4f), Color32::from_rgb(0x6c, 0xbc, 0x5a), Color32::from_rgb(0x5a, 0x8c, 0xe0)]; + +/// An axis arrow's shaft as the symmetry manipulator and the projection gizmos draw it: its width, the dark halo under it and the halo's extra width (points at the default size) +pub const SHAFT_WIDTH: f32 = 2.2; +pub const SHAFT_HALO: Color32 = Color32::from_black_alpha(128); +pub const SHAFT_HALO_EXTRA_WIDTH: f32 = 3.0; + +/// The axes' letters, as the Axis switches and the 3D fields' tags show them +pub const AXIS_NAMES: [&str; 3] = ["X", "Y", "Z"]; + +/// `from` moved `amount` of the way to `to` in gamma space, opaque +pub(crate) fn lerp_color(from: Color32, to: Color32, amount: f32) -> Color32 { + let mix = |a: u8, b: u8| (f32::from(a) + (f32::from(b) - f32::from(a)) * amount).round().clamp(0.0, 255.0) as u8; + Color32::from_rgb(mix(from.r(), to.r()), mix(from.g(), to.g()), mix(from.b(), to.b())) +} + /// A section caption inside a panel: semibold in the strong colour, as written (no capitals). pub fn caption(text: &str) -> egui::RichText { egui::RichText::new(text).font(semibold(12.5)).strong() diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 098f3638..ecfa8b14 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -435,7 +435,7 @@ mod tests { let path = PathBuf::from("changed-alpha.tcbrush"); let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; thumbs.saved_brush_previews.insert(path.clone(), (Some(settings), None, 0)); - let image = |value| Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[value; 4]; 4], srgb: false }); + let image = |value| Arc::new(ImageRes::new(2, 2, vec![[value; 4]; 4], false)); let mut images: ImageStore = [("alpha.png".into(), image(0.2))].into(); let old_preview = thumbs.saved_brush_preview(&path, &images); @@ -522,8 +522,8 @@ mod tests { let first_path = PathBuf::from("first.tcbrush"); let second_path = PathBuf::from("second.tcbrush"); let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; - let old_image = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[1.0; 4]; IMAGE_TEXELS], srgb: false }); - let other_image = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[0.5; 4]; IMAGE_TEXELS], srgb: false }); + let old_image = Arc::new(ImageRes::new(IMAGE_SIDE, IMAGE_SIDE, vec![[1.0; 4]; IMAGE_TEXELS], false)); + let other_image = Arc::new(ImageRes::new(IMAGE_SIDE, IMAGE_SIDE, vec![[0.5; 4]; IMAGE_TEXELS], false)); let old_weak = Arc::downgrade(&old_image); let other_weak = Arc::downgrade(&other_image); assert!(old_image.rgba.iter().map(|pixel| std::hint::black_box(pixel[0])).sum::() > 0.0); @@ -544,7 +544,7 @@ mod tests { Arc::strong_count(&images["alpha.png"]) ); - let replacement = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[0.0; 4]; IMAGE_TEXELS], srgb: false }); + let replacement = Arc::new(ImageRes::new(IMAGE_SIDE, IMAGE_SIDE, vec![[0.0; 4]; IMAGE_TEXELS], false)); images.insert("alpha.png".into(), replacement); drop(thumbs.saved_brush_preview(&first_path, &images)); assert!(other_weak.upgrade().is_none(), "another saved brush does not retain the old project image"); @@ -558,7 +558,7 @@ mod tests { fn replacing_an_image_rebuilds_its_preview() { let context = egui::Context::default(); let mut thumbs = Thumbs::default(); - let image = |value| Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[value; 4]; 4], srgb: false }); + let image = |value| Arc::new(ImageRes::new(2, 2, vec![[value; 4]; 4], false)); let first_image = image(0.2); let replacement_image = image(0.8); @@ -575,7 +575,7 @@ mod tests { let mut images = ImageStore::new(); for index in 0..3 { let name = format!("image-{index}"); - images.insert(name, Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[index as f32; 4]; 4], srgb: false })); + images.insert(name, Arc::new(ImageRes::new(2, 2, vec![[index as f32; 4]; 4], false))); } for (name, image) in &images { @@ -595,7 +595,7 @@ mod tests { assert!(after_pixel_bytes < before_pixel_bytes); assert!(thumbs.images.contains_key("image-2")); - images.insert("image-3".into(), Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[0.7; 4]; 4], srgb: false })); + images.insert("image-3".into(), Arc::new(ImageRes::new(2, 2, vec![[0.7; 4]; 4], false))); drop(thumbs.image(&context, "image-3", &images["image-3"])); thumbs.sync_images(&images, 2); assert_eq!(thumbs.images.len(), 2); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 97edafed..159fdecc 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -18,6 +18,7 @@ use crate::gpu::ViewCallback; use crate::i18n::{tr, trf}; use crate::path_hit::PathHit; use crate::path_surface_cache::{PathSurfaceCache, SurfaceCurve}; +use crate::projection_gizmo::ShownGizmo; use crate::state::ViewLayout; use crate::theme::Tokens; use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; @@ -731,7 +732,10 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let local = |pointer: egui::Pos2| Vec2::new(pointer.x - rect.left(), pointer.y - rect.top()); let adjusting = brush_drag(app, ui, &response); let ctrl = ui.input(|input| input.modifiers.ctrl); - let navigating = !adjusting && (alt || ui.input(|input| input.pointer.middle_down() || input.pointer.secondary_down())); + + // A held Move on model button owns the pointer and the wheel until it lets go: the camera, brush and gizmos keep still + let holding = crate::move_on_model::holding(app, ui.ctx()); + let navigating = !adjusting && !holding && (alt || ui.input(|input| input.pointer.middle_down() || input.pointer.secondary_down())); // Navigation; S + drag moves the projection stencil instead, below let delta = ui.input(|input| input.pointer.delta()); @@ -740,8 +744,8 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // Only an equipped Projection tool that can act moves its stencil: it isn't drawn otherwise let stencil_moves = tool_acts(app) && app.session.tool.tool == Tool::Projection; let stencil_drag = s_held && stencil_moves && app.session.tool.stencil.is_some(); - if stencil_drag || adjusting { - // The stencil or the brush changes instead of the camera + if stencil_drag || adjusting || holding { + // The stencil, the brush or the held Move on model button changes instead of the camera } else if response.dragged_by(PointerButton::Middle) { app.camera_glide = None; app.session.camera.pan(delta.x / size.y, delta.y / size.y); @@ -774,7 +778,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin app.orbit_snap = None; } - if response.hovered() { + if response.hovered() && !holding { size_brush_by_ctrl_wheel(app, ui); if ui.input(|input| input.multi_touch().is_none()) { let pinch = trackpad_pinch(ui); @@ -868,32 +872,12 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // A dismissing click cannot paint or place a decal through the rail popup let rail_popup = crate::rail_popup::blocks_paint_input(app, ui.ctx()); - // Decal placement: a click moves the decal being placed there, unless it dismisses a waiting image drop's menu - let placing = app.placing_decal.filter(|_| app.ui.mode == crate::state::Mode::Painting); - if let Some(target) = placing { - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); - if !alt - && !rail_popup - && !DecalDrop::blocks_input(ui.ctx()) - && response.clicked_by(PointerButton::Primary) - && let Some(pointer) = response.interact_pointer_pos() - { - let (at, viewport) = (local(pointer), app.session.viewport); - let mut params = json!({"x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]}); - - // The id is a decal layer's or a mask fill effect's - params[if app.session.doc.project.effect(target).is_some() { "effect" } else { "layer" }] = json!(target.0); - app.run("layer.decal.set", params); - app.placing_decal = None; - } - } - crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held); + let popup = app.properties_popup.is_some() || rail_popup; // A pending ID color pick takes the next click instead of the brush - let picking_id_color = app.picking_id_color.is_some(); - if picking_id_color { + if picking { crate::id_color_pick::IdColorPick::draw_cursor(ui, rect); if !alt && response.clicked_by(PointerButton::Primary) @@ -904,26 +888,29 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } } - // The selected decal's frame and handles: drag to move, scale or turn it - let decal_drag = !alt - && !s_held - && !v_held - && !focus_pick - && !popup - && placing.is_none() - && !picking_id_color - && touch.is_none() - && !DecalDrop::blocks_input(ui.ctx()) - && decal_input(app, ui, &response, rect); + // The selected fill's frame (planar, warp) or round projector (tri-planar, spherical, cylindrical): only a press on one of its handles moves it + let gizmo_free = + !adjusting && !alt && !holding && !s_held && !v_held && !focus_pick && !popup && !picking && touch.is_none() && !DecalDrop::blocks_input(ui.ctx()); + let gizmo = ShownGizmo::of(app, rect); + let frame_drag = gizmo_free && ShownGizmo::input(app, ui, &response, rect, gizmo.as_ref()); + + // Alt (or another mode) taking the pointer mid-drag ends the drag: let go of Alt, it must not resume from where it began before the camera moved + if !gizmo_free { + ShownGizmo::let_go(ui.ctx()); + } + + // A drag moved the projection: its handles and outline show where it is now + let gizmo = if frame_drag { ShownGizmo::of(app, rect) } else { gizmo }; + + let projection_drag = frame_drag || holding; let plane_pick = !popup && !s_held && !v_held && !focus_pick - && placing.is_none() - && !picking_id_color + && !picking && touch.is_none() && !DecalDrop::blocks_input(ui.ctx()) - && !decal_drag + && !projection_drag && crate::symmetry::plane_pick_input(app, ui, &response, rect); let symmetry_drag = !alt && !plane_pick @@ -932,16 +919,19 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !v_held && !focus_pick && !popup - && placing.is_none() - && !picking_id_color + && !picking && touch.is_none() && !DecalDrop::blocks_input(ui.ctx()) - && !decal_drag + && !projection_drag && crate::symmetry::manipulator_input(app, ui, &response, rect); // A handle owns a new click, but a stroke already under way must still finish over it let symmetry_handle = !app.session.stroke_active() && crate::symmetry::manipulator_hovered(app, ui, rect); + // A projection gizmo's handle owns a press that began on it through its release (the pointer may have left it by then) + let began_on_handle = handle_press(ui.ctx(), |at| gizmo.as_ref().is_some_and(|gizmo| gizmo.on_handle(rect, at))); + let gizmo_handle = gizmo_free && !app.session.stroke_active() && began_on_handle; + // Painting let painting = tool_acts(app) && !popup @@ -950,13 +940,13 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !s_held && !v_held && !focus_pick - && placing.is_none() - && !picking_id_color + && !picking && touch.is_none() - && !decal_drag + && !projection_drag && !plane_pick && !symmetry_drag && !symmetry_handle + && !gizmo_handle && !DecalDrop::blocks_input(ui.ctx()); let path_tool = app.session.tool.tool == Tool::Path; let viewport = app.session.viewport; @@ -1034,6 +1024,8 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && (app.session.tool.tool != Tool::Path || adjusting) && !crate::symmetry::manipulator_hovered(app, ui, rect) && app.picking_id_color.is_none() + && app.moving_on_model.is_none() + && !ShownGizmo::hovered(ui, rect, gizmo.as_ref()) && let Some(hover_pos) = if adjusting { ui.input(|input| input.pointer.press_origin()) } else { response.hover_pos() } && let Some(hit) = app.session.pick(local(hover_pos), app.session.viewport) { @@ -1063,7 +1055,9 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } crate::symmetry::overlay(app, ui, rect, symmetry_cursor); stencil_overlay(app, ui, rect); - decal_overlay(app, ui, rect); + if let Some(gizmo) = &gizmo { + gizmo.overlay(app, ui, rect); + } brush_readout(app, ui, &response, adjusting); if app.session.quick_mask.editing && app.picking_id_color.is_none() { ui.painter_at(rect).text( @@ -1099,237 +1093,6 @@ fn bake_visualization(app: &TextureCraftApp) -> Option egui::CursorIcon { - match self { - DecalGrab::Move => egui::CursorIcon::Move, - DecalGrab::Scale => egui::CursorIcon::ResizeNwSe, - DecalGrab::Rotate if dragging => egui::CursorIcon::Grabbing, - DecalGrab::Rotate => egui::CursorIcon::Grab, - } - } -} - -/// A decal handle being dragged (kept in egui's memory between frames) -#[derive(Clone, Copy, Debug)] -struct DecalDrag { - layer: texturecraft_engine::core::LayerId, - /// The mask fill effect holding the decal, when it was placed as a mask - effect: Option, - grab: DecalGrab, - /// Where the drag started, the decal's center on screen and the decal then - from: Pos2, - center: Pos2, - start: texturecraft_engine::core::Decal, - /// The drag made its undo step: later updates merge into it - stepped: bool, -} - -fn decal_drag_id() -> egui::Id { - egui::Id::unique("tc_decal_drag") -} - -/// Screen distance from the top edge to the rotation handle (points). -const DECAL_KNOB: f32 = 24.0; - -/// The selected decal (a decal layer's content, or a mask decal effect) as the 3D view shows it -struct DecalFrame { - layer: texturecraft_engine::core::LayerId, - /// The selected mask fill effect holding the decal, when it was placed as a mask - effect: Option, - decal: texturecraft_engine::core::Decal, - /// Top left, top right, bottom right, bottom left - corners: [Pos2; 4], - center: Pos2, - /// The middle of the top edge and the rotation handle above it - top: Pos2, - knob: Pos2, -} - -impl DecalFrame { - /// The selected decal: its layer (the mask's owner for an effect), the mask fill effect holding it when placed as a mask, and the decal - fn selected( - app: &TextureCraftApp, - ) -> Option<(texturecraft_engine::core::LayerId, Option, texturecraft_engine::core::Decal)> { - use texturecraft_engine::StackTarget; - use texturecraft_engine::core::{EffectKind, Fill, LayerKind, Projection}; - - if app.ui.mode != crate::state::Mode::Painting { - return None; - } - - let layers = &app.session.doc.project; - let selected = app.session.selected_layer()?; - match app.session.target { - StackTarget::Content => { - let layer = layers.content_layer(selected)?; - let LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) = &layer.kind else { return None }; - - Some((layer.id, None, *decal)) - } - StackTarget::Effect(effect) => { - // Only the selected layer's effective mask may supply a decal frame, including an instance's inherited mask - let owner = layers.mask_owner(selected); - let mask = layers.layer(owner).ok()?.mask.as_ref()?; - let mask_effect = mask.effects.iter().find(|candidate| candidate.id == effect)?; - let EffectKind::Fill { projection: Projection::Decal(decal), .. } = &mask_effect.kind else { return None }; - - Some((owner, Some(effect), *decal)) - } - StackTarget::Mask => None, - } - } - - fn of(app: &TextureCraftApp, rect: Rect) -> Option { - use texturecraft_engine::compose::pattern::{decal_axes, decal_corners}; - - let (layer, effect, decal) = Self::selected(app)?; - let decal = &decal; - let [top_left, top_right, bottom_right, bottom_left] = decal_corners(decal)?.map(|corner| project(app, rect, corner)); - let corners = [top_left?, top_right?, bottom_right?, bottom_left?]; - let center = project(app, rect, decal_axes(decal)?.0)?; - let top = corners[0].lerp(corners[1], 0.5); - let knob = top + (top - center).normalized() * DECAL_KNOB; - Some(DecalFrame { layer, effect, decal: *decal, corners, center, top, knob }) - } - - /// The handle under screen point `p`. - fn grab(&self, p: Pos2) -> Option { - if self.knob.distance(p) <= HANDLE_GRAB { - return Some(DecalGrab::Rotate); - } - if self.corners.iter().any(|c| c.distance(p) <= HANDLE_GRAB) { - return Some(DecalGrab::Scale); - } - // Inside the (convex) frame: on the same side of every edge. - let side = |i: usize| { - let (a, b) = (self.corners[i], self.corners[(i + 1) % 4]); - (b - a).x * (p - a).y - (b - a).y * (p - a).x - }; - let s = [side(0), side(1), side(2), side(3)]; - (s.iter().all(|v| *v >= 0.0) || s.iter().all(|v| *v <= 0.0)).then_some(DecalGrab::Move) - } -} - -/// Drags on the selected decal's frame and handles (one undo step per drag, the decal updates live); returns whether a decal drag owns the pointer -fn decal_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, rect: Rect) -> bool { - let ctx = ui.ctx(); - let frame = DecalFrame::of(app, rect); - let on_frame = |drag: &DecalDrag| frame.as_ref().is_some_and(|frame| frame.layer == drag.layer && frame.effect == drag.effect); - let mut drag = ctx.data(|data| data.get_temp::(decal_drag_id())).filter(on_frame); - if resp.drag_started_by(PointerButton::Primary) - && let (Some(frame), Some(from)) = (&frame, ctx.input(|input| input.pointer.press_origin())) - && let Some(grab) = frame.grab(from) - { - drag = Some(DecalDrag { layer: frame.layer, effect: frame.effect, grab, from, center: frame.center, start: frame.decal, stepped: false }); - } - - let Some(mut drag) = drag.filter(|_| resp.dragged_by(PointerButton::Primary) || resp.drag_started_by(PointerButton::Primary)) else { - ctx.data_mut(|data| data.remove::(decal_drag_id())); - if let (Some(frame), Some(hover)) = (&frame, resp.hover_pos()) - && let Some(grab) = frame.grab(hover) - { - ctx.set_cursor_icon(grab.cursor(false)); - } - return false; - }; - - ctx.set_cursor_icon(drag.grab.cursor(true)); - if let Some(pointer) = resp.interact_pointer_pos().filter(|_| ctx.input(|input| input.pointer.delta() != egui::Vec2::ZERO)) { - let mut params = match drag.grab { - DecalGrab::Move => { - let target = drag.center + (pointer - drag.from) - rect.left_top(); - let viewport = app.session.viewport; - json!({"x": target.x, "y": target.y, "viewport": [viewport.x, viewport.y]}) - } - DecalGrab::Scale => { - let scale = (pointer - drag.center).length() / (drag.from - drag.center).length().max(1.0); - json!({"size": [drag.start.size[0] * scale, drag.start.size[1] * scale]}) - } - DecalGrab::Rotate => { - // Screen y points down: counter-clockwise angles turn the decal's right toward its up - let angle = |offset: egui::Vec2| (-offset.y).atan2(offset.x).to_degrees(); - json!({"rotation": drag.start.rotation + angle(pointer - drag.center) - angle(drag.from - drag.center)}) - } - }; - params["layer"] = json!(drag.layer.0); - if let Some(effect) = drag.effect { - params["effect"] = json!(effect.0); - } - params["merge"] = json!(drag.stepped); - // Off the mesh while moving: the decal waits where it is - drag.stepped |= texturecraft_engine::execute(&mut app.session, "layer.decal.set", ¶ms).is_ok(); - } - ctx.data_mut(|data| data.insert_temp(decal_drag_id(), drag)); - true -} - -/// The frame of the selected decal layer over the 3D view with its handles (and a hint while -/// placing it): outline, corner handles, the rotation handle and the projection direction. -fn decal_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { - if app.ui.mode != crate::state::Mode::Painting { - return; - } - - let tk = Tokens::get(ui.ctx()); - - // Placing follows the selection: another layer or effect selected stops it - let selected_decal = DecalFrame::selected(app).map(|(layer, effect, _)| effect.unwrap_or(layer)); - if app.placing_decal.is_some() && app.placing_decal != selected_decal { - app.placing_decal = None; - } - let painter = ui.painter_at(rect); - let hint_at = rect.left_top() + vec2(12.0, 40.0); - if app.placing_decal.is_some() { - let hint = tr("Click the mesh to place the decal"); - painter.text(hint_at, egui::Align2::LEFT_TOP, hint, egui::FontId::proportional(12.0), tk.viewport_accent); - } - let Some(f) = DecalFrame::of(app, rect) else { return }; - let active = ui.ctx().data(|d| d.get_temp::(decal_drag_id())).map(|d| d.grab); - let hovered = ui.ctx().pointer_hover_pos().filter(|h| rect.contains(*h)).and_then(|h| f.grab(h)); - if app.placing_decal.is_none() && (hovered.is_some() || active.is_some()) { - let hint = tr("Drag the frame to move the decal, a corner to scale it, the round handle to turn it"); - painter.text(hint_at, egui::Align2::LEFT_TOP, hint, egui::FontId::proportional(12.0), tk.viewport_text); - } - let shadow = Stroke::new(3.0, Color32::from_black_alpha(140)); - let mut outline = f.corners.to_vec(); - outline.push(f.corners[0]); - let frame_color = if active == Some(DecalGrab::Move) || hovered == Some(DecalGrab::Move) { tk.viewport_accent } else { Color32::from_white_alpha(220) }; - for stroke in [shadow, Stroke::new(1.2, frame_color)] { - painter.add(egui::Shape::dashed_line(&outline, stroke, 6.0, 4.0)); - } - - // The projection direction from the center - if let Some((o, _, _, n)) = texturecraft_engine::compose::pattern::decal_axes(&f.decal) - && let Some(tip) = project(app, rect, o + n * f.decal.size[0].max(f.decal.size[1]) * 0.25) - { - painter.line_segment([f.center, tip], shadow); - painter.line_segment([f.center, tip], Stroke::new(1.4, tk.viewport_accent)); - } - painter.circle(f.center, 3.5, tk.viewport_accent, Stroke::new(1.0, Color32::from_black_alpha(180))); - - // Handles: white, the one under the pointer or being dragged in the accent color - let fill = |g: DecalGrab| if active == Some(g) || (active.is_none() && hovered == Some(g)) { tk.viewport_accent } else { Color32::WHITE }; - let edge = Stroke::new(1.0, Color32::from_black_alpha(200)); - painter.line_segment([f.top, f.knob], shadow); - painter.line_segment([f.top, f.knob], Stroke::new(1.4, Color32::from_white_alpha(220))); - painter.circle(f.knob, 5.0, fill(DecalGrab::Rotate), edge); - for c in f.corners { - painter.rect(Rect::from_center_size(c, vec2(8.0, 8.0)), 1.0, fill(DecalGrab::Scale), edge, egui::StrokeKind::Middle); - } -} - /// Draw the projection stencil in Paint Mode fn stencil_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { if !tool_acts(app) || app.session.tool.tool != Tool::Projection { @@ -1369,6 +1132,17 @@ pub(crate) fn project(app: &TextureCraftApp, rect: Rect, point: Vec3) -> Option< Some(pos2(rect.left() + (ndc.x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - ndc.y * 0.5) * rect.height())) } +/// The camera ray through screen point `p` of the 3D view `rect` +pub(crate) fn view_ray(app: &TextureCraftApp, rect: Rect, p: Pos2) -> texturecraft_engine::geom::Ray { + let ndc = Vec2::new((p.x - rect.left()) / rect.width() * 2.0 - 1.0, 1.0 - (p.y - rect.top()) / rect.height() * 2.0); + app.session.camera.ray(ndc, rect.width() / rect.height().max(1.0)) +} + +/// Whether the window lost the focus (Alt+Tab): egui keeps a held button down with no release to come, so a drag ends here as on a release +pub(crate) fn focus_lost(ctx: &egui::Context) -> bool { + ctx.input(|input| input.viewport().focused == Some(false) || input.events.iter().any(|event| matches!(event, egui::Event::WindowFocused(false)))) +} + /// Control point and curve grab radius (points) const HANDLE_GRAB: f32 = 8.0; /// Opacity of the selected layer's other stored paths @@ -1967,6 +1741,30 @@ fn scale_brush_by_wheel(app: &mut TextureCraftApp, scroll: f32) { brush.size = (brush.size * (1.0 + scroll * WHEEL_BRUSH_SIZE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } +/// Whether the press under way, or released this frame, began on a projection handle (`on_handle`); with no press, whether the pointer is on one +fn handle_press(ctx: &egui::Context, on_handle: impl Fn(Pos2) -> bool) -> bool { + let id = egui::Id::unique(HANDLE_PRESS_ID); + let (pressed, down, released, origin, hover) = ctx.input(|input| { + let pointer = &input.pointer; + (pointer.any_pressed(), pointer.any_down(), pointer.any_released(), pointer.press_origin(), pointer.hover_pos()) + }); + + // Kept from the press frame: egui forgets the press origin on the release frame, where a short drift still makes a click + if pressed { + let on = origin.is_some_and(&on_handle); + ctx.data_mut(|data| data.insert_temp(id, on)); + } + let kept = ctx.data(|data| data.get_temp::(id)).filter(|_| down || released); + if !down { + ctx.data_mut(|data| data.remove::(id)); + } + + kept.unwrap_or_else(|| (if down { origin } else { hover }).is_some_and(on_handle)) +} + +/// Where [`handle_press`] keeps whether the press began on a handle +const HANDLE_PRESS_ID: &str = "projection_handle_press"; + /// Ctrl (Cmd on macOS) + drag changes the brush instead of painting: true while it applies (see `adjust_brush`) fn brush_drag(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) -> bool { // Ctrl+Shift+left is not a brush change: it is left to the snapped straight line @@ -2253,7 +2051,9 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } app.ui.uv_zoom = new_zoom; } - if response.hovered() { + + // A held Move on model button takes the wheel + if response.hovered() && app.moving_on_model.is_none() { size_brush_by_ctrl_wheel(app, ui); let scroll = wheel_scroll(ui, shift); if scroll != 0.0 && shift && wheel_sizes_brush(app) { @@ -2857,7 +2657,7 @@ mod tests { harness.state_mut().run("layer.add.decal", json!({"image": image, "channel": "mask", "size": 0.5})).unwrap(); harness.run_steps(2); assert_eq!(harness.state().session.ts(), 0); - assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_some()); + assert!(crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_some()); harness } @@ -2883,7 +2683,7 @@ mod tests { for texture_set in [0, 1] { let mut harness = decal_frame_app(false); - let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let original = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); let effect = original.effect.unwrap(); let session = &mut harness.state_mut().session; execute(session, "textureSet.select", &json!({"ts": texture_set})).unwrap(); @@ -2896,14 +2696,14 @@ mod tests { assert_eq!(session.ts(), texture_set); assert_eq!(session.selected_layer().unwrap().0, other.as_u64().unwrap()); assert_eq!(session.target, StackTarget::Effect(effect), "the failed selection leaves the previous effect target"); - assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_none(), "a stale effect must not show a decal frame"); + assert!(crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "a stale effect must not show a decal frame"); drag_decal_handle(&mut harness, original.corners[1], original.center + (original.corners[1] - original.center) * 1.5); - drag_decal_handle(&mut harness, original.knob, original.knob + vec2(40.0, 0.0)); + drag_decal_handle(&mut harness, original.center, original.center + vec2(40.0, 0.0)); let effect = &harness.state().session.doc.project.effect(effect).unwrap().1.kind; assert!( - matches!(effect, texturecraft_engine::core::EffectKind::Fill { projection: texturecraft_engine::core::Projection::Decal(decal), .. } if *decal == original.decal) + matches!(effect, texturecraft_engine::core::EffectKind::Fill { projection: texturecraft_engine::core::Projection::Planar { placed: Some(decal), .. }, .. } if *decal == original.decal) ); } } @@ -2915,7 +2715,7 @@ mod tests { use texturecraft_engine::execute; let mut harness = decal_frame_app(false); - let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let original = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); let effect = original.effect.unwrap(); let session = &mut harness.state_mut().session; let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); @@ -2925,12 +2725,12 @@ mod tests { assert_eq!(session.ts(), 1); assert_eq!(session.selected_layer().unwrap().0, instance.as_u64().unwrap()); - let inherited = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let inherited = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); assert_eq!((inherited.layer, inherited.effect, inherited.decal), (original.layer, original.effect, original.decal)); drag_decal_handle(&mut harness, inherited.corners[1], inherited.center + (inherited.corners[1] - inherited.center) * 1.5); - let edited = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let edited = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); assert!(edited.decal.size[0] > original.decal.size[0], "scaling an inherited decal edits its source"); } @@ -2941,7 +2741,7 @@ mod tests { use texturecraft_engine::execute; let mut harness = decal_frame_app(false); - let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let original = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); let effect = original.effect.unwrap(); let session = &mut harness.state_mut().session; let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); @@ -2950,7 +2750,7 @@ mod tests { assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err()); - assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_none(), "an override hides the source's mask decal"); + assert!(crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "an override hides the source's mask decal"); } #[test] @@ -2964,14 +2764,14 @@ mod tests { std::fs::create_dir_all(&directory).unwrap(); let mut harness = decal_frame_app(true); - let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let original = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); let effect = original.effect.unwrap(); let session = &mut harness.state_mut().session; let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err()); harness.run_steps(6); - assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_some()); + assert!(crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_some()); harness.render().unwrap().save(directory.join("decal-frame-inherited.png")).unwrap(); let session = &mut harness.state_mut().session; @@ -2980,7 +2780,7 @@ mod tests { assert!(execute(session, "layer.select", &json!({"layer": other, "target": effect.0})).is_err()); harness.run_steps(6); - assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_none()); + assert!(crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none()); harness.render().unwrap().save(directory.join("decal-frame-stale.png")).unwrap(); } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index ef2455a1..9891dcc8 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -21,6 +21,18 @@ pub fn slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeI slider_inner(ui, label, value, range, decimals).0 } +/// For an editor `id` drawn every frame: `Some(merge)` when it `changed`, merge true for a press's later changes (one undo step per drag; typing never merges) +pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option { + let held = ui.input(|input| input.pointer.any_down()); + if !held { + // The press is over: the next one starts its own undo step + ui.data_mut(|data| data.remove_temp::(id)); + return changed.then_some(false); + } + + changed.then(|| ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::(id), true))) +} + /// [`slider`] for a value re-read from the document every frame: `Some(merge)` on every frame /// that changes `value` (live while dragging, a click on the track, a typed value). `merge` is /// true for the later changes of one drag, so the edit that applies them (with the command's @@ -29,16 +41,28 @@ pub fn slider_edit(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::R slider_inner(ui, label, value, range, decimals).1 } +/// Least width of a slider's value field, wide enough for a short number +const SLIDER_VALUE_MIN_WIDTH: f32 = 44.0; + +/// Height of a slider's track row +const SLIDER_TRACK_HEIGHT: f32 = 14.0; + +/// From the track row's sides to the track's ends, so the knob stays inside the row +const SLIDER_TRACK_INSET: f32 = 5.0; + +/// Thickness of a slider's rail and its knob's radius +const SLIDER_RAIL_WIDTH: f32 = 2.0; +const SLIDER_KNOB_RADIUS: f32 = 4.5; + /// The row above a slider's track, `label` and `value` as a field to type in: the field's id, and `Some(false)` on the frame a typed value replaces `value` pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (egui::Id, Option) { - const MIN_VALUE_WIDTH: f32 = 44.0; let tokens = Tokens::get(ui.ctx()); let (minimum, maximum) = (*range.start(), *range.end()); let font = egui::TextStyle::Body.resolve(ui.style()); let value_width = [minimum, maximum] .into_iter() .map(|bound| ui.painter().layout_no_wrap(format!("{bound:.decimals$}"), font.clone(), tokens.text).size().x) - .fold(MIN_VALUE_WIDTH, f32::max); + .fold(SLIDER_VALUE_MIN_WIDTH, f32::max); let mut edit = None; let field = ui .horizontal(|ui| { @@ -58,7 +82,7 @@ pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std .frame(egui::Frame::NONE), ); if response.has_focus() { - ui.data_mut(|data| data.insert_temp(id, text.clone())); + ui.data_mut(|data| data.insert_temp(id, text)); } else { ui.data_mut(|data| data.remove_temp::(id)); @@ -85,14 +109,10 @@ pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std } fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (Response, Option) { - const TRACK_HEIGHT: f32 = 14.0; - const TRACK_INSET: f32 = 5.0; - const TRACK_WIDTH: f32 = 2.0; - const KNOB_RADIUS: f32 = 4.5; let (minimum, maximum) = (*range.start(), *range.end()); let width = ui.available_width(); let (field, mut edit) = value_header(ui, label, value, range, decimals); - let (rect, mut response) = ui.allocate_exact_size(vec2(width, TRACK_HEIGHT), Sense::click_and_drag()); + let (rect, mut response) = ui.allocate_exact_size(vec2(width, SLIDER_TRACK_HEIGHT), Sense::click_and_drag()); if response.is_pointer_button_down_on() { ui.data_mut(|data| data.remove_temp::(field)); ui.memory_mut(|memory| memory.surrender_focus(field)); @@ -100,25 +120,26 @@ fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Rang if edit.is_some() { response.mark_changed(); } + + let mut moved = false; if (response.dragged() || response.clicked()) && let Some(pointer) = response.interact_pointer_pos() { - let fraction = ((pointer.x - rect.left() - TRACK_INSET) / (rect.width() - TRACK_INSET * 2.0).max(1.0)).clamp(0.0, 1.0); + let fraction = ((pointer.x - rect.left() - SLIDER_TRACK_INSET) / (rect.width() - 2.0 * SLIDER_TRACK_INSET).max(1.0)).clamp(0.0, 1.0); let next = minimum + (maximum - minimum) * fraction; if (next - *value).abs() > f32::EPSILON { *value = next; response.mark_changed(); - - // Later frames of one drag share its undo step - edit = Some(ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::(response.id), true))); + moved = true; } } - if response.drag_stopped() || response.clicked() { - ui.data_mut(|data| data.remove_temp::(response.id)); - } + + // Later frames of one drag share its undo step, and a drag wins over typing in the same frame + edit = press_edit(ui, response.id, moved).or(edit); let fraction = if maximum > minimum { ((*value - minimum) / (maximum - minimum)).clamp(0.0, 1.0) } else { 0.0 }; - track(ui, &response, rect.left() + TRACK_INSET..=rect.right() - TRACK_INSET, rect.center().y, fraction, TRACK_WIDTH, KNOB_RADIUS); + let track_ends = rect.left() + SLIDER_TRACK_INSET..=rect.right() - SLIDER_TRACK_INSET; + track(ui, &response, track_ends, rect.center().y, fraction, SLIDER_RAIL_WIDTH, SLIDER_KNOB_RADIUS); (response, edit) } @@ -474,22 +495,25 @@ fn color_picker(ui: &mut Ui, id: egui::Id, c: &mut Color32, width: f32) -> bool changed } -/// Fill `rect` with `rgb(x, y)` (sRGB 0..1 over 0..1 across and down), as a shaded mesh. +/// Fill `rect` with `rgb(x, y)` (sRGB 0..1 over 0..1 across and down), as a shaded mesh fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> [f32; 3]) { - const N: u32 = 24; + /// Cells across and down: fine enough that a hue strip's six ramps read smooth + const GRID_CELLS: u32 = 24; + let mut mesh = egui::Mesh::default(); - for j in 0..=N { - for i in 0..=N { - let (x, y) = (i as f32 / N as f32, j as f32 / N as f32); - let [r, g, b] = rgb(x, y).map(|c| (c.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + for j in 0..=GRID_CELLS { + for i in 0..=GRID_CELLS { + let (x, y) = (i as f32 / GRID_CELLS as f32, j as f32 / GRID_CELLS as f32); + let [r, g, b] = rgb(x, y).map(|component| (component.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); mesh.colored_vertex(rect.lerp_inside(vec2(x, y)), Color32::from_rgb(r, g, b)); } } - for j in 0..N { - for i in 0..N { - let k = j * (N + 1) + i; - mesh.add_triangle(k, k + 1, k + N + 1); - mesh.add_triangle(k + 1, k + N + 2, k + N + 1); + for j in 0..GRID_CELLS { + for i in 0..GRID_CELLS { + let top_left = j * (GRID_CELLS + 1) + i; + let bottom_left = top_left + GRID_CELLS + 1; + mesh.add_triangle(top_left, top_left + 1, bottom_left); + mesh.add_triangle(top_left + 1, bottom_left + 1, bottom_left); } } painter.add(mesh); diff --git a/crates/ui-egui/tests/it/decal_proportions.rs b/crates/ui-egui/tests/it/decal_proportions.rs deleted file mode 100644 index aa267486..00000000 --- a/crates/ui-egui/tests/it/decal_proportions.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! A decal's Width and Height keep the image's proportions, and Flip U / Flip V mirror its image - -use egui::accesskit::Role; -use egui_kittest::Harness; -use egui_kittest::kittest::{Queryable, by}; -use serde_json::json; -use texturecraft_engine::core::{Decal, LayerId, LayerKind, Projection}; -use texturecraft_ui_egui::TextureCraftApp; - -/// Frames for a click or a typed value to reach the document and the panel -const SETTLE_FRAMES: usize = 3; - -/// The longest text a side's number field shows, cleared before typing a value -const FIELD_TEXT_LIMIT: usize = 12; - -/// The sample app with a decal of a twice-as-wide-as-tall image selected, and its layer -fn app_with_decal() -> (Harness<'static, TextureCraftApp>, LayerId) { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut png = Vec::new(); - image::RgbaImage::from_pixel(8, 4, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); - let name = session.import_resource_bytes("wide.png", png).unwrap(); - let placed = texturecraft_engine::execute( - &mut session, - "layer.add.decal", - &json!({"image": name, "position": [0.0, 0.0, 0.0], "normal": [0.0, 0.0, 1.0], "up": [0.0, 1.0, 0.0], "size": [0.8, 0.4]}), - ) - .unwrap(); - let layer = LayerId(placed["layer"].as_u64().unwrap()); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - - // The labels below are English; a first run would speak the system's language - harness.state_mut().ui.prefs.language = "en".into(); - harness.run_steps(4); - (harness, layer) -} - -fn decal(harness: &Harness<'_, TextureCraftApp>, layer: LayerId) -> Decal { - let LayerKind::Fill(fill) = &harness.state().session.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; - let Projection::Decal(decal) = &fill.projection else { panic!("a decal") }; - *decal -} - -/// Type `value` into the number field of the row labelled `label` and confirm it -fn type_side(harness: &mut Harness<'_, TextureCraftApp>, label: &str, value: &str) { - let field = |harness: &Harness<'_, TextureCraftApp>| { - let row = harness.get_by_label(label).rect().center().y; - harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).map(|node| node.rect().center()).unwrap() - }; - harness.drag_at(field(harness)); - harness.drop_at(field(harness)); - harness.run_steps(2); - harness.key_press(egui::Key::End); - for _ in 0..FIELD_TEXT_LIMIT { - harness.key_press(egui::Key::Backspace); - harness.run_steps(1); - } - for character in value.chars() { - harness.get_all(by().role(Role::TextInput)).find(|node| node.is_focused()).unwrap().type_text(&character.to_string()); - harness.run_steps(1); - } - harness.key_press(egui::Key::Enter); - harness.run_steps(SETTLE_FRAMES); -} - -#[test] -fn width_and_height_follow_each_other_by_the_image_aspect() { - let (mut harness, layer) = app_with_decal(); - - type_side(&mut harness, "Width", "0.6"); - assert_eq!(decal(&harness, layer).size, [0.6, 0.3], "the width sets the height"); - - type_side(&mut harness, "Height", "0.1"); - assert_eq!(decal(&harness, layer).size, [0.2, 0.1], "the height sets the width"); -} - -#[test] -fn unticking_keep_proportions_frees_each_side() { - let (mut harness, layer) = app_with_decal(); - harness.get_by_label("Keep proportions").click(); - harness.run_steps(SETTLE_FRAMES); - - type_side(&mut harness, "Width", "0.6"); - assert_eq!(decal(&harness, layer).size, [0.6, 0.4], "only the width changes"); - - // Ticking it again fits the height to the width, in one undo step - let steps = harness.state().session.history_labels().len(); - harness.get_by_label("Keep proportions").click(); - harness.run_steps(SETTLE_FRAMES); - assert_eq!(decal(&harness, layer).size, [0.6, 0.3]); - assert_eq!(harness.state().session.history_labels().len(), steps + 1); -} - -#[test] -fn flip_toggles_mirror_the_image_and_undo_one_step_at_a_time() { - let (mut harness, layer) = app_with_decal(); - assert_eq!(decal(&harness, layer).flip, [false, false]); - - harness.get_by_label("Flip U").click(); - harness.run_steps(SETTLE_FRAMES); - assert_eq!(decal(&harness, layer).flip, [true, false]); - - harness.get_by_label("Flip V").click(); - harness.run_steps(SETTLE_FRAMES); - assert_eq!(decal(&harness, layer).flip, [true, true]); - - harness.get_by_label("Flip U").click(); - harness.run_steps(SETTLE_FRAMES); - assert_eq!(decal(&harness, layer).flip, [false, true], "Flip U toggles back and leaves Flip V"); - - texturecraft_engine::execute(&mut harness.state_mut().session, "edit.undo", &json!({})).unwrap(); - harness.run_steps(SETTLE_FRAMES); - assert_eq!(decal(&harness, layer).flip, [true, true]); -} diff --git a/crates/ui-egui/tests/it/decal_symmetry.rs b/crates/ui-egui/tests/it/decal_symmetry.rs deleted file mode 100644 index e97a24a8..00000000 --- a/crates/ui-egui/tests/it/decal_symmetry.rs +++ /dev/null @@ -1,106 +0,0 @@ -//! The decal editor's Mirror across and Flip controls set the decal's mirrored copy - -use egui::accesskit::Role; -use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; -use serde_json::json; -use texturecraft_engine::core::{DecalFlip, LayerKind, Projection}; -use texturecraft_ui_egui::TextureCraftApp; - -/// Tall enough that Properties shows the whole decal editor without scrolling -const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 1700.0); - -/// Small texture and bake sizes keep the sample session fast; the panel doesn't depend on them -const TEXTURE_RESOLUTION: u32 = 256; -const BAKE_RESOLUTION: u32 = 64; - -/// Frames for the first layout and fonts to settle -const STARTUP_FRAMES: usize = 4; - -/// Frames for a click or selection change to reach the panel -const SETTLE_FRAMES: usize = 3; - -fn red_png() -> Vec { - let mut out = Vec::new(); - image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); - out -} - -/// The app with a new decal layer selected in Properties, and its layer id -fn app_with_decal() -> (Harness<'static, TextureCraftApp>, u64) { - let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); - let image = session.import_resource_bytes("logo.png", red_png()).unwrap(); - let placed = json!({"image": image, "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0], "up": [0.0, 0.0, 1.0], "size": 0.3}); - let layer = texturecraft_engine::execute(&mut session, "layer.add.decal", &placed).unwrap()["layer"].as_u64().unwrap(); - - let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); - - // The labels below are English; a first run would speak the system's language - harness.state_mut().ui.prefs.language = "en".into(); - harness.run_steps(STARTUP_FRAMES); - (harness, layer) -} - -fn offset_of(harness: &Harness<'_, TextureCraftApp>, layer: u64) -> f32 { - let project = &harness.state().session.doc.project; - let LayerKind::Fill(fill) = &project.layer(texturecraft_engine::core::LayerId(layer)).unwrap().kind else { panic!("a fill layer") }; - let Projection::Decal(decal) = &fill.projection else { panic!("a decal") }; - decal.symmetry.expect("a mirrored copy").offset -} - -fn symmetry_of(harness: &Harness<'_, TextureCraftApp>, layer: u64) -> Option<(u8, DecalFlip)> { - let project = &harness.state().session.doc.project; - let LayerKind::Fill(fill) = &project.layer(texturecraft_engine::core::LayerId(layer)).unwrap().kind else { panic!("a fill layer") }; - let Projection::Decal(decal) = &fill.projection else { panic!("a decal") }; - decal.symmetry.map(|symmetry| (symmetry.axis, symmetry.flip)) -} - -/// Opens the combo showing `current` and picks `choice` in its menu -fn pick(harness: &mut Harness<'_, TextureCraftApp>, current: &str, choice: &str) { - harness.get_all_by_role(Role::ComboBox).find(|combo| combo.value().as_deref() == Some(current)).expect("the combo").click(); - harness.run_steps(SETTLE_FRAMES); - harness.get_all_by_label(choice).last().expect("the menu entry").click(); - harness.run_steps(SETTLE_FRAMES); -} - -#[test] -fn the_mirror_axis_and_flip_are_set_from_the_decal_editor() { - let (mut harness, layer) = app_with_decal(); - assert!(harness.query_by_label("Mirror across").is_some()); - assert!(harness.query_by_label("Flip the copy's image").is_none(), "the flip needs a copy to flip"); - assert_eq!(symmetry_of(&harness, layer), None); - - pick(&mut harness, "Off", "X"); - assert_eq!(symmetry_of(&harness, layer), Some((0, DecalFlip::None))); - assert!(harness.query_by_label("Flip the copy's image").is_some()); - - pick(&mut harness, "None", "V"); - assert_eq!(symmetry_of(&harness, layer), Some((0, DecalFlip::V))); - - pick(&mut harness, "X", "Z"); - assert_eq!(symmetry_of(&harness, layer), Some((2, DecalFlip::V)), "a new axis keeps the flip"); - - pick(&mut harness, "Z", "Off"); - assert_eq!(symmetry_of(&harness, layer), None); - assert!(harness.query_by_label("Flip the copy's image").is_none()); -} - -#[test] -fn the_axis_position_slider_moves_the_mirror_plane() { - let (mut harness, layer) = app_with_decal(); - assert!(harness.query_by_label("Axis position").is_none(), "the position needs a copy to place"); - pick(&mut harness, "Off", "Y"); - assert_eq!(offset_of(&harness, layer), 0.0); - - // Press near the track's left end, drag toward its middle and right, release there - let label_rect = harness.get_by_label("Axis position").rect(); - let y = label_rect.bottom() + 10.0; - harness.drag_at(egui::pos2(label_rect.left() + 20.0, y)); - harness.run_steps(2); - harness.hover_at(egui::pos2(label_rect.left() + 120.0, y)); - harness.run_steps(2); - harness.drop_at(egui::pos2(label_rect.left() + 120.0, y)); - harness.run_steps(SETTLE_FRAMES); - assert!(offset_of(&harness, layer).abs() > 0.01, "the dragged position applies: {}", offset_of(&harness, layer)); - assert_eq!(symmetry_of(&harness, layer).map(|symmetry| symmetry.0), Some(1), "the axis is kept"); -} diff --git a/crates/ui-egui/tests/it/effect_decal.rs b/crates/ui-egui/tests/it/effect_decal.rs deleted file mode 100644 index 101fac1c..00000000 --- a/crates/ui-egui/tests/it/effect_decal.rs +++ /dev/null @@ -1,65 +0,0 @@ -//! A decal held by a mask fill effect has the same editor as a layer's decal: sliders and the placing click - -use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; -use serde_json::json; -use texturecraft_engine::core::{Decal, EffectKind, LayerId, Projection}; -use texturecraft_ui_egui::TextureCraftApp; - -/// The sample session with a new decal mask fill effect selected, and that effect's id -fn selected_mask_decal() -> (Harness<'static, TextureCraftApp>, LayerId) { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - let image = { - let mut png = Vec::new(); - image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); - session.import_resource_bytes("decal.png", png).unwrap() - }; - let placed = json!({"image": image, "channel": "mask", "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0], "up": [0.0, 0.0, 1.0], "size": 0.5}); - let effect = LayerId(texturecraft_engine::execute(&mut session, "layer.add.decal", &placed).unwrap()["maskEffect"].as_u64().unwrap()); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); - harness.state_mut().ui.prefs.language = "en".into(); - harness.run_steps(4); - (harness, effect) -} - -fn decal(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Decal { - match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { - EffectKind::Fill { projection: Projection::Decal(decal), .. } => *decal, - _ => panic!("a decal fill effect"), - } -} - -#[test] -fn the_width_slider_resizes_a_mask_effects_decal_in_one_undo_step() { - let (mut harness, effect) = selected_mask_decal(); - - // Free width and height: with Keep proportions (on by default) the height would follow - harness.get_by_label("Keep proportions").click(); - harness.run_steps(2); - let before = decal(&harness, effect); - let steps = harness.state().session.history_labels().len(); - - let label_rect = harness.get_by_label("Width").rect(); - let y = label_rect.bottom() + 10.0; - harness.drag_at(egui::pos2(label_rect.left() + 10.0, y)); - harness.run_steps(2); - harness.hover_at(egui::pos2(label_rect.left() + 150.0, y)); - harness.run_steps(2); - harness.drop_at(egui::pos2(label_rect.left() + 150.0, y)); - harness.run_steps(3); - - let after = decal(&harness, effect); - assert!(after.size[0] > before.size[0], "the dragged width applies: {} -> {}", before.size[0], after.size[0]); - assert_eq!(after.size[1], before.size[1]); - assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); - harness.state_mut().run("edit.undo", json!({})).unwrap(); - assert_eq!(decal(&harness, effect), before); -} - -#[test] -fn place_on_the_surface_stays_armed_for_a_mask_effects_decal() { - let (mut harness, effect) = selected_mask_decal(); - harness.get_by_label_contains("Place on the surface").click(); - harness.run_steps(3); - assert_eq!(harness.state().placing_decal, Some(effect), "the click arms placing for the effect, not its layer"); -} diff --git a/crates/ui-egui/tests/it/fill_projection_section.rs b/crates/ui-egui/tests/it/fill_projection_section.rs deleted file mode 100644 index 983f1bc5..00000000 --- a/crates/ui-egui/tests/it/fill_projection_section.rs +++ /dev/null @@ -1,102 +0,0 @@ -//! A fill's projection settings fold into a "UV transformations" section under the Projection combo - -use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; -use serde_json::json; -use texturecraft_ui_egui::TextureCraftApp; - -/// Tall enough that Properties shows the whole fill without scrolling -const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 1400.0); - -/// Small texture and bake sizes keep the sample session fast; the panel doesn't depend on them -const TEXTURE_RESOLUTION: u32 = 256; -const BAKE_RESOLUTION: u32 = 64; - -/// Frames for the first layout and fonts to settle -const STARTUP_FRAMES: usize = 4; - -/// Frames for a click or selection change to reach the panel -const SETTLE_FRAMES: usize = 3; - -/// The app with a new fill layer (projected as `projection`) selected in Properties, and its layer id -fn app_with_fill(projection: &str) -> (Harness<'static, TextureCraftApp>, u64) { - let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); - let added = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({})).unwrap(); - let layer = added["layer"].as_u64().unwrap(); - texturecraft_engine::execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": projection})).unwrap(); - - let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); - // The labels below are English; a first run would speak the system's language - harness.state_mut().ui.prefs.language = "en".into(); - harness.run_steps(STARTUP_FRAMES); - (harness, layer) -} - -fn toggle_section(harness: &mut Harness<'_, TextureCraftApp>) { - harness.get_by_label("UV transformations").click(); - harness.run_steps(SETTLE_FRAMES); -} - -#[test] -fn the_uv_transformations_start_open_and_fold_away() { - let (mut harness, _) = app_with_fill("uv"); - assert!(harness.query_by_label("Rotation").is_some()); - - toggle_section(&mut harness); - assert!(harness.query_by_label("Rotation").is_none()); - assert!(harness.query_by_label("Scale / tiling").is_none()); - assert!(harness.query_by_label("Projection").is_some()); - - toggle_section(&mut harness); - assert!(harness.query_by_label("Rotation").is_some()); -} - -#[test] -fn hardness_and_axis_stay_outside_the_section() { - let (mut harness, _) = app_with_fill("triplanar"); - toggle_section(&mut harness); - assert!(harness.query_by_label("Offset X").is_none()); - assert!(harness.query_by_label("Hardness").is_some()); - - let (mut harness, _) = app_with_fill("planar"); - toggle_section(&mut harness); - assert!(harness.query_by_label("Offset X").is_none()); - assert!(harness.query_by_label("Axis").is_some()); - - let (mut harness, _) = app_with_fill("cylindrical"); - toggle_section(&mut harness); - assert!(harness.query_by_label("Scale / tiling").is_none()); - assert!(harness.query_by_label("Axis").is_some()); -} - -#[test] -fn each_fill_keeps_its_own_open_state() { - let (mut harness, first) = app_with_fill("uv"); - toggle_section(&mut harness); - - let added = texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.fill", &json!({})).unwrap(); - let second = added["layer"].as_u64().unwrap(); - texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": second})).unwrap(); - harness.run_steps(SETTLE_FRAMES); - assert!(harness.query_by_label("Rotation").is_some(), "a new fill starts open"); - - texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": first})).unwrap(); - harness.run_steps(SETTLE_FRAMES); - assert!(harness.query_by_label("Rotation").is_none(), "the first fill stays closed"); -} - -#[test] -fn a_fill_effect_keeps_a_state_apart_from_its_layer() { - let (mut harness, layer) = app_with_fill("uv"); - toggle_section(&mut harness); - - let session = &mut harness.state_mut().session; - let added = texturecraft_engine::execute(session, "effect.add.fill", &json!({"layer": layer, "target": "content"})).unwrap(); - let effect = added["effect"].as_u64().unwrap(); - texturecraft_engine::execute(session, "layer.select", &json!({"layer": layer, "target": effect})).unwrap(); - harness.run_steps(SETTLE_FRAMES); - assert!(harness.query_by_label("Rotation").is_some(), "the effect's section starts open"); - - toggle_section(&mut harness); - assert!(harness.query_by_label("Rotation").is_none()); -} diff --git a/crates/ui-egui/tests/it/fill_support.rs b/crates/ui-egui/tests/it/fill_support.rs new file mode 100644 index 00000000..6adf3212 --- /dev/null +++ b/crates/ui-egui/tests/it/fill_support.rs @@ -0,0 +1,52 @@ +//! What the fill screens' tests share: the sample app with a new fill selected, the fill as the document holds it, and real pointer clicks on its controls + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::{Fill, LayerId, LayerKind}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::filter_support::click_at; +use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// The app `window` big with a new fill layer (`settings` given to layer.add.fill, then projected as `projection`) selected in Properties, `tab` clicked, and the layer's id +pub(crate) fn fill_app(settings: Value, projection: Option<&str>, tab: Option<&str>, window: egui::Vec2) -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let added = texturecraft_engine::execute(&mut session, "layer.add.fill", &settings).unwrap(); + let layer = added["layer"].as_u64().unwrap(); + if let Some(projection) = projection { + texturecraft_engine::execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": projection})).unwrap(); + } + let mut harness = Harness::builder().with_size(window).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + if let Some(tab) = tab { + click_node(&mut harness, Role::Tab, tab); + } + (harness, LayerId(layer)) +} + +/// The fill layer as the document holds it +pub(crate) fn fill_of(harness: &Harness<'_, TextureCraftApp>, layer: LayerId) -> Fill { + match &harness.state().session.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(fill) => fill.clone(), + other => panic!("not a fill: {other:?}"), + } +} + +/// A real pointer click in the middle of the `role` named `label`, then frames for the edit to show +pub(crate) fn click_node(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + let at = harness.get_by_role_and_label(role, label).rect().center(); + click_at(harness, at); + harness.run_steps(SETTLE_FRAMES); +} + +/// A real pointer click in the middle of the widget named `label`, whatever its role +pub(crate) fn click_label(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + let at = harness.get_by_label(label).rect().center(); + click_at(harness, at); + harness.run_steps(SETTLE_FRAMES); +} diff --git a/crates/ui-egui/tests/it/filter_support.rs b/crates/ui-egui/tests/it/filter_support.rs new file mode 100644 index 00000000..912e2017 --- /dev/null +++ b/crates/ui-egui/tests/it/filter_support.rs @@ -0,0 +1,51 @@ +//! Helpers the filter panel tests share + +use egui_kittest::Harness; +use texturecraft_ui_egui::TextureCraftApp; + +/// A real pointer click at `pos`: move there, press, one frame, release, then frames for the edit to show +pub(crate) fn click_at(harness: &mut Harness<'_, TextureCraftApp>, pos: egui::Pos2) { + let modifiers = egui::Modifiers::NONE; + harness.event(egui::Event::PointerMoved(pos)); + harness.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(3); +} + +/// A press at `from`, a drag to `to` in steps and a release, as the pointer does it +pub(crate) fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: egui::Pos2, to: egui::Pos2) { + let steps: Vec = (1..=DRAG_STEPS).map(|step| from + (to - from) * (step as f32 / DRAG_STEPS as f32)).collect(); + drag_through(harness, from, &steps); +} + +/// A press at `from`, a move to each of `steps` (one frame each) and a release at the last, as the pointer does it +pub(crate) fn drag_through(harness: &mut Harness<'_, TextureCraftApp>, from: egui::Pos2, steps: &[egui::Pos2]) { + let modifiers = egui::Modifiers::NONE; + harness.event(egui::Event::PointerMoved(from)); + harness.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(1); + for step in steps { + harness.event(egui::Event::PointerMoved(*step)); + harness.run_steps(1); + } + let to = steps.last().copied().unwrap_or(from); + harness.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(2); +} + +/// How far a slider's track runs inside its rect at each end (the knob's radius) +const SLIDER_TRACK_INSET: f32 = 5.0; + +/// The point at `share` (0..1) along slider `track`'s track: 0 is the range's start, 1 its end +pub(crate) fn along(track: egui::Rect, share: f32) -> egui::Pos2 { + egui::pos2(track.left() + SLIDER_TRACK_INSET + (track.width() - 2.0 * SLIDER_TRACK_INSET) * share, track.center().y) +} + +/// Moves a drag makes on its way, one frame each, so a press makes several changes +const DRAG_STEPS: usize = 4; + +/// The undo steps the session holds now +pub(crate) fn undo_depth(harness: &Harness<'_, TextureCraftApp>) -> usize { + harness.state().session.history_labels().len() +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 2b938e89..be8a4c26 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -13,11 +13,8 @@ mod close_unsaved; mod color_picker; mod color_selection_editor; mod curvature_generator; -mod decal_proportions; -mod decal_symmetry; mod display_environment; mod display_post_effects; -mod effect_decal; mod effect_rows; mod effect_sliders; mod empty_start; @@ -29,7 +26,9 @@ mod export_settings; mod export_template_guards; mod file_dialogs; mod fill_channel_image; -mod fill_projection_section; +mod fill_projection_rows; +mod fill_support; +mod fill_symmetry_rows; mod filter_picker; mod frame_selection; mod generator_panel; @@ -92,6 +91,7 @@ mod view2d_tiles; mod view_mode_picker; mod window_menu_684; +mod filter_support; mod stencil; mod symmetry; mod symmetry_2d; diff --git a/crates/ui-egui/tests/it/panel_header.rs b/crates/ui-egui/tests/it/panel_header.rs index 6485f50a..588732e3 100644 --- a/crates/ui-egui/tests/it/panel_header.rs +++ b/crates/ui-egui/tests/it/panel_header.rs @@ -235,3 +235,28 @@ fn a_tab_menus_panel_names_keep_their_plain_layout() { assert!(!padded.is_empty(), "the menu paints the Layers entry"); assert!(padded.iter().all(|height| *height == 0.0), "the Layers entry is padded to {padded:?}"); } + +/// Where the label on `name`'s row and to its right ends, for each label named `name` +fn row_ends(harness: &Harness<'_, TextureCraftApp>, name: &str) -> Vec { + let names = harness.get_all_by_role_and_label(Role::Label, name).map(|node| node.rect()); + names + .filter_map(|name| { + let on_row = harness.get_all_by_role(Role::Label).map(|node| node.rect()); + on_row.filter(|rect| rect.left() > name.right() && (rect.center().y - name.center().y).abs() < 1.0).map(|rect| rect.right()).reduce(f32::max) + }) + .collect() +} + +/// Texture Set Settings keeps Base color's remove room, so its format ends where the other channels' formats do (it ended 24 px right) +#[test] +fn every_channels_format_ends_on_one_column() { + let mut harness = app(); + let settings = tab_rect(&harness, "Texture Set Settings"); + click_at(&mut harness, settings.center()); + harness.run_steps(SETTLE_FRAMES); + + let base_color = row_ends(&harness, "Base color"); + let roughness = row_ends(&harness, "Roughness"); + + assert!(base_color.len() == 1 && base_color == roughness, "Base color's format ends at {base_color:?}, Roughness's at {roughness:?}"); +} diff --git a/crates/ui-egui/tests/it/polygon_fill.rs b/crates/ui-egui/tests/it/polygon_fill.rs index ab50cb53..5a923224 100644 --- a/crates/ui-egui/tests/it/polygon_fill.rs +++ b/crates/ui-egui/tests/it/polygon_fill.rs @@ -158,3 +158,22 @@ fn polygon_fill_snapshots() { harness.run_steps(6); harness.render().unwrap().save(directory.join("polygon-fill-mask-2d.png")).unwrap(); } + +/// A Properties body not yet on the property sheet starts under the panel's name, at the sheet's side padding (it started 4 px left of it) +#[test] +fn the_polygon_fill_body_starts_under_the_properties_name() { + let mut harness = polygon_fill_app(); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(2); + + let painted_left = |wanted: &dyn Fn(&str) -> bool| { + harness.output().shapes.iter().find_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if wanted(text.galley.text()) => Some(text.pos.x), + _ => None, + }) + }; + let caption = painted_left(&|text| text == "POLYGON FILL"); + let header = painted_left(&|text| text.starts_with("PROPERTIES")); + + assert!(caption.is_some() && caption == header, "the body starts at {caption:?}, the header name at {header:?}"); +} diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index 1371e05b..a2cd6187 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -17,6 +17,10 @@ const TRIANGLE: &str = "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 const FORMAT_HINT: &str = "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export"; const TITLE: &str = "Project configuration"; +/// The window sits at the middle of the 1600-point-wide screen and is 560 points wide +const WINDOW_MIDDLE_X: f32 = 800.0; +const WINDOW_HALF_WIDTH: f32 = 280.0; + fn temp_dir(test: &str) -> TempDir { TempDir::new(test) } @@ -178,7 +182,9 @@ fn the_window_follows_the_reference_layout() { "Physical size", "Working color space", ]; - let top = |label: &str| h.get_all_by_label(label).map(|n| n.rect().top()).fold(f32::INFINITY, f32::min); + // Only the window's own rows: a dock panel may show the same text (the fill's Scale switch offers Physical size) + let in_window = |node: &egui_kittest::Node<'_>| (node.rect().center().x - WINDOW_MIDDLE_X).abs() <= WINDOW_HALF_WIDTH; + let top = |label: &str| h.get_all_by_label(label).filter(in_window).map(|n| n.rect().top()).fold(f32::INFINITY, f32::min); for labels in order.windows(2) { assert!(top(labels[0]) < top(labels[1]), "{} comes before {}", labels[0], labels[1]); } diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs index 8d3b413f..fcc33f66 100644 --- a/crates/ui-egui/tests/it/properties_popup.rs +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -1,18 +1,46 @@ //! A plain right click in a view opens the Properties panel's contents at the cursor; right drags keep their gestures -use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2}; +use egui::{Event, Key, Modifiers, PointerButton, Pos2, Role, vec2}; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_engine::core::LayerKind; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::properties_popup::{self, PropertiesPopup}; use texturecraft_ui_egui::state::{Mode, ViewLayout}; +use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// A common laptop window +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// Tall enough that the docked list ends before a fill's MATERIAL caption reaches its top +const JUMP_TAB_WINDOW: egui::Vec2 = egui::vec2(1600.0, 1300.0); + +/// Width of the docked jump tab strip, from its Fill tab across its other two +const DOCKED_STRIP_WIDTH: f32 = 300.0; + +/// Frames for a jump tab's scroll to land +const JUMP_FRAMES: usize = 4; + +/// Frames for a selection made through the engine to show +const SELECT_FRAMES: usize = 3; + +/// Pointer moves a drag makes between its press and its release +const DRAG_MOVES: usize = 4; + fn harness() -> Harness<'static, TextureCraftApp> { - let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - harness.run_steps(4); + harness_sized(WINDOW_SIZE) +} + +/// The sample project's app in a window of `size`, speaking English +fn harness_sized(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); harness } @@ -30,7 +58,7 @@ fn click(harness: &mut Harness<'_, TextureCraftApp>, button: PointerButton, at: harness.event(Event::PointerButton { pos: at, button, pressed: true, modifiers: Modifiers::NONE }); harness.run_steps(1); harness.event(Event::PointerButton { pos: at, button, pressed: false, modifiers: Modifiers::NONE }); - harness.run_steps(3); + harness.run_steps(SETTLE_FRAMES); } /// Drag with `button` from `from` by `by` in a few moves while `modifiers` are held @@ -38,14 +66,14 @@ fn drag(harness: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: harness.event(Event::ModifiersChanged(modifiers)); harness.hover_at(from); harness.event(Event::PointerButton { pos: from, button, pressed: true, modifiers }); - harness.run_steps(2); - for step in 1..=4 { - harness.hover_at(from + by * (step as f32 / 4.0)); + harness.run_steps(DRAG_STEP_FRAMES); + for step in 1..=DRAG_MOVES { + harness.hover_at(from + by * (step as f32 / DRAG_MOVES as f32)); harness.run_steps(1); } harness.event(Event::PointerButton { pos: from + by, button, pressed: false, modifiers }); harness.event(Event::ModifiersChanged(Modifiers::NONE)); - harness.run_steps(3); + harness.run_steps(SETTLE_FRAMES); } #[test] @@ -144,16 +172,49 @@ fn it_shows_what_the_properties_panel_shows() { let fill = harness.state().session.doc.project.layers.values().find(|layer| matches!(layer.kind, LayerKind::Fill(_))).map(|layer| layer.id.0).unwrap(); let selected = texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": fill})); assert!(selected.is_ok(), "{selected:?}"); + let projected = texturecraft_engine::execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": fill, "projection": "uv"})); + assert!(projected.is_ok(), "{projected:?}"); harness.run_steps(3); let center = view_center(&harness); click(&mut harness, PointerButton::Secondary, center); let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); let in_popup = |label: &str| harness.query_all_by_label(label).any(|node| popup.contains_rect(node.rect())); - assert!(in_popup("Projection"), "a selected fill shows its fill settings"); + assert!(in_popup("UV projection"), "a selected fill shows its fill settings"); assert!(!in_popup("Minimum size (%)"), "not the brush's"); } +/// Whether the jump tab `name` inside `area` is the lit one +fn tab_lit(harness: &Harness<'_, TextureCraftApp>, area: egui::Rect, name: &str) -> bool { + let tab = harness.get_all_by_role_and_label(Role::Tab, name).find(|tab| area.contains_rect(tab.rect())); + tab.unwrap_or_else(|| panic!("a {name} tab in {area:?}")).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +#[test] +fn its_jump_tabs_scroll_to_a_section_and_light_it_without_moving_the_docked_panel() { + let mut harness = harness_sized(JUMP_TAB_WINDOW); + let fill = harness.state().session.doc.project.layers.values().find(|layer| matches!(layer.kind, LayerKind::Fill(_))).map(|layer| layer.id.0).unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": fill})).unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": fill, "projection": "uv"})).unwrap(); + harness.run_steps(SELECT_FRAMES); + + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); + let docked_fill = harness.get_all_by_role_and_label(Role::Tab, "Fill").map(|tab| tab.rect()).find(|tab| !popup.contains_rect(*tab)).unwrap(); + + let docked = egui::Rect::from_min_max(docked_fill.min, docked_fill.max + vec2(DOCKED_STRIP_WIDTH, 0.0)); + let in_popup = |harness: &Harness<'_, TextureCraftApp>, label: &str| harness.query_all_by_label(label).any(|node| popup.contains_rect(node.rect())); + assert!(tab_lit(&harness, popup, "Fill"), "it opens on Fill"); + assert!(in_popup(&harness, "UV projection")); + + harness.run_steps(JUMP_FRAMES); + + assert!(is_open(&harness), "a tab click keeps it open"); + assert!(!tab_lit(&harness, popup, "Fill")); + assert!(tab_lit(&harness, docked, "Fill"), "the docked panel keeps its own place"); +} + #[test] fn bake_and_render_modes_never_open_it() { let mut harness = harness(); diff --git a/crates/ui-egui/tests/it/shelf_drop.rs b/crates/ui-egui/tests/it/shelf_drop.rs index 56e57f62..848064c3 100644 --- a/crates/ui-egui/tests/it/shelf_drop.rs +++ b/crates/ui-egui/tests/it/shelf_drop.rs @@ -249,13 +249,11 @@ fn changing_the_camera_cancels_a_drop_with_stale_view_coordinates() { } #[test] -fn the_click_that_closes_the_drop_menu_does_not_move_a_decal_being_placed() { +fn the_click_that_closes_the_drop_menu_paints_nothing_and_adds_no_undo_step() { let (mut harness, position) = drop_image(Some(1)); let distance = |node: &egui_kittest::Node<'_>| node.rect().center().distance(position); harness.get_all_by_label("Roughness").min_by(|a, b| distance(a).total_cmp(&distance(b))).unwrap().click(); harness.run_steps(2); - let decal_layer = harness.state().session.selected_layer().unwrap(); - harness.state_mut().placing_decal = Some(decal_layer); let image = import_white_image(&mut harness); drop_asset(&mut harness, Asset::Texture(image), position); @@ -281,7 +279,7 @@ fn the_click_that_closes_the_drop_menu_does_not_move_a_decal_being_placed() { harness.run_steps(2); assert!(!menu_open(&harness, position)); - assert_eq!(harness.state().session.history_labels().len(), history, "the decal wasn't moved"); + assert_eq!(harness.state().session.history_labels().len(), history, "the closing click painted nothing"); } #[test] diff --git a/crates/ui-egui/tests/it/symmetry.rs b/crates/ui-egui/tests/it/symmetry.rs index 030e709a..d148d41f 100644 --- a/crates/ui-egui/tests/it/symmetry.rs +++ b/crates/ui-egui/tests/it/symmetry.rs @@ -19,13 +19,15 @@ const AXIS_PROBE: f32 = 0.05; const ON_THE_SHAFT: f32 = 40.0; const DRAG_DISTANCE: f32 = 60.0; +/// Window wide enough that the top bar shows every paint control, Symmetry's included, with Properties at its least width +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1760.0, 960.0); + /// A point inside the 3D view near its lower left corner, clear of the mesh and the popup (points from the corner) const VIEW_CORNER_INSET: f32 = 40.0; fn app_harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(1024, 256).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1760.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().session.tool.tool = Tool::Paint; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 7462516b..804cf5fc 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -816,48 +816,22 @@ fn mask_fill_image_snapshot() { harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); - harness.get_by_value("Uniform value").click(); + // The Grayscale slot opens the source picker; its search finds the image + harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); + harness.run_steps(3); + harness.event(egui::Event::Text("checker".into())); harness.run_steps(3); save(&mut harness, &output_dir, "mask-fill-image-menu"); - harness.get_by_role_and_label(egui::Role::Button, &name).click(); + harness.get_by_role_and_label(egui::Role::ListBoxOption, &name).click(); harness.run_steps(4); let EffectKind::Fill { source, .. } = &harness.state().session.doc.project.effect(LayerId(effect)).unwrap().1.kind else { panic!("fill effect") }; assert_eq!(*source, Source::image(name)); - assert!(harness.query_by_label("Projection").is_some(), "image projection is editable"); + assert!(harness.query_by_label("UV projection").is_some(), "image projection is editable"); save(&mut harness, &output_dir, "mask-fill-image-selected"); } -#[test] -#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] -fn tile_generator_gradient_map_snapshot() { - use serde_json::json; - use texturecraft_engine::execute; - - let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; - - std::fs::create_dir_all(&output_dir).unwrap(); - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - execute(&mut session, "layer.add.fill", &json!({})).unwrap(); - execute( - &mut session, - "layer.fill.set", - &json!({"channel": "baseColor", "procedural": "Tile Generator", "tile": {"amount": [5, 3]}, "colors": ["#1d1745", "#4e80a0", "#f0bb75"]}), - ) - .unwrap(); - - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); - harness.state_mut().ui.prefs.language = "en".into(); - harness.state_mut().ui.dock.focus(Panel::Properties); - harness.run_steps(6); - harness.get_by_role_and_label(egui::Role::ComboBox, "Base color").scroll_to_me(); - harness.run_steps(30); - - assert!(harness.query_by_label_contains("Add color").is_some()); - save(&mut harness, &output_dir, "tile-generator-gradient-map"); -} - /// Every docked panel's header bar (names in capitals, a close × at the right), then the Properties × hovered #[test] #[ignore] @@ -887,6 +861,35 @@ fn panel_header_snapshots() { save(&mut harness, &output_dir, "panel-header-close-hovered"); } +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn tile_generator_gradient_map_snapshot() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &json!({})).unwrap(); + execute( + &mut session, + "layer.fill.set", + &json!({"channel": "baseColor", "procedural": "Tile Generator", "tile": {"amount": [5, 3]}, "colors": ["#1d1745", "#4e80a0", "#f0bb75"]}), + ) + .unwrap(); + + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.dock.focus(Panel::Properties); + harness.run_steps(6); + harness.get_by_role_and_label(egui::Role::ComboBox, "Base color").scroll_to_me(); + harness.run_steps(30); + + assert!(harness.query_by_label_contains("Add color").is_some()); + save(&mut harness, &output_dir, "tile-generator-gradient-map"); +} + /// Edit > Settings: the three pages and a compact window at 150% scale #[test] #[ignore] @@ -957,3 +960,408 @@ fn default_layout_snapshots() { harness.hover_at(egui::pos2(properties_close.center().x - 120.0, properties_close.min.y - 6.0)); save(&mut harness, &output_dir, "default-layout-split-hovered"); } + +#[test] +#[ignore] +fn fill_reset_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); + execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "tiling": [2.0, 2.0], "filtering": "nearest"})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("fill-reset-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + let reset = harness.get_by_label("Fill: Reset to defaults").rect().center(); + harness.hover_at(reset); + save(&mut harness, &output_dir, "fill-reset-hovered"); + + // The band sits under the fold at this height: scroll Properties down to it + harness.hover_at(reset); + harness.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -110.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + }); + harness.run_steps(3); + let edges = harness.get_by_label("Restore defaults").rect().center(); + harness.hover_at(edges); + save(&mut harness, &output_dir, "fill-reset-band-hovered"); + harness.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, 110.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + }); + harness.run_steps(3); + harness.get_by_label("Fill: Reset to defaults").click(); + harness.hover_at(reset); + save(&mut harness, &output_dir, "fill-reset-at-defaults"); +} + +#[test] +#[ignore] +fn fill_properties_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); + execute( + &mut session, + "layer.fill.projection", + &json!({"layer": layer, "tiling": [2.0, 2.0], "rotation": 30.0, "offset": [0.25, 0.0], "wrap": "repeat", "filtering": "bilinearHq"}), + ) + .unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("fill-uv-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + + // A UV pad drag right, held mid-way: the ring stays in the middle, the filled dot and the checker go right; then a dot past the edge + execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": layer, "offset": [0.0, 0.0]})).unwrap(); + harness.run_steps(2); + let pad = harness.get_by_label("Move on model").rect().center(); + harness.event(egui::Event::PointerMoved(pad)); + harness.event(egui::Event::PointerButton { pos: pad, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + harness.run_steps(2); + for step in 1..=20 { + harness.event(egui::Event::PointerMoved(pad + egui::vec2(6.0 * step as f32, 0.0))); + harness.run_steps(1); + } + save(&mut harness, &output_dir, "fill-uv-pad-dragged-right"); + harness.event(egui::Event::PointerButton { pos: pad, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + harness.run_steps(2); + execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": layer, "offset": [-1.6, 0.6]})).unwrap(); + save(&mut harness, &output_dir, "fill-uv-dot-past-edge"); + execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": layer, "offset": [0.25, 0.0]})).unwrap(); + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + for (shown, hover, name) in [ + ("UV projection", "Planar projection", "fill-uv-projection-open"), + ("Bilinear | HQ", "Nearest", "fill-uv-filtering-open"), + ("Repeat", "Repeat horizontally", "fill-uv-wrap-open"), + ] { + harness.get_by_label(shown).click(); + harness.run_steps(2); + harness.get_by_label(hover).hover(); + save(&mut harness, &output_dir, name); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + } + harness.get_by_label("Physical size").click(); + save(&mut harness, &output_dir, "fill-uv-physical"); + harness.get_by_label("Link").click(); + save(&mut harness, &output_dir, "fill-uv-physical-unlinked"); + + // Screen 02: every other projection, with the lists that open from its new rows + let cases = [ + ("spherical", json!({}), "fill-spherical"), + ("cylindrical", json!({"scaleMode": "physicalSize"}), "fill-cylindrical"), + ("cylindrical", json!({"angle": 120.0, "backfaceCulling": true}), "fill-cylindrical-angle"), + ("triplanar", json!({"scaleMode": "physicalSize"}), "fill-triplanar"), + ("planar", json!({"scaleMode": "physicalSize", "backfaceCulling": true, "shapeCrop": "cropped"}), "fill-planar"), + ("warp", json!({"scaleMode": "physicalSize", "warpCorners": [[-0.55, 0.48], [0.56, 0.6], [0.48, -0.55], [-0.45, -0.45]]}), "fill-warp"), + // The image's Rotation turns the checker inside the frame + ("warp", json!({"scaleMode": "tiling", "tiling": [2.0, 2.0], "rotation": 30.0}), "fill-warp-rotated"), + ("uvTile", json!({}), "fill-uvtile"), + ]; + for (kind, settings, name) in cases { + let session = &mut harness.state_mut().session; + execute(session, "layer.fill.projection", &json!({"layer": layer, "projection": kind})).unwrap(); + let mut settings = settings; + settings["layer"] = layer.clone(); + execute(session, "layer.fill.projection", &settings).unwrap(); + save(&mut harness, &output_dir, name); + } + + // The preview square is Move on model's pad: lit on hover and while held + execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": layer, "projection": "planar"})).unwrap(); + harness.run_steps(2); + harness.get_by_label("Move on model").hover(); + save(&mut harness, &output_dir, "fill-planar-pad-hover"); + let pad = harness.get_by_label("Move on model").rect().center(); + harness.event(egui::Event::PointerButton { pos: pad, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + save(&mut harness, &output_dir, "fill-planar-pad-held"); + harness.event(egui::Event::PointerButton { pos: pad, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + harness.run_steps(2); + + // A slid projector: the object stays put, the ring marks Offset 0 and the filled dot where the projector went + for (kind, offset, name) in [("planar", [0.3, 0.15, 0.0], "fill-planar-slid"), ("spherical", [0.5, 0.3, 0.0], "fill-spherical-slid")] { + execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": layer, "projection": kind, "offset": offset})).unwrap(); + save(&mut harness, &output_dir, name); + } + + // The Projection row's eye: hovered, then the gizmos hidden + execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": layer, "projection": "planar", "offset": [0.0, 0.0, 0.0]})).unwrap(); + harness.run_steps(2); + harness.get_by_label("Hide projection gizmos").hover(); + save(&mut harness, &output_dir, "fill-planar-eye-hover"); + harness.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Hide projection gizmos").click(); + harness.run_steps(2); + save(&mut harness, &output_dir, "fill-planar-eye-hidden"); + harness.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Show projection gizmos").click(); + harness.run_steps(2); + execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": layer, "projection": "uvTile"})).unwrap(); + harness.run_steps(2); + harness.get_by_label("Fill (Match per UV Tile)").click(); + harness.run_steps(2); + harness.get_by_label("Warp projection").hover(); + save(&mut harness, &output_dir, "fill-uvtile-projection-open"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + let session = &mut harness.state_mut().session; + + // Tri-planar's Shape crop sits highest in the panel: its list opens in view + execute(session, "layer.fill.projection", &json!({"layer": layer, "projection": "triplanar"})).unwrap(); + harness.run_steps(2); + harness.get_by_label("Extends Outside Shape").click(); + harness.run_steps(2); + harness.get_by_label("Cropped to Shape").hover(); + save(&mut harness, &output_dir, "fill-triplanar-crop-open"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + + // The shape previews take their colours from the theme + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("fill-triplanar-{name}")); + } +} + +/// Screen 03: a planar fill's Symmetry section off, mirrored (a moved Y plane with U flipped), radial (6 over a full turn, 4 over half a turn, also in the dark and light themes), its Type list open, and a UV fill's greyed switch +#[test] +#[ignore] +fn fill_symmetry_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); + execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": "planar"})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Tab, "Symmetry").click(); + let cases = [ + (json!({}), "symmetry-off"), + (json!({"symmetry": true}), "symmetry-mirror"), + (json!({"symmetryAxis": 1, "axisPosition": [0.0, 0.4, 0.0], "flipCopy": [true, false]}), "symmetry-mirror-y"), + (json!({"symmetryType": "radial", "symmetryAxis": 2, "axisPosition": 0, "flipCopy": [false, false]}), "symmetry-radial"), + (json!({"symmetryCount": 4, "angleSpan": 180}), "symmetry-radial-half"), + ]; + for (settings, name) in cases { + let mut settings = settings; + settings["layer"] = layer.clone(); + execute(&mut harness.state_mut().session, "layer.fill.projection", &settings).unwrap(); + save(&mut harness, &output_dir, name); + } + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("symmetry-radial-half-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + harness.get_by_role_and_label(egui::Role::ComboBox, "Radial symmetry").click(); + harness.run_steps(2); + harness.get_by_label("Mirror symmetry").hover(); + save(&mut harness, &output_dir, "symmetry-type-open"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::RadioButton, "X").hover(); + save(&mut harness, &output_dir, "symmetry-axis-hover"); + + execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": layer, "projection": "uv"})).unwrap(); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Tab, "Symmetry").click(); + harness.run_steps(4); + harness.get_by_label("Not available with UV projection").hover(); + save(&mut harness, &output_dir, "symmetry-uv"); +} + +/// The culling rows' i on a planar fill: each one hovered with its tooltip, in the medium theme, then the Depth culling one in the dark and light themes +#[test] +#[ignore] +fn info_icon_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); + execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": "planar"})).unwrap(); + execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "scaleMode": "physicalSize", "backfaceCulling": true})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + + // The test's stand-in arrow would hide the hovered i + harness.set_render_cursor(false); + harness.run_steps(4); + let tips = [ + ("Paints only the surface the projector sees first; parts hidden behind it stay unpainted.", "depth"), + ("Leaves out faces turned away from the projector, so the fill doesn't run onto their back.", "backface"), + ]; + for (tip, name) in tips { + let info = harness.get_by_label(tip).rect().center(); + harness.hover_at(info); + harness.run_steps(60); + save(&mut harness, &output_dir, &format!("info-{name}-medium")); + } + let info = harness.get_by_label(tips[0].0).rect().center(); + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.hover_at(info); + harness.run_steps(60); + save(&mut harness, &output_dir, &format!("info-depth-{name}")); + } +} + +/// The right-click Properties popup on a UV fill: its jump tabs with Symmetry hovered, Material clicked, then wheeled up to Symmetry; `TC_UI_THEMES` set adds the dark and light themes +#[test] +#[ignore] +fn popup_tabs_snapshots() { + use egui::{Event, Modifiers, PointerButton}; + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); + execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": "uv"})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.set_render_cursor(false); + harness.run_steps(4); + + let at = harness.state().viewport_rect.center() - egui::vec2(200.0, 250.0); + harness.hover_at(at); + for pressed in [true, false] { + harness.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }); + harness.run_steps(2); + } + harness.run_steps(4); + let popup = harness.ctx.memory(|memory| memory.area_rect(texturecraft_ui_egui::properties_popup::area_id())).unwrap(); + let tab = |harness: &Harness<'_, TextureCraftApp>, name: &str| { + harness.get_all_by_role_and_label(egui::accesskit::Role::Tab, name).map(|tab| tab.rect()).find(|tab| popup.contains_rect(*tab)).unwrap().center() + }; + let symmetry = tab(&harness, "Symmetry"); + harness.hover_at(symmetry); + harness.run_steps(4); + save(&mut harness, &output_dir, "popup-tabs-fill-medium"); + + let material = tab(&harness, "Material"); + harness.hover_at(material); + for pressed in [true, false] { + harness.event(Event::PointerButton { pos: material, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + harness.run_steps(2); + } + harness.run_steps(60); + save(&mut harness, &output_dir, "popup-tabs-material-medium"); + + harness.hover_at(popup.center()); + harness.event(Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, 260.0), + modifiers: Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + }); + harness.run_steps(6); + save(&mut harness, &output_dir, "popup-tabs-symmetry-medium"); + + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("popup-tabs-symmetry-{name}")); + } + } +} + +/// The Properties panel at its minimum width (the right column dragged as narrow as it goes), on the Fill tab's widest row (3D projection settings) and on a filter +#[test] +#[ignore] +fn properties_min_width_snapshot() { + use craft_ui::docking::Node; + use craft_ui::layout::SplitSize; + use serde_json::json; + use texturecraft_engine::execute; + use texturecraft_ui_egui::docking::Dock; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); + let settings = json!({"layer": layer, "projection": "planar", "scaleMode": "physicalSize", "backfaceCulling": true, "shapeCrop": "cropped"}); + execute(&mut session, "layer.fill.projection", &settings).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + let mut workspace = harness.state().ui.dock.workspace().clone(); + let Some(Node::Split { second, .. }) = workspace.layout.root.as_mut() else { panic!("default columns") }; + let Node::Split { size, .. } = second.as_mut() else { panic!("viewport and right column") }; + *size = SplitSize::FixedSecond(0.0); + harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("properties-min-width-planar-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + execute(&mut harness.state_mut().session, "effect.add.filter", &json!({"target": "content", "filter": "colorMatch"})).unwrap(); + save(&mut harness, &output_dir, "properties-min-width-filter"); +} + +/// The docked Properties list of a fill whose sections all fit, scrolled to its end: MATERIAL at the top, blank space under it +#[test] +#[ignore] +fn sheet_scroll_end_snapshots() { + use egui::{Event, Modifiers}; + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); + execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": "uv"})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 2000.0)).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.set_render_cursor(false); + harness.run_steps(4); + save(&mut harness, &output_dir, "sheet-end-top-medium"); + + let strip = harness.get_by_role_and_label(egui::accesskit::Role::Tab, "Fill").rect(); + harness.hover_at(strip.center_bottom() + egui::vec2(0.0, 100.0)); + for _ in 0..40 { + harness.event(Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -120.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: Modifiers::NONE, + }); + harness.step(); + } + harness.run_steps(30); + save(&mut harness, &output_dir, "sheet-end-scrolled-medium"); +} From 82b981e6419014dd6e1a378184bafa32243a1fd4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:12 +0000 Subject: [PATCH 15/17] Temporary: the fill's Material section keeps main's channel rows and filter effects main's filter panel --- crates/compose/src/eval.rs | 25 +++++++++--------- crates/compose/src/lib.rs | 1 + crates/core/src/layer.rs | 2 +- crates/core/src/lib.rs | 2 ++ crates/engine/src/fill_reset_cmds.rs | 1 + crates/engine/src/layer_cmds.rs | 9 ++++--- crates/engine/src/mask_cmds.rs | 2 +- crates/engine/src/materials.rs | 1 + crates/engine/src/warp_cmds.rs | 1 + crates/engine/tests/it/fill_projections.rs | 1 + crates/ui-egui/src/dock.rs | 26 ++++++++++++------- crates/ui-egui/src/fill_panel.rs | 4 +++ crates/ui-egui/src/fill_source_slot.rs | 6 ++--- crates/ui-egui/src/projection_preview.rs | 2 ++ crates/ui-egui/src/property_sheet/group.rs | 1 + crates/ui-egui/src/property_sheet/mod.rs | 2 +- crates/ui-egui/src/property_sheet/row_lead.rs | 1 + .../src/property_sheet/section_tabs.rs | 2 -- crates/ui-egui/src/property_sheet/slider.rs | 2 ++ crates/ui-egui/src/property_sheet/slot.rs | 2 ++ .../src/property_sheet/switch_control.rs | 1 + .../src/property_sheet/tests/gallery.rs | 2 ++ crates/ui-egui/src/round_gizmo.rs | 1 + crates/ui-egui/src/viewport.rs | 1 + crates/ui-egui/tests/it/properties_popup.rs | 4 +++ 25 files changed, 68 insertions(+), 34 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index adbf91ae..6413c421 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -10,9 +10,9 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ - BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Generator, - GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, MicroDetail, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, - blend1, blend3, lum, mix3, per_unit, + BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Filtering, Generator, + GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, MicroDetail, NormalFormat, Project, Projection, Sampling, ShapeCrop, Source, + TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; @@ -1097,7 +1097,7 @@ struct Node<'a> { /// Plans of the visible effects of a stack: mask effects (`channel` None) or the content /// effects of one channel (paint effects then read that channel's pixels). -fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y: u32, channel: Option) -> Vec> { +fn effect_plans<'a>(inp: &EvaluationInputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y: u32, channel: Option) -> Vec> { effects .iter() .filter(|effect| effect.visible) @@ -1155,7 +1155,7 @@ fn tile_of<'a>(inp: &Inputs, img: Option<&'a TileImage>, tx: u32, ty: u32, chann img.resampled_tile(w, h, tx, ty, &empty).map(Cow::Owned) } -fn mask_plan<'a>(inp: &Inputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32, fields: Option<&'a Fields>) -> Option> { +fn mask_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32, fields: Option<&'a Fields>) -> Option> { if !mask.enabled { return None; } @@ -1179,8 +1179,7 @@ fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, t list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true)).collect() } -/// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are -/// planned when `kids`. +/// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are planned when `kids` #[allow(clippy::too_many_arguments)] fn plan_node<'a>( inp: &Inputs<'a>, @@ -1221,6 +1220,7 @@ fn plan_node<'a>( LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) }, LayerKind::Fill(f) => { let (depth, covers_all) = fill_coverage(inp, &f.projection, f.sampling); + Content::Fill { fill: Box::new(Cow::Borrowed(f)), depth, covers_all } } LayerKind::Group { children, .. } => Content::Group(if kids { plan(inp, children, channels, tx, ty, depth + 1, fields) } else { Vec::new() }), @@ -1373,7 +1373,7 @@ impl<'t> Tape<'t> { impl<'a, 'b> Texel<'a, 'b> { fn new(inp: &'b Inputs<'a>, x: u32, y: u32, o: usize, stroke: f32) -> Self { - Texel { inp, x, y, o, res: inp.gbuf.width, coords: None, stroke, stop: None, anchors: Vec::new(), tape: Tape::Off } + Texel { inp, x, y, o, res: inp.gbuf.width, coords: None, stroke, stop: None, anchors: Vec::new(), tape: Tape::Off, copy: None } } /// Run `f` with `tape` as this texel's tape. @@ -2221,12 +2221,13 @@ impl<'a, 'b> Texel<'a, 'b> { } None => (value, coverage), }, + EffectKind::Levels(levels) => (mix3(value, per_unit(chan_plan.kind, value, |x| levels.apply(x)), opacity), coverage), // Baked lighting reads the texel's normal and occlusion, and lights the base color only EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => match Channel::ALL.get(chan_plan.ch) { Some(Channel::BaseColor) => { let nrm = self.coords().nrm.to_array(); - let k = f.baked_light(nrm, self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0)).unwrap_or(1.0); - (mix3(v, v.map(|x| (x * k).clamp(0.0, 1.0)), o), cov) + let factor = filter.baked_light(nrm, self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0)).unwrap_or(1.0); + (mix3(value, value.map(|x| (x * factor).clamp(0.0, 1.0)), opacity), coverage) } _ => (value, coverage), }, @@ -2905,7 +2906,7 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height); // A field covers the bounding box of the tiles it is built for, which for a scattered sample // is the whole set: with a neighbourhood filter below, each tile gets its own. - let probe = neighbourhood_fields(&cut_inp, &channels, tiles.get(..1).unwrap_or_default()); + let probe = evaluation_fields(&cut_inp, &channels, tiles.get(..1).unwrap_or_default()); let shared = probe.is_empty().then_some(probe); let bin = |v: f32| ((v.clamp(0.0, 1.0) * bins as f32) as usize).min(bins - 1); let hist = tiles @@ -2915,7 +2916,7 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u let fields = match &shared { Some(f) => f, None => { - own = neighbourhood_fields(&cut_inp, &channels, &[(tx, ty)]); + own = evaluation_fields(&cut_inp, &channels, &[(tx, ty)]); &own } }; diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 25548ab5..206f1437 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -41,6 +41,7 @@ pub mod warp; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, kinds_for, tile_bytes}; pub use eval::{ + BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours, }; pub use pattern_context::PatternContext; diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index b9677515..267f05c2 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -4,7 +4,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; -use crate::{BakedMap, BlendMode, Channel, ChannelKind, lum}; +use crate::{Backface, BakedMap, BlendMode, Channel, ChannelKind, DepthCulling, Projector, ShapeCrop, lum}; mod curvature_detail; mod curvature_mode; diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 3797e2a5..be8338bc 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -42,6 +42,8 @@ pub use fill_symmetry::FillSymmetry; pub use layer::{ ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, + OutputResolution, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, Sampling, ScaleMode, Source, TileBlending, TileGenerator, + TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient, hsl_adjust, per_unit, }; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, diff --git a/crates/engine/src/fill_reset_cmds.rs b/crates/engine/src/fill_reset_cmds.rs index d5d1afa6..f1c5317b 100644 --- a/crates/engine/src/fill_reset_cmds.rs +++ b/crates/engine/src/fill_reset_cmds.rs @@ -13,6 +13,7 @@ pub fn specs() -> Vec { "Reset fill settings", [], None, + "{layer? | effect?: content fill effect id} — the Fill section back to a new fill's in one undo step: the same projection kind with its defaults (tiling 1, no offset or rotation, a planar or warp frame stays where it is placed, a warp's corners unpulled), the default filtering, wrap and scale mode (symmetry, sources and material stay)", has_layer, reset_projection )] diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 4c8b209f..d5936ece 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -3,8 +3,8 @@ use serde_json::{Value, json}; use texturecraft_core::{ - BlendMode, Channel, ChannelBlend, ChannelKind, EffectKind, Fill, Layer, LayerId, LayerKind, NormalFormat, Procedural, ProceduralKind, Project, Projection, - Source, + Backface, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, EffectKind, Fill, FillSymmetry, Filtering, Layer, LayerId, LayerKind, NormalFormat, + Procedural, ProceduralKind, Project, Projection, Projector, Sampling, ScaleMode, ShapeCrop, Source, SymmetryKind, UvTransform, UvWrap, }; use crate::commands::{ @@ -113,7 +113,7 @@ pub fn specs() -> Vec { "Set fill source", [], None, - "{layer? | effect?: content fill effect id, channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?, normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}", + "{layer? | effect?: content fill effect id, channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?, normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}", has_layer, fill_set ), @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Set fill projection", [], None, - "{layer? | effect?: content fill effect id, projection?: uv|triplanar|planar|spherical|cylindrical (default: the current one), scale?: number | [u, v] (uv), rotation?: degrees (uv), offset?: [u, v] (uv) | [x, y, z] (triplanar, planar), sharpness?: 1..64 (triplanar), axis?: 0|1|2 (planar, cylindrical)} — what is not given keeps its value", + "{layer? | effect?: content fill effect id, projection?: uvTile (Fill (Match per UV Tile))|uv|triplanar|planar|spherical|cylindrical|warp (default: the current one; a new warp's frame sits around the mesh, seen from the front), tiling?: number | [u, v] (UV transformations, every projection; uv: same as scale), rotation?: degrees (UV transformations), uvOffset?: [u, v] (UV transformations of a 3D projection), scale?: number | [u, v] (uv: the tiling; 3D projections but warp: one number), offset?: [u, v] (uv) | [x, y, z] (3D projections but warp; a warp is placed by its frame with layer.decal.set, and refuses either), projectorRotation?: [x, y, z] degrees, projectorScale?: number | [x, y, z] (3D projection settings; a negative axis mirrors it), shapeCrop?: cropped|extendsOutside (3D projections), backfaceCulling?: bool, backfaceAngle?: degrees, backfaceHardness?: 0..1 (planar, cylindrical), depthCulling?: bool, depthCullingHardness?: 0..1 (planar, warp; surfaces hidden from the projector behind others get none of it; new planar and warp projections start with it on at 0.75), sharpness?: 1..64 (triplanar), warpCorners?: [[x, y] × 4] (warp: top left, top right, bottom right, bottom left, across and up in frame sizes from its centre; unpulled = ±0.5), projectionDepth?: lengths of the frame's longer side it reaches in front of and behind it when cropped (warp), angle?: 1..360 degrees one repeat spans (cylindrical), axis?: 0|1|2 (planar, cylindrical), filtering?: bilinearHq|bilinearSharp|nearest (how images are read), wrap?: repeat|repeatHorizontally|repeatVertically|none (past the 0..1 tile; not tri-planar), symmetry?: bool (copies of a 3D projection; UV projections have none), symmetryType?: mirror|radial, symmetryAxis?: 0|1|2 or x|y|z (the mirror plane's normal or the turning axis), flipCopy?: [u, v] (turn the copies' images over), axisPosition?: number | [x, y, z] (where the plane or axis passes, -1..1 mesh radii from the mesh's centre), symmetryCount?: 2..64 (radial copies, the original included), angleSpan?: 1..360 degrees (radial copies spread over it; 360 spaces them evenly)} — what is not given keeps its value", has_layer, fill_projection ), @@ -518,6 +518,7 @@ pub(crate) fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result Result<&mut Fill> { match target { FillTarget::Layer(id) => match &mut s.doc.project.layer_mut(id)?.kind { diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index ac1db3f5..98c8f906 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use texturecraft_core::{ BakedMap, BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, - MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Source, + MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, Source, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 62c36dd2..5b8c1c7d 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -786,6 +786,7 @@ pub(crate) fn brush_fill(id: LayerId, sources: Vec<(Channel, Source)>, scale: f3 Layer::new( id, "Brush material", + LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, sampling: Default::default(), link: None }), &channels, ) } diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/warp_cmds.rs index 71d0f051..6a3e18b0 100644 --- a/crates/engine/src/warp_cmds.rs +++ b/crates/engine/src/warp_cmds.rs @@ -17,6 +17,7 @@ pub fn specs() -> Vec { "Reset frame", [], None, + "{layer? | effect?: content fill effect id} — a warp projection's frame back around the mesh, seen from the front, with its corners unpulled (Projection Depth and the other settings stay)", has_layer, reset_frame )] diff --git a/crates/engine/tests/it/fill_projections.rs b/crates/engine/tests/it/fill_projections.rs index 7d0ebc93..5d9d18de 100644 --- a/crates/engine/tests/it/fill_projections.rs +++ b/crates/engine/tests/it/fill_projections.rs @@ -466,6 +466,7 @@ fn an_axis_planar_reading_a_pattern_is_not_placed() { let added = execute(&mut s, "effect.add.fill", &json!({"layer": layer.0, "target": "mask", "projection": "planar"})).unwrap(); let effect = added["effect"].as_u64().unwrap(); + execute(&mut s, "effect.set", &json!({"effect": effect, "procedural": "Checker"})).unwrap(); assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "effect": effect})).is_err(), "a mask fill's pattern keeps its axis too"); } diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 70c4f246..27d8e91c 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -6,8 +6,8 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, DecalFlip, Effect, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, LinkParam, - MaterialLink, Projection, Source, + BakedMap, BlendMode, Channel, ChannelBlend, ChannelKind, Effect, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, LinkParam, MaterialLink, Projection, + Source, }; use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; @@ -1885,7 +1885,6 @@ fn effect_type_label(kind: &EffectKind) -> &'static str { pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { // A floating scroll bar would cover the right-aligned slider values and section reset icons ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); - egui::ScrollArea::vertical().id_salt(("props", properties_place(app))).auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); let scope = SectionScope::Docked; if let Some(tabs) = properties_fill_tabs(app) { crate::property_sheet::section_tabs(ui, scope, 0, &tabs); @@ -1920,6 +1919,8 @@ pub(crate) fn properties_scrolled(app: &mut TextureCraftApp, ui: &mut Ui, area: }); } +/// The tabs over the panel when it shows a fill layer's sections, which they jump between +pub(crate) fn properties_fill_tabs(app: &TextureCraftApp) -> Option<[(&'static str, &'static str); 2]> { if app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { return None; } @@ -1928,6 +1929,7 @@ pub(crate) fn properties_scrolled(app: &mut TextureCraftApp, ui: &mut Ui, area: match app.session.target { StackTarget::Content => { let layer = app.session.selected_layer().and_then(|id| project.layers.get(&id))?; + matches!(&layer.kind, LayerKind::Fill(fill) if fill.projection.placed().is_none()).then(crate::fill_panel::fill_tabs) } _ => None, } @@ -1956,8 +1958,6 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { match (&selected, app.session.target) { // Polygon fill shows its own settings and says what it fills into, wherever it can fill _ if tool == Tool::PolygonFill && tool_usable => legacy_body(ui, |ui| polygon_fill_properties(app, ui)), - (Some(layer), StackTarget::Effect(effect)) => legacy_body(ui, |ui| effect_properties(app, ui, layer, effect)), - (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => legacy_body(ui, |ui| fill_properties(app, ui, layer)), (Some(layer), StackTarget::Effect(effect)) => effect_properties(app, ui, layer, effect), (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => fill_properties(app, ui, layer), (Some(layer), StackTarget::Content) if layer.is_group() => legacy_body(ui, |ui| { @@ -2066,6 +2066,7 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { let stroke_width = (brush.size / PREVIEW_SIZE_UNIT * PREVIEW_STROKE_WIDTH_SCALE).clamp(*PREVIEW_STROKE_WIDTH.start(), *PREVIEW_STROKE_WIDTH.end()); let alpha = (brush.flow * brush.opacity * 255.0) as u8; + painter.add(egui::Shape::line(points, Stroke::new(stroke_width, Color32::from_white_alpha(alpha.max(PREVIEW_STROKE_MIN_ALPHA))))); let base_color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or(PREVIEW_FALLBACK_BASE_COLOR); crate::thumbs::paint_sphere(painter, pos2(rect.left() + half_width * 1.5, rect.center().y), PREVIEW_SPHERE_RADIUS, base_color); ui.add_space(BRUSH_PREVIEW_GAP); @@ -2721,6 +2722,7 @@ fn fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { let LayerKind::Fill(fill) = &layer.kind else { return }; let on: Vec = layer.channels.keys().copied().collect(); PropertySheet::show(ui, ("fill_sheet", layer.id.0), |sheet| { + crate::fill_panel::placement_sections(app, sheet, fill, &json!({"layer": layer.id.0}), layer.id); }); legacy_body(ui, |ui| { if let Some(link) = &fill.link { @@ -2945,7 +2947,7 @@ const FILL_MATERIAL_GAP: f32 = 6.0; /// Space between a fill's channel chips and its channel sources const FILL_CHANNELS_GAP: f32 = 4.0; -/// Projection and sources of a fill layer or fill effect (`base`) for its enabled channels; `reader` owns it +/// Sources of a fill layer or fill effect (`base`) for its enabled channels; `reader` owns it fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, enabled_channels: &[Channel], reader: LayerId) { let salt = base.to_string(); ui.add_space(FILL_MATERIAL_GAP); @@ -3305,6 +3307,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe // Property sheets keep the panel's own edges; only the rows not yet laid out by one get the legacy margin match &effect.kind { EffectKind::Generator(generator) => legacy_body(ui, |ui| crate::generator_panel::generator_properties(app, ui, layer.id, id, generator)), + EffectKind::Levels(levels) => legacy_body(ui, |ui| crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels)), EffectKind::Fill { source, projection, .. } => legacy_body(ui, |ui| { ui.label(caption(tr("Fill"))); let anchors = effect_anchors_below(app, layer.id, effect_id); @@ -3353,9 +3356,11 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe EffectKind::Material(fill) => { let enabled: Vec = fill.sources.keys().copied().collect(); PropertySheet::show(ui, ("fill_effect_sheet", id), |sheet| { + crate::fill_panel::placement_sections(app, sheet, fill, &json!({"effect": id}), layer.id); }); + legacy_body(ui, |ui| fill_editor(app, ui, fill, &json!({"effect": id}), &enabled, layer.id)); } - EffectKind::Anchor => { + EffectKind::Anchor => legacy_body(ui, |ui| { ui.label(caption(tr("Anchor point"))); let text = if anchor_in_mask(app, effect_id) { tr("Records the mask value at this point. Fill effects and generators in masks above can read it.") @@ -3400,10 +3405,11 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe tool_properties(app, ui); } }), + EffectKind::Filter(filter) => legacy_body(ui, |ui| filter_properties(app, ui, id, filter)), + EffectKind::ColorSelection { colors, tolerance } => { + legacy_body(ui, |ui| crate::color_selection_editor::color_selection_properties(app, ui, effect_id, colors, *tolerance)) } - EffectKind::Filter(filter) => filter_properties(app, ui, id, filter), - EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, colors, *tolerance), - other => { + other => legacy_body(ui, |ui| { ui.label(RichText::new(tr(other.name())).color(tokens.text_dim)); }), } diff --git a/crates/ui-egui/src/fill_panel.rs b/crates/ui-egui/src/fill_panel.rs index b58dcde4..746c63e4 100644 --- a/crates/ui-egui/src/fill_panel.rs +++ b/crates/ui-egui/src/fill_panel.rs @@ -7,6 +7,7 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::compose::frame_placement; use texturecraft_engine::compose::tile_length::{MeshSize, tile_length, tiling_for_length}; +use texturecraft_engine::core::{Backface, Fill, Filtering, LayerId, Projection, Projector, ScaleMode, ShapeCrop, UvWrap}; use texturecraft_engine::layer_cmds::{MAX_PLACEMENT, MIN_SCALE}; use texturecraft_engine::paint::FULL_TURN_DEGREES; @@ -74,6 +75,9 @@ const ROTATION_FIELD_SPEED: f32 = 0.5; /// Change per pixel dragged on a 3D scale field const SCALE_FIELD_SPEED: f32 = 0.01; +/// The tabs over a fill's Properties, each jumping to its section +pub(crate) fn fill_tabs() -> [(&'static str, &'static str); 2] { + [(ic::SLIDERS_HORIZONTAL, tr("Fill")), (ic::FLIP_HORIZONTAL, tr("Symmetry"))] } /// Which fill a `base` addresses, (layer, effect), as the salt of its rows' widget state diff --git a/crates/ui-egui/src/fill_source_slot.rs b/crates/ui-egui/src/fill_source_slot.rs index 2b8dfeda..cecfd509 100644 --- a/crates/ui-egui/src/fill_source_slot.rs +++ b/crates/ui-egui/src/fill_source_slot.rs @@ -28,7 +28,7 @@ const UNIFORM_TILE_GRAY: f32 = 0.8; const UNIFORM_SWATCH_NAME: &str = "swatch:uniform"; /// One swatch for every frame, so its preview stays cached static UNIFORM_SWATCH: LazyLock> = - LazyLock::new(|| Arc::new(ImageRes { width: 1, height: 1, rgba: vec![[UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, 1.0]], srgb: false })); + LazyLock::new(|| Arc::new(ImageRes::new(1, 1, vec![[UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, 1.0]], false))); /// The slot of `fill`, which reads `source`; `anchors` are the anchor points below its layer and `caption` names what it fills pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, fill: &FillSourceTarget, source: &Source, (anchors, caption): (&[(LayerId, String)], &str)) { @@ -283,7 +283,7 @@ mod tests { for index in 0..IMAGE_COUNT { let name = format!("picker-image-{index:03}.png"); session.doc.resources.insert(name.clone(), Arc::new(vec![0])); - session.images.insert(name, Arc::new(ImageRes { width: 64, height: 64, rgba: vec![[0.5; 4]; 64 * 64], srgb: false })); + session.images.insert(name, Arc::new(ImageRes::new(64, 64, vec![[0.5; 4]; 64 * 64], false))); } let mut harness = picker_harness(session, Vec::new()); @@ -320,7 +320,7 @@ mod tests { let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); for index in 0..128 { let name = format!("picker-{index:03}.png"); - session.images.insert(name, Arc::new(ImageRes { width: 64, height: 64, rgba: vec![[0.5; 4]; 64 * 64], srgb: false })); + session.images.insert(name, Arc::new(ImageRes::new(64, 64, vec![[0.5; 4]; 64 * 64], false))); } let creation_context = eframe::CreationContext::_new_kittest(egui::Context::default()); let mut app = TextureCraftApp::new(&creation_context, session); diff --git a/crates/ui-egui/src/projection_preview.rs b/crates/ui-egui/src/projection_preview.rs index fefc92d8..903a01a9 100644 --- a/crates/ui-egui/src/projection_preview.rs +++ b/crates/ui-egui/src/projection_preview.rs @@ -29,6 +29,8 @@ use rendered_preview::RenderedPreview; use screen::Screen; use view::View; +/// The whole of a texture, as the part of it a picture shows +const FULL_UV: Rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); /// Largest preview side in pixels; the square is never drawn bigger than this const MAX_SIDE_PX: usize = 256; diff --git a/crates/ui-egui/src/property_sheet/group.rs b/crates/ui-egui/src/property_sheet/group.rs index d115e162..09ff1a4c 100644 --- a/crates/ui-egui/src/property_sheet/group.rs +++ b/crates/ui-egui/src/property_sheet/group.rs @@ -2,6 +2,7 @@ use egui::{Align2, CornerRadius, FontId, Rect, Sense, Shape, Stroke, pos2, vec2} use egui_phosphor::regular as ic; use super::row::{EDGE_GLYPH_INSET, RESET_ICON_SIZE}; +use super::{BandResponse, GROUP_GAP, PropertySheet, TEXT_SIZE}; use crate::theme::semibold; /// Draws a band's picture in its rect diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index cbd25d6a..1da4e0eb 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -26,7 +26,6 @@ mod tooltip; mod track; mod value_text; -pub(crate) use section_tabs::{full_height_tab_rect, shown_tab_box}; #[cfg(test)] mod tests; @@ -36,6 +35,7 @@ pub(crate) use number_field::NumberField; pub(crate) use preview_lower::PreviewLower; pub(crate) use preview_size::PreviewSize; pub(crate) use row_lead::RowLead; +pub(crate) use section_tabs::{SectionScope, forget_sections, full_height_tab_rect, in_scope, room_past_end, section_tabs, shown_tab_box}; pub(crate) use stack_slider::StackSlider; use egui::{Color32, FontId, Id, Rect, Ui, pos2, vec2}; diff --git a/crates/ui-egui/src/property_sheet/row_lead.rs b/crates/ui-egui/src/property_sheet/row_lead.rs index 5d3b981c..36d82d8a 100644 --- a/crates/ui-egui/src/property_sheet/row_lead.rs +++ b/crates/ui-egui/src/property_sheet/row_lead.rs @@ -25,6 +25,7 @@ impl<'a> RowLead<'a> { /// The row's name, as assistive tech reads it pub(crate) fn text(self) -> &'a str { match self { + RowLead::Label { text, .. } | RowLead::Loose(text) | RowLead::Picture { text, .. } | RowLead::Child(text) => text, } } } diff --git a/crates/ui-egui/src/property_sheet/section_tabs.rs b/crates/ui-egui/src/property_sheet/section_tabs.rs index 99edf990..8daf36e5 100644 --- a/crates/ui-egui/src/property_sheet/section_tabs.rs +++ b/crates/ui-egui/src/property_sheet/section_tabs.rs @@ -1,7 +1,5 @@ -use egui::{CornerRadius, Painter, Rect, pos2}; use egui::{Align2, Color32, CornerRadius, FontId, Id, Painter, Rect, Role, Sense, Ui, WidgetInfo, pos2, vec2}; -use crate::theme::Tokens; use super::row::SECTION_RULE_TO_CAPTION; use super::{PAD, SMALL_TEXT_SIZE}; use crate::theme::{Tokens, semibold}; diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index cfd35af1..a377cfdd 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -1,9 +1,11 @@ use std::ops::RangeInclusive; +use egui::{Align2, Id, Rect, Sense, Stroke, WidgetInfo, pos2}; use super::number_field::shown_number; use super::track::Track; use super::value_text::ValueText; +use super::{PropertySheet, ROW_HIT_HALF_HEIGHT, RowLead, TEXT_SIZE}; use crate::theme::semibold; /// Radius of a slider's knob diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs index 96e72f7e..fe2cef24 100644 --- a/crates/ui-egui/src/property_sheet/slot.rs +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -1,4 +1,6 @@ +use egui::{CornerRadius, FontId, Sense, Stroke, StrokeKind, pos2}; +use super::{ButtonIcon, CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, TEXT_SIZE}; /// Air between a full-width button's icon and its words const BUTTON_ICON_GAP: f32 = 8.0; diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index e0107857..54b099f8 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -1,5 +1,6 @@ use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use super::{CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, SMALL_TEXT_SIZE, TEXT_SIZE}; use crate::theme::semibold; /// Draws a picture row's picture into its square diff --git a/crates/ui-egui/src/property_sheet/tests/gallery.rs b/crates/ui-egui/src/property_sheet/tests/gallery.rs index 3a9e730a..b1774512 100644 --- a/crates/ui-egui/src/property_sheet/tests/gallery.rs +++ b/crates/ui-egui/src/property_sheet/tests/gallery.rs @@ -2,6 +2,7 @@ use super::Filtering; +/// The gallery's controls, with the values they last set pub(super) struct Gallery { pub(super) filtering: Filtering, pub(super) position: [f32; 3], @@ -11,5 +12,6 @@ pub(super) struct Gallery { impl Default for Gallery { fn default() -> Self { + Gallery { filtering: Filtering::BilinearHq, position: [0.0, 1.25, -0.5], position_merges: Vec::new(), linked: true } } } diff --git a/crates/ui-egui/src/round_gizmo.rs b/crates/ui-egui/src/round_gizmo.rs index 146cd50f..0e531677 100644 --- a/crates/ui-egui/src/round_gizmo.rs +++ b/crates/ui-egui/src/round_gizmo.rs @@ -429,6 +429,7 @@ pub(crate) mod tests { use texturecraft_engine::core::{Fill, LayerId, LayerKind, Projection, Projector}; use super::*; + use crate::frame_gizmo::tests::{drag, drag_frames, fill_app, fill_app_with, panel_xyz, press_and_move, projection}; fn gizmo(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> RoundGizmo { RoundGizmo::of(harness.state(), harness.state().viewport_rect).unwrap() diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 159fdecc..4a8015ec 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -877,6 +877,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let popup = app.properties_popup.is_some() || rail_popup; // A pending ID color pick takes the next click instead of the brush + let picking = app.picking_id_color.is_some(); if picking { crate::id_color_pick::IdColorPick::draw_cursor(ui, rect); if !alt diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs index fcc33f66..f3b7823b 100644 --- a/crates/ui-egui/tests/it/properties_popup.rs +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -208,9 +208,13 @@ fn its_jump_tabs_scroll_to_a_section_and_light_it_without_moving_the_docked_pane assert!(tab_lit(&harness, popup, "Fill"), "it opens on Fill"); assert!(in_popup(&harness, "UV projection")); + let symmetry = harness.get_all_by_role_and_label(Role::Tab, "Symmetry").find(|tab| popup.contains_rect(tab.rect())).unwrap().rect().center(); + click(&mut harness, PointerButton::Primary, symmetry); harness.run_steps(JUMP_FRAMES); assert!(is_open(&harness), "a tab click keeps it open"); + assert!(!in_popup(&harness, "UV projection"), "the list jumped down to SYMMETRY"); + assert!(tab_lit(&harness, popup, "Symmetry"), "the section in view is lit"); assert!(!tab_lit(&harness, popup, "Fill")); assert!(tab_lit(&harness, docked, "Fill"), "the docked panel keeps its own place"); } From a7d165e0295b60a5d6136bddefc8d4854786299e Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 22 Nov 2026 05:29:12 +0000 Subject: [PATCH 16/17] Fills: review repairs from #698 Chasse's repairs to this part's code, carried over from the #698 head (5644b7d3). --- apps/texturecraft/src/main.rs | 3 +- crates/automation/src/render.rs | 3 + crates/compose/src/axis_frame.rs | 1 + crates/compose/src/eval.rs | 205 +++++++++++++++--- crates/compose/src/eval/evaluation_inputs.rs | 23 ++ crates/compose/src/eval/thumbnail.rs | 9 +- crates/compose/src/fill_copies.rs | 5 + crates/compose/src/frame_placement.rs | 9 + crates/compose/src/lib.rs | 5 +- crates/compose/src/pattern.rs | 23 ++ crates/compose/src/projector_cover.rs | 13 +- crates/compose/src/projector_depth.rs | 103 +++------ crates/compose/src/projector_depth_cache.rs | 97 +++++++++ crates/compose/src/solo.rs | 9 + crates/compose/src/store.rs | 1 + crates/compose/src/tile_length.rs | 9 +- crates/compose/src/tile_length/mesh_size.rs | 6 + crates/compose/tests/cache_and_instances.rs | 22 ++ crates/core/src/layer.rs | 34 ++- crates/core/src/layer/filtering.rs | 30 +++ crates/core/src/layer/sampling.rs | 33 +++ crates/core/src/layer/scale_mode.rs | 25 +++ crates/core/src/layer/uv_transform.rs | 22 ++ crates/core/src/layer/uv_wrap.rs | 40 ++++ crates/core/src/project.rs | 1 + crates/engine/src/decal_cmds.rs | 2 +- crates/engine/src/fill_reset_cmds.rs | 5 + crates/engine/src/layer_cmds.rs | 4 + crates/engine/src/layer_cmds/fill_target.rs | 8 + crates/engine/src/resource_cmds.rs | 1 + crates/engine/src/session.rs | 53 +++-- crates/engine/src/thumbs.rs | 7 + crates/engine/src/view_cmds.rs | 14 ++ crates/engine/tests/it/fill_patterns.rs | 2 + crates/engine/tests/it/fill_projections.rs | 69 ++++++ crates/engine/tests/it/fill_sampling.rs | 13 ++ crates/engine/tests/it/painter_gaps.rs | 64 +++++- crates/engine/tests/it/user_smart_mask.rs | 1 + crates/geom/src/mesh.rs | 2 + crates/paint/src/brush.rs | 1 + crates/render/tests/headless.rs | 4 +- crates/ui-egui/src/dock.rs | 12 +- crates/ui-egui/src/fill_panel.rs | 4 +- crates/ui-egui/src/fill_pictures.rs | 1 + crates/ui-egui/src/fill_symmetry_panel.rs | 6 + crates/ui-egui/src/frame_gizmo.rs | 35 ++- crates/ui-egui/src/gray_slider.rs | 3 + crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/move_on_model.rs | 25 +++ crates/ui-egui/src/pointer_lock/tests.rs | 10 + crates/ui-egui/src/preview_dots.rs | 2 + crates/ui-egui/src/projection_gizmo.rs | 6 +- .../src/projection_gizmo/gizmo_drag.rs | 7 +- crates/ui-egui/src/projection_preview.rs | 39 +++- crates/ui-egui/src/properties_popup.rs | 3 + .../ui-egui/src/property_sheet/axis_rows.rs | 1 + .../ui-egui/src/property_sheet/info_icon.rs | 2 + crates/ui-egui/src/property_sheet/mod.rs | 9 +- .../src/property_sheet/number_field.rs | 17 +- crates/ui-egui/src/property_sheet/slider.rs | 18 +- .../src/property_sheet/switch_control.rs | 24 +- crates/ui-egui/src/property_sheet/tests.rs | 2 + .../ui-egui/src/property_sheet/value_text.rs | 67 ++++-- .../src/property_sheet/value_text_draft.rs | 9 + crates/ui-egui/src/render_mode/tests.rs | 2 + crates/ui-egui/src/round_gizmo.rs | 33 ++- crates/ui-egui/src/symmetry/view_overlay.rs | 8 +- crates/ui-egui/src/theme.rs | 18 +- crates/ui-egui/src/viewport.rs | 33 ++- crates/ui-egui/src/viewport_mesh_bounds.rs | 23 ++ crates/ui-egui/src/widgets.rs | 13 +- crates/ui-egui/tests/brush_cursor_2d.rs | 4 + .../ui-egui/tests/it/fill_projection_rows.rs | 9 + crates/ui-egui/tests/it/fill_symmetry_rows.rs | 12 + crates/ui-egui/tests/it/polygon_fill.rs | 7 + crates/ui-egui/tests/it/project_config.rs | 3 + crates/ui-egui/tests/it/properties_popup.rs | 5 + crates/ui-egui/tests/it/shelf_drop.rs | 2 + crates/ui-egui/tests/ui_snapshots.rs | 1 + 79 files changed, 1198 insertions(+), 261 deletions(-) create mode 100644 crates/compose/src/eval/evaluation_inputs.rs create mode 100644 crates/compose/src/projector_depth_cache.rs create mode 100644 crates/compose/src/tile_length/mesh_size.rs create mode 100644 crates/core/src/layer/filtering.rs create mode 100644 crates/core/src/layer/sampling.rs create mode 100644 crates/core/src/layer/scale_mode.rs create mode 100644 crates/core/src/layer/uv_transform.rs create mode 100644 crates/core/src/layer/uv_wrap.rs create mode 100644 crates/engine/src/layer_cmds/fill_target.rs create mode 100644 crates/ui-egui/src/property_sheet/value_text_draft.rs create mode 100644 crates/ui-egui/src/viewport_mesh_bounds.rs diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 3a768c2b..4af56d84 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -165,8 +165,7 @@ impl eframe::App for Shell { } fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { - // winit gives the window its caption back when it changes the window's flags (maximize, - // restore, …): take it off again before the frame is laid out. + // Restore the frameless style after winit changes the window flags if let Some(guard) = self.window_frame.as_mut() { guard(); } diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index 588f1752..d626849e 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -284,7 +284,9 @@ mod tests { let mut mesh = texturecraft_engine::geom::primitives::plane(2.0, 1); mesh.append(&texturecraft_engine::geom::primitives::plane(2.0, 1)); let mut session = Session::new_project("Test", mesh, "two-planes", None, 128).unwrap(); + assert_eq!(session.caches.len(), 2); + session.images.insert("red".into(), Arc::new(ImageRes::new(1, 1, vec![[1.0, 0.0, 0.0, 1.0]], true))); execute(&mut session, "viewport.view", &json!({"mode": "image", "image": "red"})).unwrap(); let camera = session.camera; @@ -302,6 +304,7 @@ mod tests { assert!(first.as_chunks::<4>().0.iter().any(|pixel| pixel[0] > 200 && pixel[1] < 20)); let (_, _, second) = gpu.render(&mut session, uv(1), [128, 128], camera).unwrap(); + assert!(second.as_chunks::<4>().0.iter().any(|pixel| pixel[0] > 200 && pixel[1] < 20)); assert_eq!(gpu.h.renderer.aux_size(1), Some(128)); } diff --git a/crates/compose/src/axis_frame.rs b/crates/compose/src/axis_frame.rs index a4daa864..b63be023 100644 --- a/crates/compose/src/axis_frame.rs +++ b/crates/compose/src/axis_frame.rs @@ -151,6 +151,7 @@ mod tests { fn only_axis_planars_are_placed() { let bounds = (Vec3::NEG_ONE, Vec3::ONE); assert!(placed_from_axis(&Projection::default(), bounds).is_none()); + let frame = axis_frame(1.0, 2, Vec3::ZERO, &Projector::default(), bounds).expect("a frame"); assert!(placed_from_axis(&Projection::decal(frame), bounds).is_none()); assert!(axis_frame(f32::NAN, 2, Vec3::ZERO, &Projector::default(), bounds).is_none()); diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 6413c421..5dedc593 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2,6 +2,7 @@ //! tile by tile in parallel. This is the reference implementation (the oracle) for the viewport //! and for export. +mod evaluation_inputs; pub(crate) mod thumbnail; use std::borrow::Cow; @@ -18,6 +19,7 @@ use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; +use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; use crate::curvature_sizes::CurvatureSizes; use crate::fill_copies::FillCopies; @@ -29,6 +31,7 @@ use crate::pattern_context::PatternContext; use crate::projector_cover::{framed_cover, projector_cover, projector_covers_all}; use crate::projector_depth::ProjectorDepth; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; +use evaluation_inputs::EvaluationInputs; const NCH: usize = Channel::ALL.len(); @@ -71,6 +74,7 @@ impl Stencil { if c.w <= 1e-6 { return None; } + let (dx, dy) = (c.x / c.w - self.center[0], c.y / c.w - self.center[1]); let (sn, cs) = (-self.rotation).sin_cos(); let lx = (dx * cs - dy * sn) / self.half[0].max(1e-6); @@ -78,6 +82,7 @@ impl Stencil { if !self.tile && (lx.abs() > 1.0 || ly.abs() > 1.0) { return None; } + let s = self.image.sample(lx * 0.5 + 0.5, 0.5 - ly * 0.5); let rgb = if self.image.srgb { [s[0], s[1], s[2]].map(texturecraft_texel::srgb_to_linear) } else { [s[0], s[1], s[2]] }; Some((rgb, s[3].clamp(0.0, 1.0))) @@ -279,6 +284,7 @@ impl Field { if x < self.x0 || y < self.y0 || x >= self.x0 + self.w || y >= self.y0 + self.h { return None; } + let i = ((y - self.y0) * self.w + (x - self.x0)) as usize * self.comps; self.data.get(i..i + self.comps) } @@ -600,7 +606,7 @@ fn stroke_at(preview: Option<&[u16]>, o: usize) -> f32 { /// The full stack of tile (tx, ty) when `layer` reads anchor points (empty otherwise): evaluated /// up to the layer, it records the anchors below it. -fn anchor_plan<'a>(inp: &Inputs<'a>, id: LayerId, channels: &[Channel], tx: u32, ty: u32, fields: Option<&'a Fields>) -> Vec> { +fn anchor_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, channels: &[Channel], tx: u32, ty: u32, fields: Option<&'a Fields>) -> Vec> { match inp.project.texture_set(inp.ts) { Ok(set) if reads_anchor(inp.project, id) => plan(inp, &set.stack, channels, tx, ty, 0, fields), _ => Vec::new(), @@ -639,7 +645,7 @@ enum Job<'a> { } /// A layer's mask or content channel after every neighbourhood filter of its stack, over `tiles`. -fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: Job, tiles: &[(u32, u32)]) -> Option { +fn field(inp: &EvaluationInputs, channels: &[Channel], below: &Fields, id: LayerId, job: Job, tiles: &[(u32, u32)]) -> Option { let effects = match job { Job::Mask(mask) => &mask.effects, Job::Content(_) => &inp.project.content_layer(id)?.content_effects, @@ -709,7 +715,7 @@ fn is_box_blur(op: Op) -> bool { /// The stack up to and including neighbourhood filter `filter` over texel `region`, continued from `start` (the filter below's field) when given. #[allow(clippy::too_many_arguments)] fn filter_region( - inputs: &Inputs, + inputs: &EvaluationInputs, channels: &[Channel], below: &Fields, id: LayerId, @@ -1021,13 +1027,19 @@ fn unpremultiply(data: &mut [f32], comps: usize) { /// Precompute the neighbourhood-filtered masks and content channels of every layer that needs /// one, over `tiles` plus the filter's reach. Walks bottom → top so each field sees the fields /// (and anchors) below it. Cheap when no layer has a blur or sharpen. -pub fn neighbourhood_fields(inp: &Inputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Fields { +pub fn neighbourhood_fields(inputs: &Inputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Fields { + let projectors = ProjectorDepthCache::default(); + let inputs = EvaluationInputs::new(inputs, &projectors); + evaluation_fields(&inputs, channels, tiles) +} + +fn evaluation_fields(inp: &EvaluationInputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Fields { let stack = inp.project.texture_set(inp.ts).map(|s| s.stack.as_slice()).unwrap_or_default(); fields_of(inp, channels, stack, tiles) } /// [`neighbourhood_fields`] of the layers drawn by `list` only. -fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32, u32)]) -> Fields { +fn fields_of(inp: &EvaluationInputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32, u32)]) -> Fields { let mut out = Fields::new(); if tiles.is_empty() || inp.gbuf.width == 0 { return out; @@ -1147,7 +1159,8 @@ fn tile_of<'a>(inp: &Inputs, img: Option<&'a TileImage>, tx: u32, ty: u32, chann if (img.width(), img.height()) == (w, h) { return img.tile(tx, ty).map(Cow::Borrowed); } - // Empty texels of signed channels hold a signed zero. + + // Empty texels of signed channels hold a signed zero let empty: Vec = match channel { Some(c) if c.kind() == ChannelKind::Signed => [vec![to_u16_signed(0.0); c.components()], vec![0]].concat(), _ => Vec::new(), @@ -1171,7 +1184,7 @@ fn mask_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, mask: &'a Mask, tx: u3 Some(MaskPlan { background, effects, start }) } -fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec> { +fn plan<'a>(inp: &EvaluationInputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec> { if depth > texturecraft_core::project::MAX_DEPTH { return Vec::new(); } @@ -1182,7 +1195,7 @@ fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, t /// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are planned when `kids` #[allow(clippy::too_many_arguments)] fn plan_node<'a>( - inp: &Inputs<'a>, + inp: &EvaluationInputs<'a>, id: LayerId, channels: &[Channel], tx: u32, @@ -1271,7 +1284,7 @@ struct LevelPlan<'a> { /// Plan the path to the hot layer for tile (tx, ty); the layers before the path are left out /// on tiles the cache holds (`warm`). -fn plan_levels<'a>(inp: &Inputs<'a>, levels: &[Level], channels: &[Channel], tx: u32, ty: u32, fields: &'a Fields, warm: bool) -> Vec> { +fn plan_levels<'a>(inp: &EvaluationInputs<'a>, levels: &[Level], channels: &[Channel], tx: u32, ty: u32, fields: &'a Fields, warm: bool) -> Vec> { let last = levels.len().saturating_sub(1); levels .iter() @@ -1294,6 +1307,7 @@ fn over(c: &ChanPlan, mode: BlendMode, v: [f32; 3], cov: f32, p: [f32; 3], a: f3 if a <= 0.0 { return (v, cov); } + let b = if cov > 0.0 { blend_chan(c, mode, v, p) } else { p }; let nc = a + cov * (1.0 - a); (mix3(v, b, a / nc.max(1e-5)), nc) @@ -1312,8 +1326,8 @@ fn covers_every_texel(proj: &Projection, sampling: Sampling, depth: Option<&Proj } /// A fill's projector depth (None: not culled by depth) and whether it covers every texel -fn fill_coverage(inp: &Inputs, projection: &Projection, sampling: Sampling) -> (Option>, bool) { - let depth = ProjectorDepth::of(inp.mesh, inp.bounds, projection); +fn fill_coverage(inp: &EvaluationInputs, projection: &Projection, sampling: Sampling) -> (Option>, bool) { + let depth = inp.projectors.get(inp.mesh, inp.bounds, projection); let covers_all = covers_every_texel(projection, sampling, depth.as_deref()); (depth, covers_all) } @@ -1523,7 +1537,7 @@ impl<'a, 'b> Texel<'a, 'b> { /// A fill's value and coverage through `proj`, from `one` (which samples it once): with `sampling`'s symmetry on, every copy of the projection is sampled and the copies are laid over each other, the texel's own copy on top fn symmetric(&mut self, proj: &Projection, sampling: Sampling, mut one: impl FnMut(&mut Self) -> ([f32; 3], f32)) -> ([f32; 3], f32) { - // Most fills have no symmetry: they are sampled directly and never pay for the surface lookup + // Skip the world-space lookup when no symmetry copies are needed if !takes_symmetry(proj, sampling) { return one(self); } @@ -1589,7 +1603,7 @@ impl<'a, 'b> Texel<'a, 'b> { /// `place`'s fill at this texel in channel `ch`, every symmetric copy laid over each other when its symmetry is on #[inline(always)] fn fill_place_texel(&mut self, place: FillPlace, source: Option<&Source>, ch: Channel) -> ([f32; 3], f32) { - // Without symmetry the fill is sampled directly: through `symmetric`'s closure a plain fill composites about 8% slower + // Sample directly without symmetry to keep the common path free of the copy search if takes_symmetry(&place.fill.projection, place.fill.sampling) { self.symmetric(&place.fill.projection, place.fill.sampling, |texel| texel.fill_texel(place, source, ch)) } else { @@ -1646,7 +1660,7 @@ impl<'a, 'b> Texel<'a, 'b> { let samples = self.image_uvs(proj, &c); let [(uv, _), ..] = samples; - // The shape is read over the footprint the image's colour is, so a shrunk image's coverage matches its averaged colour + // Use the image's sampling footprint so minified color and coverage agree let alpha = image.map_or(1.0, |img| { let [footprint, ..] = match sampling.filtering { Filtering::BilinearHq => self.footprints(proj, &samples, img), @@ -1818,7 +1832,7 @@ impl<'a, 'b> Texel<'a, 'b> { /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). fn generator_input(&mut self, generator: &Generator, map: BakedMap) -> Option { match generator.inputs.get(&map) { - // Generator inputs have no sampling setting: they read as projects saved before sampling choices did + // Keep legacy sampling for generator inputs without a sampling setting Some(source) => Some(self.source(source, &Projection::default(), Sampling::SAVED_BEFORE, ChannelKind::Scalar)[0]), None => self.baked(map), } @@ -2026,8 +2040,8 @@ impl<'a, 'b> Texel<'a, 'b> { /// is identical. fn eval_split(&mut self, mut acc: Acc, levels: &[LevelPlan], accs: &mut [Acc], masks: &mut [f32], warm: bool, tape: &mut Tape<'b>) -> Acc { let last = levels.len().saturating_sub(1); - // Down the path: the deepest level the stack reaches (a folder masked out or not drawn - // here stops it). + + // A hidden or masked folder limits how far the evaluator descends let mut reach = last; for (d, lv) in levels.iter().enumerate() { if !warm { @@ -2039,6 +2053,7 @@ impl<'a, 'b> Texel<'a, 'b> { if d == last { break; } + let m = match &lv.at { Some(g) => self.taped(tape, |t| t.tape_mask(g)), None => 0.0, @@ -2049,6 +2064,7 @@ impl<'a, 'b> Texel<'a, 'b> { if m > 0.0 { continue; } + reach = d; break; } @@ -2058,7 +2074,7 @@ impl<'a, 'b> Texel<'a, 'b> { { self.eval(std::slice::from_ref(hot), &mut acc); } - // Back up: the layers after the path, then each folder's mix over the stack outside it. + // Back up: the layers after the path, then each folder's mix over the stack outside it for d in (0..=reach).rev() { if let Some(lv) = levels.get(d) { self.taped(tape, |t| t.eval(&lv.above, &mut acc)); @@ -2100,10 +2116,11 @@ impl<'a, 'b> Texel<'a, 'b> { if tri == NO_TRI { return true; } + let first = tri.saturating_mul(3); let subs = &self.inp.mesh.submeshes; let holds = |k: usize| subs.get(k).is_some_and(|s| s.start <= first && first < s.start.saturating_add(s.count)); - // Submeshes are in index order; anything else is searched. + // Submeshes are in index order; anything else is searched let k = subs.partition_point(|s| s.start <= first).checked_sub(1).filter(|k| holds(*k)).or_else(|| (0..subs.len()).find(|k| holds(*k))); k.and_then(|k| allowed.get(k).copied()).unwrap_or(true) } @@ -2154,7 +2171,7 @@ impl<'a, 'b> Texel<'a, 'b> { fn painted(&mut self, data: Option<&[u16]>, c: &ChanPlan, preview: bool) -> ([f32; 3], f32) { let pv = if preview { self.inp.preview } else { None }; let mut sa = pv.map(|p| (self.stroke * p.opacity).clamp(0.0, 1.0)).unwrap_or(0.0); - // Projection: the stencil's alpha shapes the stroke and its color is the base color. + // Projection: the stencil's alpha shapes the stroke and its color is the base color let stencil = match pv.and_then(|p| p.stencil.as_ref()) { Some(st) if sa > 0.0 => { let s = self.world().and_then(|w| st.sample_world(w)); @@ -2200,6 +2217,7 @@ impl<'a, 'b> Texel<'a, 'b> { if cov <= 0.0 { return ([0.0; 3], 0.0); } + let inv = 1.0 / cov.max(1e-5); let v = if c.comps == 3 { val.map(|x| x * inv) } else { [val[0] * inv; 3] }; (v, cov.min(1.0)) @@ -2272,7 +2290,37 @@ pub const BLOCK: u32 = 16; /// [`composite_tiles`], serving everything but the hot layer from `below` where it can (and /// filling it). Results are identical to [`composite_tiles`]. -pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, u32)], mut below: Option<&mut BelowCache>) { +pub fn composite_tiles_cached(inputs: &Inputs, out: &mut Composite, tiles: &[(u32, u32)], below: Option<&mut BelowCache>) { + let projectors = ProjectorDepthCache::default(); + let inputs = EvaluationInputs::new(inputs, &projectors); + composite_evaluation_tiles(&inputs, out, tiles, below); +} + +/// Composite tile batches with a reusable cache for the mesh owned by the caller. +pub fn composite_tiles_with_projectors( + inputs: &Inputs, + mesh: &Arc, + projectors: &mut ProjectorDepthCache, + out: &mut Composite, + tiles: &[(u32, u32)], + mut below: Option<&mut BelowCache>, +) { + if !std::ptr::eq(inputs.mesh, mesh.as_ref()) { + composite_tiles_cached(inputs, out, tiles, None); + return; + } + + if projectors.bind(mesh) + && let Some(cache) = below.as_deref_mut() + { + cache.clear(); + } + + let inputs = EvaluationInputs::new(inputs, projectors); + composite_evaluation_tiles(&inputs, out, tiles, below); +} + +fn composite_evaluation_tiles(inp: &EvaluationInputs, out: &mut Composite, tiles: &[(u32, u32)], mut below: Option<&mut BelowCache>) { let Ok(set) = inp.project.texture_set(inp.ts) else { return }; if (inp.gbuf.width, inp.gbuf.height) != (out.resolution, out.height) { return; @@ -2378,7 +2426,7 @@ fn has_neighbourhood(inp: &Inputs, stack: &[LayerId]) -> bool { /// The neighbourhood fields compositing `tiles` reads: those of every layer of `stack` over the tiles the cache lacks (`fresh`), /// and off the path to the `hot` layer only there; the hot layer's over all of `tiles`. -fn block_fields(inp: &Inputs, channels: &[Channel], stack: &[LayerId], hot: Option<&Level>, fresh: &[(u32, u32)], tiles: &[(u32, u32)]) -> Fields { +fn block_fields(inp: &EvaluationInputs, channels: &[Channel], stack: &[LayerId], hot: Option<&Level>, fresh: &[(u32, u32)], tiles: &[(u32, u32)]) -> Fields { match hot { Some(hot) if fresh.len() < tiles.len() => { let mut fields = fields_of(inp, channels, stack, fresh); @@ -2402,7 +2450,7 @@ type Joined = (Vec>>>, bool); /// Composite one block of tiles, split along the path to the hot layer when `below` holds it; /// returns what to cache (for at most `quota` tiles). fn composite_block( - inp: &Inputs, + inp: &EvaluationInputs, stack: &[LayerId], out: &mut Composite, tiles: &[(u32, u32)], @@ -2421,7 +2469,7 @@ fn composite_block( let level_count = split.map_or(0, <[Level]>::len); let defaults: Acc = Channel::ALL.map(Channel::default_value); - // Tiles split into bands of rows, so a handful of tiles still keeps every thread busy. + // Tiles split into bands of rows, so a handful of tiles still keeps every thread busy let bands = TILE / BAND; let tasks: Vec<((u32, u32), u32)> = tiles.iter().flat_map(|t| (0..bands).map(move |b| (*t, b))).collect(); let mut results: Vec = tasks @@ -2459,11 +2507,13 @@ fn composite_block( if y >= h { break; } + for lx in 0..TILE { let x = tx * TILE + lx; if x >= w { break; } + let gbuffer_index = (y * w + x) as usize; let tile_offset = (ly * TILE + lx) as usize; let band_offset = ((ly - band * BAND) * TILE + lx) as usize; @@ -2473,11 +2523,11 @@ fn composite_block( any = true; let mut texel = Texel::new(inp, x, y, tile_offset, stroke_at(preview_tile, tile_offset)); - // Reuse one anchor buffer per band. + // Reuse one anchor buffer per band texel.anchors = std::mem::take(&mut anchors); match &levels { Some(levels) => { - // The texel's stream starts with the stack at each level. + // The texel's stream starts with the stack at each level let start = match &mut tape { Tape::Record(t) => { t.resize(t.len() + slots, 0.0); @@ -2518,7 +2568,7 @@ fn composite_block( }) .collect(); - // Join the bands of each tile (in parallel; uncovered tiles are freed). + // Join the bands of each tile (in parallel; uncovered tiles are freed) let joined: Vec = results .par_chunks(bands as usize) .map(|parts| { @@ -2545,7 +2595,7 @@ fn composite_block( } } - // Tiles without covered texels cost nothing to composite: not worth caching. + // Tiles without covered texels cost nothing to composite: not worth caching if any && let Some(bands) = parts.iter_mut().map(|p| p.1.take()).collect::>>() { records.push(((tx, ty), bands)); } @@ -2676,6 +2726,8 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) /// orientation of the exported maps), `gbuf.width × gbuf.height` of them; black outside the mesh /// Returns None without an enabled mask pub fn mask_texels(inputs: &Inputs, id: LayerId) -> Option> { + let projectors = ProjectorDepthCache::default(); + let inputs = &EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default(); let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); @@ -2684,7 +2736,7 @@ pub fn mask_texels(inputs: &Inputs, id: LayerId) -> Option> { // A hidden layer's mask is left out of the stack's preparation prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); - let fields = neighbourhood_fields(inputs, &channels, &coordinates); + let fields = evaluation_fields(inputs, &channels, &coordinates); let width_usize = width as usize; let tile_side = TILE as usize; let mut output = vec![0.0f32; width_usize * height as usize]; @@ -2709,6 +2761,8 @@ pub fn mask_texels(inputs: &Inputs, id: LayerId) -> Option> { /// Keep preview tiles at 8 bits instead of retaining the export's full float atlas /// Returns None without an enabled mask pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { + let projectors = ProjectorDepthCache::default(); + let inputs = &EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default(); let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); @@ -2717,7 +2771,12 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { // A hidden layer's mask is left out of the stack's preparation prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); - let fields = neighbourhood_fields(inputs, &channels, &coordinates); + let fields = evaluation_fields(inputs, &channels, &coordinates); + let size = size.max(1); + if size <= width.min(height) && (width != size || height != size) { + return Some(downsample_mask(inputs, id, mask, &channels, &fields, size)); + } + let width_usize = width as usize; let tile_side = TILE as usize; let mut atlas = vec![0u8; width_usize * height as usize]; @@ -2736,7 +2795,6 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { } }); - let size = size.max(1); if width == size && height == size { return Some(atlas); } @@ -2756,6 +2814,49 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { Some(output) } +/// Sample a smaller mask image directly into disjoint output row groups +fn downsample_mask(inputs: &EvaluationInputs, id: LayerId, mask: &Mask, channels: &[Channel], fields: &Fields, size: u32) -> Vec { + let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); + let source_at = |pixel, span| ((u64::from(pixel) * u64::from(span)) / u64::from(size)) as u32; + let first_output = |source, span| (u64::from(source) * u64::from(size)).div_ceil(u64::from(span)).min(u64::from(size)) as u32; + let mut output = vec![0; size as usize * size as usize]; + let mut destination = output.as_mut_slice(); + let mut bands = Vec::with_capacity(height.div_ceil(TILE) as usize); + + // Partition rows by the tile that contains each row's source texels + for tile_y in 0..height.div_ceil(TILE) { + let first_row = first_output(tile_y * TILE, height); + let past_row = first_output((tile_y + 1) * TILE, height); + if past_row > first_row { + let (rows, rest) = destination.split_at_mut((past_row - first_row) as usize * size as usize); + bands.push((tile_y, first_row, past_row, rows)); + destination = rest; + } + } + + bands.into_par_iter().for_each(|(tile_y, first_row, past_row, rows)| { + for tile_x in 0..width.div_ceil(TILE) { + let first_column = first_output(tile_x * TILE, width); + let past_column = first_output((tile_x + 1) * TILE, width); + if first_column == past_column { + continue; + } + + let offsets = (first_row..past_row).flat_map(|row| { + let y = source_at(row, height) % TILE; + (first_column..past_column).map(move |column| (y * TILE + source_at(column, width) % TILE) as usize) + }); + let texels = mask_tile(inputs, id, mask, channels, fields, (tile_x, tile_y), offsets); + let pixels = rows.chunks_exact_mut(size as usize).flat_map(|row| &mut row[first_column as usize..past_column as usize]); + for (pixel, (_, value)) in pixels.zip(texels) { + *pixel = (value * 255.0 + 0.5) as u8; + } + } + }); + + output +} + /// The layer mask as one-component values at the texture set's full resolution over `tiles` /// (uncovered texels read zero). Clone and smudge read it. Unlike [`mask_image`] it also reads a /// disabled mask; None when the layer has no mask. @@ -2767,11 +2868,13 @@ pub fn mask_values(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option /// Evaluate requested tiles directly into the stroke's mask image. pub fn mask_values_into(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)], image: &mut TileImage) -> Option<()> { + let projectors = ProjectorDepthCache::default(); + let inputs = &EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id)?; let channels = inputs.project.texture_set(inputs.ts).ok()?.channel_list(); prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); - let fields = neighbourhood_fields(inputs, &channels, tiles); + let fields = evaluation_fields(inputs, &channels, tiles); let computed: Vec<((u32, u32), Vec)> = tiles .par_iter() .map(|&tile| { @@ -2794,6 +2897,8 @@ pub fn mask_values_into(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)], imag /// Mask values at texture-set coordinates, in request order; None without an enabled mask /// Uncovered and out-of-range texels read zero; neighbourhood filters also evaluate surrounding texels pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option> { + let projectors = ProjectorDepthCache::default(); + let inputs = &EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; let mut output = vec![0.0; texels.len()]; @@ -2818,7 +2923,7 @@ pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option = requested .par_iter_mut() .flat_map_iter(|(&tile, requests)| { @@ -2841,7 +2946,7 @@ pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option( - inputs: &'a Inputs<'a>, + inputs: &'a EvaluationInputs<'a>, id: LayerId, mask: &'a Mask, channels: &[Channel], @@ -2902,6 +3007,8 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u } }; let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; + let projectors = ProjectorDepthCache::default(); + let cut_inp = EvaluationInputs::new(&cut_inp, &projectors); let channels = cut.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height); // A field covers the bounding box of the tiles it is built for, which for a scattered sample @@ -2981,7 +3088,9 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti l.visible = true; } let visible_inputs = Inputs { project: &solo, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; - let fields = neighbourhood_fields(&visible_inputs, &channels, tiles); + let projectors = ProjectorDepthCache::default(); + let visible_inputs = EvaluationInputs::new(&visible_inputs, &projectors); + let fields = evaluation_fields(&visible_inputs, &channels, tiles); let out: Vec> = tiles .par_iter() @@ -3155,6 +3264,7 @@ mod tests { // Not repeating, it crops to its tile, so it has to know where each texel lands let Ok(LayerKind::Fill(fill)) = f.project.layer_mut(id).map(|layer| &mut layer.kind) else { panic!("fill layer") }; fill.sampling.wrap = texturecraft_core::UvWrap::None; + assert!(coords_lookups(&f) > 0); } @@ -3173,6 +3283,7 @@ mod tests { // Not repeating, it crops to its tile, so each texel works its coverage out let Ok(LayerKind::Fill(fill)) = f.project.layer_mut(id).map(|layer| &mut layer.kind) else { panic!("fill layer") }; fill.sampling.wrap = texturecraft_core::UvWrap::None; + assert!(cover_calls(&f) > 0); } @@ -3229,17 +3340,20 @@ mod tests { cache.ahead.clear(); composite_tiles_cached(&input, &mut output, &[(1, 0)], Some(&mut cache)); + assert!(weak_fields.upgrade().is_none(), "the last tile must release retained field buffers"); cache.ahead = all_tiles(resolution, resolution).into_iter().skip(1).collect(); composite_tiles_cached(&input, &mut output, &[(0, 0)], Some(&mut cache)); let weak_fields = Arc::downgrade(&cache.held.as_ref().unwrap().fields); cache.clear(); + assert!(weak_fields.upgrade().is_none(), "invalidating the cache releases intermediate anchor stages too"); composite_tiles_cached(&input, &mut output, &[(0, 0)], Some(&mut cache)); let weak_fields = Arc::downgrade(&cache.held.as_ref().unwrap().fields); drop(cache); + assert!(weak_fields.upgrade().is_none(), "dropping the cache releases a cancelled run's fields"); } } @@ -3334,6 +3448,7 @@ mod tests { f.project.layer_mut(id).unwrap().mask = Some(mask); let out = run(&f, None); let vals: Vec = (0..64).map(|x| out.value(Channel::BaseColor, x, 20)[0]).collect(); + assert!(vals.iter().any(|v| *v > 0.99) && vals.iter().any(|v| *v < 0.51), "{vals:?}"); } @@ -3390,13 +3505,17 @@ mod tests { // Cross tile boundaries and include duplicates, a UV hole and invalid coordinates let texels = [(0, 0), (0, 40), (63, 63), (64, 64), (127, 127), (0, 40), (90, 30), (128, 0), (0, 128), (u32::MAX, u32::MAX)]; let values = assert_sparse_mask_matches_image(&fixture, layer, &texels).unwrap(); + assert!(values.iter().any(|value| *value > 0.99) && values.iter().take(6).any(|value| *value < 0.01)); assert_eq!(&values[6..], &[0.0; 4]); assert_eq!(assert_sparse_mask_matches_image(&fixture, layer, &[]), Some(Vec::new())); assert!(assert_sparse_mask_matches_image(&fixture, maskless, &texels).is_none()); + let missing = fixture.project.alloc_id(); assert!(assert_sparse_mask_matches_image(&fixture, missing, &texels).is_none()); + fixture.project.layer_mut(layer).unwrap().mask.as_mut().unwrap().enabled = false; + assert!(assert_sparse_mask_matches_image(&fixture, layer, &texels).is_none()); } @@ -3440,6 +3559,7 @@ mod tests { assert_eq!(atlas.len(), 128 * 64); assert!(preview.contains(&0)); assert!(preview.contains(&255)); + for ((&preview_value, &sparse_value), &(x, y)) in preview.iter().zip(&sparse).zip(&sampled_texels) { assert!((f32::from(preview_value) / 255.0 - sparse_value).abs() <= 0.5 / 255.0 + 1e-6); assert!((atlas[(y * 128 + x) as usize] - sparse_value).abs() <= 1e-6); @@ -3497,6 +3617,7 @@ mod tests { filtered.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(filter))); fixture.project.layer_mut(upper).unwrap().mask = Some(filtered); let values = assert_sparse_mask_matches_image(&fixture, upper, &texels).unwrap(); + assert!(values.iter().zip(&original).any(|(value, original)| (value - original).abs() > 0.1), "the filter changes the anchor values"); } } @@ -3650,6 +3771,7 @@ mod tests { assert!(sharp[ridge] > 0.99 && sharp[five_texels_away] < 0.01, "unblurred, the ridge is one texel: {sharp:?}"); assert!(blurred[ridge] < 0.99 && blurred[ridge] > blurred[five_texels_away], "the blur spreads the ridge: {blurred:?}"); assert!(blurred[five_texels_away] > 0.01, "and reaches texels away from it: {blurred:?}"); + for texel in far { assert_eq!(blurred[texel], sharp[texel], "the checker below keeps its hard edges at texel {texel}"); } @@ -3852,10 +3974,12 @@ soft {soft:?}" let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 5, 5), [0.0, 1.0, 0.0]), "{:?}", out.value(Channel::BaseColor, 5, 5)); assert!(close(out.value(Channel::Roughness, 5, 5), [0.2; 3]), "a hue shift leaves scalars alone"); + content_fx(&mut f, id, EffectKind::Filter(Filter::Invert)); let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 5, 5), [1.0, 0.0, 1.0])); assert!(close(out.value(Channel::Roughness, 5, 5), [0.8; 3])); + // Hidden effects are skipped and opacity fades an effect let fx = &mut f.project.layer_mut(id).unwrap().content_effects; fx[0].visible = false; @@ -3907,8 +4031,10 @@ soft {soft:?}" let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 30, 30), [0.5; 3]), "{:?}", out.value(Channel::BaseColor, 30, 30)); assert!(close(out.value(Channel::Roughness, 30, 30), [0.5; 3])); + f.project.layer_mut(id).unwrap().content_effects.retain(|e| e.id != hp); content_fx(&mut f, id, EffectKind::Filter(Filter::EdgeDetect { width: 64.0 })); + assert!(close(run(&f, None).value(Channel::Roughness, 30, 30), [0.0; 3])); // A checker's borders light up while cell interiors stay black @@ -3945,7 +4071,9 @@ soft {soft:?}" let rc = Filter::ReplaceColor { from: [0.8, 0.1, 0.1], to: [0.1, 0.1, 0.8], tolerance: 0.1, softness: 0.1 }; assert!(close(rc.point(ChannelKind::Color, [0.85, 0.1, 0.1]).unwrap(), [0.15, 0.1, 0.8])); assert!(close(rc.point(ChannelKind::Color, [0.1, 0.8, 0.1]).unwrap(), [0.1, 0.8, 0.1])); + let half = rc.point(ChannelKind::Color, [0.8, 0.1 + 0.15 * 3f32.sqrt(), 0.1]).unwrap(); + assert!((half[2] - 0.45).abs() < 0.02, "halfway through the softness: {half:?}"); assert_eq!(rc.point(ChannelKind::Scalar, [0.8; 3]), Some([0.8; 3])); } @@ -3990,6 +4118,7 @@ soft {soft:?}" let mut f = fixture(); let id = fill_layer(&mut f.project, [0.1; 3], 0.2); content_fx(&mut f, id, EffectKind::Filter(Filter::Glow { radius: 32.0, amount: 1.0 })); + assert!(close(run(&f, None).value(Channel::Roughness, 30, 30), [0.4; 3])); } @@ -4063,7 +4192,9 @@ soft {soft:?}" let images = ImageStore::default(); let inp = inputs(&f, &images, None); let flat = flatten_layer(&inp, id, &all_tiles(64, 64)).unwrap(); + assert!(flat.iter().all(|(c, _, _)| *c == Channel::Roughness)); + let (_, _, data) = flat.iter().find(|(_, t, _)| *t == (0, 0)).unwrap(); let o = 3 * TILE as usize + 3; assert!((from_u16(data[o * 2]) - 0.55).abs() < 1e-3 && (from_u16(data[o * 2 + 1]) - 1.0).abs() < 1e-3); @@ -4508,6 +4639,7 @@ soft {soft:?}" composite_tiles(&inp, &mut out, &all_tiles(64, 64)); out.value(Channel::BaseColor, 32, 32) }; + assert!(close(texel(&f, [false, false]), [1.0, 0.0, 0.0]), "the left half shows red"); assert!(close(texel(&f, [true, false]), [0.0, 0.0, 1.0]), "Flip U shows the right half there"); assert!(close(texel(&f, [false, true]), [1.0, 0.0, 0.0]), "Flip V leaves the left half"); @@ -4533,12 +4665,13 @@ soft {soft:?}" fn a_shrunk_cropped_frames_coverage_averages_its_image_alpha_as_its_colour_does() { let f = decal_fixture(|fill| fill.sampling.filtering = Filtering::BilinearHq); - // Red columns a texel wide, opaque and see-through in turn, far finer than the frame's texels; not a power of two, so a full-size read lands anywhere between two columns + // Odd-width alternating alpha stripes exercise minification between source texels const SIZE: u32 = 1000; let stripes = (0..SIZE * SIZE).map(|i| [1.0, 0.0, 0.0, if i % 2 == 0 { 1.0 } else { 0.0 }]).collect(); let shown = decal_texels(&composite_with_decal(&f, crate::store::ImageRes::new(SIZE, SIZE, stripes, false))); assert!(!shown.is_empty(), "the frame shows"); + let half = [0.75, 0.25, 0.25]; assert!( shown.iter().all(|v| v.iter().zip(half).all(|(got, want)| (got - want).abs() < 0.05)), diff --git a/crates/compose/src/eval/evaluation_inputs.rs b/crates/compose/src/eval/evaluation_inputs.rs new file mode 100644 index 00000000..6f50f143 --- /dev/null +++ b/crates/compose/src/eval/evaluation_inputs.rs @@ -0,0 +1,23 @@ +use std::ops::Deref; + +use super::Inputs; +use crate::ProjectorDepthCache; + +pub(super) struct EvaluationInputs<'a> { + inputs: &'a Inputs<'a>, + pub(super) projectors: &'a ProjectorDepthCache, +} + +impl<'a> EvaluationInputs<'a> { + pub(super) fn new(inputs: &'a Inputs<'a>, projectors: &'a ProjectorDepthCache) -> Self { + Self { inputs, projectors } + } +} + +impl<'a> Deref for EvaluationInputs<'a> { + type Target = Inputs<'a>; + + fn deref(&self) -> &Self::Target { + self.inputs + } +} diff --git a/crates/compose/src/eval/thumbnail.rs b/crates/compose/src/eval/thumbnail.rs index 92290afe..e7bf4f7e 100644 --- a/crates/compose/src/eval/thumbnail.rs +++ b/crates/compose/src/eval/thumbnail.rs @@ -1,6 +1,9 @@ //! Isolated folder evaluation with the original stack available for anchor inputs. -use super::{Channel, ChannelKind, Composite, Inputs, LayerId, Texel, all_tiles, neighbourhood_fields, plan, tile_texels, to_u16, to_u16_signed}; +use super::{ + Channel, ChannelKind, Composite, EvaluationInputs, Inputs, LayerId, ProjectorDepthCache, Texel, all_tiles, evaluation_fields, plan, tile_texels, to_u16, + to_u16_signed, +}; /// Composite one layer over channel defaults, keeping anchors from the stack below it. pub(crate) fn composite_layer(inputs: &Inputs, layer: LayerId, channel: Channel) -> Option { @@ -8,7 +11,9 @@ pub(crate) fn composite_layer(inputs: &Inputs, layer: LayerId, channel: Channel) let channels = set.channel_list(); let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); let tiles = all_tiles(width, height); - let fields = neighbourhood_fields(inputs, &channels, &tiles); + let projectors = ProjectorDepthCache::default(); + let inputs = &EvaluationInputs::new(inputs, &projectors); + let fields = evaluation_fields(inputs, &channels, &tiles); let mut composite = Composite::with_size(&[channel], width, height); let output = composite.channels.get_mut(&channel)?; diff --git a/crates/compose/src/fill_copies.rs b/crates/compose/src/fill_copies.rs index cd4fc02a..b14464c4 100644 --- a/crates/compose/src/fill_copies.rs +++ b/crates/compose/src/fill_copies.rs @@ -104,13 +104,16 @@ mod tests { let mut mirror = symmetry(SymmetryKind::Mirror, 0); mirror.position = [0.5, 0.0, 0.0]; let left: Vec = FillCopies::new(&mirror, Vec3::new(-1.0, 0.0, 0.0), Vec3::ZERO, 2.0).collect(); + assert_eq!(left.len(), 2); // The plane passes at x = 1 (half a radius of 2): a point at -1 sees the original at 3 first assert!(left[0].point(Vec3::new(-1.0, 0.2, 0.0)).abs_diff_eq(Vec3::new(3.0, 0.2, 0.0), 1e-5)); assert!(left[1].point(Vec3::new(-1.0, 0.2, 0.0)).abs_diff_eq(Vec3::new(-1.0, 0.2, 0.0), 1e-5)); assert!(left[0].normal(Vec3::X).abs_diff_eq(-Vec3::X, 1e-5)); + let right: Vec = FillCopies::new(&mirror, Vec3::new(2.0, 0.0, 0.0), Vec3::ZERO, 2.0).collect(); + assert!(right[0].point(Vec3::new(2.0, 0.3, 0.0)).abs_diff_eq(Vec3::new(2.0, 0.3, 0.0), 1e-5)); } @@ -120,6 +123,7 @@ mod tests { radial.count = 4; radial.flip = [true, false]; let copies: Vec = FillCopies::new(&radial, Vec3::X, Vec3::ZERO, 1.0).collect(); + assert_eq!(copies.len(), 4); assert_eq!(copies[0].uv(Vec2::new(0.25, 0.5)), Vec2::new(0.25, 0.5)); assert_eq!(copies[1].uv(Vec2::new(0.25, 0.5)), Vec2::new(0.75, 0.5)); @@ -129,6 +133,7 @@ mod tests { // A texel on +Y lies in copy 1's wedge, so copy 1 comes first there let on_y: Vec = FillCopies::new(&radial, Vec3::Y, Vec3::ZERO, 1.0).collect(); + assert!(on_y[0].point(Vec3::Y).abs_diff_eq(Vec3::X, 1e-5)); } diff --git a/crates/compose/src/frame_placement.rs b/crates/compose/src/frame_placement.rs index 0adac17b..91574127 100644 --- a/crates/compose/src/frame_placement.rs +++ b/crates/compose/src/frame_placement.rs @@ -240,6 +240,7 @@ mod tests { let flat = folded(&proj).unwrap(); let Projector { rotation, scale, crop, .. } = projector_of(&flat); assert_eq!((rotation, scale, crop), ([0.0; 3], [1.0; 3], ShapeCrop::Cropped), "the turn and scale moved into the frame, the crop stayed"); + close(&samples(&proj), &samples(&flat)); } let unturned = planar(Projector::default()); @@ -263,6 +264,7 @@ mod tests { match folded(&proj) { Some(flat) => { assert_eq!(cover(&proj), cover(&flat), "{scale:?}: culling changed"); + close(&samples(&proj), &samples(&flat)); } None => assert!(!culling_folds(&projector), "{scale:?}: only a scale culling cannot keep stays unfolded"), @@ -286,11 +288,15 @@ mod tests { let width = folded(&proj).unwrap().frame().unwrap().size[0]; let bigger = placed(&proj, &FramePlacement { scale: [place.scale[0] * 2.0, place.scale[1], place.scale[2]], ..place }, BOUNDS).unwrap(); + assert!((bigger.frame().unwrap().size[0] - width * 2.0).abs() < 1e-4, "Scale X doubles the width"); + let moved = placed(&proj, &FramePlacement { offset: [0.0; 3], ..place }, BOUNDS).unwrap(); + assert!((Vec3::from(moved.frame().unwrap().center) - Vec3::new(1.0, -0.5, 0.5)).length() < 1e-4, "offset 0 = the mesh's centre"); } let place = placement(&planar(Projector::default()), BOUNDS).unwrap(); + assert_eq!(placed(&planar(Projector::default()), &FramePlacement { scale: [0.0, 1.0, 1.0], ..place }, BOUNDS), None, "no zero size"); assert_eq!(placed(&planar(Projector::default()), &FramePlacement { rotation: [f32::NAN; 3], ..place }, BOUNDS), None); assert_eq!(placement(&Projection::default(), BOUNDS), None); @@ -300,8 +306,11 @@ mod tests { fn a_frames_upright_turn_is_its_turn_round_its_normal() { let mut flat = Decal { normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], rotation: 30.0, offset: [0.0; 2], ..frame() }; assert!((upright_turn(&flat).unwrap() - 30.0).abs() < 1e-3); + flat.rotation = -100.0; + assert!((upright_turn(&flat).unwrap() + 100.0).abs() < 1e-3); + let top = Decal { normal: [0.0, 1.0, 0.0], up: [0.0, 0.0, -1.0], rotation: 0.0, ..frame() }; assert!(upright_turn(&top).unwrap().abs() < 1e-3, "seen from above the far side is up"); } diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 206f1437..ccf2d252 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -28,6 +28,7 @@ pub mod pattern; mod pattern_context; pub mod projector_cover; pub mod projector_depth; +mod projector_depth_cache; pub mod projector_view; pub mod solo; pub mod store; @@ -42,9 +43,11 @@ pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, kinds_for, tile_bytes}; pub use eval::{ BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, - covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours, + composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, + stack_reads_neighbours, }; pub use pattern_context::PatternContext; +pub use projector_depth_cache::ProjectorDepthCache; pub use solo::solo_project; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs index f94b1d8b..bf2b319e 100644 --- a/crates/compose/src/pattern.rs +++ b/crates/compose/src/pattern.rs @@ -678,6 +678,25 @@ pub fn frame_local(frame: &Decal, projector: &Projector, point: Vec3) -> Option< local = projector_local(projector, &Coords { uv: Vec2::ZERO, pos: local, nrm: Vec3::Z }).pos; } + frame_position(frame, local) +} + +/// Read the position and facing of one sample when a placed frame culls by angle +pub(crate) fn frame_sample(frame: &Decal, projector: &Projector, position: Vec3, surface_normal: Vec3) -> Option<(Vec3, f32)> { + let (origin, right, up, normal) = decal_axes(frame)?; + let from_origin = position - origin; + let local = Vec3::new(from_origin.dot(right), from_origin.dot(up), from_origin.dot(normal)); + + if !projector.turns() { + return Some((frame_position(frame, local)?, surface_normal.dot(normal))); + } + + let normal = Vec3::new(surface_normal.dot(right), surface_normal.dot(up), surface_normal.dot(normal)); + let sample = projector_local(projector, &Coords { uv: Vec2::ZERO, pos: local, nrm: normal }); + Some((frame_position(frame, sample.pos)?, sample.nrm.z)) +} + +fn frame_position(frame: &Decal, local: Vec3) -> Option { let local = Vec3::new(local.x / frame.size[0].max(MIN_FRAME_EXTENT), local.y / frame.size[1].max(MIN_FRAME_EXTENT), local.z); local.is_finite().then_some(local) } @@ -750,6 +769,7 @@ mod tests { // Coarse reads are exact at cell centers and blend between them assert!((at(0.375, &coarse) - at(0.375, &exact)).abs() < 1e-5); + let blended = (at(0.125, &exact) + at(0.375, &exact)) * 0.5; assert!((at(0.25, &coarse) - blended).abs() < 1e-5, "{} vs {blended}", at(0.25, &coarse)); assert!((at(0.25, &exact) - blended).abs() > 1e-3, "the exact pattern is not the blend, so the coarse read shows"); @@ -823,6 +843,7 @@ mod tests { } let corner = sample(90.0, [1.0; 2], [0.0; 2], Vec2::ZERO); assert!((corner - Vec2::new(1.0, 0.0)).length() < 1e-5, "a quarter turn brings the top left to the top right: {corner}"); + let placed = Projection::Planar { scale: 1.0, axis: 2, @@ -832,6 +853,7 @@ mod tests { placed: Some(frame), }; assert!((image_samples(&placed, &at(FRAME_UV_CENTER))[0].0 - FRAME_UV_CENTER).length() < 1e-5, "a placed planar frame turns the same way"); + for (tiling, offset, uv) in [([2.0, 3.0], [0.25, -0.5], Vec2::new(0.1, 0.8)), ([1.0, 1.0], [0.0, 0.0], Vec2::new(0.7, 0.2))] { let before = uv * Vec2::from(tiling) + Vec2::from(offset); assert!((sample(0.0, tiling, offset, uv) - before).length() < 1e-6, "unturned: as before"); @@ -909,6 +931,7 @@ mod tests { } assert!(largest_difference < 1.0 / 65535.0, "worst difference {largest_difference}"); + let near_axis = triplanar_weights(Vec3::new(0.2, 1.0, 0.1).normalize(), 8.0, 1.0); assert_eq!((near_axis.x, near_axis.z), (0.0, 0.0), "{near_axis}"); diff --git a/crates/compose/src/projector_cover.rs b/crates/compose/src/projector_cover.rs index e19a6c73..7c5bf358 100644 --- a/crates/compose/src/projector_cover.rs +++ b/crates/compose/src/projector_cover.rs @@ -5,7 +5,7 @@ use texturecraft_geom::glam::{Vec2, Vec3}; use crate::frame_placement::warp_reach; use crate::organic::smoothstep; -use crate::pattern::{Coords, depth_fade, frame_crop, frame_facing, frame_local, placed_uv, projector_local}; +use crate::pattern::{Coords, depth_fade, frame_crop, frame_local, frame_sample, placed_uv, projector_local}; use crate::warp::warp_uv; /// Nearer a cylinder's axis than this a texel has no outward direction, so it counts as facing out @@ -94,8 +94,13 @@ pub fn backface_cover(backface: &Backface, facing: f32) -> f32 { /// A planar projection placed on the surface at world point `p` with normal `nrm`: its texture coordinates and how much its backface culling and shape crop let through (None when the frame is degenerate) pub fn placed_cover(frame: &Decal, projector: &Projector, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> { - let local = frame_local(frame, projector, p)?; - let mut cover = if projector.backface.on { backface_cover(&projector.backface, frame_facing(frame, projector, nrm)) } else { 1.0 }; + let (local, mut cover) = if projector.backface.on { + let (local, facing) = frame_sample(frame, projector, p, nrm)?; + (local, backface_cover(&projector.backface, facing)) + } else { + (frame_local(frame, projector, p)?, 1.0) + }; + if projector.crop == ShapeCrop::Cropped { cover *= frame_crop(frame, local); } @@ -273,8 +278,10 @@ mod tests { let now = placed_cover_symmetric(&placed, &projector, p, nrm, center).filter(|(_, cover)| *cover > 0.0); let before = symmetric_before(&frame, p, nrm, center); mirrored += usize::from(before.is_some() && decal_before(&frame, p, nrm).is_none()); + assert_eq!(before, now, "{p} {nrm}"); } + assert!(frame.symmetry.is_none() || mirrored > 0, "the mirrored copy covers points the frame does not"); } } diff --git a/crates/compose/src/projector_depth.rs b/crates/compose/src/projector_depth.rs index bf0aafcd..5b87c7a8 100644 --- a/crates/compose/src/projector_depth.rs +++ b/crates/compose/src/projector_depth.rs @@ -1,7 +1,6 @@ //! The depth map of a planar or warp projection: the surface nearest its projector across its view, for depth culling -use std::hash::{DefaultHasher, Hash, Hasher}; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use texturecraft_core::Projection; use texturecraft_geom::Mesh; @@ -21,63 +20,41 @@ pub struct ProjectorDepth { front: Vec<[f32; 3]>, } -/// Built maps by their view and the mesh they come from -type CacheEntry = (ProjectorView, u64, Arc); - /// The smallest grid cell across and up, so a flat view still divides const MIN_CELL_SIZE: f32 = 1e-6; /// A cell centre this close outside a triangle's edge (as a share of its area) still counts as inside, so shared edges leave no gaps const EDGE_TOLERANCE: f32 = 1e-6; -static CACHE: Mutex> = Mutex::new(Vec::new()); - impl ProjectorDepth { - /// The depth map of `proj` over `mesh` within `bounds`, built once per view and mesh; None unless `proj` culls by depth - pub fn of(mesh: &Mesh, bounds: (Vec3, Vec3), proj: &Projection) -> Option> { - let view = ProjectorView::of(proj, bounds)?; - let mesh_key = fingerprint(mesh); - - // Built with the cache locked: the build runs no parallel work, and tiles asking for the same map wait for it instead of building it again - let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - if let Some(at) = cache.iter().position(|(cached_view, cached_mesh, _)| *cached_view == view && *cached_mesh == mesh_key) { - let (cached_view, cached_mesh, depth) = cache.remove(at); - cache.insert(0, (cached_view, cached_mesh, depth.clone())); - return Some(depth); - } - - let depth = Arc::new(ProjectorDepth::build(view, mesh)?); - cache.insert(0, (view, mesh_key, depth.clone())); - cache.truncate(CACHE_MAPS); - Some(depth) - } - - /// Drop every built map: a mesh replacing another (a reimport, another project) can share the old one's fingerprint - pub fn forget_all() { - CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clear(); + /// Build the depth map of a borrowed mesh, if the projection uses depth culling. + pub fn of(mesh: &Mesh, bounds: (Vec3, Vec3), projection: &Projection) -> Option> { + let view = ProjectorView::of(projection, bounds)?; + Self::build(view, mesh).map(Arc::new) } /// Rasterize every triangle of `mesh` in `view`, keeping the nearest per cell (None when no vertex lands in the view) pub fn build(view: ProjectorView, mesh: &Mesh) -> Option { - let local: Vec> = mesh.positions.iter().map(|position| view.local(*position)).collect(); - let (lo, hi) = local + let projected: Vec> = mesh.positions.iter().map(|position| view.local(*position)).collect(); + let (min, max) = projected .iter() .flatten() .fold((Vec2::splat(f32::MAX), Vec2::splat(f32::MIN)), |(lo, hi), view_point| (lo.min(view_point.truncate()), hi.max(view_point.truncate()))); - if lo.x > hi.x || lo.y > hi.y { + if min.x > max.x || min.y > max.y { return None; } - let cell = ((hi - lo) / SIZE as f32).max(Vec2::splat(MIN_CELL_SIZE)); - let mut depth = ProjectorDepth { view, origin: lo, cell, front: vec![[f32::NEG_INFINITY, 0.0, 0.0]; SIZE * SIZE] }; + let cell = ((max - min) / SIZE as f32).max(Vec2::splat(MIN_CELL_SIZE)); + let mut depth = ProjectorDepth { view, origin: min, cell, front: vec![[f32::NEG_INFINITY, 0.0, 0.0]; SIZE * SIZE] }; let mut budget = CELL_BUDGET; - for tri in mesh.indices.as_chunks::<3>().0 { - let corner = |i: u32| local.get(i as usize).copied().flatten(); - let (Some(a), Some(b), Some(c)) = (corner(tri[0]), corner(tri[1]), corner(tri[2])) else { continue }; + for &[first, second, third] in mesh.indices.as_chunks::<3>().0 { + let corner = |i: u32| projected.get(i as usize).copied().flatten(); + let (Some(a), Some(b), Some(c)) = (corner(first), corner(second), corner(third)) else { continue }; if !depth.raster([a, b, c], &mut budget) { break; } } + Some(depth) } @@ -85,15 +62,16 @@ impl ProjectorDepth { fn raster(&mut self, triangle: [Vec3; 3], budget: &mut usize) -> bool { let [a, b, c] = triangle; let (d1, d2) = (b - a, c - a); - let det = d1.x * d2.y - d1.y * d2.x; - if !det.is_finite() || det.abs() < MIN_SCREEN_AREA { - // Seen edge on, it covers nothing + let determinant = d1.x * d2.y - d1.y * d2.x; + if !determinant.is_finite() || determinant.abs() < MIN_SCREEN_AREA { + // An edge-on triangle covers no cells return true; } - let slope = Vec2::new((d1.z * d2.y - d2.z * d1.y) / det, (d1.x * d2.z - d2.x * d1.z) / det).clamp(Vec2::splat(-MAX_SLOPE), Vec2::splat(MAX_SLOPE)); + let slope = Vec2::new((d1.z * d2.y - d2.z * d1.y) / determinant, (d1.x * d2.z - d2.x * d1.z) / determinant) + .clamp(Vec2::splat(-MAX_SLOPE), Vec2::splat(MAX_SLOPE)); - // Corners in cells: cell (i, j) has its centre at (i + 0.5, j + 0.5) + // Evaluate coverage at cell centres let [pa, pb, pc] = triangle.map(|corner| (corner.truncate() - self.origin) / self.cell); let (lo, hi) = (pa.min(pb).min(pc), pa.max(pb).max(pc)); let first = |v: f32| (v - 0.5).ceil().clamp(0.0, SIZE as f32) as usize; @@ -122,17 +100,18 @@ impl ProjectorDepth { } } } + true } /// How much depth culling with `hardness` leaves of a projection at world point `p`: 0 behind the surface nearest the projector, 1 on it or where nothing is in front - pub fn cover(&self, p: Vec3, hardness: f32) -> f32 { - // A hand-edited NaN hardness keeps the layer visible rather than making its texels NaN + pub fn cover(&self, position: Vec3, hardness: f32) -> f32 { + // Keep the layer visible when a hand-edited hardness is invalid if !hardness.is_finite() { return 1.0; } - let Some(view_point) = self.view.local(p) else { return 1.0 }; + let Some(view_point) = self.view.local(position) else { return 1.0 }; let at = (view_point.truncate() - self.origin) / self.cell; if !(at.x >= 0.0 && at.y >= 0.0 && at.x < SIZE as f32 && at.y < SIZE as f32) { return 1.0; @@ -141,13 +120,13 @@ impl ProjectorDepth { let (x, y) = (at.x as usize, at.y as usize); let Some(&[near, across, up]) = self.front.get(y * SIZE + x).filter(|cell| cell[0].is_finite()) else { return 1.0 }; - // The nearest surface's plane carried from the cell centre to the point, so a surface is never behind itself + // Extend the cell's plane to avoid culling a surface against itself let centre = self.origin + (Vec2::new(x as f32, y as f32) + 0.5) * self.cell; let slope = Vec2::new(across, up); let behind = near + slope.dot(view_point.truncate() - centre) - view_point.z; let unit = self.view.unit(); - // Neighbouring triangles of a curved surface part from the carried plane by about one cell of its slope + // Add slope bias for curvature across adjacent triangles let bias = BIAS * unit + (slope.abs() * self.cell).element_sum().min(MAX_SLOPE_BIAS * unit); let width = (1.0 - hardness.clamp(0.0, 1.0)) * FADE * unit; if width <= f32::EPSILON { @@ -163,19 +142,6 @@ fn edge(a: Vec2, b: Vec2, q: Vec2) -> f32 { (b - a).perp_dot(q - a) } -/// Which mesh a map was built for: its sizes and a spread of its vertices and indices -fn fingerprint(mesh: &Mesh) -> u64 { - let mut hasher = DefaultHasher::new(); - (mesh.positions.len(), mesh.indices.len()).hash(&mut hasher); - for position in mesh.positions.iter().step_by((mesh.positions.len() / FINGERPRINT_SAMPLES).max(1)) { - position.to_array().map(f32::to_bits).hash(&mut hasher); - } - for index in mesh.indices.iter().step_by((mesh.indices.len() / FINGERPRINT_SAMPLES).max(1)) { - index.hash(&mut hasher); - } - hasher.finish() -} - /// Cells across and up the grid const SIZE: usize = 512; @@ -197,12 +163,6 @@ const MAX_SLOPE_BIAS: f32 = 0.05; /// How far behind the nearest surface culling fades out at hardness 0, in mesh radii const FADE: f32 = 0.1; -/// Maps kept built (each is about 3 MB) -const CACHE_MAPS: usize = 8; - -/// Vertices and indices the mesh fingerprint reads -const FINGERPRINT_SAMPLES: usize = 64; - #[cfg(test)] mod tests { use super::*; @@ -254,22 +214,21 @@ mod tests { } #[test] - fn a_mesh_edited_where_its_fingerprint_does_not_look_is_rebuilt_once_forgotten() { - // Unused vertices spread the fingerprint's samples so the front square's right edge is not among them + fn interleaved_meshes_keep_their_own_projector_depth() { let mut mesh = two_squares(0.5, -0.5); - mesh.positions.extend((0..FINGERPRINT_SAMPLES * 3).map(|_| Vec3::ZERO)); + // Add enough unused vertices for the old sample to skip the changed edge + mesh.positions.resize(200, Vec3::ZERO); let mut edited = mesh.clone(); for right in [1, 2] { edited.positions[right].x = 0.5; } - assert_eq!(fingerprint(&mesh), fingerprint(&edited), "the edit is unseen by the fingerprint"); + assert_eq!(mesh.bounds(), edited.bounds()); + let proj = planar_z(true, 1.0); let behind_the_cut = Vec3::new(0.75, 0.3, -0.5); let bounds = mesh.bounds(); assert_eq!(ProjectorDepth::of(&mesh, bounds, &proj).unwrap().cover(behind_the_cut, 1.0), 0.0); - ProjectorDepth::forget_all(); - let rebuilt = ProjectorDepth::of(&edited, bounds, &proj).unwrap(); assert_eq!(rebuilt.cover(behind_the_cut, 1.0), 1.0, "nothing is in front there any more"); } diff --git a/crates/compose/src/projector_depth_cache.rs b/crates/compose/src/projector_depth_cache.rs new file mode 100644 index 00000000..658e480d --- /dev/null +++ b/crates/compose/src/projector_depth_cache.rs @@ -0,0 +1,97 @@ +use std::sync::{Arc, Mutex, Weak}; + +use texturecraft_core::Projection; +use texturecraft_geom::{Mesh, glam::Vec3}; + +use crate::{projector_depth::ProjectorDepth, projector_view::ProjectorView}; + +type ViewDepth = (ProjectorView, Option>); + +// Each map holds about 3 MiB +const MAX_CACHED_VIEWS: usize = 8; + +/// Reuse projector depth maps for one mesh across tile batches. +#[derive(Default)] +pub struct ProjectorDepthCache { + mesh: Weak, + maps: Mutex>, +} + +impl ProjectorDepthCache { + pub(crate) fn bind(&mut self, mesh: &Arc) -> bool { + if !std::ptr::eq(self.mesh.as_ptr(), mesh.as_ref()) { + self.maps.get_mut().unwrap_or_else(|poisoned| poisoned.into_inner()).clear(); + self.mesh = Arc::downgrade(mesh); + return true; + } + + false + } + + pub(crate) fn get(&self, mesh: &Mesh, bounds: (Vec3, Vec3), projection: &Projection) -> Option> { + let view = ProjectorView::of(projection, bounds)?; + + // Rasterization is serial so tile workers can wait for a single build + let mut maps = self.maps.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(index) = maps.iter().position(|(cached_view, _)| *cached_view == view) { + let entry = maps.remove(index); + let depth = entry.1.clone(); + maps.insert(0, entry); + return depth; + } + + let depth = ProjectorDepth::build(view, mesh).map(Arc::new); + maps.insert(0, (view, depth.clone())); + maps.truncate(MAX_CACHED_VIEWS); + + depth + } +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_core::{Projector, UvTransform}; + use texturecraft_geom::primitives; + + #[test] + fn eviction_and_mesh_replacement_release_maps_after_the_last_reader() { + let mut cache = ProjectorDepthCache::default(); + let mut mesh = Arc::new(primitives::plane(2.0, 2)); + let mesh_reference = Arc::downgrade(&mesh); + let bounds = mesh.bounds(); + let mut maps = Vec::new(); + let mut first_reader = None; + + cache.bind(&mesh); + for angle_degrees in 0..MAX_CACHED_VIEWS + 4 { + let mut projector = Projector::depth_culled(); + projector.rotation[2] = angle_degrees as f32; + let projection = Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None }; + let map = cache.get(&mesh, bounds, &projection).unwrap(); + let reused = cache.get(&mesh, bounds, &projection).unwrap(); + assert!(Arc::ptr_eq(&map, &reused)); + maps.push(Arc::downgrade(&map)); + if angle_degrees == 0 { + first_reader = Some(map); + } + } + + assert_eq!(maps.iter().filter(|map| map.upgrade().is_some()).count(), MAX_CACHED_VIEWS + 1); + drop(first_reader); + assert_eq!(maps.iter().filter(|map| map.upgrade().is_some()).count(), MAX_CACHED_VIEWS); + + // Mutating a uniquely held Arc disassociates its weak references + Arc::make_mut(&mut mesh).positions[0].y += 1.0; + assert!(mesh_reference.upgrade().is_none()); + cache.bind(&mesh); + assert!(maps.iter().all(|map| map.upgrade().is_none())); + + let projection = + Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::depth_culled(), placed: None }; + let last_map = Arc::downgrade(&cache.get(&mesh, mesh.bounds(), &projection).unwrap()); + + drop(cache); + assert!(last_map.upgrade().is_none()); + } +} diff --git a/crates/compose/src/solo.rs b/crates/compose/src/solo.rs index 3703ba57..c9d17f5a 100644 --- a/crates/compose/src/solo.rs +++ b/crates/compose/src/solo.rs @@ -103,6 +103,7 @@ mod tests { p.layer_mut(rust).unwrap().visible = false; let before = p.clone(); let view = solo_project(&p, rust, false).unwrap(); + assert!(view.layers[&rust].visible, "the soloed layer shows even with its eye off"); assert!(!view.layers[&below].visible, "the others are hidden"); assert!(view.layers[&other_set].visible, "another texture set keeps its layers"); @@ -117,9 +118,12 @@ mod tests { let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true); let sibling = add(&mut p, 0, LayerKind::Paint, Some(inner), false); let view = solo_project(&p, inner, false).unwrap(); + assert!(view.layers[&folder].visible && view.layers[&inner].visible); assert!(!view.layers[&sibling].visible && !view.layers[&outside].visible); + let whole = solo_project(&p, folder, false).unwrap(); + assert!(whole.layers[&inner].visible && whole.layers[&sibling].visible, "a soloed folder shows its contents"); assert!(!whole.layers[&outside].visible); } @@ -134,8 +138,11 @@ mod tests { masked(&mut p, id); } let kept = solo_project(&p, inner, false).unwrap(); + assert!(kept.layers[&inner].mask.as_ref().unwrap().enabled, "without the flag the mask stays"); + let view = solo_project(&p, inner, true).unwrap(); + assert!(!view.layers[&inner].mask.as_ref().unwrap().enabled && !view.layers[&folder].mask.as_ref().unwrap().enabled); assert!(view.layers[&other].mask.as_ref().unwrap().enabled, "a hidden layer's mask is not touched"); assert!(p.layers[&inner].mask.as_ref().unwrap().enabled, "the project keeps its mask"); @@ -148,6 +155,7 @@ mod tests { masked(&mut p, source); let instance = add(&mut p, 1, LayerKind::Instance { source }, None, false); let view = solo_project(&p, instance, true).unwrap(); + assert!(!view.layers[&instance].mask.as_ref().unwrap().enabled); assert!(view.layers[&source].mask.as_ref().unwrap().enabled, "the source keeps its mask"); } @@ -159,6 +167,7 @@ mod tests { let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true); let instance = add(&mut p, 0, LayerKind::Instance { source: folder }, None, false); let view = solo_project(&p, instance, false).unwrap(); + assert!(view.layers[&instance].visible && view.layers[&folder].visible && view.layers[&inner].visible); } diff --git a/crates/compose/src/store.rs b/crates/compose/src/store.rs index 43d9b19a..e7b78d3b 100644 --- a/crates/compose/src/store.rs +++ b/crates/compose/src/store.rs @@ -124,6 +124,7 @@ impl ImageRes { if !u.is_finite() || !v.is_finite() { return [0.0; 4]; } + bilinear(&self.rgba, self.width, self.height, u, v, (true, true)) } diff --git a/crates/compose/src/tile_length.rs b/crates/compose/src/tile_length.rs index c08e668f..21a2872b 100644 --- a/crates/compose/src/tile_length.rs +++ b/crates/compose/src/tile_length.rs @@ -6,12 +6,9 @@ use texturecraft_core::{FULL_TURN_DEGREES, Projection}; use crate::pattern::{MIN_CYLINDER_ANGLE, cylinder_axis_index, projector_stretch}; -/// The mesh's size as the projections see it: the bounds radius (3D projections) and the mesh units one UV unit covers (UV) -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct MeshSize { - pub radius: f32, - pub uv_density: f32, -} +mod mesh_size; + +pub use mesh_size::MeshSize; /// Mesh units one tile covers across and down at a tiling of 1, the projector's stretch included; None without a physical size (per UV tile, spherical, or a stretch uneven across the planes a tile wraps round) fn unit_tile(projection: &Projection, size: MeshSize) -> Option<[f32; 2]> { diff --git a/crates/compose/src/tile_length/mesh_size.rs b/crates/compose/src/tile_length/mesh_size.rs new file mode 100644 index 00000000..9d433361 --- /dev/null +++ b/crates/compose/src/tile_length/mesh_size.rs @@ -0,0 +1,6 @@ +/// The mesh's size as the projections see it: the bounds radius (3D projections) and the mesh units one UV unit covers (UV) +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MeshSize { + pub radius: f32, + pub uv_density: f32, +} diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 406d8480..4ec0863e 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -214,12 +214,14 @@ fn mask_with_height_follows_the_layer_height() { let row = TILE * 2; let (left, right) = (16, RES - 16); let v = |c: &Composite, x| c.value(Channel::BaseColor, x, row)[0]; + assert!((v(&plain, left) - 0.75).abs() < 0.01 && (v(&plain, right) - 0.75).abs() < 0.01, "plain mask: 50 % white over gray"); assert!(v(&hm, left) > 0.84, "high parts show first: {}", v(&hm, left)); assert!(v(&hm, right) < 0.66, "low parts later: {}", v(&hm, right)); // Without a mask there is nothing to combine f.project.layer_mut(id).unwrap().mask.as_mut().unwrap().enabled = false; + assert!((v(&reference(&f, 0), left) - 1.0).abs() < 1e-3); } @@ -544,11 +546,13 @@ fn anchors_inside_a_content_stack_record_the_content_up_to_them() { f.project.layer_mut(low).unwrap().content_effects.insert(0, blur); let blurred = reference(&f, 0); assert!((blurred.value(Channel::Roughness, 128, 128)[0] - 0.2).abs() < 2e-3, "a flat height stays flat"); + let mut one_by_one = Composite::new(&f.project.texture_sets[0].channel_list(), RES); let (images, baked) = (Default::default(), Default::default()); for t in all_tiles(RES, RES) { composite_tiles(&inputs(&f, 0, &images, &baked), &mut one_by_one, &[t]); } + assert!(one_by_one == blurred); } @@ -584,7 +588,9 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() { for t in all_tiles(RES, RES) { composite_tiles(&inputs(&f, 0, &images, &baked), &mut one_by_one, &[t]); } + assert!(one_by_one == want, "per-tile composites differ from one pass"); + for hot in [top, streaks] { assert!(!check_cached(&f, 0, hot).is_empty()); } @@ -665,6 +671,7 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() { let (images, baked) = (Default::default(), Default::default()); cache.ahead = Vec::new(); composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &all, Some(&mut cache)); + assert!(out == reference(&fixture, 0), "fields kept from before an edit were used after it"); assert!(!cache.holds_fields()); @@ -677,6 +684,7 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() { let mut inp = inputs(&fixture, 0, &images, &baked); inp.preview = Some(&preview); composite_tiles_cached(&inp, &mut live, rest, Some(&mut cache)); + assert!(live == run_with(&fixture, 0, &all, None, Some(&preview)), "a live stroke over a sliced pass differs"); } @@ -719,7 +727,9 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() { cache.set_hot(Some(hot)); let mut out = Composite::new(&channels, SIZE); composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, bottom, Some(&mut cache)); + assert_eq!(cache.len(), bottom.len()); + cache.budget = cache.bytes(); // Cache eviction during the run must rebuild missing lower-layer fields @@ -731,6 +741,7 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() { assert!(cache.holds_fields()); } } + assert!(above.len() > bottom.len()); assert!(out == expected, "a tile dropped from the cache was composited with fields that lack the layers off the hot path"); } @@ -790,13 +801,17 @@ fn cached_stack_tracks_the_images_a_tile_generator_reads() { fixture.pixels.layer_mut(hot_layer, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]); let input = inputs(&fixture, 0, &images, &baked); composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache)); + assert!(!cache.is_empty(), "{stage}: first tile should be cached"); + let retained = cache.len() - 1; composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache)); + assert_eq!(retained, 0, "{stage}: the layers below are drawn again with the new image"); let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); composite_tiles(&input, &mut expected, &tiles); + assert!(output == expected, "{stage}"); } } @@ -832,11 +847,14 @@ fn cached_stack_tracks_referenced_images_only() { let replacement = image_with_value(0.4); let replacement_weak = Arc::downgrade(&replacement); images.insert("used".into(), replacement); + assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain replaced image pixels"); + previous_image = Some(replacement_weak); } "remove" => { images.remove("used"); + assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain removed image pixels"); } "cold" => {} @@ -848,13 +866,17 @@ fn cached_stack_tracks_referenced_images_only() { fixture.pixels.layer_mut(hot_layer, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]); let input = inputs(&fixture, 0, &images, &baked); composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache)); + assert!(!cache.is_empty(), "{stage}: first tile should be cached"); + let retained = cache.len() - 1; composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache)); + assert_eq!(retained, if stage.starts_with("unused") { tiles.len() - 1 } else { 0 }, "{stage}"); let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); composite_tiles(&input, &mut expected, &tiles); + assert!(output == expected, "{stage}"); } } diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 267f05c2..34664b03 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -10,31 +10,41 @@ mod curvature_detail; mod curvature_mode; mod decal_flip; mod decal_symmetry; +mod filtering; mod generator_global; mod micro_detail; mod output_resolution; mod resolution_mode; +mod sampling; +mod scale_mode; mod tile_blending; mod tile_generator; mod tile_input_distribution; mod tile_shape; mod tile_size_mode; mod tile_symmetry; +mod uv_transform; +mod uv_wrap; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; pub use decal_flip::DecalFlip; pub use decal_symmetry::DecalSymmetry; +pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; pub use micro_detail::MicroDetail; pub use output_resolution::OutputResolution; pub use resolution_mode::ResolutionMode; +pub use sampling::Sampling; +pub use scale_mode::ScaleMode; pub use tile_blending::TileBlending; pub use tile_generator::TileGenerator; pub use tile_input_distribution::TileInputDistribution; pub use tile_shape::TileShape; pub use tile_size_mode::TileSizeMode; pub use tile_symmetry::TileSymmetry; +pub use uv_transform::UvTransform; +pub use uv_wrap::UvWrap; /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] @@ -103,6 +113,7 @@ impl HeightMask { if !self.enabled || !h.is_finite() { return m; } + (m + self.contrast * 4.0 * m * (1.0 - m) * (h + self.offset)).clamp(0.0, 1.0) } } @@ -244,27 +255,6 @@ pub enum Projection { }, } -/// Tiling, rotation (degrees) and offset a 3D projection lays on the surface; the default changes nothing -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub struct UvTransform { - pub tiling: [f32; 2], - pub rotation: f32, - pub offset: [f32; 2], -} - -impl Default for UvTransform { - fn default() -> Self { - UvTransform { tiling: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] } - } -} - -impl UvTransform { - /// Whether it changes nothing, as projections saved before it existed did (not saved then) - pub fn is_default(&self) -> bool { - *self == UvTransform::default() - } -} - /// The frame a planar projection placed on the surface (a decal) projects from, in world space #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub struct Decal { @@ -1789,6 +1779,7 @@ mod tests { ]; for saved in fills { let loaded: Fill = serde_json::from_str(saved).unwrap(); + assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "a fill saves as it was saved"); } @@ -1798,6 +1789,7 @@ mod tests { ]; for saved in effects { let loaded: EffectKind = serde_json::from_str(saved).unwrap(); + assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "an effect saves as it was saved"); } } diff --git a/crates/core/src/layer/filtering.rs b/crates/core/src/layer/filtering.rs new file mode 100644 index 00000000..2f5667bb --- /dev/null +++ b/crates/core/src/layer/filtering.rs @@ -0,0 +1,30 @@ +use serde::{Deserialize, Serialize}; + +/// How a fill reads its image sources between texels +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum Filtering { + /// Bilinear on the image level that matches the texel's footprint: smooth when the image is shrunk + #[default] + BilinearHq, + /// Bilinear on the full image: sharp, but may shimmer where the image is shrunk + BilinearSharp, + /// The nearest image texel + Nearest, +} + +impl Filtering { + pub const ALL: [Filtering; 3] = [Filtering::BilinearHq, Filtering::BilinearSharp, Filtering::Nearest]; + + /// Command id + pub fn id(self) -> &'static str { + match self { + Filtering::BilinearHq => "bilinearHq", + Filtering::BilinearSharp => "bilinearSharp", + Filtering::Nearest => "nearest", + } + } + + pub fn from_id(id: &str) -> Option { + Filtering::ALL.into_iter().find(|f| f.id() == id) + } +} diff --git a/crates/core/src/layer/sampling.rs b/crates/core/src/layer/sampling.rs new file mode 100644 index 00000000..9fa568fb --- /dev/null +++ b/crates/core/src/layer/sampling.rs @@ -0,0 +1,33 @@ +use serde::{Deserialize, Serialize}; + +use super::{Filtering, ScaleMode, UvWrap}; +use crate::FillSymmetry; + +/// How a fill samples its images and what its size is set in; older fills read with [`Sampling::SAVED_BEFORE`] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Default)] +pub struct Sampling { + #[serde(default)] + pub filtering: Filtering, + #[serde(default)] + pub wrap: UvWrap, + #[serde(default)] + pub scale: ScaleMode, + #[serde(default, skip_serializing_if = "FillSymmetry::is_default")] + pub symmetry: FillSymmetry, +} + +impl Sampling { + /// What fills saved before the sampling choices existed did: plain bilinear + pub const SAVED_BEFORE: Sampling = + Sampling { filtering: Filtering::BilinearSharp, wrap: UvWrap::Repeat, scale: ScaleMode::Tiling, symmetry: FillSymmetry::OFF }; + + /// Serde default for fills saved before the field existed + pub fn saved_before() -> Sampling { + Sampling::SAVED_BEFORE + } + + /// Whether it samples as fills saved before the field existed did (not saved then, so they save as they were) + pub fn is_saved_before(&self) -> bool { + *self == Sampling::SAVED_BEFORE + } +} diff --git a/crates/core/src/layer/scale_mode.rs b/crates/core/src/layer/scale_mode.rs new file mode 100644 index 00000000..b9659eb6 --- /dev/null +++ b/crates/core/src/layer/scale_mode.rs @@ -0,0 +1,25 @@ +use serde::{Deserialize, Serialize}; + +/// What a fill's size is set in: repeats of its tile, or the tile's length on the mesh (stored as tiling either way) +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum ScaleMode { + #[default] + Tiling, + PhysicalSize, +} + +impl ScaleMode { + pub const ALL: [ScaleMode; 2] = [ScaleMode::Tiling, ScaleMode::PhysicalSize]; + + /// Command id + pub fn id(self) -> &'static str { + match self { + ScaleMode::Tiling => "tiling", + ScaleMode::PhysicalSize => "physicalSize", + } + } + + pub fn from_id(id: &str) -> Option { + ScaleMode::ALL.into_iter().find(|mode| mode.id() == id) + } +} diff --git a/crates/core/src/layer/uv_transform.rs b/crates/core/src/layer/uv_transform.rs new file mode 100644 index 00000000..e341ea19 --- /dev/null +++ b/crates/core/src/layer/uv_transform.rs @@ -0,0 +1,22 @@ +use serde::{Deserialize, Serialize}; + +/// Tiling, rotation (degrees) and offset a 3D projection lays on the surface; the default changes nothing +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct UvTransform { + pub tiling: [f32; 2], + pub rotation: f32, + pub offset: [f32; 2], +} + +impl Default for UvTransform { + fn default() -> Self { + UvTransform { tiling: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] } + } +} + +impl UvTransform { + /// Whether it changes nothing, as projections saved before it existed did (not saved then) + pub fn is_default(&self) -> bool { + *self == UvTransform::default() + } +} diff --git a/crates/core/src/layer/uv_wrap.rs b/crates/core/src/layer/uv_wrap.rs new file mode 100644 index 00000000..4ff480ff --- /dev/null +++ b/crates/core/src/layer/uv_wrap.rs @@ -0,0 +1,40 @@ +use serde::{Deserialize, Serialize}; + +/// Whether a UV-placed fill repeats past its 0..1 tile, across, down, both or neither +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum UvWrap { + #[default] + Repeat, + RepeatHorizontally, + RepeatVertically, + /// One tile only: outside it the fill does not cover + None, +} + +impl UvWrap { + pub const ALL: [UvWrap; 4] = [UvWrap::None, UvWrap::RepeatHorizontally, UvWrap::RepeatVertically, UvWrap::Repeat]; + + /// Command id + pub fn id(self) -> &'static str { + match self { + UvWrap::Repeat => "repeat", + UvWrap::RepeatHorizontally => "repeatHorizontally", + UvWrap::RepeatVertically => "repeatVertically", + UvWrap::None => "none", + } + } + + pub fn from_id(id: &str) -> Option { + UvWrap::ALL.into_iter().find(|w| w.id() == id) + } + + /// Whether the fill repeats across (u) and down (v) + pub fn repeats(self) -> (bool, bool) { + match self { + UvWrap::Repeat => (true, true), + UvWrap::RepeatHorizontally => (true, false), + UvWrap::RepeatVertically => (false, true), + UvWrap::None => (false, false), + } + } +} diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 7bbb1aa5..7b6c92c2 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -841,6 +841,7 @@ mod tests { l.as_object_mut().unwrap().remove("content_effects"); } let old: Project = serde_json::from_value(v).unwrap(); + assert!(old.layers.values().all(|l| l.content_effects.is_empty())); } diff --git a/crates/engine/src/decal_cmds.rs b/crates/engine/src/decal_cmds.rs index d49e7afe..255ff27c 100644 --- a/crates/engine/src/decal_cmds.rs +++ b/crates/engine/src/decal_cmds.rs @@ -238,7 +238,7 @@ fn framed(session: &Session, command: &str, id: LayerId, effect: Option return Err(bad(command, "an axis planar reading a procedural pattern keeps its axis: placing its frame would move the pattern")); } - // A frame faces one way: culling read through an uneven or mirrored scale would hide other faces once the scale is in the frame (a placed frame keeps its edits that move no frame) + // Keep the active projection while folding scaling would change which faces cull if matches!(projection, Projection::Planar { placed: None, .. }) && !culling_keeps_facing(projection) { return Err(bad(command, UNFOLDABLE_CULLING)); } diff --git a/crates/engine/src/fill_reset_cmds.rs b/crates/engine/src/fill_reset_cmds.rs index f1c5317b..6d50a4c4 100644 --- a/crates/engine/src/fill_reset_cmds.rs +++ b/crates/engine/src/fill_reset_cmds.rs @@ -51,6 +51,7 @@ pub fn at_defaults(projection: &Projection, sampling: Sampling) -> bool { fn reset_projection(s: &mut Session, p: &Value) -> Result { let target = fill_target(s, p, "layer.fill.resetProjection")?; let (projection, sampling) = placement_mut(s, target)?; + if at_defaults(projection, *sampling) { return Ok(Value::Null); } @@ -61,6 +62,7 @@ fn reset_projection(s: &mut Session, p: &Value) -> Result { *sampling = reset_sampling(*sampling); Ok(()) })?; + Ok(Value::Null) } @@ -84,6 +86,7 @@ mod tests { flip: [false; 2], }; let mut kinds: Vec = UNFRAMED_PROJECTION_IDS.iter().filter_map(|id| new_unframed_projection(id)).collect(); + assert_eq!(kinds.len(), UNFRAMED_PROJECTION_IDS.len(), "every listed id makes a projection"); kinds.extend([Projection::warp(frame), Projection::decal(frame)]); @@ -94,7 +97,9 @@ mod tests { } other => other, }; + let reset = reset_projection_of(&turned); + assert_eq!(std::mem::discriminant(&reset), std::mem::discriminant(&kind), "{kind:?}"); assert_eq!(reset.frame(), kind.frame(), "the frame stays where it is placed"); } diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index d5936ece..86fd4a55 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -13,6 +13,10 @@ use crate::commands::{ use crate::layer_selection::{batch_param, ids_json}; use crate::{EngineError, Result, Session, cmd, session::StackTarget}; +mod fill_target; + +pub(crate) use fill_target::FillTarget; + /// One full turn, in degrees (the brush's, so every angle wraps on the same turn) pub(crate) use texturecraft_paint::FULL_TURN_DEGREES; diff --git a/crates/engine/src/layer_cmds/fill_target.rs b/crates/engine/src/layer_cmds/fill_target.rs new file mode 100644 index 00000000..62cfaa7c --- /dev/null +++ b/crates/engine/src/layer_cmds/fill_target.rs @@ -0,0 +1,8 @@ +use texturecraft_core::LayerId; + +/// Which fill `layer.fill.*` edits: a fill layer's (`layer`) or a content fill effect's (`effect`) +#[derive(Clone, Copy)] +pub(crate) enum FillTarget { + Layer(LayerId), + Effect(LayerId), +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index d20a81e5..e1f352c7 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -247,6 +247,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { if !s.doc.resources.contains_key(&name) { return Err(bad("resource.remove", format!("no resource `{name}`"))); } + s.edit("Remove resource", |s| { s.doc.resources.remove(&name); Ok(()) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 8a036f72..83a8461d 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -1,6 +1,6 @@ //! The editing session: document, mesh, per-texture-set caches, history, tool state. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, BinaryHeap}; use std::sync::Arc; use serde::{Deserialize, Serialize}; @@ -60,7 +60,7 @@ impl SetCache { pub(crate) fn new(mesh: &Mesh, ts: &TextureSet) -> SetCache { let (w, h) = ts.size(); let gbuf = UvGBuffer::new(mesh, ts.material, w, h); - // Padding stays inside each UV tile. + // Padding stays inside each UV tile let dilation = DilationMap::in_blocks(&gbuf.coverage_mask(), w, h, Some(DISPLAY_PADDING), ts.block_resolution()); let covered = covered_tiles(&gbuf); let all: BTreeSet<(u32, u32)> = texturecraft_compose::all_tiles(w, h).into_iter().collect(); @@ -476,6 +476,8 @@ pub struct Session { /// The last stroke's camera visibility buffer: reused while the camera, view size and mesh /// are unchanged, so back-to-back dabs start instantly. pub(crate) depth_cache: Option, + /// Projection fill depth maps shared by this session's tile batches. + projector_depth_cache: texturecraft_compose::ProjectorDepthCache, /// The polygon fill box being dragged pub(crate) polygon_fill_drag: Option, /// The user's export presets (kept when another project opens). @@ -497,9 +499,6 @@ impl Session { let source = Arc::new(mesh); let mesh = tiled_mesh(&source, &doc.project); - // Depth maps built for the mesh this one replaces must not be taken for its own - texturecraft_compose::projector_depth::ProjectorDepth::forget_all(); - let bvh = Bvh::new(&mesh); let mut camera = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() }; let (bounds_min, bounds_max) = mesh.bounds(); @@ -547,6 +546,7 @@ impl Session { log: crate::log::SessionLog::new(), log_id: next_mesh_id(), depth_cache: None, + projector_depth_cache: Default::default(), polygon_fill_drag: None, export_presets: Default::default(), brush_presets: Default::default(), @@ -827,9 +827,11 @@ impl Session { if changed.is_empty() && before.texture_sets.len() == self.doc.project.texture_sets.len() { return; } + self.mesh = tiled_mesh(&self.source, &self.doc.project); self.mesh_id = next_mesh_id(); self.depth_cache = None; + self.projector_depth_cache = Default::default(); for ts in changed { if let (Some(c), Some(set)) = (self.caches.get_mut(ts), self.doc.project.texture_sets.get(ts)) { *c = SetCache::new(&self.mesh, set); @@ -1021,6 +1023,7 @@ impl Session { let solo_view = if self.pending_tiles() > 0 { self.solo_view() } else { None }; let active = self.ts(); let order = std::iter::once(active).chain((0..self.caches.len()).filter(|ts| *ts != active)); + let mut mesh_bounds = None; let mut changed = false; for ts in order { let Some(cache) = self.caches.get_mut(ts) else { continue }; @@ -1058,12 +1061,19 @@ impl Session { block_scales: cache.composite.block_scales.clone(), preview, images: &self.images, - bounds: self.mesh.bounds(), + bounds: *mesh_bounds.get_or_insert_with(|| self.mesh.bounds()), }; // Look ahead so sliced updates filter a run of tiles once cache.below.ahead = if budget_ms.is_finite() { tiles_ahead(&cache.dirty, &tiles) } else { Vec::new() }; - texturecraft_compose::composite_tiles_cached(&inputs, &mut cache.composite, &tiles, Some(&mut cache.below)); + texturecraft_compose::composite_tiles_with_projectors( + &inputs, + &self.mesh, + &mut self.projector_depth_cache, + &mut cache.composite, + &tiles, + Some(&mut cache.below), + ); // The composited tiles and the neighbours their padding reached change let padded = pad_tiles(&mut cache.composite, &cache.dilation, &tiles); @@ -1247,7 +1257,7 @@ const CHUNK: usize = 256; /// The most a budgeted update spends on settling tiles (what they show is already right). pub const SETTLE_BUDGET_MS: f64 = 6.0; -/// Take up to `n` dirty tiles, block by block (16 × 16 tiles) so neighbourhood filters +/// Take up to `max_tiles` dirty tiles, block by block (16 × 16 tiles) so neighbourhood filters /// evaluate compact regions. fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, max_tiles: usize) -> Vec<(u32, u32)> { // A zero-sized request cannot select a pivot @@ -1259,17 +1269,26 @@ fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, max_tiles: usize) -> Vec<(u32, u return std::mem::take(dirty).into_iter().collect(); } - let mut tiles: Vec<(u32, u32)> = dirty.iter().copied().collect(); - - // Partition by block order so only the requested chunk needs sorting - tiles.select_nth_unstable_by_key(max_tiles - 1, |&(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x)); - tiles.truncate(max_tiles); - tiles.sort_by_key(|&(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x)); - for tile in &tiles { - dirty.remove(tile); + // Keep only the earliest block-ordered tiles in this chunk + let block_order = |(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x); + let mut keys = dirty.iter().copied().map(block_order); + let mut selected: BinaryHeap<_> = keys.by_ref().take(max_tiles).collect(); + for key in keys { + if let Some(mut latest) = selected.peek_mut() + && key < *latest + { + *latest = key; + } } - tiles + selected + .into_sorted_vec() + .into_iter() + .map(|(_, _, y, x)| { + dirty.remove(&(x, y)); + (x, y) + }) + .collect() } /// Dirty tiles a neighbourhood filter runs over ahead of the chunk being composited. diff --git a/crates/engine/src/thumbs.rs b/crates/engine/src/thumbs.rs index bd6bdd13..0fd6c6e4 100644 --- a/crates/engine/src/thumbs.rs +++ b/crates/engine/src/thumbs.rs @@ -513,17 +513,23 @@ mod tests { let (mut service, jobs, results) = held_worker(); service.begin_frame(&session, 0.0); service.get(&session, target); + assert!(service.poll(&session)); + let job = jobs.try_recv().unwrap(); results.send(Done { generation: job.generation, target, image: job.snapshot.render(target) }).unwrap(); service.begin_frame(&session, 0.1); + assert!(service.get(&session, target).image.is_none()); + let repaint = service.poll(&session); assert!(service.is_fresh(target)); assert!(repaint, "the frame drew before collecting the final thumbnail"); + service.begin_frame(&session, 0.2); + assert!(service.get(&session, target).image.is_some()); assert!(!service.poll(&session), "an idle cache must stop repainting"); } @@ -539,6 +545,7 @@ mod tests { service.begin_frame(&session, 0.1); service.poll(&session); + assert_eq!(jobs.try_recv().map(|job| job.target).ok(), Some(target), "the late request is dispatched, not dropped"); } diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index fc85fd59..6d77ebf5 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -499,10 +499,14 @@ mod tests { #[test] fn hdr_resources_become_the_environment() { let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + assert!(execute(&mut s, "display.set", &json!({"environment": "resource:sky.hdr"})).is_err(), "unknown resources are rejected"); + let e = execute(&mut s, "display.set", &json!({"environment": "nonexistent"})).unwrap_err().to_string(); + assert!(e.contains("Studio Soft"), "unknown environments are rejected with the valid names: {e}"); assert_eq!(s.doc.project.display.environment, "Studio Soft"); + execute(&mut s, "display.set", &json!({"environment": "Night"})).unwrap(); let img = image::Rgb32FImage::from_fn(64, 32, |_, y| image::Rgb([if y < 8 { 40.0 } else { 0.5 }; 3])); let mut hdr = Vec::new(); @@ -510,6 +514,7 @@ mod tests { let name = s.import_resource_bytes("sky.hdr", hdr).unwrap(); let res = &s.images[&name]; assert!(!res.srgb && res.rgba[0][0] > 30.0, "HDR keeps values above 1"); + let env = format!("resource:{name}"); let r = execute( &mut s, @@ -517,12 +522,16 @@ mod tests { &json!({"environment": env, "specGloss": true, "parallax": true, "displacement": true, "taa": false, "scatterColor": [2.0, 0.5, 0.25], "scatterRadius": 0.3}), ) .unwrap(); + assert_eq!(r["environment"], json!(env)); + let d = &s.doc.project.display; assert!(d.spec_gloss && d.parallax && d.displacement && !d.taa); assert_eq!((d.scatter_color, d.scatter_radius), ([1.0, 0.5, 0.25], 0.3), "scatter settings (clamped)"); assert_eq!(d.environment_resource(), Some(name.as_str())); + execute(&mut s, "file.removeUnused", &Value::Null).unwrap(); + assert!(s.doc.resources.contains_key(&name), "the environment's image counts as used"); } @@ -530,16 +539,21 @@ mod tests { fn the_projection_gizmos_hide_per_project_and_old_projects_show_them() { let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); let shown = serde_json::to_value(&s.doc.project.display).unwrap(); + assert!(s.doc.project.display.projection_gizmos && shown.get("projection_gizmos").is_none(), "shown by default and saved as before: {shown}"); let hidden = execute(&mut s, "display.set", &json!({"projectionGizmos": false})).unwrap(); + assert!(!s.doc.project.display.projection_gizmos); assert_eq!(hidden["projection_gizmos"], json!(false), "hidden is saved with the project"); assert!(s.history_labels().is_empty(), "a view flag is no undo step"); let reopened: texturecraft_core::project::DisplaySettings = serde_json::from_value(hidden).unwrap(); + assert!(!reopened.projection_gizmos, "a saved project opens with its gizmos hidden"); + let old: texturecraft_core::project::DisplaySettings = serde_json::from_value(shown).unwrap(); + assert!(old.projection_gizmos, "a project saved before the flag shows them"); } } diff --git a/crates/engine/tests/it/fill_patterns.rs b/crates/engine/tests/it/fill_patterns.rs index c5d854ba..18ba302c 100644 --- a/crates/engine/tests/it/fill_patterns.rs +++ b/crates/engine/tests/it/fill_patterns.rs @@ -57,6 +57,7 @@ fn a_pattern_parameter_given_alone_keeps_every_other_one() { } let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"balance\":-0.5") && inspected.contains("\"invert\":false"), "inspect shows the balance and invert"); } @@ -65,5 +66,6 @@ fn a_pattern_parameter_given_alone_keeps_every_other_one() { fn another_pattern_kind_starts_from_its_defaults() { let (mut session, layer) = clouds_fill(); execute(&mut session, "layer.fill.set", &json!({"layer": layer.0, "channel": "roughness", "procedural": "Cells"})).unwrap(); + assert_eq!(roughness(&session, layer), (Procedural::new(ProceduralKind::Cells), [0.0; 3], [1.0; 3])); } diff --git a/crates/engine/tests/it/fill_projections.rs b/crates/engine/tests/it/fill_projections.rs index 5d9d18de..23711592 100644 --- a/crates/engine/tests/it/fill_projections.rs +++ b/crates/engine/tests/it/fill_projections.rs @@ -50,12 +50,19 @@ fn three_d_projection_settings_turn_stretch_and_move_every_3d_projection() { let plain = snapshot(&mut s); set(&mut s, layer, json!({"projectorRotation": [30, 45, 60]})); + assert_ne!(snapshot(&mut s), plain, "{kind}: rotation turns the pattern"); + set(&mut s, layer, json!({"projectorRotation": [0, 0, 0], "projectorScale": [2, 0.5, 1]})); + assert_ne!(snapshot(&mut s), plain, "{kind}: per-axis scale stretches the pattern"); + set(&mut s, layer, json!({"projectorScale": 1, "offset": [0.3, 0.2, 0.1]})); + assert_ne!(snapshot(&mut s), plain, "{kind}: offset moves the pattern"); + set(&mut s, layer, json!({"offset": 0})); + assert_eq!(snapshot(&mut s), plain, "{kind}: the defaults change nothing"); set(&mut s, layer, json!({"projectorRotation": [10, 20, 30], "projectorScale": [1, 2, 3]})); @@ -71,6 +78,7 @@ fn three_d_projection_settings_turn_stretch_and_move_every_3d_projection() { other => panic!("{kind}: loaded as {other:?}"), }; assert_eq!(settings, Projector::default(), "{kind}: an older save has no turn or stretch"); + set(&mut s, layer, json!({"projectorRotation": 0, "projectorScale": 1})); } @@ -118,9 +126,12 @@ fn match_per_uv_tile_repeats_the_source_once_per_tile() { assert_ne!(left, right, "a UV projection runs on into the next tile"); set(&mut s, layer, json!({"projection": "uvTile"})); + assert_eq!(projection(&s, layer), Projection::UvTile); + let (left, right) = tiles(&mut s); let worst = left.iter().zip(&right).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); + assert!(worst < 1e-4, "every tile shows the same pattern (worst difference {worst})"); } @@ -132,13 +143,17 @@ fn cylindrical_angle_is_the_arc_one_repeat_spans() { set(&mut s, layer, json!({"projection": "cylindrical"})); let plain = snapshot(&mut s); set(&mut s, layer, json!({"angle": 120})); + assert!(matches!(projection(&s, layer), Projection::Cylindrical { angle: 120.0, .. })); assert_ne!(snapshot(&mut s), plain, "a third of the way round repeats three times"); + set(&mut s, layer, json!({"angle": 360})); + assert_eq!(snapshot(&mut s), plain, "360 degrees is the whole way round"); let mut saved = serde_json::to_value(projection(&s, layer)).unwrap(); saved["Cylindrical"].as_object_mut().unwrap().remove("angle"); + assert!(matches!(serde_json::from_value(saved).unwrap(), Projection::Cylindrical { angle: 360.0, .. })); } @@ -160,6 +175,7 @@ fn shape_crop_stops_a_projection_at_its_shape() { set(&mut s, layer, json!({"projection": "triplanar"})); let plain = snapshot(&mut s); set(&mut s, layer, json!({"shapeCrop": "cropped"})); + assert_eq!(snapshot(&mut s), plain, "the default box holds the whole mesh"); set(&mut s, layer, json!({"projectorScale": 0.5})); @@ -186,6 +202,7 @@ fn backface_culling_keeps_a_planar_projection_off_faces_turned_away() { let (far, near) = (facing_z(&s, -1.1, -0.05), facing_z(&s, 0.05, 1.1)); assert!(!far.is_empty() && !near.is_empty()); assert!(far.iter().any(|&i| plain[i] != empty[i]), "without culling the projection reaches the far side"); + set(&mut s, layer, json!({"backfaceCulling": true, "backfaceAngle": 90, "backfaceHardness": 1})); let culled = snapshot(&mut s); assert!(far.iter().all(|&i| culled[i] == empty[i]), "faces turned away get none of the projection"); @@ -241,6 +258,7 @@ fn placed_planars_with_a_decals_look_save_as_decals() { let fill = Fill { projection: Projection::decal(frame), ..Fill::default() }; let saved = serde_json::to_value(&fill).unwrap(); + assert_eq!(saved["projection"], json!({ "Decal": frame })); assert_eq!(serde_json::from_value::(saved).unwrap(), fill, "and reads back the same"); @@ -248,6 +266,7 @@ fn placed_planars_with_a_decals_look_save_as_decals() { let Projection::Planar { uv, .. } = &mut turned.projection else { panic!("{:?}", turned.projection) }; uv.rotation = 30.0; let saved = serde_json::to_value(&turned).unwrap(); + assert_eq!(saved["projection"]["Planar"]["placed"], json!(frame)); assert_eq!(serde_json::from_value::(saved).unwrap(), turned); } @@ -265,6 +284,7 @@ fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame() assert_eq!((corners, depth), (Projection::FRAME_CORNERS, Projection::WARP_DEPTH)); assert_eq!((frame.normal, frame.up), ([0.0, 0.0, 1.0], [0.0, 1.0, 0.0]), "seen from the front"); assert!(frame.size.iter().all(|side| (side - 2.0).abs() < 1e-3) && frame.center.iter().all(|c| c.abs() < 1e-3), "around the unit sphere: {frame:?}"); + let unpulled = snapshot(&mut s); assert_ne!(unpulled, empty); @@ -272,7 +292,9 @@ fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame() set(&mut s, layer, json!({"warpCorners": pulled})); let bent = snapshot(&mut s); assert_ne!(bent, unpulled, "a pulled corner bends the image"); + set(&mut s, layer, json!({"projection": "warp", "rotation": 0})); + assert_eq!(snapshot(&mut s), bent, "picking warp again keeps the corners"); set(&mut s, layer, json!({"shapeCrop": "cropped", "warpCorners": Projection::FRAME_CORNERS})); @@ -283,6 +305,7 @@ fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame() assert!(!beyond.is_empty() && !within.is_empty()); assert!(beyond.iter().all(|&i| cropped[i] == empty[i]), "past its Projection Depth the warp does not reach"); assert!(within.iter().all(|&i| cropped[i] == unpulled[i]), "within it the warp covers as before"); + set(&mut s, layer, json!({"projectionDepth": 1})); let deep = snapshot(&mut s); assert!(beyond.iter().all(|&i| deep[i] == unpulled[i]), "a deeper warp reaches the whole sphere"); @@ -291,15 +314,20 @@ fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame() execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).unwrap(); let Projection::Warp { frame: reset, corners, depth, .. } = projection(&s, layer) else { panic!("still a warp") }; assert_eq!((reset, corners, depth), (frame, Projection::FRAME_CORNERS, 1.0), "the frame and corners go back; the depth stays"); + let steps = s.history_labels().len(); execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "resetting a frame already reset adds no undo step"); let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["projection"], "Warp projection"); assert_eq!(row["fill"]["projectionSettings"]["Warp"]["corners"], json!(Projection::FRAME_CORNERS)); + set(&mut s, layer, json!({"projection": "planar"})); + assert!(execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).is_err(), "only a warp has a frame to reset"); } @@ -314,6 +342,7 @@ fn depth_culling_keeps_planar_and_warp_projections_off_hidden_surfaces() { set(&mut s, layer, json!({"projection": "planar", "axis": 2})); let Projection::Planar { projector, .. } = projection(&s, layer) else { panic!("{:?}", projection(&s, layer)) }; assert_eq!(projector.depth, DepthCulling::NEW, "a new planar projection culls by depth"); + let culled = snapshot(&mut s); set(&mut s, layer, json!({"depthCulling": false})); let plain = snapshot(&mut s); @@ -326,18 +355,23 @@ fn depth_culling_keeps_planar_and_warp_projections_off_hidden_surfaces() { assert!(near.iter().all(|&i| culled[i] == plain[i]), "the near side keeps all of it"); set(&mut s, layer, json!({"depthCulling": true, "depthCullingHardness": 0})); + assert_ne!(snapshot(&mut s), culled, "a softer cull fades further behind the near side"); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["projectionSettings"]["Planar"]["projector"]["depth"], json!({"on": true, "hardness": 0.0})); set(&mut s, layer, json!({"projection": "warp"})); let Projection::Warp { projector, .. } = projection(&s, layer) else { panic!("{:?}", projection(&s, layer)) }; assert_eq!(projector.depth, DepthCulling::NEW, "a new warp culls by depth"); + let warped = snapshot(&mut s); assert!(far.iter().all(|&i| warped[i] == empty[i]), "a warp from the front leaves the far side bare"); let saved: Projector = serde_json::from_value(json!({"rotation": [0, 0, 0], "scale": [1, 1, 1]})).unwrap(); + assert_eq!(saved.depth, DepthCulling { on: false, hardness: 0.75 }, "an older save has no depth culling"); } @@ -357,13 +391,17 @@ fn fill_symmetry_axis_reads_an_index_or_a_letter() { }; set(&mut s, layer, json!({"symmetryAxis": "Y"})); + assert_eq!(axis(&s), 1); + set(&mut s, layer, json!({"symmetryAxis": 2})); + assert_eq!(axis(&s), 2); for refused in [json!("w"), json!(true), json!(-1), json!(3)] { assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryAxis": refused})).is_err(), "{refused}"); } + assert_eq!(axis(&s), 2, "a refused axis changes nothing"); } @@ -392,7 +430,9 @@ fn fill_symmetry_mirrors_or_turns_copies_of_a_3d_projection() { assert!(filled(&far, &turned, &empty) > far.len() / 2, "the copy turned half round reaches the far side"); assert!(near.iter().all(|&i| turned[i] == plain[i]), "the original keeps its own wedge"); assert_ne!(turned, mirrored, "a turned copy is not a mirrored one"); + set(&mut s, layer, json!({"symmetry": false})); + assert_eq!(snapshot(&mut s), plain, "switched off, the copies go"); // A left to right ramp shows a copy's image turned over @@ -408,11 +448,14 @@ fn fill_symmetry_mirrors_or_turns_copies_of_a_3d_projection() { set(&mut s, layer, json!({"projection": "uv"})); let uv = snapshot(&mut s); set(&mut s, layer, json!({"symmetry": false})); + assert_eq!(snapshot(&mut s), uv, "a UV projection has no copies"); assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryType": "spiral"})).is_err()); assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryAxis": 3})).is_err()); + let saved: Sampling = serde_json::from_value(json!({"filtering": "BilinearHq", "wrap": "Repeat", "scale": "Tiling"})).unwrap(); + assert_eq!(saved.symmetry, FillSymmetry::OFF, "an older save has no symmetry"); } @@ -431,23 +474,28 @@ fn moving_an_axis_planar_places_it_as_its_frame_first() { let placed = projection(&s, layer); let Projection::Planar { placed: Some(frame), projector, .. } = &placed else { panic!("placed: {placed:?}") }; assert_eq!((projector.rotation, projector.scale), ([0.0; 3], [1.0; 3]), "the turn is in the frame now"); + let after = snapshot(&mut s); let moved = before.iter().zip(&after).filter(|(a, b)| (*a - *b).abs() > 2.0 / 255.0).count(); assert!(moved * 200 < before.len(), "the image stays where it was: {moved} of {} texels changed", before.len()); execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "offset": [0.4, 0.0], "merge": true})).unwrap(); + assert_ne!(snapshot(&mut s), after, "then the frame moves the image"); let Projection::Planar { placed: Some(slid), .. } = projection(&s, layer) else { panic!("still placed") }; assert_eq!((slid.offset, slid.size), ([0.4, 0.0], frame.size)); s.undo().unwrap(); + assert_eq!(projection(&s, layer), axis, "placing and moving is one step"); set(&mut s, layer, json!({"projection": "warp", "warpCorners": [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]]})); execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "rotation": 30})).unwrap(); let Projection::Warp { frame, corners, .. } = projection(&s, layer) else { panic!("still a warp") }; assert_eq!((frame.rotation, corners[1]), (30.0, [0.9, 0.9]), "a warp's frame turns and keeps its corners"); + set(&mut s, layer, json!({"projection": "spherical"})); + assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "rotation": 30})).is_err(), "a spherical projection has no frame"); } @@ -486,6 +534,7 @@ fn a_frame_under_uneven_culling_is_refused_with_the_way_out_and_changes_nothing( if placed { set(&mut s, layer, json!({"projectorScale": 1})); execute(&mut s, "layer.decal.set", &json!({"layer": layer.0})).unwrap(); + assert!(projection(&s, layer).placed().is_some(), "an even scale places the frame"); } @@ -502,6 +551,7 @@ fn a_frame_under_uneven_culling_is_refused_with_the_way_out_and_changes_nothing( // A placed frame's edit that moves no frame still lands execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "flipU": true})).unwrap(); + assert!(projection(&s, layer).frame().is_some_and(|frame| frame.flip[0]), "the flip lands on the placed frame"); } @@ -524,10 +574,14 @@ fn a_frame_takes_its_offset_rotation_and_scale_and_folds_its_projector_in_first( execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameOffset": [0.0, 0.0, 0.0]})).unwrap(); let Projection::Planar { placed: Some(frame), projector, .. } = projection(&s, layer) else { panic!("still placed") }; assert_eq!((projector.rotation, projector.scale), ([0.0; 3], [1.0; 3]), "folded into the frame"); + let (lo, hi) = s.mesh.bounds(); assert!((Vec3::from(frame.center) - (lo + hi) * 0.5).length() < 1e-4, "offset 0 = the mesh's centre: {frame:?}"); + let shown = texturecraft_engine::compose::frame_placement::placement(&projection(&s, layer), (lo, hi)).unwrap(); + assert!((shown.rotation[2] - 30.0).abs() < 1e-3 && shown.rotation[0].abs() < 1e-3, "the projector's turn shows as the frame's: {shown:?}"); + let folded = snapshot(&mut s); let changed = turned.iter().zip(&folded).filter(|(a, b)| (*a - *b).abs() > 2.0 / 255.0).count(); assert!(changed * 200 < turned.len(), "the frame was already at the centre: the image stays, {changed} of {} texels changed", turned.len()); @@ -536,16 +590,21 @@ fn a_frame_takes_its_offset_rotation_and_scale_and_folds_its_projector_in_first( .unwrap(); let Projection::Planar { placed: Some(narrow), .. } = projection(&s, layer) else { panic!("still placed") }; assert!((narrow.size[0] - frame.size[0] * 0.5).abs() < 1e-4 && (narrow.size[1] - frame.size[1]).abs() < 1e-4, "Scale X halves the width"); + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameRotation": [0, 0, 90], "merge": true})).unwrap(); let again = texturecraft_engine::compose::frame_placement::placement(&projection(&s, layer), (lo, hi)).unwrap(); + assert!((again.rotation[2] - 90.0).abs() < 1e-3 && (again.scale[0] - shown.scale[0] * 0.5).abs() < 1e-4, "{again:?}"); assert_eq!(s.history_labels().len(), steps + 1, "a drag is one undo step"); + s.undo().unwrap(); + assert_eq!(snapshot(&mut s), turned, "undo puts the turned projector back"); for bad in [json!({"frameScale": [1, 2]}), json!({"frameOffset": "x"}), json!({"frameScale": [0, -1, "deep"]})] { let mut params = bad.clone(); params["layer"] = json!(layer.0); + assert!(execute(&mut s, "layer.decal.set", ¶ms).is_err(), "{bad}"); } @@ -583,10 +642,12 @@ fn a_decal_edit_that_changes_nothing_adds_no_undo_step() { json!({"effect": mask_effect, "image": ramp}), ] { execute(&mut s, "layer.decal.set", &unchanged).unwrap(); + assert_eq!(s.history_labels().len(), steps, "{unchanged} changes nothing"); } execute(&mut s, "layer.decal.set", &json!({"layer": layer, "rotation": 45})).unwrap(); + assert_eq!(s.history_labels().len(), steps + 1, "a turn is an edit"); } @@ -625,6 +686,7 @@ fn inspect_shows_a_mask_decals_frame_as_a_layer_decals() { ] { assert!(on_request(frame), "the {name} shows its frame on the requested placement: {frame}"); } + assert_eq!(layer_frame, layer_decal["decal"], "a layer decal's frame"); assert_eq!(mask_effect["decal"], mask_decal["decal"], "a mask decal's frame"); } @@ -652,6 +714,7 @@ fn a_warps_current_reach_as_depth_adds_no_undo_step() { let reach = depth * frame.size[0].max(frame.size[1]); execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "depth": reach})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "reach {reach} is the one it has"); } @@ -705,17 +768,21 @@ fn reset_fill_settings_keeps_the_projection_and_restores_its_defaults_in_one_und assert_eq!(reset.sampling, Sampling { symmetry: changed.sampling.symmetry, ..Sampling::default() }, "the sampling is a new fill's; the symmetry stays"); assert_eq!(reset.sources, changed.sources, "the material stays"); assert!(texturecraft_engine::fill_reset_cmds::at_defaults(&reset.projection, reset.sampling)); + let steps = s.history_labels().len(); execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "resetting a Fill section at its defaults adds no undo step"); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(fill(&s), changed, "one undo brings every setting back"); assert!(execute(&mut s, "layer.fill.resetProjection", &json!({"layer": 9999})).is_err(), "no such layer"); // A UV fill comes back to a UV projection at tiling 1 and renders like a new fill set(&mut s, layer, json!({"projection": "uv", "tiling": [3, 2], "rotation": 30})); execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap(); + assert_eq!(fill(&s).projection, Projection::default()); assert_eq!(snapshot(&mut s), fresh, "it renders like the new fill"); } @@ -737,6 +804,7 @@ fn reset_fill_settings_keeps_a_warp_frame_and_restores_its_settings() { assert_ne!(moved, fitted, "the frame was moved"); execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap(); + assert_eq!(projection(&s, layer), Projection::warp(moved), "still a warp: its frame stays, every setting is a new warp's"); } @@ -760,6 +828,7 @@ fn malformed_warp_corners_copy_flips_and_a_warps_own_placement_are_rejected_and_ ] { let mut p = bad.clone(); p["layer"] = json!(layer.0); + assert!(execute(&mut s, "layer.fill.projection", &p).is_err(), "{bad}"); } diff --git a/crates/engine/tests/it/fill_sampling.rs b/crates/engine/tests/it/fill_sampling.rs index fd17f481..cfb64e15 100644 --- a/crates/engine/tests/it/fill_sampling.rs +++ b/crates/engine/tests/it/fill_sampling.rs @@ -71,10 +71,12 @@ fn filtering_decides_how_a_shrunk_image_reads() { let red = cache.composite.value(Channel::BaseColor, x, y)[0]; !(0.01..=0.99).contains(&red) }); + assert!(pure, "Nearest reads one image texel: black or white only"); let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["filtering"], json!("nearest")); assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "filtering": "trilinear"})).is_err()); } @@ -90,6 +92,7 @@ fn fills_saved_before_filtering_keep_their_look() { let mut saved = serde_json::to_value(fill).unwrap(); saved.as_object_mut().unwrap().remove("sampling"); let loaded: Fill = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.sampling, Sampling::SAVED_BEFORE); assert_eq!(loaded.sampling.filtering, Filtering::BilinearSharp); } @@ -126,18 +129,22 @@ fn uv_wrap_repeats_the_tile_or_stops_at_its_edge() { let near = |got: f32, want: f32| (got - want).abs() < 0.05; let repeat = shown(&mut s); assert!(near(repeat, 1.0), "Repeat covers the band: {repeat}"); + set(&mut s, json!({"wrap": "none"})).unwrap(); let none = shown(&mut s); assert!(near(none, 0.125), "None: a quarter across, half down: {none}"); + set(&mut s, json!({"wrap": "repeatHorizontally"})).unwrap(); let across = shown(&mut s); assert!(near(across, 0.5), "repeating across: the whole width, half down: {across}"); + set(&mut s, json!({"wrap": "repeatVertically"})).unwrap(); let down = shown(&mut s); assert!(near(down, 0.25), "repeating down: a quarter across, the whole height: {down}"); let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["wrap"], json!("repeatVertically")); assert!(set(&mut s, json!({"wrap": "mirror"})).is_err()); @@ -187,12 +194,16 @@ fn three_d_projections_take_uv_transformations() { let mut saved = serde_json::to_value(projection(&s)).unwrap(); saved["Triplanar"].as_object_mut().unwrap().remove("uv"); let loaded: Projection = serde_json::from_value(saved).unwrap(); + assert!(matches!(loaded, Projection::Triplanar { uv, .. } if uv == UvTransform::default())); + set(&mut s, json!({"tiling": 1, "rotation": 0, "uvOffset": [0, 0]})).unwrap(); + assert_eq!(snapshot(&mut s), plain, "the identity transform changes nothing"); // On a UV projection, tiling is its scale set(&mut s, json!({"projection": "uv", "tiling": [2, 4]})).unwrap(); + assert!(matches!(projection(&s), Projection::Uv { scale, .. } if scale == [2.0, 4.0])); } @@ -208,11 +219,13 @@ fn scale_mode_is_stored_without_changing_the_tiling() { let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["scaleMode"], json!("physicalSize")); assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "scaleMode": "inches"})).is_err()); let mut saved = serde_json::to_value(&fill).unwrap(); saved["sampling"].as_object_mut().unwrap().remove("scale"); let loaded: Fill = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.sampling.scale, ScaleMode::Tiling); } diff --git a/crates/engine/tests/it/painter_gaps.rs b/crates/engine/tests/it/painter_gaps.rs index 4ad6c736..26fcb753 100644 --- a/crates/engine/tests/it/painter_gaps.rs +++ b/crates/engine/tests/it/painter_gaps.rs @@ -133,6 +133,7 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() { p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); execute(&mut s, "effect.add.filter", &p).unwrap(); } + assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0).iter().all(|v| v.is_finite())); } @@ -187,10 +188,13 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() { let name = s .import_resource_bytes("logo.png", png(32, 32, |x, y| if (x as i32 - 16).pow(2) + (y as i32 - 16).pow(2) < 196 { [255, 0, 0, 255] } else { [0; 4] })) .unwrap(); + assert!(execute(&mut s, "layer.add.decal", &json!({"image": "missing.png"})).is_err()); assert!(execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 2, "y": 2})).is_err(), "off the mesh"); + let r = execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 200, "y": 200, "size": 0.5})).unwrap(); let layer = id(r.clone(), "layer"); + assert!((r["decal"]["size"][1].as_f64().unwrap() - 0.5).abs() < 1e-6); let LayerKind::Fill(f) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; assert!(matches!(f.projection, Projection::Planar { placed: Some(_), .. })); @@ -202,19 +206,30 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() { // Bigger, then moved along its plane, then re-placed with a click execute(&mut s, "layer.decal.set", &json!({"size": 1.2})).unwrap(); + assert!(red(at(&mut s, Channel::BaseColor, 160.0, 200.0))); + execute(&mut s, "layer.decal.set", &json!({"size": 0.4, "offset": [0.6, 0.0], "rotation": 45})).unwrap(); + assert!(!red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "moved away"); + let r = execute(&mut s, "layer.decal.set", &json!({"x": 170, "y": 180})).unwrap(); + assert_eq!(r["decal"]["offset"], json!([0.0, 0.0]), "re-placing resets the offset"); assert!(red(at(&mut s, Channel::BaseColor, 170.0, 180.0))); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains("Planar projection") && inspect.contains("\"decal\"") && inspect.contains("\"rotation\":45"), "inspect shows the decal"); + // Not a decal; one undo step per edit let plain = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer"); + assert!(execute(&mut s, "layer.decal.set", &json!({"layer": plain.0, "size": 1})).is_err()); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(!red(at(&mut s, Channel::BaseColor, 170.0, 180.0))); } @@ -239,9 +254,13 @@ fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() { // Only the effect id, with no layer selected s.selected.clear(); + assert!(s.selected_layer().is_none()); + let r = execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "size": [0.3, 0.2], "offset": [0.1, -0.05], "rotation": 30, "depth": 0.2})).unwrap(); + assert_eq!(r["layer"], json!(layer.0), "the owning layer is reported"); + let after = effect_decal(&s, effect); assert_eq!((after.size, after.offset, after.rotation), ([0.3, 0.2], [0.1, -0.05], 30.0)); assert_eq!(after.center, before.center, "the other fields stay"); @@ -249,10 +268,12 @@ fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() { // Re-placing with a click execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "layer": layer.0, "x": 170, "y": 180})).unwrap(); + assert_eq!(effect_decal(&s, effect).offset, [0.0, 0.0]); execute(&mut s, "edit.undo", &Value::Null).unwrap(); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(effect_decal(&s, effect), before, "undo restores the effect's decal"); // The layer decal is untouched by all of it @@ -261,8 +282,10 @@ fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() { // Errors: unknown effect, an effect that is not a decal, an effect of another layer assert!(execute(&mut s, "layer.decal.set", &json!({"effect": 999_999, "size": 1})).is_err()); + execute(&mut s, "layer.select", &json!({"layer": layer.0})).unwrap(); let levels = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": "levels"})).unwrap(), "effect"); + assert!(execute(&mut s, "layer.decal.set", &json!({"effect": levels.0, "size": 1})).is_err()); assert!(execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "layer": layer_decal.0, "size": 1})).is_err()); assert_eq!(effect_decal(&s, effect), before); @@ -270,6 +293,7 @@ fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() { // A new image replaces the effect's source, not a layer channel let other = s.import_resource_bytes("other.png", png(4, 4, |_, _| [0, 0, 0, 255])).unwrap(); execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "image": other})).unwrap(); + assert!(matches!(&s.doc.project.effect(effect).unwrap().1.kind, EffectKind::Fill { source: Source::Image { name, .. }, .. } if *name == other)); } @@ -281,8 +305,10 @@ fn decals_keep_the_image_aspect_and_flip_their_image() { let name = s.import_resource_bytes("wide.png", png(8, 4, |x, _| if x < 4 { [255, 0, 0, 255] } else { [0, 0, 255, 255] })).unwrap(); let r = execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 200, "y": 200, "size": 0.5})).unwrap(); let layer = id(r.clone(), "layer"); + assert_eq!(r["decal"]["size"], json!([1.0, 0.5]), "a new decal follows its image"); assert!(r["decal"].get("flip").is_none(), "nothing flipped saves nothing extra"); + let size = |s: &mut Session| { let LayerKind::Fill(f) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; let Projection::Planar { placed: Some(d), .. } = &f.projection else { panic!("a decal") }; @@ -291,33 +317,52 @@ fn decals_keep_the_image_aspect_and_flip_their_image() { // A pair of sides is taken as given, unless the proportions are kept: then the width wins execute(&mut s, "layer.decal.set", &json!({"size": [0.6, 0.6]})).unwrap(); + assert_eq!(size(&mut s).0, [0.6, 0.6]); + execute(&mut s, "layer.decal.set", &json!({"size": [0.8, 0.8], "keepProportions": true})).unwrap(); + assert_eq!(size(&mut s).0, [0.8, 0.4], "the width sets the height by the image's aspect"); + execute(&mut s, "layer.decal.set", &json!({"size": 0.2, "keepProportions": true})).unwrap(); + assert_eq!(size(&mut s).0, [0.4, 0.2], "a height sets the width"); + execute(&mut s, "layer.decal.set", &json!({"size": [0.6, 0.6]})).unwrap(); execute(&mut s, "layer.decal.set", &json!({"keepProportions": true})).unwrap(); + assert_eq!(size(&mut s).0, [0.6, 0.3], "turning the lock on fits the height to the width"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(size(&mut s).0, [0.6, 0.6], "one undo step"); // Flip U and V each on their own, kept by later edits, undone one step at a time execute(&mut s, "layer.decal.set", &json!({"size": [1.0, 0.5]})).unwrap(); + assert!(red(at(&mut s, Channel::BaseColor, 190.0, 200.0)) && !red(at(&mut s, Channel::BaseColor, 210.0, 200.0))); + let r = execute(&mut s, "layer.decal.set", &json!({"flipU": true})).unwrap(); + assert_eq!(r["decal"]["flip"], json!([true, false])); assert!(!red(at(&mut s, Channel::BaseColor, 190.0, 200.0)) && red(at(&mut s, Channel::BaseColor, 210.0, 200.0)), "Flip U mirrors the image in its frame"); + execute(&mut s, "layer.decal.set", &json!({"flipV": true, "rotation": 10})).unwrap(); + assert_eq!(size(&mut s).1, [true, true]); + execute(&mut s, "layer.decal.set", &json!({"flipU": false})).unwrap(); + assert_eq!(size(&mut s).1, [false, true], "the other flip stays"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(size(&mut s).1, [true, true]); // A new image in the same call sets the aspect: a tall one (1:2) let tall = s.import_resource_bytes("tall.png", png(4, 8, |_, _| [255, 0, 0, 255])).unwrap(); execute(&mut s, "layer.decal.set", &json!({"image": tall, "size": 0.4, "keepProportions": true})).unwrap(); + assert_eq!(size(&mut s).0, [0.2, 0.4]); } @@ -505,28 +550,36 @@ fn a_decal_image_fills_a_chosen_channel_or_a_mask() { let place = |channel: &str| json!({"image": name, "channel": channel, "x": 200, "y": 200, "size": 0.5}); let rough = id(execute(&mut s, "layer.add.decal", &place("roughness")).unwrap(), "layer"); + assert_eq!(s.doc.project.layer(rough).unwrap().channels.keys().copied().collect::>(), [Channel::Roughness]); assert!(at(&mut s, Channel::Roughness, 200.0, 200.0)[0] > 0.95, "the white image is full roughness under the decal"); assert!(execute(&mut s, "layer.add.decal", &place("sparkle")).is_err(), "unknown channel"); + let missing = Channel::ALL.into_iter().find(|channel| !s.doc.project.texture_sets[0].has_channel(*channel)).unwrap(); + assert!(execute(&mut s, "layer.add.decal", &place(missing.id())).is_err(), "a channel the set lacks"); let added = execute(&mut s, "layer.add.decal", &place("mask")).unwrap(); let masked = id(added.clone(), "layer"); let mask = s.doc.project.layer(masked).unwrap().mask.as_ref().unwrap(); + assert!( matches!(mask.effects.as_slice(), [effect] if matches!(effect.kind, EffectKind::Fill { projection: Projection::Planar { placed: Some(_), .. }, .. })) ); assert_eq!(added["maskEffect"], json!(mask.effects[0].id.0)); + execute(&mut s, "layer.fill.set", &json!({"layer": masked.0, "channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the mask shows the layer under the decal"); assert!(!red(at(&mut s, Channel::BaseColor, 120.0, 200.0)), "and hides it elsewhere"); let effect = &added["maskEffect"]; execute(&mut s, "layer.decal.set", &json!({"effect": effect, "x": 150, "y": 200})).unwrap(); + assert!(red(at(&mut s, Channel::BaseColor, 150.0, 200.0)), "a mask decal moves like a decal layer"); assert!(!red(at(&mut s, Channel::BaseColor, 230.0, 200.0))); assert!(execute(&mut s, "layer.decal.set", &json!({"effect": rough.0, "x": 150, "y": 200})).is_err(), "a layer id is not an effect"); + execute(&mut s, "layer.decal.set", &json!({"effect": effect, "layer": masked.0, "size": 0.4})).expect("an effect with its own layer"); let mismatched = json!({"effect": effect, "layer": rough.0, "size": 0.4}); assert!(execute(&mut s, "layer.decal.set", &mismatched).is_err(), "an effect with another layer is refused"); @@ -686,24 +739,32 @@ fn fill_projection_edits_keep_what_they_do_not_change() { }; set(&mut s, json!({"rotation": 390, "offset": [0.25, 0.5]})).unwrap(); set(&mut s, json!({"scale": 2})).unwrap(); + assert_eq!(proj(&s), Projection::Uv { scale: [2.0, 2.0], rotation: 30.0, offset: [0.25, 0.5] }, "a scale keeps the rotation and offset"); + set(&mut s, json!({"projection": "uv", "scale": [2, 3], "offset": "far"})).unwrap(); + assert_eq!(proj(&s), Projection::Uv { scale: [2.0, 3.0], rotation: 30.0, offset: [0.25, 0.5] }, "the same kind keeps its fields; a bad offset is ignored"); + set(&mut s, json!({"projection": "triplanar", "offset": [1, 2, 3]})).unwrap(); set(&mut s, json!({"sharpness": 100})).unwrap(); + assert_eq!( proj(&s), Projection::Triplanar { scale: 1.0, sharpness: 64.0, offset: [1.0, 2.0, 3.0], uv: Default::default(), projector: Default::default() }, "a new kind starts from its defaults" ); + set(&mut s, json!({"projection": "planar", "axis": 7, "offset": [1e9, 0, 0]})).unwrap(); + assert_eq!( proj(&s), Projection::Planar { scale: 1.0, axis: 2, offset: [1000.0, 0.0, 0.0], uv: Default::default(), projector: Projector::depth_culled(), placed: None }, "hostile values are clamped" ); assert!(set(&mut s, json!({"projection": "hexagonal"})).is_err()); - // The offset moves the pattern: a UV offset changes what the composite shows. + + // The offset moves the pattern: a UV offset changes what the composite shows set(&mut s, json!({"projection": "uv", "scale": 1})).unwrap(); execute( &mut s, @@ -934,6 +995,7 @@ fn a_saved_decal_with_an_out_of_range_axis_is_repaired_on_load_and_can_be_edited let bytes = session.to_project_bytes().unwrap(); let mut loaded = Session::from_project_bytes(&bytes).unwrap(); + assert_eq!(decal_of(&loaded, layer).symmetry.unwrap().axis, 2); execute(&mut loaded, "layer.decal.set", &json!({"layer": layer.0, "rotation": 12})).unwrap(); diff --git a/crates/engine/tests/it/user_smart_mask.rs b/crates/engine/tests/it/user_smart_mask.rs index 72916dcb..b51d7dd1 100644 --- a/crates/engine/tests/it/user_smart_mask.rs +++ b/crates/engine/tests/it/user_smart_mask.rs @@ -202,6 +202,7 @@ fn an_external_anchor_cannot_be_saved_or_rebound_in_another_project() { } assert!(s.smart_mask_bytes(source, "Preset").unwrap_err().to_string().contains("outside this mask")); + let bytes = texturecraft_engine::formats::save_project_bytes(&file).unwrap(); let before = s.doc.project.clone(); let history = s.history_labels(); diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index bf68e50b..cdb17b2e 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -610,7 +610,9 @@ mod tests { #[test] fn uv_density_is_mesh_units_per_uv_unit() { assert_eq!(quad().uv_density(0), Some(1.0)); + let plane = crate::primitives::plane(3.0, 4).uv_density(0).unwrap(); + assert!((plane - 3.0).abs() < 1e-4, "{plane}"); assert_eq!(quad().uv_density(1), None, "no triangles of that material"); } diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index 2cb62488..c7039666 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -496,6 +496,7 @@ mod tests { (None, Some(lib)) => lib.sample(shape.level, x, y), (None, None) => shape.alpha.sample(x, y, 0.4, 7), }; + assert_eq!(shape.sample(x, y, 0.4, 7).to_bits(), before.to_bits(), "{:?} at ({x}, {y})", shape.alpha); } } diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 39ab2e2b..43843f69 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -762,7 +762,7 @@ fn warmth(img: &Img) -> f32 { fn imported_hdr_environment_lights_the_ball() { let Some((mut h, frame)) = setup() else { return }; let base = render(&mut h, &frame, "env_default"); - // A procedural HDR: a hot orange sky over a dim blue ground (values far above 1). + // A procedural HDR: a hot orange sky over a dim blue ground (values far above 1) let (w, hh) = (256u32, 128u32); let rgba = (0..w * hh).map(|i| if i / w < hh / 2 { [12.0, 4.0, 1.0, 1.0] } else { [0.02, 0.05, 0.2, 1.0] }).collect(); let sky = ImageRes::new(w, hh, rgba, false); @@ -771,7 +771,9 @@ fn imported_hdr_environment_lights_the_ball() { assert_ne!(lit.px, base.px, "the imported environment changes the lighting"); assert!(warmth(&lit) > warmth(&base) + 10.0, "the orange sky tints the ball"); assert!(lit.mean(200, 100, 280, 180) > 20.0, "lit, finite shading (NaNs would render black)"); + h.renderer.set_environment(&h.device, &h.queue, "Studio Soft", None); + assert_eq!(render(&mut h, &frame, "env_default_again").px, base.px, "built-ins come back"); } diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 27d8e91c..dd2a06d3 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -519,7 +519,7 @@ fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize, effect_group(app, ui, &layer, depth, true, false); } - // A line under the layer and its effects separates it from the next layer. + // A line under the layer and its effects separates it from the next layer let tokens = Tokens::get(ui.ctx()); let available = ui.available_rect_before_wrap(); ui.painter().hline(available.x_range(), available.top() - 0.5, Stroke::new(1.0, tokens.separator)); @@ -567,7 +567,6 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize // One of several selected layers (Shift/Ctrl+click) is highlighted like the active one let highlighted = selected || app.session.is_layer_selected(layer.id); - let several = selection_with(app, layer.id); let content_target = selected && targets_content(app); let preferred_size = layer_preview_size(app); let row_height = layer_row_height(preferred_size); @@ -849,8 +848,10 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let shelf = row.dnd_hover_payload::().map(|drag| drag.asset.clone()); // Several selected layers move together, so none of them is a place to drop them - let in_drag = |dragged: u64| dragged == layer.id.0 || several.as_ref().is_some_and(|layers| layers.contains(&dragged)); - let moving = row.dnd_hover_payload::().is_some_and(|dragged| !in_drag(*dragged)); + let in_drag = |app: &TextureCraftApp, dragged: u64| { + dragged == layer.id.0 || (app.session.is_layer_selected(layer.id) && app.session.is_layer_selected(LayerId(dragged))) + }; + let moving = row.dnd_hover_payload::().is_some_and(|dragged| !in_drag(app, *dragged)); let drop_stroke = Stroke::new(DROP_LINE_WIDTH, tokens.accent); let shelf_material = shelf.as_ref().is_some_and(Asset::is_material); if moving || shelf_material { @@ -867,7 +868,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); } if let Some(dragged) = dnd_release::(&row) - && !in_drag(*dragged) + && !in_drag(app, *dragged) { match selection_with(app, LayerId(*dragged)) { Some(layers) => app.run("layer.move", json!({"layers": layers, "above": layer.id.0, "inside": inside})), @@ -1812,6 +1813,7 @@ mod image_menu_tests { harness.run_steps(30); assert!(preview_stats(&harness.ctx).0 > initial_previews, "scrolling creates newly visible previews"); + harness.get_by_label(&last_name).click(); harness.run_steps(2); diff --git a/crates/ui-egui/src/fill_panel.rs b/crates/ui-egui/src/fill_panel.rs index 746c63e4..88aef1be 100644 --- a/crates/ui-egui/src/fill_panel.rs +++ b/crates/ui-egui/src/fill_panel.rs @@ -355,7 +355,7 @@ fn placement_rows( None => PreviewLower::Offset { values: &mut lower_offset, range: OFFSET_TRACK, typed: OFFSET_TYPED }, }; let placement = Placement { tiling, rotation, offset }; - let bounds = app.session.mesh.bounds(); + let bounds = app.viewport_mesh_bounds.get(&app.session.mesh); // A warp shows its frame's size and turn as its gizmo leaves them let warp = match &fill.projection { @@ -423,7 +423,7 @@ fn world_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &F let edited = |fields: &[NumberField]| -> Vec { fields.iter().map(|field| field.value).collect() }; // A placed planar or a warp: the frame, its projector folded in - if let Some(shown) = frame_placement::placement(&fill.projection, app.session.mesh.bounds()) { + if let Some(shown) = frame_placement::placement(&fill.projection, app.viewport_mesh_bounds.get(&app.session.mesh)) { let run = |app: &mut TextureCraftApp, key: &str, values: Vec, merge: bool| { app.run("layer.decal.set", with(base, json!({key: values, "merge": merge}))); }; diff --git a/crates/ui-egui/src/fill_pictures.rs b/crates/ui-egui/src/fill_pictures.rs index 25c48d60..5a9fa0d7 100644 --- a/crates/ui-egui/src/fill_pictures.rs +++ b/crates/ui-egui/src/fill_pictures.rs @@ -386,6 +386,7 @@ mod tests { let placement = |offset: [f32; 2]| Placement { tiling: [2.0, 2.0], rotation: 30.0, offset }; let (still, rest) = slid_window(placement([0.0, 0.0])); assert_eq!(rest, [0.5, 0.5], "at Offset 0 the dot sits in the ring"); + let slid = placement([-0.25, 0.0]); let (columns, dot) = slid_window(slid); assert_eq!(columns, still, "the view never zooms or turns for the Offset"); diff --git a/crates/ui-egui/src/fill_symmetry_panel.rs b/crates/ui-egui/src/fill_symmetry_panel.rs index 0a95f428..20e18818 100644 --- a/crates/ui-egui/src/fill_symmetry_panel.rs +++ b/crates/ui-egui/src/fill_symmetry_panel.rs @@ -30,11 +30,13 @@ const SPAN_SLIDER: usize = 1; pub(crate) fn symmetry_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, projection: &Projection, sampling: Sampling, base: &Value) { let symmetry = sampling.symmetry; let run = |app: &mut TextureCraftApp, fields: Value| run_projection(app, base, fields); + if !projection.takes_symmetry() { let reason = match projection { Projection::UvTile => tr("Not available with Fill (Match per UV Tile)"), _ => tr("Not available with UV projection"), }; + sheet.section_unavailable(tr("Symmetry"), reason); return; } @@ -51,10 +53,12 @@ pub(crate) fn symmetry_section(app: &mut TextureCraftApp, sheet: &mut PropertySh if let Some(kind) = picked { run(app, json!({"symmetryType": kind.id()})); } + let axis = symmetry.axis_index(); if let Some(picked) = sheet.switch_tinted(tr("Axis"), &AXIS_NAMES, axis, &AXIS_COLORS) { run(app, json!({"symmetryAxis": picked})); } + if symmetry.kind == SymmetryKind::Radial { radial_rows(app, sheet, &symmetry, base); } @@ -86,10 +90,12 @@ fn radial_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, symmetr let picture = |painter: &Painter, rect: Rect| ring_picture(painter, rect, symmetry, axis_color, &tokens); let count = symmetry.copies(); let (mut count_value, mut span_value) = (count as f32, symmetry.span); + let mut sliders = [ StackSlider { label: tr("Count"), value: &mut count_value, range: COUNT_TRACK, typed: COUNT_TYPED, decimals: 0, suffix: "" }, StackSlider { label: tr("Angle span"), value: &mut span_value, range: FillSymmetry::SPANS, typed: FillSymmetry::SPANS, decimals: 0, suffix: "°" }, ]; + let edited = sheet.picture_sliders(&picture, &mut sliders); if let Some((SPAN_SLIDER, merge)) = edited { run_projection(app, base, json!({"angleSpan": span_value, "merge": merge})); diff --git a/crates/ui-egui/src/frame_gizmo.rs b/crates/ui-egui/src/frame_gizmo.rs index 6b27767b..2671f4b2 100644 --- a/crates/ui-egui/src/frame_gizmo.rs +++ b/crates/ui-egui/src/frame_gizmo.rs @@ -101,7 +101,8 @@ impl FrameGizmo { if unplaced && placing_moves_pattern(sources.into_iter()) { return None; } - let placed = placed_from_axis(projection, app.session.mesh.bounds()); + + let placed = placed_from_axis(projection, app.viewport_mesh_bounds.get(&app.session.mesh)); // Where the projection lands: a projector's own turn and scale moved into the frame, as the panel's 3D projection settings show it let landed = folded(placed.as_ref().unwrap_or(projection))?; @@ -290,7 +291,7 @@ impl Gizmo for FrameGizmo { json!({"size": size}) } FrameGrab::Turn => { - // The sweep round the centre on the frame's own plane (across turning towards up is a positive turn), so a tilted or off-centre frame follows the pointer too + // Measure the turn in the frame's own plane so a tilted frame follows the pointer let angle = |p: Pos2| self.on_plane(app, rect, p).map(|[across, up]| (up * self.decal.size[1]).atan2(across * self.decal.size[0]).to_degrees()); let swept = angle(to)? - angle(from)?; let swept = (swept + HALF_TURN).rem_euclid(2.0 * HALF_TURN) - HALF_TURN; @@ -537,6 +538,7 @@ pub(crate) mod tests { assert!(slid.offset[0] > 0.0 && slid.offset[1].abs() < slid.offset[0] * 0.2, "the centre square slides it right: {slid:?}"); assert_eq!(slid.size, axis.decal.size, "sliding keeps its size"); assert_eq!(harness.state().session.history_labels().last().map(String::as_str), Some("Edit decal")); + let steps = harness.state().session.history_labels().len(); let placed = gizmo(&harness); @@ -557,6 +559,7 @@ pub(crate) mod tests { let (mut harness, layer) = fill_app("warp"); let warp = gizmo(&harness); assert_eq!(warp.warp, Some(Projection::FRAME_CORNERS)); + let to = warp.corners[1] + vec2(-40.0, 30.0); drag(&mut harness, warp.corners[1], to, Modifiers::NONE); let Projection::Warp { corners, frame, .. } = projection(&harness, layer) else { panic!("still a warp") }; @@ -646,6 +649,7 @@ pub(crate) mod tests { let (mut harness, layer) = fill_app("warp"); let warp = gizmo(&harness); assert_eq!(warp.grab(warp.sides[1]), Some(FrameGrab::Side(1))); + drag(&mut harness, warp.sides[1], warp.center + (warp.sides[1] - warp.center) * 0.5, Modifiers::NONE); let Projection::Warp { frame, corners, .. } = projection(&harness, layer) else { panic!("still a warp") }; assert!(frame.size[0] < warp.decal.size[0] * 0.75 && (frame.size[1] - warp.decal.size[1]).abs() < 1e-4, "the right edge dot narrows it: {frame:?}"); @@ -661,6 +665,7 @@ pub(crate) mod tests { let center = gizmo(&harness).center; let to = center + vec2(40.0, 0.0); press_and_move(&mut harness, center, to, Modifiers::NONE); + assert!(frame_dragging(&harness), "the centre square is held"); harness.event(egui::Event::WindowFocused(false)); @@ -673,9 +678,12 @@ pub(crate) mod tests { harness.event(egui::Event::PointerMoved(to + vec2(20.0, 10.0) * step as f32)); harness.run_steps(1); } + assert_eq!(projection(&harness, layer), left, "moves after it leave the frame where it was"); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); harness.run_steps(2); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "and add no step"); } @@ -693,6 +701,7 @@ pub(crate) mod tests { harness.event_modifiers(egui::Event::PointerMoved(to + vec2(20.0, 0.0)), Modifiers::ALT); harness.run_steps(1); + assert_ne!(harness.state().session.camera, camera, "Alt turns the camera"); assert!(!frame_dragging(&harness), "and ends the frame drag"); @@ -700,9 +709,12 @@ pub(crate) mod tests { harness.event(egui::Event::PointerMoved(to + vec2(20.0, 5.0) * step as f32)); harness.run_steps(1); } + assert_eq!(projection(&harness, layer), slid, "Alt let go, the frame stays where the drag left it"); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); harness.run_steps(2); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step"); } @@ -722,7 +734,7 @@ pub(crate) mod tests { let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let (mut harness, layer) = fill_app("warp"); - // The frame waits at its left limit, a mesh diagonal off the ball's centre, clear of the panels on the right; the camera backs off so it shows with its arrows + // Offset the frame from the panels and back the camera up to expose its arrows harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "offset": [-100.0, 0.0]})).unwrap(); harness.state_mut().session.camera.distance *= 3.0; harness.run_steps(2); @@ -735,12 +747,14 @@ pub(crate) mod tests { press_and_move(&mut harness, tip, tip - inward * 25.0, Modifiers::NONE); assert_eq!(projection(&harness, layer), at_limit, "past the limit the frame stays where it is"); + move_and_let_go(&mut harness, tip - inward * 25.0, tip + inward * 25.0); assert_ne!(projection(&harness, layer), at_limit, "back inside the frame moves"); assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the drag made its own undo step"); harness.state_mut().session.undo().unwrap(); + assert_eq!(projection(&harness, layer), at_limit, "undo takes back the drag only"); } @@ -752,6 +766,7 @@ pub(crate) mod tests { harness.state_mut().run("layer.fill.set", json!({"layer": layer.0, "channel": "roughness", "procedural": "Checker"})).unwrap(); harness.run_steps(2); + assert!(FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "placing would move the pattern"); } @@ -769,11 +784,15 @@ pub(crate) mod tests { press_and_move(&mut harness, center, center + vec2(0.0, 30.0), Modifiers::NONE); harness.key_press_modifiers(Modifiers::COMMAND, egui::Key::Z); harness.run_steps(1); + assert_eq!(projection(&harness, layer), first, "Ctrl+Z undid the drag so far"); + move_and_let_go(&mut harness, center + vec2(0.0, 30.0), center + vec2(0.0, 40.0)); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the drag's later edits made a step of their own"); harness.state_mut().session.undo().unwrap(); + assert_eq!(projection(&harness, layer), first, "undo goes back to where the first drag left the frame"); } @@ -797,21 +816,28 @@ pub(crate) mod tests { assert!(eye.left() > projection_row.right() && (eye.center().y - projection_row.center().y).abs() < 0.5, "the eye ends the Projection row"); click(&mut harness, eye.center()); + assert!(!harness.state().session.doc.project.display.projection_gizmos, "the eye hides the gizmos"); assert!(FrameGizmo::shown(harness.state(), harness.state().viewport_rect).is_none(), "the 3D view has no frame to draw or grab"); + let before = projection(&harness, layer); drag(&mut harness, shown.center, shown.center + vec2(30.0, 0.0), Modifiers::NONE); + assert_eq!(projection(&harness, layer), before, "a drag where the centre square was moves nothing"); let eye = harness.get_by_label("Show projection gizmos").rect(); click(&mut harness, eye.center()); + assert!(harness.state().session.doc.project.display.projection_gizmos, "the eye shows them again"); + drag(&mut harness, shown.center, shown.center + vec2(30.0, 0.0), Modifiers::NONE); + assert_ne!(projection(&harness, layer), before, "shown, the centre square slides it again"); // A UV projection has no gizmo: its row keeps the whole width for the dropdown harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "projection": "uv"})).unwrap(); harness.run_steps(2); + assert!(harness.query_by_label("Hide projection gizmos").is_none(), "no eye without a gizmo"); } @@ -957,6 +983,7 @@ pub(crate) mod tests { let side = gizmo(&harness); drag_frames(&mut harness, layer, side.sides[0], side.center + (side.sides[0] - side.center) * 0.5, Modifiers::NONE, true, check(layer)); let narrowed = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + assert!(narrowed.scale[1] < slid.scale[1] * 0.75 && (narrowed.scale[0] - slid.scale[0]).abs() < 1e-4, "{slid:?} -> {narrowed:?}"); // The view steps back so a corner shows beside the panels @@ -967,6 +994,7 @@ pub(crate) mod tests { let inside = *corner.corners.iter().find(|at| view.contains(**at)).expect("a corner in the view"); drag_frames(&mut harness, layer, inside, corner.center + (inside - corner.center) * 0.6, Modifiers::NONE, true, check(layer)); let scaled = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + assert!(scaled.scale[1] < narrowed.scale[1] * 0.8 && scaled.scale[0] < narrowed.scale[0] * 0.8, "a corner scales it: {scaled:?}"); // Move on model held with Shift turns the frame round its normal @@ -974,6 +1002,7 @@ pub(crate) mod tests { let button = harness.get_by_label("Move on model").rect().center(); drag_frames(&mut harness, layer, button, button + vec2(-60.0, 0.0), Modifiers::SHIFT, true, check(layer)); let turned = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + assert!((turned.rotation[2] - before.rotation[2]).abs() > 10.0, "turned: {before:?} -> {turned:?}"); assert_eq!(harness.state().session.history_labels().len(), steps + 4, "one undo step per drag"); diff --git a/crates/ui-egui/src/gray_slider.rs b/crates/ui-egui/src/gray_slider.rs index eac04af1..1dd5ae91 100644 --- a/crates/ui-egui/src/gray_slider.rs +++ b/crates/ui-egui/src/gray_slider.rs @@ -19,6 +19,7 @@ const MIN_BAR_WIDTH: f32 = KNOB_RADIUS * 4.0; pub(crate) fn gray_slider(ui: &mut Ui, label: &str, value: &mut f32) -> Option { let tokens = Tokens::get(ui.ctx()); let (field, typed) = value_header(ui, label, value, 0.0..=1.0, 2); + ui.horizontal(|ui| { let mut edit = typed; @@ -28,6 +29,7 @@ pub(crate) fn gray_slider(ui: &mut Ui, label: &str, value: &mut f32) -> Option(field)); @@ -54,6 +56,7 @@ pub(crate) fn gray_slider(ui: &mut Ui, label: &str, value: &mut f32) -> Option, /// Yaw and pitch an Alt+Shift drag has reached before snapping to 90° steps (see `viewport`). @@ -337,6 +339,7 @@ impl TextureCraftApp { uv_rotation_snap: None, uv_view_reset: false, session, + viewport_mesh_bounds: viewport_mesh_bounds::ViewportMeshBounds::default(), ui, ui_store, gpu, diff --git a/crates/ui-egui/src/move_on_model.rs b/crates/ui-egui/src/move_on_model.rs index 0871d95e..37a15b5c 100644 --- a/crates/ui-egui/src/move_on_model.rs +++ b/crates/ui-egui/src/move_on_model.rs @@ -323,17 +323,21 @@ mod tests { let mut pointer = press_the_button(&mut harness); let from = pointer.at; assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "a press starts the hold"); + let moved = vec2(-300.0, -20.0); pointer.drags(&mut harness, moved, 30, Modifiers::NONE); let after = RoundGizmo::of(harness.state(), rect).unwrap(); + assert!((after.center - (before.center + moved)).length() < 2.0, "the projector follows the mouse: {:?} -> {:?}", before.center, after.center); assert!(pointer.hidden, "the pointer hides while held"); assert!(pointer.at.distance(from) < 1.0, "and stays on the pad, so no screen edge stops the drag: {:?}", pointer.at); + let slid = projection(&harness, layer); assert_ne!(projector_offset(&slid), [0.0; 3], "the projector itself moved: {slid:?}"); assert_eq!(uv_of(&slid), UvTransform::default(), "not only the image inside it"); let_go(&mut harness, &mut pointer); + assert_eq!(harness.state().moving_on_model, None, "letting go ends it"); assert!(!pointer.hidden && pointer.at == from, "the pointer shows again where the press began: {:?}", pointer.at); assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step per hold"); @@ -342,6 +346,7 @@ mod tests { // The 3D view has its drags back: a drag on the model off the projector's handles moves nothing let off = on_the_model_off_the_handles(&harness); drag(&mut harness, off, off + vec2(60.0, 0.0), Modifiers::NONE); + assert_eq!(projection(&harness, layer), slid, "no mode is left on"); } @@ -353,6 +358,7 @@ mod tests { let steps = harness.state().session.history_labels().len(); let mut pointer = press_the_button(&mut harness); pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE); + assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "the hold is under way"); harness.input_mut().events.push(egui::Event::WindowFocused(false)); @@ -363,6 +369,7 @@ mod tests { assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step, as letting go makes"); pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE); + assert_eq!(harness.state().moving_on_model, None, "the button still down in egui starts no new hold"); assert_eq!(projection(&harness, layer), left, "moves after it leave the projection alone"); } @@ -377,10 +384,12 @@ mod tests { harness.run_steps(2); let mut pointer = press_the_button(&mut harness); pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE); + assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "{layout:?}: the hold is under way"); harness.state_mut().run("layer.remove", json!({"layer": layer.0})).unwrap(); pointer.frame(&mut harness); + assert_eq!(harness.state().moving_on_model, None, "{layout:?}: the hold ended with its fill"); assert!(!pointer.hidden, "{layout:?}: the pointer shows again"); } @@ -393,13 +402,19 @@ mod tests { let (mut harness, layer) = fill_app("triplanar"); let pad = harness.get_by_label("Move on model").rect(); assert!((pad.width() - pad.height()).abs() < 1.0 && pad.width() > 60.0, "Move on model is the preview square, no row of its own: {pad:?}"); + let before = projection(&harness, layer); let mut pointer = SystemPointer::at(&mut harness, pad.left_top() + vec2(4.0, 4.0)); pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); + assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "a press at its corner starts the hold"); + pointer.drags(&mut harness, vec2(40.0, 0.0), 10, Modifiers::NONE); + assert!(pointer.hidden, "the pointer is held"); + let_go(&mut harness, &mut pointer); + assert_ne!(projection(&harness, layer), before, "the drag moved the projection"); assert_eq!(harness.state().moving_on_model, None); } @@ -428,6 +443,7 @@ mod tests { let turned = projection(&harness, layer); assert!(uv_of(&turned).rotation < shifted.rotation, "the right button turns it: {shifted:?} -> {turned:?}"); assert_eq!(projector_offset(&turned), projector_offset(&slid), "without sliding"); + pointer.button(&mut harness, PointerButton::Secondary, false, Modifiers::NONE); wheel(&mut harness, &mut pointer); @@ -437,10 +453,13 @@ mod tests { assert!(harness.state().properties_popup.is_none(), "the right click opened no Properties popup"); let_go(&mut harness, &mut pointer); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the whole hold is one undo step"); + let back = pointer.at; pointer.moves(&mut harness, over_view - back, Modifiers::NONE); wheel(&mut harness, &mut pointer); + assert_ne!(harness.state().session.camera, camera, "let go, the wheel zooms the camera"); assert_eq!(uv_of(&projection(&harness, layer)), scaled, "and leaves the projection alone"); } @@ -457,13 +476,17 @@ mod tests { let mut pointer = press_the_button(&mut harness); pointer.drags(&mut harness, vec2(0.0, -40.0), 10, Modifiers::SHIFT); + assert_eq!(projection(&harness, layer), turned, "an up and down turn changes nothing"); + pointer.drags(&mut harness, vec2(0.0, -40.0), 10, Modifiers::NONE); let_go(&mut harness, &mut pointer); + assert_ne!(projection(&harness, layer), turned, "the slide moved the frame"); assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the hold made its own undo step"); harness.state_mut().session.undo().unwrap(); + assert_eq!(projection(&harness, layer), turned, "undo takes back the hold only"); } @@ -476,9 +499,11 @@ mod tests { let mut pointer = press_the_button(&mut harness); let from = pointer.at; wheel(&mut harness, &mut pointer); + assert_eq!(harness.get_by_label("Move on model").rect().center(), from, "a wheel step over the panel while held scales, it does not scroll the panel"); let Projection::Uv { scale, .. } = projection(&harness, layer) else { panic!("still UV") }; assert!(scale[0] < 1.0, "the wheel up makes the image bigger: {scale:?}"); + let far = vec2(-3.0 * from.x, 0.0); pointer.drags(&mut harness, far, 60, Modifiers::NONE); let_go(&mut harness, &mut pointer); diff --git a/crates/ui-egui/src/pointer_lock/tests.rs b/crates/ui-egui/src/pointer_lock/tests.rs index bbce1297..7b85654e 100644 --- a/crates/ui-egui/src/pointer_lock/tests.rs +++ b/crates/ui-egui/src/pointer_lock/tests.rs @@ -44,11 +44,14 @@ fn a_put_back_pointer_never_reaches_the_edge_and_comes_back_where_the_press_bega pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); pointer.frame(&mut harness); + assert!(!pointer.hidden, "let go, the pointer shows again"); assert_eq!(pointer.at, PRESS, "where the press began"); assert_eq!(harness.ctx.input(|input| input.pointer.latest_pos()), Some(PRESS), "egui sees it there too"); + let moved = *harness.state(); pointer.moves(&mut harness, vec2(30.0, 0.0), Modifiers::NONE); + assert_eq!(pointer.at, PRESS + vec2(30.0, 0.0), "a free pointer moves again"); assert_eq!(*harness.state(), moved, "and drags nothing"); } @@ -61,11 +64,13 @@ fn a_folded_put_back_counts_every_move_from_the_press() { pointer.folds = true; pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); pointer.drags(&mut harness, vec2(1500.0, -40.0), 30, Modifiers::NONE); + assert!(pointer.hidden && pointer.put_backs >= 30, "hidden, and put back after every move: {pointer:?}"); assert!((*harness.state() - vec2(1500.0, -40.0)).length() < 0.01, "every move counts: {:?}", harness.state()); pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); pointer.frame(&mut harness); + assert!(!pointer.hidden && pointer.at == PRESS, "let go, it shows again where the press began: {pointer:?}"); } @@ -78,6 +83,7 @@ fn a_locked_pointer_reads_raw_motion_and_is_let_go_where_the_press_began() { pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); pointer.frame(&mut harness); + assert!(!pointer.locked && !pointer.hidden, "let go, the pointer is free and shows"); assert_eq!(harness.ctx.input(|input| input.pointer.latest_pos()), Some(PRESS), "egui sees it where the press began"); } @@ -88,6 +94,7 @@ fn a_browser_pointer_is_not_held() { let mut pointer = SystemPointer::at(&mut harness, PRESS); pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); pointer.drags(&mut harness, vec2(100.0, 0.0), 10, Modifiers::NONE); + assert!(!pointer.hidden && pointer.put_backs == 0, "the pointer moves and shows"); assert_eq!(*harness.state(), vec2(100.0, 0.0), "the drag reads it as it moves"); } @@ -103,9 +110,12 @@ fn a_number_field_scrubs_past_the_edge_with_the_pointer_held() { pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); let window = harness.ctx.content_rect().width(); pointer.drags(&mut harness, vec2(2.0 * window, 0.0), 40, Modifiers::NONE); + assert!(pointer.hidden && pointer.at.distance(press) < 1.0, "the pointer is hidden and kept on the field: {pointer:?}"); + pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); pointer.frame(&mut harness); + assert!(!pointer.hidden && pointer.at == press, "let go, it shows again on the field: {pointer:?}"); let texturecraft_engine::core::Projection::Triplanar { offset, .. } = crate::frame_gizmo::tests::projection(&harness, layer) else { diff --git a/crates/ui-egui/src/preview_dots.rs b/crates/ui-egui/src/preview_dots.rs index 09af91a8..d4220c73 100644 --- a/crates/ui-egui/src/preview_dots.rs +++ b/crates/ui-egui/src/preview_dots.rs @@ -37,6 +37,7 @@ pub(crate) fn preview_dots(painter: &Painter, center: Pos2, position: Pos2, toke let length = span.length(); let start = DOT_RADIUS + LINE_SPACING; let end = length - RING_RADIUS - LINE_SPACING / 2.0; + if length.is_finite() && end > start { let toward = span / length; let count = (((end - start) / LINE_SPACING).floor() as usize).min(MAX_LINE_DOTS); @@ -46,6 +47,7 @@ pub(crate) fn preview_dots(painter: &Painter, center: Pos2, position: Pos2, toke painter.circle_filled(at, LINE_DOT, tokens.text); } } + painter.circle_stroke(center, RING_RADIUS, Stroke::new(RING_UNDER, tokens.field)); painter.circle_stroke(center, RING_RADIUS, Stroke::new(RING_LINE, tokens.text)); painter.circle_filled(position, DOT_RADIUS + DOT_RIM, tokens.field); diff --git a/crates/ui-egui/src/projection_gizmo.rs b/crates/ui-egui/src/projection_gizmo.rs index 06b1c199..edc56a76 100644 --- a/crates/ui-egui/src/projection_gizmo.rs +++ b/crates/ui-egui/src/projection_gizmo.rs @@ -4,6 +4,8 @@ mod gizmo; mod gizmo_drag; mod shown_gizmo; +use std::sync::Arc; + use egui::{PointerButton, Rect}; use serde_json::{Value, json}; use texturecraft_engine::Session; @@ -32,10 +34,10 @@ pub(crate) fn input(app: &mut TextureCraftApp, ctx: &egui::Context, re && let (Some(gizmo), Some(from)) = (gizmo, ctx.input(|input| input.pointer.press_origin())) && let Some(grab) = gizmo.grab(from) { - drag = Some(GizmoDrag { grab, from, start: gizmo.clone(), edited_revision: None }); + drag = Some(GizmoDrag { grab, from, start: Arc::new(gizmo.clone()), edited_revision: None }); } - // A window that lost the focus gets no release: the drag ends there. A release still applies a move that came in the same frame + // Apply a final move on release and let focus loss end a drag without one let released = response.drag_stopped_by(PointerButton::Primary); let pressed = response.dragged_by(PointerButton::Primary) || response.drag_started_by(PointerButton::Primary) || released; let Some(mut drag) = drag.filter(|_| pressed && !focus_lost(ctx)) else { diff --git a/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs b/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs index bf8221b5..184009c1 100644 --- a/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs +++ b/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs @@ -1,3 +1,5 @@ +use std::sync::Arc; + use egui::Pos2; use super::Gizmo; @@ -6,9 +8,10 @@ use super::Gizmo; #[derive(Clone, Debug)] pub(crate) struct GizmoDrag { pub(crate) grab: G::Grab, - /// Where the drag started and the gizmo then + /// Where the drag started pub(crate) from: Pos2, - pub(crate) start: G, + /// The starting gizmo shared by the pointer, edit and overlay paths + pub(crate) start: Arc, /// The session revision the drag's last edit left: later updates merge into its undo step while the history is still there pub(crate) edited_revision: Option, } diff --git a/crates/ui-egui/src/projection_preview.rs b/crates/ui-egui/src/projection_preview.rs index 903a01a9..37992c63 100644 --- a/crates/ui-egui/src/projection_preview.rs +++ b/crates/ui-egui/src/projection_preview.rs @@ -12,7 +12,7 @@ use texturecraft_engine::compose::frame_placement::{folded, upright_turn}; use texturecraft_engine::compose::pattern::{Coords, decal_axes, image_samples}; use texturecraft_engine::compose::projector_cover::projector_cover; use texturecraft_engine::core::{Projection, Projector, ShapeCrop}; -use texturecraft_engine::geom::glam::{Vec2, Vec3}; +use texturecraft_engine::geom::glam::{Vec2, Vec3, Vec4}; use rayon::prelude::*; @@ -134,6 +134,9 @@ const UNCOVERED: f32 = 0.45; /// How much of the projection reaches a ray past which it counts as covered, for the edge of its reach const HALF_COVERED: f32 = 0.5; +/// A missed ray has no coverage value in the 0..1 range +const MISSED_RAY_COVERAGE: f32 = -1.0; + /// How far a ray on the edge of the projection's reach is drawn from the accent towards the shape's colour const EDGE_BLEND: f32 = 0.5; @@ -378,18 +381,18 @@ fn render(projection: &Projection, side: usize, half: f32, supersample: usize, t let supersample = supersample.max(1); let rays = side * supersample; - // Per ray: the lit colour and how much of the projection lands there (None = the background) - let samples: Vec> = (0..rays * rays) + // Pack lit RGB and coverage into one vector per ray + let samples: Vec = (0..rays * rays) .into_par_iter() .map(|ray| { let (x, y) = (ray % rays, ray / rays); let across = ((x as f32 + 0.5) / rays as f32 * 2.0 - 1.0) * half; let down = ((y as f32 + 0.5) / rays as f32 * 2.0 - 1.0) * half; let origin = right * across - up * down + eye * CAMERA_DISTANCE; - let hit = intersect(shape, origin, forward)?; + let Some(hit) = intersect(shape, origin, forward) else { return Vec4::new(0.0, 0.0, 0.0, MISSED_RAY_COVERAGE) }; let shade = AMBIENT + (1.0 - AMBIENT) * hit.nrm.dot(light).max(0.0); let (color, cover) = surface(projection, &hit, shades); - Some((color * shade, cover)) + (color * shade).extend(cover) }) .collect(); @@ -400,10 +403,13 @@ fn render(projection: &Projection, side: usize, half: f32, supersample: usize, t let mut sum = Vec3::ZERO; for sub in 0..supersample * supersample { let (rx, ry) = (x * supersample + sub % supersample, y * supersample + sub / supersample); - let color = match samples.get(ry * rays + rx).copied().flatten() { - Some((color, cover)) if on_edge(&samples, rays, rx, ry, cover) => edge.lerp(color, EDGE_BLEND), - Some((color, _)) => color, - None => background, + let sample = samples[ry * rays + rx]; + let color = if sample.w == MISSED_RAY_COVERAGE { + background + } else if on_edge(&samples, rays, rx, ry, sample.w) { + edge.lerp(sample.truncate(), EDGE_BLEND) + } else { + sample.truncate() }; sum += color; } @@ -413,7 +419,7 @@ fn render(projection: &Projection, side: usize, half: f32, supersample: usize, t } /// Where the projection's reach ends on the shape: covered here, not on a neighbouring ray of the shape -fn on_edge(samples: &[Option<(Vec3, f32)>], rays: usize, x: usize, y: usize, cover: f32) -> bool { +fn on_edge(samples: &[Vec4], rays: usize, x: usize, y: usize, cover: f32) -> bool { if cover <= HALF_COVERED { return false; } @@ -421,7 +427,7 @@ fn on_edge(samples: &[Option<(Vec3, f32)>], rays: usize, x: usize, y: usize, cov let neighbours = [(x.wrapping_sub(1), y), (x + 1, y), (x, y.wrapping_sub(1)), (x, y + 1)]; neighbours .into_iter() - .any(|(nx, ny)| nx < rays && ny < rays && samples.get(ny * rays + nx).copied().flatten().is_some_and(|(_, cover)| cover <= HALF_COVERED)) + .any(|(nx, ny)| nx < rays && ny < rays && samples.get(ny * rays + nx).is_some_and(|sample| sample.w != MISSED_RAY_COVERAGE && sample.w <= HALF_COVERED)) } /// The unlit colour at a hit and how much of the projection reaches it, from the dark and light checker and the uncovered shape `shades` in linear light @@ -651,6 +657,7 @@ mod tests { #[test] fn the_view_fits_the_projector_down_to_half_the_shape() { assert_eq!(fitted_half(&sized(0.4)), VIEW_HALF, "a small projector keeps the plain framing"); + let default = fitted_half(&sized(1.0)); assert!(default > VIEW_HALF && default < MAX_VIEW_HALF, "{default}"); assert_eq!(fitted_half(&sized(3.0)), MAX_VIEW_HALF, "x3 stops at half the shape's size"); @@ -662,6 +669,7 @@ mod tests { let screen = Screen { view: View::new(), rect, half: fitted_half(&shown) }; passed_sides(outline.points().map(|point| screen.at(point)), rect) }; + assert_eq!(sides(1.0), [false; 4], "a fitted projector stays inside the square"); assert_eq!(sides(3.0), [true; 4], "an x3 sphere runs past every side"); @@ -683,10 +691,12 @@ mod tests { for offset in [[0.0, 0.0, 0.0], [0.3, 0.0, 0.0], [1.5, 0.8, 0.0]] { let slid = Projection::Spherical { scale, uv, offset, projector }; assert_eq!(fitted_half(&slid), fitted_half(&sized(1.0)), "Offset {offset:?} keeps the view"); + let (resting, half) = resting_fit(&slid, PreviewShape::Sphere); let screen = Screen { view: View::new(), rect, half }; let ring = screen.at(resting.unwrap().center); let dot = screen.at(ProjectorOutline::of(&slid, PreviewShape::Sphere.half_size()).unwrap().center); + assert!(ring.distance(rect.center()) < 1e-3, "the ring marks the middle: {ring:?}"); assert_eq!(dot.distance(ring) > 1.0, offset != [0.0; 3], "the filled dot leaves the ring only when slid: {dot:?}"); } @@ -709,6 +719,7 @@ mod tests { let outline = ProjectorOutline::of(&sized(1.0), PreviewShape::Sphere.half_size()).unwrap(); let hidden = |line: &Vec| line.iter().filter(|point| screen.hidden(PreviewShape::Sphere, **point)).count(); assert_eq!(hidden(&outline.lines[0]), 0, "the rim is all seen"); + let equator = hidden(&outline.lines[1]); assert!(equator > 0 && equator < outline.lines[1].len(), "the equator is half hidden: {equator}"); } @@ -788,15 +799,21 @@ mod tests { let at = pos2(10.0, 10.0); let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; preview_frame(&ctx, &spherical(1.0), Vec::new()); + assert_eq!(shown_supersample(&ctx), Some(SUPERSAMPLE), "at rest: in full"); preview_frame(&ctx, &spherical(1.0), vec![egui::Event::PointerMoved(at), button(true)]); + assert_eq!(shown_supersample(&ctx), Some(SUPERSAMPLE), "a press alone keeps the full picture: nothing changed"); + preview_frame(&ctx, &spherical(2.0), Vec::new()); + assert_eq!(shown_supersample(&ctx), Some(DRAG_SUPERSAMPLE), "a change while held renders lighter"); + let dragged = shown_key(&ctx); preview_frame(&ctx, &spherical(2.0), vec![button(false)]); + assert_eq!(shown_supersample(&ctx), Some(SUPERSAMPLE), "let go: the same picture in full"); assert_eq!(shown_key(&ctx), dragged); } diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs index 341fda86..4e4d2f34 100644 --- a/crates/ui-egui/src/properties_popup.rs +++ b/crates/ui-egui/src/properties_popup.rs @@ -39,6 +39,7 @@ pub(crate) fn open_on_right_click(app: &mut TextureCraftApp, ui: &Ui, response: && !gesture_key_held && !crate::viewport::focus_picking(ui.ctx()) && ui.input(|input| input.modifiers.is_none()); + if !free || !response.clicked_by(PointerButton::Secondary) { return; } @@ -71,8 +72,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { egui::Area::new(area_id()).order(egui::Order::Foreground).fixed_pos(at).constrain_to(bounds.shrink(PROPERTIES_POPUP_VIEW_MARGIN)).show(ctx, |ui| { egui::Frame::popup(ui.style()).fill(tokens.panel).inner_margin(egui::Margin::ZERO).show(ui, |ui| { ui.set_width(PROPERTIES_POPUP_WIDTH); + // The area's remembered size would otherwise cap the scroll height ui.set_max_height(bounds.height() * PROPERTIES_POPUP_MAX_HEIGHT_SHARE); + // A floating bar would cover the sliders' right-aligned values ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); diff --git a/crates/ui-egui/src/property_sheet/axis_rows.rs b/crates/ui-egui/src/property_sheet/axis_rows.rs index 13d65ee9..5eb2724c 100644 --- a/crates/ui-egui/src/property_sheet/axis_rows.rs +++ b/crates/ui-egui/src/property_sheet/axis_rows.rs @@ -46,6 +46,7 @@ impl PropertySheet<'_> { let response = self.ui.interact(Rect::from_center_size(center, CAPTION_SWITCH_HIT), id, Sense::click()); response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, on, title)); self.pill(center, on, true); + self.paint_control_focus(&response); response } diff --git a/crates/ui-egui/src/property_sheet/info_icon.rs b/crates/ui-egui/src/property_sheet/info_icon.rs index b18c0513..a8cbee52 100644 --- a/crates/ui-egui/src/property_sheet/info_icon.rs +++ b/crates/ui-egui/src/property_sheet/info_icon.rs @@ -50,6 +50,7 @@ impl<'u> PropertySheet<'u> { /// Paints the pending i at `glyph_x` in its slot from `slot_left` fn paint_info_in(&mut self, slot_left: f32, glyph_x: f32, center_y: f32) { let Some(tip) = self.info.take() else { return }; + let row_top = center_y - ROW_HEIGHT / 2.0; let slot = Rect::from_min_size(pos2(slot_left, row_top), vec2(INFO_SLOT, ROW_HEIGHT)); let id = self.next_id(); @@ -69,6 +70,7 @@ impl<'u> PropertySheet<'u> { .inner_margin(TIP_MARGIN) .shadow(TIP_SHADOW); let text_width = anchor.width() - TIP_MARGIN.sum().x; + let mut tooltip = egui::Tooltip::for_enabled(&response); tooltip.popup = tooltip .popup diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 1da4e0eb..e5c97ea2 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -25,6 +25,7 @@ mod switch_control; mod tooltip; mod track; mod value_text; +mod value_text_draft; #[cfg(test)] mod tests; @@ -44,6 +45,8 @@ use crate::theme::{Tokens, semibold}; use open_card::OpenCard; use sheet_measure::SheetMeasure; +type SheetMeasures = egui::cache::FramePublisher; + /// Side padding: every row starts and ends this far inside the panel pub(crate) const PAD: f32 = 12.0; @@ -124,7 +127,7 @@ impl<'u> PropertySheet<'u> { /// Lays out `body` as one panel; when its measured columns change, egui reruns the frame unseen pub(crate) fn show(ui: &'u mut Ui, id_salt: impl egui::AsIdSalt, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { let id = ui.make_persistent_id(id_salt); - let used = ui.data(|data| data.get_temp::(id)).unwrap_or_default(); + let used = ui.memory_mut(|memory| memory.caches.cache::().get(&id).copied()).unwrap_or_default(); ui.spacing_mut().item_spacing = vec2(0.0, 0.0); let rect = ui.available_rect_before_wrap(); let mut sheet = PropertySheet { @@ -153,11 +156,13 @@ impl<'u> PropertySheet<'u> { section_tabs::remember(sheet.ui, section_tabs::SectionTops { tops: std::mem::take(&mut sheet.sections), view_top }); } + // Refresh visible sheets so measurements of closed sheets expire let seen = sheet.seen; + sheet.ui.memory_mut(|memory| memory.caches.cache::().set(id, seen)); if seen != used { - sheet.ui.data_mut(|data| data.insert_temp(id, seen)); sheet.ui.ctx().request_discard("Properties columns changed"); } + result } diff --git a/crates/ui-egui/src/property_sheet/number_field.rs b/crates/ui-egui/src/property_sheet/number_field.rs index 22337ebb..f3f76bcc 100644 --- a/crates/ui-egui/src/property_sheet/number_field.rs +++ b/crates/ui-egui/src/property_sheet/number_field.rs @@ -92,7 +92,7 @@ impl PropertySheet<'_> { /// One field: its tag on the left, the value on the right; drag or click to type. Named "`label` `tag`" ("Scale X") fn number_field(&mut self, rect: Rect, label: &str, field: &mut NumberField) -> Option { let id = self.next_id(); - let typing_id = id.with("typed"); + let typing_id = id.with((self.id, "typed")); let tokens = self.tokens; let painter = self.ui.painter().clone(); painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), tokens.field, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); @@ -112,26 +112,27 @@ impl PropertySheet<'_> { } let decimals = field.decimals; - if let Some(mut text) = self.ui.data(|data| data.get_temp::(typing_id)) { - let edit = egui::TextEdit::singleline(&mut text).id(typing_id).font(semibold(TEXT_SIZE)).align(egui::Align2::RIGHT_CENTER); - let response = self.typing_edit(rect.left() + 2.0 * TAG_LETTER_INSET + TAG_TO_TYPING, rect.right() - VALUE_INSET, rect.center().y, edit); + if let Some(mut draft) = self.typing_draft(typing_id) { + let response = + self.typing_edit(rect.left() + 2.0 * TAG_LETTER_INSET + TAG_TO_TYPING, rect.right() - VALUE_INSET, rect.center().y, typing_id, &mut draft); painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(1.0, tokens.accent), StrokeKind::Inside); if !response.lost_focus() { - self.ui.data_mut(|data| data.insert_temp(typing_id, text)); + self.keep_typing(typing_id, draft); return None; } - let untouched = self.end_typing(typing_id, &text); + let untouched = self.end_typing(typing_id, &draft); + let text = draft.text.trim(); if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) { return None; } // Leaving the field as it opened changes nothing: no undo step, no rounding to the shown decimals, no overwriting a value changed meanwhile - if untouched || text.trim() == shown_number(field.value, decimals) { + if untouched || text == shown_number(field.value, decimals) { return None; } - let typed: f32 = text.trim().trim_end_matches(field.suffix).trim().parse().ok()?; + let typed: f32 = text.trim_end_matches(field.suffix).trim().parse().ok()?; if !typed.is_finite() || typed == field.value { return None; } diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index a377cfdd..9ce3760a 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -188,12 +188,12 @@ impl PropertySheet<'_> { pub(super) fn value_text_field(&mut self, id: Id, value_text: ValueText<'_>, value: f32, range: &RangeInclusive, decimals: usize) -> Option { let ValueText { label, right, width, center_y, shown, suffix } = value_text; let rect = Rect::from_min_max(pos2(right - width, center_y - ROW_HIT_HALF_HEIGHT), pos2(right, center_y + ROW_HIT_HALF_HEIGHT)); - let field_id = id.with("typed"); - let editing = self.ui.data(|data| data.get_temp::(field_id)); + let field_id = id.with((self.id, "typed")); + let editing = self.typing_draft(field_id); let seeded = || shown_number(value, decimals); let tokens = self.tokens; - let Some(mut typed_text) = editing else { + let Some(mut draft) = editing else { self.skip_typing_edit(); let response = self.ui.interact(rect, id.with("value"), Sense::click()).on_hover_cursor(egui::CursorIcon::Text); response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, true, crate::i18n::trf("{label} value", &[("label", label)]))); @@ -209,25 +209,25 @@ impl PropertySheet<'_> { }; // Typing happens on the value's own line: no box, the line under it goes accent - let edit = egui::TextEdit::singleline(&mut typed_text).id(field_id).font(semibold(TEXT_SIZE)).align(egui::Align2::RIGHT_CENTER); - let response = self.typing_edit(rect.left(), right, center_y, edit); + let response = self.typing_edit(rect.left(), right, center_y, field_id, &mut draft); self.value_line(rect.left(), right, center_y, tokens.accent); if !response.lost_focus() { - self.ui.data_mut(|data| data.insert_temp(field_id, typed_text)); + self.keep_typing(field_id, draft); return None; } - let untouched = self.end_typing(field_id, &typed_text); + let untouched = self.end_typing(field_id, &draft); + let typed_text = draft.text.trim(); if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) { return None; } // Leaving the field as it opened changes nothing: no undo step, no rounding to the shown decimals, no overwriting a value changed meanwhile - if untouched || typed_text.trim() == seeded() { + if untouched || typed_text == seeded() { return None; } - let typed: f32 = typed_text.trim().trim_end_matches(suffix).trim_start_matches(['×', 'x']).trim().parse().ok()?; + let typed: f32 = typed_text.trim_end_matches(suffix).trim_start_matches(['×', 'x']).trim().parse().ok()?; // A typed value that lands on the current one (a clamp, "0.750" for 0.75) is no edit either typed.is_finite().then(|| kept_in(typed, range)).filter(|kept| *kept != value) diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index 54b099f8..03677ab4 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -1,4 +1,4 @@ -use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; use super::{CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, SMALL_TEXT_SIZE, TEXT_SIZE}; use crate::theme::semibold; @@ -36,7 +36,21 @@ const TOGGLE_KNOB_TRAVEL: f32 = 4.5; const PAIR_PITCH: f32 = 76.0; const PAIR_NAME_TO_PILL: f32 = 32.0; +/// Width of a focused control's outline in points +const FOCUS_OUTLINE_WIDTH: f32 = 2.0; + impl PropertySheet<'_> { + pub(super) fn paint_control_focus(&self, response: &Response) { + if response.has_focus() { + self.ui.painter().rect_stroke( + response.rect, + CornerRadius::same(CONTROL_RADIUS), + Stroke::new(FOCUS_OUTLINE_WIDTH, self.tokens.text_strong), + StrokeKind::Inside, + ); + } + } + /// Two to four short choices as a boxed switch, or a dropdown when one doesn't fit; returns the picked index pub(crate) fn switch(&mut self, label: &str, options: &[&str], selected: usize) -> Option { self.switch_tinted(label, options, selected, &[]) @@ -96,6 +110,8 @@ impl PropertySheet<'_> { } else if response.hovered() { painter.rect_filled(rect.shrink(SEGMENT_INSET), CornerRadius::same(CONTROL_RADIUS), tokens.row_hover); } + + self.paint_control_focus(&response); let runs = tints(index); let tint = runs.first().copied().unwrap_or(tokens.text); let (font, color) = if on { (semibold(SMALL_TEXT_SIZE), tint) } else { (FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim) }; @@ -150,7 +166,9 @@ impl PropertySheet<'_> { if response.clicked() { *on = !*on; } + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *on, label)); + self.paint_control_focus(&response); response.clicked() } @@ -165,14 +183,16 @@ impl PropertySheet<'_> { let hit = Rect::from_min_max(pos2(x, control.top()), pos2(pill.x + PILL_SIZE.x / 2.0, control.bottom())); let id = self.next_id(); let response = self.ui.interact(hit, id, Sense::click()); - response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *state, format!("{label} {name}"))); if response.clicked() { *state = !*state; clicked = Some(index); } + + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *state, format!("{label} {name}"))); let tokens = self.tokens; self.ui.painter().text(pos2(x, center_y), Align2::LEFT_CENTER, name, font.clone(), if *state { tokens.text } else { tokens.text_dim }); self.pill(pill, *state, true); + self.paint_control_focus(&response); } clicked } diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index 546bddf2..11b20f48 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -177,6 +177,7 @@ fn dropdown_list_hangs_from_its_button_at_its_width_and_picks() { let at = harness.get_by_label("Nearest").rect().center(); click_at(&mut harness, at); harness.run_steps(2); + assert_eq!(harness.state().filtering, Filtering::Nearest); } @@ -206,6 +207,7 @@ fn a_cut_unavailable_reason_reads_whole_in_its_tooltip() { harness.hover_at(reason.center()); harness.run_steps(TOOLTIP_WAIT_FRAMES); + assert!(harness.get_all_by_label(REASON).count() > 1, "its tooltip reads it whole"); } diff --git a/crates/ui-egui/src/property_sheet/value_text.rs b/crates/ui-egui/src/property_sheet/value_text.rs index b40ca7a4..a569f284 100644 --- a/crates/ui-egui/src/property_sheet/value_text.rs +++ b/crates/ui-egui/src/property_sheet/value_text.rs @@ -1,5 +1,13 @@ //! Where a slider's value sits and how it reads +use egui::Id; +use egui::text_edit::TextEditState; + +use super::value_text_draft::ValueTextDraft; +use crate::theme::semibold; + +type ValueTextDrafts = egui::cache::FramePublisher>; + /// A value drawn right-aligned at `right` in a `width` wide box centred on `center_y`, reading `shown`; typing may end in `suffix`; it answers as `label`'s value pub(super) struct ValueText<'a> { pub(super) label: &'a dyn std::fmt::Display, @@ -13,41 +21,52 @@ pub(super) struct ValueText<'a> { /// How far below a value's centre its typing line runs const LINE_DROP: f32 = 9.0; -/// Where the field `field_id` keeps the text its typing opened with -fn opened_id(field_id: egui::Id) -> egui::Id { - field_id.with("opened") -} - impl super::PropertySheet<'_> { /// Starts typing `text` into the field `field_id`, all of it selected so the first key replaces it - pub(super) fn start_typing(&mut self, field_id: egui::Id, text: String) { - let mut state = egui::text_edit::TextEditState::load(self.ui.ctx(), field_id).unwrap_or_default(); - state.cursor.set_char_range(Some(egui::text::CCursorRange::select_all_str(&text))); - state.store(self.ui.ctx(), field_id); - self.ui.data_mut(|data| { - data.insert_temp(opened_id(field_id), text.clone()); - data.insert_temp(field_id, text); - }); + pub(super) fn start_typing(&mut self, field_id: Id, text: String) { + let mut editor = TextEditState::default(); + editor.cursor.set_char_range(Some(egui::text::CCursorRange::select_all_str(&text))); + self.keep_typing(field_id, ValueTextDraft { original: text.clone(), text, editor }); self.ui.memory_mut(|memory| memory.request_focus(field_id)); } - /// Ends typing into the field `field_id`; whether `typed` is still the text it opened with (left so, it changes nothing, even after the value changed meanwhile) - pub(super) fn end_typing(&mut self, field_id: egui::Id, typed: &str) -> bool { - let opened = self.ui.data_mut(|data| { - data.remove::(field_id); - data.remove_temp::(opened_id(field_id)) - }); - opened.is_some_and(|opened| opened.trim() == typed.trim()) + pub(super) fn typing_draft(&self, field_id: Id) -> Option { + self.ui.memory_mut(|memory| memory.caches.cache::().get(&field_id).cloned().flatten()) } - /// Shows `edit` from `left` to `right` centred on `center_y` (an edit is never shorter than the theme's interact height), so its value sits where the shown value sat; leaves the sheet's rows where they are - pub(super) fn typing_edit(&mut self, left: f32, right: f32, center_y: f32, edit: egui::TextEdit<'_>) -> egui::Response { - let line = self.ui.painter().layout_no_wrap("0".to_owned(), crate::theme::semibold(super::TEXT_SIZE), self.tokens.text).size().y; + /// Keep the draft only while its field is drawn + pub(super) fn keep_typing(&self, field_id: Id, draft: ValueTextDraft) { + self.ui.memory_mut(|memory| memory.caches.cache::().set(field_id, Some(draft))); + } + + /// Ends typing and reports whether the text still matches what the field opened with + pub(super) fn end_typing(&self, field_id: Id, draft: &ValueTextDraft) -> bool { + self.ui.memory_mut(|memory| memory.caches.cache::().set(field_id, None)); + draft.original.trim() == draft.text.trim() + } + + /// Shows an edit in place of the displayed value, without shifting the sheet's rows + pub(super) fn typing_edit(&mut self, left: f32, right: f32, center_y: f32, field_id: Id, draft: &mut ValueTextDraft) -> egui::Response { + let font = semibold(super::TEXT_SIZE); + let line = self.ui.painter().layout_no_wrap("0".to_owned(), font.clone(), self.tokens.text).size().y; let height = line.max(self.ui.spacing().interact_size.y); let rect = egui::Rect::from_min_max(egui::pos2(left, center_y - height / 2.0), egui::pos2(right, center_y + height / 2.0)); let layout = egui::Layout::centered_and_justified(egui::Direction::TopDown); let mut child = self.ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(layout)); - child.add(edit.frame(egui::Frame::NONE).margin(egui::vec2(0.0, 0.0))) + + draft.editor.clone().store(child.ctx(), field_id); + let output = egui::TextEdit::singleline(&mut draft.text) + .id(field_id) + .font(font) + .align(egui::Align2::RIGHT_CENTER) + .frame(egui::Frame::NONE) + .margin(egui::Margin::ZERO) + .show(&mut child); + + // Keep selection and undo history with the draft instead of egui's persistent widget data + child.data_mut(|data| data.remove::(field_id)); + draft.editor = output.state; + output.response.response } /// Takes the one auto id [`Self::typing_edit`]'s child takes, for a value shown instead of typed: the controls after it keep their ids when typing starts or ends, so a click from one field to the next types into the one clicked diff --git a/crates/ui-egui/src/property_sheet/value_text_draft.rs b/crates/ui-egui/src/property_sheet/value_text_draft.rs new file mode 100644 index 00000000..a124fd47 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/value_text_draft.rs @@ -0,0 +1,9 @@ +use egui::text_edit::TextEditState; + +/// The input, original value, and editor state of a visible Properties field +#[derive(Clone)] +pub(super) struct ValueTextDraft { + pub(super) text: String, + pub(super) original: String, + pub(super) editor: TextEditState, +} diff --git a/crates/ui-egui/src/render_mode/tests.rs b/crates/ui-egui/src/render_mode/tests.rs index d8f7ada3..d480483b 100644 --- a/crates/ui-egui/src/render_mode/tests.rs +++ b/crates/ui-egui/src/render_mode/tests.rs @@ -53,6 +53,7 @@ fn environment_cache_retains_source_identity_until_replaced() { assert!(original_source.upgrade().is_none(), "replacing the resource releases its decoded pixels immediately"); assert_ne!(first_key, gpu_scene_key(&app.session), "a new source restarts tracing under the same environment name"); + let second = super::trace_scene(&app).env; assert!(!Arc::ptr_eq(&first, &second)); assert_ne!(first.data, second.data, "replacing the image changes the lighting"); @@ -60,6 +61,7 @@ fn environment_cache_retains_source_identity_until_replaced() { app.session.images.insert("renamed".into(), replacement); app.session.doc.project.display.environment = "resource:renamed".into(); + assert!(!Arc::ptr_eq(&second, &super::trace_scene(&app).env), "the environment name is also part of the key"); } diff --git a/crates/ui-egui/src/round_gizmo.rs b/crates/ui-egui/src/round_gizmo.rs index 0e531677..f017b9ba 100644 --- a/crates/ui-egui/src/round_gizmo.rs +++ b/crates/ui-egui/src/round_gizmo.rs @@ -89,7 +89,7 @@ impl RoundGizmo { _ => return None, }; - let (lower, upper) = app.session.mesh.bounds(); + let (lower, upper) = app.viewport_mesh_bounds.get(&app.session.mesh); let (mesh_center, radius) = mesh_frame((lower, upper)); let [x, y, z] = projector.rotation.map(f32::to_radians); let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x); @@ -214,7 +214,7 @@ impl RoundGizmo { let right_of_rim = top.iter().copied().max_by(|first, second| first.x.total_cmp(&second.x)); self.outline.extend([top, cap(-half_height)]); - // The two side lines, where the round side turns away from the camera; seen end on there are none, and the dot sits on the rim's right + // End-on views show a rim handle because the two side lines coincide let side = along.cross(facing - along * facing.dot(along)).try_normalize(); let mut sides = Vec::new(); for edge in side.into_iter().flat_map(|side| [side, -side]) { @@ -273,7 +273,7 @@ impl RoundGizmo { (turn, self.stretch, origin) } RoundGrab::Size(axes) => { - // How far the pointer went along the line from the centre through where the handle was grabbed (past the centre, none: a drag never flips it); the command keeps each axis's size in its limits on its own side, so does the offset worked out here + // Clamp the drag to the command's size limits so the offset keeps the same center let reach = from - self.center; let factor = ((to - self.center).dot(reach) / reach.length().max(MIN_HANDLE_REACH).powi(2)).max(0.0); let stretch = Vec3::from(axes.map(|on| if on { factor } else { 1.0 })) * self.stretch; @@ -476,6 +476,7 @@ pub(crate) mod tests { let stored = &mut harness.state_mut().session.doc.project.layer_mut(layer).unwrap().kind; let LayerKind::Fill(Fill { projection: Projection::Cylindrical { axis, .. }, .. }) = stored else { panic!("a cylindrical fill") }; *axis = 3; + assert_eq!(gizmo(&harness).outline, round_y); } @@ -491,13 +492,16 @@ pub(crate) mod tests { let (projector, offset) = projector_and_offset(&projection(&harness, layer)); assert!(offset[0] < -0.05 && offset[1].abs() < 1e-3 && offset[2].abs() < 1e-3, "the X arrow moves the centre along X: {offset:?}"); assert_eq!(projector.rotation, [0.0; 3]); + let moved = gizmo(&harness); assert!(moved.center.x > start.center.x + 20.0, "the centre follows: {moved:?}"); // The Z ring (seen face on) turns it round Z; the centre stays where it is let clear = |p: &&Pos2| moved.rings[..2].iter().flatten().map(|other| other.distance(**p)).fold(f32::INFINITY, f32::min); let on_ring = *moved.rings[2].iter().max_by(|a, b| clear(a).total_cmp(&clear(b))).unwrap(); + assert_eq!(moved.grab(on_ring), Some(RoundGrab::Ring(2))); + drag(&mut harness, on_ring, moved.center + (on_ring - moved.center).rot90(), Modifiers::NONE); let (turned, _) = projector_and_offset(&projection(&harness, layer)); assert!(turned.rotation[2].abs() > 30.0 && turned.rotation[0].abs() < 1e-2, "{:?}", turned.rotation); @@ -507,6 +511,7 @@ pub(crate) mod tests { let dot = scaling.sizes.iter().find(|size| size.axes == [true; 3]).expect("the even-scale dot").at; let center = scaling.center; assert_eq!(gizmo(&harness).grab(dot), Some(RoundGrab::Size([true; 3]))); + drag(&mut harness, dot, center + (dot - center) * 1.5, Modifiers::NONE); let (scaled, _) = projector_and_offset(&projection(&harness, layer)); assert!(scaled.scale.iter().all(|scale| (scale - 1.5).abs() < 0.05), "the side dot scales it evenly: {:?}", scaled.scale); @@ -522,9 +527,11 @@ pub(crate) mod tests { let height = cylinder.sizes.iter().find(|size| size.axes == [false, true, false]).expect("the height handle"); let SizeHandle { at: top, axes, along } = *height; assert_eq!(axes, [false, true, false], "the top handle works along the axis"); + let along = along.expect("the height handle is a double arrow"); assert!(along.y.abs() > 0.99, "drawn upright, along the upright axis: {along:?}"); assert_eq!(cylinder.cursor(RoundGrab::Size(axes), false), egui::CursorIcon::ResizeVertical); + drag(&mut harness, top, cylinder.center + (top - cylinder.center) * 0.5, Modifiers::NONE); let (projector, _) = projector_and_offset(&projection(&harness, layer)); assert!(projector.scale[1] < 0.7 && projector.scale[0] == 1.0 && projector.scale[2] == 1.0, "{:?}", projector.scale); @@ -593,6 +600,7 @@ pub(crate) mod tests { let center = gizmo(&harness).center; let to = center + vec2(40.0, 0.0); press_and_move(&mut harness, center, to, Modifiers::NONE); + assert!(round_dragging(&harness), "the centre square is held"); harness.event(egui::Event::WindowFocused(false)); @@ -605,6 +613,7 @@ pub(crate) mod tests { harness.event(egui::Event::PointerMoved(to + vec2(20.0, 10.0) * step as f32)); harness.run_steps(1); } + assert_eq!(projection(&harness, layer), left, "moves after it leave the projector where it was"); } @@ -622,6 +631,7 @@ pub(crate) mod tests { harness.event_modifiers(egui::Event::PointerMoved(to + vec2(20.0, 0.0)), Modifiers::ALT); harness.run_steps(1); + assert_ne!(harness.state().session.camera, camera, "Alt turns the camera"); assert!(!round_dragging(&harness), "and ends the projector drag"); @@ -629,9 +639,12 @@ pub(crate) mod tests { harness.event(egui::Event::PointerMoved(to + vec2(20.0, 5.0) * step as f32)); harness.run_steps(1); } + assert_eq!(projection(&harness, layer), slid, "Alt let go, the projector stays where the drag left it"); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); harness.run_steps(2); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step"); } @@ -646,11 +659,13 @@ pub(crate) mod tests { let front = gizmo(&harness); assert!(front.rings[0].is_empty(), "the X ring seen edge on is left out: {:?}", front.rings[0]); assert!(front.rings[1..].iter().all(|ring| !ring.is_empty()), "the Y and Z rings show"); + let on_the_line = front.center + vec2(0.0, 40.0); assert_ne!(front.grab(on_the_line), Some(RoundGrab::Ring(0)), "a press where its line would be does not grab it"); harness.state_mut().session.camera.yaw = 0.5; harness.run_steps(2); + assert!(gizmo(&harness).rings.iter().all(|ring| !ring.is_empty()), "turned aside, every ring shows"); } @@ -678,8 +693,10 @@ pub(crate) mod tests { let (mut harness, layer) = fill_app("spherical"); let start = gizmo(&harness); assert_eq!(start.sizes.len(), 1, "one dot: {:?}", start.sizes); + let dot = start.sizes[0].at; assert_eq!(start.grab(dot), Some(RoundGrab::Size([true; 3]))); + drag(&mut harness, dot, start.center + (dot - start.center) * 1.4, Modifiers::NONE); let (scaled, _) = projector_and_offset(&projection(&harness, layer)); assert!(scaled.scale.iter().all(|scale| (scale - 1.4).abs() < 0.08), "it scales evenly: {:?}", scaled.scale); @@ -700,6 +717,7 @@ pub(crate) mod tests { Some(RoundGrab::Size([true, false, false])), "grabbed from its tip" ); + drag(&mut harness, across.at, box_gizmo.center + (across.at - box_gizmo.center) * 0.5, Modifiers::NONE); let (stretched, _) = projector_and_offset(&projection(&harness, layer)); assert!((stretched.scale[0] - scaled.scale[0] * 0.5).abs() < 0.05, "the X face halves it across: {:?}", stretched.scale); @@ -727,6 +745,7 @@ pub(crate) mod tests { let start = gizmo(&harness); assert_eq!(start.stretch, Vec3::from(mirrored), "the gizmo reads the mirror as the projection does"); + drag(&mut harness, start.center, start.center + vec2(30.0, -20.0), Modifiers::NONE); let (slid, offset) = projector_and_offset(&projection(&harness, layer)); assert_eq!(slid.scale, mirrored, "a slide keeps the mirror"); @@ -735,6 +754,7 @@ pub(crate) mod tests { let tip = gizmo(&harness).arrows[1].unwrap(); let center = gizmo(&harness).center; drag(&mut harness, tip, tip + (tip - center).normalized() * 20.0, Modifiers::NONE); + assert_eq!(projector_and_offset(&projection(&harness, layer)).0.scale, mirrored, "so does a move along an arrow"); let before_turn = projector_and_offset(&projection(&harness, layer)).0; @@ -782,12 +802,15 @@ pub(crate) mod tests { let center = gizmo(&harness).center; harness.hover_at(center); harness.run_steps(2); + assert_eq!(harness.output().platform_output.cursor_icon, egui::CursorIcon::Grab, "the centre square shows it slides"); harness.event(egui::Event::ModifiersChanged(Modifiers::ALT)); harness.event(egui::Event::PointerMoved(center + vec2(1.0, 0.0))); harness.run_steps(2); + assert_ne!(harness.output().platform_output.cursor_icon, egui::CursorIcon::Grab, "with Alt held it does not"); + harness.event(egui::Event::ModifiersChanged(Modifiers::NONE)); harness.run_steps(2); } @@ -816,6 +839,7 @@ pub(crate) mod tests { drag(&mut harness, center, center + vec2(-40.0, 0.0), Modifiers::COMMAND); harness.event(egui::Event::ModifiersChanged(Modifiers::NONE)); harness.run_steps(2); + assert_ne!(harness.state().session.tool.brush.flow, flow, "the drag changes the brush"); assert_eq!(projection(&harness, layer), before, "and leaves the projection"); } @@ -859,10 +883,12 @@ pub(crate) mod tests { let painted = harness.state().session.quick_mask.revision; click(&mut harness, edge, off); + assert_eq!(harness.state().session.quick_mask.revision, painted, "a press that began on the handle paints no dab"); // The same click a little past the handle paints click(&mut harness, off, off + (off - edge)); + assert_ne!(harness.state().session.quick_mask.revision, painted, "a press off the handle paints"); } @@ -879,6 +905,7 @@ pub(crate) mod tests { let across = [true, true, false]; let dot = end_on.sizes.iter().find(|size| size.axes == across).unwrap_or_else(|| panic!("the across dot: {:?}", end_on.sizes)).at; assert_eq!(end_on.grab(dot), Some(RoundGrab::Size(across))); + drag(&mut harness, dot, end_on.center + (dot - end_on.center) * 1.5, Modifiers::NONE); let (projector, _) = projector_and_offset(&projection(&harness, layer)); assert!(projector.scale[0] > 1.2 && projector.scale[1] > 1.2 && projector.scale[2] == 1.0, "it scales across only: {:?}", projector.scale); diff --git a/crates/ui-egui/src/symmetry/view_overlay.rs b/crates/ui-egui/src/symmetry/view_overlay.rs index 4f805951..eff8362e 100644 --- a/crates/ui-egui/src/symmetry/view_overlay.rs +++ b/crates/ui-egui/src/symmetry/view_overlay.rs @@ -67,7 +67,7 @@ pub(crate) fn scene_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect) -> Vec= 2.5, "{b:?} {a:?}: accent on panel"); assert!(contrast(Color32::WHITE, t.accent_strong) >= 2.5, "{b:?} {a:?}: white on accent button"); assert!(contrast(t.viewport_text, t.viewport) >= 3.0, "{b:?}: lettering on the views"); - // Slider rails show on the card. + // Slider rails show on the card assert!(contrast(t.button_border, t.panel) >= 1.6, "{b:?}: rail on panel"); } } - // The views keep their studio slate. + + // The views keep their studio slate assert_eq!(Tokens::for_brightness(Brightness::Light).viewport, Tokens::for_brightness(Brightness::Dark).viewport); } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 4a8015ec..a58be4de 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -895,7 +895,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let gizmo = ShownGizmo::of(app, rect); let frame_drag = gizmo_free && ShownGizmo::input(app, ui, &response, rect, gizmo.as_ref()); - // Alt (or another mode) taking the pointer mid-drag ends the drag: let go of Alt, it must not resume from where it began before the camera moved + // End the gizmo drag when navigation takes over because the camera may have moved if !gizmo_free { ShownGizmo::let_go(ui.ctx()); } @@ -1031,7 +1031,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && let Some(hit) = app.session.pick(local(hover_pos), app.session.viewport) { ui.ctx().set_cursor_icon(egui::CursorIcon::None); - let (bounds_min, bounds_max) = app.session.mesh.bounds(); + let (bounds_min, bounds_max) = app.viewport_mesh_bounds.get(&app.session.mesh); let radius = app.session.tool.brush.size * (bounds_max - bounds_min).length(); brush_cursor(app, ui, rect, hit.pos, hit.nrm, radius); symmetry_cursor = Some((hit.pos, hit.nrm)); @@ -2542,7 +2542,7 @@ mod tests { #[test] fn unavailable_tools_finish_strokes_and_box_fills() { - // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + // Hold the language lock while drawing the harness let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::{StackTarget, core::LayerId, geom::primitives}; @@ -2580,17 +2580,22 @@ mod tests { let app = harness.state_mut(); app.ui.mode = crate::state::Mode::Painting; app.session.view = ViewMode::Mask(LayerId(7)); + assert_eq!(mask_view_layer(app), Some(LayerId(7))); + app.session.quick_mask.editing = true; + assert!(quick_mask_shown(app)); assert_eq!(mask_view_layer(app), None, "the quick mask is on screen, not the layer mask"); + app.session.quick_mask.editing = false; + assert_eq!(mask_view_layer(app), Some(LayerId(7)), "the label returns with the mask view"); } #[test] fn stored_surfaces_release_after_a_frame_without_paths() { - // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + // Hold the language lock while drawing the harness let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::{core::EffectKind, execute, geom::primitives}; @@ -2678,7 +2683,7 @@ mod tests { #[test] fn decal_frame_rejects_a_stale_effect_after_failed_layer_selection() { - // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + // Hold the language lock while drawing the harness let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::{StackTarget, execute}; @@ -2703,6 +2708,7 @@ mod tests { drag_decal_handle(&mut harness, original.center, original.center + vec2(40.0, 0.0)); let effect = &harness.state().session.doc.project.effect(effect).unwrap().1.kind; + assert!( matches!(effect, texturecraft_engine::core::EffectKind::Fill { projection: texturecraft_engine::core::Projection::Planar { placed: Some(decal), .. }, .. } if *decal == original.decal) ); @@ -2711,7 +2717,7 @@ mod tests { #[test] fn decal_frame_keeps_an_instances_inherited_mask_effect_editable() { - // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + // Hold the language lock while drawing the harness let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::execute; @@ -2726,18 +2732,21 @@ mod tests { assert_eq!(session.ts(), 1); assert_eq!(session.selected_layer().unwrap().0, instance.as_u64().unwrap()); + let inherited = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); + assert_eq!((inherited.layer, inherited.effect, inherited.decal), (original.layer, original.effect, original.decal)); drag_decal_handle(&mut harness, inherited.corners[1], inherited.center + (inherited.corners[1] - inherited.center) * 1.5); let edited = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); + assert!(edited.decal.size[0] > original.decal.size[0], "scaling an inherited decal edits its source"); } #[test] fn decal_frame_rejects_a_source_mask_overridden_by_the_selected_instance() { - // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + // Hold the language lock while drawing the harness let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::execute; @@ -2757,7 +2766,7 @@ mod tests { #[test] #[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] fn decal_frame_selection_snapshots() { - // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + // Hold the language lock while drawing the harness let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::execute; @@ -2769,25 +2778,31 @@ mod tests { let effect = original.effect.unwrap(); let session = &mut harness.state_mut().session; let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); + assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err()); + harness.run_steps(6); assert!(crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_some()); + harness.render().unwrap().save(directory.join("decal-frame-inherited.png")).unwrap(); let session = &mut harness.state_mut().session; let other = execute(session, "layer.add.paint", &json!({"name": "Other layer"})).unwrap()["layer"].clone(); execute(session, "layer.select", &json!({"layer": original.layer.0, "target": effect.0})).unwrap(); + assert!(execute(session, "layer.select", &json!({"layer": other, "target": effect.0})).is_err()); + harness.run_steps(6); assert!(crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none()); + harness.render().unwrap().save(directory.join("decal-frame-stale.png")).unwrap(); } #[test] fn live_bake_preview_hides_setup_overlays_and_restores_their_preferences() { - // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + // Hold the language lock while drawing the harness let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); diff --git a/crates/ui-egui/src/viewport_mesh_bounds.rs b/crates/ui-egui/src/viewport_mesh_bounds.rs new file mode 100644 index 00000000..32542076 --- /dev/null +++ b/crates/ui-egui/src/viewport_mesh_bounds.rs @@ -0,0 +1,23 @@ +use std::cell::RefCell; +use std::sync::{Arc, Weak}; + +use texturecraft_engine::geom::{Mesh, glam::Vec3}; + +/// Axis-aligned bounds shared by projection controls for the current mesh +#[derive(Default)] +pub(crate) struct ViewportMeshBounds { + mesh: RefCell>, + bounds: std::cell::Cell<(Vec3, Vec3)>, +} + +impl ViewportMeshBounds { + pub(crate) fn get(&self, mesh: &Arc) -> (Vec3, Vec3) { + let mut previous = self.mesh.borrow_mut(); + if previous.as_ptr() != Arc::as_ptr(mesh) { + self.bounds.set(mesh.bounds()); + *previous = Arc::downgrade(mesh); + } + + self.bounds.get() + } +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 9891dcc8..93bb6b5a 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -449,7 +449,7 @@ fn color_picker(ui: &mut Ui, id: egui::Id, c: &mut Color32, width: f32) -> bool let tk = Tokens::get(ui.ctx()); let mut srgb = [c.r(), c.g(), c.b()]; let hsv_of = |srgb: [u8; 3]| hsv_from_rgb(srgb.map(|v| v as f32 / 255.0)); - // Remembered with the color it was for, so hue and saturation survive black, white and grays. + // Remembered with the color it was for, so hue and saturation survive black, white and grays let (mut h, mut s, mut v) = ui.data(|d| d.get_temp::<(Color32, (f32, f32, f32))>(id)).filter(|(k, _)| k == c).map_or_else(|| hsv_of(srgb), |(_, hsv)| hsv); let mut typed = false; let mut dragged = false; @@ -465,7 +465,7 @@ fn color_picker(ui: &mut Ui, id: egui::Id, c: &mut Color32, width: f32) -> bool (h, s, v) = hsv_of(srgb); } let border = Stroke::new(1.0, tk.field_border); - // Saturation across, value up. + // Saturation across, value up let (rect, resp) = ui.allocate_exact_size(vec2(width, width), Sense::click_and_drag()); if let Some(p) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.clicked()) { (s, v) = (((p.x - rect.left()) / rect.width()).clamp(0.0, 1.0), 1.0 - ((p.y - rect.top()) / rect.height()).clamp(0.0, 1.0)); @@ -500,7 +500,12 @@ fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> /// Cells across and down: fine enough that a hue strip's six ramps read smooth const GRID_CELLS: u32 = 24; - let mut mesh = egui::Mesh::default(); + let side_vertices = GRID_CELLS as usize + 1; + let cell_count = (GRID_CELLS * GRID_CELLS) as usize; + // Each grid cell contributes two triangles + let mut mesh = + egui::Mesh { vertices: Vec::with_capacity(side_vertices * side_vertices), indices: Vec::with_capacity(cell_count * 6), ..Default::default() }; + for j in 0..=GRID_CELLS { for i in 0..=GRID_CELLS { let (x, y) = (i as f32 / GRID_CELLS as f32, j as f32 / GRID_CELLS as f32); @@ -508,6 +513,7 @@ fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> mesh.colored_vertex(rect.lerp_inside(vec2(x, y)), Color32::from_rgb(r, g, b)); } } + for j in 0..GRID_CELLS { for i in 0..GRID_CELLS { let top_left = j * (GRID_CELLS + 1) + i; @@ -516,6 +522,7 @@ fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> mesh.add_triangle(top_left + 1, bottom_left + 1, bottom_left); } } + painter.add(mesh); } diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs index 6c54d052..d56067e4 100644 --- a/crates/ui-egui/tests/brush_cursor_2d.rs +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -145,13 +145,17 @@ fn a_ctrl_right_drag_out_of_the_2d_view_keeps_its_outline_at_the_anchor() { // The outline stays anchored while the pointer is hidden inside the view harness.hover_at(center + egui::vec2(10.0, 0.0)); harness.run_steps(3); + assert_eq!(rings_at(&harness, center).len(), 1, "anchored outline while the pointer is in the view"); assert_eq!(cursor(&harness), CursorIcon::None); + // Outside the view, the outline stays anchored and the system pointer returns harness.hover_at(egui::pos2(2.0, 2.0)); harness.run_steps(3); + assert_eq!(rings_at(&harness, center).len(), 1, "the outline stays at the press origin outside the view"); assert_ne!(cursor(&harness), CursorIcon::None, "outside the view the pointer is visible"); + harness.event(Event::PointerButton { pos: egui::pos2(2.0, 2.0), button: egui::PointerButton::Secondary, pressed: false, modifiers: ctrl }); harness.event(Event::ModifiersChanged(egui::Modifiers::NONE)); harness.run_steps(2); diff --git a/crates/ui-egui/tests/it/fill_projection_rows.rs b/crates/ui-egui/tests/it/fill_projection_rows.rs index 8d0fbe71..a84a7743 100644 --- a/crates/ui-egui/tests/it/fill_projection_rows.rs +++ b/crates/ui-egui/tests/it/fill_projection_rows.rs @@ -34,6 +34,7 @@ fn each_projection_shows_its_own_rows() { for label in ["Depth culling", "Backface culling", "Angle", "Extends Outside Shape", "Offset X", "Rotation Y", "Scale Z"] { assert!(shows(&harness, label), "planar: {label}"); } + assert!(!shows(&harness, "Reset frame"), "planar has no frame to reset"); let (harness, _) = app_with_fill("warp"); @@ -42,12 +43,14 @@ fn each_projection_shows_its_own_rows() { for label in ["Depth", "Reset frame", "Depth culling", "Offset X", "Rotation X", "Scale X"] { assert!(shows(&harness, label), "warp: {label}"); } + assert!(!shows(&harness, "Backface culling"), "a warp has no backface culling"); let (harness, _) = app_with_fill("cylindrical"); for label in ["Angle", "Backface culling", "Extends Outside Shape", "Offset X"] { assert!(shows(&harness, label), "cylindrical: {label}"); } + assert!(!shows(&harness, "Depth culling")); let (harness, _) = app_with_fill("triplanar"); @@ -111,6 +114,7 @@ fn the_culling_rows_i_explains_the_row_on_hover_without_covering_its_values() { let before = projection(&harness, layer); let info = harness.get_by_label(DEPTH_CULLING_TIP).rect().center(); click_at(&mut harness, info); + assert_eq!(projection(&harness, layer), before); } @@ -173,7 +177,9 @@ fn reset_frame_puts_a_warps_corners_back() { fn the_3d_projection_settings_fold_away() { let (mut harness, _) = app_with_fill("spherical"); assert!(harness.query_by_label("Scale X").is_some(), "the band starts open"); + click_label(&mut harness, "3D projection settings"); + assert!(harness.query_by_label("Scale X").is_none()); assert!(harness.query_by_label("Spherical projection").is_some(), "the rows above it stay"); } @@ -205,10 +211,13 @@ fn the_fill_caption_resets_the_whole_fill_section_to_its_projections_defaults_in ); assert_eq!(after.sampling, Sampling { symmetry: changed.sampling.symmetry, ..Sampling::default() }, "the symmetry stays"); assert!(harness.get_by_label("Fill: Reset to defaults").accesskit_node().is_disabled(), "at the defaults it is faint and inert"); + click_at(&mut harness, reset); + assert_eq!(fill(&harness, layer), after, "a click at the defaults changes nothing"); harness.state_mut().run("edit.undo", json!({})); + assert_eq!(fill(&harness, layer), after_band, "one undo step brings the whole section back"); } diff --git a/crates/ui-egui/tests/it/fill_symmetry_rows.rs b/crates/ui-egui/tests/it/fill_symmetry_rows.rs index 466f07f5..240be1a9 100644 --- a/crates/ui-egui/tests/it/fill_symmetry_rows.rs +++ b/crates/ui-egui/tests/it/fill_symmetry_rows.rs @@ -48,24 +48,32 @@ fn the_symmetry_switch_shows_its_rows_and_each_row_changes_the_symmetry() { assert!(harness.query_by_label("Mirror symmetry").is_none(), "off, the section is the caption alone"); click_node(&mut harness, Role::CheckBox, "Symmetry"); + assert!(symmetry(&harness, layer).on); assert!(harness.query_by_label("Axis position X").is_some(), "a mirror across X moves along X"); assert!(harness.query_by_label("Count").is_none(), "a mirror has no radial rows"); click_node(&mut harness, Role::RadioButton, "Y"); + assert_eq!(symmetry(&harness, layer).axis, 1); + click_node(&mut harness, Role::CheckBox, "Flip copy U"); + assert_eq!(symmetry(&harness, layer).flip, [true, false]); click_node(&mut harness, Role::ComboBox, "Mirror symmetry"); click_node(&mut harness, Role::ListBoxOption, "Radial symmetry"); + assert_eq!(symmetry(&harness, layer).kind, SymmetryKind::Radial); + for label in ["Count", "Angle span", "Axis position X", "Axis position Z"] { assert!(harness.query_by_label(label).is_some(), "radial round Y: {label}"); } + assert!(harness.query_by_label("Axis position Y").is_none(), "the turning axis does not move along itself"); click_node(&mut harness, Role::CheckBox, "Symmetry"); + assert!(!symmetry(&harness, layer).on); assert_eq!(symmetry(&harness, layer).kind, SymmetryKind::Radial, "switched off, the settings stay"); } @@ -74,7 +82,9 @@ fn the_symmetry_switch_shows_its_rows_and_each_row_changes_the_symmetry() { fn a_uv_fill_says_why_in_place_of_the_symmetry_switch() { let (mut harness, layer) = app_with_fill("uv"); assert!(harness.query_by_role_and_label(Role::CheckBox, "Symmetry").is_none(), "no switch to click"); + click_label(&mut harness, "Not available with UV projection"); + assert!(!symmetry(&harness, layer).on, "a UV projection has no symmetry to switch on"); assert!(harness.query_by_label("Type").is_none(), "its settings stay hidden, not greyed"); } @@ -87,11 +97,13 @@ fn a_count_click_that_keeps_the_count_adds_no_undo_step_and_a_drag_to_the_next_a let inside = count_at(&harness, 6.2); click_at(&mut harness, inside); + assert_eq!(symmetry(&harness, layer).count, 6); assert_eq!(undo_depth(&harness), steps, "a count that stays six is no edit"); let (from, to) = (count_at(&harness, 6.0), count_at(&harness, 7.3)); drag(&mut harness, from, to); + assert_eq!(symmetry(&harness, layer).count, 7); assert_eq!(undo_depth(&harness), steps + 1, "the drag's frames merge into one step"); } diff --git a/crates/ui-egui/tests/it/polygon_fill.rs b/crates/ui-egui/tests/it/polygon_fill.rs index 5a923224..ac418f44 100644 --- a/crates/ui-egui/tests/it/polygon_fill.rs +++ b/crates/ui-egui/tests/it/polygon_fill.rs @@ -59,10 +59,12 @@ fn a_box_drag_in_the_3d_view_is_one_fill_over_more_than_a_click() { let center = clicked.state().viewport_rect.center(); let before = history(&clicked).len(); click(&mut clicked, center); + assert_eq!(history(&clicked).len(), before + 1, "a click fills one triangle"); let mut boxed = polygon_fill_app(); drag(&mut boxed, center - vec2(120.0, 120.0), center + vec2(120.0, 120.0)); + assert_eq!(history(&boxed).len(), before + 1); assert_eq!(history(&boxed).last().map(String::as_str), Some("Polygon fill")); assert!( @@ -81,6 +83,7 @@ fn a_box_drag_in_the_2d_view_is_one_fill() { let before = history(&harness).len(); drag(&mut harness, center - vec2(80.0, 20.0), center + vec2(80.0, 20.0)); + assert_eq!(history(&harness).len(), before + 1); assert_eq!(history(&harness).last().map(String::as_str), Some("Polygon fill")); } @@ -100,10 +103,12 @@ fn a_new_press_after_release_does_not_resume_the_previous_box() { .events .extend([Event::PointerMoved(point), Event::PointerButton { pos: point, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]); harness.run_steps(1); + assert_eq!(painted_tiles(&harness), tiles_after_drag, "a press alone must not refill the old rectangle"); harness.event(Event::PointerButton { pos: point, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); harness.run_steps(1); + assert_eq!(history(&harness).len(), history_after_drag.len() + 1, "only the new click records a step"); } @@ -115,11 +120,13 @@ fn the_symmetry_toggle_is_offered_for_polygon_fill_and_a_symmetric_click_is_one_ harness.get_by_label("Symmetry settings"); harness.get_by_label("Symmetry").click(); harness.run_steps(2); + assert!(harness.state().session.tool.brush.symmetry.any(), "the toggle turns mirroring on for the fill"); let center = harness.state().viewport_rect.center(); let before = history(&harness).len(); click(&mut harness, center); + assert_eq!(history(&harness).len(), before + 1, "the fill and its mirror copies are one undo step"); assert_eq!(history(&harness).last().map(String::as_str), Some("Polygon fill")); } diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index a2cd6187..50b4f220 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -188,7 +188,9 @@ fn the_window_follows_the_reference_layout() { for labels in order.windows(2) { assert!(top(labels[0]) < top(labels[1]), "{} comes before {}", labels[0], labels[1]); } + assert!(h.query_by_label("Custom unit scale").is_none(), "Physical size starts collapsed"); + let disabled = |role: Role, label: &str| h.get_by_role_and_label(role, label).accesskit_node().is_disabled(); for (role, label) in [ (Role::CheckBox, "Compute tangent space per fragment"), @@ -205,6 +207,7 @@ fn the_window_follows_the_reference_layout() { let center = h.get_by_role_and_label(Role::CheckBox, "Compute tangent space per fragment").rect().center(); h.hover_at(center); h.run_steps(30); + assert!(h.query_by_label("Not available yet").is_some(), "the hint of a setting TextureCraft does not have yet"); } diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs index f3b7823b..3ff215b7 100644 --- a/crates/ui-egui/tests/it/properties_popup.rs +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -171,9 +171,13 @@ fn it_shows_what_the_properties_panel_shows() { let mut harness = harness(); let fill = harness.state().session.doc.project.layers.values().find(|layer| matches!(layer.kind, LayerKind::Fill(_))).map(|layer| layer.id.0).unwrap(); let selected = texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": fill})); + assert!(selected.is_ok(), "{selected:?}"); + let projected = texturecraft_engine::execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": fill, "projection": "uv"})); + assert!(projected.is_ok(), "{projected:?}"); + harness.run_steps(3); let center = view_center(&harness); @@ -227,6 +231,7 @@ fn bake_and_render_modes_never_open_it() { harness.state_mut().ui.mode = mode; harness.run_steps(3); click(&mut harness, PointerButton::Secondary, center); + assert_eq!(harness.state().properties_popup, None, "{mode:?}"); } } diff --git a/crates/ui-egui/tests/it/shelf_drop.rs b/crates/ui-egui/tests/it/shelf_drop.rs index 848064c3..d1c732fd 100644 --- a/crates/ui-egui/tests/it/shelf_drop.rs +++ b/crates/ui-egui/tests/it/shelf_drop.rs @@ -258,7 +258,9 @@ fn the_click_that_closes_the_drop_menu_paints_nothing_and_adds_no_undo_step() { let image = import_white_image(&mut harness); drop_asset(&mut harness, Asset::Texture(image), position); harness.run_steps(2); + assert!(menu_open(&harness, position)); + let history = harness.state().session.history_labels().len(); // A point on the same set, away from the menu diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 804cf5fc..01b2e2e2 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -829,6 +829,7 @@ fn mask_fill_image_snapshot() { let EffectKind::Fill { source, .. } = &harness.state().session.doc.project.effect(LayerId(effect)).unwrap().1.kind else { panic!("fill effect") }; assert_eq!(*source, Source::image(name)); assert!(harness.query_by_label("UV projection").is_some(), "image projection is editable"); + save(&mut harness, &output_dir, "mask-fill-image-selected"); } From a90313c888a4c5e92602c754ef98e5eb62155c10 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 22 Nov 2026 06:06:10 -0500 Subject: [PATCH 17/17] Clear texture updates in the headless Properties scroll test --- crates/ui-egui/src/property_sheet/properties_scroll.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/property_sheet/properties_scroll.rs b/crates/ui-egui/src/property_sheet/properties_scroll.rs index 294d52f5..4c3a5be7 100644 --- a/crates/ui-egui/src/property_sheet/properties_scroll.rs +++ b/crates/ui-egui/src/property_sheet/properties_scroll.rs @@ -116,12 +116,15 @@ mod tests { let context = egui::Context::default(); for (selection, expected_offset) in [(content, 42.0), (effect, 68.0), (content, 42.0)] { - let _ = context.run_ui(egui::RawInput::default(), |ui| { + let mut frame = context.run_ui(egui::RawInput::default(), |ui| { let area = scroll.prepare(ScrollArea::vertical().max_height(80.0), ui.scope_id(), selection); let output = area.show(ui, |ui| ui.add_space(256.0)); assert_eq!(output.state.clamped_offset().y, expected_offset); }); + + // This headless test has no renderer to apply texture updates + frame.textures_delta.clear(); } execute(&mut session, "effect.remove", &json!({"effect": effect_id.0})).unwrap();