mirror of
https://github.com/storytold/texturecraft.git
synced 2026-12-01 21:47:59 +00:00
Move viewport UV padding to the GPU and trace layer updates
This commit is contained in:
@@ -217,6 +217,10 @@ fn main() {
|
||||
std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id())));
|
||||
let ui_file =
|
||||
persistence_path.as_ref().map(|path| path.with_extension("json")).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("ui.json")));
|
||||
if let Some(file) = &ui_file {
|
||||
let log = if persistence_path.is_some() { file.with_extension("performance.log") } else { file.with_file_name("performance.log") };
|
||||
texturecraft_engine::log::set_performance_log_path(log);
|
||||
}
|
||||
if let Some(file) = &ui_file {
|
||||
let _ = ui_state_store::FILE.set(file.clone());
|
||||
}
|
||||
|
||||
@@ -12,14 +12,18 @@ use crate::session::DISPLAY_PADDING;
|
||||
|
||||
/// The viewport's padding map. Reading the dense map explicitly also works for uniform UVs.
|
||||
pub struct DisplayPadding {
|
||||
dense: OnceLock<Arc<DilationMap>>,
|
||||
dense: Arc<OnceLock<Arc<DilationMap>>>,
|
||||
size: (u32, u32),
|
||||
mixed: Option<Arc<UvGBuffer>>,
|
||||
block: u32,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
worker_started: bool,
|
||||
/// All texels covered or all uncovered. Mixed coverage needs the ordinary dilation map.
|
||||
uniform: Option<bool>,
|
||||
}
|
||||
|
||||
impl DisplayPadding {
|
||||
pub(crate) fn new(gbuf: &UvGBuffer, has_coverage: bool, block: u32) -> Self {
|
||||
pub(crate) fn new(gbuf: &Arc<UvGBuffer>, has_coverage: bool, block: u32) -> Self {
|
||||
let size = (gbuf.width, gbuf.height);
|
||||
let uniform = if !has_coverage {
|
||||
Some(false)
|
||||
@@ -28,12 +32,16 @@ impl DisplayPadding {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let dense = if uniform.is_none() {
|
||||
Arc::new(DilationMap::in_blocks(&gbuf.coverage_mask(), size.0, size.1, Some(DISPLAY_PADDING), block)).into()
|
||||
} else {
|
||||
OnceLock::new()
|
||||
};
|
||||
Self { dense, size, uniform }
|
||||
let mixed = uniform.is_none().then(|| Arc::clone(gbuf));
|
||||
Self {
|
||||
dense: Arc::default(),
|
||||
size,
|
||||
mixed,
|
||||
block,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
worker_started: false,
|
||||
uniform,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn apply_to_tiles(&self, output: &mut Composite, tiles: &[(u32, u32)]) -> BTreeSet<(u32, u32)> {
|
||||
@@ -45,9 +53,29 @@ impl DisplayPadding {
|
||||
self.uniform == Some(true)
|
||||
}
|
||||
|
||||
/// Share existing island padding without constructing a dense map for uniform coverage.
|
||||
pub fn existing_sources(&self) -> Option<Arc<DilationMap>> {
|
||||
if self.uniform.is_none() { self.dense.get().cloned() } else { None }
|
||||
/// Share the UV coverage so GPU display can calculate padding without the CPU map.
|
||||
pub fn mixed_coverage(&self) -> Option<Arc<UvGBuffer>> {
|
||||
self.mixed.clone()
|
||||
}
|
||||
|
||||
/// Start the dense CPU fallback on a worker so the viewport can keep drawing.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn prepare_on_worker(&mut self) -> bool {
|
||||
let Some(gbuf) = self.mixed.as_ref() else { return true };
|
||||
if self.dense.get().is_some() {
|
||||
return true;
|
||||
}
|
||||
if !self.worker_started {
|
||||
let (gbuf, dense, block) = (gbuf.clone(), self.dense.clone(), self.block);
|
||||
self.worker_started = std::thread::Builder::new()
|
||||
.name("texturecraft-padding".into())
|
||||
.spawn(move || {
|
||||
dense.get_or_init(|| mixed_sources(&gbuf, block));
|
||||
})
|
||||
.is_ok();
|
||||
}
|
||||
// If creating a thread failed, let the caller prepare the map synchronously.
|
||||
!self.worker_started
|
||||
}
|
||||
|
||||
pub(crate) fn bytes(&self) -> usize {
|
||||
@@ -61,9 +89,16 @@ impl Deref for DisplayPadding {
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.dense.get_or_init(|| {
|
||||
let (width, height) = self.size;
|
||||
if let Some(gbuf) = &self.mixed {
|
||||
return mixed_sources(gbuf, self.block);
|
||||
}
|
||||
let n = width as usize * height as usize;
|
||||
let src = if self.uniform == Some(true) { (0..n as u32).collect() } else { vec![texturecraft_texel::dilate::NONE; n] };
|
||||
Arc::new(DilationMap { width, height, src })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn mixed_sources(gbuf: &UvGBuffer, block: u32) -> Arc<DilationMap> {
|
||||
Arc::new(DilationMap::in_blocks(&gbuf.coverage_mask(), gbuf.width, gbuf.height, Some(DISPLAY_PADDING), block))
|
||||
}
|
||||
|
||||
@@ -192,11 +192,17 @@ impl Session {
|
||||
|
||||
/// Open a `.tcraft` project from bytes.
|
||||
pub fn from_project_bytes(bytes: &[u8]) -> Result<Session> {
|
||||
let start = chrono::Utc::now();
|
||||
let pf = texturecraft_formats::load_project_bytes(bytes).map_err(fe)?;
|
||||
Session::from_project_file(pf)
|
||||
let mut log = crate::SessionLog::new();
|
||||
log.performance(format!("CPU project archive decoded in {} ms", (chrono::Utc::now() - start).num_milliseconds()));
|
||||
let mut session = Session::from_project_file(pf)?;
|
||||
session.log.prepend(log);
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
pub fn from_project_file(pf: ProjectFile) -> Result<Session> {
|
||||
let start = chrono::Utc::now();
|
||||
let mesh = match (&pf.mesh, pf.project.mesh.strip_prefix("builtin:")) {
|
||||
(_, Some(id)) => primitives::builtin(id).ok_or_else(|| EngineError::Other(format!("unknown built-in mesh `{id}`")))?,
|
||||
(Some((ext, bytes)), None) => read_stored_mesh(&pf.project, ext, bytes)?.mesh,
|
||||
@@ -206,13 +212,22 @@ impl Session {
|
||||
check_materials(&pf.project, &mesh)?;
|
||||
let source = pf.mesh.clone();
|
||||
let resources = pf.resources.into_iter().map(|(k, v)| (k, std::sync::Arc::new(v))).collect();
|
||||
let mesh_time = chrono::Utc::now();
|
||||
let mut s =
|
||||
Session::new(Document { bake_paint: Default::default(), project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, mesh, source)?;
|
||||
|
||||
let cache_time = chrono::Utc::now();
|
||||
s.sync_images();
|
||||
s.load_bake_meshes(pf.high_poly, pf.cage);
|
||||
s.load_bake_paint(pf.bake_paint);
|
||||
s.log.warnings("Project", pf.warnings);
|
||||
s.log.performance(format!(
|
||||
"CPU project setup: mesh {} ms, UV and mesh indexes {} ms, resources {} ms ({} texture sets)",
|
||||
(mesh_time - start).num_milliseconds(),
|
||||
(cache_time - mesh_time).num_milliseconds(),
|
||||
(chrono::Utc::now() - cache_time).num_milliseconds(),
|
||||
s.caches.len()
|
||||
));
|
||||
|
||||
Ok(s)
|
||||
}
|
||||
@@ -469,8 +484,12 @@ mod native {
|
||||
pub fn open_path(path: &str) -> Result<Session> {
|
||||
let p = Path::new(path);
|
||||
if ext_of(path) == PROJECT_EXT {
|
||||
let start = chrono::Utc::now();
|
||||
let pf = texturecraft_formats::load_project(p).map_err(fe)?;
|
||||
let mut log = crate::SessionLog::new();
|
||||
log.performance(format!("CPU project archive read and decoded in {} ms", (chrono::Utc::now() - start).num_milliseconds()));
|
||||
let mut s = Session::from_project_file(pf)?;
|
||||
s.log.prepend(log);
|
||||
s.path = Some(path.to_string());
|
||||
s.modified = false;
|
||||
Ok(s)
|
||||
|
||||
@@ -6,6 +6,12 @@ pub use crate::log_entry::LogEntry;
|
||||
pub use crate::log_level::LogLevel;
|
||||
pub use crate::session_log::SessionLog;
|
||||
|
||||
/// Set the optional file for desktop diagnostics before opening a project.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn set_performance_log_path(path: std::path::PathBuf) {
|
||||
crate::session_log::set_performance_log_path(path);
|
||||
}
|
||||
|
||||
/// The source of entries that came without one (plain `push`)
|
||||
pub const DEFAULT_SOURCE: &str = "TextureCraft";
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
//! A bounded, disposable material image for a viewport with a cold composite.
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_compose::{BakedMaps, Composite, DisplayKind, Inputs, all_tiles, composite_tiles, kinds_for, tile_bytes};
|
||||
use texturecraft_core::Channel;
|
||||
use texturecraft_geom::UvGBuffer;
|
||||
@@ -37,7 +39,7 @@ impl Session {
|
||||
});
|
||||
let (tri, bary) =
|
||||
positions.map(|i| (source.tri.get(i).copied().unwrap_or(texturecraft_geom::NO_TRI), source.bary.get(i).copied().unwrap_or_default())).unzip();
|
||||
let gbuf = UvGBuffer { width, height, tri, bary, overlaps: 0 };
|
||||
let gbuf = Arc::new(UvGBuffer { width, height, tri, bary, overlaps: 0 });
|
||||
let empty = BakedMaps::default();
|
||||
let baked = self.doc.baked.get(&ts).unwrap_or(&empty);
|
||||
let channels = set.channel_list();
|
||||
|
||||
@@ -62,14 +62,14 @@ pub struct SetCache {
|
||||
impl SetCache {
|
||||
pub(crate) fn new(mesh: &Mesh, ts: &TextureSet) -> SetCache {
|
||||
let (w, h) = ts.size();
|
||||
let gbuf = UvGBuffer::new(mesh, ts.material, w, h);
|
||||
let gbuf = Arc::new(UvGBuffer::new(mesh, ts.material, w, h));
|
||||
// Padding stays inside each UV tile.
|
||||
let covered = covered_tiles(&gbuf);
|
||||
let dilation = DisplayPadding::new(&gbuf, !covered.is_empty(), ts.block_resolution());
|
||||
let all: BTreeSet<(u32, u32)> = texturecraft_compose::all_tiles(w, h).into_iter().collect();
|
||||
SetCache {
|
||||
size: (w, h),
|
||||
gbuf: Arc::new(gbuf),
|
||||
gbuf,
|
||||
dilation,
|
||||
covered_tiles: Arc::new(covered),
|
||||
composite: Composite { block_scales: ts.block_scales(), ..Composite::with_size(&ts.channel_list(), w, h) },
|
||||
|
||||
@@ -7,6 +7,14 @@ use crate::{LogEntry, LogLevel};
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct SessionLog(Vec<LogEntry>);
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
static PERFORMANCE_LOG: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new();
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn set_performance_log_path(path: std::path::PathBuf) {
|
||||
let _ = PERFORMANCE_LOG.set(path);
|
||||
}
|
||||
|
||||
impl SessionLog {
|
||||
pub fn new() -> SessionLog {
|
||||
SessionLog(Vec::new())
|
||||
@@ -25,6 +33,22 @@ impl SessionLog {
|
||||
self.0.push(LogEntry::new(LogLevel::Info, source, message));
|
||||
}
|
||||
|
||||
/// Keep timings in the session log and, on desktop, in the local diagnostic log.
|
||||
pub fn performance(&mut self, message: impl Into<String>) {
|
||||
let entry = LogEntry::new(LogLevel::Info, "Performance", message);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(path) = PERFORMANCE_LOG.get() {
|
||||
use std::io::Write as _;
|
||||
if let Some(dir) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(dir);
|
||||
}
|
||||
if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
|
||||
let _ = writeln!(file, "[{}] {}", entry.time.to_rfc3339(), entry.message);
|
||||
}
|
||||
}
|
||||
self.0.push(entry);
|
||||
}
|
||||
|
||||
pub fn warn(&mut self, source: &str, message: impl Into<String>) {
|
||||
self.0.push(LogEntry::new(LogLevel::Warning, source, message));
|
||||
}
|
||||
@@ -45,6 +69,11 @@ impl SessionLog {
|
||||
self.0.extend(other.0);
|
||||
}
|
||||
|
||||
pub(crate) fn prepend(&mut self, mut earlier: SessionLog) {
|
||||
earlier.0.append(&mut self.0);
|
||||
self.0 = earlier.0;
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.0.clear();
|
||||
}
|
||||
|
||||
@@ -136,6 +136,7 @@ impl ResizeTask {
|
||||
/// Resample the set's painted pixels (bilinear; strokes are not replayed) and build its
|
||||
/// caches. Progress goes from 0 to 1.
|
||||
pub fn run(self, progress: &texturecraft_bake::Progress) -> Result<ResizeOutput> {
|
||||
let start = chrono::Utc::now();
|
||||
let ResizeTask { ts, resolution, mut doc, mesh, from } = self;
|
||||
let set = doc.project.texture_set_mut(ts)?;
|
||||
let old = set.clone();
|
||||
@@ -151,9 +152,18 @@ impl ResizeTask {
|
||||
crate::uv_tile_cmds::relayout(&mut doc, ts, &old, &mut log)?;
|
||||
}
|
||||
progress.done.store(3_000, std::sync::atomic::Ordering::Relaxed);
|
||||
let resampled = chrono::Utc::now();
|
||||
let set = doc.project.texture_set(ts)?;
|
||||
let cache = (crate::session::uv_layout(&old) == crate::session::uv_layout(set)).then(|| SetCache::new(&mesh, set));
|
||||
progress.done.store(10_000, std::sync::atomic::Ordering::Relaxed);
|
||||
log.performance(format!(
|
||||
"CPU resize of texture set {} from {} to {}: paint resampling {} ms, UV cache {}",
|
||||
ts + 1,
|
||||
old.resolution,
|
||||
resolution,
|
||||
(resampled - start).num_milliseconds(),
|
||||
if cache.is_some() { format!("{} ms", (chrono::Utc::now() - resampled).num_milliseconds()) } else { "rebuilt on apply".into() }
|
||||
));
|
||||
Ok(ResizeOutput { ts, resolution, doc, cache, log, from })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,8 @@ use bytemuck::{Pod, Zeroable};
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_compose::PixelStore;
|
||||
use texturecraft_core::{BlendMode, Channel, Effect, EffectKind, Filter, LayerKind, MaskBackground, ProceduralKind, Project, Projection, Source};
|
||||
use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage};
|
||||
use texturecraft_geom::{NO_TRI, UvGBuffer};
|
||||
use texturecraft_texel::{TILE, TILE_AREA, TileImage};
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
const MAX_LAYERS: usize = 128;
|
||||
@@ -75,7 +76,7 @@ pub struct CompositeProgram {
|
||||
layer_count: u32,
|
||||
paint: Vec<u32>,
|
||||
pub(crate) region: Option<CompositeRegion>,
|
||||
pub(crate) coverage: Option<Arc<DilationMap>>,
|
||||
coverage: Option<(Arc<UvGBuffer>, u32)>,
|
||||
pub(crate) writes_height: bool,
|
||||
pub(crate) writes_normal: bool,
|
||||
}
|
||||
@@ -86,8 +87,8 @@ impl CompositeProgram {
|
||||
}
|
||||
|
||||
/// Let the shader sample the nearest covered UV texel for island padding.
|
||||
pub fn set_coverage(&mut self, coverage: Option<Arc<DilationMap>>) {
|
||||
self.coverage = coverage;
|
||||
pub fn set_coverage(&mut self, coverage: Arc<UvGBuffer>, radius: u32) {
|
||||
self.coverage = Some((coverage, radius.min(15)));
|
||||
}
|
||||
|
||||
/// A flat stack of sparse paint, solid and UV procedural fills, masks and point effects.
|
||||
@@ -97,21 +98,29 @@ impl CompositeProgram {
|
||||
}
|
||||
|
||||
pub fn compile_region(project: &Project, pixels: &PixelStore, ts: usize, region: Option<CompositeRegion>) -> Option<Self> {
|
||||
Self::try_compile_region(project, pixels, ts, region).ok()
|
||||
}
|
||||
|
||||
/// Also provide the reason the viewport must select its CPU compositor.
|
||||
pub fn try_compile_region(project: &Project, pixels: &PixelStore, ts: usize, region: Option<CompositeRegion>) -> Result<Self, &'static str> {
|
||||
use Channel::*;
|
||||
let set = project.texture_sets.get(ts)?;
|
||||
if !set.uv_tiles.is_empty() || set.has_channel(Glossiness) {
|
||||
return None;
|
||||
let set = project.texture_sets.get(ts).ok_or("The texture set is missing.")?;
|
||||
if !set.uv_tiles.is_empty() {
|
||||
return Err("UDIM texture sets use CPU compositing.");
|
||||
}
|
||||
if set.has_channel(Glossiness) {
|
||||
return Err("The Glossiness channel uses CPU compositing.");
|
||||
}
|
||||
let mut operations = Vec::new();
|
||||
let mut paint = vec![0];
|
||||
let mut effects = Vec::new();
|
||||
for id in &set.stack {
|
||||
let layer = project.layers.get(id)?;
|
||||
let layer = project.layers.get(id).ok_or("A layer is missing from the material.")?;
|
||||
if !layer.visible {
|
||||
continue;
|
||||
}
|
||||
if layer.geometry_mask.is_some() || layer.height_mask.enabled {
|
||||
return None;
|
||||
return Err("A geometry or height mask uses CPU compositing.");
|
||||
}
|
||||
let mask = layer.mask.as_ref().filter(|m| m.enabled);
|
||||
let mask_start = effects.len() as u32;
|
||||
@@ -119,18 +128,22 @@ impl CompositeProgram {
|
||||
if let Some(mask) = mask {
|
||||
for effect in mask.effects.iter().filter(|e| e.visible) {
|
||||
let mut op = match &effect.kind {
|
||||
EffectKind::Fill { source, projection } => source_operation(Some(source), projection, [0.0; 3])?,
|
||||
EffectKind::Fill { source, projection } => {
|
||||
source_operation(Some(source), projection, [0.0; 3]).ok_or("A mask fill source or projection uses CPU compositing.")?
|
||||
}
|
||||
EffectKind::Paint | EffectKind::Path(_) => {
|
||||
let Some(image) = pixels.masks.get(&effect.id).filter(|im| im.allocated_count() > 0) else { continue };
|
||||
if (image.width(), image.height()) != set.size() || image.comps() != 2 {
|
||||
return None;
|
||||
return Err("A painted mask has a layout that uses CPU compositing.");
|
||||
}
|
||||
Operation { ids: [0, 10, pack_paint(&mut paint, image, region.map(|r| r.expanded(TILE)))?, 2], ..Operation::zeroed() }
|
||||
let offset =
|
||||
pack_paint(&mut paint, image, region.map(|r| r.expanded(TILE))).ok_or("The painted material exceeds the GPU upload budget.")?;
|
||||
Operation { ids: [0, 10, offset, 2], ..Operation::zeroed() }
|
||||
}
|
||||
_ => point_effect(effect)?,
|
||||
_ => point_effect(effect).ok_or("A mask effect uses CPU compositing.")?,
|
||||
};
|
||||
if !effect.opacity.is_finite() {
|
||||
return None;
|
||||
return Err("A mask effect has an invalid opacity.");
|
||||
}
|
||||
op.low[3] = effect.opacity.clamp(0.0, 1.0);
|
||||
op.balance[2] = blend_code(effect.blend) as f32;
|
||||
@@ -143,22 +156,22 @@ impl CompositeProgram {
|
||||
continue;
|
||||
}
|
||||
for effect in layer.content_effects.iter().filter(|e| e.visible) {
|
||||
effects.push(point_effect(effect)?);
|
||||
effects.push(point_effect(effect).ok_or("A layer effect uses CPU compositing.")?);
|
||||
}
|
||||
let content_count = effects.len() as u32 - content_start;
|
||||
if effects.len() > MAX_EFFECTS {
|
||||
return None;
|
||||
return Err("The number of effects exceeds the GPU compositor limit.");
|
||||
}
|
||||
let fill = match &layer.kind {
|
||||
LayerKind::Fill(fill) => Some(fill),
|
||||
LayerKind::Paint => None,
|
||||
_ => return None,
|
||||
_ => return Err("A group or another layer type uses CPU compositing."),
|
||||
};
|
||||
if fill.is_some_and(|fill| {
|
||||
matches!(fill.projection, Projection::Decal(_))
|
||||
|| fill.sources.values().any(|source| !matches!(source, Source::Uniform(_) | Source::Procedural { .. }))
|
||||
}) {
|
||||
return None;
|
||||
return Err("An image source or decal uses CPU compositing.");
|
||||
}
|
||||
|
||||
for &(channel, _) in &set.channels {
|
||||
@@ -167,12 +180,12 @@ impl CompositeProgram {
|
||||
continue;
|
||||
}
|
||||
if !blend.opacity.is_finite() {
|
||||
return None;
|
||||
return Err("A layer has an invalid opacity.");
|
||||
}
|
||||
let painted = if fill.is_none() {
|
||||
let Some(image) = pixels.layer(*id, channel).filter(|img| img.allocated_count() > 0) else { continue };
|
||||
if (image.width(), image.height()) != set.size() || image.comps() != channel.components() + 1 {
|
||||
return None;
|
||||
return Err("A paint layer has a layout that uses CPU compositing.");
|
||||
}
|
||||
Some(image)
|
||||
} else {
|
||||
@@ -196,12 +209,14 @@ impl CompositeProgram {
|
||||
{
|
||||
continue;
|
||||
}
|
||||
_ => return None,
|
||||
_ => return Err("A channel in the layer stack uses CPU compositing."),
|
||||
};
|
||||
let mut op = if let Some(image) = painted {
|
||||
Operation { ids: [slot, 10, pack_paint(&mut paint, image, region.map(|r| r.expanded(TILE)))?, image.comps() as u32], ..Operation::zeroed() }
|
||||
let offset =
|
||||
pack_paint(&mut paint, image, region.map(|r| r.expanded(TILE))).ok_or("The painted material exceeds the GPU upload budget.")?;
|
||||
Operation { ids: [slot, 10, offset, image.comps() as u32], ..Operation::zeroed() }
|
||||
} else {
|
||||
source_operation(source, &fill?.projection, default)?
|
||||
fill.and_then(|fill| source_operation(source, &fill.projection, default)).ok_or("A fill source or projection uses CPU compositing.")?
|
||||
};
|
||||
op.ids[0] = slot;
|
||||
op.low[3] = blend.opacity.min(1.0);
|
||||
@@ -209,13 +224,13 @@ impl CompositeProgram {
|
||||
op.balance[2] = blend_code(blend.mode) as f32;
|
||||
op.effects = [mask_start, mask_count, content_start, content_count];
|
||||
if operations.len() == MAX_LAYERS {
|
||||
return None;
|
||||
return Err("The number of layer channels exceeds the GPU compositor limit.");
|
||||
}
|
||||
operations.push(op);
|
||||
}
|
||||
}
|
||||
if operations.is_empty() {
|
||||
return None;
|
||||
return Err("The layer stack has no visible material inputs.");
|
||||
}
|
||||
let changes_channel = |slot, default: [f32; 3]| {
|
||||
operations
|
||||
@@ -226,7 +241,7 @@ impl CompositeProgram {
|
||||
let writes_normal = changes_channel(7, Normal.default_value());
|
||||
let layer_count = operations.len() as u32;
|
||||
operations.extend(effects);
|
||||
Some(Self { operations, layer_count, paint, region, coverage: None, writes_height, writes_normal })
|
||||
Ok(Self { operations, layer_count, paint, region, coverage: None, writes_height, writes_normal })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -363,11 +378,15 @@ fn pack_paint(dst: &mut Vec<u32>, image: &TileImage, region: Option<CompositeReg
|
||||
Some(table as u32)
|
||||
}
|
||||
|
||||
fn coverage_word(triangles: &[u32]) -> u32 {
|
||||
triangles.iter().enumerate().fold(0, |word, (bit, &triangle)| word | (u32::from(triangle != NO_TRI) << bit))
|
||||
}
|
||||
|
||||
pub(crate) struct GpuCompositor {
|
||||
pipeline: wgpu::ComputePipeline,
|
||||
lookup: wgpu::Buffer,
|
||||
uniform_coverage: wgpu::Buffer,
|
||||
coverage: Option<(Weak<DilationMap>, u32, wgpu::Buffer)>,
|
||||
coverage: Option<(Weak<UvGBuffer>, wgpu::Buffer)>,
|
||||
}
|
||||
|
||||
impl GpuCompositor {
|
||||
@@ -406,46 +425,40 @@ impl GpuCompositor {
|
||||
Self { pipeline, lookup, uniform_coverage, coverage: None }
|
||||
}
|
||||
|
||||
fn coverage_buffer(&mut self, device: &wgpu::Device, map: Option<&Arc<DilationMap>>, shift: u32, size: (u32, u32)) -> Result<wgpu::Buffer, String> {
|
||||
fn coverage_buffer(&mut self, device: &wgpu::Device, map: Option<&Arc<UvGBuffer>>) -> Result<wgpu::Buffer, String> {
|
||||
let Some(map) = map else { return Ok(self.uniform_coverage.clone()) };
|
||||
let key = Arc::downgrade(map);
|
||||
if let Some((cached, last_shift, buffer)) = &self.coverage
|
||||
if let Some((cached, buffer)) = &self.coverage
|
||||
&& key.ptr_eq(cached)
|
||||
&& shift == *last_shift
|
||||
{
|
||||
return Ok(buffer.clone());
|
||||
}
|
||||
let (w, h) = (size.0 as usize, size.1 as usize);
|
||||
let count = (w * h).div_ceil(2);
|
||||
let width = map.width as usize;
|
||||
let words_per_row = width.div_ceil(32);
|
||||
let count = words_per_row * map.height as usize;
|
||||
let limits = device.limits();
|
||||
if (count * 4) as u64 > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) {
|
||||
return Err("UV padding data exceeds the adapter's storage-buffer limit".into());
|
||||
}
|
||||
let sample = |i: usize| -> Option<u32> {
|
||||
if i >= w * h {
|
||||
return Some(0xffff);
|
||||
}
|
||||
let (x, y) = (((i % w) as u32) << shift, ((i / w) as u32) << shift);
|
||||
let Some((sx, sy)) = map.source(x, y) else { return Some(0xffff) };
|
||||
let (dx, dy) = (sx as i32 - x as i32, sy as i32 - y as i32);
|
||||
if !(-31..=31).contains(&dx) || !(-31..=31).contains(&dy) {
|
||||
return None;
|
||||
}
|
||||
Some(((dx + 31) as u32) | (((dy + 31) as u32) << 6))
|
||||
// Each word packs 32 coverage samples. The same buffer serves every display resolution.
|
||||
let words: Vec<u32> = if width.is_multiple_of(32) {
|
||||
map.tri.par_chunks(32).map(coverage_word).collect()
|
||||
} else {
|
||||
(0..count)
|
||||
.into_par_iter()
|
||||
.map(|i| {
|
||||
let row = i / words_per_row * width;
|
||||
let start = row + i % words_per_row * 32;
|
||||
coverage_word(&map.tri[start..(start + 32).min(row + width)])
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
// Store two offset pairs per word. The source atlas already owns its exact, dense
|
||||
// padding map. A reduced viewport only uploads offsets for the texels it will sample.
|
||||
let words: Vec<u32> = (0..count)
|
||||
.into_par_iter()
|
||||
.map(|i| Some(sample(2 * i)? | (sample(2 * i + 1)? << 16)))
|
||||
.collect::<Option<_>>()
|
||||
.ok_or("UV padding exceeds the shader's offset range")?;
|
||||
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("tc_composite_coverage"),
|
||||
contents: bytemuck::cast_slice(&words),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
});
|
||||
self.coverage = Some((key, shift, buffer.clone()));
|
||||
self.coverage = Some((key, buffer.clone()));
|
||||
Ok(buffer)
|
||||
}
|
||||
|
||||
@@ -461,7 +474,7 @@ impl GpuCompositor {
|
||||
textures: [&wgpu::Texture; 4],
|
||||
) -> Result<(), String> {
|
||||
let extent = (textures[0].width(), textures[0].height());
|
||||
let coverage = self.coverage_buffer(device, program.coverage.as_ref(), shift, extent)?;
|
||||
let coverage = self.coverage_buffer(device, program.coverage.as_ref().map(|(map, _)| map))?;
|
||||
let region = program.region.map(|r| r.viewport(shift, extent)).unwrap_or(CompositeRegion { min: [0; 2], max: [extent.0, extent.1] });
|
||||
let [left, start_y] = region.min;
|
||||
let width = region.max[0].saturating_sub(left);
|
||||
@@ -515,8 +528,8 @@ impl GpuCompositor {
|
||||
u32::from(program.writes_normal),
|
||||
left,
|
||||
u32::from(program.coverage.is_some()),
|
||||
extent.0,
|
||||
0,
|
||||
source_size.0.div_ceil(32),
|
||||
program.coverage.as_ref().map_or(0, |(_, radius)| *radius),
|
||||
0,
|
||||
];
|
||||
let params = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
|
||||
@@ -23,7 +23,7 @@ struct Params {
|
||||
@group(0) @binding(2) var<storage, read> srgb: array<u32>;
|
||||
@group(0) @binding(3) var<storage, read_write> output: array<u32>;
|
||||
@group(0) @binding(4) var<storage, read> paint: array<u32>;
|
||||
@group(0) @binding(5) var<storage, read> island_padding: array<u32>;
|
||||
@group(0) @binding(5) var<storage, read> uv_coverage: array<u32>;
|
||||
|
||||
fn pcg3d(cell: vec3<u32>) -> vec3<u32> {
|
||||
var v = cell * 1664525u + 1013904223u;
|
||||
@@ -386,6 +386,62 @@ fn to_u16(v: f32) -> u32 {
|
||||
return u32(clamp(v, 0.0, 1.0) * 65535.0 + 0.5);
|
||||
}
|
||||
|
||||
// Find a covered source within the padding radius. The CPU padding's breadth-first
|
||||
// search breaks equal Chebyshev distances in row-major source order.
|
||||
fn padded_source(pixel: vec2<u32>) -> vec2<u32> {
|
||||
let pitch = params.coverage.y;
|
||||
let radius = params.coverage.z;
|
||||
let current = uv_coverage[pixel.y * pitch + pixel.x / 32u];
|
||||
if (current & (1u << (pixel.x % 32u))) != 0u {
|
||||
return pixel;
|
||||
}
|
||||
|
||||
let left = pixel.x - min(pixel.x, radius);
|
||||
let right = min(pixel.x + radius, params.source.x - 1u);
|
||||
let start_word = left / 32u;
|
||||
let start_bit = left % 32u;
|
||||
let center = pixel.x - left;
|
||||
let column_mask = (1u << (right - left + 1u)) - 1u;
|
||||
let lower_columns = (1u << (center + 1u)) - 1u;
|
||||
let top = pixel.y - min(pixel.y, radius);
|
||||
let bottom = min(pixel.y + radius, params.source.y - 1u);
|
||||
var best = params.source.xy;
|
||||
var distance = radius + 1u;
|
||||
|
||||
for (var row = top; row <= bottom; row++) {
|
||||
let dy = max(row, pixel.y) - min(row, pixel.y);
|
||||
if dy >= distance {
|
||||
continue;
|
||||
}
|
||||
let index = row * pitch + start_word;
|
||||
var bits = uv_coverage[index] >> start_bit;
|
||||
if right / 32u != start_word {
|
||||
bits |= uv_coverage[index + 1u] << (32u - start_bit);
|
||||
}
|
||||
bits &= column_mask;
|
||||
if bits == 0u {
|
||||
continue;
|
||||
}
|
||||
|
||||
let lower = bits & lower_columns;
|
||||
let upper = bits & (0xffffffffu << center);
|
||||
var dx = radius + 1u;
|
||||
if lower != 0u {
|
||||
dx = center - firstLeadingBit(lower);
|
||||
}
|
||||
if upper != 0u {
|
||||
dx = min(dx, firstTrailingBit(upper) - center);
|
||||
}
|
||||
let candidate = max(dx, dy);
|
||||
if candidate < distance {
|
||||
distance = candidate;
|
||||
let first = center - min(center, distance);
|
||||
best = vec2(left + firstTrailingBit(bits & (0xffffffffu << first)), row);
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
@compute @workgroup_size(8, 8)
|
||||
fn compose(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
if id.x >= params.band.x || id.y >= params.band.y {
|
||||
@@ -393,16 +449,10 @@ fn compose(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
}
|
||||
let display_pixel = vec2(id.x + params.program.w, id.y + params.band.z);
|
||||
var pixel = display_pixel * params.source.z;
|
||||
var covered = true;
|
||||
if params.coverage.x != 0u {
|
||||
let i = display_pixel.y * params.coverage.y + display_pixel.x;
|
||||
let packed = (island_padding[i / 2u] >> ((i % 2u) * 16u)) & 65535u;
|
||||
covered = packed != 65535u;
|
||||
if covered {
|
||||
let offset = vec2<i32>(i32(packed & 63u) - 31, i32(packed >> 6u) - 31);
|
||||
pixel = vec2<u32>(vec2<i32>(pixel) + offset);
|
||||
}
|
||||
pixel = padded_source(pixel);
|
||||
}
|
||||
let covered = all(pixel < params.source.xy);
|
||||
let uv = (vec2<f32>(pixel) + 0.5) / vec2<f32>(params.source.xy);
|
||||
var base = vec3(0.5);
|
||||
var normal = vec3(0.5, 0.5, 1.0);
|
||||
|
||||
+134
-30
@@ -47,6 +47,7 @@ pub type MissingSeamEdges = Vec<Vec<(u32, u32)>>;
|
||||
#[derive(Default)]
|
||||
pub struct SceneSync {
|
||||
pub mesh: Option<(Arc<Mesh>, u64)>,
|
||||
mesh_id: u64,
|
||||
/// (texels across and down, material) per texture set, the mesh material count and the
|
||||
/// viewport texture resolution (display shift).
|
||||
pub sets: Option<(Vec<SetLayout>, usize, u32)>,
|
||||
@@ -57,6 +58,8 @@ pub struct SceneSync {
|
||||
pub overview: Option<(usize, texturecraft_engine::MaterialOverview)>,
|
||||
cleared_overviews: Vec<usize>,
|
||||
composite: Option<(CompositeProgram, Arc<AtomicBool>)>,
|
||||
trace_composite: Option<(f64, Arc<AtomicBool>)>,
|
||||
pub(crate) compositor_changed: bool,
|
||||
pub tiles: Vec<(usize, DisplayKind, u32, u32, Vec<u8>)>,
|
||||
pub aux: Vec<(usize, u32, Vec<u8>)>,
|
||||
/// One image buffer per resolution, with all texture sets that need it.
|
||||
@@ -74,7 +77,7 @@ pub struct SceneSync {
|
||||
}
|
||||
|
||||
impl SceneSync {
|
||||
fn apply_display(&self, renderer: &mut Renderer, device: &wgpu::Device, queue: &wgpu::Queue) -> Vec<usize> {
|
||||
fn apply_display(&self, renderer: &mut Renderer, device: &wgpu::Device, queue: &wgpu::Queue) -> (Vec<usize>, Option<String>) {
|
||||
let mut reset = Vec::new();
|
||||
if let Some((sets, material_count, shift)) = &self.sets {
|
||||
renderer.set_display_shift(*shift);
|
||||
@@ -84,19 +87,19 @@ impl SceneSync {
|
||||
renderer.seed_display(device, queue, ts, (1, 1), &[]);
|
||||
reset.push(ts);
|
||||
}
|
||||
if let Some((program, failed)) = &self.composite
|
||||
&& let Err(error) = renderer.composite_on_gpu(device, queue, 0, program)
|
||||
{
|
||||
let error = self.composite.as_ref().and_then(|(program, failed)| {
|
||||
let error = renderer.composite_on_gpu(device, queue, 0, program).err()?;
|
||||
log::warn!("Using CPU composition after a GPU error: {error}");
|
||||
failed.store(true, Ordering::Release);
|
||||
}
|
||||
Some(error)
|
||||
});
|
||||
if let Some((ts, overview)) = &self.overview {
|
||||
renderer.seed_display(device, queue, *ts, overview.size, &overview.maps);
|
||||
}
|
||||
for (texture_set, kind, tile_x, tile_y, bytes) in &self.tiles {
|
||||
renderer.upload_display_tile(device, queue, *texture_set, *kind, *tile_x, *tile_y, bytes, self.tile_shift);
|
||||
}
|
||||
reset
|
||||
(reset, error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,6 +120,7 @@ pub struct GpuReports {
|
||||
pub memory: Vec<usize>,
|
||||
/// wgpu errors no error scope caught (logged instead of wgpu's default panic).
|
||||
pub errors: Vec<String>,
|
||||
pub performance: Vec<(u64, String)>,
|
||||
}
|
||||
|
||||
/// Most distinct uncaptured GPU errors kept until the UI shows them.
|
||||
@@ -159,8 +163,12 @@ pub struct GpuLink {
|
||||
cpu_reason: &'static str,
|
||||
gpu_composite_current: Option<CompositeKey>,
|
||||
gpu_display_stroke: Option<u64>,
|
||||
gpu_composite_rejected: Option<CompositeKey>,
|
||||
gpu_composite_rejected: Option<(CompositeKey, &'static str)>,
|
||||
gpu_composite_failed: Arc<AtomicBool>,
|
||||
gpu_composite_in_flight: Arc<AtomicBool>,
|
||||
logged_compositor: Option<(u64, &'static str, &'static str)>,
|
||||
cpu_composite_started: Option<f64>,
|
||||
cpu_padding_pending: bool,
|
||||
bake_scene: BakeSceneLink,
|
||||
}
|
||||
|
||||
@@ -227,6 +235,10 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink {
|
||||
gpu_display_stroke: None,
|
||||
gpu_composite_rejected: None,
|
||||
gpu_composite_failed: Arc::default(),
|
||||
gpu_composite_in_flight: Arc::default(),
|
||||
logged_compositor: None,
|
||||
cpu_composite_started: None,
|
||||
cpu_padding_pending: false,
|
||||
bake_scene: BakeSceneLink::default(),
|
||||
}
|
||||
}
|
||||
@@ -253,6 +265,14 @@ impl GpuLink {
|
||||
s.pending_tiles() > 0 || s.caches.iter().any(|cache| !cache.upload.is_empty())
|
||||
}
|
||||
|
||||
pub(crate) fn gpu_composite_pending(&self) -> bool {
|
||||
self.gpu_composite_in_flight.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub(crate) fn cpu_padding_pending(&self) -> bool {
|
||||
self.cpu_padding_pending
|
||||
}
|
||||
|
||||
pub(crate) fn compositor_status(&self) -> (&'static str, &'static str) {
|
||||
if self.gpu_composite_failed.load(Ordering::Acquire) {
|
||||
return (n_("Layers: CPU"), n_("GPU compositing reported a device error. See the app log for details."));
|
||||
@@ -264,6 +284,27 @@ impl GpuLink {
|
||||
}
|
||||
}
|
||||
|
||||
fn log_compositor(&mut self, session: &mut Session, out: &mut SceneSync, gpu: bool, started: f64) {
|
||||
let (label, reason) = self.compositor_status();
|
||||
let state = (session.mesh_id, label, reason);
|
||||
if self.logged_compositor == Some(state) && out.sets.is_none() {
|
||||
return;
|
||||
}
|
||||
self.logged_compositor = Some(state);
|
||||
out.compositor_changed = true;
|
||||
let (w, h) = session.caches.get(session.ts()).map_or((0, 0), |cache| cache.size);
|
||||
session.log.performance(format!("{label} at {w}×{h}: {reason}"));
|
||||
if gpu {
|
||||
self.cpu_composite_started = None;
|
||||
if out.composite.is_some() {
|
||||
self.gpu_composite_in_flight = Arc::new(AtomicBool::new(true));
|
||||
out.trace_composite = Some((started, self.gpu_composite_in_flight.clone()));
|
||||
}
|
||||
} else if !cfg!(target_arch = "wasm32") {
|
||||
self.cpu_composite_started = Some(started);
|
||||
}
|
||||
}
|
||||
|
||||
fn plan_gpu_composite(&mut self, session: &mut Session, shift: u32, interactive: bool, out: &mut SceneSync) -> bool {
|
||||
self.cpu_reason = if !self.prefer_gpu_layers {
|
||||
n_("CPU is selected for layer compositing in Settings.")
|
||||
@@ -285,13 +326,12 @@ impl GpuLink {
|
||||
return false;
|
||||
}
|
||||
let Some(cache) = session.caches.first() else { return false };
|
||||
let padding = cache.dilation.existing_sources();
|
||||
let padding = cache.dilation.mixed_coverage();
|
||||
if !cache.dilation.fully_covered() && padding.is_none() {
|
||||
self.cpu_reason = n_("The texture set has no covered UV texels.");
|
||||
return false;
|
||||
}
|
||||
|
||||
self.cpu_reason = n_("This material contains layers, effects or channels that use CPU compositing.");
|
||||
let key = CompositeKey { mesh: session.mesh_id, revision: session.revision, size: cache.size, shift };
|
||||
let stroke = session.pending_display_stroke(0);
|
||||
let stroke_id = stroke.map(|(id, _)| id);
|
||||
@@ -300,7 +340,10 @@ impl GpuLink {
|
||||
if current && unchanged_stroke && stroke.is_none_or(|(_, tiles)| tiles.is_empty()) {
|
||||
return true;
|
||||
}
|
||||
if stroke.is_none() && self.gpu_composite_rejected == Some(key) {
|
||||
if stroke.is_none()
|
||||
&& let Some((_, reason)) = self.gpu_composite_rejected.filter(|(rejected, _)| *rejected == key)
|
||||
{
|
||||
self.cpu_reason = reason;
|
||||
return false;
|
||||
}
|
||||
let changed_tiles = if current
|
||||
@@ -326,22 +369,27 @@ impl GpuLink {
|
||||
}
|
||||
let preview = session.display_stroke_pixels(0, region.map(|r| r.expanded(texturecraft_engine::texel::TILE).bounds()));
|
||||
let pixels = preview.as_ref().unwrap_or(&session.doc.pixels);
|
||||
if let Some(mut program) = CompositeProgram::compile_region(&session.doc.project, pixels, 0, region) {
|
||||
program.set_coverage(padding);
|
||||
out.composite = Some((program, self.gpu_composite_failed.clone()));
|
||||
self.gpu_composite_current = Some(key);
|
||||
self.gpu_display_stroke = stroke_id;
|
||||
session.clear_display_stroke_tiles();
|
||||
self.pending_overviews.remove(&0);
|
||||
self.active_overviews.remove(&0);
|
||||
self.sent.entry(0).or_default().extend(DisplayKind::ALL);
|
||||
true
|
||||
} else {
|
||||
if stroke_id.is_none() {
|
||||
self.gpu_composite_rejected = Some(key);
|
||||
let mut program = match CompositeProgram::try_compile_region(&session.doc.project, pixels, 0, region) {
|
||||
Ok(program) => program,
|
||||
Err(reason) => {
|
||||
self.cpu_reason = reason;
|
||||
if stroke_id.is_none() {
|
||||
self.gpu_composite_rejected = Some((key, reason));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
false
|
||||
};
|
||||
if let Some(padding) = padding {
|
||||
program.set_coverage(padding, texturecraft_engine::session::DISPLAY_PADDING);
|
||||
}
|
||||
out.composite = Some((program, self.gpu_composite_failed.clone()));
|
||||
self.gpu_composite_current = Some(key);
|
||||
self.gpu_display_stroke = stroke_id;
|
||||
session.clear_display_stroke_tiles();
|
||||
self.pending_overviews.remove(&0);
|
||||
self.active_overviews.remove(&0);
|
||||
self.sent.entry(0).or_default().extend(DisplayKind::ALL);
|
||||
true
|
||||
}
|
||||
|
||||
/// Compositing progress (0..1) while tiles wait to be composited.
|
||||
@@ -371,7 +419,7 @@ impl GpuLink {
|
||||
self.composite_total = if pending == 0 { 0 } else { self.composite_total.max(pending) };
|
||||
let demand = session.tile_demand(visible_uv);
|
||||
|
||||
let mut out = SceneSync { tile_shift: shift.min(texturecraft_engine::texel::TILE.ilog2()), ..Default::default() };
|
||||
let mut out = SceneSync { mesh_id: session.mesh_id, tile_shift: shift.min(texturecraft_engine::texel::TILE.ilog2()), ..Default::default() };
|
||||
if self.lost.swap(false, Ordering::AcqRel) {
|
||||
self.mesh_id = 0;
|
||||
self.sets.clear();
|
||||
@@ -439,8 +487,10 @@ impl GpuLink {
|
||||
}
|
||||
}
|
||||
|
||||
self.cpu_padding_pending = false;
|
||||
let interactive = aux_map.is_some() || bake.is_some();
|
||||
if self.plan_gpu_composite(session, shift, interactive, &mut out) {
|
||||
self.log_compositor(session, &mut out, true, start_ms);
|
||||
return out;
|
||||
}
|
||||
self.gpu_display_stroke = None;
|
||||
@@ -449,9 +499,20 @@ impl GpuLink {
|
||||
{
|
||||
cache.queue_ready_uploads();
|
||||
}
|
||||
self.log_compositor(session, &mut out, false, start_ms);
|
||||
|
||||
let count = session.caches.len();
|
||||
let active = session.ts();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
// Start at most one dense map at a time, with the active material first.
|
||||
let (before, from_active) = session.caches.split_at_mut(active.min(count));
|
||||
self.cpu_padding_pending = from_active
|
||||
.iter_mut()
|
||||
.chain(before)
|
||||
.filter(|cache| cache.size.0.max(cache.size.1) > 1024 && (!cache.dirty.is_empty() || !cache.settle.is_empty()))
|
||||
.any(|cache| !cache.dilation.prepare_on_worker());
|
||||
}
|
||||
// At most one small full-atlas evaluation per frame, active material first.
|
||||
let next_overview = if self.pending_overviews.remove(&active) { Some(active) } else { self.pending_overviews.pop_first() };
|
||||
if let Some(ts) = next_overview
|
||||
@@ -463,7 +524,7 @@ impl GpuLink {
|
||||
self.active_overviews.insert(ts);
|
||||
out.overview = Some((ts, overview));
|
||||
}
|
||||
if out.overview.is_none() || demand.has_brush() {
|
||||
if !self.cpu_padding_pending && (out.overview.is_none() || demand.has_brush()) {
|
||||
session.update_for_view(COMPOSITE_BUDGET_MS.min(time_left_ms(0)).max(MIN_SLICE_MS), crate::now_ms, demand);
|
||||
}
|
||||
let first = self.upload_cursor.take().filter(|&set| set < count && out.mesh.is_none()).unwrap_or(active);
|
||||
@@ -508,6 +569,11 @@ impl GpuLink {
|
||||
}
|
||||
|
||||
self.active_overviews.retain(|&ts| session.caches.get(ts).is_some_and(|c| !c.dirty.is_empty() || !c.upload.is_empty()));
|
||||
if !self.display_pending(session)
|
||||
&& let Some(started) = self.cpu_composite_started.take()
|
||||
{
|
||||
session.log.performance(format!("CPU layer composition and display tile preparation completed in {:.0} ms", crate::now_ms() - started));
|
||||
}
|
||||
|
||||
if self.aux_image.as_ref().is_some_and(|image| image.strong_count() == 0) {
|
||||
self.aux_image = None;
|
||||
@@ -653,7 +719,10 @@ pub struct ViewCallback {
|
||||
|
||||
impl Drop for ViewCallback {
|
||||
fn drop(&mut self) {
|
||||
if self.sync.get_mut().unwrap_or_else(PoisonError::into_inner).is_some() {
|
||||
if let Some(sync) = self.sync.get_mut().unwrap_or_else(PoisonError::into_inner) {
|
||||
if let Some((_, pending)) = &sync.trace_composite {
|
||||
pending.store(false, Ordering::Release);
|
||||
}
|
||||
self.lost.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
@@ -677,9 +746,26 @@ impl CallbackTrait for ViewCallback {
|
||||
if let Some((mesh, id)) = &sync.mesh {
|
||||
gpu.renderer.set_mesh(device, queue, mesh, *id);
|
||||
}
|
||||
let reset = sync.apply_display(&mut gpu.renderer, device, queue);
|
||||
if sync.composite.as_ref().is_some_and(|(_, failed)| failed.load(Ordering::Acquire)) {
|
||||
let (reset, composite_error) = sync.apply_display(&mut gpu.renderer, device, queue);
|
||||
if let Some(error) = composite_error {
|
||||
if let Some((_, pending)) = &sync.trace_composite {
|
||||
pending.store(false, Ordering::Release);
|
||||
}
|
||||
gpu.reports.lock().unwrap_or_else(PoisonError::into_inner).performance.push((sync.mesh_id, format!("GPU layer submission failed: {error}")));
|
||||
gpu.ctx.request_repaint();
|
||||
} else if let Some((started, pending)) = &sync.trace_composite {
|
||||
let (started, pending, mesh) = (*started, pending.clone(), sync.mesh_id);
|
||||
let cpu_ms = crate::now_ms() - started;
|
||||
let (reports, ctx) = (gpu.reports.clone(), gpu.ctx.clone());
|
||||
queue.on_submitted_work_done(move || {
|
||||
let elapsed = crate::now_ms() - started;
|
||||
reports.lock().unwrap_or_else(PoisonError::into_inner).performance.push((
|
||||
mesh,
|
||||
format!("GPU layer work completed in {elapsed:.0} ms since viewport update started (CPU preparation and submission {cpu_ms:.0} ms)"),
|
||||
));
|
||||
pending.store(false, Ordering::Release);
|
||||
ctx.request_repaint();
|
||||
});
|
||||
}
|
||||
record_recreated_uploads(&mut gpu.recreated.lock().unwrap_or_else(PoisonError::into_inner), &reset, &sync);
|
||||
for (texture_set, size, bytes) in &sync.aux {
|
||||
@@ -789,6 +875,10 @@ pub(crate) mod tests {
|
||||
gpu_display_stroke: None,
|
||||
gpu_composite_rejected: None,
|
||||
gpu_composite_failed: Arc::default(),
|
||||
gpu_composite_in_flight: Arc::default(),
|
||||
logged_compositor: None,
|
||||
cpu_composite_started: None,
|
||||
cpu_padding_pending: false,
|
||||
bake_scene: BakeSceneLink::default(),
|
||||
}
|
||||
}
|
||||
@@ -1070,7 +1160,7 @@ pub(crate) mod tests {
|
||||
if let Some((mesh, id)) = &scene.mesh {
|
||||
h.renderer.set_mesh(&h.device, &h.queue, mesh, *id);
|
||||
}
|
||||
let reset = scene.apply_display(&mut h.renderer, &h.device, &h.queue);
|
||||
let (reset, _) = scene.apply_display(&mut h.renderer, &h.device, &h.queue);
|
||||
record_recreated_uploads(&mut gpu.recreated.lock().unwrap(), &reset, &scene);
|
||||
frames += 1;
|
||||
let ready = s.pending_tiles() == 0 && s.caches[0].upload.is_empty();
|
||||
@@ -1128,6 +1218,12 @@ pub(crate) mod tests {
|
||||
}
|
||||
let mut session = Session::new_project("inset UVs", mesh, "builtin:plane", None, 128).unwrap();
|
||||
execute(&mut session, "layer.add.fill", &json!({"color":[1.0,0.0,0.0]})).unwrap();
|
||||
execute(&mut session, "layer.add.paint", &json!({})).unwrap();
|
||||
let layer = session.selected_layer().unwrap();
|
||||
let paint = session.doc.pixels.layer_mut(layer, Channel::BaseColor, (128, 128));
|
||||
paint.set(32, 32, &[0, 0, 65535, 65535]);
|
||||
paint.set(33, 32, &[0, 65535, 0, 65535]);
|
||||
let geometry_bytes = session.memory().geometry;
|
||||
let mut link = link();
|
||||
link.gpu_composite_enabled = true;
|
||||
let scene = link.sync(&mut session, None, None, 0, 0.0);
|
||||
@@ -1143,11 +1239,19 @@ pub(crate) mod tests {
|
||||
assert_eq!(samples(32, 64), &[255, 0, 0, 255]);
|
||||
assert_eq!(samples(31, 64), &[255, 0, 0, 255]);
|
||||
assert_ne!(samples(16, 64), &[255, 0, 0, 255]);
|
||||
assert_eq!(samples(31, 31), samples(32, 32), "padding across a packed word boundary");
|
||||
assert_eq!(samples(33, 31), samples(32, 32), "the leftmost equidistant texel wins");
|
||||
assert_eq!(samples(34, 31), samples(33, 32), "the closer texel wins");
|
||||
assert_ne!(samples(32, 32), samples(33, 32));
|
||||
assert_eq!(session.memory().geometry, geometry_bytes);
|
||||
assert!(session.log.iter().any(|entry| entry.source == "Performance" && entry.message.contains("Layers: GPU")));
|
||||
|
||||
execute(&mut session, "effect.add.filter", &json!({"target":"content", "filter":"blur", "radius":8})).unwrap();
|
||||
let scene = link.sync(&mut session, None, None, 0, 0.0);
|
||||
assert!(scene.composite.is_none());
|
||||
assert_eq!(link.compositor_status().0, "Layers: CPU");
|
||||
assert!(session.log.iter().any(|entry| entry.message.contains("A layer effect uses CPU compositing.")));
|
||||
assert!(session.memory().geometry > geometry_bytes, "only the CPU path allocates the dense padding map");
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -536,6 +536,14 @@ pub fn status_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
|
||||
.frame(egui::Frame::NONE.fill(tk.chrome).inner_margin(egui::Margin::symmetric(10, 0)))
|
||||
.show(ui, |ui| {
|
||||
ui.horizontal_centered(|ui| {
|
||||
if app.session.project_open {
|
||||
let (label, reason) = app.gpu.as_ref().map_or((tr("Layers: CPU"), tr("The GPU renderer is unavailable.")), |gpu| {
|
||||
let (label, reason) = gpu.compositor_status();
|
||||
(tr(label), tr(reason))
|
||||
});
|
||||
ui.label(RichText::new(label).size(11.0)).on_hover_text(reason);
|
||||
ui.separator();
|
||||
}
|
||||
if let Some(p) = app.bake_progress() {
|
||||
ui.add(egui::ProgressBar::new(p).desired_width(160.0).desired_height(10.0).text(RichText::new(tr("Baking")).size(10.0)));
|
||||
if ui.small_button(tr("Cancel")).clicked() {
|
||||
@@ -543,19 +551,20 @@ pub fn status_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
|
||||
}
|
||||
} else if let Some(job) = &app.resize {
|
||||
let bar = egui::ProgressBar::new(job.progress.fraction()).desired_width(160.0).desired_height(10.0);
|
||||
ui.add(bar.animate(true).text(RichText::new(tr("Resizing")).size(10.0)));
|
||||
ui.add(bar.animate(true).text(RichText::new(tr("CPU resizing")).size(10.0)));
|
||||
} else if app.gpu.as_ref().is_some_and(|gpu| gpu.cpu_padding_pending()) {
|
||||
ui.add(egui::Spinner::new().size(10.0));
|
||||
ui.label(RichText::new(tr("CPU preparing UV padding")).size(11.0));
|
||||
} else if let Some(p) = app.gpu.as_ref().and_then(|g| g.composite_progress(&app.session)) {
|
||||
ui.add(egui::ProgressBar::new(p).desired_width(160.0).desired_height(10.0).text(RichText::new(tr("Compositing")).size(10.0)));
|
||||
ui.add(egui::ProgressBar::new(p).desired_width(160.0).desired_height(10.0).text(RichText::new(tr("CPU compositing")).size(10.0)));
|
||||
ui.ctx().request_repaint();
|
||||
} else if app.gpu.as_ref().is_some_and(|gpu| gpu.gpu_composite_pending()) {
|
||||
ui.add(egui::Spinner::new().size(10.0));
|
||||
ui.label(RichText::new(tr("GPU compositing")).size(11.0));
|
||||
} else if let Some(msg) = app.session.log.last() {
|
||||
ui.label(RichText::new(&msg.message).size(11.0).color(tk.text_dim));
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if let Some(gpu) = app.gpu.as_ref().filter(|_| app.session.project_open) {
|
||||
let (label, reason) = gpu.compositor_status();
|
||||
ui.label(RichText::new(tr(label)).size(11.0).color(tk.text_dim)).on_hover_text(tr(reason));
|
||||
ui.separator();
|
||||
}
|
||||
let gpu = app.gpu.as_ref().map(|g| g.adapter.as_str()).unwrap_or(tr("no GPU"));
|
||||
ui.label(
|
||||
RichText::new(trf("Version: {version} ({gpu})", &[("version", &texturecraft_engine::VERSION), ("gpu", &gpu)]))
|
||||
|
||||
@@ -384,6 +384,11 @@ fn drop_highlight(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) ->
|
||||
|
||||
/// Show what the GPU side reported (each message once while its toast is up).
|
||||
fn gpu_report_toasts(app: &mut TextureCraftApp, reports: crate::gpu::GpuReports) {
|
||||
for (mesh, message) in reports.performance {
|
||||
if app.session.mesh_id == mesh {
|
||||
app.session.log.performance(message);
|
||||
}
|
||||
}
|
||||
let names: Vec<String> = reports.memory.iter().filter_map(|ts| app.session.doc.project.texture_sets.get(*ts).map(|t| t.name.clone())).collect();
|
||||
if !names.is_empty() {
|
||||
// One sticky notice for every set the GPU could not hold (they are not retried, so the
|
||||
@@ -463,7 +468,7 @@ impl PendingSync {
|
||||
visible_uv,
|
||||
);
|
||||
let reports = gpu.take_reports();
|
||||
if gpu.display_pending(&app.session) || gpu.bake_busy() {
|
||||
if scene.compositor_changed || gpu.display_pending(&app.session) || gpu.gpu_composite_pending() || gpu.bake_busy() {
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
app.profiler.sync_ms += (crate::now_ms() - start) as f32;
|
||||
|
||||
Reference in New Issue
Block a user