Fix color selection picking and inspection

This commit is contained in:
Chris Hassebrook committed 2026-11-08 09:13:46 +00:00
1 parent 433ae07387
commit 9aebba686b
8 files changed
+294 -15

No files matched your search

+19 -9
View File
@@ -5,7 +5,7 @@ use texturecraft_core::{BakedMap, EffectKind, LayerId};
use texturecraft_geom::glam::Vec2;
use texturecraft_geom::surface_at;
use crate::commands::{CommandSpec, bad, f32p, has_layer, u64p};
use crate::commands::{CommandSpec, bad, f32p, has_layer};
use crate::mask_cmds::effect_id;
use crate::tool_cmds::viewport_of;
use crate::{Result, Session, cmd};
@@ -46,8 +46,8 @@ fn colors_param(list: &Value) -> Result<Vec<[f32; 3]>> {
items
.iter()
.map(|item| match finite_numbers(item).as_deref() {
Some([red, green, blue]) => Ok([*red, *green, *blue].map(|value| (value as f32).clamp(0.0, 1.0))),
.map(|item| match finite_numbers::<3>(item) {
Some(color) => Ok(color.map(|value| value.clamp(0.0, 1.0) as f32)),
_ => Err(bad(CMD, "each color must be [r, g, b] with finite numbers")),
})
.collect()
@@ -65,7 +65,12 @@ fn pick(session: &mut Session, params: &Value) -> Result<Value> {
None => return Err(bad(CMD, format!("no effect {}", effect.0))),
};
let index = match u64p(params, "index") {
let index = params
.get("index")
.filter(|index| !index.is_null())
.map(|index| index.as_u64().ok_or_else(|| bad(CMD, "`index` must be a non-negative integer")))
.transpose()?;
let index = match index {
Some(index) => Some(usize::try_from(index).ok().filter(|index| *index < color_count).ok_or_else(|| bad(CMD, format!("no color {index} to replace")))?),
None if color_count >= MAX_SELECTED_COLORS => return Err(bad(CMD, format!("a color selection holds at most {MAX_SELECTED_COLORS} colors"))),
None => None,
@@ -138,13 +143,18 @@ fn visible_surface(session: &Session, screen: Vec2, viewport: Vec2) -> Option<(V
/// A `[u, v]` param of finite numbers
fn uv_param(uv: &Value) -> Result<Vec2> {
match finite_numbers(uv).as_deref() {
Some([u, v]) => Ok(Vec2::new(*u as f32, *v as f32)),
match finite_numbers::<2>(uv) {
Some([u, v]) => Ok(Vec2::new(u as f32, v as f32)),
_ => Err(bad("effect.colorSelection.pick", "`uv` must be [u, v] with finite numbers")),
}
}
/// The numbers of a list param, or None when any entry is not a finite number
fn finite_numbers(list: &Value) -> Option<Vec<f64>> {
list.as_array()?.iter().map(|value| value.as_f64().filter(|number| number.is_finite())).collect()
/// Validate the shape before reading components, without allocating for oversized input
fn finite_numbers<const N: usize>(list: &Value) -> Option<[f64; N]> {
let items: &[Value; N] = list.as_array()?.as_slice().try_into().ok()?;
let mut numbers = [0.0; N];
for (number, item) in numbers.iter_mut().zip(items) {
*number = item.as_f64().filter(|value| value.is_finite())?;
}
Some(numbers)
}
+4
View File
@@ -42,6 +42,10 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value {
match &effect.kind {
EffectKind::Generator(generator) => out["generator"] = generator_json(generator),
EffectKind::Levels(levels) => out["levels"] = json!([levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high]),
EffectKind::ColorSelection { colors, tolerance } => {
out["colors"] = json!(colors);
out["tolerance"] = json!(tolerance);
}
EffectKind::Path(paths) => {
out["paths"] = json!(
paths.iter().map(|path| json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill })).collect::<Vec<_>>()
+112
View File
@@ -195,3 +195,115 @@ fn a_hidden_texture_set_does_not_block_a_pick_behind_it() {
execute(&mut session, "textureSet.visible", &json!({"ts": ball, "visible": true})).unwrap();
assert!(pick_at(&mut session, y).unwrap_err().to_string().contains("another texture set"), "a shown ball still blocks it");
}
#[test]
fn malformed_replacement_indices_are_rejected_without_editing() {
let mut session = session();
let (_, effect) = masked_layer(&mut session, true);
let history = session.history_labels();
for index in [json!(-1), json!(0.4), json!("0"), json!(true), json!([])] {
let result = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25], "index": index}));
assert!(result.is_err(), "invalid index {index} was accepted: {result:?}");
assert_eq!(colors(&session, effect), vec![NO_PART]);
assert_eq!(session.history_labels(), history);
}
}
#[test]
fn the_color_limit_rejects_additions_but_allows_replacement() {
let mut session = session();
let (_, effect) = masked_layer(&mut session, true);
let full = vec![NO_PART; 256];
execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": full})).unwrap();
let history = session.history_labels();
let project = session.doc.project.clone();
for params in [json!({"effect": effect.0, "uv": [0.25, 0.25]}), json!({"effect": effect.0, "uv": [0.25, 0.25], "index": 256})] {
assert!(execute(&mut session, "effect.colorSelection.pick", &params).is_err());
assert_eq!(colors(&session, effect), full);
assert_eq!(session.history_labels(), history);
}
assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": vec![NO_PART; 257], "name": "Invalid edit"})).is_err());
assert_eq!(session.history_labels(), history);
assert_eq!(session.doc.project, project, "invalid colors also roll back edits to other fields");
execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25], "index": 255})).unwrap();
assert_eq!(colors(&session, effect).len(), 256);
assert_close(colors(&session, effect)[255], stored(TOP_LEFT_ID));
}
#[test]
fn inspect_exposes_the_selected_colors_and_tolerance() {
let mut session = session();
let (layer, effect) = masked_layer(&mut session, true);
execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25]})).unwrap();
execute(&mut session, "effect.set", &json!({"effect": effect.0, "tolerance": 0.25})).unwrap();
let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap();
let layer = inspected["layers"].as_array().unwrap().iter().find(|found| found["id"] == layer.0).unwrap();
let found = &layer["mask"]["effects"][0];
assert_eq!(found["colors"], json!(colors(&session, effect)));
assert_eq!(found["tolerance"], json!(0.25));
}
#[test]
fn picks_use_the_working_texel_on_a_smaller_uv_tile() {
let mut session = Session::new_project("UV tiles", primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap();
for tile in [1001, 1002] {
session.import_resource_bytes(&format!("id.{tile}.png"), id_map_png()).unwrap();
}
execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": "id.1001.png"})).unwrap();
let (layer, effect) = masked_layer(&mut session, false);
execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
execute(&mut session, "effect.set", &json!({"effect": effect.0, "tolerance": 0.0})).unwrap();
let size = session.doc.project.texture_sets[0].size();
let uv = [0.625, 0.25];
let texel = ((uv[0] * size.0 as f32) as u32, (uv[1] * size.1 as f32) as u32);
assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![0.0]);
execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": uv})).unwrap();
assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![1.0]);
let before = colors(&session, effect);
let result = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.9, 0.8]}));
assert!(result.unwrap_err().to_string().contains("no ID color"), "unused tile space has no sample");
assert_eq!(colors(&session, effect), before);
}
#[test]
#[ignore = "release benchmark; run with --ignored --nocapture --test-threads=1"]
fn benchmark_color_selection_edits() {
use std::time::{Duration, Instant};
const SAMPLES: u32 = 10;
for resolution in [256, 1024] {
let started = Instant::now();
let mut session = Session::new_project("benchmark", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, resolution).unwrap();
let (_, effect) = masked_layer(&mut session, true);
session.update();
let construction = started.elapsed();
for count in [1, 256] {
execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": vec![NO_PART; count]})).unwrap();
session.update();
let params = json!({"effect": effect.0, "uv": [0.25, 0.25], "index": count - 1});
let (mut command_time, mut composite_time) = (Duration::ZERO, Duration::ZERO);
for _ in 0..SAMPLES {
let started = Instant::now();
execute(&mut session, "effect.colorSelection.pick", &params).unwrap();
command_time += started.elapsed();
let started = Instant::now();
session.update();
composite_time += started.elapsed();
execute(&mut session, "edit.undo", &Value::Null).unwrap();
session.update();
}
println!(
"{resolution}x{resolution}, {count} colors, {SAMPLES} samples: construction {construction:.3?}; pick {:.3?}; composite {:.3?}; session memory {} bytes",
command_time / SAMPLES,
composite_time / SAMPLES,
session.memory().total()
);
}
}
}
@@ -67,6 +67,8 @@ pub fn color_selection_properties(app: &mut TextureCraftApp, ui: &mut Ui, effect
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let remove = ui.add_enabled_ui(colors.len() > 1, |ui| icon_button(ui, ic::MINUS, tr("Remove"), false, ROW_BUTTON_SIZE)).inner;
if remove.clicked() {
// Removing a row changes the indices of pending replacements
IdColorPick::end(app);
let remaining: Vec<[f32; 3]> = colors.iter().enumerate().filter(|(kept, _)| *kept != index).map(|(_, kept)| *kept).collect();
app.run("effect.set", json!({"effect": effect.0, "colors": remaining}));
}
+5
View File
@@ -27,6 +27,7 @@ impl IdColorPick {
None => app.session.view,
};
app.properties_popup = None;
app.picking_id_color = Some(IdColorPick { effect, index, previous_view });
app.run("viewport.view", json!({"mode": format!("map:{}", BakedMap::Id.id())}));
}
@@ -34,6 +35,7 @@ impl IdColorPick {
/// Leaves pick mode, returning to the earlier view unless the user chose another meanwhile
pub fn end(app: &mut TextureCraftApp) {
let Some(pick) = app.picking_id_color.take() else { return };
if app.session.view == ViewMode::MeshMap(BakedMap::Id) {
app.run("viewport.view", view_params(pick.previous_view));
}
@@ -42,6 +44,7 @@ impl IdColorPick {
/// Picks at `point` (`x`/`y`/`viewport` or `uv` params) and leaves pick mode
pub fn pick_at(app: &mut TextureCraftApp, point: Value) {
let Some(pick) = app.picking_id_color else { return };
let mut params = json!({"effect": pick.effect.0, "index": pick.index});
if let (Some(target), Some(source)) = (params.as_object_mut(), point.as_object()) {
target.extend(source.clone());
@@ -54,6 +57,7 @@ impl IdColorPick {
/// An eyedropper in place of the pointer while it is over `rect`, its tip on the hotspot
pub fn draw_cursor(ui: &egui::Ui, rect: egui::Rect) {
let Some(pointer) = ui.ctx().pointer_hover_pos().filter(|pointer| rect.contains(*pointer)) else { return };
ui.ctx().set_cursor_icon(egui::CursorIcon::None);
// The glyph's tip is its bottom-left corner; a dark outline keeps it readable on any ID color
@@ -69,6 +73,7 @@ impl IdColorPick {
/// Ends pick mode once its effect is no longer selected or painting mode is left
pub fn end_when_stale(app: &mut TextureCraftApp) {
let Some(pick) = app.picking_id_color else { return };
if app.session.target != StackTarget::Effect(pick.effect) || app.ui.mode != Mode::Painting {
IdColorPick::end(app);
}
+2
View File
@@ -343,6 +343,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
app.properties_popup = None;
} else if !popup_open && app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
crate::id_color_pick::IdColorPick::end(app);
} else if app.ui.mode == Mode::Painting && !popup_open && input.consume_key(Modifiers::NONE, Key::Escape) {
app.session.cancel_stroke();
app.session.tool.path.points.clear();
+4 -4
View File
@@ -51,15 +51,15 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) {
crate::toolbar::paint_bar(app, ui);
}
crate::id_color_pick::IdColorPick::end_when_stale(app);
let tokens = Tokens::get(ui.ctx());
let aux_view = match app.session.view {
_ if mode == crate::state::Mode::Painting && app.session.quick_mask.editing => Some(crate::gpu::AuxView::QuickMask),
_ if mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => Some(crate::gpu::AuxView::QuickMask),
ViewMode::MeshMap(map) => Some(crate::gpu::AuxView::MeshMap(map)),
ViewMode::Mask(id) => Some(crate::gpu::AuxView::Mask(id)),
_ => None,
};
let mut sync = PendingSync(Some(aux_view));
crate::id_color_pick::IdColorPick::end_when_stale(app);
let full = ui.available_rect_before_wrap();
path_keys(app, ui);
@@ -206,7 +206,7 @@ fn split_divider_grab(ui: &Ui, full: Rect, divider_x: f32) {
fn shade(app: &TextureCraftApp) -> Shade {
let (view_mode, channel) = match app.session.view {
_ if app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing => (2, 0),
_ if app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => (2, 0),
ViewMode::Material => (0, 0),
ViewMode::Channel(selected_channel) => (1, selected_channel.index() as u32),
ViewMode::MeshMap(_) | ViewMode::Mask(_) => (2, 0),
@@ -692,7 +692,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
stencil_overlay(app, ui, rect);
decal_overlay(app, ui, rect);
brush_readout(app, ui, &response, adjusting);
if app.session.quick_mask.editing {
if app.session.quick_mask.editing && app.picking_id_color.is_none() {
ui.painter_at(rect).text(
rect.left_top() + vec2(12.0, 40.0),
egui::Align2::LEFT_TOP,
+146 -2
View File
@@ -22,8 +22,8 @@ fn id_map_png() -> Vec<u8> {
bytes
}
/// The app with a selected color selection of three colors on a fill layer's mask
fn app_with_color_selection(with_id_map: bool) -> (Harness<'static, TextureCraftApp>, LayerId) {
/// A selected color selection of three colors on a fill layer's mask
fn color_selection_session(with_id_map: bool) -> (texturecraft_engine::Session, LayerId) {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
if with_id_map {
let image = session.import_resource_bytes("id.png", id_map_png()).unwrap();
@@ -38,7 +38,11 @@ fn app_with_color_selection(with_id_map: bool) -> (Harness<'static, TextureCraft
let effect = session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects[0].id;
execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": [FIRST, SECOND, THIRD]})).unwrap();
session.target = StackTarget::Effect(effect);
(session, effect)
}
fn app_with_color_selection(with_id_map: bool) -> (Harness<'static, TextureCraftApp>, LayerId) {
let (session, effect) = color_selection_session(with_id_map);
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.run_steps(4);
(harness, effect)
@@ -123,3 +127,143 @@ fn without_an_id_map_picking_is_off_and_a_warning_says_why() {
harness.run_steps(3);
assert!(harness.state().picking_id_color.is_none());
}
fn row_button(harness: &Harness<'_, TextureCraftApp>, readout: &str, label: &str) -> Pos2 {
let row_y = harness.get_by_label(readout).rect().center().y;
harness.query_all_by_label(label).find(|button| (button.rect().center().y - row_y).abs() < 8.0).unwrap().rect().center()
}
#[test]
fn removing_a_row_cancels_a_pending_replacement() {
let (mut harness, effect) = app_with_color_selection(true);
let repick = row_button(&harness, "R: 10", "Pick color");
click_at(&mut harness, repick);
assert_eq!(harness.state().picking_id_color.unwrap().index, Some(1));
let remove = row_button(&harness, "R: 200", "Remove");
click_at(&mut harness, remove);
assert_eq!(colors(&harness, effect), vec![SECOND, THIRD]);
assert!(harness.state().picking_id_color.is_none(), "removing a row must not leave a replacement targeting a different color");
assert_eq!(harness.state().session.view, ViewMode::Material);
}
#[test]
fn escape_cancels_the_pick_without_editing_colors() {
let (mut harness, effect) = app_with_color_selection(true);
harness.get_by_label(&pick_color_label()).click();
harness.run_steps(3);
let history = harness.state().session.history_labels();
harness.key_press(egui::Key::Escape);
harness.run_steps(3);
assert!(harness.state().picking_id_color.is_none());
assert_eq!(harness.state().session.view, ViewMode::Material);
assert_eq!(colors(&harness, effect), vec![FIRST, SECOND, THIRD]);
assert_eq!(harness.state().session.history_labels(), history);
}
#[test]
fn picking_from_the_popup_closes_it_before_the_viewport_click() {
use texturecraft_ui_egui::properties_popup::{self, PropertiesPopup};
let (mut harness, effect) = app_with_color_selection(true);
let bounds = harness.state().viewport_rect;
harness.state_mut().properties_popup = Some(PropertiesPopup::Open { at: bounds.center() - egui::vec2(100.0, 100.0), bounds });
harness.run_steps(4);
let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap();
let pick = harness.query_all_by_label(&pick_color_label()).find(|button| popup.contains_rect(button.rect())).unwrap().rect().center();
click_at(&mut harness, pick);
assert!(harness.state().picking_id_color.is_some());
let center = harness.state().viewport_rect.center();
assert!(popup.contains(center), "pick a point the popup would otherwise cover");
click_at(&mut harness, center);
assert_eq!(colors(&harness, effect).len(), 4, "the next viewport click must pick, even under the former popup");
assert_eq!(harness.state().properties_popup, None);
}
#[test]
fn a_2d_pick_replaces_the_chosen_row_and_undo_restores_it() {
use texturecraft_ui_egui::state::ViewLayout;
let (mut harness, effect) = app_with_color_selection(true);
harness.state_mut().ui.layout = ViewLayout::Only3D;
harness.run_steps(3);
let center = harness.state().viewport_rect.center();
harness.state_mut().ui.layout = ViewLayout::Only2D;
harness.run_steps(3);
let repick = row_button(&harness, "R: 10", "Pick color");
click_at(&mut harness, repick);
click_at(&mut harness, center);
assert_eq!(colors(&harness, effect), vec![FIRST, ID_PART.map(|channel| channel as f32 / 255.0), THIRD]);
assert_eq!(harness.state().session.view, ViewMode::Material);
assert!(!harness.state().session.stroke_active());
harness.state_mut().session.undo().unwrap();
assert_eq!(colors(&harness, effect), vec![FIRST, SECOND, THIRD]);
}
#[test]
fn deselection_cancels_picking_and_preserves_a_view_chosen_meanwhile() {
let (mut harness, effect) = app_with_color_selection(true);
harness.get_by_label(&pick_color_label()).click();
harness.run_steps(3);
execute(&mut harness.state_mut().session, "viewport.view", &json!({"mode": "uvChecker"})).unwrap();
harness.state_mut().session.target = StackTarget::Content;
harness.run_steps(3);
assert!(harness.state().picking_id_color.is_none());
assert_eq!(harness.state().session.view, ViewMode::UvChecker);
assert_eq!(colors(&harness, effect), vec![FIRST, SECOND, THIRD]);
}
#[test]
#[ignore = "requires a GPU adapter; set TC_UI_SNAPSHOTS to save the rendered views"]
fn color_selection_snapshots_and_quick_mask_pick() {
let (session, _) = color_selection_session(true);
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|context| {
let mut app = TextureCraftApp::new(context, session);
app.ui.layout = texturecraft_ui_egui::state::ViewLayout::Only3D;
app
});
let adapter = harness.state().render_state.as_ref().unwrap().adapter.get_info();
eprintln!("Offscreen adapter: {adapter:?}");
let save = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| {
harness.run_steps(8);
let image = harness.render().unwrap();
if let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS") {
let path = std::path::Path::new(&directory).join(format!("{name}.png"));
image.save(&path).unwrap();
eprintln!("wrote {}", path.display());
}
image
};
save(&mut harness, "color-selection-editor");
harness.get_by_label(&pick_color_label()).click();
let center = harness.state().viewport_rect.center();
harness.hover_at(center + egui::vec2(80.0, 0.0));
let expected = save(&mut harness, "color-selection-picking");
execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap();
let with_quick_mask = save(&mut harness, "color-selection-picking-quick-mask");
assert_eq!(
with_quick_mask.get_pixel(center.x as u32, center.y as u32),
expected.get_pixel(center.x as u32, center.y as u32),
"picking must display the ID map while quick-mask editing is enabled"
);
click_at(&mut harness, center);
assert!(harness.state().session.quick_mask.editing, "picking preserves quick-mask editing");
save(&mut harness, "color-selection-quick-mask-restored");
execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": false})).unwrap();
harness.state_mut().ui.layout = texturecraft_ui_egui::state::ViewLayout::Only2D;
harness.get_by_label(&pick_color_label()).click();
save(&mut harness, "color-selection-picking-2d");
click_at(&mut harness, center);
assert!(harness.state().picking_id_color.is_none());
execute(&mut harness.state_mut().session, "textureSet.meshMap.clear", &json!({"map": "id"})).unwrap();
save(&mut harness, "color-selection-no-id-map");
}