Merge pull request #55 from Agapenordev/fix/import-gpu-oom

Never crash importing meshes with many materials
This commit is contained in:
BFlat authored and GitHub committed 2026-11-02 12:33:22 +07:00
commit 558168d09a
18 files changed
+602 -41

No files matched your search

Generated
+2
View File
@@ -3968,6 +3968,7 @@ dependencies = [
"bytemuck",
"half",
"image",
"log",
"pollster 0.4.0",
"rayon",
"texturecraft-bake",
@@ -3975,6 +3976,7 @@ dependencies = [
"texturecraft-core",
"texturecraft-geom",
"texturecraft-texel",
"wasm-bindgen-futures",
"wgpu",
]
+1 -1
View File
@@ -77,7 +77,7 @@ impl Gpu {
_ => None,
};
if let Some(rgba) = aux {
h.renderer.upload_aux(&h.queue, ts, res, &rgba);
h.renderer.upload_aux(&h.device, &h.queue, ts, res, &rgba);
}
}
}
+5
View File
@@ -17,10 +17,15 @@ texturecraft-bake = { workspace = true }
wgpu = { workspace = true }
bytemuck = { workspace = true }
half = { workspace = true }
log = { workspace = true }
rayon = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
pollster = "0.4"
# The browser's WebGPU resolves error scopes later: their results are awaited on the page.
[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen-futures = "0.4"
[dev-dependencies]
image = { workspace = true }
+87 -1
View File
@@ -140,6 +140,54 @@ pub(crate) fn scoped<T>(device: &wgpu::Device, what: &str, f: impl FnOnce() -> T
}
}
/// What [`checked`] knows right after the call.
pub(crate) enum Checked<T> {
/// wgpu answered at once (native backends, WebGL): the value, or what went wrong.
Done(Result<T, String>),
/// The browser's WebGPU answers later: the value, possibly invalid, and where the answer
/// arrives (`None` for success). Don't use the value until it arrives. (Native backends
/// never answer late; the renderer's tests build this variant by hand.)
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
Later(T, std::sync::mpsc::Receiver<Option<String>>),
}
/// [`scoped`] for work whose errors may arrive later: never takes an unanswered scope as success.
pub(crate) fn checked<T>(device: &wgpu::Device, what: &str, f: impl FnOnce() -> T) -> Checked<T> {
let oom = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
let invalid = device.push_error_scope(wgpu::ErrorFilter::Validation);
let out = f();
let (invalid, oom) = (invalid.pop(), oom.pop());
let what = what.to_string();
let mut answer = Box::pin(async move {
let invalid = invalid.await;
let oom = oom.await;
// An allocation that ran out of memory also makes later calls on it invalid: the
// out-of-memory error is the cause.
oom.or(invalid).map(|e| format!("{what}: {e}"))
});
#[cfg(not(target_arch = "wasm32"))]
{
Checked::Done(match pollster::block_on(answer.as_mut()) {
Some(e) => Err(e),
None => Ok(out),
})
}
#[cfg(target_arch = "wasm32")]
{
match answer.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
Poll::Ready(Some(e)) => Checked::Done(Err(e)),
Poll::Ready(None) => Checked::Done(Ok(out)),
Poll::Pending => {
let (tx, rx) = std::sync::mpsc::channel();
wasm_bindgen_futures::spawn_local(async move {
let _ = tx.send(answer.await);
});
Checked::Later(out, rx)
}
}
}
}
pub(crate) fn entry(binding: u32, ty: wgpu::BindingType) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty, count: None }
}
@@ -439,7 +487,8 @@ impl GpuTracer {
let mut info: Vec<[f32; 3]> = sets
.iter()
.map(|s| {
let dims = s.first().map_or((1, 1), |t| (t.width(), t.height()));
// The set's size is its largest texture's; any kind may still be a 1×1 placeholder.
let dims = s.iter().fold((1, 1), |(w, h), t| (t.width().max(w), t.height().max(h)));
let small = s.iter().enumerate().filter(|(_, t)| (t.width(), t.height()) != dims).fold(0u32, |m, (k, _)| m | 1 << k);
[dims.0 as f32, dims.1 as f32, small as f32]
})
@@ -821,6 +870,43 @@ mod tests {
}
}
#[test]
fn gpu_reads_full_size_channels_beside_placeholders() {
// Base color stays at its default (a 1×1 placeholder texture) while roughness varies
// across the surface (a full-size texture): the tracer must still read every texel of it.
use Channel::*;
let Some((mut h, mut t)) = gpu() else { return };
let mut composite = Composite::new(&[Roughness, Metallic], 64);
for y in 0..64 {
for x in 0..64 {
let rough = if x < 32 { 0.05 } else { 0.9 };
composite.channels.get_mut(&Roughness).unwrap().set(x, y, &[texturecraft_texel::to_u16(rough)]);
composite.channels.get_mut(&Metallic).unwrap().set(x, y, &[texturecraft_texel::to_u16(1.0)]);
}
}
h.renderer.set_texture_sets(&h.device, &h.queue, &[((64, 64), 0)], 1);
for (tx, ty) in all_tiles(64, 64) {
for k in DisplayKind::ALL {
h.renderer.upload_tile(&h.device, &h.queue, 0, k, tx, ty, &tile_bytes(&composite, &BakedMaps::default(), k, tx, ty));
}
}
let sizes: Vec<u32> = h.renderer.display_textures()[0].iter().map(|t| t.width()).collect();
assert_eq!(sizes[0], 1, "base color stays a placeholder");
assert_eq!(sizes[1], 64, "roughness and metallic are full size");
let mesh = Arc::new(primitives::sphere(1.0, 32, 16));
let bvh = Arc::new(Bvh::new(&mesh));
let env = crate::ibl::environment("Studio Contrast", 256);
let scene = TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0 }], Arc::new(env), 0.0);
let d = TraceDisplay { exposure: 1.0, aces: true, env_opacity: 0.5, denoise: false };
let settings = TraceSettings { bounces: 4 };
let (_, _, gpu) = t.render(&h.device, &h.queue, &h.renderer, &scene, &camera(), &settings, &d, [48, 36], 1024).unwrap();
let mut cpu = Tracer::new(48, 36);
for _ in 0..1024 {
cpu.pass(&scene, &camera(), &settings);
}
assert_region_means_match("varying roughness, default base color", &gpu, &cpu.rgba8(&d), 48, 36, 3.0);
}
/// Mean luminance of each 6×6 block of two RGBA8 renders agrees within `tol` 8-bit levels.
fn assert_region_means_match(name: &str, a: &[u8], b: &[u8], w: usize, h: usize, tol: f32) {
let lum = |img: &[u8], x: usize, y: usize| {
+234 -31
View File
@@ -30,6 +30,7 @@ use texturecraft_geom::glam::{Mat4, Vec3};
use texturecraft_geom::{Mesh, OrbitCamera};
use texturecraft_texel::TILE;
use crate::gpu_trace::{Checked, checked};
use crate::ibl;
use crate::subdivide::{self, Vertex};
@@ -327,10 +328,67 @@ struct SetGpu {
/// Display textures hold the set at `size >> shift`: halved until they fit the device.
shift: u32,
/// The display textures in [`DisplayKind::ALL`] order, then the aux (mesh map) texture.
/// [`lazy`] kinds stay 1×1 until a tile with a non-default value arrives.
/// Each starts as a 1×1 neutral placeholder and gets its full size with the first tile (or
/// aux image) that holds something else, so a mesh with many materials costs no GPU memory
/// until its sets are painted.
tex: Vec<Tex>,
bind_group: wgpu::BindGroup,
mips_dirty: Vec<bool>,
/// Textures whose full-size allocation failed (out of GPU memory): they keep their
/// placeholder until the set is re-created, instead of retrying on every tile.
failed: Vec<bool>,
/// Full-size textures the browser's WebGPU has not yet confirmed: tiles go into them while
/// the placeholder stays bound (see [`Renderer::resolve_pending`]).
pending: Vec<Option<PendingTex>>,
}
/// A full-size texture waiting for WebGPU's verdict on its allocation.
struct PendingTex {
tex: Tex,
/// `None` for success, else what went wrong. (A mutex: the renderer is shared with the
/// paint callback, so it must be `Sync`.)
answer: std::sync::Mutex<std::sync::mpsc::Receiver<Option<String>>>,
}
/// Swap `tex` in for slot `slot` of `set` (bound at once; its mips are rebuilt).
fn install(set: &mut SetGpu, slot: usize, tex: Tex, device: &wgpu::Device, layout: &wgpu::BindGroupLayout, sampler: &wgpu::Sampler) {
if let Some(s) = set.tex.get_mut(slot) {
*s = tex;
}
set.bind_group = set_bind_group(device, layout, sampler, &set.tex);
if let Some(d) = set.mips_dirty.get_mut(slot) {
*d = true;
}
}
/// Give slot `slot` of `set` (texture set `ts`) the full-size texture `checked` allocated:
/// installed when wgpu accepted it, kept pending while WebGPU has not answered, or (out of GPU
/// memory) left as the placeholder with the failure recorded. False when there is nothing to
/// write into.
fn grow(
set: &mut SetGpu,
ts: usize,
slot: usize,
checked: Checked<Tex>,
ctx: (&wgpu::Device, &wgpu::BindGroupLayout, &wgpu::Sampler),
failures: &mut Vec<usize>,
) -> bool {
match checked {
Checked::Done(Ok(full)) => install(set, slot, full, ctx.0, ctx.1, ctx.2),
Checked::Done(Err(e)) => {
if let Some(f) = set.failed.get_mut(slot) {
*f = true;
}
memory_failed(failures, ts, &e);
return false;
}
Checked::Later(tex, answer) => {
if let Some(p) = set.pending.get_mut(slot) {
*p = Some(PendingTex { tex, answer: std::sync::Mutex::new(answer) });
}
}
}
true
}
/// Vertex and index buffers with their draws (first index, count, material).
@@ -477,6 +535,9 @@ pub struct Renderer {
black: wgpu::TextureView,
/// [`DisplayKind::default_texel`] in [`DisplayKind::ALL`] order.
default_texels: Vec<Vec<u8>>,
/// Texture sets whose display textures could not be allocated (out of GPU memory) since
/// [`Renderer::take_memory_failures`].
memory_failures: Vec<usize>,
accum_pipeline: wgpu::RenderPipeline,
env: Tex,
env_name: String,
@@ -530,11 +591,8 @@ pub(crate) fn display_format(k: DisplayKind) -> wgpu::TextureFormat {
}
}
/// Textures of the optional lobe channels: most sets never use them, so they cost no memory or
/// bandwidth (a 1×1 neutral texture) until painted.
fn lazy(k: DisplayKind) -> bool {
matches!(k, DisplayKind::Lobes | DisplayKind::Sheen | DisplayKind::Extra)
}
/// Texel of the aux texture before a mesh map or mask is shown.
const AUX_NEUTRAL: [u8; 4] = [128, 128, 128, 255];
/// A `w × h` texture filled with `texel`.
fn neutral_tex(device: &wgpu::Device, queue: &wgpu::Queue, (w, h): (u32, u32), format: wgpu::TextureFormat, mips: u32, texel: &[u8]) -> Tex {
@@ -557,6 +615,14 @@ fn neutral_tex(device: &wgpu::Device, queue: &wgpu::Queue, (w, h): (u32, u32), f
t
}
/// Record that texture set `ts` could not get a display texture (`error` says which).
fn memory_failed(failures: &mut Vec<usize>, ts: usize, error: &str) {
log::warn!("cannot allocate the display texture of {error}");
if !failures.contains(&ts) {
failures.push(ts);
}
}
/// Bytes per write when filling a texture with one texel.
const NEUTRAL_BAND_BYTES: usize = 8 << 20;
@@ -946,6 +1012,7 @@ impl Renderer {
shadow,
black,
default_texels: DisplayKind::ALL.map(DisplayKind::default_texel).to_vec(),
memory_failures: Vec::new(),
env,
env_name: String::new(),
sh: [[0.0; 4]; 9],
@@ -1068,20 +1135,13 @@ impl Renderer {
if self.sets.get(i).is_some_and(|s| s.size == size && s.shift == shift) {
continue;
}
let dims = display_dims(size, shift);
let mut tex: Vec<Tex> = DisplayKind::ALL
.iter()
.zip(&self.default_texels)
.map(|(k, texel)| {
let (d, mips) = if lazy(*k) { ((1, 1), 1) } else { (dims, mip_count(dims.0.max(dims.1))) };
neutral_tex(device, queue, d, display_format(*k), mips, texel)
})
.collect();
let aux = aux_size(size);
tex.push(neutral_tex(device, queue, (aux, aux), wgpu::TextureFormat::Rgba8Unorm, mip_count(aux), &[128, 128, 128, 255]));
// Placeholders only: full-size textures come with the first non-neutral upload.
let mut tex: Vec<Tex> =
DisplayKind::ALL.iter().zip(&self.default_texels).map(|(k, texel)| neutral_tex(device, queue, (1, 1), display_format(*k), 1, texel)).collect();
tex.push(neutral_tex(device, queue, (1, 1), wgpu::TextureFormat::Rgba8Unorm, 1, &AUX_NEUTRAL));
let bind_group = set_bind_group(device, &self.set_bgl, &self.sampler, &tex);
let n = tex.len();
let gpu = SetGpu { size, shift, tex, bind_group, mips_dirty: vec![true; n] };
let gpu = SetGpu { size, shift, tex, bind_group, mips_dirty: vec![true; n], failed: vec![false; n], pending: (0..n).map(|_| None).collect() };
if i < self.sets.len() {
self.sets[i] = gpu;
} else {
@@ -1110,18 +1170,24 @@ impl Renderer {
return;
}
let dims = display_dims(set.size, set.shift);
if t.texture.width() < dims.0 {
// A lazy placeholder: neutral tiles change nothing, the first real one allocates it.
if bytes.chunks_exact(texel.len()).all(|px| px == texel.as_slice()) {
let awaiting = set.pending.get(ki).is_some_and(Option::is_some);
if !awaiting && (t.texture.width() < dims.0 || t.texture.height() < dims.1) {
// A placeholder: neutral tiles change nothing, the first real one allocates it.
if set.failed.get(ki).copied().unwrap_or(true) || bytes.chunks_exact(texel.len()).all(|px| px == texel.as_slice()) {
return;
}
let full = neutral_tex(device, queue, dims, display_format(kind), mip_count(dims.0.max(dims.1)), texel);
if let Some(slot) = set.tex.get_mut(ki) {
*slot = full;
let what = format!("texture set {} ({kind:?}, {}×{})", ts + 1, dims.0, dims.1);
let full = checked(device, &what, || neutral_tex(device, queue, dims, display_format(kind), mip_count(dims.0.max(dims.1)), texel));
if !grow(set, ts, ki, full, (device, &self.set_bgl, &self.sampler), &mut self.memory_failures) {
return;
}
set.bind_group = set_bind_group(device, &self.set_bgl, &self.sampler, &set.tex);
}
let Some(t) = set.tex.get(ki) else { return };
// While WebGPU has not confirmed the full-size texture, tiles go into it (its errors, if
// it is invalid, are dropped with these scopes) and the placeholder stays bound.
let pending = set.pending.get(ki).and_then(Option::as_ref).map(|p| &p.tex);
let Some(t) = pending.or(set.tex.get(ki)) else { return };
let oom = pending.is_some().then(|| device.push_error_scope(wgpu::ErrorFilter::OutOfMemory));
let invalid = pending.is_some().then(|| device.push_error_scope(wgpu::ErrorFilter::Validation));
// Downscaled sets take every `step`-th texel of the tile.
let (step, n) = (1usize << set.shift.min(6), TILE >> set.shift.min(6));
let small: Vec<u8>;
@@ -1143,33 +1209,96 @@ impl Renderer {
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(n * bpt), rows_per_image: Some(n) },
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
);
// Innermost scope first.
drop(invalid);
drop(oom);
self.content_rev += 1;
if let Some(d) = set.mips_dirty.get_mut(ki) {
*d = true;
}
}
/// Upload the aux (mesh map / debug) texture of a set: RGBA8, `size × size`.
pub fn upload_aux(&mut self, queue: &wgpu::Queue, ts: usize, size: u32, rgba: &[u8]) {
/// Upload the aux (mesh map / debug) texture of a set: RGBA8, `size × size` with `size` from
/// [`aux_size`]. The first upload allocates it.
pub fn upload_aux(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, ts: usize, size: u32, rgba: &[u8]) {
let Some(set) = self.sets.get_mut(ts) else { return };
let want = aux_size(set.size);
let ai = set.tex.len().saturating_sub(1);
let Some(t) = set.tex.last() else { return };
let (w, h) = (t.texture.width(), t.texture.height());
if size != w || rgba.len() < (w * h * 4) as usize {
if size != want || rgba.len() < (size as usize) * (size as usize) * 4 {
return;
}
let awaiting = set.pending.get(ai).is_some_and(Option::is_some);
if !awaiting && t.texture.width() != size {
if set.failed.get(ai).copied().unwrap_or(true) {
return;
}
let what = format!("texture set {} (mesh map view, {size}×{size})", ts + 1);
let full = checked(device, &what, || neutral_tex(device, queue, (size, size), wgpu::TextureFormat::Rgba8Unorm, mip_count(size), &AUX_NEUTRAL));
if !grow(set, ts, ai, full, (device, &self.set_bgl, &self.sampler), &mut self.memory_failures) {
return;
}
}
let pending = set.pending.get(ai).and_then(Option::as_ref).map(|p| &p.tex);
let Some(t) = pending.or(set.tex.last()) else { return };
let (w, h) = (t.texture.width(), t.texture.height());
let oom = pending.is_some().then(|| device.push_error_scope(wgpu::ErrorFilter::OutOfMemory));
let invalid = pending.is_some().then(|| device.push_error_scope(wgpu::ErrorFilter::Validation));
queue.write_texture(
wgpu::TexelCopyTextureInfo { texture: &t.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
rgba,
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 4), rows_per_image: Some(h) },
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
);
drop(invalid);
drop(oom);
self.content_rev += 1;
if let Some(d) = set.mips_dirty.last_mut() {
*d = true;
}
}
/// Size of the aux texture of a set.
/// Texture sets whose display textures could not be allocated since the last call (out of
/// GPU memory: they show neutral values where they could not be allocated).
pub fn take_memory_failures(&mut self) -> Vec<usize> {
std::mem::take(&mut self.memory_failures)
}
/// Whether a full-size texture still waits for WebGPU's verdict: keep drawing frames, since
/// [`Renderer::prepare`] installs it (or reports the failure) once the answer is in.
pub fn awaiting_gpu(&self) -> bool {
self.sets.iter().any(|s| s.pending.iter().any(Option::is_some))
}
/// Install the pending full-size textures WebGPU accepted; drop the ones it rejected (their
/// placeholder stays and the failure is reported).
fn resolve_pending(&mut self, device: &wgpu::Device) {
for (ts, set) in self.sets.iter_mut().enumerate() {
for slot in 0..set.pending.len() {
let poll = |p: &PendingTex| p.answer.lock().unwrap_or_else(std::sync::PoisonError::into_inner).try_recv();
let verdict = match set.pending.get(slot).and_then(Option::as_ref).map(poll) {
None | Some(Err(std::sync::mpsc::TryRecvError::Empty)) => continue,
Some(Ok(v)) => v,
Some(Err(std::sync::mpsc::TryRecvError::Disconnected)) => Some(format!("texture set {}: the GPU never answered", ts + 1)),
};
let Some(p) = set.pending.get_mut(slot).and_then(Option::take) else { continue };
match verdict {
None => {
install(set, slot, p.tex, device, &self.set_bgl, &self.sampler);
self.content_rev += 1;
}
Some(e) => {
if let Some(f) = set.failed.get_mut(slot) {
*f = true;
}
memory_failed(&mut self.memory_failures, ts, &e);
}
}
}
}
}
/// Size of the aux texture of a set (1 until a mesh map or mask was shown).
pub fn aux_size(&self, ts: usize) -> Option<u32> {
self.sets.get(ts).and_then(|s| s.tex.last()).map(|t| t.texture.width())
}
@@ -1490,6 +1619,7 @@ impl Renderer {
/// `shade.taa` that repeats the previous one adds a jittered sample to the average instead,
/// and renders nothing once [`TAA_SAMPLES`] are in.
pub fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, frame: &Frame) {
self.resolve_pending(device);
self.generate_mips(device, encoder);
let rev = self.content_rev;
let sample = match self.views.get(&frame.view_id) {
@@ -1832,3 +1962,76 @@ impl Renderer {
self.views.remove(&id);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::headless::Headless;
/// A headless renderer with one 256² texture set, and the base color slot's full-size
/// texture handed over as WebGPU would: allocated, with its verdict still to come.
fn awaiting() -> Option<(Headless, std::sync::mpsc::Sender<Option<String>>)> {
let Ok(mut h) = Headless::new() else {
eprintln!("skipping: no GPU adapter");
return None;
};
h.renderer.set_texture_sets(&h.device, &h.queue, &[((256, 256), 0)], 1);
let (tx, rx) = std::sync::mpsc::channel();
let full = neutral_tex(&h.device, &h.queue, (256, 256), display_format(DisplayKind::BaseColor), mip_count(256), &[0, 0, 0, 255]);
let r = &mut h.renderer;
let set = r.sets.get_mut(0).unwrap();
assert!(grow(set, 0, 0, Checked::Later(full, rx), (&h.device, &r.set_bgl, &r.sampler), &mut r.memory_failures));
Some((h, tx))
}
fn base_width(h: &Headless) -> u32 {
h.renderer.display_textures()[0][0].width()
}
fn prepare(h: &mut Headless) {
let mut enc = h.device.create_command_encoder(&Default::default());
h.renderer.resolve_pending(&h.device);
h.renderer.generate_mips(&h.device, &mut enc);
h.queue.submit([enc.finish()]);
}
#[test]
fn a_late_texture_stays_unbound_until_accepted() {
let Some((mut h, tx)) = awaiting() else { return };
assert!(h.renderer.awaiting_gpu());
// Tiles go into the pending texture; the placeholder stays bound and nothing is retried.
h.renderer.upload_tile(&h.device, &h.queue, 0, DisplayKind::BaseColor, 0, 0, &[200, 30, 30, 255].repeat(64 * 64));
prepare(&mut h);
assert_eq!(base_width(&h), 1, "no verdict yet: the placeholder stays bound");
assert!(h.renderer.awaiting_gpu());
tx.send(None).unwrap();
prepare(&mut h);
assert_eq!(base_width(&h), 256, "accepted: installed");
assert!(!h.renderer.awaiting_gpu());
assert!(h.renderer.take_memory_failures().is_empty());
}
#[test]
fn a_late_rejection_keeps_the_placeholder_and_is_reported() {
let Some((mut h, tx)) = awaiting() else { return };
tx.send(Some("texture set 1 (BaseColor, 256×256): Out of Memory".into())).unwrap();
prepare(&mut h);
assert_eq!(base_width(&h), 1);
assert!(!h.renderer.awaiting_gpu());
assert_eq!(h.renderer.take_memory_failures(), vec![0]);
// The failed kind is not allocated again by later tiles.
h.renderer.upload_tile(&h.device, &h.queue, 0, DisplayKind::BaseColor, 1, 0, &[200, 30, 30, 255].repeat(64 * 64));
prepare(&mut h);
assert_eq!(base_width(&h), 1);
assert!(!h.renderer.awaiting_gpu());
}
#[test]
fn a_verdict_that_never_comes_counts_as_a_failure() {
let Some((mut h, tx)) = awaiting() else { return };
drop(tx);
prepare(&mut h);
assert_eq!(base_width(&h), 1);
assert_eq!(h.renderer.take_memory_failures(), vec![0]);
}
}
+44
View File
@@ -734,3 +734,47 @@ fn refraction_shows_the_scene_behind_transmissive_surfaces() {
let frosted = render(&mut h, &refr, "refr_frosted_checker");
assert!(detail(&frosted, &ball) < detail(&clear, &ball), "frosted glass blurs the scene behind");
}
/// Kinds in [`DisplayKind::ALL`] order with each set's display texture widths, then the aux width.
fn widths(h: &Headless) -> Vec<Vec<u32>> {
h.renderer.display_textures().iter().map(|s| s.iter().map(|t| t.width()).collect()).collect()
}
#[test]
fn texture_sets_take_no_gpu_memory_until_painted() {
// A mesh with many materials (one texture set each) must not reserve full-size textures
// for every set up front: that ran a 4 GB GPU out of memory, and wgpu's handler aborted.
let Some((mut h, _)) = setup() else { return };
let sets: Vec<((u32, u32), usize)> = (0..40).map(|m| ((2048, 2048), m)).collect();
h.renderer.set_texture_sets(&h.device, &h.queue, &sets, 40);
assert!(widths(&h).iter().flatten().all(|w| *w == 1), "every display texture starts as a 1×1 placeholder");
assert!((0..40).all(|ts| h.renderer.aux_size(ts) == Some(1)), "so does every aux texture");
// A neutral tile changes nothing; the first painted one allocates that kind alone.
let kind = DisplayKind::BaseColor;
let neutral = kind.default_texel().repeat(64 * 64);
h.renderer.upload_tile(&h.device, &h.queue, 3, kind, 0, 0, &neutral);
assert_eq!(widths(&h)[3][0], 1);
h.renderer.upload_tile(&h.device, &h.queue, 3, kind, 0, 0, &[200, 30, 30, 255].repeat(64 * 64));
let w = widths(&h);
assert_eq!(w[3][0], 2048, "the painted kind is full size");
assert!(w[3][1..].iter().all(|w| *w == 1) && w[2].iter().all(|w| *w == 1), "nothing else was allocated");
// The aux texture is allocated by its first upload, at the set's aux size only.
h.renderer.upload_aux(&h.device, &h.queue, 3, 512, &[0; 512 * 512 * 4]);
assert_eq!(h.renderer.aux_size(3), Some(1), "a wrong aux size is ignored");
h.renderer.upload_aux(&h.device, &h.queue, 3, 2048, &[90; 2048 * 2048 * 4]);
assert_eq!(h.renderer.aux_size(3), Some(2048));
assert!(h.renderer.take_memory_failures().is_empty());
}
#[test]
fn painted_placeholders_render_like_full_textures() {
// A set painted in one kind renders that paint whether the other kinds are placeholders.
let Some((mut h, frame)) = setup() else { return };
let before = render(&mut h, &frame, "placeholders");
fill(&mut h, &[0, 1], DisplayKind::BaseColor, &[220, 40, 40, 255]);
let red = render(&mut h, &frame, "painted_base_color");
let (w, hgt) = (frame.size[0], frame.size[1]);
let [r0, g0, _] = before.at(w / 2, hgt / 2);
let [r1, g1, _] = red.at(w / 2, hgt / 2);
assert!(r1 > r0 && g1 < g0, "the painted base color shows: {:?} → {:?}", before.at(w / 2, hgt / 2), red.at(w / 2, hgt / 2));
}
+54 -3
View File
@@ -43,11 +43,27 @@ pub struct GpuState {
pub renderer: Renderer,
/// Raised when texture-set textures were recreated: the UI must upload every tile again.
pub reset: Arc<AtomicBool>,
pub reports: Arc<Mutex<GpuReports>>,
/// Wakes the UI when the GPU side has something to report.
pub ctx: egui::Context,
}
/// Problems the GPU side hands to the UI, which shows them as toasts.
#[derive(Default)]
pub struct GpuReports {
/// Texture sets whose display textures could not be allocated (out of GPU memory).
pub memory: Vec<usize>,
/// wgpu errors no error scope caught (logged instead of wgpu's default panic).
pub errors: Vec<String>,
}
/// Most distinct uncaptured GPU errors kept until the UI shows them.
const MAX_GPU_ERRORS: usize = 8;
/// UI-side bookkeeping of what the GPU already has.
pub struct GpuLink {
pub reset: Arc<AtomicBool>,
pub reports: Arc<Mutex<GpuReports>>,
/// Raised when a view callback was dropped before the GPU applied its scene sync (the
/// frame was never painted, e.g. a WebGPU surface not ready yet): send everything again.
pub lost: Arc<AtomicBool>,
@@ -78,13 +94,28 @@ const UPLOAD_CHUNK: usize = 64;
/// display kind, measured at ~5.5 µs on a desktop GPU), counted against the frame budget.
const UPLOAD_MS_PER_TILE: f64 = 0.006;
pub fn init(rs: &egui_wgpu::RenderState) -> GpuLink {
pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink {
let reset = Arc::new(AtomicBool::new(false));
let reports = Arc::new(Mutex::new(GpuReports::default()));
// wgpu's default handler panics on any error no scope caught (an out-of-memory texture, a
// driver hiccup): report it instead, so the user keeps the session.
let (sink, wake) = (reports.clone(), ctx.clone());
rs.device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| {
log::error!("GPU error: {e}");
let mut r = sink.lock().unwrap_or_else(PoisonError::into_inner);
let text = e.to_string();
if r.errors.len() < MAX_GPU_ERRORS && !r.errors.contains(&text) {
r.errors.push(text);
}
// The UI may be idle: draw a frame to show it.
wake.request_repaint();
}));
let renderer = Renderer::new(&rs.device, &rs.queue, rs.target_format);
rs.renderer.write().callback_resources.insert(GpuState { renderer, reset: reset.clone() });
rs.renderer.write().callback_resources.insert(GpuState { renderer, reset: reset.clone(), reports: reports.clone(), ctx: ctx.clone() });
let info = rs.adapter.get_info();
GpuLink {
reset,
reports,
lost: Arc::new(AtomicBool::new(false)),
mesh_id: 0,
sets: Vec::new(),
@@ -97,6 +128,11 @@ pub fn init(rs: &egui_wgpu::RenderState) -> GpuLink {
}
impl GpuLink {
/// What the GPU side reported since the last call (see [`GpuReports`]).
pub fn take_reports(&self) -> GpuReports {
std::mem::take(&mut *self.reports.lock().unwrap_or_else(PoisonError::into_inner))
}
/// Collect everything the GPU needs this frame (runs the compositor first).
/// Compositing progress (0..1) while tiles wait to be composited.
pub fn composite_progress(&self, s: &Session) -> Option<f32> {
@@ -264,10 +300,25 @@ impl CallbackTrait for ViewCallback {
gpu.renderer.upload_tile(device, queue, *ts, *k, *tx, *ty, bytes);
}
for (ts, size, bytes) in &sync.aux {
gpu.renderer.upload_aux(queue, *ts, *size, bytes);
gpu.renderer.upload_aux(device, queue, *ts, *size, bytes);
}
}
// Also installs (or rejects) full-size textures WebGPU answered for since last frame.
gpu.renderer.prepare(device, queue, encoder, &self.frame);
let failed = gpu.renderer.take_memory_failures();
if !failed.is_empty() {
let mut r = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner);
for ts in failed {
if !r.memory.contains(&ts) {
r.memory.push(ts);
}
}
// This frame's report drain already ran: the next frame shows the toast.
gpu.ctx.request_repaint();
}
if gpu.renderer.awaiting_gpu() {
gpu.ctx.request_repaint();
}
let ppp = screen.pixels_per_point;
let r = self.rect;
gpu.renderer.set_blit_rect(queue, self.frame.view_id, [r.min.x * ppp, r.min.y * ppp, r.width() * ppp, r.height() * ppp], screen.size_in_pixels);
+9
View File
@@ -339,6 +339,7 @@ pub const TABLE: &[(&str, &str)] = &[
("From template", "من قالب"),
("From template / project", "من قالب / مشروع"),
("Full", "كامل"),
("GPU error: {error}", "خطأ في GPU: {error}"),
("Geometry mask", "قناع هندسي"),
(
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
@@ -538,6 +539,14 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal map format", "صيغة خريطة النواظم"),
("Normal map inverse detail", "عكس تفاصيل خريطة النواظم"),
("Normal: painting uses the flat normal", "عادي: يستخدم الرسم الناظم المسطح"),
(
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"لا توجد ذاكرة GPU كافية لعرض مجموعة الخامات \"{name}\" كاملة: خفّض دقة الخامة لمنفذ العرض في الإعدادات. لا يتأثر الرسم والتصدير.",
),
(
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"لا توجد ذاكرة GPU كافية لعرض {count} من مجموعات الخامات كاملة ({names}): خفّض دقة الخامة لمنفذ العرض في الإعدادات. لا يتأثر الرسم والتصدير.",
),
("Not exported: no source in this texture set", "لم يتم التصدير: لا يوجد مصدر في مجموعة الخامات هذه"),
("Not saved: {error}", "لم يتم الحفظ: {error}"),
("Off", "معطل"),
+9
View File
@@ -363,6 +363,7 @@ pub const TABLE: &[(&str, &str)] = &[
("From template", "Aus Vorlage"),
("From template / project", "Aus Vorlage / Projekt"),
("Full", "Voll"),
("GPU error: {error}", "GPU-Fehler: {error}"),
("Geometry mask", "Geometriemaske"),
(
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
@@ -568,6 +569,14 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal map format", "Normal-Map-Format"),
("Normal map inverse detail", "Normal-Map-Detail invertiert"),
("Normal: painting uses the flat normal", "Normale: Malen verwendet die flache Normale"),
(
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"Nicht genug GPU-Speicher, um das Texturset \"{name}\" vollständig anzuzeigen: Verringere in den Einstellungen die Texturauflösung des Ansichtsfensters. Malen und Export sind nicht betroffen.",
),
(
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"Nicht genug GPU-Speicher, um {count} Texturesets vollständig anzuzeigen ({names}): Verringere in den Einstellungen die Texturauflösung des Ansichtsfensters. Malen und Export sind nicht betroffen.",
),
("Not exported: no source in this texture set", "Nicht exportiert: keine Quelle in diesem Texturset"),
("Not saved: {error}", "Nicht gespeichert: {error}"),
("Off", "Aus"),
+9
View File
@@ -354,6 +354,7 @@ pub const TABLE: &[(&str, &str)] = &[
("From template", "Desde la plantilla"),
("From template / project", "Desde la plantilla / el proyecto"),
("Full", "Completa"),
("GPU error: {error}", "Error de GPU: {error}"),
("Geometry mask", "Máscara de geometría"),
(
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
@@ -559,6 +560,14 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal map format", "Formato del mapa de normales"),
("Normal map inverse detail", "Detalle inverso de mapa de normales"),
("Normal: painting uses the flat normal", "Normal: la pintura usa la normal plana"),
(
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"No hay suficiente memoria de GPU para mostrar el conjunto de texturas \"{name}\" por completo: reduce en Ajustes la resolución de texturas de la ventana gráfica. La pintura y la exportación no se ven afectadas.",
),
(
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"No hay suficiente memoria de GPU para mostrar por completo {count} conjuntos de texturas ({names}): reduce en Ajustes la resolución de texturas de la ventana gráfica. La pintura y la exportación no se ven afectadas.",
),
("Not exported: no source in this texture set", "No exportado: no hay origen en este conjunto de texturas"),
("Not saved: {error}", "No guardado: {error}"),
("Off", "Desactivado"),
+9
View File
@@ -366,6 +366,7 @@ pub const TABLE: &[(&str, &str)] = &[
("From template", "Selon le modèle"),
("From template / project", "Selon le modèle / projet"),
("Full", "Pleine"),
("GPU error: {error}", "Erreur GPU : {error}"),
("Geometry mask", "Masque de géométrie"),
(
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
@@ -574,6 +575,14 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal map format", "Format de carte de normales"),
("Normal map inverse detail", "Normales : détail inverse"),
("Normal: painting uses the flat normal", "Normal : la peinture utilise la normale plate"),
(
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"Mémoire GPU insuffisante pour afficher entièrement l'ensemble de textures \"{name}\" : réduisez la résolution des textures de l'affichage dans les Paramètres. La peinture et l'export ne sont pas affectés.",
),
(
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"Mémoire GPU insuffisante pour afficher entièrement {count} ensembles de textures ({names}) : réduisez la résolution des textures de l'affichage dans les Paramètres. La peinture et l'export ne sont pas affectés.",
),
("Not exported: no source in this texture set", "Non exporté : aucune source dans cet ensemble de textures"),
("Not saved: {error}", "Non enregistré : {error}"),
("Off", "Désactivé"),
+9
View File
@@ -360,6 +360,7 @@ pub const TABLE: &[(&str, &str)] = &[
("From template", "Da modello"),
("From template / project", "Da modello / progetto"),
("Full", "Piena"),
("GPU error: {error}", "Errore GPU: {error}"),
("Geometry mask", "Maschera geometria"),
(
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
@@ -565,6 +566,14 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal map format", "Formato mappa normali"),
("Normal map inverse detail", "Dettaglio inverso mappa normali"),
("Normal: painting uses the flat normal", "Normale: la pittura usa la normale piatta"),
(
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"Memoria GPU insufficiente per mostrare per intero il set di texture \"{name}\": riduci nelle Impostazioni la risoluzione texture della viewport. Pittura ed esportazione non sono interessate.",
),
(
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"Memoria GPU insufficiente per mostrare per intero {count} set di texture ({names}): riduci nelle Impostazioni la risoluzione texture della viewport. Pittura ed esportazione non sono interessate.",
),
("Not exported: no source in this texture set", "Non esportato: nessuna sorgente in questo set di texture"),
("Not saved: {error}", "Non salvato: {error}"),
("Off", "Disattivato"),
+9
View File
@@ -351,6 +351,7 @@ pub const TABLE: &[(&str, &str)] = &[
("From template", "テンプレートから"),
("From template / project", "テンプレート / プロジェクトから"),
("Full", "フル"),
("GPU error: {error}", "GPU エラー: {error}"),
("Geometry mask", "ジオメトリマスク"),
(
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
@@ -553,6 +554,14 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal map format", "ノーマルマップ形式"),
("Normal map inverse detail", "ノーマルマップ 逆ディテール"),
("Normal: painting uses the flat normal", "ノーマル: ペイントにはフラットな法線を使用"),
(
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"GPU メモリが不足しているため、テクスチャセット「{name}」を完全には表示できません:設定でビューポートのテクスチャ解像度を下げてください。ペイントと書き出しには影響しません。",
),
(
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"GPU メモリが不足しているため、{count} 個のテクスチャセット({names})を完全には表示できません:設定でビューポートのテクスチャ解像度を下げてください。ペイントと書き出しには影響しません。",
),
("Not exported: no source in this texture set", "エクスポートされません: このテクスチャセットにソースがありません"),
("Not saved: {error}", "保存されていません: {error}"),
("Off", "オフ"),
+9
View File
@@ -345,6 +345,7 @@ pub const TABLE: &[(&str, &str)] = &[
("From template", "템플릿 기준"),
("From template / project", "템플릿 / 프로젝트 기준"),
("Full", "전체"),
("GPU error: {error}", "GPU 오류: {error}"),
("Geometry mask", "지오메트리 마스크"),
(
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
@@ -547,6 +548,14 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal map format", "노멀 맵 형식"),
("Normal map inverse detail", "노멀 맵 역 디테일"),
("Normal: painting uses the flat normal", "노멀: 평면 노멀로 페인팅합니다"),
(
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"GPU 메모리가 부족하여 텍스처 세트 \"{name}\"을(를) 모두 표시할 수 없습니다: 설정에서 뷰포트의 텍스처 해상도를 낮추세요. 페인팅과 내보내기에는 영향이 없습니다.",
),
(
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"GPU 메모리가 부족하여 텍스처 세트 {count}개({names})를 모두 표시할 수 없습니다: 설정에서 뷰포트의 텍스처 해상도를 낮추세요. 페인팅과 내보내기에는 영향이 없습니다.",
),
("Not exported: no source in this texture set", "내보내지 않음: 이 텍스처 세트에 소스가 없습니다"),
("Not saved: {error}", "저장되지 않음: {error}"),
("Off", "끄기"),
+9
View File
@@ -354,6 +354,7 @@ pub const TABLE: &[(&str, &str)] = &[
("From template", "Do modelo"),
("From template / project", "Do modelo / projeto"),
("Full", "Completa"),
("GPU error: {error}", "Erro de GPU: {error}"),
("Geometry mask", "Máscara de geometria"),
(
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
@@ -556,6 +557,14 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal map format", "Formato do mapa normal"),
("Normal map inverse detail", "Detalhe inverso de mapa normal"),
("Normal: painting uses the flat normal", "Normal: a pintura usa a normal plana"),
(
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"Memória de GPU insuficiente para mostrar o conjunto de texturas \"{name}\" por completo: reduza nas Configurações a resolução das texturas da viewport. A pintura e a exportação não são afetadas.",
),
(
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"Memória de GPU insuficiente para mostrar por completo {count} conjuntos de texturas ({names}): reduza nas Configurações a resolução das texturas da viewport. A pintura e a exportação não são afetadas.",
),
("Not exported: no source in this texture set", "Não exportado: sem origem neste conjunto de texturas"),
("Not saved: {error}", "Não salvo: {error}"),
("Off", "Desligado"),
+9
View File
@@ -309,6 +309,7 @@ pub const TABLE: &[(&str, &str)] = &[
("From template", "基于模板"),
("From template / project", "基于模板 / 项目"),
("Full", "完整"),
("GPU error: {error}", "GPU 错误:{error}"),
("Geometry mask", "几何遮罩"),
(
"GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.",
@@ -499,6 +500,14 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal map format", "法线贴图格式"),
("Normal map inverse detail", "法线贴图反向细节"),
("Normal: painting uses the flat normal", "法线:绘画使用平坦法线"),
(
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"GPU 内存不足,无法完整显示纹理集“{name}”:请在设置中降低视口的纹理分辨率。绘制和导出不受影响。",
),
(
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
"GPU 内存不足,无法完整显示 {count} 个纹理集({names}):请在设置中降低视口的纹理分辨率。绘制和导出不受影响。",
),
("Not exported: no source in this texture set", "未导出:此纹理集中没有来源"),
("Not saved: {error}", "未保存:{error}"),
("Off", "关"),
+39 -5
View File
@@ -70,6 +70,8 @@ pub struct TextureCraftApp {
pub gpu: Option<gpu::GpuLink>,
pub control: Option<std::sync::mpsc::Receiver<ControlRequest>>,
pub toasts: Vec<Toast>,
/// Texture sets the GPU could not hold, and the text of the one sticky toast naming them.
pub(crate) gpu_memory: (Vec<String>, Option<String>),
pub bake: Option<BakeJob>,
pub resize: Option<ResizeJob>,
pub thumbs: thumbs::Thumbs,
@@ -112,7 +114,7 @@ impl TextureCraftApp {
// Bakes cast their rays on a GPU device of their own (created on the first bake).
#[cfg(not(target_arch = "wasm32"))]
texturecraft_engine::bake_cmds::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new()));
let gpu = cc.wgpu_render_state.as_ref().map(gpu::init);
let gpu = cc.wgpu_render_state.as_ref().map(|rs| gpu::init(rs, &cc.egui_ctx));
// The first run speaks the OS (or browser) language.
let ui = cc.storage.and_then(|s| eframe::get_value::<UiState>(s, "ui")).unwrap_or_else(|| {
let mut ui = UiState::default();
@@ -126,6 +128,7 @@ impl TextureCraftApp {
gpu,
control: None,
toasts: Vec::new(),
gpu_memory: (Vec::new(), None),
bake: None,
resize: None,
thumbs: thumbs::Thumbs::default(),
@@ -173,6 +176,12 @@ impl TextureCraftApp {
self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 } });
}
/// An error toast that stays until the user dismisses it (for a problem that persists and
/// is reported once, like a texture set the GPU could not hold).
pub fn toast_sticky(&mut self, text: impl Into<String>) {
self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY });
}
/// Start baking texture sets in the background (one after another).
pub fn start_bake(&mut self, sets: Vec<usize>) {
if self.bake.is_some() || sets.is_empty() {
@@ -471,10 +480,19 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
if app.toasts.is_empty() {
return;
}
ctx.request_repaint_after(std::time::Duration::from_millis(250));
// Expiring toasts need frames to disappear on time; sticky ones wait for a click.
if app.toasts.iter().any(|t| t.until.is_finite()) {
ctx.request_repaint_after(std::time::Duration::from_millis(250));
}
let tk = theme::Tokens::get(ctx);
let mut dismissed = None;
// Toasts fit the window: at most 360 points wide and, for their text, a part of its height
// (longer text scrolls), so a sticky toast's dismiss button always stays on screen.
let screen = ctx.content_rect().size();
let max_width = (screen.x - 52.0).clamp(120.0, 360.0);
let max_text_height = (screen.y * 0.35).clamp(48.0, 220.0);
egui::Area::new(egui::Id::unique("toasts")).anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-16.0, -36.0)).show(ctx, |ui| {
for t in &app.toasts {
for (i, t) in app.toasts.iter().enumerate() {
egui::Frame::NONE
.fill(tk.panel)
.stroke(egui::Stroke::new(1.0, if t.error { tk.danger } else { tk.accent }))
@@ -482,10 +500,26 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
.shadow(ui.visuals().popup_shadow)
.inner_margin(egui::Margin::symmetric(10, 6))
.show(ui, |ui| {
ui.set_max_width(360.0);
ui.label(egui::RichText::new(&t.text).color(tk.text_strong));
ui.set_max_width(max_width);
let sticky = t.until.is_infinite();
ui.horizontal_top(|ui| {
// The text wraps in the width the dismiss button leaves.
let width = if sticky { max_width - 28.0 } else { max_width };
ui.allocate_ui_with_layout(egui::vec2(width, 0.0), egui::Layout::top_down(egui::Align::Min), |ui| {
egui::ScrollArea::vertical().id_salt(("toast", i)).max_height(max_text_height).show(ui, |ui| {
ui.set_max_width(width);
ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap());
});
});
if sticky && widgets::icon_button(ui, egui_phosphor::regular::X, i18n::tr("Dismiss"), false, 18.0).clicked() {
dismissed = Some(i);
}
});
});
ui.add_space(4.0);
}
});
if let Some(i) = dismissed.filter(|i| *i < app.toasts.len()) {
app.toasts.remove(i);
}
}
+55
View File
@@ -95,6 +95,59 @@ fn shade(app: &TextureCraftApp) -> Shade {
}
}
/// 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) {
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
// notice stays until dismissed); after a dismissal, a new one names only the new sets.
let (sets, shown) = &mut app.gpu_memory;
let current = shown.take().filter(|text| app.toasts.iter().any(|t| &t.text == text));
match &current {
Some(text) => app.toasts.retain(|t| &t.text != text),
None => sets.clear(),
}
for n in names {
if !sets.contains(&n) {
sets.push(n);
}
}
let text = match sets.as_slice() {
[one] => trf(
"Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
&[("name", one)],
),
many => {
let short = |n: &String| match n.char_indices().nth(MAX_NAME_CHARS) {
Some((cut, _)) => format!("\"{}...\"", &n[..cut]),
None => format!("\"{n}\""),
};
let mut list = many.iter().take(MAX_NAMED_SETS).map(short).collect::<Vec<_>>().join(", ");
if many.len() > MAX_NAMED_SETS {
list.push_str(", ...");
}
trf(
"Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
&[("count", &many.len()), ("names", &list)],
)
}
};
app.gpu_memory.1 = Some(text.clone());
app.toast_sticky(text);
}
for e in &reports.errors {
let text = trf("GPU error: {error}", &[("error", e)]);
if !app.toasts.iter().any(|t| t.text == text) {
app.toast(text, true);
}
}
}
/// Texture sets a GPU memory notice names before "...".
const MAX_NAMED_SETS: usize = 5;
/// Characters of a set name in that notice (long names are cut, with "...").
const MAX_NAME_CHARS: usize = 32;
/// This frame's scene sync (compositing and GPU uploads), run by the first view drawn, after
/// that view handled its input: a stroke shows in the frame it is painted, not the next.
pub struct PendingSync(Option<Option<crate::gpu::AuxView>>);
@@ -105,7 +158,9 @@ fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, frame: Frame, sy
(Some(aux), Some(g)) => {
let t0 = crate::now_ms();
let scene = g.sync(&mut app.session, aux, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms));
let reports = g.take_reports();
app.profiler.sync_ms += (crate::now_ms() - t0) as f32;
gpu_report_toasts(app, reports);
// Display tiles left for later frames (the frame budget ran out).
if app.session.caches.iter().any(|c| !c.upload.is_empty()) {
ui.ctx().request_repaint();