diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 1d266ee1..e6ee88ac 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -6,8 +6,8 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerId, LayerKind, - LinkParam, MaterialLink, ProceduralKind, Projection, Source, + BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, Projection, + Source, }; use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; @@ -270,6 +270,77 @@ fn row_shade(tk: &Tokens, index: usize) -> Color32 { const RIGHT_COLUMN: f32 = 58.0; /// Indent per folder level, and per level of the effect tree. const INDENT: f32 = 14.0; +/// Edge of the small icon buttons in the properties panel. +const ICON_BUTTON_SIZE: f32 = 22.0; +/// Height of a blend mode menu or opacity field in a stack row, and the rounding of its hover fill. +const ROW_CONTROL_HEIGHT: f32 = 17.0; +const ROW_CONTROL_ROUNDING: f32 = 2.0; +/// Gap between the controls at the right of a stack row, and between them and the row's edge. +const ROW_CONTROL_GAP: f32 = 4.0; +/// Space before an effect row's eye and after its name. +const ROW_LEFT_PADDING: f32 = 7.0; +const ROW_RIGHT_PADDING: f32 = 6.0; +/// Width of the selected row's accent edge. +const SELECTED_EDGE_WIDTH: f32 = 3.0; +/// An effect thumbnail's corner rounding and border, the strike across a hidden effect's, and the line marking where a drag drops. +const THUMBNAIL_ROUNDING: f32 = 2.0; +const THUMBNAIL_BORDER_WIDTH: f32 = 1.0; +const HIDDEN_STRIKE_WIDTH: f32 = 1.5; +const DROP_LINE_WIDTH: f32 = 2.0; +/// The eye's size and the column it sits in (the eye and a gap before the thumbnail). +const EYE_SIZE: f32 = 16.0; +const EYE_COLUMN_WIDTH: f32 = 22.0; +/// Gap between an effect's thumbnail and its name, and the narrowest name worth showing. +const THUMBNAIL_GAP: f32 = 8.0; +const MIN_NAME_WIDTH: f32 = 20.0; +/// Font sizes in an effect row: the eye, the name, the blend mode and its caret. +const EYE_FONT_SIZE: f32 = 12.0; +const EFFECT_NAME_FONT_SIZE: f32 = 11.5; +const ROW_SMALL_FONT_SIZE: f32 = 11.0; +const CARET_FONT_SIZE: f32 = 8.0; +/// Room for the caret at the right of the blend mode's name. +const CARET_WIDTH: f32 = 10.0; +/// The blend mode menu's width, wide enough for the longest mode name. +const BLEND_MENU_MIN_WIDTH: f32 = 190.0; +/// Padding inside a row's opacity field, and the percent it moves per point dragged. +const ROW_FIELD_PADDING: f32 = 4.0; +const OPACITY_DRAG_SPEED: f64 = 0.5; +/// A layer row's eye: its hit area, its glyph size and the column it sits in. +const LAYER_EYE_SIZE: f32 = 18.0; +const LAYER_EYE_FONT_SIZE: f32 = 13.0; +const LAYER_EYE_COLUMN_WIDTH: f32 = 20.0; +/// A folder's caret: its size (the space it takes before the thumbnail) and its center from where it starts. +const FOLDER_CARET_SIZE: f32 = 14.0; +const FOLDER_CARET_CENTER: f32 = 6.0; +/// A thumbnail's border while it is the layer's target, and how far outside it the mask-view and drop outlines sit. +const TARGET_BORDER_WIDTH: f32 = 1.5; +const HIGHLIGHT_OUTSET: f32 = 2.0; +/// The gap between a layer row's stacked blend mode and opacity, either side of the row's middle. +const ROW_STACK_GAP: f32 = 1.0; +/// Width of a layer's colour tag beside the accent edge. +const TAG_WIDTH: f32 = 3.0; +/// Space between a layer's content and mask thumbnails, and the size of the empty mask slot. +const THUMBNAIL_SPACING: f32 = 4.0; +const MASK_SLOT_SIZE: f32 = 18.0; +/// Grays of a white or black mask before its thumbnail arrives. +const WHITE_MASK_GRAY: u8 = 225; +const BLACK_MASK_GRAY: u8 = 18; +/// A layer's name and subtitle font sizes, and their distance from the row's middle. +const LAYER_NAME_FONT_SIZE: f32 = 12.5; +const LAYER_SUBTITLE_FONT_SIZE: f32 = 10.0; +const NAME_LINE_GAP: f32 = 2.0; +/// Folder lines: their width, how faded they are, how far an indent must reach past one, and where the branch starts. +const FOLDER_LINE_WIDTH: f32 = 1.0; +const FOLDER_LINE_FADE: f32 = 0.6; +const FOLDER_LINE_CLEARANCE: f32 = 8.0; +const FOLDER_BRANCH_OFFSET: f32 = 15.0; +/// The share of a folder row's height, either side of its middle, where a drop goes inside it. +const FOLDER_DROP_ZONE: f32 = 0.25; +/// How far each alternating effect row shade goes from the panel towards the hover colour. +const EFFECT_ROW_SHADES: [f32; 2] = [0.2, 0.5]; +/// Width of the blend mode and opacity pair at the right of an effect row (a gap between them), and of its opacity part. +const EFFECT_BLEND_WIDTH: f32 = 82.0; +const EFFECT_OPACITY_WIDTH: f32 = 36.0; /// Height of the "Content effects" / "Mask effects" header rows. const GROUP_HEADER_H: f32 = 20.0; @@ -292,7 +363,7 @@ fn layer_name_layout(rect: Rect, left: f32) -> (Rect, bool) { /// Preserve the effect eye, preview and a readable name before spending space on nesting. fn effect_row_indent(width: f32, level: usize, preview: f32) -> f32 { - (level as f32 * INDENT).min((width - 7.0 - 22.0 - preview - 8.0 - 20.0 - 6.0).max(0.0)) + (level as f32 * INDENT).min((width - ROW_LEFT_PADDING - EYE_COLUMN_WIDTH - preview - THUMBNAIL_GAP - MIN_NAME_WIDTH - ROW_RIGHT_PADDING).max(0.0)) } /// X of the centre of the eye column at indent `level` in a row spanning from `left`. @@ -351,292 +422,280 @@ fn thumb_box(ui: &Ui, app: &mut TextureCraftApp, rect: Rect, target: ThumbTarget false } +/// The row of `layer` at folder depth `depth`, the `index`th row of the stack (rows alternate shades). fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, index: usize) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let selected = app.session.selected_layer() == Some(layer.id); let content_target = selected && targets_content(app); - let size = layer_preview_size(app); - let h = layer_row_height(size); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &layer.name)); - let p = ui.painter().clone(); - let bg = if selected { - tk.row_selected - } else if resp.hovered() { - tk.row_hover + let preferred_size = layer_preview_size(app); + let row_height = layer_row_height(preferred_size); + let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), row_height), Sense::click_and_drag()); + row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &layer.name)); + + // Background, folder lines, the selected row's accent edge and the colour tag + let painter = ui.painter().clone(); + let background = if selected { + tokens.row_selected + } else if row.hovered() { + tokens.row_hover } else { - row_shade(&tk, index) + row_shade(&tokens, index) }; - p.rect_filled(rect, 0.0, bg); - let (indent, size) = layer_thumbnail_layout(rect.width(), depth, layer.is_group(), size); + painter.rect_filled(rect, 0.0, background); + let (indent, thumbnail_size) = layer_thumbnail_layout(rect.width(), depth, layer.is_group(), preferred_size); // Folder contents hang off lines down the left without crossing compact row controls - let line = Stroke::new(1.0, tk.button_border.gamma_multiply(0.6)); + let line = Stroke::new(FOLDER_LINE_WIDTH, tokens.button_border.gamma_multiply(FOLDER_LINE_FADE)); for level in 0..depth { - let x = level_x(rect.left(), level); - if level as f32 * INDENT + 8.0 < indent { - p.vline(x, rect.y_range(), line); + if level as f32 * INDENT + FOLDER_LINE_CLEARANCE < indent { + painter.vline(level_x(rect.left(), level), rect.y_range(), line); } } if depth > 0 && indent >= INDENT { - let x = rect.left() + 15.0 + indent - INDENT; - p.hline(x..=x + INDENT * 0.5, rect.center().y, line); + let x = rect.left() + FOLDER_BRANCH_OFFSET + indent - INDENT; + painter.hline(x..=x + INDENT * 0.5, rect.center().y, line); } if selected { - p.rect_filled(Rect::from_min_size(rect.min, vec2(3.0, h)), 0.0, tk.accent); + painter.rect_filled(Rect::from_min_size(rect.min, vec2(SELECTED_EDGE_WIDTH, row_height)), 0.0, tokens.accent); } - if let Some(tag) = layer.color_tag.and_then(|t| TAG_COLORS.get(t as usize)) { - p.rect_filled(Rect::from_min_size(rect.min + vec2(3.0, 0.0), vec2(3.0, h)), 0.0, *tag); + if let Some(tag) = layer.color_tag.and_then(|tag| TAG_COLORS.get(tag as usize)) { + painter.rect_filled(Rect::from_min_size(rect.min + vec2(SELECTED_EDGE_WIDTH, 0.0), vec2(TAG_WIDTH, row_height)), 0.0, *tag); } - let x0 = rect.left() + 7.0 + indent; - // Eye. - let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(18.0, 18.0)); - let eye_resp = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_text(tr("Show or hide the layer")); - p.text( + + // The eye + let content_left = rect.left() + ROW_LEFT_PADDING + indent; + let eye = Rect::from_center_size(pos2(content_left + EYE_SIZE * 0.5, rect.center().y), vec2(LAYER_EYE_SIZE, LAYER_EYE_SIZE)); + let eye_response = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_text(tr("Show or hide the layer")); + painter.text( eye.center(), egui::Align2::CENTER_CENTER, if layer.visible { ic::EYE } else { ic::EYE_SLASH }, - egui::FontId::proportional(13.0), - if layer.visible { tk.text } else { tk.text_dim }, + egui::FontId::proportional(LAYER_EYE_FONT_SIZE), + if layer.visible { tokens.text } else { tokens.text_dim }, ); - if eye_resp.clicked() { + if eye_response.clicked() { app.run("layer.visible", json!({"layer": layer.id.0})); } - // Group caret. - let mut x = x0 + 20.0; + + // A folder's caret + let mut x = content_left + LAYER_EYE_COLUMN_WIDTH; if let LayerKind::Group { collapsed, .. } = layer.kind { - let caret = Rect::from_center_size(pos2(x + 6.0, rect.center().y), vec2(14.0, 14.0)); - let cr = ui.interact(caret, ui.scope_id().with(("caret", layer.id.0)), Sense::click()).on_hover_text(tr("Expand or collapse the folder")); - p.text( + let caret = Rect::from_center_size(pos2(x + FOLDER_CARET_CENTER, rect.center().y), vec2(FOLDER_CARET_SIZE, FOLDER_CARET_SIZE)); + let caret_response = ui.interact(caret, ui.scope_id().with(("caret", layer.id.0)), Sense::click()).on_hover_text(tr("Expand or collapse the folder")); + painter.text( caret.center(), egui::Align2::CENTER_CENTER, if collapsed { ic::CARET_RIGHT } else { ic::CARET_DOWN }, - egui::FontId::proportional(11.0), - tk.text_dim, + egui::FontId::proportional(ROW_SMALL_FONT_SIZE), + tokens.text_dim, ); - if cr.clicked() - && let Some(LayerKind::Group { collapsed, .. }) = app.session.doc.project.layers.get_mut(&layer.id).map(|l| &mut l.kind) + if caret_response.clicked() + && let Some(LayerKind::Group { collapsed, .. }) = app.session.doc.project.layers.get_mut(&layer.id).map(|edited| &mut edited.kind) { *collapsed = !*collapsed; } - x += 14.0; + x += FOLDER_CARET_SIZE; } - // Content thumbnail: the layer's own result in the displayed channel. - let ch = app.ui.layer_channel; - let thumb = Rect::from_min_size(pos2(x, rect.center().y - size * 0.5), vec2(size, size)); - let drawn = thumb_box(ui, app, thumb, ThumbTarget::Content { layer: layer.id, channel: ch }, !layer.visible); - if !drawn { - content_glyph(&p, &tk, thumb, layer); + + // Content thumbnail: the layer's own result in the displayed channel + let channel = app.ui.layer_channel; + let thumbnail = Rect::from_min_size(pos2(x, rect.center().y - thumbnail_size * 0.5), vec2(thumbnail_size, thumbnail_size)); + if !thumb_box(ui, app, thumbnail, ThumbTarget::Content { layer: layer.id, channel }, !layer.visible) { + content_glyph(&painter, &tokens, thumbnail, layer); } - p.rect_stroke( - thumb, - 2.0, - Stroke::new(if content_target { 1.5 } else { 1.0 }, if content_target { tk.accent } else { tk.button_border }), - egui::StrokeKind::Outside, - ); - let content_resp = ui.interact(thumb, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(tr("Select the layer content")); - if content_resp.clicked() { + painter.rect_stroke(thumbnail, THUMBNAIL_ROUNDING, target_stroke(&tokens, content_target), egui::StrokeKind::Outside); + let content_response = ui.interact(thumbnail, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(tr("Select the layer content")); + if content_response.clicked() { app.run("layer.select", json!({"layer": layer.id.0, "target": "content"})); } - x = thumb.right() + 4.0; - // An instance draws its source's content, blending and (unless it has its own) mask. + x = thumbnail.right() + THUMBNAIL_SPACING; + + // An instance draws its source's content, blending and (unless it has its own) mask let project = &app.session.doc.project; - let source = layer.instance_source().map(|src| { - let set = project.locate(src).and_then(|(ts, _, _)| project.texture_sets.get(ts)).map(|t| t.name.as_str()).unwrap_or("?"); - project.layers.get(&src).map_or_else(|| tr("missing source").to_string(), |l| format!("{} · {set}", l.name)) + let source = layer.instance_source().map(|source| { + let set = project.locate(source).and_then(|(set, _, _)| project.texture_sets.get(set)).map(|set| set.name.as_str()).unwrap_or("?"); + project.layers.get(&source).map_or_else(|| tr("missing source").to_string(), |source_layer| format!("{} · {set}", source_layer.name)) }); - let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|l| l.mask.clone()); - let blend = project.content_layer(layer.id).and_then(|l| l.blend(ch)); - // Mask thumbnail, selectable on its own; or the slot that adds one. + let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.clone()); + let blend = project.content_layer(layer.id).and_then(|content| content.blend(channel)); + + // Mask thumbnail, selectable on its own; or the slot that adds one let mask_rect; - if let Some(m) = &mask { - let mask_sel = selected && !targets_content(app); - mask_rect = Rect::from_min_size(pos2(x, rect.center().y - size * 0.5), vec2(size, size)); - let drawn = thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !m.enabled); - if !drawn { - p.rect_filled( - mask_rect, - 2.0, - if m.background == texturecraft_engine::core::MaskBackground::White { Color32::from_gray(225) } else { Color32::from_gray(18) }, - ); - if !m.effects.is_empty() { - p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(13.0), tk.text_dim); + if let Some(mask) = &mask { + let mask_target = selected && !targets_content(app); + mask_rect = Rect::from_min_size(pos2(x, rect.center().y - thumbnail_size * 0.5), vec2(thumbnail_size, thumbnail_size)); + if !thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !mask.enabled) { + let white = mask.background == texturecraft_engine::core::MaskBackground::White; + painter.rect_filled(mask_rect, THUMBNAIL_ROUNDING, Color32::from_gray(if white { WHITE_MASK_GRAY } else { BLACK_MASK_GRAY })); + if !mask.effects.is_empty() { + painter.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(LAYER_EYE_FONT_SIZE), tokens.text_dim); } } - p.rect_stroke( - mask_rect, - 2.0, - Stroke::new(if mask_sel { 1.5 } else { 1.0 }, if mask_sel { tk.accent } else { tk.button_border }), - egui::StrokeKind::Outside, - ); - if !m.enabled { - p.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(1.5, tk.danger)); + painter.rect_stroke(mask_rect, THUMBNAIL_ROUNDING, target_stroke(&tokens, mask_target), egui::StrokeKind::Outside); + if !mask.enabled { + painter.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.danger)); } - let mr = ui + let mask_response = ui .interact(mask_rect, ui.scope_id().with(("mask", layer.id.0)), Sense::click()) .on_hover_text(tr("Select the mask (Alt+click: show it in the viewport)")); - if mr.clicked() { + if mask_response.clicked() { app.run("layer.select", json!({"layer": layer.id.0, "target": "mask"})); - if ui.input(|i| i.modifiers.alt) { + if ui.input(|input| input.modifiers.alt) { let showing = app.session.view == texturecraft_engine::ViewMode::Mask(layer.id); - let p = if showing { json!({"mode": "material"}) } else { json!({"mode": "mask", "layer": layer.id.0}) }; - app.run("viewport.view", p); + let view = if showing { json!({"mode": "material"}) } else { json!({"mode": "mask", "layer": layer.id.0}) }; + app.run("viewport.view", view); } } if app.session.view == texturecraft_engine::ViewMode::Mask(layer.id) { - p.rect_stroke(mask_rect.expand(2.0), 2.0, Stroke::new(1.5, tk.warning), egui::StrokeKind::Outside); + painter.rect_stroke( + mask_rect.expand(HIGHLIGHT_OUTSET), + THUMBNAIL_ROUNDING, + Stroke::new(TARGET_BORDER_WIDTH, tokens.warning), + egui::StrokeKind::Outside, + ); } - x = mask_rect.right() + 8.0; } else { - // The empty slot adds a mask to this layer. - let slot_size = size.min(18.0); + // The empty slot adds a mask to this layer + let slot_size = thumbnail_size.min(MASK_SLOT_SIZE); mask_rect = Rect::from_min_size(pos2(x, rect.center().y - slot_size * 0.5), vec2(slot_size, slot_size)); let slot = ui.interact(mask_rect, ui.scope_id().with(("mask_slot", layer.id.0)), Sense::click()).on_hover_text(tr("Add mask")); - p.rect_stroke(mask_rect, 2.0, Stroke::new(1.0, if slot.hovered() { tk.accent } else { tk.field_border }), egui::StrokeKind::Inside); + let slot_color = if slot.hovered() { tokens.accent } else { tokens.field_border }; + painter.rect_stroke(mask_rect, THUMBNAIL_ROUNDING, Stroke::new(THUMBNAIL_BORDER_WIDTH, slot_color), egui::StrokeKind::Inside); if slot.hovered() { - p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::PLUS, egui::FontId::proportional(12.0), tk.text); + painter.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::PLUS, egui::FontId::proportional(EYE_FONT_SIZE), tokens.text); } egui::Popup::menu(&slot).show(|ui| add_mask_menu(app, ui, Some(layer.id.0))); - x = mask_rect.right() + 8.0; } - // Blend mode and opacity of the displayed channel, stacked at the right. - let blend_rect = Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - 4.0, rect.center().y - 18.0), vec2(RIGHT_COLUMN, 17.0)); - let op_rect = Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - 4.0, rect.center().y + 1.0), vec2(RIGHT_COLUMN, 17.0)); - // Name (or rename editor) with the quieter subtitle under it. + x = mask_rect.right() + THUMBNAIL_GAP; + + // Name (or rename editor) with the quieter subtitle under it let (name_rect, show_blend) = layer_name_layout(rect, x); - let show_name = name_rect.width() >= 20.0; + let show_name = name_rect.width() >= MIN_NAME_WIDTH; if !show_name { - resp.clone().on_hover_text(&layer.name); + row.clone().on_hover_text(&layer.name); if app.ui.rename.as_ref().is_some_and(|(id, _)| *id == layer.id.0) { app.ui.rename = None; } } - let renaming = app.ui.rename.as_ref().is_some_and(|(r, _)| *r == layer.id.0); + let renaming = app.ui.rename.as_ref().is_some_and(|(id, _)| *id == layer.id.0); if renaming { - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(name_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); - if let Some((_, buf)) = app.ui.rename.as_mut() { - // Escape reaches us instead of just unfocusing the field, so it can cancel. + let mut editor_ui = ui.new_child(egui::UiBuilder::new().max_rect(name_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); + if let Some((_, text)) = app.ui.rename.as_mut() { + // Escape reaches us instead of just unfocusing the field, so it can cancel let filter = egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, escape: true, ..Default::default() }; - let r = child.add(egui::TextEdit::singleline(buf).desired_width(name_rect.width()).event_filter(filter)); - if ui.input(|i| i.key_pressed(egui::Key::Escape)) { + let editor = editor_ui.add(egui::TextEdit::singleline(text).desired_width(name_rect.width()).event_filter(filter)); + if ui.input(|input| input.key_pressed(egui::Key::Escape)) { app.ui.rename = None; - } else if r.lost_focus() { - // Enter or a click elsewhere. - let name = buf.trim().to_string(); + } else if editor.lost_focus() { + // Enter or a click elsewhere + let name = text.trim().to_string(); app.ui.rename = None; if !name.is_empty() && name != layer.name { app.run("layer.rename", json!({"layer": layer.id.0, "name": name})); } - } else if !r.has_focus() { - // Only until the field has focus: requesting it every frame kept it from ever - // losing focus, which trapped the editor open and blocked every shortcut. - r.request_focus(); + } else if !editor.has_focus() { + // Only until the field has focus: asking every frame trapped the editor open and blocked every shortcut + editor.request_focus(); } } } else if show_name { - let galley = elided(&p, layer.name.clone(), 12.5, if layer.visible { tk.text_strong } else { tk.text_dim }, name_rect.width()); - p.galley(pos2(name_rect.left(), rect.center().y - 2.0 - galley.size().y), galley, tk.text); + let name_color = if layer.visible { tokens.text_strong } else { tokens.text_dim }; + let galley = elided(&painter, layer.name.clone(), LAYER_NAME_FONT_SIZE, name_color, name_rect.width()); + painter.galley(pos2(name_rect.left(), rect.center().y - NAME_LINE_GAP - galley.size().y), galley, tokens.text); let kind = tr(match &layer.kind { LayerKind::Paint => "Paint layer", LayerKind::Fill(_) => "Fill layer", LayerKind::Group { .. } => "Folder", LayerKind::Instance { .. } => "Instance", }); - let effects = layer.content_effects.len() + mask.as_ref().map_or(0, |m| m.effects.len()); + let effects = layer.content_effects.len() + mask.as_ref().map_or(0, |mask| mask.effects.len()); let subtitle = match (source, effects) { - (Some(src), _) => format!("{kind} · {} {src}", ic::LINK_SIMPLE), + (Some(source), _) => format!("{kind} · {} {source}", ic::LINK_SIMPLE), (None, 0) => kind.to_string(), (None, 1) => format!("{kind} · {}", tr("1 effect")), - (None, n) => format!("{kind} · {}", trf("{count} effects", &[("count", &n)])), + (None, count) => format!("{kind} · {}", trf("{count} effects", &[("count", &count)])), }; - let sub = elided(&p, subtitle, 10.0, tk.text_dim, name_rect.width()); - p.galley(pos2(name_rect.left(), rect.center().y + 2.0), sub, tk.text_dim); + let subtitle = elided(&painter, subtitle, LAYER_SUBTITLE_FONT_SIZE, tokens.text_dim, name_rect.width()); + painter.galley(pos2(name_rect.left(), rect.center().y + NAME_LINE_GAP), subtitle, tokens.text_dim); } - if let Some(b) = blend.filter(|_| show_blend) { - let br = ui.interact(blend_rect, ui.scope_id().with(("blend", layer.id.0)), Sense::click()).on_hover_text(tr("Blending mode of the displayed channel")); - if br.hovered() { - p.rect_filled(blend_rect, 2.0, tk.row_hover); + + // Blend mode and opacity of the displayed channel, stacked at the right + let mode_rect = Rect::from_min_size( + pos2(rect.right() - RIGHT_COLUMN - ROW_CONTROL_GAP, rect.center().y - ROW_CONTROL_HEIGHT - ROW_STACK_GAP), + vec2(RIGHT_COLUMN, ROW_CONTROL_HEIGHT), + ); + let opacity_rect = + Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - ROW_CONTROL_GAP, rect.center().y + ROW_STACK_GAP), vec2(RIGHT_COLUMN, ROW_CONTROL_HEIGHT)); + if let Some(channel_blend) = blend.filter(|_| show_blend) { + let id = ui.scope_id().with(("blend", layer.id.0)); + let (mode, opacity) = + blend_controls(ui, id, (mode_rect, opacity_rect), (channel_blend.mode, channel_blend.opacity), tr("Blending mode of the displayed channel")); + if let Some(mode) = mode { + app.run("layer.blend", json!({"layer": layer.id.0, "channel": channel.id(), "mode": format!("{mode:?}")})); } - p.text(blend_rect.right_center() - vec2(10.0, 0.0), egui::Align2::RIGHT_CENTER, b.mode.short(), egui::FontId::proportional(11.0), tk.text); - p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(8.0), tk.text_dim); - egui::Popup::menu(&br).show(|ui| { - ui.set_min_width(190.0); - for m in BlendMode::MENU { - match m { - Some(m) => { - if ui.selectable_label(m == b.mode, tr(m.label())).clicked() { - app.run("layer.blend", json!({"layer": layer.id.0, "channel": ch.id(), "mode": format!("{m:?}")})); - ui.close(); - } - } - None => { - ui.separator(); - } - } - } - }); - let mut op = (b.opacity * 100.0).round(); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(op_rect).layout(egui::Layout::right_to_left(egui::Align::Center))); - // As tall as its slot in the row (the style's fields are taller), in the row's small print. - child.spacing_mut().interact_size.y = op_rect.height(); - child.spacing_mut().button_padding = vec2(4.0, 0.0); - child.style_mut().override_text_style = Some(egui::TextStyle::Small); - let r = child.add(egui::DragValue::new(&mut op).range(0.0..=100.0).speed(0.5).max_decimals(0).suffix("%")); - if r.changed() { - app.run("layer.blend", json!({"layer": layer.id.0, "channel": ch.id(), "opacity": op / 100.0})); + if let Some((opacity, merge)) = opacity { + app.run("layer.blend", json!({"layer": layer.id.0, "channel": channel.id(), "opacity": opacity, "merge": merge})); } } else if show_blend { - p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(11.0), tk.text_dim); + painter.text(mode_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(ROW_SMALL_FONT_SIZE), tokens.text_dim); } - // Interaction: select, rename, drag & drop, context menu. - let on_control = eye_resp.clicked() || content_resp.clicked(); - if resp.clicked() && !on_control && !renaming { + + // Interaction: select, rename, drag & drop, context menu + let on_control = eye_response.clicked() || content_response.clicked(); + if row.clicked() && !on_control && !renaming { app.run("layer.select", json!({"layer": layer.id.0})); } - if resp.double_clicked() && !on_control && !renaming && show_name { + if row.double_clicked() && !on_control && !renaming && show_name { app.ui.rename = Some((layer.id.0, layer.name.clone())); } - if resp.drag_started() && !renaming { - resp.dnd_set_drag_payload(layer.id.0); + if row.drag_started() && !renaming { + row.dnd_set_drag_payload(layer.id.0); } - // Drops: a layer or a shelf material lands above this row (inside a folder when dropped on - // its middle); a shelf smart mask replaces this layer's mask. - let inside = layer.is_group() && ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| (p.y - rect.center().y).abs() < h * 0.25); - let shelf = resp.dnd_hover_payload::().map(|d| d.asset.clone()); - let moving = resp.dnd_hover_payload::().is_some_and(|src| *src != layer.id.0); + + // Drops: a layer or a shelf material lands above this row (inside a folder on its middle); a shelf smart mask replaces the mask + let inside = layer.is_group() + && ui.input(|input| input.pointer.hover_pos()).is_some_and(|pointer| (pointer.y - rect.center().y).abs() < row_height * FOLDER_DROP_ZONE); + let shelf = row.dnd_hover_payload::().map(|drag| drag.asset.clone()); + let moving = row.dnd_hover_payload::().is_some_and(|dragged| *dragged != layer.id.0); + let drop_stroke = Stroke::new(DROP_LINE_WIDTH, tokens.accent); if moving || shelf.as_ref().is_some_and(Asset::is_material) { if inside { - p.rect_stroke(rect, 2.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside); + painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); } else { - p.line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, tk.accent)); + painter.line_segment([rect.left_top(), rect.right_top()], drop_stroke); } } else if matches!(shelf, Some(Asset::SmartMask(_))) { - p.rect_stroke(mask_rect.expand(2.0), 2.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Outside); + painter.rect_stroke(mask_rect.expand(HIGHLIGHT_OUTSET), THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Outside); } else if matches!(shelf, Some(Asset::Filter(_))) && !layer.is_group() { - p.rect_stroke(rect, 2.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside); + painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); } - if let Some(src) = dnd_release::(&resp) - && *src != layer.id.0 + if let Some(dragged) = dnd_release::(&row) + && *dragged != layer.id.0 { - app.run("layer.move", json!({"layer": *src, "above": layer.id.0, "inside": inside})); + app.run("layer.move", json!({"layer": *dragged, "above": layer.id.0, "inside": inside})); } - match dnd_release::(&resp).map(|d| d.asset.clone()) { - Some(Asset::Material(m)) => { - app.run("material.apply", json!({"material": m, "above": layer.id.0, "inside": inside})); + match dnd_release::(&row).map(|drag| drag.asset.clone()) { + Some(Asset::Material(material)) => { + app.run("material.apply", json!({"material": material, "above": layer.id.0, "inside": inside})); } Some(Asset::Library(path)) => { app.run("material.load", json!({"path": path, "above": layer.id.0, "inside": inside})); } - Some(Asset::SmartMask(m)) => { - app.run("mask.smart.apply", json!({"name": m, "layer": layer.id.0})); + Some(Asset::SmartMask(smart_mask)) => { + app.run("mask.smart.apply", json!({"name": smart_mask, "layer": layer.id.0})); } - Some(Asset::Filter(f)) => { + Some(Asset::Filter(filter)) => { app.run("layer.select", json!({"layer": layer.id.0})); - app.run("effect.add.filter", json!({"layer": layer.id.0, "filter": f, "target": "content"})); + app.run("effect.add.filter", json!({"layer": layer.id.0, "filter": filter, "target": "content"})); } Some(Asset::Alpha(_) | Asset::Texture(_)) | None => {} } - resp.context_menu(|ui| layer_context_menu(app, ui, layer)); + row.context_menu(|ui| layer_context_menu(app, ui, layer)); +} + +/// The border of a content or mask thumbnail: the accent while it is the layer's target. +fn target_stroke(tokens: &Tokens, target: bool) -> Stroke { + if target { Stroke::new(TARGET_BORDER_WIDTH, tokens.accent) } else { Stroke::new(THUMBNAIL_BORDER_WIDTH, tokens.button_border) } } /// What a content thumbnail shows until its picture arrives (or where the layer has none). @@ -721,97 +780,194 @@ fn tree_lines(p: &egui::Painter, tk: &Tokens, rect: Rect, indent: f32, trunks: & /// The drag-and-drop payload of an effect row (the effect id). struct EffectDrag(u64); -/// Effect `e` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level`. +/// A stack row's blend mode menu and opacity field (percent): the mode picked, and the opacity (0..1) set this frame with whether it continues a drag. +fn blend_controls( + ui: &mut Ui, + id: egui::Id, + (mode_rect, opacity_rect): (Rect, Rect), + (mode, opacity): (BlendMode, f32), + hover: &str, +) -> (Option, Option<(f32, bool)>) { + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter().clone(); + + let mut picked = None; + let menu = ui.interact(mode_rect, id, Sense::click()).on_hover_text(hover); + if menu.hovered() { + painter.rect_filled(mode_rect, ROW_CONTROL_ROUNDING, tokens.row_hover); + } + let mode_font = egui::FontId::proportional(ROW_SMALL_FONT_SIZE); + painter.text(mode_rect.right_center() - vec2(CARET_WIDTH, 0.0), egui::Align2::RIGHT_CENTER, mode.short(), mode_font, tokens.text); + painter.text(mode_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(CARET_FONT_SIZE), tokens.text_dim); + egui::Popup::menu(&menu).show(|ui| { + ui.set_min_width(BLEND_MENU_MIN_WIDTH); + for item in BlendMode::MENU { + match item { + Some(item) => { + if ui.selectable_label(item == mode, tr(item.label())).clicked() { + picked = Some(item); + ui.close(); + } + } + None => { + ui.separator(); + } + } + } + }); + + let mut percent = (opacity * 100.0).round(); + let mut field_ui = ui.new_child(egui::UiBuilder::new().max_rect(opacity_rect).layout(egui::Layout::right_to_left(egui::Align::Center))); + // As tall as its slot in the row (the style's fields are taller), in the row's small print + field_ui.spacing_mut().interact_size.y = opacity_rect.height(); + field_ui.spacing_mut().button_padding = vec2(ROW_FIELD_PADDING, 0.0); + field_ui.style_mut().override_text_style = Some(egui::TextStyle::Small); + + // Plain text like the blend mode beside it: no field box, only the hover fill + let widgets = &mut field_ui.visuals_mut().widgets; + for state in [&mut widgets.inactive, &mut widgets.noninteractive] { + state.weak_bg_fill = Color32::TRANSPARENT; + state.bg_fill = Color32::TRANSPARENT; + state.bg_stroke = Stroke::NONE; + } + for state in [&mut widgets.hovered, &mut widgets.active] { + state.weak_bg_fill = tokens.row_hover; + state.bg_stroke = Stroke::NONE; + } + let field = field_ui.add(egui::DragValue::new(&mut percent).range(0.0..=100.0).speed(OPACITY_DRAG_SPEED).max_decimals(0).suffix("%")); + + // The later changes of one drag continue its first undo step + let merge = field.dragged() && !field.drag_started(); + (picked, field.changed().then_some((percent / 100.0, merge))) +} + +/// Effect `effect` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level`. #[allow(clippy::too_many_arguments)] -fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, level: usize, trunks: &[usize], last: bool, in_mask: bool) { - let tk = Tokens::get(ui.ctx()); - let (eid, visible) = (e.id, e.visible); - let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(eid); - let size = effect_preview_size(layer_preview_size(app)); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), effect_row_height(layer_preview_size(app))), Sense::click_and_drag()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &e.name)); - let p = ui.painter().clone(); - p.rect_filled( - rect, - 0.0, - if selected { - tk.row_selected - } else if resp.hovered() { - tk.row_hover - } else { - tk.panel - }, - ); - let indent = effect_row_indent(rect.width(), level, size); - tree_lines(&p, &tk, rect, indent, trunks, !last); +fn effect_row( + app: &mut TextureCraftApp, + ui: &mut Ui, + layer: &Layer, + stack: &[Effect], + effect: &Effect, + level: usize, + trunks: &[usize], + last: bool, + in_mask: bool, +) { + let tokens = Tokens::get(ui.ctx()); + let (effect_id, visible) = (effect.id, effect.visible); + let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(effect_id); + let preview_size = effect_preview_size(layer_preview_size(app)); + let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), effect_row_height(layer_preview_size(app))), Sense::click_and_drag()); + row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &effect.name)); + + // Background, tree lines and the selected row's accent edge + let painter = ui.painter().clone(); + // Effect rows alternate two shades just above the panel, counted from the top of their list + let row_index = stack.iter().rev().position(|other| other.id == effect_id).unwrap_or(0); + let background = if selected { + tokens.row_selected + } else if row.hovered() { + tokens.row_hover + } else { + tokens.panel.lerp_to_gamma(tokens.row_hover, EFFECT_ROW_SHADES[row_index % EFFECT_ROW_SHADES.len()]) + }; + painter.rect_filled(rect, 0.0, background); + let indent = effect_row_indent(rect.width(), level, preview_size); + tree_lines(&painter, &tokens, rect, indent, trunks, !last); if selected { - p.rect_filled(Rect::from_min_size(rect.min, vec2(3.0, rect.height())), 0.0, tk.accent); + painter.rect_filled(Rect::from_min_size(rect.min, vec2(SELECTED_EDGE_WIDTH, rect.height())), 0.0, tokens.accent); } - let x0 = rect.left() + 7.0 + indent; - let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(16.0, 16.0)); - let er = ui.interact(eye, ui.scope_id().with(("eff_eye", eid.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect")); - p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(12.0), tk.text_dim); - // The stack as it is up to and including this effect; a hidden one shows what it bypasses. - let thumb = Rect::from_min_size(pos2(x0 + 22.0, rect.center().y - size * 0.5), vec2(size, size)); - let ch = app.ui.layer_channel; - if !thumb_box(ui, app, thumb, ThumbTarget::Stage { effect: eid, channel: ch }, false) { + + // The eye, then the stack as it is up to and including this effect (a hidden one shows what it bypasses) + let content_left = rect.left() + ROW_LEFT_PADDING + indent; + let eye = Rect::from_center_size(pos2(content_left + EYE_SIZE * 0.5, rect.center().y), vec2(EYE_SIZE, EYE_SIZE)); + let eye_response = ui.interact(eye, ui.scope_id().with(("eff_eye", effect_id.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect")); + let eye_glyph = if visible { ic::EYE } else { ic::EYE_SLASH }; + painter.text(eye.center(), egui::Align2::CENTER_CENTER, eye_glyph, egui::FontId::proportional(EYE_FONT_SIZE), tokens.text_dim); + let thumbnail = Rect::from_min_size(pos2(content_left + EYE_COLUMN_WIDTH, rect.center().y - preview_size * 0.5), vec2(preview_size, preview_size)); + let channel = app.ui.layer_channel; + if !thumb_box(ui, app, thumbnail, ThumbTarget::Stage { effect: effect_id, channel }, false) { let glyph = if in_mask { ic::MAGIC_WAND } else { ic::SPHERE }; - p.text(thumb.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(size * 0.5), tk.text_dim); + painter.text(thumbnail.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(preview_size * 0.5), tokens.text_dim); } - p.rect_stroke(thumb, 2.0, Stroke::new(1.0, tk.button_border), egui::StrokeKind::Outside); + painter.rect_stroke(thumbnail, THUMBNAIL_ROUNDING, Stroke::new(THUMBNAIL_BORDER_WIDTH, tokens.button_border), egui::StrokeKind::Outside); if !visible { - p.line_segment([thumb.left_bottom(), thumb.right_top()], Stroke::new(1.5, tk.text_dim)); + painter.line_segment([thumbnail.left_bottom(), thumbnail.right_top()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.text_dim)); } - let name_x = thumb.right() + 8.0; - let galley = elided(&p, e.name.clone(), 11.5, if visible { tk.text } else { tk.text_dim }, (rect.right() - name_x - 6.0).max(20.0)); - p.galley(pos2(name_x, rect.center().y - galley.size().y * 0.5), galley, tk.text); - if er.clicked() { - app.run("effect.set", json!({"effect": eid.0, "visible": !visible})); - } else if resp.clicked() { - app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); + + // The name, then the blend mode and opacity side by side at the right when the name keeps room to be read + let name_left = thumbnail.right() + THUMBNAIL_GAP; + let controls_left = rect.right() - ROW_CONTROL_GAP - EFFECT_BLEND_WIDTH; + let show_blend = controls_left - ROW_CONTROL_GAP - name_left >= MIN_NAME_WIDTH; + let name_right = if show_blend { controls_left - ROW_CONTROL_GAP } else { rect.right() - ROW_RIGHT_PADDING }; + let name_color = if visible { tokens.text } else { tokens.text_dim }; + let galley = elided(&painter, effect.name.clone(), EFFECT_NAME_FONT_SIZE, name_color, (name_right - name_left).max(MIN_NAME_WIDTH)); + painter.galley(pos2(name_left, rect.center().y - galley.size().y * 0.5), galley, tokens.text); + if show_blend { + let mode_width = EFFECT_BLEND_WIDTH - ROW_CONTROL_GAP - EFFECT_OPACITY_WIDTH; + let mode_rect = Rect::from_center_size(pos2(controls_left + mode_width * 0.5, rect.center().y), vec2(mode_width, ROW_CONTROL_HEIGHT)); + let opacity_center = pos2(mode_rect.right() + ROW_CONTROL_GAP + EFFECT_OPACITY_WIDTH * 0.5, rect.center().y); + let opacity_rect = Rect::from_center_size(opacity_center, vec2(EFFECT_OPACITY_WIDTH, ROW_CONTROL_HEIGHT)); + let id = ui.scope_id().with(("eff_blend", effect_id.0)); + let (mode, opacity) = blend_controls(ui, id, (mode_rect, opacity_rect), (effect.blend, effect.opacity), tr("Blending mode of the effect")); + if let Some(mode) = mode { + app.run("effect.set", json!({"effect": effect_id.0, "blend": format!("{mode:?}")})); + } + if let Some((opacity, merge)) = opacity { + app.run("effect.set", json!({"effect": effect_id.0, "opacity": opacity, "merge": merge})); + } } - // Drag to reorder within the stack: a drop lands above this row, or below it from its lower half. - if resp.drag_started() { - resp.dnd_set_drag_payload(EffectDrag(eid.0)); + + if eye_response.clicked() { + app.run("effect.set", json!({"effect": effect_id.0, "visible": !visible})); + } else if row.clicked() { + app.run("layer.select", json!({"layer": layer.id.0, "target": effect_id.0})); } - let pos = |id: u64| stack.iter().position(|x| x.id.0 == id); - let below = ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| p.y > rect.center().y); - if resp.dnd_hover_payload::().is_some_and(|src| src.0 != eid.0 && pos(src.0).is_some()) { + + // Drag to reorder within the stack: a drop lands above this row, or below it from its lower half + if row.drag_started() { + row.dnd_set_drag_payload(EffectDrag(effect_id.0)); + } + let position = |id: u64| stack.iter().position(|other| other.id.0 == id); + let below = ui.input(|input| input.pointer.hover_pos()).is_some_and(|pointer| pointer.y > rect.center().y); + if row.dnd_hover_payload::().is_some_and(|dragged| dragged.0 != effect_id.0 && position(dragged.0).is_some()) { let y = if below { rect.bottom() } else { rect.top() }; - p.line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(2.0, tk.accent)); + painter.line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(DROP_LINE_WIDTH, tokens.accent)); } - if let Some(src) = dnd_release::(&resp) - && let (Some(from), Some(to)) = (pos(src.0), pos(eid.0)) + if let Some(dragged) = dnd_release::(&row) + && let (Some(from), Some(to)) = (position(dragged.0), position(effect_id.0)) && from != to { - // Rows list the stack top first, so above this row is the next index up. + // Rows list the stack top first, so above this row is the next index up let index = match (from < to, below) { (true, false) | (false, true) => to, (true, true) => to - 1, (false, false) => to + 1, }; - app.run("effect.move", json!({"effect": src.0, "index": index})); + app.run("effect.move", json!({"effect": dragged.0, "index": index})); } - resp.context_menu(|ui| { + + row.context_menu(|ui| { let keymap = app.ui.keymap.clone(); - // The row is selected before the paste runs, so a copied effect is all it needs. + // The row is selected before the paste runs, so a copied effect is all it needs let paste = texturecraft_engine::effect_clipboard::clipboard_effect(&app.session).is_some(); - // The clipboard items show the layer clipboard's shortcuts, which act on a selected effect. - for (label, id, keys, enabled) in [ + // The clipboard items show the layer clipboard's shortcuts, which act on a selected effect + for (label, command, keys, enabled) in [ (tr("Copy effect"), "effect.copy", Some("layer.copy"), true), (tr("Cut effect"), "effect.cut", Some("layer.cut"), true), (tr("Paste effect"), "effect.paste", Some("layer.paste"), paste), (tr("Duplicate effect"), "effect.duplicate", None, true), (tr("Remove effect"), "effect.remove", None, true), ] { - let mut b = egui::Button::new(label); - if let Some(sc) = keys.and_then(|k| crate::keymap::shortcut_of(&keymap, k)) { - b = b.shortcut_text(sc); + let mut button = egui::Button::new(label); + if let Some(shortcut) = keys.and_then(|key| crate::keymap::shortcut_of(&keymap, key)) { + button = button.shortcut_text(shortcut); } - if ui.add_enabled(enabled, b).clicked() { - // Selected first: a paste lands above it, a duplicate takes the selection. - app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); - app.run(id, json!({"effect": eid.0})); + if ui.add_enabled(enabled, button).clicked() { + // Selected first: a paste lands above it, a duplicate takes the selection + app.run("layer.select", json!({"layer": layer.id.0, "target": effect_id.0})); + app.run(command, json!({"effect": effect_id.0})); ui.close(); } } @@ -1069,7 +1225,7 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { } /// Menu items listing the image resources, then Import...: the image picked, if any. -fn image_menu(app: &mut TextureCraftApp, ui: &mut Ui) -> Option { +pub(crate) fn image_menu(app: &mut TextureCraftApp, ui: &mut Ui) -> Option { ui.label(caption(tr("Images"))); let mut picked = None; // Bounded, so Import... and the items after it stay on screen with many images. @@ -1092,7 +1248,7 @@ fn image_menu(app: &mut TextureCraftApp, ui: &mut Ui) -> Option { /// An image from the Assets panel dropped on `resp`, outlined while one hovers it. Other assets /// are left for the drop targets around it. -fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { +pub(crate) fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { if !resp.dnd_hover_payload::().is_some_and(|d| matches!(d.asset, Asset::Texture(_))) { return None; } @@ -1103,7 +1259,7 @@ fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { } } -fn mesh_map_color(map: BakedMap) -> Color32 { +pub(crate) fn mesh_map_color(map: BakedMap) -> Color32 { match map { BakedMap::Normal => Color32::from_rgb(128, 128, 255), BakedMap::WorldNormal => Color32::from_rgb(120, 200, 140), @@ -1910,7 +2066,7 @@ fn with(base: &Value, extra: Value) -> Value { } /// Anchor points below layer `reader` in its texture set: (effect id, "layer / anchor" label). -fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String)> { +pub(crate) fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String)> { let p = &app.session.doc.project; let Some((ts, _, _)) = p.locate(reader) else { return Vec::new() }; p.walk(ts) @@ -1922,7 +2078,7 @@ fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String .collect() } -fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> String { +pub(crate) fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> String { let name = app.session.doc.project.effect(anchor).map(|(_, e)| e.name.clone()).unwrap_or_else(|| tr("missing").into()); trf("Anchor: {name} ({channel})", &[("name", &name), ("channel", &tr(channel.label()))]) } @@ -2221,30 +2377,16 @@ fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Valu } } -fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId) { - let tk = Tokens::get(ui.ctx()); - let Some((_, effect)) = app.session.doc.project.effect(eid).map(|(owner, effect)| (owner, effect.clone())) else { return }; +/// The properties of effect `effect_id` of `layer`: each kind's own settings. +fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId) { + let tokens = Tokens::get(ui.ctx()); + let Some(effect) = app.session.doc.project.effect(effect_id).map(|(_, effect)| effect.clone()) else { return }; - let id = eid.0; - ui.horizontal(|ui| { - ui.label(tr("Blending")); - egui::ComboBox::from_id_salt("eff_blend").selected_text(tr(effect.blend.label())).show_ui(ui, |ui| { - for mode in BlendMode::all() { - if ui.selectable_label(mode == effect.blend, tr(mode.label())).clicked() { - app.run("effect.set", json!({"effect": id, "blend": format!("{mode:?}")})); - } - } - }); - }); - let mut opacity = effect.opacity; - if let Some(merge) = slider_edit(ui, tr("Opacity"), &mut opacity, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": id, "opacity": opacity, "merge": merge})); - } - ui.separator(); + let id = effect_id.0; match &effect.kind { - EffectKind::Generator(generator) => generator_properties(app, ui, id, generator), - EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, eid, levels), + EffectKind::Generator(generator) => crate::generator_panel::generator_properties(app, ui, layer.id, id, generator), + EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels), EffectKind::Fill { source, .. } => { ui.label(caption(tr("Fill"))); let anchors = anchors_below(app, layer.id); @@ -2280,12 +2422,12 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: } } }); - ui.label(RichText::new(tr("Colors read as gray. Add a levels or blur effect above to shape the result.")).color(tk.text_dim)); + ui.label(RichText::new(tr("Colors read as gray. Add a levels or blur effect above to shape the result.")).color(tokens.text_dim)); } _ => {} } if anchors.is_empty() { - ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tk.text_dim)); + ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tokens.text_dim)); } } EffectKind::Material(fill) => { @@ -2297,27 +2439,27 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: ui.label(caption(tr("Anchor point"))); ui.label( RichText::new(tr("Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.")) - .color(tk.text_dim), + .color(tokens.text_dim), ); } EffectKind::Paint => { - let hint = if layer.content_effects.iter().any(|content| content.id == eid) { + let hint = if layer.content_effects.iter().any(|content| content.id == effect_id) { tr("Paint on the mesh to edit the layer content.") } else { tr("Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.") }; - ui.label(RichText::new(hint).color(tk.text_dim)); + ui.label(RichText::new(hint).color(tokens.text_dim)); tool_properties(app, ui); } EffectKind::Path(paths) => { ui.label( RichText::new(tr("Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.")) - .color(tk.text_dim), + .color(tokens.text_dim), ); let editing = app.session.tool.path.editing; for index in 0..paths.len() { ui.horizontal(|ui| { - let selected = editing == Some((eid, index)); + let selected = editing == Some((effect_id, index)); if ui.selectable_label(selected, format!("{} {}", tr("Path"), index + 1)).on_hover_text(tr("Edit")).clicked() { if selected { app.run("tool.path", json!({"clear": true})); @@ -2325,7 +2467,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: app.run("path.edit", json!({"effect": id, "index": index})); } } - if icon_button(ui, ic::TRASH, tr("Remove"), false, 22.0).clicked() { + if icon_button(ui, ic::TRASH, tr("Remove"), false, ICON_BUTTON_SIZE).clicked() { app.run("path.remove", json!({"effect": id, "index": index})); } }); @@ -2333,86 +2475,13 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: tool_properties(app, ui); } EffectKind::Filter(filter) => filter_properties(app, ui, id, filter), - EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_editor::color_selection_properties(app, ui, eid, colors, *tolerance), + EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, colors, *tolerance), other => { - ui.label(RichText::new(tr(other.name())).color(tk.text_dim)); + ui.label(RichText::new(tr(other.name())).color(tokens.text_dim)); } } } -/// The settings of generator effect `id`. -fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { - let tk = Tokens::get(ui.ctx()); - ui.label(caption(tr("Generator"))); - egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(generator.kind.label())).show_ui(ui, |ui| { - for kind in GeneratorKind::ALL { - if ui.selectable_label(kind == generator.kind, tr(kind.label())).clicked() { - // Replace the generator kind: remove and add keeps ordering simple - app.run("effect.remove", json!({"effect": id})); - app.run("effect.add.generator", json!({"generator": format!("{kind:?}")})); - } - } - }); - - let (mut level, mut softness, mut noise, mut noise_scale, mut offset, mut invert) = - (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.offset, generator.invert); - let level_edit = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); - let softness_edit = slider_edit(ui, tr("Softness"), &mut softness, 0.0..=1.0, 2); - let noise_edit = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); - let noise_scale_edit = slider_edit(ui, tr("Noise scale"), &mut noise_scale, 0.1..=64.0, 1); - let offset_edit = slider_edit(ui, tr("Offset"), &mut offset, -1.0..=1.0, 2); - let invert_edit = ui.checkbox(&mut invert, tr("Invert")).changed().then_some(false); - if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(offset_edit).or(invert_edit) { - app.run( - "effect.set", - json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "offset": offset, "invert": invert, "merge": merge}), - ); - } - - if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { - curvature_detail_properties(app, ui, id, generator.detail.as_ref()); - } - if !app.session.doc.baked.contains_key(&app.session.ts()) { - ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tk.warning)); - } -} - -/// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes). -fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) { - let tk = Tokens::get(ui.ctx()); - let shown = detail.cloned().unwrap_or_default(); - combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| { - for mode in CurvatureMode::ALL { - if ui.selectable_label(mode == shown.mode, curvature_mode_label(mode)).clicked() { - app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")})); - } - } - }); - - ui.label(caption(tr("Detail sizes"))); - let mut weights = shown.weights; - let mut edit = None; - for (weight, size) in weights.iter_mut().zip(CurvatureDetail::SIZES) { - edit = edit.or(slider_edit(ui, &format!("{size} px"), weight, 0.0..=1.0, 2)); - } - if let Some(merge) = edit { - app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); - } - if detail.is_none() { - ui.label(RichText::new(tr("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.")).color(tk.text_dim)); - } -} - -/// The translated name of curvature mode `mode`. -fn curvature_mode_label(mode: CurvatureMode) -> &'static str { - match mode { - CurvatureMode::Edges => tr("Edges"), - CurvatureMode::Cavities => tr("Cavities"), - CurvatureMode::Both => tr("Edges and cavities"), - CurvatureMode::Raw => tr("Raw curvature"), - } -} - /// The filter slot and the parameters of filter effect `id` fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, filter: &Filter) { let tk = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs new file mode 100644 index 00000000..99b93905 --- /dev/null +++ b/crates/ui-egui/src/generator_panel.rs @@ -0,0 +1,385 @@ +//! A generator effect's properties, laid out like the reference app's: attributes, resolution, parameters, image inputs. + +use egui::{RichText, Ui}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::core::{BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, OutputResolution, ResolutionMode, Source}; + +use crate::TextureCraftApp; +use crate::dock::{anchor_label, anchors_below, image_drop, image_menu, mesh_map_color}; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::theme::{Tokens, caption}; +use crate::widgets::{combo, section, slider_edit}; + +/// Random seeds stay below this, short enough to read and type. +const SEED_RANGE: u32 = 10_000; +/// Knuth's multiplicative hash constant: spreads the clock's nanoseconds over the seed range. +const SEED_MIX: u32 = 2_654_435_761; + +/// Font size of the notes under a control. +const NOTE_FONT_SIZE: f32 = 10.5; + +/// Edge of the picture beside each image input, its corner rounding and the size of an icon drawn in it. +const INPUT_TILE_SIZE: f32 = 32.0; +const INPUT_TILE_ROUNDING: f32 = 2.0; +const INPUT_TILE_ICON_SIZE: f32 = 16.0; + +/// Width of the names in the Attributes section, so their values line up. +const ATTRIBUTE_KEY_WIDTH: f32 = 80.0; + +/// The settings of generator effect `id`. +pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, id: u64, generator: &Generator) { + let tokens = Tokens::get(ui.ctx()); + ui.label(caption(tr("Generator"))); + egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(generator.kind.label())).show_ui(ui, |ui| { + for kind in GeneratorKind::ALL { + if ui.selectable_label(kind == generator.kind, tr(kind.label())).clicked() { + // Another kind starts from its own defaults: this effect is removed and one of that kind added + app.run("effect.remove", json!({"effect": id})); + app.run("effect.add.generator", json!({"generator": format!("{kind:?}")})); + } + } + }); + + section(ui, "generator_attributes", tr("Attributes"), false, |ui| attributes(ui, generator.kind)); + section(ui, "generator_resolution", tr("Resolution"), false, |ui| resolution(app, ui, id, generator.resolution)); + section(ui, "generator_parameters", tr("Parameters"), true, |ui| { + global_adjustments(app, ui, id, generator); + ramp_parameters(app, ui, id, generator); + if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { + curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + } + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Restore defaults")).clicked() { + app.run("effect.set", defaults_of(id, generator.kind)); + } + }); + }); + }); + if !generator.kind.inputs().is_empty() { + section(ui, "generator_inputs", tr("Image inputs"), true, |ui| { + for map in generator.kind.inputs() { + input_slot(app, ui, (layer, id), *map, generator.inputs.get(map), generator.detail.is_some()); + } + }); + } + if !app.session.doc.baked.contains_key(&app.session.ts()) { + ui.label( + RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tokens.warning), + ); + } +} + +/// What a generator kind makes, its category and its tags (read only). +fn attributes(ui: &mut Ui, kind: GeneratorKind) { + let tokens = Tokens::get(ui.ctx()); + let (description, tags) = match kind { + GeneratorKind::EdgeWear => ( + tr("Convex edges from the curvature map, broken up by noise: worn paint and polished edges."), + [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")], + ), + GeneratorKind::Dirt => ( + tr("Crevices and occluded areas from the ambient occlusion map: dirt and grime."), + [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")], + ), + GeneratorKind::ThinAreas => (tr("Thin parts of the mesh from the thickness map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("thickness")]), + GeneratorKind::Curvature => ( + tr("Convex edges, cavities or both from the curvature map, at several detail sizes."), + [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")], + ), + GeneratorKind::AmbientOcclusion => { + (tr("Occluded areas from the ambient occlusion map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]) + } + GeneratorKind::Position => (tr("A gradient along a world direction across the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), + GeneratorKind::Direction => (tr("Surfaces facing a direction, as if lit from it."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), + }; + + // Wrapped rows: a long line must not widen the panel past its edge + let tags = tags.join(", "); + for (key, value) in [(tr("Description"), description), (tr("Category"), tr("Generators")), (tr("Tags"), tags.as_str())] { + ui.horizontal_top(|ui| { + ui.add_sized([ATTRIBUTE_KEY_WIDTH, 0.0], egui::Label::new(RichText::new(key).color(tokens.text_dim))); + ui.add(egui::Label::new(value).wrap()); + }); + } +} + +/// What the generator's output resolution is based on, the factor applied to it, and the size it comes to. +fn resolution(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, resolution: OutputResolution) { + let tokens = Tokens::get(ui.ctx()); + combo(ui, tr("Resolution"), tr(resolution.mode.label()), |ui| { + for mode in ResolutionMode::ALL { + if ui.selectable_label(mode == resolution.mode, tr(mode.label())).clicked() { + app.run("effect.set", json!({"effect": id, "resolution": format!("{mode:?}")})); + } + } + }) + .on_hover_text(tr("Auto and UV tile use the UV tile's resolution, Texture set the texture set's, Custom a size of its own.")); + if resolution.mode == ResolutionMode::Custom { + combo(ui, tr("Size"), format!("{0} × {0}", resolution.custom), |ui| { + for size in OutputResolution::CUSTOM_SIZES { + if ui.selectable_label(size == resolution.custom, format!("{size} × {size}")).clicked() { + app.run("effect.set", json!({"effect": id, "customResolution": size})); + } + } + }); + } + combo(ui, tr("Factor"), factor_label(resolution.factor), |ui| { + for factor in OutputResolution::FACTORS { + if ui.selectable_label(factor == resolution.factor, factor_label(factor)).clicked() { + app.run("effect.set", json!({"effect": id, "resolutionFactor": factor})); + } + } + }) + .on_hover_text(tr("Scales the base resolution: below 1 the generator is computed coarser and smoothed back up.")); + + let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.resolution) else { return }; + + let size = resolution.output_size(texture_set, texture_set); + ui.horizontal(|ui| { + ui.label(RichText::new(tr("Output size")).color(tokens.text_dim)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(format!("{size} × {size}"))); + }) + .response + .on_hover_text(tr("A finer output than the texture set gives the same result as the texture set's resolution.")); +} + +/// The most powers of two a resolution factor scales by, either way. +const LARGEST_FACTOR_STEPS: u8 = OutputResolution::FACTORS.end().unsigned_abs(); + +/// "Same as context", or the fraction or multiple a resolution factor stands for. +fn factor_label(factor: i8) -> String { + match factor { + 0 => tr("Same as context").to_string(), + negative if negative < 0 => format!("1/{}", 1u32 << negative.unsigned_abs().min(LARGEST_FACTOR_STEPS)), + positive => format!("×{}", 1u32 << positive.unsigned_abs().min(LARGEST_FACTOR_STEPS)), + } +} + +/// Global invert, blur, balance and contrast: what every generator applies to its finished value. +fn global_adjustments(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { + let (mut invert, mut global) = (generator.invert, generator.global); + let invert_edit = ui.checkbox(&mut invert, tr("Global invert")).changed().then_some(false); + let blur_edit = slider_edit(ui, tr("Global blur"), &mut global.blur, 0.0..=1.0, 2); + let balance_edit = slider_edit(ui, tr("Global balance"), &mut global.balance, 0.0..=1.0, 2); + let contrast_edit = slider_edit(ui, tr("Global contrast"), &mut global.contrast, 0.0..=1.0, 2); + if let Some(merge) = invert_edit.or(blur_edit).or(balance_edit).or(contrast_edit) { + app.run( + "effect.set", + json!({"effect": id, "invert": invert, "blur": global.blur, "balance": global.balance, "contrast": global.contrast, "merge": merge}), + ); + } +} + +/// Where the generator's ramp starts, how soft it is, the noise breaking it up, its offset and its seed. +fn ramp_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { + let (mut level, mut softness, mut noise, mut noise_scale, mut offset) = + (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.offset); + let level_edit = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); + let softness_edit = slider_edit(ui, tr("Softness"), &mut softness, 0.0..=1.0, 2); + let noise_edit = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); + let noise_scale_edit = slider_edit(ui, tr("Noise scale"), &mut noise_scale, 0.1..=64.0, 1); + let offset_edit = slider_edit(ui, tr("Offset"), &mut offset, -1.0..=1.0, 2); + if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(offset_edit) { + app.run( + "effect.set", + json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "offset": offset, "merge": merge}), + ); + } + seed_row(app, ui, id, generator.seed); +} + +/// The seed with a button that picks a new one and a pencil that opens a field to type it, as in the reference. +fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { + let typing_id = ui.make_persistent_id(("generator_seed_typing", id)); + let mut typing = ui.data(|data| data.get_temp::(typing_id)).unwrap_or(false); + ui.horizontal(|ui| { + ui.label(tr("Seed")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.selectable_label(typing, ic::PENCIL_SIMPLE).on_hover_text(tr("Type the seed")).clicked() { + typing = !typing; + } + if typing { + let mut typed = seed; + let field = ui.add(egui::DragValue::new(&mut typed).speed(1.0)); + if field.changed() { + // The later changes of one drag continue its first undo step + let merge = field.dragged() && !field.drag_started(); + app.run("effect.set", json!({"effect": id, "seed": typed, "merge": merge})); + } + } else if ui.button(tr("Random")).on_hover_text(trf("Seed {seed}", &[("seed", &seed)])).clicked() { + app.run("effect.set", json!({"effect": id, "seed": random_seed(seed)})); + } + }); + }); + ui.data_mut(|data| data.insert_temp(typing_id, typing)); +} + +/// A seed different from `current`, from the clock. +fn random_seed(current: u32) -> u32 { + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.subsec_nanos()); + let mixed = nanos.wrapping_mul(SEED_MIX) % SEED_RANGE; + if mixed == current { (mixed + 1) % SEED_RANGE } else { mixed } +} + +/// The `effect.set` params that put generator effect `id` back to the defaults of its kind. +fn defaults_of(id: u64, kind: GeneratorKind) -> Value { + let defaults = Generator::new(kind); + let mut params = json!({ + "effect": id, + "level": defaults.level, + "softness": defaults.softness, + "noise": defaults.noise_amount, + "noiseScale": defaults.noise_scale, + "offset": defaults.offset, + "seed": defaults.seed, + "direction": defaults.direction, + "invert": defaults.invert, + "blur": defaults.global.blur, + "balance": defaults.global.balance, + "contrast": defaults.global.contrast, + "resolution": format!("{:?}", defaults.resolution.mode), + "customResolution": defaults.resolution.custom, + "resolutionFactor": defaults.resolution.factor, + }); + if let Some(detail) = defaults.detail { + params["mode"] = json!(format!("{:?}", detail.mode)); + params["sizes"] = json!(detail.weights); + } + params +} + +/// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes). +fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) { + let tokens = Tokens::get(ui.ctx()); + let shown = detail.cloned().unwrap_or_default(); + combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| { + for mode in CurvatureMode::ALL { + if ui.selectable_label(mode == shown.mode, curvature_mode_label(mode)).clicked() { + app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")})); + } + } + }); + + ui.label(caption(tr("Detail sizes"))); + let mut weights = shown.weights; + let mut edit = None; + for (weight, size) in weights.iter_mut().zip(CurvatureDetail::SIZES) { + edit = edit.or(slider_edit(ui, &format!("{size} px"), weight, 0.0..=1.0, 2)); + } + if let Some(merge) = edit { + app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); + } + if detail.is_none() { + ui.label(RichText::new(tr("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.")).color(tokens.text_dim)); + } +} + +/// The translated name of curvature mode `mode`. +fn curvature_mode_label(mode: CurvatureMode) -> &'static str { + match mode { + CurvatureMode::Edges => tr("Edges"), + CurvatureMode::Cavities => tr("Cavities"), + CurvatureMode::Both => tr("Edges and cavities"), + CurvatureMode::Raw => tr("Raw curvature"), + } +} + +/// One input of generator effect `id` on `layer`: what it reads (its mesh map unless `source` replaces it), a menu to replace it, and a button to read the mesh map again. +fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64), map: BakedMap, source: Option<&Source>, detail_sizes: bool) { + let tokens = Tokens::get(ui.ctx()); + let input = map.id(); + let current = match source { + None => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]), + Some(Source::Image { name, .. }) => trf("Image: {name}", &[("name", name)]), + Some(Source::Uniform(_)) => tr("Uniform value").to_string(), + Some(Source::Anchor { anchor, channel }) => anchor_label(app, *anchor, *channel), + Some(Source::Procedural { .. }) => tr("Procedural").to_string(), + }; + let group = ui.group(|ui| { + ui.horizontal(|ui| { + input_tile(app, ui, map, source); + ui.vertical(|ui| { + ui.label(RichText::new(tr(baked_map_label(map))).strong()); + ui.label(RichText::new(¤t).size(NOTE_FONT_SIZE).color(tokens.text_dim)); + }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if source.is_some() && ui.button(ic::X).on_hover_text(tr("Read the mesh map again")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); + } + }); + }); + combo(ui, tr("Source"), current.clone(), |ui| { + let anchors = anchors_below(app, layer); + if ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); + } + if ui.selectable_label(matches!(source, Some(Source::Uniform(_))), tr("Uniform value")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": map.neutral()[0]})); + } + for (anchor, label) in &anchors { + if ui + .selectable_label( + matches!(source, Some(Source::Anchor { anchor: picked, .. }) if picked == anchor), + trf("Anchor: {name}", &[("name", label)]), + ) + .clicked() + { + app.run("effect.set", json!({"effect": id, "input": input, "inputAnchor": anchor.0})); + } + } + if let Some(name) = image_menu(app, ui) { + app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); + } + }); + if let Some(Source::Uniform(value)) = source { + let mut value = value[0]; + if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": value, "merge": merge})); + } + } + if detail_sizes && map == BakedMap::Curvature && source.is_some_and(|source| !matches!(source, Source::Uniform(_))) { + ui.label( + RichText::new(tr("Detail sizes blur the mesh map, so a replaced curvature input is read at its own size only.")) + .size(NOTE_FONT_SIZE) + .color(tokens.text_dim), + ); + } + }); + if let Some(name) = image_drop(ui, &group.response) { + app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); + } +} + +/// The picture of what an input reads: the image itself, the uniform value's gray, or the mesh map's swatch (as in the texture set's list). +fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, source: Option<&Source>) { + let tokens = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(egui::vec2(INPUT_TILE_SIZE, INPUT_TILE_SIZE), egui::Sense::hover()); + let painter = ui.painter(); + let whole = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); + match source { + Some(Source::Image { name, .. }) => match app.session.images.get(name) { + Some(image) => { + let texture = app.thumbs.image(ui.ctx(), name, image); + painter.image(texture.id(), rect, whole, egui::Color32::WHITE); + } + None => { + painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); + } + }, + Some(Source::Uniform(value)) => { + painter.rect_filled(rect, INPUT_TILE_ROUNDING, egui::Color32::from_gray((value[0].clamp(0.0, 1.0) * 255.0).round() as u8)); + } + Some(Source::Anchor { .. } | Source::Procedural { .. }) => { + let glyph = if matches!(source, Some(Source::Anchor { .. })) { ic::ANCHOR } else { ic::MAGIC_WAND }; + painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); + painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(INPUT_TILE_ICON_SIZE), tokens.text_dim); + } + None => { + let baked = app.session.doc.baked.get(&app.session.ts()).is_some_and(|baked| baked.maps.contains_key(&map)); + painter.rect_filled(rect, INPUT_TILE_ROUNDING, if baked { mesh_map_color(map) } else { tokens.button }); + } + } + painter.rect_stroke(rect, INPUT_TILE_ROUNDING, egui::Stroke::new(1.0, tokens.button_border), egui::StrokeKind::Outside); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 815ba793..4dd0b5fc 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -20,6 +20,7 @@ pub mod export_templates; pub mod file_dialogs; mod filter_slot; pub mod fonts; +mod generator_panel; pub mod gpu; pub mod i18n; pub mod id_color_pick; diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index 218eb0cc..156b6616 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -1,4 +1,4 @@ -//! Effect rows in the layer stack: dragging one reorders its stack. +//! Effect rows in the layer stack: dragging one reorders its stack, and its blend mode and opacity sit at its right. use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -12,16 +12,16 @@ fn id(v: Value, key: &str) -> u64 { } /// Drag the row labelled `from` onto the upper (`below` false) or lower half of the row `to`. -fn drag(h: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) { - let start = h.get_by_label(from).rect().center(); - let r = h.get_by_label(to).rect(); - let end = egui::pos2(r.center().x, if below { r.bottom() - 4.0 } else { r.top() + 4.0 }); - h.drag_at(start); - h.run_steps(2); - h.hover_at(end); - h.run_steps(2); - h.drop_at(end); - h.run_steps(3); +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) { + let start = harness.get_by_label(from).rect().center(); + let row_rect = harness.get_by_label(to).rect(); + let end = egui::pos2(row_rect.center().x, if below { row_rect.bottom() - 4.0 } else { row_rect.top() + 4.0 }); + harness.drag_at(start); + harness.run_steps(2); + harness.hover_at(end); + harness.run_steps(2); + harness.drop_at(end); + harness.run_steps(3); } #[test] @@ -32,17 +32,54 @@ fn dragging_an_effect_row_reorders_its_stack() { |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C")); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.run_steps(4); - let order = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); - assert_eq!(order(&h), [a, b, c]); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let order = + |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); + assert_eq!(order(&harness), [a, b, c]); // The rows list the top first: C, B, A. A dropped on C's upper half goes to the top. - drag(&mut h, "Effect A", "Effect C", false); - assert_eq!(order(&h), [b, c, a]); + drag(&mut harness, "Effect A", "Effect C", false); + assert_eq!(order(&harness), [b, c, a]); // A dropped on B's lower half goes back to the bottom. - drag(&mut h, "Effect A", "Effect B", true); - assert_eq!(order(&h), [a, b, c]); + drag(&mut harness, "Effect A", "Effect B", true); + assert_eq!(order(&harness), [a, b, c]); // C dropped on A's upper half lands between A and B. - drag(&mut h, "Effect C", "Effect A", false); - assert_eq!(order(&h), [a, c, b]); + drag(&mut harness, "Effect C", "Effect A", false); + assert_eq!(order(&harness), [a, c, b]); +} + +/// An effect row's blend mode menu and opacity field sit at its right, as on layer rows. +#[test] +fn an_effect_row_sets_its_blend_mode_and_opacity() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect"); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); + assert_eq!(effect, effect_of(&harness).id.0); + + // From the row's right edge: a 4-point gap, then the 82-point pair of mode menu and opacity field + let row = harness.get_by_label("Effect A").rect(); + let pair_right = row.right() - 4.0; + let pair_left = pair_right - 82.0; + let mode_at = egui::pos2(pair_left + 20.0, row.center().y); + harness.drag_at(mode_at); + harness.drop_at(mode_at); + harness.run_steps(2); + harness.get_by_label("Multiply").click(); + harness.run_steps(3); + assert_eq!(effect_of(&harness).blend, texturecraft_engine::core::BlendMode::Multiply); + + let history = harness.state().session.history_labels().len(); + let opacity_at = egui::pos2(pair_right - 20.0, row.center().y); + harness.drag_at(opacity_at); + harness.run_steps(2); + harness.hover_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(2); + harness.drop_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(3); + assert!(effect_of(&harness).opacity < 0.9, "dragging the field to the left lowers the opacity: {}", effect_of(&harness).opacity); + assert_eq!(harness.state().session.history_labels().len(), history + 1, "the whole drag is one undo step"); } diff --git a/crates/ui-egui/tests/it/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs index a26ac303..469edeca 100644 --- a/crates/ui-egui/tests/it/effect_sliders.rs +++ b/crates/ui-egui/tests/it/effect_sliders.rs @@ -1,5 +1,4 @@ -//! The sliders of a selected effect (opacity, generator, levels…) apply what they were dragged -//! or clicked to. +//! A selected effect's sliders apply what they are dragged, clicked or typed to (a generator's global balance stands in for them all). use egui::accesskit::Role; use egui_kittest::Harness; @@ -9,79 +8,82 @@ use texturecraft_engine::core::{EffectKind, LayerId}; use texturecraft_ui_egui::TextureCraftApp; /// The sample session with its first generator effect selected, and that effect's id. -fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) { +fn selected_generator() -> (Harness<'static, TextureCraftApp>, LayerId) { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let (layer, effect) = session .doc .project .layers .values() - .find_map(|l| { - let mask = l.mask.iter().flat_map(|m| m.effects.iter()); - l.content_effects.iter().chain(mask).find(|e| matches!(e.kind, EffectKind::Generator(_))).map(|e| (l.id, e.id)) + .find_map(|label_rect| { + let mask = label_rect.mask.iter().flat_map(|m| m.effects.iter()); + label_rect.content_effects.iter().chain(mask).find(|e| matches!(e.kind, EffectKind::Generator(_))).map(|e| (label_rect.id, e.id)) }) .unwrap(); texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.run_steps(4); - (h, effect) + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + (harness, effect) } -fn opacity(h: &Harness<'_, TextureCraftApp>, effect: LayerId) -> f32 { - h.state().session.doc.project.effect(effect).unwrap().1.opacity +fn balance(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> f32 { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Generator(generator) => generator.global.balance, + _ => panic!("a generator"), + } } /// The track under the slider labelled `label` (the row below the label). -fn track(h: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect { - let l = h.get_by_label(label).rect(); - egui::Rect::from_min_max(egui::pos2(l.left() + 6.0, l.bottom() + 6.0), egui::pos2(l.left() + 200.0, l.bottom() + 14.0)) +fn track(harness: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect { + let label_rect = harness.get_by_label(label).rect(); + egui::Rect::from_min_max(egui::pos2(label_rect.left() + 6.0, label_rect.bottom() + 6.0), egui::pos2(label_rect.left() + 200.0, label_rect.bottom() + 14.0)) } #[test] -fn dragging_the_effect_opacity_applies_it() { - let (mut h, effect) = harness(); - assert_eq!(opacity(&h, effect), 1.0); - let t = track(&h, "Opacity"); - h.drag_at(egui::pos2(t.right(), t.center().y)); - h.run_steps(2); - h.hover_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(2); - h.drop_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(3); - assert!(opacity(&h, effect) < 0.5, "the dragged opacity applies: {}", opacity(&h, effect)); +fn dragging_a_slider_applies_it() { + let (mut harness, effect) = selected_generator(); + assert_eq!(balance(&harness, effect), 0.5); + let track_rect = track(&harness, "Global balance"); + harness.drag_at(egui::pos2(track_rect.right(), track_rect.center().y)); + harness.run_steps(2); + harness.hover_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(2); + harness.drop_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(3); + assert!(balance(&harness, effect) < 0.25, "the dragged balance applies: {}", balance(&harness, effect)); } /// A generator slider applies while it is dragged (the texture follows the pointer), and the /// whole drag is one undo step. #[test] fn dragging_a_generator_slider_applies_live_as_one_undo_step() { - let (mut h, effect) = harness(); - let level = |h: &Harness<'_, TextureCraftApp>| match &h.state().session.doc.project.effect(effect).unwrap().1.kind { + let (mut harness, effect) = selected_generator(); + let level = |harness: &Harness<'_, TextureCraftApp>| match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { EffectKind::Generator(g) => g.level, _ => panic!("a generator"), }; - let steps = h.state().session.history_labels().len(); - let t = track(&h, "Level"); - let at = |x: f32| egui::pos2(t.left() + x, t.center().y); - h.drag_at(at(10.0)); - h.run_steps(2); + let steps = harness.state().session.history_labels().len(); + let track_rect = track(&harness, "Level"); + let at = |x: f32| egui::pos2(track_rect.left() + x, track_rect.center().y); + harness.drag_at(at(10.0)); + harness.run_steps(2); let mut last = 0.0; for x in [60.0, 160.0] { - h.hover_at(at(x)); - h.run_steps(2); - assert!(level(&h) > last && level(&h) != 0.5, "the level follows the drag before it is released: {last} -> {}", level(&h)); - last = level(&h); + harness.hover_at(at(x)); + harness.run_steps(2); + assert!(level(&harness) > last && level(&harness) != 0.5, "the level follows the drag before it is released: {last} -> {}", level(&harness)); + last = level(&harness); } - h.drop_at(at(160.0)); - h.run_steps(3); - assert_eq!(level(&h), last); - assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); + harness.drop_at(at(160.0)); + harness.run_steps(3); + assert_eq!(level(&harness), last); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); } /// The combo box in the row of the levels editor's Reset button. -fn channel_picker<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { - let row = h.get_by_label("Reset").rect().center().y; - h.get_all(by().role(Role::ComboBox)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() +fn channel_picker<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { + let row = harness.get_by_label("Reset").rect().center().y; + harness.get_all(by().role(Role::ComboBox)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() } /// A content levels effect offers a channel for its histogram; picking one keeps it selected. @@ -90,102 +92,102 @@ fn content_levels_pick_the_histogram_channel() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"color": [0.5, 0.2, 0.1], "roughness": 0.6})).unwrap(); texturecraft_engine::execute(&mut session, "effect.add.levels", &json!({"target": "content"})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.run_steps(4); - assert_eq!(channel_picker(&h).value().as_deref(), Some("Base color"), "the layer's first channel"); - channel_picker(&h).click(); - h.run_steps(2); - h.get_by_label("Roughness").click(); - h.run_steps(3); - assert_eq!(channel_picker(&h).value().as_deref(), Some("Roughness"), "the picked channel stays"); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + assert_eq!(channel_picker(&harness).value().as_deref(), Some("Base color"), "the layer's first channel"); + channel_picker(&harness).click(); + harness.run_steps(2); + harness.get_by_label("Roughness").click(); + harness.run_steps(3); + assert_eq!(channel_picker(&harness).value().as_deref(), Some("Roughness"), "the picked channel stays"); } #[test] -fn clicking_the_effect_opacity_applies_it() { - let (mut h, effect) = harness(); - let t = track(&h, "Opacity"); - let at = egui::pos2(t.left() + 20.0, t.center().y); - h.drag_at(at); - h.drop_at(at); - h.run_steps(3); - assert!(opacity(&h, effect) < 0.5, "a click on the track applies: {}", opacity(&h, effect)); +fn clicking_a_slider_track_applies_it() { + let (mut harness, effect) = selected_generator(); + let track_rect = track(&harness, "Global balance"); + let at = egui::pos2(track_rect.left() + 20.0, track_rect.center().y); + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(3); + assert!(balance(&harness, effect) < 0.25, "a click on the track applies: {}", balance(&harness, effect)); } /// The number field in the row of the slider labelled `label`. -fn number_field<'a>(h: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { - let row = h.get_by_label(label).rect().center().y; - h.get_all(by().role(Role::TextInput)).find(|n| (n.rect().center().y - row).abs() < 4.0).unwrap() +fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { + let row = harness.get_by_label(label).rect().center().y; + harness.get_all(by().role(Role::TextInput)).find(|n| (n.rect().center().y - row).abs() < 4.0).unwrap() } -/// Focus the opacity field and press `keys`, then type `text`, one key per frame like a person. -fn type_opacity(h: &mut Harness<'_, TextureCraftApp>, keys: &[egui::Key], text: &str) { - number_field(h, "Opacity").focus(); - h.run_steps(2); - for k in keys { - h.key_press(*k); - h.run_steps(1); +/// Focus the balance field and press `keys`, then type `text`, one key per frame like a person. +fn type_balance(harness: &mut Harness<'_, TextureCraftApp>, keys: &[egui::Key], text: &str) { + number_field(harness, "Global balance").focus(); + harness.run_steps(2); + for key in keys { + harness.key_press(*key); + harness.run_steps(1); } - for c in text.chars() { - number_field(h, "Opacity").type_text(&c.to_string()); - h.run_steps(1); + for character in text.chars() { + number_field(harness, "Global balance").type_text(&character.to_string()); + harness.run_steps(1); } } #[test] fn a_value_typed_in_the_number_field_applies() { - let (mut h, effect) = harness(); - let steps = h.state().session.history_labels().len(); - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.25"); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(opacity(&h, effect), 0.25); - assert_eq!(h.state().session.history_labels().len(), steps + 1); + let (mut harness, effect) = selected_generator(); + let steps = harness.state().session.history_labels().len(); + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.25"); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.25); + assert_eq!(harness.state().session.history_labels().len(), steps + 1); } /// Dragging the track while the number field has focus drops what was typed there: leaving the /// field afterwards does not undo the drag. #[test] fn a_track_drag_drops_text_typed_in_the_number_field() { - let (mut h, effect) = harness(); - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace], "5"); - let t = track(&h, "Opacity"); - h.drag_at(egui::pos2(t.right(), t.center().y)); - h.run_steps(2); - h.hover_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(2); - h.drop_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(2); - let dragged = opacity(&h, effect); - assert!(dragged < 0.5, "the drag applies: {dragged}"); - // Leave whatever has focus: a click on empty space. - h.drag_at(egui::pos2(5.0, 1390.0)); - h.drop_at(egui::pos2(5.0, 1390.0)); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(opacity(&h, effect), dragged, "the text typed before the drag stays dropped"); + let (mut harness, effect) = selected_generator(); + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace], "5"); + let track_rect = track(&harness, "Global balance"); + harness.drag_at(egui::pos2(track_rect.right(), track_rect.center().y)); + harness.run_steps(2); + harness.hover_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(2); + harness.drop_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(2); + let dragged = balance(&harness, effect); + assert!(dragged < 0.25, "the drag applies: {dragged}"); + // Leave whatever has focus: a click on empty space + harness.drag_at(egui::pos2(5.0, 1390.0)); + harness.drop_at(egui::pos2(5.0, 1390.0)); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), dragged, "the text typed before the drag stays dropped"); } /// Leaving the number field without typing, or with Escape, keeps the value (not the rounded /// text the field shows) and makes no undo step. #[test] fn leaving_the_number_field_unchanged_keeps_the_value() { - let (mut h, effect) = harness(); - texturecraft_engine::execute(&mut h.state_mut().session, "effect.set", &json!({"effect": effect.0, "opacity": 0.333})).unwrap(); - h.run_steps(2); - let steps = h.state().session.history_labels().len(); - type_opacity(&mut h, &[], ""); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(opacity(&h, effect), 0.333, "left without typing"); - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace], "9"); - assert_eq!(number_field(&h, "Opacity").value().as_deref(), Some("0.39")); - assert!(number_field(&h, "Opacity").is_focused()); - h.key_press(egui::Key::Escape); - h.run_steps(3); - assert_eq!(opacity(&h, effect), 0.333); - // Typing the value it already has is no edit either. - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.333"); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(h.state().session.history_labels().len(), steps); + let (mut harness, effect) = selected_generator(); + texturecraft_engine::execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "balance": 0.333})).unwrap(); + harness.run_steps(2); + let steps = harness.state().session.history_labels().len(); + type_balance(&mut harness, &[], ""); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.333, "left without typing"); + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace], "9"); + assert_eq!(number_field(&harness, "Global balance").value().as_deref(), Some("0.39")); + assert!(number_field(&harness, "Global balance").is_focused()); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.333); + // Typing the value it already has is no edit either + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.333"); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(harness.state().session.history_labels().len(), steps); } diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs new file mode 100644 index 00000000..c8afadc9 --- /dev/null +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -0,0 +1,128 @@ +//! The generator panel: global adjustments, restore defaults and image inputs edit the selected generator. + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{BakedMap, EffectKind, Generator, GeneratorKind, LayerId, Source}; +use texturecraft_engine::{ViewMode, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::theme::Brightness; + +/// The sample session with a fill layer whose black mask holds a curvature generator, selected in the properties panel. +fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(512, 256).unwrap(); + session.active_set = 1; + session.camera.pitch = 0.5; + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({})).unwrap(); + let effect = execute(&mut session, "effect.add.generator", &json!({"generator": "curvature"})).unwrap()["effect"].as_u64().unwrap(); + session.view = ViewMode::Mask(LayerId(layer)); + session.update(); + let builder = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)); + let builder = if render { builder.wgpu() } else { builder }; + let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.dock.close(Panel::Layers); + harness.state_mut().ui.dock.close(Panel::TextureSetSettings); + harness.state_mut().ui.dock.focus(Panel::Properties); + harness.run_steps(6); + (harness, LayerId(effect)) +} + +fn generator(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Generator { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + _ => panic!("expected a generator"), + } +} + +/// Drags the track under slider `label` to the right. +fn drag_slider(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_by_label(label).scroll_to_me(); + harness.run_steps(3); + let rect = harness.get_by_label(label).rect(); + let start = egui::pos2(rect.left() + 20.0, rect.bottom() + 10.0); + let end = start + egui::vec2(120.0, 0.0); + harness.drag_at(start); + harness.run_steps(2); + harness.hover_at(end); + harness.run_steps(2); + harness.drop_at(end); + harness.run_steps(3); +} + +#[test] +fn global_blur_applies_as_one_undo_step() { + let (mut harness, effect) = harness(false); + let history = harness.state().session.history_labels().len(); + drag_slider(&mut harness, "Global blur"); + assert!(generator(&harness, effect).global.blur > 0.0); + assert_eq!(harness.state().session.history_labels().len(), history + 1); + harness.state_mut().session.undo().unwrap(); + assert_eq!(generator(&harness, effect).global.blur, 0.0); +} + +#[test] +fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { + let (mut harness, effect) = harness(false); + let edits = json!({"effect": effect.0, "level": 0.9, "blur": 0.5, "balance": 0.2, "resolutionFactor": -2, "seed": 99}); + execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); + harness.run_steps(3); + harness.get_by_label("Restore defaults").scroll_to_me(); + harness.run_steps(2); + harness.get_by_label("Restore defaults").click(); + harness.run_steps(3); + assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Curvature)); +} + +#[test] +fn an_input_can_read_a_uniform_value_and_the_mesh_map_again() { + let (mut harness, effect) = harness(false); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Mesh map: Curvature")).unwrap().scroll_to_me(); + harness.run_steps(3); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Mesh map: Curvature")).unwrap().click(); + harness.run_steps(2); + harness.get_by_label("Uniform value").click(); + harness.run_steps(3); + assert!(matches!(generator(&harness, effect).inputs.get(&BakedMap::Curvature), Some(Source::Uniform(_)))); + + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().click(); + harness.run_steps(2); + harness.get_by_label("Mesh map").click(); + harness.run_steps(3); + assert!(generator(&harness, effect).inputs.is_empty()); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn generator_panel_snapshots() { + let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&directory).unwrap(); + let (mut harness, effect) = harness(true); + harness.run_steps(12); + harness.render().unwrap().save(directory.join("generator-panel-default.png")).unwrap(); + + for section in ["Attributes", "Resolution"] { + harness.get_by_label(section).click(); + harness.run_steps(3); + } + harness.run_steps(6); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(3); + harness.render().unwrap().save(directory.join(format!("generator-panel-sections-open-{name}.png"))).unwrap(); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + + let edits = json!({"effect": effect.0, "blur": 0.3, "balance": 0.6, "contrast": 0.4, "resolutionFactor": -2}); + execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); + harness.state_mut().session.update(); + harness.run_steps(12); + harness.render().unwrap().save(directory.join("generator-panel-adjusted.png")).unwrap(); + + // The effect row with its blend mode and opacity, in the layer stack + harness.state_mut().ui.dock.focus(Panel::Layers); + harness.run_steps(12); + harness.render().unwrap().save(directory.join("generator-effect-row.png")).unwrap(); +} diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 7597d587..50e4458e 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -58,9 +58,9 @@ fn mask_and_content_thumbnails_select_their_own_target() { let at = thumb(&h, "Masked fill", false); click(&mut h, at); assert_eq!(h.state().session.target, StackTarget::Content, "the content thumbnail routes back"); - // Clicking an effect row still selects that effect. - let r = h.get_by_label("Effect A").rect(); - click(&mut h, egui::pos2(r.right() - 40.0, r.center().y)); + // Clicking an effect row's name still selects that effect (its right end holds the blend mode and opacity) + let row = h.get_by_label("Effect A").rect(); + click(&mut h, row.center()); assert!(matches!(h.state().session.target, StackTarget::Effect(_))); } diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 6f1c5092..1b467ac7 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -14,6 +14,7 @@ mod file_dialogs; mod fill_channel_image; mod fill_projection_section; mod filter_picker; +mod generator_panel; mod history_panel; mod layer_clipboard; mod layer_rename;