Bake mode pass 2: map preview on the model while a map's settings show

This commit is contained in:
Rebornim committed 2026-11-24 14:32:46 +00:00
1 parent 3f72b65487
commit 623bd9008d
12 files changed
+709 -13

No files matched your search

+1 -1
View File
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Bake preview",
[],
None,
"{show?: \"follow\" (the newest finished map) | \"material\" | \"map:<id>\" (pin a map)} → {active, show, shown, newest, stage, sets}. While the app bakes, the 3D view shows the maps as they finish; `show` picks what it shows. With no bake running {active: false} (setting `show` is then an error)",
"{show?: \"follow\" (the newest finished map) | \"material\" | \"map:<id>\" (pin a map)} → {active, show, shown, newest, stage, sets}. While the app bakes, the 3D view shows the maps as they finish; `show` picks what it shows. In Bake mode the app's map preview also shows here while Mesh Map Settings is in front. With neither {active: false} (setting `show` is then an error)",
always,
preview
)]
@@ -1,9 +1,11 @@
use egui::collapsing_header::CollapsingState;
use egui::{Rect, Ui, vec2};
use egui_phosphor::regular as icon;
use texturecraft_engine::core::{BakeResolution, BakedMap};
use texturecraft_render::BakeOverlay;
use super::BakeVisualizationToggles;
use super::map_preview_fold::MapPreviewFold;
use super::section_opening::SectionOpening;
use crate::TextureCraftApp;
use crate::i18n::{n_, tr, trf};
@@ -25,6 +27,10 @@ const ROW_BUTTON_SIZE: f32 = 18.0;
/// Width of an overlay's color swatch
const SWATCH_WIDTH: f32 = 44.0;
/// The map preview's sizes and how the list names them
const PREVIEW_SIZES: [(BakeResolution, &str); 4] =
[(BakeResolution::R128, "128"), (BakeResolution::R256, "256"), (BakeResolution::R512, "512"), (BakeResolution::R1024, "1K")];
/// The neutral material's quality steps: samples per pixel and their names
const QUALITIES: [(u32, &str); 6] = [
(4, n_("Very Low (4 spp)")),
@@ -37,6 +43,8 @@ const QUALITIES: [(u32, &str); 6] = [
/// The Baking Visualization panel in the top-left corner of bake mode's 3D view `view`
pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: Rect) {
let matching_error_applies = super::matching_error_applies(&app.session);
let (shown, selected) = (app.live_preview.shown(), super::live_preview::map_settings_shown(app).map(|target| target.map));
let toggles = &mut app.ui.bake_visualization;
let tokens = Tokens::get(ui.ctx());
egui::Area::new(ui.scope_id().with("bake_visualization_panel")).fixed_pos(view.left_top() + vec2(PANEL_MARGIN, PANEL_MARGIN)).constrain_to(view).show(
@@ -52,14 +60,14 @@ pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view:
collapsing_state.toggle(ui);
}
collapsing_state.show_body_unindented(ui, |ui| sections(ui, toggles));
collapsing_state.show_body_unindented(ui, |ui| sections(ui, toggles, matching_error_applies, shown, selected));
});
},
);
}
/// The panel's sections below its header
fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) {
/// The panel's sections below its header; the Matching Error row greys unless `matching_error_applies`
fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles, matching_error_applies: bool, shown: Option<BakedMap>, selected: Option<BakedMap>) {
ui.horizontal(|ui| {
ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only"));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
@@ -72,7 +80,7 @@ fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) {
let meshes_editable = !toggles.hide_baking_meshes;
if collapsible(ui, "high_poly", tr("High Definition Mesh (HP)"), SectionOpening::Open, true, meshes_editable, |ui| {
overlay_row(ui, "bake_high_poly_color", tr("Mesh"), &mut toggles.high_poly_mesh);
overlay_row(ui, "bake_matching_error_color", tr("Matching Error"), &mut toggles.matching_error);
ui.add_enabled_ui(matching_error_applies, |ui| overlay_row(ui, "bake_matching_error_color", tr("Matching Error"), &mut toggles.matching_error));
}) {
toggles.reset_high_poly();
}
@@ -100,6 +108,42 @@ fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) {
}) {
toggles.reset_project_mesh();
}
map_preview_section(ui, toggles, shown, selected);
}
/// The Map Preview section: whether the selected map shows on the model, and the size it bakes at; it opens by itself while a preview shows
fn map_preview_section(ui: &mut Ui, toggles: &mut BakeVisualizationToggles, shown: Option<BakedMap>, selected: Option<BakedMap>) {
let fold_id = ui.make_persistent_id("map_preview_fold");
let mut fold: MapPreviewFold = ui.ctx().data(|data| data.get_temp(fold_id)).unwrap_or_default();
let section = section_id(ui, "map_preview");
let mut state = CollapsingState::load_with_default_open(ui.ctx(), section, false);
if let Some(open) = fold.follow(shown, selected, !toggles.map_preview) {
state.set_open(open);
state.store(ui.ctx());
}
let open_before = state.is_open();
let reset = collapsible(ui, "map_preview", tr("Map Preview"), SectionOpening::Closed, true, true, |ui| {
ui.checkbox(&mut toggles.map_preview, tr("Preview the Selected Map"));
ui.add_enabled_ui(toggles.map_preview, |ui| {
let size = &mut toggles.map_preview_size;
let selected = PREVIEW_SIZES.iter().find(|(option, _)| option == size).map_or("", |(_, name)| *name);
combo(ui, tr("Resolution"), selected, |ui| {
for (option, name) in PREVIEW_SIZES {
ui.selectable_value(size, option, name);
}
});
});
});
let open_after = CollapsingState::load_with_default_open(ui.ctx(), section, false).is_open();
if open_after != open_before {
fold.toggled(open_after);
}
ui.ctx().data_mut(|data| data.insert_temp(fold_id, fold));
if reset {
toggles.reset_map_preview();
}
}
/// The project mesh's neutral material (picked in the 3D view's view menu): its quality, roughness, metallic, occlusion strength and bent normal
@@ -126,8 +170,7 @@ fn neutral_material(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) {
/// A section `title`, open or closed at first as `opening` says, with a reset button on its header when `resettable` and its contents greyed unless `editable`; returns whether the reset was clicked
fn collapsible(ui: &mut Ui, id: &str, title: &str, opening: SectionOpening, resettable: bool, editable: bool, body: impl FnOnce(&mut Ui)) -> bool {
let tokens = Tokens::get(ui.ctx());
let mut collapsing_state =
CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id(("baking_visualization_section", id)), opening == SectionOpening::Open);
let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), section_id(ui, id), opening == SectionOpening::Open);
let (header, reset) = ui
.horizontal(|ui| {
ui.set_min_height(EYE_BUTTON_SIZE);
@@ -157,6 +200,11 @@ fn collapsible(ui: &mut Ui, id: &str, title: &str, opening: SectionOpening, rese
reset.is_some_and(|reset| reset.clicked())
}
/// The id a section keeps its open state under
fn section_id(ui: &Ui, id: &str) -> egui::Id {
ui.make_persistent_id(("baking_visualization_section", id))
}
/// A checkbox for whether `overlay` shows, with its color swatch and an eyedropper for it on the right
fn overlay_row(ui: &mut Ui, id: &str, label: &str, overlay: &mut BakeOverlay) {
ui.horizontal(|ui| {
@@ -1,4 +1,5 @@
use serde::{Deserialize, Serialize};
use texturecraft_engine::core::BakeResolution;
use texturecraft_render::{BakeOverlay, BakeVisualization, NeutralMaterial};
/// Opacity of the cage's surface and wireframe until changed
@@ -20,6 +21,10 @@ pub struct BakeVisualizationToggles {
/// Show the project mesh with [`Self::neutral`] instead of its painted material
pub neutral_shown: bool,
pub neutral: NeutralMaterial,
/// Show the selected map on the model while Mesh Map Settings shows its settings
pub map_preview: bool,
/// The size the map preview bakes at once a change settles
pub map_preview_size: BakeResolution,
}
impl Default for BakeVisualizationToggles {
@@ -37,6 +42,9 @@ impl Default for BakeVisualizationToggles {
project_mesh: shown(parts.low_poly),
neutral_shown: true,
neutral: NeutralMaterial::default(),
// Web builds bake on the UI thread, so the preview there is opt-in
map_preview: !cfg!(target_arch = "wasm32"),
map_preview_size: BakeResolution::R256,
}
}
}
@@ -85,6 +93,12 @@ impl BakeVisualizationToggles {
self.missing_seams = Self::default().missing_seams;
}
/// Put the Map Preview section back to its defaults
pub fn reset_map_preview(&mut self) {
let defaults = Self::default();
(self.map_preview, self.map_preview_size) = (defaults.map_preview, defaults.map_preview_size);
}
/// Put the Project Mesh section back to its defaults
pub fn reset_project_mesh(&mut self) {
let defaults = Self::default();
@@ -0,0 +1,325 @@
//! The map preview: while Mesh Map Settings shows a map's settings, the 3D view shows that map on the model, re-baked small on a worker as the settings change
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::sync::mpsc::TryRecvError;
use texturecraft_engine::StreamedMap;
use texturecraft_engine::bake::Progress;
use texturecraft_engine::core::{BakeResolution, BakedMap};
use super::live_preview_target::LivePreviewTarget;
use super::preview_input::PreviewInput;
use super::running_preview::RunningPreview;
use crate::TextureCraftApp;
use crate::docking::Panel;
use crate::i18n::{baked_map_label, tr, trf};
use crate::state::Mode;
/// Sizes a dragged slider's previews step through, smallest first
const DRAG_SIZES: [BakeResolution; 5] = [BakeResolution::R64, BakeResolution::R128, BakeResolution::R256, BakeResolution::R512, BakeResolution::R1024];
/// A drag preview this quick bakes one size up next time
const DRAG_STEP_UP_SECONDS: f64 = 0.07;
/// A drag preview this slow bakes one size down next time
const DRAG_STEP_DOWN_SECONDS: f64 = 0.14;
/// How often the view looks for a finished preview: about one frame at 60 Hz, so it shows at once
const POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(16);
/// The map preview's state: what it shows, what its picture was made from (and the session revision and size it was last checked at), the bake running for it, the drag change waiting for it, whether a drag still needs the full-size bake, whether its last bake could not start, and each map's drag size on this machine
#[derive(Default)]
pub(crate) struct LivePreview {
shown: Option<LivePreviewTarget>,
made_from: Option<PreviewInput>,
checked_at: Option<(u64, BakeResolution)>,
cannot_bake: bool,
running: Option<RunningPreview>,
drag_waiting: bool,
refine_on_release: bool,
drag_sizes: BTreeMap<BakedMap, BakeResolution>,
}
impl LivePreview {
/// The map the preview shows now, if any
pub(crate) fn shown(&self) -> Option<BakedMap> {
self.shown.map(|target| target.map)
}
/// Stop the preview and give the 3D view back; a real bake calls this before it takes the view
pub(crate) fn release(&mut self, session: &mut texturecraft_engine::Session) {
self.cancel();
self.refine_on_release = false;
self.made_from = None;
self.checked_at = None;
self.cannot_bake = false;
if self.shown.take().is_some() {
session.bake_preview_end();
}
}
fn cancel(&mut self) {
self.drag_waiting = false;
if let Some(running) = self.running.take() {
running.progress.cancel.store(true, Ordering::Relaxed);
}
}
/// The size `map` bakes at while a slider drags: it starts small, follows how fast this machine bakes it, and never passes `chosen`
fn drag_size(&self, map: BakedMap, chosen: BakeResolution) -> BakeResolution {
let learned = self.drag_sizes.get(&map).copied().unwrap_or_else(|| first_drag_size(map));
if learned.pixels() > chosen.pixels() { chosen } else { learned }
}
/// A drag preview of `map` at `size` took `seconds`: step its drag size up or down one size, never past `chosen`
fn learn_drag_size(&mut self, map: BakedMap, size: BakeResolution, seconds: f64, chosen: BakeResolution) {
let Some(index) = DRAG_SIZES.iter().position(|step| *step == size) else { return };
let next = if seconds < DRAG_STEP_UP_SECONDS {
DRAG_SIZES.get(index + 1).copied().filter(|bigger| bigger.pixels() <= chosen.pixels()).unwrap_or(size)
} else if seconds > DRAG_STEP_DOWN_SECONDS {
index.checked_sub(1).and_then(|smaller| DRAG_SIZES.get(smaller).copied()).unwrap_or(size)
} else {
size
};
self.drag_sizes.insert(map, next);
}
}
/// The texture set and the map whose settings a Mesh Map Settings panel in front shows, in Bake mode
pub(crate) fn map_settings_shown(app: &TextureCraftApp) -> Option<LivePreviewTarget> {
let set = app.session.ts();
let settings = &app.session.doc.project.texture_sets.get(set)?.bake;
let shows = app.ui.mode == Mode::Baking && app.ui.dock.is_visible(Panel::MeshMapSettings);
shows.then(|| LivePreviewTarget { set, map: super::selected_map(app.ui.selected_baked_map, settings) })
}
/// What the preview should show: the map whose settings show, while the preview is on and no real bake runs
fn wanted(app: &TextureCraftApp) -> Option<LivePreviewTarget> {
map_settings_shown(app).filter(|_| app.ui.bake_visualization.map_preview && app.bake.is_none())
}
/// A slider dragged in Mesh Map Settings changed a setting: a running drag bake finishes and shows before the newest value bakes, so pictures keep coming while the slider moves
pub(crate) fn slider_dragged(app: &mut TextureCraftApp, ctx: &egui::Context) {
let Some(target) = app.live_preview.shown else { return };
app.live_preview.refine_on_release = true;
// Web builds bake on the UI thread, so they wait for the release; a set that can't bake waits too
if cfg!(target_arch = "wasm32") || app.live_preview.cannot_bake {
return;
}
if app.live_preview.running.as_ref().is_some_and(|running| running.dragging) {
app.live_preview.drag_waiting = true;
} else {
let size = app.live_preview.drag_size(target.map, app.ui.bake_visualization.map_preview_size);
start(app, ctx, target, size, true);
}
}
/// Once a frame: follow what the preview should show, bake again when its picture is out of date, and take a finished bake
pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) {
// A new session (a project opened, the mesh replaced) has no preview layer: start over
if app.live_preview.shown.is_some() && !app.session.bake_preview_active() {
app.live_preview.release(&mut app.session);
}
let wanted = wanted(app);
if wanted != app.live_preview.shown {
app.live_preview.release(&mut app.session);
if let Some(target) = wanted {
show(app, ctx, target);
}
}
// After a drag, and whenever what the picture was made from changes (undo, a synced set, automation, the chosen size, the meshes)
if let Some(target) = app.live_preview.shown {
let released = app.live_preview.refine_on_release && ctx.dragged_id().is_none();
let chosen = app.ui.bake_visualization.map_preview_size;
// Only after an edit or a new size: comparing the inputs copies the settings
let check = (app.session.revision, chosen);
let unchecked = app.live_preview.checked_at != Some(check);
let out_of_date = unchecked && !app.live_preview.refine_on_release && app.live_preview.made_from != input(app, target, chosen);
if unchecked && !app.live_preview.refine_on_release {
app.live_preview.checked_at = Some(check);
}
if released || out_of_date {
app.live_preview.refine_on_release = false;
start(app, ctx, target, chosen, false);
}
}
take_finished(app, ctx);
}
/// Show a finished preview bake, learn the drag size from it, and start the drag change that waited for it; a failed one goes to the Log
fn take_finished(app: &mut TextureCraftApp, ctx: &egui::Context) {
let Some(running) = &app.live_preview.running else { return };
ctx.request_repaint_after(POLL_INTERVAL);
let finished = match running.receiver.try_recv() {
Err(TryRecvError::Empty) => return,
Ok(finished) => finished,
Err(TryRecvError::Disconnected) => Err(texturecraft_engine::EngineError::Other(tr("The map preview worker stopped").into())),
};
let Some(running) = app.live_preview.running.take() else { return };
// A failure keeps the old picture and says why
let mut output = match finished {
Ok(output) => output,
Err(error) => {
let map = tr(baked_map_label(running.target.map));
app.session.log.warn("Baker", trf("The {map} preview failed: {error}", &[("map", &map), ("error", &error.to_string())]));
app.live_preview.drag_waiting = false;
return;
}
};
if running.dragging {
let seconds = ctx.input(|input| input.time) - running.started;
app.live_preview.learn_drag_size(running.target.map, running.size, seconds, app.ui.bake_visualization.map_preview_size);
}
if let Some(data) = output.maps.remove(&running.target.map) {
let streamed = StreamedMap { map: running.target.map, index: 0, total: 1, resolution: output.resolution, height: output.height, data: Arc::new(data) };
app.session.bake_preview_map(running.target.set, streamed);
}
// The newest drag change waited for this picture
if std::mem::take(&mut app.live_preview.drag_waiting) && app.live_preview.refine_on_release {
let size = app.live_preview.drag_size(running.target.map, app.ui.bake_visualization.map_preview_size);
start(app, ctx, running.target, size, true);
}
}
/// Start showing `target`: the map's last real bake at once when there is one (it may predate the settings), then a preview bake at the chosen size
fn show(app: &mut TextureCraftApp, ctx: &egui::Context, target: LivePreviewTarget) {
app.session.bake_preview_begin(vec![(target.set, vec![target.map])]);
app.live_preview.shown = Some(target);
let baked = app.session.baked(target.set).and_then(|baked| baked.maps.get(&target.map).map(|data| (baked.resolution, data.clone())));
if let Some((resolution, data)) = baked {
let height = (data.len() / target.map.components()).checked_div(resolution as usize).unwrap_or(0) as u32;
app.session.bake_preview_map(target.set, StreamedMap { map: target.map, index: 0, total: 1, resolution, height, data });
}
start(app, ctx, target, app.ui.bake_visualization.map_preview_size, false);
}
/// What a preview of `target` at `size` would be made from now
fn input(app: &TextureCraftApp, target: LivePreviewTarget, size: BakeResolution) -> Option<PreviewInput> {
let set = app.session.doc.project.texture_sets.get(target.set)?;
let meshes = &app.session.doc.bake_meshes;
let painted = app.session.doc.bake_paint.iter().filter(|((index, _), _)| *index == target.set).map(|(_, map)| Arc::as_ptr(map) as usize).collect();
Some(PreviewInput {
settings: set.bake.clone(),
mesh_id: app.session.mesh_id,
uv_tiles: set.uv_tiles.clone(),
excluded_tiles: set.bake_excluded_tiles.clone(),
tile_resolutions: set.tile_resolutions.clone(),
high_polys: meshes.high.iter().map(|mesh| Arc::as_ptr(&mesh.mesh) as usize).collect(),
cage: meshes.cage.as_ref().map(|cage| Arc::as_ptr(&cage.mesh) as usize),
painted,
size,
})
}
/// Bake `target`'s map alone at `size` on the preview pool (`dragging`: for a slider still moving), cancelling the preview bake still running
fn start(app: &mut TextureCraftApp, ctx: &egui::Context, target: LivePreviewTarget, size: BakeResolution, dragging: bool) {
app.live_preview.cancel();
app.live_preview.made_from = input(app, target, size);
let mut task = match app.session.bake_task(target.set) {
Ok(task) => task,
Err(error) => {
// Once, not on every change while it stays unbakeable
if !app.live_preview.cannot_bake {
let map = tr(baked_map_label(target.map));
app.session.log.warn("Baker", trf("The {map} preview can't bake: {error}", &[("map", &map), ("error", &error.to_string())]));
}
app.live_preview.cannot_bake = true;
return;
}
};
app.live_preview.cannot_bake = false;
task.settings.maps.select([target.map]);
let own = task.settings.common.resolution;
let size = if own.pixels() < size.pixels() { own } else { size };
task.settings.common.resolution = size;
task.settings.common.resolution_height = None;
let progress = Arc::new(Progress::new());
let worker_progress = progress.clone();
// Queued on the preview pool's own threads: starting a new thread per change can stall the UI while a bake allocates
let receiver = match preview_pool() {
Some(pool) => {
let (sender, receiver) = std::sync::mpsc::channel();
pool.spawn(move || {
let _ = sender.send(task.run(&worker_progress));
});
receiver
}
None => crate::spawn_worker("texturecraft-map-preview", move || task.run(&worker_progress)),
};
let started = ctx.input(|input| input.time);
app.live_preview.running = Some(RunningPreview { target, size, started, dragging, progress, receiver });
}
/// A dragged slider's first preview size before this machine's speed is known: 64 for the ray-traced bakers (well over 100 ms at 128 on a 4-core machine), else 128
fn first_drag_size(map: BakedMap) -> BakeResolution {
match map {
BakedMap::AmbientOcclusion | BakedMap::Thickness | BakedMap::BentNormal | BakedMap::Curvature => BakeResolution::R64,
_ => BakeResolution::R128,
}
}
/// The preview bakes' own thread pool, a thread short of the cores, so the UI's parallel work never waits behind a preview; None where no pool can start
#[cfg(not(target_arch = "wasm32"))]
fn preview_pool() -> Option<&'static rayon::ThreadPool> {
static POOL: std::sync::OnceLock<Option<rayon::ThreadPool>> = std::sync::OnceLock::new();
POOL.get_or_init(|| {
let threads = std::thread::available_parallelism().map_or(1, |cores| cores.get().saturating_sub(1).max(1));
let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|index| format!("texturecraft-map-preview-{index}")).build();
if let Err(error) = &pool {
log::warn!("map previews share the global thread pool: {error}");
}
pool.ok()
})
.as_ref()
}
/// Web builds have no threads: the preview bakes on the UI thread
#[cfg(target_arch = "wasm32")]
fn preview_pool() -> Option<&'static rayon::ThreadPool> {
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_drag_size_steps_up_while_fast_down_while_slow_and_never_past_the_chosen_size() {
let mut preview = LivePreview::default();
let map = BakedMap::AmbientOcclusion;
let largest = BakeResolution::R1024;
let start = preview.drag_size(map, largest);
preview.learn_drag_size(map, start, DRAG_STEP_UP_SECONDS / 2.0, largest);
let bigger = preview.drag_size(map, largest);
assert!(bigger.pixels() > start.pixels(), "a quick bake steps up");
preview.learn_drag_size(map, bigger, DRAG_STEP_DOWN_SECONDS * 2.0, largest);
assert_eq!(preview.drag_size(map, largest), start, "a slow bake steps back down");
preview.learn_drag_size(map, start, DRAG_STEP_UP_SECONDS / 2.0, start);
assert_eq!(preview.drag_size(map, largest), start, "never steps past the chosen size");
preview.learn_drag_size(map, start, DRAG_STEP_UP_SECONDS / 2.0, largest);
assert_eq!(preview.drag_size(map, start), start, "a smaller chosen size caps what was learned");
}
}
@@ -0,0 +1,8 @@
use texturecraft_engine::core::BakedMap;
/// One map of one texture set, as the map preview shows it
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct LivePreviewTarget {
pub(crate) set: usize,
pub(crate) map: BakedMap,
}
@@ -0,0 +1,69 @@
use texturecraft_engine::core::BakedMap;
/// The Map Preview section's fold: it opens while a preview shows and folds when the preview goes away; folded by hand on a map, it stays folded until another map is picked
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct MapPreviewFold {
/// The map the preview showed last frame
pub(super) shown: Option<BakedMap>,
/// The map the user folded the section on while its preview showed
pub(super) folded_for: Option<BakedMap>,
}
impl MapPreviewFold {
/// Whether the section should open (Some(true)) or fold (Some(false)) this frame, or stay as it is; `selected` is the map whose settings show, `switched_off` whether the preview is turned off
pub(super) fn follow(&mut self, shown: Option<BakedMap>, selected: Option<BakedMap>, switched_off: bool) -> Option<bool> {
// Only another map ends it; no map at all (Common Settings in front) keeps it
if selected.is_some() && selected != self.folded_for {
self.folded_for = None;
}
if shown == self.shown {
return None;
}
self.shown = shown;
match shown {
Some(map) => (self.folded_for != Some(map)).then_some(true),
// Turning the preview off from inside the section leaves it open until the user moves on
None => (!(switched_off && selected.is_some())).then_some(false),
}
}
/// The user folded or opened the section by hand
pub(super) fn toggled(&mut self, open: bool) {
self.folded_for = if open { None } else { self.shown };
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_section_opens_with_a_preview_and_folds_when_it_goes() {
let mut fold = MapPreviewFold::default();
assert_eq!(fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false), Some(true));
assert_eq!(fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false), None, "no change, no move");
assert_eq!(fold.follow(None, None, false), Some(false));
}
#[test]
fn folded_by_hand_it_stays_folded_until_another_map_is_picked() {
let mut fold = MapPreviewFold::default();
fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false);
fold.toggled(false);
fold.follow(None, None, false);
assert_eq!(fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false), None, "same map: stays folded");
assert_eq!(fold.follow(Some(BakedMap::Curvature), Some(BakedMap::Curvature), false), Some(true));
}
#[test]
fn switching_the_preview_off_leaves_the_section_open() {
let mut fold = MapPreviewFold::default();
fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false);
assert_eq!(fold.follow(None, Some(BakedMap::AmbientOcclusion), true), None);
}
}
+21 -4
View File
@@ -7,6 +7,12 @@ mod bake_visualization_toggles;
mod breadcrumb;
mod common_settings;
mod glyph_look;
mod live_preview;
mod live_preview_target;
mod map_preview_fold;
mod preview_input;
mod running_preview;
pub(crate) use live_preview::LivePreview;
mod section_opening;
pub(crate) use bake_checks::bake_warnings;
pub use bake_paint_brush::BakePaintBrush;
@@ -178,9 +184,19 @@ pub fn mesh_map_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) {
.inner
});
let texture_sets = json!(app.session.doc.project.bake_synced_sets(app.session.ts(), BakeSyncGroup::Map(selected)));
edit_settings(app, ui, "mesh_map_settings", texture_sets, |_, ui, settings| {
let changed = edit_settings(app, ui, "mesh_map_settings", texture_sets, |_, ui, settings| {
PropertySheet::show(ui, ("mesh_map_settings_sheet", selected), |sheet| map_settings::show(sheet, selected, &mut settings.maps, restore.inner))
});
// Other changes reach the preview through its check of what its picture was made from
if changed && ui.ctx().dragged_id().is_some() {
let ctx = ui.ctx().clone();
live_preview::slider_dragged(app, &ctx);
}
}
/// Once a frame: the map preview follows the selected map and takes its finished bakes
pub(crate) fn poll_live_preview(app: &mut TextureCraftApp, ctx: &egui::Context) {
live_preview::poll(app, ctx);
}
/// The Common Settings panel: output, high poly, cage and skew settings
@@ -203,14 +219,14 @@ fn edit_settings(
scroll_id: &str,
texture_sets: Value,
contents: impl FnOnce(&mut TextureCraftApp, &mut Ui, &mut BakeSettings) -> Option<Value>,
) {
) -> bool {
let set_index = app.session.ts();
let Some(before) = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.clone()) else { return };
let Some(before) = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.clone()) else { return false };
let mut settings = before.clone();
let reset = egui::ScrollArea::vertical().id_salt(scroll_id).auto_shrink([false; 2]).show(ui, |ui| contents(app, ui, &mut settings)).inner;
if settings == before && reset.is_none() {
return;
return false;
}
let mut patch = settings_patch(&before, &settings);
@@ -218,6 +234,7 @@ fn edit_settings(
fields.extend(reset);
}
app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch }));
true
}
/// What the 3D view shows while a bake runs: the newest finished map, one finished map or the material
@@ -0,0 +1,19 @@
use std::collections::{BTreeMap, BTreeSet};
use texturecraft_engine::core::{BakeResolution, BakeSettings};
/// What a map preview picture is made from, everything its bake reads: when any of it changes, the picture is out of date
#[derive(Clone, Debug, PartialEq)]
pub(super) struct PreviewInput {
pub(super) settings: BakeSettings,
pub(super) mesh_id: u64,
/// The set's UV tiles, the ones left out of the bake, and their resolutions
pub(super) uv_tiles: Vec<u32>,
pub(super) excluded_tiles: BTreeSet<u32>,
pub(super) tile_resolutions: BTreeMap<u32, u32>,
/// The high polys', the cage's and the set's painted maps' shared buffers: a file loaded again under the same name is another buffer
pub(super) high_polys: Vec<usize>,
pub(super) cage: Option<usize>,
pub(super) painted: Vec<usize>,
pub(super) size: BakeResolution,
}
@@ -0,0 +1,18 @@
use std::sync::Arc;
use std::sync::mpsc::Receiver;
use texturecraft_engine::Result;
use texturecraft_engine::bake::{BakeOutput, Progress};
use texturecraft_engine::core::BakeResolution;
use super::live_preview_target::LivePreviewTarget;
/// A map preview bake on its worker: its size, when it started (app time) and whether a dragged slider asked for it
pub(super) struct RunningPreview {
pub(super) target: LivePreviewTarget,
pub(super) size: BakeResolution,
pub(super) started: f64,
pub(super) dragging: bool,
pub(super) progress: Arc<Progress>,
pub(super) receiver: Receiver<Result<BakeOutput>>,
}
+11 -2
View File
@@ -276,6 +276,8 @@ pub struct TextureCraftApp {
pub layer_panel: layer_panel::LayerPanel,
/// The Mesh Map Bakers rows' thumbnails
pub(crate) bake_map_thumbnails: bake_mode::MapThumbnails,
/// The map preview: the selected map on the model while Mesh Map Settings shows it
pub(crate) live_preview: bake_mode::LivePreview,
/// Last frame's viewport rect (logical points), for scripted input.
pub viewport_rect: egui::Rect,
pub fps: f32,
@@ -418,6 +420,7 @@ impl TextureCraftApp {
thumbs: thumbs::Thumbs::default(),
layer_panel: layer_panel::LayerPanel::default(),
bake_map_thumbnails: bake_mode::MapThumbnails::default(),
live_preview: bake_mode::LivePreview::default(),
viewport_rect: egui::Rect::NOTHING,
fps: 0.0,
ui_ms: 0.0,
@@ -618,6 +621,9 @@ impl TextureCraftApp {
return;
}
// The bake takes the 3D view over from the map preview
self.live_preview.release(&mut self.session);
// Restore the picker's view before the preview starts following baked maps
id_color_pick::IdColorPick::end(self);
@@ -738,8 +744,10 @@ impl TextureCraftApp {
}
let Some(job) = self.bake.as_mut() else {
// A preview whose bake is gone must not keep the view
self.session.bake_preview_end();
// A preview whose bake is gone must not keep the view; the map preview keeps its own
if self.live_preview.shown().is_none() {
self.session.bake_preview_end();
}
return;
};
@@ -1131,6 +1139,7 @@ impl eframe::App for TextureCraftApp {
}
}
self.poll_bake(ctx);
bake_mode::poll_live_preview(self, ctx);
self.poll_resize(ctx);
#[cfg(not(target_arch = "wasm32"))]
self.poll_high_poly_job(ctx);
@@ -0,0 +1,168 @@
//! The map preview: the selected map's settings show it on the model, small while a slider is dragged
use egui::{Event, Modifiers, PointerButton, Role};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use texturecraft_engine::core::{BakeResolution, BakedMap};
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::docking::Panel;
use texturecraft_ui_egui::state::Mode;
/// How long a steady drag may take to bring its first new pictures, on a slow machine
const MOVING_DRAG_LIMIT: std::time::Duration = std::time::Duration::from_secs(20);
/// Bake mode on the sample with Ambient Occlusion's settings in front
fn harness() -> Harness<'static, TextureCraftApp> {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
session.doc.project.texture_sets[0].bake = Default::default();
session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::R1024;
// No earlier bake to start the preview from: its first picture is a preview bake at the chosen size
session.doc.baked.clear();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.mode = Mode::Baking;
harness.state_mut().ui.bake_visualization.map_preview_size = BakeResolution::R256;
harness.run_steps(4);
harness.get(egui_kittest::kittest::by().role(Role::Button).label("Ambient Occlusion")).click();
harness.state_mut().ui.dock.focus(Panel::MeshMapSettings);
harness.run_steps(3);
harness
}
/// The size of the picture the preview shows for the first set, once it is `wanted` (the worker gets a few seconds)
fn wait_for_preview(harness: &mut Harness<'static, TextureCraftApp>, wanted: impl Fn(u32) -> bool) -> Option<u32> {
for _ in 0..600 {
harness.run_steps(1);
let shown =
harness.state().session.bake_preview_baked(0).and_then(|baked| baked.maps.contains_key(&BakedMap::AmbientOcclusion).then_some(baked.resolution));
if shown.is_some_and(&wanted) {
return shown;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
None
}
#[test]
fn the_selected_map_shows_on_the_model_and_common_settings_hide_it_at_once() {
let mut harness = harness();
let shown = wait_for_preview(&mut harness, |_| true);
assert!(shown.is_some(), "selecting a map's settings shows it");
assert_eq!(harness.state().session.view, texturecraft_engine::ViewMode::MeshMap(BakedMap::AmbientOcclusion));
harness.state_mut().ui.dock.focus(Panel::CommonSettings);
harness.run_steps(1);
assert!(!harness.state().session.bake_preview_active(), "no lingering picture");
assert_ne!(harness.state().session.view, texturecraft_engine::ViewMode::MeshMap(BakedMap::AmbientOcclusion));
}
#[test]
fn a_dragged_slider_previews_smaller_than_the_picture_it_settles_on() {
let mut harness = harness();
let settled = wait_for_preview(&mut harness, |_| true).unwrap();
let track = harness.get_by_role_and_label(Role::Slider, "Secondary Rays").rect();
let (from, to) = (track.center(), track.left_center() + egui::vec2(track.width() * 0.1, 0.0));
harness.hover_at(from);
harness.run_steps(1);
harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
harness.run_steps(1);
harness.hover_at(to);
let dragged = wait_for_preview(&mut harness, |size| size < settled);
harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
let released = wait_for_preview(&mut harness, |size| size == settled);
assert!(dragged.is_some(), "while dragging the preview bakes smaller");
assert!(released.is_some(), "the release refines it to the chosen size");
}
#[test]
fn switching_the_preview_off_hides_it() {
let mut harness = harness();
wait_for_preview(&mut harness, |_| true);
harness.state_mut().ui.bake_visualization.map_preview = false;
harness.run_steps(1);
assert!(!harness.state().session.bake_preview_active());
}
#[test]
fn pictures_keep_coming_while_the_slider_is_still_moving() {
let mut harness = harness();
// Many rays: each preview bake takes several frames, as on a real mesh
harness.state_mut().session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.rays = 256;
wait_for_preview(&mut harness, |_| true);
let track = harness.get_by_role_and_label(Role::Slider, "Spread Angle").rect();
let from = track.left_center() + egui::vec2(track.width() * 0.05, 0.0);
let picture = |harness: &Harness<'static, TextureCraftApp>| {
harness.state().session.bake_preview_baked(0).and_then(|baked| baked.maps.get(&BakedMap::AmbientOcclusion).cloned())
};
harness.hover_at(from);
harness.run_steps(1);
harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
// Holding the last picture keeps a new one from reusing its address
let mut last = picture(&harness);
let mut pictures = 0;
let started = std::time::Instant::now();
for step in 0.. {
if pictures > 2 || started.elapsed() > MOVING_DRAG_LIMIT {
break;
}
// Every frame moves the slider, as a steady drag does
harness.hover_at(from + egui::vec2(track.width() * 0.002 * (step % 200) as f32, 0.0));
harness.run_steps(1);
let now = picture(&harness);
if now.as_ref().map(std::sync::Arc::as_ptr) != last.as_ref().map(std::sync::Arc::as_ptr) {
pictures += 1;
last = now;
}
}
assert!(pictures > 2, "new pictures arrive while the slider never stops");
}
#[test]
fn a_new_resolution_or_a_settings_change_from_anywhere_bakes_the_preview_again() {
let mut harness = harness();
let first = wait_for_preview(&mut harness, |_| true).unwrap();
let picture = |harness: &Harness<'static, TextureCraftApp>| {
harness.state().session.bake_preview_baked(0).and_then(|baked| baked.maps.get(&BakedMap::AmbientOcclusion).cloned())
};
harness.state_mut().ui.bake_visualization.map_preview_size = BakeResolution::R128;
let resized = wait_for_preview(&mut harness, |size| size < first);
assert!(resized.is_some(), "a smaller resolution bakes a smaller picture");
// A change that doesn't come from the panel: a script, an undo or a synced set
let before = picture(&harness);
harness.state_mut().run("bake.settings", serde_json::json!({ "ts": 0, "patch": { "maps": { "ao": { "parameters": { "rays": { "rays": 8 } } } } } }));
let mut changed = false;
for _ in 0..600 {
harness.run_steps(1);
if picture(&harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr) {
changed = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(changed, "the settings change brings a new picture");
// The same file loaded again: same name, new geometry
for (index, bytes) in [b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".as_slice(), b"v 0 0 0\nv 2 0 0\nv 0 2 0\nf 1 2 3\n".as_slice()].into_iter().enumerate() {
let session = &mut harness.state_mut().session;
if index > 0 {
session.remove_high_poly(0).unwrap();
}
session.add_high_poly_bytes("High.obj", bytes.to_vec()).unwrap();
let before = picture(&harness);
let reloaded = (0..600).any(|_| {
harness.run_steps(1);
std::thread::sleep(std::time::Duration::from_millis(10));
picture(&harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr)
});
assert!(reloaded, "high poly load {index} brings a new picture");
}
}
+1
View File
@@ -4,6 +4,7 @@
mod alpha_parameters;
mod anchor_point;
mod bake_job_mesh;
mod bake_live_preview;
mod bake_map_rows;
mod bake_mode;
mod bake_presets;