Merge pull request #412 from Rebornim/feat/assets-pass

Assets panel pass 1: the reference's layout (4-column grid, one-line labels, type row, breadcrumb, side panes, toolbar)
This commit is contained in:
Chris Hassebrook authored and GitHub committed 2026-11-15 19:16:45 -05:00
commit cce9adafb8
31 files changed
+12560 -386

No files matched your search

+138
View File
@@ -0,0 +1,138 @@
//! Saving the current brush as a preset (Properties › Brush › Preset); presets show on the shelf's Brushes tab
use egui::Ui;
use serde_json::json;
use std::path::Path;
use texturecraft_engine::brush_preset_cmds::BRUSH_EXT;
use crate::TextureCraftApp;
use crate::i18n::tr;
/// The preset name field's width in points
const NAME_WIDTH: f32 = 110.0;
/// A name field and a button that saves the current brush under that name
pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui) {
let dir = crate::user_dir("brushes");
let name_id = ui.make_persistent_id("brush_preset_name");
let confirm_id = ui.make_persistent_id("brush_preset_overwrite");
let mut new_name: String = ui.data_mut(|data| data.get_temp(name_id)).unwrap_or_default();
let mut pending_path: Option<std::path::PathBuf> = ui.data_mut(|data| data.get_temp(confirm_id));
ui.horizontal(|ui| {
ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(NAME_WIDTH));
if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() {
let path = dir.join(format!("{}.{BRUSH_EXT}", preset_file_stem(new_name.trim())));
match std::fs::symlink_metadata(&path) {
Ok(_) => pending_path = Some(path),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
if save_brush(app, &dir, &path) {
new_name.clear();
}
}
Err(_) => pending_path = Some(path),
}
}
});
if let Some(path) = pending_path.clone() {
let mut replace = false;
let mut cancel = false;
egui::Window::new(tr("Replace"))
.id(ui.make_persistent_id("brush_preset_replace_dialog"))
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
.show(ui.ctx(), |ui| {
ui.label(path.file_name().and_then(|name| name.to_str()).unwrap_or_default());
ui.horizontal(|ui| {
replace = ui.button(tr("Replace")).clicked();
cancel = ui.button(tr("Cancel")).clicked();
});
});
if replace {
if save_brush(app, &dir, &path) {
new_name.clear();
}
pending_path = None;
} else if cancel {
pending_path = None;
}
}
ui.data_mut(|data| {
data.insert_temp(name_id, new_name);
data.insert_temp(confirm_id, pending_path);
});
}
/// Preserve Unicode names and encode filename punctuation without collisions
fn preset_file_stem(name: &str) -> String {
let mut stem = String::new();
// Six digits cover every Unicode scalar and separate adjacent escapes
for character in name.chars() {
if character.is_alphanumeric() || character == '-' || character == '_' || character == ' ' {
stem.push(character);
} else {
stem.push_str(&format!("~{:06X}", character as u32));
}
}
let uppercase = stem.to_ascii_uppercase();
if matches!(
uppercase.as_str(),
"CON"
| "PRN"
| "AUX"
| "NUL"
| "COM1"
| "COM2"
| "COM3"
| "COM4"
| "COM5"
| "COM6"
| "COM7"
| "COM8"
| "COM9"
| "LPT1"
| "LPT2"
| "LPT3"
| "LPT4"
| "LPT5"
| "LPT6"
| "LPT7"
| "LPT8"
| "LPT9"
) {
stem.insert_str(0, "brush-");
}
stem
}
/// Save a preset and invalidate cached tiles only when the write succeeds
fn save_brush(app: &mut TextureCraftApp, dir: &Path, path: &Path) -> bool {
// A folder that cannot be made is reported by the save command
let _ = std::fs::create_dir_all(dir);
if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_none() {
return false;
}
app.brushes = None;
app.thumbs.forget_saved_files();
true
}
#[cfg(test)]
mod tests {
use super::preset_file_stem;
#[test]
fn distinct_unicode_brush_names_have_distinct_safe_file_stems() {
assert_ne!(preset_file_stem("水彩"), preset_file_stem("油画"));
assert_ne!(preset_file_stem("a/b"), preset_file_stem("a~00002Fb"));
assert_eq!(preset_file_stem("水彩"), "水彩");
assert!(!preset_file_stem("a/b").contains('/'));
assert_eq!(preset_file_stem("CON"), "brush-CON");
}
}
+4
View File
@@ -1799,6 +1799,10 @@ fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) {
}
*brush = brush.sanitized();
// Presets are files, which the browser doesn't have
#[cfg(not(target_arch = "wasm32"))]
section(ui, "sec_brush_preset", tr("Preset"), false, |ui| crate::brush_preset_save::row(app, ui));
}
/// One alpha in the picker: a 52×64 tile with the shape drawn by `paint` and a label.
+16 -5
View File
@@ -133,17 +133,28 @@ fn split(axis: SplitAxis, size: SplitSize, first: Node<Panel>, second: Node<Pane
Node::Split { axis, size, first: Box::new(first), second: Box::new(second) }
}
/// The default: assets left of the viewport, then texture sets, layers (tabbed with texture set settings) and properties; ratios fit 1600x960
/// The default: assets (4 tile columns at 1920 px) left of the viewport, then texture sets, layers (tabbed with texture set settings) and properties
pub fn default_workspace() -> Workspace {
use Panel::*;
// The Assets split keeps four tiles visible at the reference window width
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;
let column = split(
SplitAxis::Vertical,
SplitSize::Ratio(0.125),
SplitSize::Ratio(TEXTURE_SET_SPLIT_RATIO),
tabs(&[TextureSetList]),
split(SplitAxis::Vertical, SplitSize::Ratio(0.57), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])),
split(SplitAxis::Vertical, SplitSize::Ratio(LAYERS_SPLIT_RATIO), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])),
);
let root = split(
SplitAxis::Horizontal,
SplitSize::Ratio(ASSETS_SPLIT_RATIO),
tabs(&[Assets]),
split(SplitAxis::Horizontal, SplitSize::Ratio(VIEWPORT_SPLIT_RATIO), tabs(&[Viewport]), column),
);
let root =
split(SplitAxis::Horizontal, SplitSize::Ratio(0.115), tabs(&[Assets]), split(SplitAxis::Horizontal, SplitSize::Ratio(0.78), tabs(&[Viewport]), column));
let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() });
for panel in Panel::ALL {
+9
View File
@@ -0,0 +1,9 @@
//! A grid tile's measurements in the shelf's small, medium and large views
/// A grid tile's size and its thumbnail's size and center below the tile's top, in points
pub(crate) struct GridTile {
pub(crate) width: f32,
pub(crate) height: f32,
pub(crate) thumbnail_size: f32,
pub(crate) thumbnail_center_y: f32,
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+10
View File
@@ -10,6 +10,8 @@
mod bake_job;
pub mod bake_mode;
mod bake_scene;
#[cfg(not(target_arch = "wasm32"))]
mod brush_preset_save;
mod color_selection_editor;
pub mod control;
mod decal_drop;
@@ -22,6 +24,7 @@ mod filter_slot;
pub mod fonts;
mod generator_panel;
pub mod gpu;
mod grid_tile;
pub mod i18n;
pub mod id_color_pick;
pub mod keymap;
@@ -47,8 +50,15 @@ pub mod render_mode;
mod resource_picker;
mod resource_picker_item;
mod running_bake;
pub mod saved_search;
pub mod shelf;
mod shelf_entry;
mod shelf_folders;
pub mod shelf_panes;
pub mod shelf_preview;
mod shelf_tabs;
mod shelf_toolbar;
pub mod shelf_view;
mod soft_box;
pub mod state;
pub mod symmetry;
+64 -24
View File
@@ -153,44 +153,84 @@ pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage {
preview
}
/// Preview the brush along an S curve in an `n`-pixel square
pub fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage {
let library = b.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image);
let radius = n as f32 * 0.11;
let shape = Shape { alpha: b.alpha, image: None, library, level: 0 }.at_radius(radius);
let curve = |t: f32| (n as f32 * (0.15 + 0.7 * t), n as f32 * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin()));
let mut cover = vec![0f32; n * n];
// Stable jitter keeps the preview reproducible
let rnd = |i: u32, k: u32| (i.wrapping_mul(0x9E37_79B9) ^ k.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32;
let step = (b.spacing * 2.0 * radius).max(0.5);
/// Preview the brush along an S curve in a `size_px` square
pub fn stroke_preview(brush: &BrushSettings, size_px: usize, image: Option<&ImageRes>) -> ColorImage {
// Leave room around the S curve and cap work for a single preview
const STROKE_RADIUS_FRACTION: f32 = 0.11;
const CURVE_SAMPLE_STEP: f32 = 0.002;
const MIN_STAMP_SPACING_PX: f32 = 0.5;
const MAX_STAMPS: u32 = 2000;
const CURVE_HORIZONTAL_INSET: f32 = 0.15;
const CURVE_HORIZONTAL_SPAN: f32 = 0.7;
const CURVE_WAVE_AMPLITUDE: f32 = 0.22;
let library = brush.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image);
let radius = size_px as f32 * STROKE_RADIUS_FRACTION;
let shape = Shape { alpha: brush.alpha, image, library, level: 0 }.at_radius(radius);
// The horizontal inset and vertical wave keep the S curve inside the swatch
let curve = |t: f32| {
(
size_px as f32 * (CURVE_HORIZONTAL_INSET + CURVE_HORIZONTAL_SPAN * t),
size_px as f32 * (0.5 - CURVE_WAVE_AMPLITUDE * (t * std::f32::consts::TAU).sin()),
)
};
let mut cover = vec![0f32; size_px * size_px];
// Odd multipliers decorrelate reproducible jitter across stamps and channels
let jitter_sample = |stamp_index: u32, channel: u32| {
(stamp_index.wrapping_mul(0x9E37_79B9) ^ channel.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32
};
let step = (brush.spacing * 2.0 * radius).max(MIN_STAMP_SPACING_PX);
let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32);
let mut last = curve(0.0);
while t <= 1.0 && i < 2000 {
while t <= 1.0 && i < MAX_STAMPS {
let p = curve(t);
travelled += (p.0 - last.0).hypot(p.1 - last.1);
last = p;
t += 0.002;
t += CURVE_SAMPLE_STEP;
if travelled < step {
continue;
}
travelled = 0.0;
i += 1;
let r = radius * (1.0 - b.jitter_size * rnd(i, 1));
let tangent = if b.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 };
let angle = b.angle.to_radians() + tangent + b.jitter_angle * std::f32::consts::TAU * rnd(i, 2);
let (cx, cy) = (p.0 + b.jitter_position * radius * (rnd(i, 3) * 2.0 - 1.0), p.1 + b.jitter_position * radius * (rnd(i, 4) * 2.0 - 1.0));
let flow = b.flow * (1.0 - b.jitter_flow * rnd(i, 5));
let stamp_radius = radius * (1.0 - brush.jitter_size * jitter_sample(i, 1));
let tangent = if brush.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 };
let angle = brush.angle.to_radians() + tangent + brush.jitter_angle * std::f32::consts::TAU * jitter_sample(i, 2);
let (cx, cy) = (
p.0 + brush.jitter_position * radius * (jitter_sample(i, 3) * 2.0 - 1.0),
p.1 + brush.jitter_position * radius * (jitter_sample(i, 4) * 2.0 - 1.0),
);
let flow = brush.flow * (1.0 - brush.jitter_flow * jitter_sample(i, 5));
let (sin, cos) = angle.sin_cos();
let (x0, x1) = ((cx - r).floor().max(0.0) as usize, ((cx + r).ceil() as usize).min(n));
let (y0, y1) = ((cy - r).floor().max(0.0) as usize, ((cy + r).ceil() as usize).min(n));
let (x0, x1) = ((cx - stamp_radius).floor().max(0.0) as usize, ((cx + stamp_radius).ceil() as usize).min(size_px));
let (y0, y1) = ((cy - stamp_radius).floor().max(0.0) as usize, ((cy + stamp_radius).ceil() as usize).min(size_px));
for y in y0..y1 {
for x in x0..x1 {
let (dx, dy) = ((x as f32 + 0.5 - cx) / r, (cy - y as f32 - 0.5) / r);
let a = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, b.hardness, i) * flow;
let c = &mut cover[y * n + x];
*c = 1.0 - (1.0 - *c) * (1.0 - a.clamp(0.0, 1.0));
let (dx, dy) = ((x as f32 + 0.5 - cx) / stamp_radius, (cy - y as f32 - 0.5) / stamp_radius);
let alpha = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, brush.hardness, i) * flow;
let coverage = &mut cover[y * size_px + x];
*coverage = 1.0 - (1.0 - *coverage) * (1.0 - alpha.clamp(0.0, 1.0));
}
}
}
ColorImage::new([n, n], cover.into_iter().map(|v| Color32::from_gray((v * b.opacity * 255.0 + 0.5) as u8)).collect())
ColorImage::new([size_px, size_px], cover.into_iter().map(|v| Color32::from_gray((v * brush.opacity * 255.0 + 0.5) as u8)).collect())
}
/// Environment `name`'s panorama across a `size²` swatch, transparent above and below
pub fn environment_image(name: &str, size: usize) -> ColorImage {
let panorama = texturecraft_render::ibl::environment(name, u32::try_from(size).unwrap_or(u32::MAX));
let (width, height) = (panorama.width as usize, panorama.height as usize);
let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT);
let top = size.saturating_sub(height) / 2;
for (y, row) in panorama.data.chunks(width.max(1)).enumerate() {
for (x, linear) in row.iter().enumerate().take(size) {
let Some(pixel) = image.pixels.get_mut((top + y) * size + x) else { continue };
let [r, g, b] = linear.map(|component| (linear_to_srgb(aces(component * EXPOSURE)) * 255.0 + 0.5) as u8);
*pixel = Color32::from_rgb(r, g, b);
}
}
image
}
+12
View File
@@ -0,0 +1,12 @@
//! A shelf query the user saved in the Saved searches pane
use serde::{Deserialize, Serialize};
/// The search text, tab and library folder of a saved shelf query, under the name it lists as
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SavedSearch {
pub name: String,
pub filter: String,
pub tab: usize,
pub path: Vec<String>,
}
+295 -329
View File
@@ -1,40 +1,49 @@
//! The asset shelf (the Assets dock tab): tabs (materials, smart materials, smart
//! masks, filters, alphas, procedurals, environments, textures), all built in and procedural.
//! Search filters across every tab. Materials (built in and saved), smart masks, filters, alphas
//! and textures drag onto the layer stack, a layer row, the viewport or the brush properties
//! ([`ShelfDrag`]); a texture dropped on the 3D view becomes a decal there, in the channel picked from a menu
//! The Assets panel: built-in, saved and project assets in one grid by type, library and search, dragged onto the layer stack, the views or the brush
use egui::{Color32, RichText, Sense, Stroke, Ui, vec2};
use egui_phosphor::regular as ic;
use serde_json::json;
use texturecraft_engine::core::ProceduralKind;
use texturecraft_engine::filter_lib::FILTERS;
#[cfg(not(target_arch = "wasm32"))]
use texturecraft_engine::formats::mcmat::MCMAT_EXT;
use texturecraft_engine::geom::glam::Vec2;
use texturecraft_engine::materials::MATERIALS;
use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX;
use texturecraft_engine::paint::alphas;
use texturecraft_engine::paint::presets::{BrushPreset, PRESETS};
use texturecraft_engine::smart_masks::SMART_MASKS;
use texturecraft_render::ibl::ENVIRONMENTS;
use crate::TextureCraftApp;
use crate::decal_drop::DecalDrop;
use crate::i18n::{tr, trf};
use crate::shelf_entry::ShelfEntry;
use crate::shelf_preview::ShelfPreview;
use crate::shelf_view::ShelfView;
use crate::theme::Tokens;
use crate::thumbs::Thumbs;
use crate::widgets::{dnd_release, icon_button};
use crate::widgets::dnd_release;
/// A shelf tile's size in points
const TILE_WIDTH: f32 = 72.0;
const TILE_HEIGHT: f32 = 86.0;
/// The gap between tiles in points (their sizes are [`ShelfView`]'s)
const TILE_GAP: f32 = 2.0;
/// The gap after a grid or a list of rows, in points
const SECTION_GAP: f32 = 6.0;
/// The gap between the type row and asset grid, in points
const TYPE_GRID_GAP: f32 = 4.0;
/// The saved material hint's font size, in points
#[cfg(not(target_arch = "wasm32"))]
const HINT_SIZE: f32 = 10.0;
/// The name of a saved material whose file name isn't text
const SAVED_MATERIAL_NAME: &str = "material";
/// Corner radius of a tile's hover and selection highlights, in points
const TILE_ROUNDING: f32 = 3.0;
/// The thumbnail's size in a tile and its center below the tile's top, in points
const THUMBNAIL_SIZE: f32 = 56.0;
const THUMBNAIL_CENTER_Y: f32 = 32.0;
/// The last clicked or right-clicked tile's [`ShelfEntry::identity`], kept in egui's memory under this id
const SELECTED_TILE: &str = "shelf_selected_tile";
/// The outline widths of the selected tile and of the one in use (the brush's alpha, the shown environment), in points
const SELECTED_OUTLINE_WIDTH: f32 = 1.5;
const IN_USE_OUTLINE_WIDTH: f32 = 1.0;
/// The randomness badge's dot radius, dot spacing and inset from the thumbnail's corner, in points
const BADGE_DOT_RADIUS: f32 = 1.3;
const BADGE_DOT_SPACING: f32 = 3.6;
const BADGE_INSET: f32 = 2.5;
/// The randomness badge's dot colour and its rim's width (points) and colour
const BADGE_DOT_FILL: Color32 = Color32::from_gray(205);
const BADGE_DOT_RIM: f32 = 0.8;
const BADGE_DOT_RIM_COLOR: Color32 = Color32::from_black_alpha(170);
/// Loading icon size relative to the thumbnail width, and its opacity over the dim text color
const LOADING_ICON_SCALE: f32 = 0.9;
const LOADING_ICON_OPACITY: f32 = 0.5;
@@ -56,22 +65,21 @@ pub(crate) enum Tab {
Filters,
Brushes,
Alphas,
Procedurals,
Environments,
/// Procedural patterns and the project's images
Textures,
Environments,
}
/// The shelf tabs: icon and (English, translated where shown) name.
pub(crate) const TABS: [(Tab, &str, &str); 9] = [
/// The shelf tabs: icon and (English, translated where shown) name
pub(crate) const TABS: [(Tab, &str, &str); 8] = [
(Tab::Materials, ic::SPHERE, "Materials"),
(Tab::Smart, ic::STACK, "Smart materials"),
(Tab::Masks, ic::CIRCLE_HALF, "Smart masks"),
(Tab::Filters, ic::FUNNEL, "Filters"),
(Tab::Brushes, ic::PAINT_BRUSH_BROAD, "Brushes"),
(Tab::Alphas, ic::SHAPES, "Alphas"),
(Tab::Procedurals, ic::CHECKERBOARD, "Procedurals"),
(Tab::Environments, ic::SUN_HORIZON, "Environments"),
(Tab::Textures, ic::IMAGE, "Textures"),
(Tab::Environments, ic::SUN_HORIZON, "Environments"),
];
/// A shelf asset: built in (by id), a saved smart material (file path) or an image resource.
@@ -117,7 +125,7 @@ pub fn apply(app: &mut TextureCraftApp, asset: &Asset) {
&& content
&& let Some(name) = unpainted_paint_layer(app)
{
// Otherwise the filter seems to do nothing: it has nothing to change yet.
// Otherwise the filter seems to do nothing: it has nothing to change yet
app.toast(trf("\"{layer}\" has no paint yet: the filter changes what you paint on it.", &[("layer", &name)]), false);
}
return;
@@ -223,55 +231,106 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response
/// The Assets panel body (a dock tab)
pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
let tokens = Tokens::get(ui.ctx());
let ctx = ui.ctx().clone();
let mut tab = app.ui.shelf_tab.min(TABS.len() - 1);
let searching = !app.ui.shelf_filter.is_empty();
let filter = app.ui.shelf_filter.to_lowercase();
scan_library(app);
scan_brushes(app);
let all = ShelfEntry::all(app);
let paths = crate::shelf_folders::with_every_library(crate::shelf_folders::paths(&all));
ui.horizontal_wrapped(|ui| {
let button_size = ui.spacing().interact_size.y;
ui.spacing_mut().item_spacing = vec2(2.0, 2.0);
for (i, (_, icon, label)) in TABS.iter().enumerate() {
if icon_button(ui, icon, tr(label), i == tab && !searching, button_size).clicked() {
tab = i;
app.ui.shelf_filter.clear();
}
// A folder that is gone (its last image removed) shows everything again
if !paths.iter().any(|path| path.starts_with(&app.ui.shelf_path)) {
app.ui.shelf_path.clear();
}
let folder = app.ui.shelf_path.clone();
let picked_tab = app.ui.shelf_tab;
let searched: Vec<ShelfEntry> = all.into_iter().filter(|entry| entry.matches(&filter)).collect();
let mut applicable = crate::shelf_folders::paths(searched.iter().filter(|entry| crate::shelf_tabs::shows(picked_tab, entry.tab())));
let matching: Vec<ShelfEntry> = searched.into_iter().filter(|entry| entry.in_folder(&folder)).collect();
let mut counts: Vec<usize> = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect();
// Saved smart materials list under the grid rather than as tiles, so they count apart
let in_user_library = folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER);
let saved_materials_matching = saved_materials_matching(app, &filter);
if in_user_library && let Some(smart) = TABS.iter().position(|(tab, _, _)| *tab == Tab::Smart).and_then(|smart| counts.get_mut(smart)) {
*smart += saved_materials_matching;
}
if saved_materials_matching > 0 && crate::shelf_tabs::shows(picked_tab, Tab::Smart) {
applicable.push(vec![crate::shelf_entry::USER.to_string()]);
}
crate::shelf_folders::breadcrumb(app, ui, &paths);
search_field(app, ui);
crate::shelf_tabs::row(app, ui, &counts, crate::shelf_view::menu);
ui.add_space(TYPE_GRID_GAP);
let tab = app.ui.shelf_tab;
let shown_tab = TABS.get(tab).map(|(shown, _, _)| *shown);
let mut entries: Vec<ShelfEntry> = matching.into_iter().filter(|entry| crate::shelf_tabs::shows(tab, entry.tab())).collect();
entries.sort_by_cached_key(|entry| entry.label().to_lowercase());
// The toolbar has its own strip at the panel's bottom, so nothing above it can push it out
let area = ui.available_rect_before_wrap();
let toolbar_top = (area.bottom() - crate::shelf_toolbar::height(ui)).max(area.top());
let grid_rect = egui::Rect::from_min_max(area.min, egui::pos2(area.right(), toolbar_top));
let toolbar_rect = egui::Rect::from_min_max(egui::pos2(area.left(), toolbar_top), area.max);
ui.scope_builder(egui::UiBuilder::new().max_rect(grid_rect).layout(egui::Layout::left_to_right(egui::Align::Min)), |ui| {
if let Some(width) = crate::shelf_panes::column_width(app, ui.available_width()) {
ui.allocate_ui_with_layout(vec2(width, grid_rect.height()), egui::Layout::top_down(egui::Align::Min), |ui| {
ui.set_min_size(vec2(width, grid_rect.height()));
crate::shelf_panes::column(app, ui, &paths, &applicable);
});
ui.separator();
}
});
app.ui.shelf_tab = tab;
// Saved smart materials are files in the user's library, without folders of their own
let saved_materials = in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart);
grid(app, ui, &ctx, &entries, grid_rect.height(), saved_materials, &filter);
});
ui.scope_builder(egui::UiBuilder::new().max_rect(toolbar_rect), |ui| crate::shelf_toolbar::show(app, ui));
drag_preview(&ctx);
}
/// The tiles of `entries` in a scroll area `height` high, then the saved smart materials when `saved_materials`
fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ShelfEntry], height: f32, saved_materials: bool, filter: &str) {
let view = app.ui.shelf_view;
let selected: Option<(String, String)> = ctx.data(|data| data.get_temp(egui::Id::unique(SELECTED_TILE)));
egui::ScrollArea::vertical()
.id_salt("shelf_scroll")
.auto_shrink([false, false])
.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible)
.max_height(height)
.show(ui, |ui| {
tiles(ui, |ui| {
for entry in entries {
let is_selected = selected.as_ref().is_some_and(|(kind, id)| entry.identity() == (kind.as_str(), id.as_str()));
entry_tile(app, ui, ctx, entry, view, is_selected);
}
});
if saved_materials {
library(app, ui, filter);
}
});
}
/// How many of the user's saved smart materials match `filter` (none until the library is read)
fn saved_materials_matching(app: &TextureCraftApp, filter: &str) -> usize {
app.library.iter().flatten().filter(|path| matches(filter, &[saved_material_name(path)])).count()
}
/// The search field: a live filter on names (and categories) with a clear button while it has text
fn search_field(app: &mut TextureCraftApp, ui: &mut Ui) {
let tokens = Tokens::get(ui.ctx());
ui.horizontal(|ui| {
ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tokens.text_dim));
ui.add(egui::TextEdit::singleline(&mut app.ui.shelf_filter).hint_text(tr("Search all assets")).desired_width(f32::INFINITY));
});
ui.add_space(4.0);
let filter = app.ui.shelf_filter.to_lowercase();
egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).show(ui, |ui| {
// Searching shows matches from every tab, each under its tab's name
for (i, (t, _, title)) in TABS.iter().enumerate() {
if filter.is_empty() && i != tab {
continue;
}
let title = tr(title);
match t {
Tab::Materials => materials(app, ui, &ctx, &filter, false, title),
Tab::Smart => {
materials(app, ui, &ctx, &filter, true, title);
library(app, ui, &filter);
}
Tab::Masks => smart_masks(app, ui, &ctx, &filter, title),
Tab::Filters => filters(app, ui, &ctx, &filter, title),
Tab::Brushes => brushes(app, ui, &ctx, &filter, title),
Tab::Alphas => alpha_library(app, ui, &ctx, &filter, title),
Tab::Procedurals => procedurals(app, ui, &ctx, &filter, title),
Tab::Environments => environments(app, ui, &filter, title),
Tab::Textures => textures(app, ui, &ctx, &filter, title),
}
let clear_width = if app.ui.shelf_filter.is_empty() { 0.0 } else { ui.spacing().interact_size.y + ui.spacing().item_spacing.x };
let field = egui::TextEdit::singleline(&mut app.ui.shelf_filter).hint_text(tr("Search")).desired_width(ui.available_width() - clear_width);
ui.add(field);
if !app.ui.shelf_filter.is_empty() && ui.add(egui::Button::new(ic::X).frame(false)).on_hover_text(tr("Clear")).clicked() {
app.ui.shelf_filter.clear();
}
});
drag_preview(&ctx);
}
/// The dragged asset's name next to the pointer.
@@ -290,11 +349,6 @@ pub(crate) fn matches(filter: &str, texts: &[&str]) -> bool {
filter.is_empty() || texts.iter().any(|t| t.to_lowercase().contains(filter))
}
fn title(ui: &mut Ui, text: &str) {
let tk = Tokens::get(ui.ctx());
ui.label(RichText::new(text).strong().color(tk.text_strong));
}
pub(crate) fn header(ui: &mut Ui, text: &str) {
let tk = Tokens::get(ui.ctx());
ui.add_space(2.0);
@@ -303,10 +357,10 @@ pub(crate) fn header(ui: &mut Ui, text: &str) {
pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) {
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(4.0, 4.0);
ui.spacing_mut().item_spacing = vec2(TILE_GAP, TILE_GAP);
body(ui);
});
ui.add_space(6.0);
ui.add_space(SECTION_GAP);
}
/// The distinct categories of `items`, in order of first appearance.
@@ -320,46 +374,38 @@ pub(crate) fn categories<T>(items: &[T], category: impl Fn(&T) -> &'static str)
out
}
/// Built-in materials or smart materials, grouped by category
fn materials(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, smart: bool, name: &str) {
let shown: Vec<_> =
MATERIALS.iter().filter(|material| material.smart == smart && matches(filter, &[material.label, material.category, material.id])).collect();
if shown.is_empty() {
/// Read the user's saved smart materials (desktop library folder) unless they are already listed
#[cfg(not(target_arch = "wasm32"))]
fn scan_library(app: &mut TextureCraftApp) {
if app.library.is_some() {
return;
}
title(ui, name);
for category in categories(&shown, |material| material.category) {
header(ui, category);
tiles(ui, |ui| {
for material in shown.iter().filter(|material| material.category == category) {
let texture = app.thumbs.material(ctx, material.id);
let asset = Asset::Material(material.id);
if tile(ui, &mut app.thumbs, texture.as_ref(), || ShelfPreview::material(material.id), material.label, Some(&asset)).clicked() {
apply(app, &asset);
}
}
});
}
let saved_material = |path: &std::path::PathBuf| path.extension().is_some_and(|extension| extension == "tcmat" || extension == MCMAT_EXT);
let mut files: Vec<std::path::PathBuf> =
std::fs::read_dir(crate::library_dir()).map(|dir| dir.flatten().map(|entry| entry.path()).filter(saved_material).collect()).unwrap_or_default();
files.sort();
app.library = Some(files);
}
/// The user's saved smart materials (desktop library folder).
#[cfg(target_arch = "wasm32")]
fn scan_library(_: &mut TextureCraftApp) {}
/// A saved smart material's name: its file name without the extension
fn saved_material_name(path: &std::path::Path) -> &str {
path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_MATERIAL_NAME)
}
/// The user's saved smart materials matching `filter`, as rows under the grid
#[cfg(not(target_arch = "wasm32"))]
fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) {
let tk = Tokens::get(ui.ctx());
if app.library.is_none() {
let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(crate::library_dir())
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "tcmat" || x == MCMAT_EXT)).collect())
.unwrap_or_default();
files.sort();
app.library = Some(files);
}
let tokens = Tokens::get(ui.ctx());
let files = app.library.clone().unwrap_or_default();
let name = |f: &std::path::PathBuf| f.file_stem().and_then(|s| s.to_str()).unwrap_or("material").to_string();
let shown: Vec<_> = files.iter().filter(|f| matches(filter, &[&name(f)])).collect();
let shown: Vec<_> = files.iter().filter(|path| matches(filter, &[saved_material_name(path)])).collect();
if !filter.is_empty() && shown.is_empty() {
return;
}
ui.horizontal(|ui| {
header(ui, tr("My smart materials"));
if ui.small_button(ic::ARROW_CLOCKWISE).on_hover_text(tr("Rescan the library folder")).clicked() {
@@ -367,276 +413,174 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) {
}
});
if files.is_empty() {
ui.label(RichText::new(tr("Right-click a layer > Create smart material")).size(10.0).color(tk.text_dim));
ui.label(RichText::new(tr("Right-click a layer > Create smart material")).size(HINT_SIZE).color(tokens.text_dim));
}
for f in shown {
let (label, asset) = (name(f), Asset::Library(f.display().to_string()));
// MaterialCraft materials (sent from MaterialCraft) show a graph.
let glyph = if f.extension().is_some_and(|x| x == MCMAT_EXT) { ic::GRAPH } else { ic::SPHERE };
let r = ui.add(egui::Button::selectable(false, format!("{glyph} {label}")).sense(Sense::click_and_drag())).on_hover_ui(|ui| {
for path in shown {
let (label, asset) = (saved_material_name(path).to_string(), Asset::Library(path.display().to_string()));
// MaterialCraft materials (sent from MaterialCraft) show a graph
let glyph = if path.extension().is_some_and(|extension| extension == MCMAT_EXT) { ic::GRAPH } else { ic::SPHERE };
let response = ui.add(egui::Button::selectable(false, format!("{glyph} {label}")).sense(Sense::click_and_drag())).on_hover_ui(|ui| {
ui.label(crate::i18n::trf(
"{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)",
&[("file", &f.display())],
&[("file", &path.display())],
));
});
if r.drag_started() {
r.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label });
if response.drag_started() {
response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label });
}
if r.clicked() {
if response.clicked() {
apply(app, &asset);
}
}
ui.add_space(6.0);
ui.add_space(SECTION_GAP);
}
#[cfg(target_arch = "wasm32")]
fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {}
fn smart_masks(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) {
let shown: Vec<_> = SMART_MASKS.iter().filter(|m| matches(filter, &[m.label, m.id])).collect();
if shown.is_empty() {
return;
}
title(ui, name);
tiles(ui, |ui| {
for m in shown {
let tex = app.thumbs.smart_mask(ctx, m.id);
let asset = Asset::SmartMask(m.id);
if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::SmartMask(m.id), m.label, Some(&asset)).clicked() {
apply(app, &asset);
}
}
});
}
/// The filter library, grouped: a click adds the filter to the selected layer's content (or its
/// mask when the mask is selected), a drop onto a layer to that layer's content.
fn filters(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) {
let shown: Vec<_> = FILTERS.iter().filter(|f| matches(filter, &[f.label, f.group, f.id, tr(f.label), tr(f.group)])).collect();
if shown.is_empty() {
return;
}
title(ui, name);
for group in categories(&shown, |f| f.group) {
header(ui, tr(group));
tiles(ui, |ui| {
for f in shown.iter().filter(|f| f.group == group) {
let tex = app.thumbs.filter(ctx, f.id);
let asset = Asset::Filter(f.id);
if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Filter(f.id), tr(f.label), Some(&asset)).clicked() {
apply(app, &asset);
}
}
});
}
}
/// Brush presets, grouped by category, then the user's own: a click sets the brush's stroke
/// (alpha, spacing, flow, jitters…) and keeps its size.
fn brushes(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) {
let shown: Vec<&BrushPreset> = PRESETS.iter().filter(|p| matches(filter, &[p.label, p.category, p.id])).collect();
if !shown.is_empty() {
title(ui, name);
for cat in categories(&shown, |p| p.category) {
header(ui, cat);
tiles(ui, |ui| {
for p in shown.iter().filter(|p| p.category == cat) {
let tex = app.thumbs.brush_preset(ctx, p);
if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Brush(p), p.label, None).clicked() {
app.run("brush.preset.apply", json!({"preset": p.id}));
}
}
});
}
}
my_brushes(app, ui, filter);
}
/// The user's saved brush presets (desktop brushes folder) and saving the current brush there.
/// Read the user's saved brush presets (desktop brushes folder) unless they are already listed
#[cfg(not(target_arch = "wasm32"))]
fn my_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) {
fn scan_brushes(app: &mut TextureCraftApp) {
use texturecraft_engine::brush_preset_cmds::BRUSH_EXT;
let dir = crate::user_dir("brushes");
if app.brushes.is_none() {
let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(&dir)
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == BRUSH_EXT)).collect())
.unwrap_or_default();
files.sort();
app.brushes = Some(files);
}
let files = app.brushes.clone().unwrap_or_default();
let name = |f: &std::path::PathBuf| f.file_stem().and_then(|s| s.to_str()).unwrap_or("brush").to_string();
let shown: Vec<_> = files.iter().filter(|f| matches(filter, &[&name(f)])).collect();
if !filter.is_empty() && shown.is_empty() {
if app.brushes.is_some() {
return;
}
ui.horizontal(|ui| {
header(ui, tr("My brushes"));
if ui.small_button(ic::ARROW_CLOCKWISE).on_hover_text(tr("Rescan the library folder")).clicked() {
app.brushes = None;
}
});
for f in shown {
if ui
.add(egui::Button::selectable(false, format!("{} {}", ic::PAINT_BRUSH_BROAD, name(f))))
.on_hover_text(tr("Use this brush (keeps its size)"))
.clicked()
{
app.run("brush.preset.load", json!({"path": f.display().to_string()}));
}
}
ui.horizontal(|ui| {
let id = ui.make_persistent_id("brush_preset_name");
let mut new_name: String = ui.data_mut(|d| d.get_temp(id)).unwrap_or_default();
ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(110.0));
let file = texturecraft_engine::formats::export::sanitize_file_stem(new_name.trim());
if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() {
let path = dir.join(format!("{file}.{BRUSH_EXT}"));
// A folder that can't be made fails the save, which reports it.
let _ = std::fs::create_dir_all(&dir);
if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_some() {
new_name.clear();
app.brushes = None;
}
}
ui.data_mut(|d| d.insert_temp(id, new_name));
});
ui.add_space(6.0);
let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(crate::user_dir("brushes"))
.map(|dir| dir.flatten().map(|entry| entry.path()).filter(|path| path.extension().is_some_and(|extension| extension == BRUSH_EXT)).collect())
.unwrap_or_default();
files.sort();
app.brushes = Some(files);
}
#[cfg(target_arch = "wasm32")]
fn my_brushes(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {}
fn scan_brushes(_: &mut TextureCraftApp) {}
/// The built-in alpha library, grouped by category; the brush's alpha is outlined.
fn alpha_library(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) {
let tk = Tokens::get(ctx);
let shown: Vec<&'static alphas::LibraryAlpha> = alphas::library().iter().filter(|a| matches(filter, &[&a.label, a.category, &a.id])).collect();
if shown.is_empty() {
/// The tile of `entry`, outlined when `selected`: a click applies it, an image resource has a context menu
fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView, selected: bool) {
// An image removed this frame has nothing to show
if let ShelfEntry::Image(name) = entry
&& !app.session.images.contains_key(name)
{
return;
}
title(ui, name);
let brush = &app.session.tool.brush;
let current = if brush.alpha_image.is_none() { brush.alpha_library.clone() } else { None };
for cat in categories(&shown, |a| a.category) {
header(ui, cat);
tiles(ui, |ui| {
for &a in shown.iter().filter(|a| a.category == cat) {
let tex = app.thumbs.alpha(ctx, a);
let asset = Asset::Alpha(&a.id);
let r = tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Alpha(a), &a.label, Some(&asset));
if current.as_deref() == Some(a.id.as_str()) {
ui.painter().rect_stroke(r.rect, TILE_ROUNDING, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside);
}
if r.clicked() {
apply(app, &asset);
}
let texture = entry.thumbnail(app, ctx);
let asset = entry.asset();
let session = &app.session;
let response = tile_in_view(
ui,
&mut app.thumbs,
texture.as_ref(),
|thumbs| match entry {
ShelfEntry::SavedBrush(path) => Some(thumbs.saved_brush_preview(path, &session.images)),
_ => entry.preview(session),
},
entry.label(),
asset.as_ref(),
view,
);
if selected || entry.in_use(app) {
let tokens = Tokens::get(ctx);
let width = if selected { SELECTED_OUTLINE_WIDTH } else { IN_USE_OUTLINE_WIDTH };
ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(width, tokens.accent), egui::StrokeKind::Inside);
}
if entry.includes_randomness() {
randomness_badge(ui.painter(), view.thumbnail_rect(response.rect));
}
if response.clicked() || response.secondary_clicked() {
let (kind, id) = entry.identity();
ctx.data_mut(|data| data.insert_temp(egui::Id::unique(SELECTED_TILE), (kind.to_string(), id.to_string())));
}
if response.clicked() {
entry.activate(app);
}
if let ShelfEntry::Image(name) = entry {
response.context_menu(|ui| {
if ui.button(tr("Add as decal (view center)")).clicked() {
app.run("layer.add.decal", json!({"image": name}));
ui.close();
}
if ui.button(tr("Remove resource")).clicked() {
app.run("resource.remove", json!({"name": name}));
ui.close();
}
});
}
}
fn procedurals(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) {
let shown: Vec<ProceduralKind> = ProceduralKind::ALL.into_iter().filter(|k| matches(filter, &[k.label(), tr(k.label())])).collect();
if shown.is_empty() {
return;
}
title(ui, name);
tiles(ui, |ui| {
for k in shown {
let tex = app.thumbs.procedural(ctx, k);
if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Procedural(k), tr(k.label()), None).clicked() {
app.run("layer.add.fill", json!({"name": k.label()}));
app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": k.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]}));
}
}
});
}
fn environments(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, name: &str) {
let shown: Vec<&&str> = ENVIRONMENTS.iter().filter(|e| matches(filter, &[e])).collect();
if shown.is_empty() {
return;
}
title(ui, name);
for env in shown {
let on = app.session.doc.project.display.environment == **env;
if ui.selectable_label(on, format!("{} {env}", ic::SUN_HORIZON)).clicked() {
app.run("display.set", json!({"environment": env}));
}
}
ui.add_space(6.0);
}
fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) {
let tk = Tokens::get(ctx);
let names: Vec<String> = app.session.doc.resources.keys().filter(|n| matches(filter, &[n])).cloned().collect();
if !filter.is_empty() && names.is_empty() {
return;
}
ui.horizontal(|ui| {
title(ui, name);
if ui.small_button(tr("Import...")).clicked() {
crate::menus::invoke(app, ctx, "resource.import");
}
});
if names.is_empty() {
ui.label(RichText::new(tr("Import images to use them in fills and masks")).size(10.0).color(tk.text_dim));
}
tiles(ui, |ui| {
for name in names {
let Some(img) = app.session.images.get(&name).cloned() else { continue };
let tex = app.thumbs.image(ctx, &name, &img);
let asset = Asset::Texture(name.clone());
let preview = || ShelfPreview::Image(name.clone(), img);
let r = tile(ui, &mut app.thumbs, Some(&tex), preview, &name, Some(&asset));
if r.clicked() {
apply(app, &asset);
}
r.context_menu(|ui| {
if ui.button(tr("Add as decal (view center)")).clicked() {
app.run("layer.add.decal", json!({"image": name}));
ui.close();
}
if ui.button(tr("Remove resource")).clicked() {
app.run("resource.remove", json!({"name": name}));
ui.close();
}
});
}
});
}
/// Asset tile with optional dragging and a larger hover preview
/// Asset tile with optional dragging and a larger hover preview, at the medium size
pub(crate) fn tile(
ui: &mut Ui,
thumbs: &mut Thumbs,
tex: Option<&egui::TextureHandle>,
texture: Option<&egui::TextureHandle>,
preview: impl FnOnce() -> ShelfPreview,
label: &str,
drag: Option<&Asset>,
) -> egui::Response {
let tk = Tokens::get(ui.ctx());
tile_in_view(ui, thumbs, texture, |_| Some(preview()), label, drag, ShelfView::Medium)
}
/// [`tile`] at `view`'s size: a grid tile with the name under the thumbnail, or a list row with it beside; `preview` runs on hover
fn tile_in_view(
ui: &mut Ui,
thumbs: &mut Thumbs,
texture: Option<&egui::TextureHandle>,
preview: impl FnOnce(&mut Thumbs) -> Option<ShelfPreview>,
label: &str,
drag: Option<&Asset>,
view: ShelfView,
) -> egui::Response {
let tokens = Tokens::get(ui.ctx());
let sense = if drag.is_some() { Sense::click_and_drag() } else { Sense::click() };
let (rect, resp) = ui.allocate_exact_size(vec2(TILE_WIDTH, TILE_HEIGHT), sense);
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
let (rect, response) = ui.allocate_exact_size(view.tile_size(ui.available_width()), sense);
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
if let Some(asset) = drag
&& resp.drag_started()
&& response.drag_started()
{
resp.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() });
response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() });
}
let painter = ui.painter();
if resp.hovered() || resp.dragged() {
painter.rect_filled(rect, TILE_ROUNDING, tk.row_hover);
if response.hovered() || response.dragged() {
painter.rect_filled(rect, TILE_ROUNDING, tokens.row_hover);
}
let image_rect = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, THUMBNAIL_CENTER_Y), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE));
thumbnail(painter, tex, image_rect, &tk);
let galley = painter.layout(label.to_string(), egui::FontId::proportional(LABEL_FONT_SIZE), tk.text, rect.width() - LABEL_MARGIN);
painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tk.text);
let big = if resp.hovered() { big_preview(ui, thumbs, preview) } else { None };
resp.on_hover_ui(|ui| hover_preview(ui, tex, big.as_ref(), label))
let image_rect = view.thumbnail_rect(rect);
thumbnail(painter, texture, image_rect, &tokens);
if view.name_beside() {
let left = image_rect.right() + crate::shelf_view::LIST_NAME_GAP;
let galley = painter.layout_job(one_line(label, rect.right() - left - LABEL_MARGIN, tokens.text));
painter.galley(egui::pos2(left, rect.center().y - galley.size().y * 0.5), galley, tokens.text);
} else {
let galley = painter.layout_job(one_line(label, rect.width() - LABEL_MARGIN, tokens.text));
painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tokens.text);
}
let big = if response.hovered() { preview(thumbs).and_then(|preview| big_preview(ui, thumbs, || preview)) } else { None };
response.on_hover_ui(|ui| hover_preview(ui, texture, big.as_ref(), label))
}
/// Three light, dark-rimmed dots at the thumbnail's bottom-right corner: the asset includes randomness
fn randomness_badge(painter: &egui::Painter, thumbnail: egui::Rect) {
let corner = thumbnail.right_bottom() - vec2(BADGE_INSET, BADGE_INSET);
for offset in [vec2(0.0, 0.0), vec2(-BADGE_DOT_SPACING, 0.0), vec2(-BADGE_DOT_SPACING * 0.5, -BADGE_DOT_SPACING)] {
painter.circle(corner + offset, BADGE_DOT_RADIUS, BADGE_DOT_FILL, Stroke::new(BADGE_DOT_RIM, BADGE_DOT_RIM_COLOR));
}
}
/// A tile label on one line, cut with "…" past `width` points (the hover popup shows the whole name)
fn one_line(label: &str, width: f32, color: Color32) -> egui::text::LayoutJob {
let mut job = egui::text::LayoutJob::single_section(label.to_string(), egui::TextFormat::simple(egui::FontId::proportional(LABEL_FONT_SIZE), color));
job.wrap = egui::text::TextWrapping::truncate_at_width(width);
job
}
/// Start rendering during the popup delay once the pointer rests
@@ -689,3 +633,25 @@ fn hover_preview(ui: &mut Ui, small: Option<&egui::TextureHandle>, big: Option<&
ui.label(label);
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_long_label_stays_on_one_line_ending_in_an_ellipsis() {
let width = 60.0;
let mut laid_out = None;
let mut output = egui::Context::default().run_ui(egui::RawInput::default(), |ui| {
laid_out = Some(ui.painter().layout_job(one_line("Steel Painted Rust Leaks Extra", width, Color32::WHITE)));
});
// The font atlas upload is not under test
output.textures_delta.clear();
let galley = laid_out.unwrap();
assert_eq!(galley.rows.len(), 1);
assert!(galley.size().x <= width);
assert_eq!(galley.rows[0].glyphs.last().map(|glyph| glyph.chr), Some('…'));
}
}
+270
View File
@@ -0,0 +1,270 @@
//! One asset on the shelf: its name, the tab it belongs to, and how it previews, drags and applies
use std::path::PathBuf;
use serde_json::json;
use texturecraft_engine::Session;
use texturecraft_engine::core::ProceduralKind;
use texturecraft_engine::core::project::ENVIRONMENTS;
use texturecraft_engine::filter_lib::{FILTERS, FilterDef};
use texturecraft_engine::materials::{MATERIALS, SmartMaterial};
use texturecraft_engine::paint::alphas::{self, LibraryAlpha};
use texturecraft_engine::paint::presets::{BrushPreset, PRESETS};
use texturecraft_engine::smart_masks::{SMART_MASKS, SmartMask};
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::shelf::{Asset, Tab, apply};
use crate::shelf_preview::ShelfPreview;
/// The name of a saved brush whose file name isn't text
const SAVED_BRUSH_NAME: &str = "brush";
/// Probes per side of the grid that compares a procedural under two seeds, off the pattern's grid lines
const SEED_PROBES: usize = 4;
const SEED_PROBE_OFFSET: f32 = 0.13;
/// A smaller difference between the two seeds' samples is rounding
const SEED_TOLERANCE: f32 = 1e-4;
/// The libraries' ids: the open project's images, the built-in assets, the user's saved assets
pub(crate) const PROJECT: &str = "project";
pub(crate) const STARTER: &str = "starter";
pub(crate) const USER: &str = "user";
/// The libraries in the picker's order: id and (English, translated where shown) name
pub(crate) const LIBRARIES: [(&str, &str); 3] = [(PROJECT, "Project"), (STARTER, "Starter assets"), (USER, "Your assets")];
/// A shelf tile's asset
pub(crate) enum ShelfEntry {
Material(&'static SmartMaterial),
SmartMask(&'static SmartMask),
Filter(&'static FilterDef),
Brush(&'static BrushPreset),
/// A brush preset file the user saved
SavedBrush(PathBuf),
Alpha(&'static LibraryAlpha),
Procedural(ProceduralKind),
/// A built-in lighting environment, by name
Environment(&'static str),
/// An image resource of the project, by name
Image(String),
}
impl ShelfEntry {
/// Every built-in asset, the user's saved brushes and the project's images
pub(crate) fn all(app: &TextureCraftApp) -> Vec<ShelfEntry> {
let built_in = MATERIALS
.iter()
.map(ShelfEntry::Material)
.chain(SMART_MASKS.iter().map(ShelfEntry::SmartMask))
.chain(FILTERS.iter().map(ShelfEntry::Filter))
.chain(PRESETS.iter().map(ShelfEntry::Brush))
.chain(alphas::library().iter().map(ShelfEntry::Alpha))
.chain(ProceduralKind::ALL.into_iter().map(ShelfEntry::Procedural))
.chain(ENVIRONMENTS.into_iter().map(ShelfEntry::Environment));
let saved = app.brushes.iter().flatten().cloned().map(ShelfEntry::SavedBrush);
let images = app.session.doc.resources.keys().filter(|name| app.session.images.contains_key(*name)).cloned().map(ShelfEntry::Image);
built_in.chain(saved).chain(images).collect()
}
/// The tab that lists the asset
pub(crate) fn tab(&self) -> Tab {
match self {
ShelfEntry::Material(material) if material.smart => Tab::Smart,
ShelfEntry::Material(_) => Tab::Materials,
ShelfEntry::SmartMask(_) => Tab::Masks,
ShelfEntry::Filter(_) => Tab::Filters,
ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) => Tab::Brushes,
ShelfEntry::Alpha(_) => Tab::Alphas,
ShelfEntry::Procedural(_) => Tab::Textures,
ShelfEntry::Environment(_) => Tab::Environments,
ShelfEntry::Image(_) => Tab::Textures,
}
}
/// The asset's identity across frames: its kind and id
pub(crate) fn identity(&self) -> (&'static str, &str) {
match self {
ShelfEntry::Material(material) => ("material", material.id),
ShelfEntry::SmartMask(mask) => ("mask", mask.id),
ShelfEntry::Filter(filter) => ("filter", filter.id),
ShelfEntry::Brush(preset) => ("brush", preset.id),
ShelfEntry::SavedBrush(path) => ("saved-brush", path.to_str().unwrap_or_default()),
ShelfEntry::Alpha(alpha) => ("alpha", &alpha.id),
ShelfEntry::Procedural(kind) => ("procedural", kind.label()),
ShelfEntry::Environment(name) => ("environment", name),
ShelfEntry::Image(name) => ("image", name),
}
}
/// Where the asset lives: its library id ([`LIBRARIES`]), its type's folder, then its category if it has one (names in English, shown through `tr`)
pub(crate) fn path(&self) -> Vec<&str> {
let (library, folder, category) = match self {
ShelfEntry::Material(material) if material.smart => (STARTER, "Smart materials", Some(material.category)),
ShelfEntry::Material(material) => (STARTER, "Materials", Some(material.category)),
ShelfEntry::SmartMask(_) => (STARTER, "Smart masks", None),
ShelfEntry::Filter(filter) => (STARTER, "Filters", Some(filter.group)),
ShelfEntry::Brush(preset) => (STARTER, "Brushes", Some(preset.category)),
ShelfEntry::SavedBrush(_) => (USER, "Brushes", None),
ShelfEntry::Alpha(alpha) => (STARTER, "Alphas", Some(alpha.category)),
ShelfEntry::Procedural(_) => (STARTER, "Procedurals", None),
ShelfEntry::Environment(_) => (STARTER, "Environments", None),
ShelfEntry::Image(_) => (PROJECT, "Textures", None),
};
[library, folder].into_iter().chain(category).collect()
}
/// Whether the asset is in folder `path` (a library id, then folder names) or below it
pub(crate) fn in_folder(&self, path: &[String]) -> bool {
let own = self.path();
path.len() <= own.len() && path.iter().zip(own).all(|(wanted, have)| wanted == have)
}
/// The name under the tile, translated where the asset's name is
pub(crate) fn label(&self) -> &str {
match self {
ShelfEntry::Material(material) => material.label,
ShelfEntry::SavedBrush(path) => path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_BRUSH_NAME),
ShelfEntry::SmartMask(mask) => mask.label,
ShelfEntry::Filter(filter) => tr(filter.label),
ShelfEntry::Brush(preset) => preset.label,
ShelfEntry::Alpha(alpha) => &alpha.label,
ShelfEntry::Procedural(kind) => tr(kind.label()),
ShelfEntry::Environment(name) => name,
ShelfEntry::Image(name) => name,
}
}
/// Whether `filter` (lowercase) matches the asset's name, id or category, in English or translated
pub(crate) fn matches(&self, filter: &str) -> bool {
let texts: &[&str] = match self {
ShelfEntry::Material(material) => &[material.label, material.category, material.id],
ShelfEntry::SavedBrush(_) => &[self.label()],
ShelfEntry::SmartMask(mask) => &[mask.label, mask.id],
ShelfEntry::Filter(filter) => &[filter.label, filter.group, filter.id, tr(filter.label), tr(filter.group)],
ShelfEntry::Brush(preset) => &[preset.label, preset.category, preset.id],
ShelfEntry::Alpha(alpha) => &[&alpha.label, alpha.category, &alpha.id],
ShelfEntry::Procedural(kind) => &[kind.label(), tr(kind.label())],
ShelfEntry::Environment(name) => &[name],
ShelfEntry::Image(name) => &[name],
};
crate::shelf::matches(filter, texts)
}
/// The thumbnail, or None while it renders
pub(crate) fn thumbnail(&self, app: &mut TextureCraftApp, ctx: &egui::Context) -> Option<egui::TextureHandle> {
match self {
ShelfEntry::Material(material) => app.thumbs.material(ctx, material.id),
ShelfEntry::SmartMask(mask) => app.thumbs.smart_mask(ctx, mask.id),
ShelfEntry::Filter(filter) => app.thumbs.filter(ctx, filter.id),
ShelfEntry::Brush(preset) => app.thumbs.brush_preset(ctx, preset),
ShelfEntry::SavedBrush(path) => app.thumbs.saved_brush(ctx, path, &app.session.images),
ShelfEntry::Alpha(alpha) => app.thumbs.alpha(ctx, alpha),
ShelfEntry::Procedural(kind) => app.thumbs.procedural(ctx, *kind),
ShelfEntry::Environment(name) => app.thumbs.environment(ctx, name),
ShelfEntry::Image(name) => {
let image = app.session.images.get(name).cloned()?;
Some(app.thumbs.image(ctx, name, &image))
}
}
}
/// What the hover popup renders; None for an image that is gone
pub(crate) fn preview(&self, session: &Session) -> Option<ShelfPreview> {
Some(match self {
ShelfEntry::Material(material) => ShelfPreview::material(material.id),
ShelfEntry::SmartMask(mask) => ShelfPreview::SmartMask(mask.id),
ShelfEntry::Filter(filter) => ShelfPreview::Filter(filter.id),
ShelfEntry::Brush(preset) => ShelfPreview::Brush(preset),
ShelfEntry::SavedBrush(path) => ShelfPreview::saved_brush(path, &session.images),
ShelfEntry::Alpha(alpha) => ShelfPreview::Alpha(alpha),
ShelfEntry::Procedural(kind) => ShelfPreview::Procedural(*kind),
ShelfEntry::Environment(name) => ShelfPreview::Environment(name),
ShelfEntry::Image(name) => ShelfPreview::Image(name.clone(), session.images.get(name).cloned()?),
})
}
/// The drag payload's asset; brushes and procedurals don't drag
pub(crate) fn asset(&self) -> Option<Asset> {
match self {
ShelfEntry::Material(material) => Some(Asset::Material(material.id)),
ShelfEntry::SmartMask(mask) => Some(Asset::SmartMask(mask.id)),
ShelfEntry::Filter(filter) => Some(Asset::Filter(filter.id)),
ShelfEntry::Alpha(alpha) => Some(Asset::Alpha(&alpha.id)),
ShelfEntry::Image(name) => Some(Asset::Texture(name.clone())),
ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) | ShelfEntry::Procedural(_) | ShelfEntry::Environment(_) => None,
}
}
/// Whether the tile is outlined as in use: the brush's library alpha, the shown environment
pub(crate) fn in_use(&self, app: &TextureCraftApp) -> bool {
match self {
ShelfEntry::Alpha(alpha) => {
let brush = &app.session.tool.brush;
brush.alpha_image.is_none() && brush.alpha_library.as_deref() == Some(alpha.id.as_str())
}
ShelfEntry::Environment(name) => app.session.doc.project.display.environment == *name,
_ => false,
}
}
/// Whether applying the asset gives a different result per random seed (the tile's dots badge)
pub(crate) fn includes_randomness(&self) -> bool {
match self {
ShelfEntry::Procedural(kind) => SEEDED_PROCEDURALS.contains(kind),
_ => false,
}
}
/// What a click on the tile does
pub(crate) fn activate(&self, app: &mut TextureCraftApp) {
match self {
ShelfEntry::Brush(preset) => {
app.run("brush.preset.apply", json!({"preset": preset.id}));
}
ShelfEntry::SavedBrush(path) => {
app.run("brush.preset.load", json!({"path": path.display().to_string()}));
}
ShelfEntry::Procedural(kind) => {
app.run("layer.add.fill", json!({"name": kind.label()}));
app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": kind.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]}));
}
ShelfEntry::Environment(name) => {
app.run("display.set", json!({"environment": name}));
}
entry => {
if let Some(asset) = entry.asset() {
apply(app, &asset);
}
}
}
}
}
/// The procedurals whose pattern depends on the seed, worked out once
static SEEDED_PROCEDURALS: std::sync::LazyLock<Vec<ProceduralKind>> =
std::sync::LazyLock::new(|| ProceduralKind::ALL.into_iter().filter(|kind| seed_changes(*kind)).collect());
/// Whether procedural `kind` samples differently under two seeds
fn seed_changes(kind: ProceduralKind) -> bool {
use texturecraft_engine::compose::pattern::{Coords, procedural};
use texturecraft_engine::core::{Procedural, Projection};
use texturecraft_engine::geom::glam::{Vec2, Vec3};
let sample = |seed: u32, i: usize| {
let uv = Vec2::new((i % SEED_PROBES) as f32 / SEED_PROBES as f32, (i / SEED_PROBES) as f32 / SEED_PROBES as f32) + SEED_PROBE_OFFSET;
procedural(&Procedural { seed, ..Procedural::new(kind) }, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y })
};
(0..SEED_PROBES * SEED_PROBES).any(|i| (sample(1, i) - sample(2, i)).abs() > SEED_TOLERANCE)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_seeded_procedurals_include_randomness() {
let seeded = &*SEEDED_PROCEDURALS;
assert!(seeded.contains(&ProceduralKind::Clouds), "{seeded:?}");
assert!(!seeded.contains(&ProceduralKind::Checker), "{seeded:?}");
}
}
+95
View File
@@ -0,0 +1,95 @@
//! The shelf's library folders ([`ShelfEntry::path`]) for the breadcrumb above the search and the Filter by path tree
use std::collections::BTreeSet;
use egui::{RichText, Ui};
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::shelf_entry::{LIBRARIES, ShelfEntry};
use crate::theme::Tokens;
use crate::widgets::icon_button;
/// The breadcrumb arrows' size relative to an icon button
const ARROW_SCALE: f32 = 0.8;
/// The folder paths of `entries`, each a library id then folder names
pub(crate) fn paths<'a>(entries: impl IntoIterator<Item = &'a ShelfEntry>) -> Vec<Vec<String>> {
let unique_paths: BTreeSet<Vec<&str>> = entries.into_iter().map(ShelfEntry::path).collect();
unique_paths.into_iter().map(|segments| segments.into_iter().map(str::to_string).collect()).collect()
}
/// `paths` and every library, even one with nothing in it (the picker always lists them all)
pub(crate) fn with_every_library(mut paths: Vec<Vec<String>>) -> Vec<Vec<String>> {
paths.extend(LIBRARIES.iter().map(|(id, _)| vec![id.to_string()]));
paths.sort();
paths.dedup();
paths
}
/// The folders right below `prefix` (libraries in their usual order, folders by name)
pub(crate) fn children(paths: &[Vec<String>], prefix: &[String]) -> Vec<String> {
let mut children = Vec::new();
for path in paths.iter().filter(|path| path.len() > prefix.len() && path.starts_with(prefix)) {
if let Some(child) = path.get(prefix.len())
&& !children.contains(child)
{
children.push(child.clone());
}
}
if prefix.is_empty() {
children.sort_by_key(|library| LIBRARIES.iter().position(|(id, _)| id == library));
}
children
}
/// A folder's shown name: libraries by their name, folders (type and category names) translated
pub(crate) fn name(level: usize, segment: &str) -> &str {
match LIBRARIES.iter().find(|(id, _)| *id == segment) {
Some((_, library)) if level == 0 => tr(library),
_ => tr(segment),
}
}
/// "› All libraries › …": each arrow lists the folders at its level, the names are plain text, a last arrow lists the folders inside
pub(crate) fn breadcrumb(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec<String>]) {
let tokens = Tokens::get(ui.ctx());
let size = ui.spacing().interact_size.y * ARROW_SCALE;
let mut picked: Option<Vec<String>> = None;
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = ui.spacing().item_spacing.x * 0.5;
let path = app.ui.shelf_path.clone();
for level in 0..=path.len() {
let options = children(paths, &path[..level]);
if level > 0 && options.is_empty() {
break;
}
let current = path.get(level);
let response = icon_button(ui, egui_phosphor::regular::CARET_RIGHT, tr("Browse folders"), false, size);
egui::Popup::menu(&response).show(|ui| {
if level == 0 && ui.selectable_label(current.is_none(), tr("All libraries")).clicked() {
picked = Some(Vec::new());
}
for option in &options {
if ui.selectable_label(current == Some(option), name(level, option)).clicked() {
picked = Some(path[..level].iter().cloned().chain([option.clone()]).collect());
}
}
});
let shown = match current {
Some(segment) => name(level, segment),
None if level == 0 => tr("All libraries"),
None => continue,
};
ui.label(RichText::new(shown).strong().color(tokens.text_strong));
}
});
if let Some(path) = picked {
app.ui.shelf_path = path;
}
}
+175
View File
@@ -0,0 +1,175 @@
//! The shelf's side panes left of the grid, toggled from the toolbar: saved searches and the folder tree
use egui::{RichText, Ui};
use egui_phosphor::regular as ic;
use serde::{Deserialize, Serialize};
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::saved_search::SavedSearch;
use crate::shelf::TABS;
use crate::theme::Tokens;
use crate::widgets::icon_button;
/// The panes' column width as a fraction of the panel, and its least width in points
const COLUMN_FRACTION: f32 = 0.45;
const COLUMN_MIN_WIDTH: f32 = 110.0;
/// Maximum share of the column used by saved searches while both panes are open
const SAVED_SEARCHES_HEIGHT_FRACTION: f32 = 0.45;
/// The pane header's caption size in points
const HEADER_SIZE: f32 = 10.0;
/// Which side panes are open
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShelfPanes {
pub saved_searches: bool,
pub filter_by_path: bool,
/// Filter by path lists only the folders with assets matching the search and tab
pub hide_non_applicable: bool,
}
/// The toolbar's buttons that open and close the panes
pub(crate) fn toggles(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) {
let panes = &mut app.ui.shelf_panes;
if icon_button(ui, ic::BOOKMARKS_SIMPLE, tr("Saved searches"), panes.saved_searches, size).clicked() {
panes.saved_searches = !panes.saved_searches;
}
if icon_button(ui, ic::TREE_STRUCTURE, tr("Filter by path"), panes.filter_by_path, size).clicked() {
panes.filter_by_path = !panes.filter_by_path;
}
}
/// The width of the panes' column in a panel `width` wide, or None while no pane is open
pub(crate) fn column_width(app: &TextureCraftApp, width: f32) -> Option<f32> {
let panes = &app.ui.shelf_panes;
(panes.saved_searches || panes.filter_by_path).then(|| (width * COLUMN_FRACTION).max(COLUMN_MIN_WIDTH).min(width))
}
/// The open panes, top to bottom; the tree shows `paths`, or `applicable` while it hides folders with nothing matching
pub(crate) fn column(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec<String>], applicable: &[Vec<String>]) {
// Names past the narrow column end in "…" rather than breaking mid-word
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
if app.ui.shelf_panes.saved_searches {
saved_searches(app, ui);
}
if app.ui.shelf_panes.filter_by_path {
if app.ui.shelf_panes.saved_searches {
ui.separator();
}
let shown = if app.ui.shelf_panes.hide_non_applicable { applicable } else { paths };
filter_by_path(app, ui, shown);
}
}
/// "All libraries", then each library's folders as a tree; a click shows that folder
fn filter_by_path(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec<String>]) {
let size = ui.spacing().interact_size.y;
header(ui, tr("Filter by path"), |ui| {
let hiding = app.ui.shelf_panes.hide_non_applicable;
if icon_button(ui, ic::EYE_SLASH, tr("Hide non-applicable folders"), hiding, size).clicked() {
app.ui.shelf_panes.hide_non_applicable = !hiding;
}
});
let mut picked = None;
egui::ScrollArea::vertical().id_salt("shelf_path_tree").auto_shrink([false, true]).show(ui, |ui| {
if ui.selectable_label(app.ui.shelf_path.is_empty(), tr("All libraries")).clicked() {
picked = Some(Vec::new());
}
folders(ui, paths, &[], &app.ui.shelf_path, &mut picked);
});
if let Some(path) = picked {
app.ui.shelf_path = path;
}
}
/// The folders below `prefix`: one with folders inside opens and closes, a click on a name picks it
fn folders(ui: &mut Ui, paths: &[Vec<String>], prefix: &[String], current: &[String], picked: &mut Option<Vec<String>>) {
for child in crate::shelf_folders::children(paths, prefix) {
let path: Vec<String> = prefix.iter().cloned().chain([child.clone()]).collect();
let name = crate::shelf_folders::name(prefix.len(), &child);
let selected = current == path.as_slice();
if crate::shelf_folders::children(paths, &path).is_empty() {
ui.indent(("shelf_path_leaf", &path), |ui| {
if ui.selectable_label(selected, name).clicked() {
*picked = Some(path.clone());
}
});
continue;
}
let id = ui.make_persistent_id(("shelf_path", &path));
let open_by_default = current.starts_with(&path);
egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, open_by_default)
.show_header(ui, |ui| {
if ui.selectable_label(selected, name).clicked() {
*picked = Some(path.clone());
}
})
.body(|ui| folders(ui, paths, &path, current, picked));
}
}
/// A pane's caption with a button at its right
fn header(ui: &mut Ui, title: &str, button: impl FnOnce(&mut Ui)) {
let tokens = Tokens::get(ui.ctx());
ui.horizontal(|ui| {
ui.label(RichText::new(title.to_uppercase()).size(HEADER_SIZE).color(tokens.text_dim));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), button);
});
}
/// "All", then the saved queries; the header's button saves the current one, a right-click deletes one
fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) {
let size = ui.spacing().interact_size.y;
let current = current_query(app);
header(ui, tr("Saved searches"), |ui| {
if icon_button(ui, ic::FLOPPY_DISK, tr("Save the current search"), false, size).clicked() && !app.ui.shelf_saved_searches.contains(&current) {
app.ui.shelf_saved_searches.push(current.clone());
}
});
let everything = current.filter.is_empty() && current.path.is_empty() && current.tab == crate::shelf_tabs::NO_TYPE;
if ui.selectable_label(everything, tr("All")).clicked() {
crate::shelf_toolbar::reset_query(app);
}
let mut deleted = None;
let max_height = if app.ui.shelf_panes.filter_by_path { ui.available_height() * SAVED_SEARCHES_HEIGHT_FRACTION } else { ui.available_height() };
let row_height = ui.spacing().interact_size.y;
let total_rows = app.ui.shelf_saved_searches.len();
egui::ScrollArea::vertical().id_salt("shelf_saved_searches").max_height(max_height).show_rows(ui, row_height, total_rows, |ui, visible_rows| {
for i in visible_rows {
let Some(saved) = app.ui.shelf_saved_searches.get(i) else { continue };
let same = saved.filter == current.filter && saved.tab == current.tab && saved.path == current.path;
let response = ui.selectable_label(same, &saved.name);
if response.clicked() {
(app.ui.shelf_filter, app.ui.shelf_tab, app.ui.shelf_path) = (saved.filter.clone(), saved.tab, saved.path.clone());
}
response.context_menu(|ui| {
if ui.button(tr("Delete")).clicked() {
deleted = Some(i);
ui.close();
}
});
}
});
if let Some(i) = deleted {
app.ui.shelf_saved_searches.remove(i);
}
}
/// The shelf's query, named after its search text, else its folder, else its tab
fn current_query(app: &TextureCraftApp) -> SavedSearch {
let (filter, tab, path) = (app.ui.shelf_filter.clone(), app.ui.shelf_tab, app.ui.shelf_path.clone());
let name = if !filter.is_empty() {
filter.clone()
} else if let Some(folder) = path.last() {
crate::shelf_folders::name(path.len() - 1, folder).to_string()
} else {
TABS.get(tab).map_or(tr("All"), |(_, _, label)| tr(label)).to_string()
};
SavedSearch { name, filter, tab, path }
}
+61 -2
View File
@@ -1,9 +1,11 @@
//! Shelf assets and their preview renderers
use std::path::PathBuf;
use std::sync::Arc;
use egui::ColorImage;
use texturecraft_engine::compose::ImageRes;
use texturecraft_engine::compose::ImageStore;
use texturecraft_engine::core::ProceduralKind;
use texturecraft_engine::materials;
use texturecraft_engine::paint::BrushSettings;
@@ -11,9 +13,14 @@ use texturecraft_engine::paint::alphas::LibraryAlpha;
use texturecraft_engine::paint::presets::BrushPreset;
use texturecraft_engine::preview;
use crate::preview_image::{alpha_image, image_preview, procedural_image, sphere_image, stroke_preview};
use crate::preview_image::{alpha_image, environment_image, image_preview, procedural_image, sphere_image, stroke_preview};
/// Larger brush preset files aren't read (the `brush.preset.load` command's limit)
#[cfg(not(target_arch = "wasm32"))]
const MAX_SAVED_BRUSH_BYTES: u64 = 1 << 20;
/// The asset a shelf tile previews
#[derive(Clone)]
pub enum ShelfPreview {
/// A built-in plain material on a sphere
Material(&'static str),
@@ -29,11 +36,22 @@ pub enum ShelfPreview {
Alpha(&'static LibraryAlpha),
/// A brush preset's stroke along an S curve
Brush(&'static BrushPreset),
/// A brush preset file the user saved, its stroke along an S curve
SavedBrush { path: PathBuf, settings: Option<BrushSettings>, image: Option<Arc<ImageRes>> },
/// An image resource by name
Image(String, Arc<ImageRes>),
/// A built-in lighting environment's panorama
Environment(&'static str),
}
impl ShelfPreview {
/// Resolve a saved brush's image alpha while the project images are available
pub fn saved_brush(path: &std::path::Path, images: &ImageStore) -> Self {
let settings = read_saved_brush(path);
let image = settings.as_ref().and_then(|brush| brush.alpha_image.as_ref()).and_then(|name| images.get(name)).cloned();
ShelfPreview::SavedBrush { path: path.to_path_buf(), settings, image }
}
/// Smart materials preview on the orb, plain materials on a sphere
pub fn material(id: &'static str) -> ShelfPreview {
match materials::find(id) {
@@ -52,7 +70,9 @@ impl ShelfPreview {
ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"),
ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id),
ShelfPreview::Brush(preset) => format!("brush:{}", preset.id),
ShelfPreview::SavedBrush { path, .. } => format!("saved-brush:{}", path.display()),
ShelfPreview::Image(name, _) => format!("image:{name}"),
ShelfPreview::Environment(name) => format!("environment:{name}"),
}
}
@@ -65,12 +85,39 @@ impl ShelfPreview {
ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)),
ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)),
ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)),
ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size)),
ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size, None)),
ShelfPreview::SavedBrush { settings, image, .. } => {
let settings = settings.as_ref()?;
if settings.alpha_image.is_some() && image.is_none() {
return None;
}
Some(stroke_preview(settings, size, image.as_deref()))
}
ShelfPreview::Image(_, image) => Some(image_preview(image, size)),
ShelfPreview::Environment(name) => Some(environment_image(name, size)),
}
}
}
/// A saved brush preset's settings; None when the file can't be read (or in the browser, which has no files)
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn read_saved_brush(path: &std::path::Path) -> Option<BrushSettings> {
use std::io::Read as _;
let mut bytes = Vec::new();
std::fs::File::open(path).and_then(|file| file.take(MAX_SAVED_BRUSH_BYTES + 1).read_to_end(&mut bytes)).ok()?;
if bytes.len() as u64 > MAX_SAVED_BRUSH_BYTES {
return None;
}
serde_json::from_slice::<BrushSettings>(&bytes).ok().map(|settings| settings.sanitized())
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn read_saved_brush(_: &std::path::Path) -> Option<BrushSettings> {
None
}
#[cfg(test)]
mod tests {
use texturecraft_engine::filter_lib::FILTERS;
@@ -93,6 +140,7 @@ mod tests {
ShelfPreview::Alpha(&alphas::library()[0]),
ShelfPreview::Brush(&PRESETS[0]),
ShelfPreview::Image("image".into(), Arc::new(image)),
ShelfPreview::Environment(texturecraft_engine::core::project::ENVIRONMENTS[0]),
];
for preview in previews {
let key = preview.key();
@@ -117,4 +165,15 @@ mod tests {
assert_eq!(on_the_orb, material.smart, "{}", material.id);
}
}
#[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 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)));
let missing = ShelfPreview::SavedBrush { path: PathBuf::from("brush.tcbrush"), settings: Some(settings), image: None };
assert!(missing.image(64).is_none());
}
}
+72
View File
@@ -0,0 +1,72 @@
//! The shelf's type row: one icon per type (none picked shows every type), greyed without matches, one dropdown when narrow
use egui::{Ui, vec2};
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::shelf::{TABS, Tab};
use crate::widgets::{icon_button, icon_dropdown_button};
/// The gap between the row's icons in points
const ICON_GAP: f32 = 2.0;
/// The size of the dot that marks the collapsed row's dropdown while a type is picked, in points
const FILTER_DOT_RADIUS: f32 = 2.5;
/// `app.ui.shelf_tab` while no type is picked: every type shows
pub(crate) const NO_TYPE: usize = TABS.len();
/// The row, then `trailing` at its right end; `counts[i]` is how many assets of `TABS[i]` match the search
pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui, counts: &[usize], trailing: impl FnOnce(&mut TextureCraftApp, &mut Ui, f32)) {
let size = ui.spacing().interact_size.y;
// The type icons and one icon after them
let row_width = (TABS.len() + 1) as f32 * (size + ICON_GAP);
let mut picked = app.ui.shelf_tab.min(NO_TYPE);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing = vec2(ICON_GAP, ICON_GAP);
if ui.available_width() >= row_width {
for (i, (_, icon, label)) in TABS.iter().enumerate() {
// The picked type stays clickable so it can be unpicked
let empty = i != picked && counts.get(i).is_none_or(|count| *count == 0);
if ui.add_enabled_ui(!empty, |ui| icon_button(ui, icon, tr(label), i == picked, size)).inner.clicked() {
picked = if i == picked { NO_TYPE } else { i };
}
}
} else {
collapsed(ui, &mut picked, counts, size);
}
let rest = ui.available_width() - size;
ui.add_space(rest.max(0.0));
trailing(app, ui, size);
});
app.ui.shelf_tab = picked;
}
/// One dropdown listing the types, dotted while one is picked
fn collapsed(ui: &mut Ui, picked: &mut usize, counts: &[usize], size: f32) {
let filtering = *picked != NO_TYPE;
let response = icon_dropdown_button(ui, egui_phosphor::regular::FUNNEL_SIMPLE, tr("Filter by type"), filtering, size);
let response = response.on_hover_text(tr("Filter by type"));
if filtering {
let tokens = crate::theme::Tokens::get(ui.ctx());
let dot = response.rect.left_top() + vec2(size - FILTER_DOT_RADIUS, FILTER_DOT_RADIUS);
ui.painter().circle_filled(dot, FILTER_DOT_RADIUS, tokens.accent);
}
egui::Popup::menu(&response).show(|ui| {
for (i, (_, icon, label)) in TABS.iter().enumerate() {
let empty = i != *picked && counts.get(i).is_none_or(|count| *count == 0);
if ui.add_enabled(!empty, egui::Button::selectable(i == *picked, format!("{icon} {}", tr(label)))).clicked() {
*picked = if i == *picked { NO_TYPE } else { i };
ui.close();
}
}
});
}
/// Whether `tab` (an index into [`TABS`], or [`NO_TYPE`]) shows assets of type `kind`
pub(crate) fn shows(tab: usize, kind: Tab) -> bool {
TABS.get(tab).is_none_or(|(shown, _, _)| *shown == kind)
}
+50
View File
@@ -0,0 +1,50 @@
//! The shelf's bottom toolbar: the side pane toggles on the left; refresh, reset query and import on the right
use egui::Ui;
use egui_phosphor::regular as ic;
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::widgets::icon_button;
/// The gap above the toolbar in points
const GAP_ABOVE: f32 = 4.0;
/// The toolbar's height for a `ui` (one icon button and the gap above it)
pub(crate) fn height(ui: &Ui) -> f32 {
ui.spacing().interact_size.y + GAP_ABOVE
}
/// The toolbar
pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
let size = ui.spacing().interact_size.y;
ui.add_space(GAP_ABOVE);
ui.horizontal(|ui| {
crate::shelf_panes::toggles(app, ui, size);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if icon_button(ui, ic::PLUS, tr("Import resources..."), false, size).clicked() {
crate::menus::invoke(app, &ui.ctx().clone(), "resource.import");
}
if icon_button(ui, ic::X_CIRCLE, tr("Reset query"), false, size).clicked() {
reset_query(app);
}
if icon_button(ui, ic::ARROWS_CLOCKWISE, tr("Refresh"), false, size).clicked() {
refresh(app);
}
});
});
}
/// Show every asset again: no search, no type picked, all libraries
pub(crate) fn reset_query(app: &mut TextureCraftApp) {
app.ui.shelf_filter.clear();
app.ui.shelf_tab = crate::shelf_tabs::NO_TYPE;
app.ui.shelf_path.clear();
}
/// Read the user's saved assets from disk again and redraw their thumbnails
fn refresh(app: &mut TextureCraftApp) {
app.library = None;
app.brushes = None;
app.thumbs.forget_saved_files();
}
+83
View File
@@ -0,0 +1,83 @@
//! How the shelf shows its assets: small, medium or large tiles, or a list (the menu at the type row's end)
use egui::{Rect, Ui, Vec2, vec2};
use egui_phosphor::regular as ic;
use serde::{Deserialize, Serialize};
use crate::TextureCraftApp;
use crate::grid_tile::GridTile;
use crate::i18n::tr;
use crate::widgets::icon_button;
/// A list row's height and its thumbnail's size, in points
const LIST_ROW_HEIGHT: f32 = 30.0;
const LIST_THUMBNAIL_SIZE: f32 = 26.0;
/// The gap between a list row's thumbnail and its name, in points
pub(crate) const LIST_NAME_GAP: f32 = 6.0;
/// The shelf's tile size, or the list
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum ShelfView {
Small,
/// A 68 x 78 grid step, as in the reference
#[default]
Medium,
Large,
List,
}
/// The views in the menu's order: icon and (English, translated where shown) name
const VIEWS: [(ShelfView, &str, &str); 4] = [
(ShelfView::Small, ic::GRID_NINE, "Small"),
(ShelfView::Medium, ic::GRID_FOUR, "Medium"),
(ShelfView::Large, ic::SQUARE, "Large"),
(ShelfView::List, ic::LIST, "List"),
];
impl ShelfView {
/// A grid tile's measurements; None for the list
fn grid(self) -> Option<GridTile> {
match self {
ShelfView::Small => Some(GridTile { width: 50.0, height: 58.0, thumbnail_size: 44.0, thumbnail_center_y: 23.0 }),
ShelfView::Medium => Some(GridTile { width: 66.0, height: 76.0, thumbnail_size: 60.0, thumbnail_center_y: 31.0 }),
ShelfView::Large => Some(GridTile { width: 88.0, height: 100.0, thumbnail_size: 82.0, thumbnail_center_y: 42.0 }),
ShelfView::List => None,
}
}
/// A tile's size in a grid `width` points wide (a list row spans it)
pub(crate) fn tile_size(self, width: f32) -> Vec2 {
match self.grid() {
Some(tile) => vec2(tile.width, tile.height),
None => vec2(width.max(LIST_ROW_HEIGHT), LIST_ROW_HEIGHT),
}
}
/// Where the thumbnail goes in the tile `rect`
pub(crate) fn thumbnail_rect(self, rect: Rect) -> Rect {
match self.grid() {
Some(tile) => Rect::from_center_size(rect.center_top() + vec2(0.0, tile.thumbnail_center_y), vec2(tile.thumbnail_size, tile.thumbnail_size)),
None => Rect::from_center_size(rect.left_center() + vec2(LIST_ROW_HEIGHT * 0.5, 0.0), vec2(LIST_THUMBNAIL_SIZE, LIST_THUMBNAIL_SIZE)),
}
}
/// Whether the name sits right of the thumbnail (a list) rather than under it
pub(crate) fn name_beside(self) -> bool {
self == ShelfView::List
}
}
/// The view menu button: its icon is the current view's
pub(crate) fn menu(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) {
let current = app.ui.shelf_view;
let icon = VIEWS.iter().find(|(view, _, _)| *view == current).map_or(ic::GRID_FOUR, |(_, icon, _)| icon);
let response = icon_button(ui, icon, tr("Thumbnail size"), false, size);
egui::Popup::menu(&response).show(|ui| {
for (view, icon, label) in VIEWS {
if ui.selectable_label(view == current, format!("{icon} {}", tr(label))).clicked() {
app.ui.shelf_view = view;
ui.close();
}
}
});
}
+41 -4
View File
@@ -5,6 +5,9 @@ use texturecraft_engine::core::{BakedMap, Channel, NormalFormat};
use crate::docking::Dock;
use crate::keymap::Keymap;
use crate::saved_search::SavedSearch;
use crate::shelf_panes::ShelfPanes;
use crate::shelf_view::ShelfView;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum Mode {
@@ -297,9 +300,21 @@ pub struct UiState {
/// Channel whose blending the layer rows show.
pub layer_channel: Channel,
pub shelf_filter: String,
/// The asset shelf's open tab.
/// The asset shelf's picked type: an index into the shelf's types, or past them for every type
#[serde(default)]
pub shelf_tab: usize,
/// The asset shelf's library folder: a library id, then folder names (empty: all libraries)
#[serde(default)]
pub shelf_path: Vec<String>,
/// The asset shelf's tile size, or its list
#[serde(default)]
pub shelf_view: ShelfView,
/// The asset shelf's open side panes
#[serde(default)]
pub shelf_panes: ShelfPanes,
/// The asset shelf's saved queries, in the order they were saved
#[serde(default)]
pub shelf_saved_searches: Vec<SavedSearch>,
pub props_tab: PropsTab,
#[serde(default)]
pub text: TextUi,
@@ -357,17 +372,21 @@ impl UiState {
self.bake_layout_version = BAKE_LAYOUT_VERSION;
}
/// Take `layout`'s panels, windows and view settings, keeping this state's dialogs, export
/// settings and recent files.
/// Take `layout`'s panels, windows and view settings, keeping this state's dialogs, settings, files and shelf query
pub fn adopt_layout(&mut self, layout: UiState) {
let keep = std::mem::replace(self, layout);
self.new_project = keep.new_project;
self.export = keep.export;
self.recent = keep.recent;
self.shelf_filter = keep.shelf_filter;
self.prefs = keep.prefs;
self.keymap = keep.keymap;
self.rename = None;
// The shelf's search, type and folder are one query, and saved searches are the user's own
self.shelf_filter = keep.shelf_filter;
self.shelf_tab = keep.shelf_tab;
self.shelf_path = keep.shelf_path;
self.shelf_saved_searches = keep.shelf_saved_searches;
}
}
@@ -390,6 +409,10 @@ impl Default for UiState {
layer_channel: Channel::BaseColor,
shelf_filter: String::new(),
shelf_tab: 0,
shelf_path: Vec::new(),
shelf_view: ShelfView::default(),
shelf_panes: ShelfPanes::default(),
shelf_saved_searches: Vec::new(),
props_tab: PropsTab::Brush,
text: TextUi::default(),
rename: None,
@@ -419,13 +442,27 @@ mod tests {
ui.keymap.insert("file.save".into(), "F5".into());
let mut layout = UiState::default();
layout.dock.close(crate::docking::Panel::Assets);
ui.adopt_layout(layout);
assert!(!ui.dock.is_open(crate::docking::Panel::Assets));
assert_eq!(ui.recent, vec!["a.tcraft".to_string()]);
assert_eq!(ui.export.preset, "Mine");
assert_eq!(ui.keymap.get("file.save").map(String::as_str), Some("F5"));
}
#[test]
fn adopting_a_layout_keeps_the_shelf_query_and_saved_searches() {
let saved = crate::saved_search::SavedSearch { name: "rust".into(), filter: "rust".into(), tab: 2, path: vec!["starter".into()] };
let mut ui = UiState { shelf_filter: "rust".into(), shelf_tab: 2, shelf_path: vec!["starter".into()], ..UiState::default() };
ui.shelf_saved_searches.push(saved.clone());
ui.adopt_layout(UiState::default());
assert_eq!((ui.shelf_filter.as_str(), ui.shelf_tab, ui.shelf_path.as_slice()), ("rust", 2, ["starter".to_string()].as_slice()));
assert_eq!(ui.shelf_saved_searches, [saved]);
}
#[test]
fn the_data_folder_is_an_absolute_choice_or_documents_texturecraft() {
let default = crate::data_folder("");
+207 -13
View File
@@ -3,13 +3,14 @@
//! Smart masks, smart materials and hover previews use [`PreviewWorker`]
use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Weak};
use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions};
use texturecraft_engine::compose::{ImageRes, ImageStore};
use texturecraft_engine::core::ProceduralKind;
use texturecraft_engine::paint::presets::BrushPreset;
use texturecraft_engine::paint::{BrushAlpha, alphas};
use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas};
use texturecraft_engine::texel::linear_to_srgb;
use crate::preview_image::{aces, image_preview, shade};
@@ -23,21 +24,30 @@ const PER_FRAME: usize = 2;
/// Shelf sphere and smart mask thumbnail size in pixels
const SPHERE_PX: usize = 72;
/// Shelf procedural swatch size in pixels
const PROCEDURAL_PX: usize = 56;
const PROCEDURAL_PX: usize = 64;
/// Shelf alpha and brush stroke swatch size in pixels
const SWATCH_PX: usize = 64;
/// Image resource preview size in pixels
const IMAGE_PX: usize = 64;
/// The [`ShelfPreview::key`] prefix of the user's saved files
const SAVED_FILE_KEY_PREFIX: &str = "saved-";
/// Largest stencil preview dimension in pixels
const STENCIL_MAX_SIZE_PX: f32 = 1024.0;
/// Big hover previews kept at most (the least recently shown go first)
const BIG_PREVIEWS_KEPT: usize = 32;
/// Parsed settings, weak image identity and preview revision for a saved brush
type SavedBrushCacheEntry = (Option<BrushSettings>, Option<Weak<ImageRes>>, u64);
/// The shelf's and the brush panel's preview textures
#[derive(Default)]
pub struct Thumbs {
/// Shelf thumbnails by [`ShelfPreview::key`]
shelf: HashMap<String, TextureHandle>,
/// Parsed settings, weak image identity and preview revision for each saved brush
saved_brush_previews: HashMap<PathBuf, SavedBrushCacheEntry>,
/// Refresh generation; queued results from earlier generations must not match new requests
saved_files_epoch: u64,
images: HashMap<String, (Weak<ImageRes>, TextureHandle)>,
images_revision: Option<u64>,
/// (frame, thumbnails rendered in it)
@@ -145,7 +155,7 @@ impl Thumbs {
fn worker_rendered(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize, hover: bool) -> Option<TextureHandle> {
self.receive(ctx);
let key = worker_key(&preview, size_px);
let key = self.worker_key(&preview, size_px);
if !self.rendered.contains_key(&key) && self.may_request(ctx) {
let queued = self.worker.request(ctx, PreviewRequest { key: key.clone(), preview, size_px, hover });
self.rendered.insert(key.clone(), if queued { WorkerPreview::Rendering } else { WorkerPreview::Failed });
@@ -194,7 +204,7 @@ impl Thumbs {
/// Request a hover preview and evict the least recently shown beyond the cache limit
pub fn big(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option<TextureHandle> {
let key = worker_key(&preview, size_px);
let key = self.worker_key(&preview, size_px);
self.big_shown.retain(|k| *k != key);
self.big_shown.push_back(key);
while self.big_shown.len() > BIG_PREVIEWS_KEPT {
@@ -209,7 +219,7 @@ impl Thumbs {
/// The big preview of `preview` if the worker already rendered it (requests nothing)
pub fn rendered_big(&mut self, ctx: &egui::Context, preview: &ShelfPreview, size_px: usize) -> Option<TextureHandle> {
self.receive(ctx);
self.ready(&worker_key(preview, size_px))
self.ready(&self.worker_key(preview, size_px))
}
/// Material thumbnail: smart materials come from the worker's orb, plain ones are spheres
@@ -220,6 +230,16 @@ impl Thumbs {
}
}
/// Drop the thumbnails and hover previews of the user's saved files, which may have changed on disk
pub fn forget_saved_files(&mut self) {
self.saved_files_epoch = self.saved_files_epoch.wrapping_add(1);
let current = |key: &String| !key.starts_with(SAVED_FILE_KEY_PREFIX);
self.shelf.retain(|key, _| current(key));
self.rendered.retain(|key, _| current(key));
self.big_shown.retain(current);
self.saved_brush_previews.clear();
}
/// Smart mask thumbnail; None until the worker returns it
pub fn smart_mask(&mut self, ctx: &egui::Context, id: &'static str) -> Option<TextureHandle> {
self.worker_rendered(ctx, ShelfPreview::SmartMask(id), SPHERE_PX, false)
@@ -240,17 +260,69 @@ impl Thumbs {
self.shelf(ctx, ShelfPreview::Alpha(alpha), SWATCH_PX)
}
/// A lighting environment's panorama
pub fn environment(&mut self, ctx: &egui::Context, name: &'static str) -> Option<TextureHandle> {
self.shelf(ctx, ShelfPreview::Environment(name), SWATCH_PX)
}
/// A saved brush preset's stroke along an S curve; None while it renders, empty when the file is unreadable
pub fn saved_brush(&mut self, ctx: &egui::Context, path: &Path, images: &ImageStore) -> Option<TextureHandle> {
let key = format!("saved-brush:{}", path.display());
let cached_preview = self.saved_brush_previews.contains_key(path).then(|| self.saved_brush_preview(path, images));
if let Some(texture) = self.shelf.get(&key) {
return Some(texture.clone());
}
if !self.spend_budget(ctx, 1) {
return None;
}
let preview = cached_preview.unwrap_or_else(|| self.saved_brush_preview(path, images));
let image = preview.image(SWATCH_PX).unwrap_or_else(|| ColorImage::filled([SWATCH_PX, SWATCH_PX], Color32::TRANSPARENT));
let texture = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR);
self.shelf.insert(key, texture.clone());
Some(texture)
}
/// Reuse parsed settings until refresh; rebuild previews when their project image changes
pub fn saved_brush_preview(&mut self, path: &Path, images: &ImageStore) -> ShelfPreview {
let cached = self.saved_brush_previews.entry(path.to_path_buf()).or_insert_with(|| (crate::shelf_preview::read_saved_brush(path), None, 0));
let (settings, previous_image, revision) = cached;
let image = settings.as_ref().and_then(|brush| brush.alpha_image.as_ref()).and_then(|name| images.get(name));
let image_changed = match (previous_image.as_ref(), image) {
(Some(previous), Some(current)) => previous.upgrade().is_none_or(|previous| !Arc::ptr_eq(&previous, current)),
(None, None) => false,
_ => true,
};
*previous_image = image.map(Arc::downgrade);
if image_changed {
*revision = revision.wrapping_add(1);
let key = format!("saved-brush:{}", path.display());
let rendered_prefix = format!("{key}@");
self.shelf.remove(&key);
self.rendered.retain(|rendered, _| !rendered.starts_with(&rendered_prefix));
self.big_shown.retain(|rendered| !rendered.starts_with(&rendered_prefix));
}
ShelfPreview::SavedBrush { path: path.to_path_buf(), settings: settings.clone(), image: image.cloned() }
}
/// A saved-brush key also identifies the refresh and image version of its request
fn worker_key(&self, preview: &ShelfPreview, size_px: usize) -> String {
let key = format!("{}@{size_px}", preview.key());
if let ShelfPreview::SavedBrush { path, .. } = preview {
let revision = self.saved_brush_previews.get(path).map_or(0, |(_, _, revision)| *revision);
format!("{key}#{}:{revision}", self.saved_files_epoch)
} else {
key
}
}
/// A brush preset's stroke along an S curve
pub fn brush_preset(&mut self, ctx: &egui::Context, preset: &'static BrushPreset) -> Option<TextureHandle> {
self.shelf(ctx, ShelfPreview::Brush(preset), SWATCH_PX)
}
}
/// The key of a worker-rendered preview: one per asset and size
fn worker_key(preview: &ShelfPreview, size_px: usize) -> String {
format!("{}@{size_px}", preview.key())
}
/// A small shaded sphere drawn with a vertex-colored mesh (layer thumbnails, previews).
pub fn paint_sphere(p: &Painter, c: Pos2, r: f32, base: [f32; 3]) {
let mut mesh = egui::Mesh::default();
@@ -307,11 +379,133 @@ pub fn paint_alpha(p: &Painter, rect: Rect, a: BrushAlpha, hardness: f32) {
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use texturecraft_engine::compose::{ImageRes, ImageStore};
use crate::orb_shape::OrbShape;
use super::Thumbs;
static NEXT_FILE: AtomicUsize = AtomicUsize::new(0);
#[test]
fn saved_brush_refresh_discards_old_worker_result() {
let ctx = egui::Context::default();
let mut thumbs = Thumbs { worker: PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() }, ..Thumbs::default() };
let preview = ShelfPreview::SavedBrush { path: PathBuf::from("refreshed.tcbrush"), settings: None, image: None };
assert!(thumbs.big(&ctx, preview.clone(), 8).is_none());
thumbs.forget_saved_files();
assert!(thumbs.big(&ctx, preview.clone(), 8).is_none());
let PreviewWorker::Inline { results, .. } = &mut thumbs.worker else { panic!("test worker must render inline") };
let old_key = results[0].0.clone();
let current_key = results[1].0.clone();
*results = vec![(current_key, None), (old_key, Some(ColorImage::filled([8, 8], Color32::RED)))];
let mut output = ctx.run_pass(Default::default(), |_| {});
output.textures_delta.clear();
assert!(thumbs.rendered_big(&ctx, &preview, 8).is_none(), "an old completion must not replace the current failed result");
}
#[test]
fn saved_brush_image_replacement_preserves_current_worker_result() {
let ctx = egui::Context::default();
let mut thumbs = Thumbs { worker: PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() }, ..Thumbs::default() };
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 mut images: ImageStore = [("alpha.png".into(), image(0.2))].into();
let old_preview = thumbs.saved_brush_preview(&path, &images);
assert!(thumbs.big(&ctx, old_preview, 8).is_none());
images.insert("alpha.png".into(), image(0.8));
let current_preview = thumbs.saved_brush_preview(&path, &images);
assert!(thumbs.big(&ctx, current_preview.clone(), 8).is_none());
let PreviewWorker::Inline { results, .. } = &mut thumbs.worker else { panic!("test worker must render inline") };
let old_key = results[0].0.clone();
let current_key = results[1].0.clone();
*results = vec![(current_key, Some(ColorImage::filled([8, 8], Color32::RED))), (old_key, None)];
let mut output = ctx.run_pass(Default::default(), |_| {});
output.textures_delta.clear();
assert!(thumbs.rendered_big(&ctx, &current_preview, 8).is_some(), "the current completion must survive an old failure");
}
#[test]
fn saved_brush_file_read_waits_for_the_thumbnail_budget() {
let path = std::env::temp_dir().join(format!("texturecraft-brush-budget-{}-{}.tcbrush", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed)));
std::fs::write(&path, serde_json::to_vec(&BrushSettings::default()).unwrap()).unwrap();
let context = egui::Context::default();
let mut thumbs = Thumbs::default();
thumbs.budget = (context.cumulative_pass_nr(), PER_FRAME);
assert!(thumbs.saved_brush(&context, &path, &ImageStore::new()).is_none());
assert!(thumbs.saved_brush_previews.is_empty(), "a deferred thumbnail has not read its file");
std::fs::remove_file(&path).unwrap();
}
#[test]
fn saved_brush_settings_are_read_once_until_refresh() {
let path =
std::env::temp_dir().join(format!("texturecraft-brush-preview-{}-{}.tcbrush", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed)));
std::fs::write(&path, serde_json::to_vec(&BrushSettings::default()).unwrap()).unwrap();
let mut thumbs = Thumbs::default();
let images = ImageStore::new();
assert!(matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: Some(_), .. }));
std::fs::remove_file(&path).unwrap();
assert!(
matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: Some(_), .. }),
"cached settings avoid a second file read"
);
thumbs.forget_saved_files();
assert!(matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: None, .. }), "refresh reads the file again");
}
#[test]
fn saved_brush_cache_releases_old_images_on_change_and_refresh() {
const IMAGE_SIDE: u32 = 512;
const IMAGE_TEXELS: usize = IMAGE_SIDE as usize * IMAGE_SIDE as usize;
const IMAGE_BYTES: usize = IMAGE_TEXELS * std::mem::size_of::<[f32; 4]>();
let mut thumbs = Thumbs::default();
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_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::<f32>() > 0.0);
assert!(other_image.rgba.iter().map(|pixel| std::hint::black_box(pixel[0])).sum::<f32>() > 0.0);
thumbs.saved_brush_previews.insert(first_path.clone(), (Some(settings.clone()), None, 0));
thumbs.saved_brush_previews.insert(second_path.clone(), (Some(settings), None, 0));
let mut images: ImageStore = [("alpha.png".into(), old_image.clone())].into();
drop(thumbs.saved_brush_preview(&first_path, &images));
images.insert("alpha.png".into(), other_image.clone());
drop(thumbs.saved_brush_preview(&second_path, &images));
drop(old_image);
drop(other_image);
assert!(old_weak.upgrade().is_none(), "cached settings do not retain a replaced image");
assert!(other_weak.upgrade().is_some(), "the project still owns its current image");
eprintln!(
"saved brush cache after first replacement: 0 of {IMAGE_BYTES} old image bytes retained, {} current image strong owners",
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 });
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");
eprintln!("saved brush cache after second replacement: 0 of {IMAGE_BYTES} previous image bytes retained");
thumbs.forget_saved_files();
assert!(thumbs.saved_brush_previews.is_empty(), "refresh releases parsed brush settings");
}
#[test]
fn replacing_an_image_rebuilds_its_preview() {
+66 -3
View File
@@ -13,6 +13,9 @@ const STORAGE_STEM: &str = "ui";
/// eframe storage key under which earlier builds kept the UI state, as RON
const RON_STORAGE_KEY: &str = "ui";
/// Textures moved from index 8 to index 6 when procedurals joined that type
const LEGACY_TEXTURES_TAB: usize = 8;
const TEXTURES_TAB: usize = 6;
/// Maximum encoded UI state size for both reads and writes; typical states are a few kilobytes
const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024;
@@ -65,7 +68,7 @@ impl UiStateStore {
return None;
}
let ui = serde_json::from_slice::<UiState>(&bytes).ok();
let ui = decode_json_ui(&bytes);
if !ui.as_ref().is_some_and(fully_read) {
self.unreadable = Some((bytes, "json"));
}
@@ -75,7 +78,10 @@ impl UiStateStore {
/// Preserve the original RON when decoding loses either dock, even if other settings load
fn load_ron(&mut self, storage: &dyn eframe::Storage) -> Option<UiState> {
let text = storage.get_string(RON_STORAGE_KEY)?;
let ui = eframe::get_value::<UiState>(storage, RON_STORAGE_KEY);
let mut ui = eframe::get_value::<UiState>(storage, RON_STORAGE_KEY);
if let Some(ui) = &mut ui {
migrate_shelf_tab(ui, ron_has_shelf_path(&text));
}
if !ui.as_ref().is_some_and(fully_read) {
self.unreadable = Some((text.into_bytes(), "ron"));
}
@@ -158,9 +164,52 @@ impl UiStateStore {
}
}
/// Old saved states have no shelf path, so their former Textures index needs remapping
fn migrate_shelf_tab(ui: &mut UiState, has_shelf_path: bool) {
if ui.shelf_tab == LEGACY_TEXTURES_TAB && !has_shelf_path {
ui.shelf_tab = TEXTURES_TAB;
}
}
/// Decode JSON settings and map the old Textures index only when its new fields are absent
fn decode_json_ui(bytes: &[u8]) -> Option<UiState> {
let mut ui = serde_json::from_slice::<UiState>(bytes).ok()?;
if ui.shelf_tab == LEGACY_TEXTURES_TAB {
let has_shelf_path = serde_json::from_slice::<serde_json::Value>(bytes)
.ok()
.and_then(|state| state.as_object().map(|fields| fields.contains_key("shelf_path")))
.unwrap_or(true);
migrate_shelf_tab(&mut ui, has_shelf_path);
}
Some(ui)
}
/// Ignore user text while looking for the field in legacy RON settings
fn ron_has_shelf_path(text: &str) -> bool {
let bytes = text.as_bytes();
let mut quoted = false;
let mut escaped = false;
for (index, byte) in bytes.iter().enumerate() {
if quoted {
if escaped {
escaped = false;
} else if *byte == b'\\' {
escaped = true;
} else if *byte == b'"' {
quoted = false;
}
} else if *byte == b'"' {
quoted = true;
} else if bytes[index..].starts_with(b"shelf_path:") && (index == 0 || matches!(bytes[index - 1], b',' | b'(' | b' ' | b'\n')) {
return true;
}
}
false
}
/// The UI state saved in `file`, if it reads
pub fn read(file: &Path) -> Option<UiState> {
serde_json::from_slice(&read_bytes(file).ok()?).ok()
decode_json_ui(&read_bytes(file).ok()?)
}
/// eframe's browser storage reports write failures only through logging, so verify before discarding old settings
@@ -311,6 +360,20 @@ pub(crate) mod tests {
assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded);
}
#[test]
fn legacy_ron_textures_index_migrates_to_the_combined_type() {
let mut storage = MemoryStorage::default();
let legacy = include_str!("../tests/fixture/ui_state_before_json.ron")
.replace("shelf_tab:0", "shelf_tab:8")
.replace("shelf_filter:\"\"", "shelf_filter:\"shelf_path:\"");
assert!(legacy.contains("shelf_tab:8") && !ron_has_shelf_path(&legacy));
storage.values.insert(RON_STORAGE_KEY.into(), legacy);
let loaded = UiStateStore::default().load(Some(&storage)).expect("the legacy state loads");
assert_eq!(loaded.shelf_tab, TEXTURES_TAB);
}
#[test]
fn an_unreadable_layout_loads_the_default_and_is_kept_beside_the_file() {
let folder = test_folder("unreadable");
+1
View File
@@ -31,6 +31,7 @@ mod properties_popup;
mod rail;
mod shelf_drop;
mod shelf_hover_preview;
mod shelf_panel;
mod shift_lines_2d;
mod shortcut_keys;
mod skew_paint;
@@ -20,20 +20,22 @@ const REST: f32 = 0.1;
/// Real time the worker gets to render
const WORKER_TIMEOUT: Duration = Duration::from_secs(60);
/// Open the Materials tab and find two labels unique to shelf tiles
/// Open the Materials tab and find the first two labels (the grid is sorted by name) unique to shelf tiles
fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static, TextureCraftApp>, Vec<&'static SmartMaterial>) {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder()
let mut harness = Harness::builder()
.with_size(egui::vec2(1600.0, 960.0))
.with_step_dt(step_seconds)
.with_pixels_per_point(pixels_per_point)
.build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.shelf_tab = MATERIALS_TAB;
h.run_steps(4);
harness.state_mut().ui.shelf_tab = MATERIALS_TAB;
harness.run_steps(4);
let unique: Vec<_> = MATERIALS.iter().filter(|m| !m.smart && h.query_all_by_label(m.label).count() == 1).take(2).collect();
let mut plain: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect();
plain.sort_by_key(|material| material.label.to_lowercase());
let unique: Vec<_> = plain.into_iter().filter(|material| harness.query_all_by_label(material.label).count() == 1).take(2).collect();
assert_eq!(unique.len(), 2, "two materials with unique names");
(h, unique)
(harness, unique)
}
/// Largest drawn texture in pixels, excluding fonts and images below `min_width` points
+316
View File
@@ -0,0 +1,316 @@
//! The Assets panel's layout: columns at the reference width, type row, size menu, breadcrumb, side panes and toolbar
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use texturecraft_engine::core::ProceduralKind;
use texturecraft_engine::core::project::ENVIRONMENTS;
use texturecraft_engine::materials::{MATERIALS, SmartMaterial};
use texturecraft_engine::smart_masks::SMART_MASKS;
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::saved_search::SavedSearch;
use texturecraft_ui_egui::shelf_view::ShelfView;
/// The reference's capture window: its Assets panel shows four columns there
const REFERENCE_WINDOW: egui::Vec2 = egui::vec2(1920.0, 1032.0);
/// A window whose default Assets panel is too narrow for the full type row
const NARROW_WINDOW: egui::Vec2 = egui::vec2(1100.0, 1032.0);
/// The types' positions in the shelf's type row (its table is crate-private)
const MATERIALS_TYPE: usize = 0;
const SMART_MASKS_TYPE: usize = 2;
const BRUSHES_TYPE: usize = 4;
const TEXTURES_TYPE: usize = 6;
const ENVIRONMENTS_TYPE: usize = 7;
/// How far the saved brush's spacing differs from the current brush's, so loading it shows
const SAVED_SPACING_CHANGE: f32 = 0.25;
/// Tile columns the reference shows at its panel width
const REFERENCE_COLUMNS: usize = 4;
/// The sample project with the shelf on the Materials type
fn shelf(size: egui::Vec2) -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.shelf_tab = MATERIALS_TYPE;
harness.run_steps(4);
harness
}
/// The plain materials in the grid's order (by name)
fn plain_materials() -> Vec<&'static SmartMaterial> {
let mut plain: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect();
plain.sort_by_key(|material| material.label.to_lowercase());
plain
}
/// A clickable node labelled `label` (its tooltip, once shown, has the same label)
fn button<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> egui_kittest::Node<'a> {
harness.get_all_by_label(label).next().unwrap_or_else(|| panic!("no {label}"))
}
#[test]
fn the_default_panel_shows_the_reference_column_count() {
let harness = shelf(REFERENCE_WINDOW);
let tops: Vec<f32> = plain_materials().iter().take(REFERENCE_COLUMNS + 1).map(|material| harness.get_by_label(material.label).rect().top()).collect();
assert!(tops[..REFERENCE_COLUMNS].iter().all(|top| *top == tops[0]), "the first {REFERENCE_COLUMNS} tiles share a row: {tops:?}");
assert!(tops[REFERENCE_COLUMNS] > tops[0], "the next tile starts a row: {tops:?}");
}
#[test]
fn a_click_on_the_picked_type_shows_every_type() {
let mut harness = shelf(REFERENCE_WINDOW);
let mask = SMART_MASKS[0].label;
assert!(harness.query_by_label(mask).is_none(), "the Materials type hides smart masks");
button(&harness, "Materials").click();
harness.run_steps(3);
assert!(harness.query_by_label(mask).is_some(), "no type picked shows smart masks too");
}
#[test]
fn the_search_narrows_the_picked_type_and_greys_types_without_matches() {
let mut harness = shelf(REFERENCE_WINDOW);
let material = plain_materials().into_iter().find(|material| material.label.to_lowercase().contains("rust")).unwrap();
let mask = SMART_MASKS.iter().find(|mask| mask.label.to_lowercase().contains("rust")).unwrap();
harness.state_mut().ui.shelf_filter = "rust".into();
harness.state_mut().ui.shelf_tab = SMART_MASKS_TYPE;
harness.run_steps(3);
assert!(harness.query_by_label(mask.label).is_some(), "the matching mask shows");
assert!(harness.query_by_label(material.label).is_none(), "a matching material of another type does not");
assert!(button(&harness, "Environments").accesskit_node().is_disabled(), "no environment matches");
assert!(!button(&harness, "Materials").accesskit_node().is_disabled());
button(&harness, "Materials").click();
harness.run_steps(3);
assert_eq!(harness.state().ui.shelf_filter, "rust", "picking a type keeps the search");
assert!(harness.query_by_label(material.label).is_some());
}
#[test]
fn unavailable_project_images_do_not_make_textures_match() {
let mut harness = shelf(REFERENCE_WINDOW);
harness.state_mut().session.doc.resources.insert("unavailable-preview.png".into(), vec![0].into());
harness.state_mut().ui.shelf_filter = "unavailable-preview.png".into();
harness.run_steps(3);
assert!(button(&harness, "Textures").accesskit_node().is_disabled());
assert!(harness.query_by_label("unavailable-preview.png").is_none());
}
#[test]
fn the_breadcrumb_arrow_picks_a_library() {
let mut harness = shelf(REFERENCE_WINDOW);
let material = plain_materials()[0].label;
button(&harness, "Browse folders").click();
harness.run_steps(2);
for library in ["Project", "Starter assets", "Your assets"] {
assert!(harness.query_by_label(library).is_some(), "the list offers {library}");
}
harness.get_by_label("Project").click();
harness.run_steps(3);
assert_eq!(harness.state().ui.shelf_path, ["project"]);
assert!(harness.query_by_label(material).is_none(), "built-in materials are not in the project");
}
#[test]
fn the_thumbnail_size_menu_switches_to_the_list() {
let mut harness = shelf(REFERENCE_WINDOW);
let material = plain_materials()[0].label;
let tile_width = harness.get_by_label(material).rect().width();
button(&harness, "Thumbnail size").click();
harness.run_steps(2);
harness.get_by_label_contains("List").click();
harness.run_steps(3);
assert_eq!(harness.state().ui.shelf_view, ShelfView::List);
assert!(harness.get_by_label(material).rect().width() > tile_width * 2.0, "a list row spans the panel");
}
#[test]
fn reset_query_shows_every_asset_again() {
let mut harness = shelf(REFERENCE_WINDOW);
harness.state_mut().ui.shelf_filter = "rust".into();
harness.state_mut().ui.shelf_path = vec!["starter".into()];
harness.run_steps(2);
button(&harness, "Reset query").click();
harness.run_steps(3);
let ui = &harness.state().ui;
assert!(ui.shelf_filter.is_empty() && ui.shelf_path.is_empty());
assert!(harness.query_by_label(SMART_MASKS[0].label).is_some(), "every type shows");
}
#[test]
fn refresh_reads_the_saved_brushes_again() {
let mut harness = shelf(REFERENCE_WINDOW);
let stale = vec![std::path::PathBuf::from("gone.tcbrush")];
harness.state_mut().brushes = Some(stale.clone());
harness.run_steps(1);
button(&harness, "Refresh").click();
harness.run_steps(3);
assert_ne!(harness.state().brushes, Some(stale), "the brushes folder was read again");
assert!(harness.query_by_label("Import resources...").is_some(), "the toolbar has the import button");
}
#[test]
fn a_saved_search_restores_its_query() {
let mut harness = shelf(REFERENCE_WINDOW);
button(&harness, "Saved searches").click();
harness.state_mut().ui.shelf_filter = "rust".into();
harness.run_steps(3);
button(&harness, "Save the current search").click();
harness.run_steps(2);
assert_eq!(harness.state().ui.shelf_saved_searches.len(), 1);
harness.state_mut().ui.shelf_filter.clear();
harness.run_steps(2);
harness.get_by_label("rust").click();
harness.run_steps(2);
assert_eq!(harness.state().ui.shelf_filter, "rust");
harness.get_by_label("rust").click_secondary();
harness.run_steps(2);
// The context menu opens last, so its Delete is the newest node with that label
harness.get_all_by_label("Delete").last().unwrap().click();
harness.run_steps(2);
assert!(harness.state().ui.shelf_saved_searches.is_empty());
}
#[test]
fn filter_by_path_picks_a_folder() {
let mut harness = shelf(REFERENCE_WINDOW);
button(&harness, "Filter by path").click();
harness.run_steps(3);
harness.get_by_label("Starter assets").click();
harness.run_steps(2);
assert_eq!(harness.state().ui.shelf_path, ["starter"]);
}
#[test]
fn many_saved_searches_keep_the_path_filter_reachable() {
let mut harness = shelf(NARROW_WINDOW);
harness.state_mut().ui.shelf_panes.saved_searches = true;
harness.state_mut().ui.shelf_panes.filter_by_path = true;
harness.state_mut().ui.shelf_saved_searches = (0..100)
.map(|index| SavedSearch { name: format!("search {index}"), filter: format!("filter {index}"), tab: MATERIALS_TYPE, path: Vec::new() })
.collect();
harness.run_steps(3);
let heading = harness.get_by_label("FILTER BY PATH").rect();
assert!(heading.bottom() < NARROW_WINDOW.y, "the path pane heading stays on screen: {heading:?}");
assert!(harness.query_by_label("Starter assets").is_some(), "the folder tree remains reachable");
}
#[test]
fn a_long_saved_search_list_can_select_the_last_query() {
let mut harness = shelf(NARROW_WINDOW);
harness.state_mut().ui.shelf_panes.saved_searches = true;
harness.state_mut().ui.shelf_saved_searches = (0..1000)
.map(|index| SavedSearch { name: format!("search {index}"), filter: format!("filter {index}"), tab: MATERIALS_TYPE, path: Vec::new() })
.collect();
harness.run_steps(3);
assert!(harness.query_by_label("search 500").is_none(), "offscreen searches do not build rows");
harness.get_by_label("search 0").hover();
harness.event(egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: egui::vec2(0.0, -50_000.0),
phase: egui::TouchPhase::Move,
source: egui::MouseWheelSource::Wheel,
modifiers: egui::Modifiers::NONE,
});
harness.run_steps(3);
harness.get_by_label("search 999").click();
harness.run_steps(2);
assert_eq!(harness.state().ui.shelf_filter, "filter 999");
}
#[test]
fn a_narrow_panel_keeps_the_toolbar_and_folds_the_type_row() {
let mut harness = shelf(NARROW_WINDOW);
harness.state_mut().ui.shelf_panes.saved_searches = true;
harness.state_mut().ui.shelf_panes.filter_by_path = true;
harness.run_steps(3);
for label in ["Refresh", "Reset query", "Import resources...", "Saved searches", "Filter by path"] {
let rect = button(&harness, label).rect();
assert!(rect.bottom() <= NARROW_WINDOW.y, "{label} is inside the window: {rect:?}");
}
assert!(harness.query_by_label("Filter by type").is_some(), "the type row folds into one dropdown");
assert!(harness.query_by_label("Environments").is_none());
}
#[test]
fn an_environment_tile_switches_the_lighting() {
let mut harness = shelf(REFERENCE_WINDOW);
harness.state_mut().ui.shelf_tab = ENVIRONMENTS_TYPE;
harness.run_steps(3);
let shown = harness.state().session.doc.project.display.environment.clone();
let other = ENVIRONMENTS.iter().find(|name| **name != shown).unwrap();
harness.get_by_label(other).click();
harness.run_steps(2);
assert_eq!(harness.state().session.doc.project.display.environment, *other);
}
#[test]
fn a_saved_brush_is_a_tile_that_loads_the_preset() {
let mut harness = shelf(REFERENCE_WINDOW);
let mut saved = harness.state().session.tool.brush.clone();
saved.spacing += SAVED_SPACING_CHANGE;
let path = std::env::temp_dir().join(format!("shelf-panel-{}.tcbrush", std::process::id()));
std::fs::write(&path, serde_json::to_vec(&saved).unwrap()).unwrap();
harness.state_mut().brushes = Some(vec![path.clone()]);
harness.state_mut().ui.shelf_tab = BRUSHES_TYPE;
harness.run_steps(3);
harness.get_by_label(path.file_stem().unwrap().to_str().unwrap()).click();
harness.run_steps(2);
std::fs::remove_file(&path).unwrap();
assert_eq!(harness.state().session.tool.brush.spacing, saved.spacing, "the click loads the saved stroke");
}
#[test]
fn saved_smart_materials_keep_their_type_pickable_in_your_assets() {
let mut harness = shelf(REFERENCE_WINDOW);
harness.state_mut().library = Some(vec![std::path::PathBuf::from("Mine.tcmat")]);
harness.state_mut().ui.shelf_path = vec!["user".into()];
harness.state_mut().ui.shelf_tab = BRUSHES_TYPE;
harness.run_steps(3);
assert!(!button(&harness, "Smart materials").accesskit_node().is_disabled(), "a saved smart material is in Your assets");
assert!(button(&harness, "Materials").accesskit_node().is_disabled(), "no plain material is");
}
#[test]
fn saved_smart_materials_are_read_whatever_the_type_and_after_a_refresh() {
let mut harness = shelf(REFERENCE_WINDOW);
assert!(harness.state().library.is_some(), "read on the Materials type");
button(&harness, "Refresh").click();
harness.run_steps(2);
assert!(harness.state().library.is_some(), "read again after a refresh");
}
#[test]
fn procedurals_are_in_the_textures_type() {
let mut harness = shelf(REFERENCE_WINDOW);
harness.state_mut().ui.shelf_tab = TEXTURES_TYPE;
harness.run_steps(3);
assert!(harness.query_by_label(ProceduralKind::ALL[0].label()).is_some());
}
+20
View File
@@ -157,6 +157,26 @@ fn the_divider_position_survives_a_restart_and_old_saved_states_load_centred() {
assert_eq!(restored.split_ratio, 0.5);
}
#[test]
fn old_textures_tab_index_migrates_without_changing_new_all_types() {
let mut storage = MemoryStorage::default();
let mut state = UiState::default();
state.shelf_tab = 8;
UiStateStore::default().save(&state, &mut storage);
assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(8));
let mut legacy: serde_json::Value = serde_json::from_str(&storage.0["ui.json"]).unwrap();
legacy.as_object_mut().unwrap().remove("shelf_path");
legacy.as_object_mut().unwrap().insert("shelf_filter".into(), "shelf_path".into());
storage.0.insert("ui.json".into(), legacy.to_string());
assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(6));
state.shelf_tab = 0;
UiStateStore::default().save(&state, &mut storage);
assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(0));
}
#[test]
fn dragging_the_divider_keeps_the_uv_texture_size_and_offset_on_screen() {
// Zoomed in, a 2D sliver needs a zoom far past the one the view starts with